Tuesday, 7 April 2015

How to create Action Filter in Liferay

How to create Action Filter in Liferay

1) Create a filter class inside portlet

    Here is the sample code for the ActionFilter
   
    package com.test;

    import java.io.IOException;    
    import javax.portlet.ActionRequest;
    import javax.portlet.ActionResponse;
    import javax.portlet.PortletException;
    import javax.portlet.filter.ActionFilter;
    import javax.portlet.filter.FilterChain;
    import javax.portlet.filter.FilterConfig;
    
    public class ActionTestFilter implements ActionFilter {
    
    public void init(FilterConfig arg0) throws PortletException {
    System.out.println("Hey I am in init method of filter");
    }
    
    public void doFilter(ActionRequest arg0, ActionResponse arg1,
    FilterChain arg2) throws IOException, PortletException {
    System.out.println("Hey I am in doFilter");
    }
    
    @Override
    public void destroy() {
    System.out.println("Hey I am in destroy method of filter");
    }
    
    }
   
So far, we have decided what action needs to be performed before "init" , "destroy" and  "processAction" method gets called of a portlet.

2) Use portlet.xml file to specify for which portlet we need to call above filter
    (It is possible that in one war we might have created more than one portlet)

3) Below entries need to be added after <portlet> tag inside "portlet.xml" file  
    <filter>
<filter-name>Action</filter-name>
<filter-class>com.test.ActionTestFilter</filter-class>
<lifecycle>ACTION_PHASE</lifecycle>
</filter>

<filter-mapping>
<filter-name>Action</filter-name>
<portlet-name>*</portlet-name>
</filter-mapping>

4) We have configured "*" inside "<portlet-name>*</portlet-name>" which means filter will be called across all the portlet available in same war file.

Thats it! Custom filter is configured.

Now, Lets test it.

1) Deploy portlet and you will see below message inside log file

    Hey I am in init method of filter

2) Call processAction method and you will see below message inside log file.

    Hey I am in doFilter
   
3) Undeploy portlet and you will see below message inside log file

    Hey I am in destroy method of filter
   
Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics     

Monday, 30 March 2015

How to remove Liferay Ext / How to undeploy Liferay Ext


There are 10 easy steps to remove/undeploy ext environment from Liferay Bundle

Step 0 : Stop Server / Tomcat Bundle

Step 1 : Go to the location "...\liferay-portal-*\tomcat-*\webapps\ROOT\WEB-INF and remove below files
    >   ext-*-*-ext.xml
    >   liferay-portlet-ext.xml
    >   portlet-ext.xml
    >   struts-config-ext.xml
    >   tiles-defs-ext.xml

Step 2: Go to the location "...\liferay-portal-*\tomcat-*\webapps\ROOT\WEB-INF\lib and remove below jar files
    >   ext-*-ext-impl.jar
    >   ext-*-ext-util-bridges.jar
    >   ext-*-ext-util-java.jar
    >   ext-*-ext-util-taglib.jar

Step 3: Go to the location "...\liferay-portal-*\tomcat-*\lib\ext and delete the below service jar
    >   ext-*-ext-service.jar

Step 4: Go to the location "...\liferay-portal-*\tomcat-*\webapps and delete the below folder
    >   *-ext

Step 5: Go to the location "...\liferay-portal-*\tomcat-*\webapps\ROOT\WEB-INF\classes / ...\liferay-portal-*\ and modify portal-ext.properties file
    Note : 1) Need to check for any of the start up events like "application.startup.events="
           2) Skip such events on server start up

Step 6: Remove "temp" and "work" folders from the location "liferay-portal-*\tomcat-*"

Step 7: Start tomcat bundle

Step 8: Put .war file of ext inside "deploy" folder and wait for below message on catalina.out

    "Extension environment for *-ext has been applied. You must reboot the server and redeploy all other plugins."
   
Step 9: Uncomment any changes in portal-ext.properties file made in point #5

Step 10: Restart your server

All Done! Ext is removed/undeployed. Enjoy Coding.

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics 

Tuesday, 24 February 2015

How to make Liferay's Action Request Parameters available in Render / doView

There are four different ways to pass/copy parameters from Liferay's Action Phase to Render Phase.

1) Pass all parameters
    -   Use PortalUtil class to copy all the parameters in processAction method
    -   PortalUtil.copyRequestParameters(actionRequest, actionResponse);    
        (This can be used if all the parameters passed are required in render method)

2) Pass selective parameters
    -   Manually set variables inside renderparameter inside processAction method
    -   actionResponse.setRenderParameter("action", "Y");    
        (Value set here can be used in rendermethod using renderRequest.getParameter("action"))
 
3) Pass all parameters across all processAction method
    -   Specify below value inside portlet.xml file
                 <init-param>
<name>copy-request-parameters</name>
<value>true</value> 
</init-param>  
   (Need to redeploy your portlet to brig above change into effect.)
 
