Sunday, October 20, 2024

New Book - Building Scalable Web Apps with Node.js and Express

 

🚀 I’m excited to announce the launch of my new book, Building Scalable Web Apps with Node.js and Express, now available on Amazon India!

https://m.media-amazon.com/images/S/aplus-media-library-service-media/13a77388-6cad-4282-bfaf-9a141720c45c.__CR0,0,970,600_PT0_SX970_V1___.jpg

Co-authored with Yamini Panchal, this book is designed for developers, architects, and tech enthusiasts who want to master the craft of building fast, efficient, and scalable web applications using Node.js and Express.

📘 What You'll Learn:

  • Architectural Best Practices: Dive deep into the design of scalable systems with real-world examples and practical insights.
  • Efficient Coding with Express: Discover how to leverage Express for creating robust, maintainable applications.
  • Advanced Topics: Covering everything from load balancing and distributed systems to caching and microservices.
  • Hands-on Projects: Build practical, hands-on projects that reinforce each concept as you progress through the book.

Whether you’re just starting out or looking to advance your skills, this book offers something for everyone on the journey to mastering scalable web development.

🎯 Grab your copy today and start building scalable web apps with ease!

👉 Order Now

#Nodejs #Express #WebDevelopment #ScalableApps #TechBooks

Wednesday, September 21, 2016

[Liferay] Multiple Service Builders in one Liferay Project

While working on liferay projects and portlets, sometimes we have a huge amount of service entities and we can logically group them and divide into multiple files and then import into main service.xml file.

Lets take an example of a company intranet where several modules are to be designed to support employee information, leaves, timesheet, projects, performance evaluations, trainings, meeting room booking etc. Our main service.xml will look like

This service.xml file can include any number of entities just like we add in usual way. For specific modules, we have imported children xxx-service.xml files.

The name of the files need not to be in xxx-service.xml, it can be anything that suits you.

The child xml files will contain entities related to a specific module. For example leave management system related service lms-service.xml will be like -

Our performance management system related service pms-service.xml will be like -

Hope this helps you to manage your long entities into smaller xml files and set you up with a short, readable, and organized service.xml. :)

Sunday, January 24, 2016

[ELK] An introduction to ELK Stack - Elasticsearch, Logstash, Kibana


... I had more than 5 servers continuously running on my computer when I was in college. My interest in PHP led me to install Apache, MySQL, and a mail server so that I could host multiple sites from my machine. Apart from these there were ftp, vnc etc. Whenever there was a problem with a server, I would go and check logs of that server. Even till 2 years back, I used to do same for other servers also. This time the list added app servers for Liferay.

I used to check logs for each servers individually, until I got to know about Splunk, a tool which my client was using to see all of the logs at one place. It was providing way more than just view, I could search logs for a defined time range etc. It was not collecting logs from just one server machine but almost 20 machines and for few machines, multiple servers. Troubleshooting was easy this way. I was not logging in to 20 different machines to check logs and look for possible problems. Honestly, I had no access to most of them. But I had access to Splunk, and I could query logs already indexed and could diagnose which server had problems.

But, Splunk (full features) is not free.

Then, what are the other options. Let me give you a hint in the image below..

Google (GOD) gave a hint : Look at ELK, once!

Out of curiosity, I just jumped to knowing ELK Stack rather than checking any search results. Instant, Google said once. :P

ELK = Elasticsearch, Logstash, Kibana.

Below image would tell you how this stack works.

 The above is a very very simplified representation of ELK stack.

Elasticsearch - Indexes the data sent to it. The core of elasticsearch is lucene.

Logstash - Its a data pipeline which can read data from a number of sources. There are more than 200 plugins available for logstash classified in four categories - Input, Output, Filter, Codec plugins.

Kibana - Whatever elasticsearch has indexed, Kibana gives opportunity to visualize that data in different forms. The data can be queried, be listed, be drawn as charts.

This was just a very basic introduction to these components. These components offer a lot more than just these. We will get to learn more about these components in future posts.

Until next time :)



Saturday, January 23, 2016

[ELK] Reading, Indexing and Visualizing Windows logs with ELK Stack

Hello Friends,

A system administrator knows how much system logs can help to troubleshoot critical problems. And what if those logs are indexed at one place and can be visualized in charts etc. Fun, isn't it?

Let's see what can help us to set it up..

1. Nothing special to be done at Elasticsearch just run it by executing elasticsearch.bat from bin directory.

2. Prepare a config so that Logstash can read windows logs. We need to add config in input plugin.

This eventlog plugin helps logstash to read windows logs. Windows logs are stored in binary format and can be accessed using only Win32 API. This plugin takes several configuration options but all of those are optional. These config options are codec, add_field, logfile, interval, tags, type out of which we are using logfile and type.

