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.

Thursday, January 29, 2015

[Liferay][Tomcat] Permission Denied Errors in Catalina.out

Hi,

I have seen some people struggling with permission errors when running Liferay. Errors like below..


The main cause for these errors is that server was started with a user lets say A having permissions(like root) and then server was stopped and started by a user lets say B with limited permissions. Now entries in temp and several other places are owned by A and when B tries to start/restart server B is unable to access those files and get permission denied errors.

Tuesday, January 27, 2015

[OSGi] Hello World from OSGi | Create your first OSGi Bundle

Hi Friends,

This post will guide you to create a very very simple Hello World bundle using OSGi. We will use Eclipse for this purpose.

Few simple steps to follow.

Step 1. Create a new project in Eclipse. Open New > Project

Sunday, January 25, 2015

[Eclipse] Workbench has not been created yet. Error while creating OSGi modules.

Hi,

It was my first day with OSGi bundles and I got an error.. Workbench has not been created yet. If you have the same error, please follow the steps below to resolve it.

Step 1. Go to MANIFEST.MF and right click on it and then navigate to Run As > Run Configuration.

Friday, January 23, 2015

[Liferay] java.net.UnknownHostException | Unknown Host Exception Liferay

Hi,

I got this exception on a fresh Linux machine. It was clear that Liferay was not able to find the hostname entries properly. Solution was simple. Just needed to add hostname in hosts file. Here is the exception log.

And the solution here.. On linux open /etc/hosts file and make an entry.

> sudo vim /etc/hosts


That's it. Pretty easy. :) Hope this helps someone.