Thursday, 30 April 2015

How to create multiple actions in Liferay MVC

There are 4 simple steps to create Multiple actions in Liferay MVC Portlet

1) Create multiple liferay actions inside JSP
2) Create corresponding action method inside controller
3) Create buttons inside JSP with different action to be performed
4) Write below script to change the action method on form submit based on the student action performed

Here are the detailed level steps

1) Create multiple liferay actions inside JSP

<portlet:actionURL name="saveStudentDetails" var="saveStudentDetails" />
<portlet:actionURL var="getStudentDetails" name="getStudentDetails" />    


2) Create corresponding action method inside controller

public void saveStudentDetails(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {

System.out.println("Inside save student details");
//Your custom logic to save student details starts
}


public void getStudentDetails(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {

System.out.println("Inside get student details");
//Your custom logic to fetch student details starts
}


3) Create buttons inside JSP with different action to be performed

<input type="button" name="retrieveStudentDetails" id="retrieveStudentDetails" onclick='getStudentDetail()' value="Get Student Details" /> &nbsp;
<input type="button" name="saveStudentDetail" id="saveStudentDetail" onclick='saveStudentDetail()' value="Save Student Details" /> <br/>


4) Write below script to change the action method on form submit based on the student action performed

<script type="text/javascript">

    //Below method to be called if user clicks on the "retrieveStudentDetails" button
    function getStudentDetail() {
    document.fm.action='<%=getStudentDetails%>';
    document.fm.submit();
    }
    
    //Below method to be called if user click on the save student details
    function saveStudentDetail() {
    document.fm.action='<%=saveStudentDetails%>';
    document.fm.submit();
    }

</script>

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics

Monday, 27 April 2015

How to implement Liferay Captcha in Custom Portlet

There are 3 simple steps to implement and verify/validate Liferay Captcha in your custom portlet

1) Declare taglibs in your JSP

2) Generate resourceURL which will return random number as a captcha

3) Verify captcha in your controller before executing business logic

Here are the detailed steps/code snippet with explanations

1) Declare taglibs in your JSP

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>

<portlet:defineObjects />

<%-- Liferay URL's for Action and Ajax --%>
<portlet:actionURL name="saveStudentDetails" var="saveStudentDetails" />
<portlet:resourceURL var="captchaURL" />

<aui:form action="<%= saveStudentDetails %>" method="post" name="fm">
    <input type="text" name="studentName" id="studentName" />
    <input type="submit" name="student" id="student" name="student" value="Save Student" /> &nbsp;
    <%-- Below line will show Image on the JSP --%>
    <liferay-ui:captcha url="<%=captchaURL%>" />

</aui:form>

2) Generate resourceURL which will return random number as a captcha

In above JSP we can see that we have used liferay's tag i.e. <liferay-ui:captcha url="<%=captchaURL%>" /> which will serve / show image to the user.

Here we can see that random image will be served via Liferay Ajax call i.e. <portlet:resourceURL var="captchaURL" />

3) Verify captcha in your controller before executing business logic

Inside controller there are two methods available
i) "serveResource" method which will simply return random number to the user via Ajax call
    //Here is a quick snippent:
   
    import com.liferay.portal.kernel.captcha.CaptchaUtil;

    @Override
    public void serveResource(ResourceRequest resourceRequest,
                ResourceResponse resourceResponse)
          throws  IOException, PortletException {

          try {
                CaptchaUtil.serveImage(resourceRequest, resourceResponse);
          }
          catch (Exception e) {
                System.out.println("An exception occured while serving captcha image");
          }
    }
ii) Validate user entered captcha on form submit
    Here is a quick snippent:
   
    public void saveStudentDetails(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {

System.out.println("Save student details");
try{
          CaptchaUtil.check(actionRequest);
          //This piece of code will be executed only if user entered data is correct for captch. If it is mis match it will throw "CaptchaException"
          }catch(CaptchaException e){
                System.out.println("User entered captcha miss match.");               
          }
}

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics   

Thursday, 16 April 2015

How to sort Java Objects using Comparable / Comparator Interface

There are two ways for sorting an object.

Here, is the quick reference
1) Comparable we use for natural sorting
2) Comparator for no natural sort order