a) type has no default value and used for filter activation. The given type is stored as part of event and we can search events in Kibana using this.
b) logfile is an array of String and contains Application, Security, System as default values in array. In the config we have used only System.

3. Store this config to a custom file in conf in Logstash with name logstash-windowslogs.conf
and run logstash using

where complete config file will be as -

4. We're done with configuration of Logstash. Next is to read this in kibana. Here is our config to connect Kibana to Elasticsearch to read indices.


5. As soon as we start Logstash, it will start collecting all the events and index them to elasticsearch. Now lets run Kibana by executing kibana.bat in bin directory.

6. Once Kibana is started, we can open its interface in browser using http://localhost:5601/. We need to configure index pattern. By default, it shows logstash-* in index name or pattern field and @timestamp in Time-Field name. Hit create by keeping defaults.

7. Now click Discover on the top menu to see the results. It will show histogram of counts of event.

All the results are also listed below histogram but for security reasons, I have not shown them here..

That's it. Pretty clean, what you say?


Thursday, July 30, 2015

[Forms] Detect enter key pressed using javascript/JQuery

Hi,

Sometimes, we need to detect when Enter key was pressed or some other key as per the requirement. I had a use case where I had a search box and it was not a form. User could put some content in search input text box and when user hits Enter, it should fetch data using ajax call. The code below detects when Enter key was pressed.

We will add a keypress handler to the document which will capture all events whenever a key is pressed. We need to check which one is Enter. The code for Enter is 13.


We also need to check if the focus was actually the search input text.

That's all what we need.

Until next time :)

Friday, July 3, 2015

[Apache] Creating virtual hosts with Apache Httpd web server.

Its common to see multiple project running on one machine. Sometimes, it looks great if every web application runs with its own domain name. I usually keep my hostname as rkg.test, and for projects xxxx.proj. If I have multiple projects lets say blog, forum etc. so I can keep them as blog.proj, forum.proj etc. Neat, isn't it.

Here are simple steps to make it work.
1. Open your hosts file - in C:\Windows\System32\drivers\etc\hosts and add your domain to it. Add the lines at the end of file like this.
127.0.0.1 blog.proj
127.0.0.1 forum.proj

2. Make sure httpd.conf file has virtual hosting enabled. Either add virtual hosts in the same httpd.conf file or put them in a different file and use that. Lets keep them separate in another file and keep this line in httpd.conf
Include conf/extra/httpd-vhosts.conf

3. If already not present, create a folder in conf/ named extra and create a httpd-vhosts.conf file.

4. Add a line for enabling NameVirtualHost
NameVirtualHost *:80

5.  Add a virtual host by adding these lines in httpd-vhosts.conf file
<VirtualHost *:80>
    ServerAdmin webmaster@blog.proj
    DocumentRoot "D:/pFiles/xampp/htdocs/blog.proj"
    ServerName blog.proj
    ErrorLog "logs/blog.proj-error.log"
    CustomLog "logs/blog.proj.log" common
</VirtualHost>

6. Similarly add one more for forum.proj
<VirtualHost *:80>
    ServerAdmin webmaster@forum.proj
    DocumentRoot "D:/pFiles/xampp/htdocs/forum.proj"
    ServerName forum.proj
    ErrorLog "logs/forum.proj-error.log"
    CustomLog "logs/forum.proj.log" common
</VirtualHost>

7. Restart your apache. And open blog.proj and forum.proj in your browser.

Simple enough. Isn't it?

Until next time, C ya. Enjoy.



Thursday, July 2, 2015

[Tomcat][Debug] Start tomcat in debug mode and remote debug java code in eclipse

More often, we need to debug our applications irrespective of the programming language. I need to debug liferay portlets, hooks etc for troubleshooting issues.

Lets see how we can start our tomcat in debug mode and debug with eclipse. Follow the simple steps.

1. Open catalina.bat in tomcat/bin folder.

2. Search for the line starting with set DEBUG_OPTS=

3. Replace the line with
set DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044

4. Port number given here is 1044, you can choose any port as per the availability.

5. Now start your tomcat by running catalina.bat. Tomcat logs should print this line at the start
Listening for transport dt_socket at address: 1044

6. In the eclipse, you can do remote debugging, Go to Run > Debug Configurations, under Remote Java Application, create a new node and make sure to change port number for debugging.

All done. Your application is ready for debugging.

Until next time, C ya.


Wednesday, July 1, 2015

[Liferay][JSTL] Adding JSTL support for liferay portlet.

Hi,

It a good practice to use JSTL for your portlets jsp rather than using scriptlets. This blog will show how to add support of jstl for your portlets. Follow these simple steps -