4) Pass all parameters via manually reading
    -   Some people create Enumeration to iterate over all the elements and put in RenderParameter one by one
    -   Ex:
    Enumeration<String> paramNames = actionRequest.getParameterNames();
    while(paramNames.hasMoreElements()){        
        actionResponse.setRenderParameter(paramNames.nextElement(), actionRequest.getParameter(paramNames.nextElement()));
    }  
   
Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics

Monday, 23 February 2015

How to read Liferay's URL parameter via script

Steps to read Liferay URL parameter via script.

1) Add a tag in your .JSP to read portlet namespace
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

2) Create a global script variable inside your JSP for portlet name space
<script type="text/javascript" charset="utf-8">
var portletNamespace ='<portlet:namespace/>';
</script>

In a js file we can not use '<portlet:namespace/>' directly, hence we need to create a global js variable which can be accessed in .js file.

3) Create a function which reads and returns the URL parameter
function getURLParameterValue(parameterName, url) {
parameterName = parameterName.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var results = new RegExp('[\\?&]'+parameterName+'=?([^&#]*)').exec(url || window.location.href);
return results == null ? null : results[1];
}

Here, function accepts two values
#1) "parameterName" whose value needs to be read (This is an actual name from the URL parameter)
#2) "url" (Its an href location / window's current URL)

4) Read the URL in the javascript function
Let's say this is your URL :     <protocol>://<hostname>:<port>/group/control_panel/manage?p_auth=asdfg&p_p_auth=xyz&p_p_id=_sometext_WAR_sometextportlet_&p_p_lifecycle=1&p_p_state=maximized&p_p_mode=view&doAsGroupId=12345&refererPlid=5555&_sometext_WAR_sometextportlet_id=123456

Ex: Read Liferay Parameter
>) getURLParameterValue(portletNamespace + "id", window.location.href)
will return "123456"
Ex: Read Any parameter without portletNamespace prefixed
>) getURLParameterValue("p_auth", window.location.href) 
will return "asdfg"

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics

Friday, 20 February 2015

How to use Liferay's serveResource method

Steps to use Liferay's serveResource method / Ajax call

Step 1: Create "resourceURL" in your JSP

Here is the snippet for the "View.jsp"

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:resourceURL var="dynamiceResourceURL"></portlet:resourceURL>

<a href="dynamiceResourceURL">Dynamic Content</a>

Step 2: Create a "serveResource" method inside your MVCPortlet/Controller

Here is the snippet for <Your>Portlet

        @Override
public void serveResource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
System.out.println("In serveResource method");
resourceResponse.setContentType("text/html");
PrintWriter writer = resourceResponse.getWriter();
writer.print("This is dynamic content.");
super.serveResource(resourceRequest, resourceResponse);
}

Step 3: Drop <your portlet> on portal page and click on the link "Dynamic Content". It will show result "This is dynamic content." which is returned by "serverResource" method of <your> controller.


Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics


Wednesday, 11 February 2015

Liferay + Alloy UI + Iterate Element via CSS Class

How to apply "selectedClass" on "li" element based on the dynamic value (Page Load).

<!-- HTML structure -->

<ul class="ul_container">
<li class="selectLiDynamically" id="sort_1" textContent="first">
<a href="#">Hello One</a> 
</li>
<li class="selectLiDynamically" id="sort_2" textContent="second">
<a href="#">Hello Two</a>
</li>
<li class="selectLiDynamically" id="sort_3" textContent="third">
<a href="#">Hello Three</a>
</li>
</ul>

//AUI script

AUI().ready('node', function (A) {
A.all('.selectLiDynamically').each(function(obj) {
if(obj.attr("textContent") == '<%=selectValue%>') {
if(A.one("#"+obj.attr("id"))) {
A.one("#"+obj.attr("id")).addClass(selectedClass);
}
} else {
if(A.one("#"+obj.attr("id"))) {
A.one("#"+obj.attr("id")).removeClass(selectedClass);
}
}
});
});

Here '<%=selectValue%>' is the value which comes dynamically from the request and based on that value, we iterate all the "li" element via class value i.e. "selectLiDynamically".

If dynamic value matches with the "id" of the "li" element, we add the "selectedClass" on that object else we remove "selectedClass" from the "li" element.

We are done with applying css class dynamically via AUI, on page load.

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics

Friday, 7 November 2014

Liferay + Solr Configuration

Steps to configure Solr on Windows with Liferay

I have configured Solr for below environment
>    apache-solr-1.4.1
>    apache-tomcat-7.0.47
>    liferay-portal-6.1.20-ee-ga2

1)    Download Apache Solr 1.4.1
2)    Unzip downloaded .zip file on the location D:/runtime/apache-solr-1.4.1
3)    Copy war file D:/runtime/apache-solr-1.4.1/dist/apache-solr-1.4.1.war to D:/runtime/apache-solr-1.4.1/example/solr
4)    Go to the location D:/runtime/apache-solr-1.4.1/example/solr/conf/
5)    Open file "solrconfig.xml" from above location
6)    Search for the tag "<dataDir>${solr.data.dir: ./solr/data}</dataDir>"
7)    Replace the above tag like below
    "<dataDir>${solr.data.dir:D:/runtime/apache-solr-1.4.1/example/solr/data}</dataDir>"
    (This is the data folder where all the solr indexes will be created)
   