Lets see both the examples one bye one

1) Comparable Example

package comparable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Student implements Comparable<Student> {

private int studentId;

//Constructor with one argument
public Student(int studentId) {
this.studentId = studentId;
}

public int compareTo(Student anotherInstance) {
return this.studentId - anotherInstance.studentId;
}

public static void main(String args[]) {

//Lets create a student list with random numbers
List<Student> studentList = new ArrayList<Student>();
studentList.add(new Student(5));
studentList.add(new Student(1));
studentList.add(new Student(3));
studentList.add(new Student(4));
studentList.add(new Student(2));

//Sorting of Student object based on studentId
Collections.sort(studentList);

System.out.println("Sorting Result (Based on studentId)");
//Display Student in ascending order
for(Student student: studentList) {
System.out.println(student.studentId);
}
}
}

Here is the output of above program execution:

Output
Sorting Result (Based on studentId)
1
2
3
4

5

2) Comparator Example

package comparator;

import comparator.Student;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Student {

    private int weight;
    private int height;

    public Student(int weight, int height) {
        this.weight = weight;
        this.height = height;
    }
   
public int getWeight() {
return weight;
}

public void setWeight(int weight) {
this.weight = weight;
}

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}


public static void main(String[] args) {

//Dummy List of Students
List<Student> studentList = new ArrayList<Student>();
studentList.add(new Student(60,5));
studentList.add(new Student(50,6));
studentList.add(new Student(55,4));
studentList.add(new Student(65,6));
studentList.add(new Student(70,5));

// Sort by weight:
Collections.sort(studentList, new StudentWeightComparator());

System.out.println("Sorting based on Weight");
//Display Student in ascending order based on weight
for(Student student: studentList) {
System.out.println(student.getWeight() + "," + student.getHeight());
}

// Sort by height:
Collections.sort(studentList, new StudentHeightComparator());

System.out.println("Sorting based on Height");
//Display Student in ascending order based on height
for(Student student: studentList) {
System.out.println(student.getWeight() + "," + student.getHeight());
}

//In line comparator
Collections.sort(studentList, new Comparator<Student>() {
public int compare(Student student1, Student student2) {
return student1.getWeight() - student2.getWeight();
}
});


System.out.println("Inline comparator for Sorting (Based on Weight)");
//Display Student in ascending order based on weight
for(Student student: studentList) {
System.out.println(student.getWeight() + "," + student.getHeight());
}

}
}

//Student Weight Comparator
class StudentWeightComparator implements Comparator<Student> {
    public int compare(Student student1, Student student2) {
        return student1.getWeight() - student2.getWeight();
    }
}

//Student Height Comparator
class StudentHeightComparator implements Comparator<Student> {
    public int compare(Student student1, Student student2) {
        return student1.getHeight() - student2.getHeight();
    }
}

Output
Sorting based on Weight
50,6
55,4
60,5
65,6
70,5
Sorting based on Height
55,4
60,5
70,5
50,6
65,6
Inline comparator for Sorting (Based on Weight)
50,6
55,4
60,5
65,6

70,5

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics  

Wednesday, 8 April 2015

How to use Lieray Service without creating portlet

There are 6 simple steps to check / test OOTB Liferay's LocalServiceUtil methods

Step 1: Go to the Liferay login page

Step 2: Login using portal admin

Step 3: Go to the "Control Panel" -> "Server Administration" -> "Script" tab

Step 4: Select the "Javascript" as Language

Step 5: Provide below script under "Script" tab

    // ### Javascript Sample ###

    number = Packages.com.liferay.portal.service.UserLocalServiceUtil.getUsersCount();
    
    out.println(number);

Step 6: Click on "Execute"

Cheers! You are done. Output is available under the "Output" section

FYI, 1) We have used User Local Service to get user count like wise we can use any liferay OOTB service.
        2) Apart from "Javascript", Liferay provides "Beanshell", "Groovy", "Python", "Ruby" languages.

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics  

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