1. Add portal-dependency jars to lifeary-plugin-package.properties file

portal-dependency-jars=\
    jstl-api.jar,\
    jstl-impl.jar,\

2. Add portal-dependency tlds to liferay-plugin-package.properties file.

portal-dependency-tlds=\
    liferay-portlet_2_0.tld,\
    liferay-ui.tld,\
    fn.tld,\
    c.tld,\
    fmt.tld

3. In the JSP add taglibs.

<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

4. And now you can use <c:xx />, <fn:xx/> and <fmt:xx> and similarly other taglibs.

Hope this helps.

Until next time. C Ya

[PHP] PHP not working | Code not being executed by apache.

Hi,

I had this problem yet to be resolved. I tried easyphp, zpanel but php did not work for me. I could see my php code in page source in browser. My apache was actually not executing php code as php, rather it was taking as simple html.

To solve this problem, follow the steps below.
1. Check if php is really installed and available. Open command prompt anywhere and execute php -version

This should return something like this.


If you're unable to see, add php to path.

2. Check if php module is added in httpd.conf of your apache. Something like this should be present
LoadModule php5_module "C:/zpanel/bin/php/php5apache2_4.dll"
PHPIniDir "c:/zpanel/bin/php" 

3. Check if AddType is added and uncommented in httpd.conf. If this is not present, add it.
AddType application/x-httpd-php .php

Apart from these, just check the file extension, it should not .php and not accidently saved as .php.txt. And if you're using short tags <? then short tags should be allowed. To allow php short tags follow this post

Hope this helps.

Until next time. C ya.

Tuesday, June 2, 2015

[MySql] Importing Data to Mysql From SQL file

Hi,

Its very often that we need to import data to mysql. Sometimes we have database already created, sometimes does not.

Below is the syntax to import data. When we do have a database already created and want to use that.
mysql -u ravi -p mydatabasename < databasefile.sql

This will prompt for password and import data to mydatabasename.

When we do not have a database already but create database command is written in the file and the same database is used.
mysql -u ravi -p < databasefile.sql

This will also prompt for password because we used -p option which is for password. For username we used -u. Remember that if we want to create a database then user should have appropriate permissions.

That's it.

Hope this helps someone. 

Wednesday, May 6, 2015

[Liferay] Writing Custom Sql for multiple tables in Liferay

Hi Friends,

There were a number of times you might have faced a situation when you need data from multiple tables. Sometimes you would have got the data from one service, extract some data and then call another service, extract some more data and do the processing by writing some logic. Well, this has a major impact on performance and that's not good.

That's not good choice because you can write your own custom SQL query and get the desired result. The query we are writing, we always have a chance to optimize it and boost/improve performance. Alright, enough of the lecture.. lets get to work.

Friday, May 1, 2015

[Liferay][iPad][iPhone] Safari turns numbers into links

There are many calling applications which install some kind of plugin to turn numbers to links on which if you click will offer you to call. Skype's click to call is one of such application.

Well Safari, by default does this. We did not like it. You also don't, probably that's why you're here.. Here is the solution.

Open the theme or template or html file and add this meta tag.

<meta name="format-detection" content="telephone=no">

This will leave all numbers as it is. Now, you may also want to show some phone numbers as link which were actually phone numbers. In this case use like this.

<p>My phone number: <a href="tel:1-203-203-2020">1-203-203-2020</a></p>

This will show the phone number as link.

In case of liferay, open your theme's portal_normal.vm file and add the meta tag as mentioned above.

Hope this helps.

Tuesday, April 7, 2015

[Liferay] Access Liferay Services in Theme or Web Content using Velocity

Sometime, we need to get some data in our web contents. Well, using velocity, we can get the data we want. Create a simple structure and a template. You can assign that structure to some web content later.

Make sure your template script is VM. The below lines of code are for reference, they should help you to get the actual requirement done.

To get namespace of the portlet,
#set ($namespace = $request.get('portlet-namespace'))

To get company id
#set($companyId = $getterUtil.getLong($request.get("theme-display").get("company-id")))

In the line above you also get themeDisplay which can get you many more things. We have $request object here.

To get user service we can use $serviceLocator.
#set($userLocalService = $serviceLocator.findService("com.liferay.portal.service.UserLocalService"))

If you're unable to get $serviceLocator check portal-ext.properties for the property below and set accordingly.

# Set a comma delimited list of variables the Velocity engine cannot
# have access to. This will affect Dynamic Data List templates, Journal
# templates, and Portlet Display templates.
#
velocity.engine.restricted.variables=serviceLocator

Get user from the service
#set($user = $userLocalService.getUserByScreenName($companyId, "kravigupta"))

Get phone service
#set($phoneLocalService = $serviceLocator.findService("com.liferay.portal.service.PhoneLocalService"))

Get all phone numbers of user
#set($userPhones = $phoneLocalService.getPhones($companyId, "com.liferay.portal.model.Contact", $user.getContact().getContactId()))

You can even use validator
#if($validator.isNull($user))
<div>The user is null.</div>
#end

Hope this helps.


Thursday, April 2, 2015

[Iframe] X-Frame-Options : website does not permit framing


One of my friends, working on a project wanted to load another website in an iframe. But kept getting error similar to

Load denied by X-Frame-Options: http://some-website.com/dashboard/home does not permit framing. 

There is a meta tag for HTML that you can include which prevents embedding your site on other sites. For example Someone might use this blog on their own site using iframe. If I want that anyone can embed this site, I could use the meta tag below.

<meta http-equiv="X-Frame-Options" content="allow">

As explained by Mozilla.

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe> or <object> . Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

X-Frame-Options can have three values - DENY, SAMEORIGIN, ALLOW-FROM uri. The values explain themselves very well.

To configure this on Apache modify configuration ( httpd.conf )as below -

Header always append X-Frame-Options SAMEORIGIN

In case you do not have access to httpd.conf file.. you can also use .htaccess as below-

Header append X-FRAME-OPTIONS "SAMEORIGIN"

Well, that was fun :) we'll learn more on clickjacking more in another post.. stay tuned.

Until next time.

Ref : https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options

Wednesday, March 18, 2015

[Liferay] Get HTTPServletRequest in portlet

Hello Friends,

In case you submitted need HttpServletRequest in your portlet, here is the code snippet.

HttpServletRequest request = PortalUtil.getHttpServletRequest(renderRequest);
HttpServletRequest originalServletRequest= PortalUtil.getOriginalServletRequest(request);

This goes all the way from your custom code to  PortalImpl  and then PortletRequestImpl to get the request.

After getting request object it goes to find originalServletRequest.


This will be useful when you submitted your form or link without a proper portlet request or want to read a parameter from url.

Hope this helps.

Wednesday, March 4, 2015

[Liferay] Get URL using Portlet ID

Hi,

Sometimes, we need to get url based on portlet id. All we have is a portlet, we can easily get portlet id and then find the page where it is added.

To generate a url like this, we need PortletRequest, portletId, plid, and phase of the portlet.

plid is layout id which can be get like this..

long plid = PortalUtil.getPlidFromPortletId(themeDisplay.getScopeGroupId(), true, portletId); 

In case you don't know how to get themeDisplay,

ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

Second argument to method is true which shows that this is private layout. In case of public layoue make it false. We already have portletId. 

We now have plid. Phase of the portlet is as per the requirement, assuming it is render phase for us. So once we have all the things. We call PortletURLFactoryUtil and create the url ( PortletURL )- 

PortletURLFactoryUtil.create(request, portletId, plid, PortletRequest.RENDER_PHASE);

That's it. Hope this helps.
Until next time. 

[Liferay] Model Listener hook in 6.2

If you are looking for help to create a model listener hook in Liferay 6.2 here are the simple steps to walk you through.

Step 1. Create a simple hook in plugins sdk. Go to plugins-sdk > hooks directory and run the command below.

create journal-article "Journal Article hook"

Tuesday, February 17, 2015

[Liferay] Can't access request parameters in v6.2 which worked in v6.1

Hi Friends,

I recently had to migrate a portlet from v6.1 to v6.2 of Liferay. Few regular steps and everything showed up in UI. But whenever I submitted a form, nothing was received at processAction. Like if I submit cityName, it can't be received using request.getParameter("cityName") which was working fine till 6.1

But if I change cityName in form to <portlet:namespace/>cityName then it worked.

Thursday, February 12, 2015

[Liferay] Cover Flow portlet is now available on Liferay Marketplace

Hi,

Cover flow portlet is now available on Liferay marketplace.

Here is the link of Liferay Marketplace. Cover Flow Portlet.
Github URL for this portlet, Cover Flow Portlet at Github

Below is the configuration screen, its pretty simple. Just add a folder in Document Library, put images in it, and select in config. Also, you have liberty to choose a number upto which the images should appear in cover flow.

Saturday, January 31, 2015

[OSGi][Service] Creating a service and calling it from other bundle

Hi,

We are going to create a service, export it and import in another bundle. If you did not create a simple bundle yet, follow the post [OSGi] Hello World from OSGi | Create your first OSGi Bundle

We are going to create a classic ECHO service. Whatever is given to the service is ECHOed back to us.

After you are done creating a simple bundle HelloFromOSGi. Follow the steps below.