Lets run the solr instance on the plain apache tomcat instance
(In our case it is "apache-tomcat-7.0.47")

1)    Extract the "apache-tomcat-7.0.47" on the location "D:\bundle\solr"
2)    Create a below folder structure if not already available
    D:\bundle\solr\apache-tomcat-7.0.47\conf\Catalina\localhost
3)    Create a file on above path with the name "solr.xml"
4)    Add below content inside "solr.xml" file
    <?xml version="1.0" encoding="utf-8"?>
    <Context docBase="D:/runtime/apache-solr-1.4.1/example/solr/apache-solr-1.4.1.war" debug="0" crossContext="true">
    <Environment name="solr/home" type="java.lang.String" value="D:/runtime/apache-solr-1.4.1/example/solr" override="true"/>
    </Context>

5)    Start tomcat to monitor logs. Make sure that there are no logs available.
    You should see below message under logs to make sure that server is started properly.
   
    INFO: Deploying web application directory D:\bundle\solr\apache-tomcat-7.0.47\webapps\examples
    Nov 07, 2014 4:21:58 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory D:\bundle\solr\apache-tomcat-7.0.47\webapps\host-manager
    Nov 07, 2014 4:21:58 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory D:\bundle\solr\apache-tomcat-7.0.47\webapps\manager
    Nov 07, 2014 4:21:58 PM org.apache.catalina.startup.HostConfig deployDirectory
    INFO: Deploying web application directory D:\bundle\solr\apache-tomcat-7.0.47\webapps\ROOT
    Nov 07, 2014 4:21:58 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-apr-8080"]
    Nov 07, 2014 4:21:58 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-apr-8009"]
    Nov 07, 2014 4:21:58 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 4928 ms

   
6)    Confirm from browser that server is working properly
7)    Hit "http://localhost:8080/solr/"
8)    You should see below message in browser
    Welcome to Solr!
    Solr Admin
9)    If you are able to see above message, congratulations we are done with solr setup

Now, lets see the steps to integrate solr with Liferay.

1)    Extract "liferay-portal-6.1.20-ee-ga2" to the location "D:\bundle\solr"
2)    Download solr plugin from net in my case it is as below
    15187207_18881208_18881218.lpkg
    (Make sure that it is compatible with your Liferay)
3)    Put the solr plugin in the location "D:\bundle\solr\liferay-portal-6.1.20-ee-ga2\deploy
4)    Go to the location D:\bundle\solr\liferay-portal-6.1.20-ee-ga2\tomcat-7.0.27\conf
5)    Open server.xml file to change the port (Need to change as tomcat is already using default ports)
    Change below ports:
        >    <Server port="9005" shutdown="SHUTDOWN"> from <Server port="8005" shutdown="SHUTDOWN">
        >    <Connector port="9080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8" />

            from
            <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8" />

        >     <Connector port="9009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8" />
            from
             <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8" />
6)    Start the liferay tomcat server
7)    Monitor tomcat logs for exceptions if any
8)    You should see below message in tomcat to make sure that tomcat is started successfuly
    Nov 7, 2014 10:52:56 AM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    Nov 7, 2014 10:52:56 AM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-bio-9080"]
    Nov 7, 2014 10:52:56 AM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-bio-9009"]
    Nov 7, 2014 10:52:56 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 45386 ms
9)    Shutdown both the servers
    >    apache-tomcat-7.0.47
    >    liferay-portal-6.1.20-ee-ga2
10)    Go to the location D:\bundle\solr\liferay-portal-6.1.20-ee-ga2\tomcat-7.0.27\webapps\solr-web\WEB-INF\classes\META-INF
11)    Open file "solr-spring.xml"
12)    Search for the tag <bean id="com.liferay.portal.search.solr.server.BasicAuthSolrServer"
    (Replace the constructor-argument as below "<constructor-arg type="java.lang.String" value="http://localhost:8080/solr" />")
13)    Go to the location "D:\bundle\solr\liferay-portal-6.1.20-ee-ga2\tomcat-7.0.27\webapps\solr-web\WEB-INF\conf"
14)    Copy the file "schema.xml"
15)    Go to the location D:\runtime\apache-solr-1.4.1\example\solr\conf
16)    Paste the "schema.xml" file in this location (Need to overwrite file)
17)    Start "apache-tomcat-7.0.47" server, once it is up then start "liferay-portal-6.1.20-ee-ga2"
18)    Go to the Liferay Control panel -> Server Administration -> Resources
19)    Click on the "Reindex all search indexes"
20)    Indexes will be generated on the path "D:\runtime\apache-solr-1.4.1\example\solr\data"

We are done with integration of liferay with solr.

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics