Thursday, 2 July 2015

How does Abstract Factory Design Pattern work in java

Abstract Factory Design Pattern (AFDP) falls under the creational type. It provides one of the best ways to create the object. It is also known as the factory of factories.

Lets see in details how Abstract Factory Design Pattern works with the example of "Vehicle" and "Manufacturer" of the Vehicle.

Here is the overall architecture of our example.


Step 1: Create the interface of the Vehicle.

package com.designpattern.abstractfactory;

public interface Vehicle {
void speed();
}

Step 2: Create the implementation of the "Vehicle"

package com.designpattern.abstractfactory;

public class TwoWheeler implements Vehicle {
public void speed() {
System.out.println("My speed is 110km/hr");
}
}

package com.designpattern.abstractfactory;

public class FourWheeler implements Vehicle {
public void speed() {
System.out.println("My speed is 180km/hr");
}
}

Step 3: Create the interface for the "Manufacturer"

package com.designpattern.abstractfactory;

public interface Manufacturer {
void logo();
}

Step 4: Create the implementation of the "Manufacturer"

package com.designpattern.abstractfactory;

public class German implements Manufacturer{
public void logo() {
System.out.println("German Logo");
}
}


package com.designpattern.abstractfactory;

public class Korean implements Manufacturer{
public void logo() {
System.out.println("Korean Logo");
}
}

Step 5: Create the "AbstractFactory" class 

package com.designpattern.abstractfactory;

public abstract class AbstractFactory {
abstract Vehicle getVehicle(String vehicleType);
abstract Manufacturer getManufacturer(String manufacturerType);
}

Step 6 : Create the implementation class of "AbstractFactory"

package com.designpattern.abstractfactory;

public class VehicleFactory extends AbstractFactory{

@Override
Manufacturer getManufacturer(String manufacturerType) {
// TODO Auto-generated method stub
return null;
}
@Override
Vehicle getVehicle(String vehicleType) {
if(null == vehicleType) {
return null;
} else if ("TwoWheeler".equalsIgnoreCase(vehicleType)) {
return new TwoWheeler();
} else if ("FourWheeler".equalsIgnoreCase(vehicleType)) {
return new FourWheeler();
} else {
return null;
}
}

}


package com.designpattern.abstractfactory;

public class ManufacturerFactory extends AbstractFactory{

@Override
Manufacturer getManufacturer(String manufacturerType) {
if(null == manufacturerType) {
return null;
} else if ("German".equalsIgnoreCase(manufacturerType)) {
return new German();
} else if ("Korean".equalsIgnoreCase(manufacturerType)) {
return new Korean();
} else {
return null;
}
}
@Override
Vehicle getVehicle(String vehicleType) {
// TODO Auto-generated method stub
return null;
}

}


Step 7: Create FactoryProducer class 

package com.designpattern.abstractfactory;

public class FactoryProducer {
public static AbstractFactory getFactory(String option) {
if("Vehicle".equalsIgnoreCase(option)) {
return new VehicleFactory();
} else {
return new ManufacturerFactory();
}
}
}


Step 8: Create a Demo class

package com.designpattern.abstractfactory;

public class Demo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractFactory abstractFactory1 = FactoryProducer.getFactory("Vehicle");
Vehicle vehicle1 = abstractFactory1.getVehicle("TwoWheeler");
vehicle1.speed();
Vehicle vehicle2 = abstractFactory1.getVehicle("FourWheeler");
vehicle2.speed();
AbstractFactory abstractFactory2 = FactoryProducer.getFactory("Manufacturer");
Manufacturer manufacturer1 = abstractFactory2.getManufacturer("German");
manufacturer1.logo();
Manufacturer manufacturer2 = abstractFactory2.getManufacturer("Korean");
manufacturer2.logo();
}

}


Step 9: Check out the output

Here is the output for "Demo" class

My speed is 110km/hr
My speed is 180km/hr
German Logo
Korean Logo


Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

How does Factory Design Pattern work in Java

Factory Design Pattern (DP) is used to create an object without exposing the creation logic. It comes under the creational pattern.

To understand how Factory DP works lets take a simple example of "Vehicle".

To get the object of the "Vehicle" we will pass details like (TwoWheeler, FourWheeler) to VehicleFactory and VehicleFactory will return an object of the type "Vehicle" based on the parameter passed.

Overall here is an architecture of our implementation:


Lets see implementation of classes/interface:

Step 1: Vehicle Interface which has prototype method called "speed"

package com.designpattern.factory;

public interface Vehicle {
void speed();
}

Step 2: Concrete implementation of "Vehicle" interface.

package com.designpattern.factory;

public class TwoWheeler implements Vehicle {
@Override
public void speed() {
System.out.println("Hey my max speed is 110km/hr");
}
}


package com.designpattern.factory;

public class FourWheeler implements Vehicle {
@Override
public void speed() {
System.out.println("Hey my max speed is 180km/hr");
}
}

Step 3: VehicleFactory class which actually creates the object of Vehicle based on the "vehicleType"

package com.designpattern.factory;

public class VehicleFactory {
public Vehicle getVehicle(String vehicleType) {
if(null == vehicleType) {
return null;
} else if("TwoWheeler".equalsIgnoreCase(vehicleType)) {
return new TwoWheeler();
} else if("FourWheeler".equalsIgnoreCase(vehicleType)) {
return new FourWheeler();
}
return null;
}
}


Step 4: Demo class which makes use of the "VehicleFactory" class and uses the object returned/created by "VehicleFactory" class

package com.designpattern.factory;

public class Demo {
public static void main (String args[]) {
VehicleFactory vehicleFactory = new VehicleFactory();
Vehicle vehicle1 = vehicleFactory.getVehicle("TwoWheeler");
vehicle1.speed();
Vehicle vehicle2 = vehicleFactory.getVehicle("FourWheeler");
vehicle2.speed();
}
}


Step 5: Check out the output of "Demo" class

Here is the output of "Demo" program:

Hey my max speed is 110km/hr
Hey my max speed is 180km/


Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Tuesday, 30 June 2015

How to modify/override default value of Liferay's property

Liferay controls many things via properties and it supports to override the value of the portal.properties file.
There are two ways available to override portal.properties file.
1) Using portal-ext.properties
2) via Hook.

Lets see how can we override liferay properties via hook.

There are three simple steps to achieve it:

1)  Modify "lieray-hook.xml" to provide support for "properties" file
2)  Create the "portal.properties" file inside "src" folder of the Hook project
3)  Deploy and verify changes

Lets look at the steps in detailed:

1)  Modify "lieray-hook.xml" to provide support for "properties" file
    <hook>
        :
        <portal-properties>portal.properties</portal-properties>
        :
    </hook>
 
    We have specified the file which should be used to override existing liferay properties
 
2)  Create the "portal.properties" file inside "src" folder of the Hook project

Lets say we like to call perform some action before user logs in. That is being controlled by the property called "login.events.pre".

Here is the entry you need to write inside "portal.properties" file.
login.events.pre=com.student.CheckRegistration

So "CheckRegistration" will be called before student/user logs in.

 
3)  Deploy and verify changes

    Once changes are done we need to deploy our Hook project and upon next time login your custom class will be triggered before student login.
 
Note:
   1) If you like to know what all properties can be override using Hook you need to check "liferay-portal-src-6.*\definitions\liferay-hook_6*.dtd"
   2) If you like to know what is the default value of the property you override you can check it on location "\liferay-portal-src-6*\portal-impl\src\portal.properties"
 
 
Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics

Monday, 29 June 2015

How to override custom JSP using Liferay Hook

Many a times we like to make a minor changes on the existing OOTB portlet's JSP. Liferay allows to override / modify existing JSP using Hook.

There are three simple steps to achieve it:

1)  Modify "lieray-hook.xml" to provide support for custom jsps (Assuming you have Hook project with JSP Hook created)
2)  Copy the mirror path (JSP name along with folder structure) from  "liferay-portal-[version]/tomcat-6.*/webapps/ROOT"
3)  Deploy and verify changes


Lets look at the steps in detailed:

1)  Modify "lieray-hook.xml" to provide support for custom jsps  (Assuming you have Hook project with JSP Hook created)
    <hook>
        :
        <custom-jsp-dir>/custom_jsps</custom-jsp-dir>
        :
    </hook>
   
    We have specified the custom JSP path inside which all the overridden JSPs will reside
   
2)  Copy the mirror path (JSP name along with folder structure) from  "liferay-portal-[version]/tomcat-6.*/webapps/ROOT"

Lets say we like to override error page which resides inside "webapps\ROOT\errors\404.jsp".

In this case we need to create the folder "errors" inside "/custom_jsps" and copy and paste the 404.jsp file inside "errors".

So after copy our folder structure would look like this "docroot\custom_jsps\errors\404.jsp".
Open the JSP file and make your changes in it.
   
3)  Deploy and verify changes

    Once changes are done we need to deploy our JSP hook project. Once hook is successfully deployed move onto the below path
   
    "liferay-portal-[version]/tomcat-6.*/webapps/ROOT/errors/" and see that now there would be two JSPs.
   
    1)  404.jsp (your overridden changes)
    2)  404.portal.jsp (original JSP)
   
    Note: If you undeploy your JSP hook at that time liferay will delete 404.jsp and rename "404.portal.jsp" with 404.jsp to bring original file back.
   
   
Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics

Sunday, 28 June 2015

How to create Singleton class in Java (Design Pattern)

Singleton Design Pattern needs to be used when :

    1)  Application needs one, and only one, instance of an object
    2)  Provide a global point of access to the object
   
Here are the thumb rule for creating singleton class

1)  Create private constroctor
    -   This is required so that no one can create instance directly using "new" keyword"
2)  Create "static" method to return Singleton class's object (Lets say method is "getInstance()")
    -   This method is used to create and return object of "Singleton" class
    -   This method will make sure that only one object is available
    -   Since constructor is private in that case we can not create object and access method hence we need a static method which can be
        accessed directly with the "Class" name
3)  Create method "getInstance" as "synchronized"
    -   To avoid creating two objects accidently in case of multi threading environment
4)  Create "private" data member of "Singleton" class
    -   So that datamember can't be accessed directly


Here is the code snippet for the quick reference:

class Singleton
{
private static Singleton instance;
private Singleton() {
//Private constructor, because we don't allow object to be created using new keyword
}

public static synchronized Singleton getInstance()
{
   //Checks if object is not created then only it will go and create next time onwards it will return already created instance
   //keeping this method synchronized is very important where multiple threads gets executed in parallel
if (instance == null)
instance = new Singleton();

return instance;
}
}


Now, you can access/create object of a "Singleton" class like this.

Singleton singleton = null;
singleton = Singleton.getInstance();


Note: Singleton design pattern ensures that one object is available per JVM, in case of clustering environement where more than one JVM are available at that time as many objects would be created as many JVMs.  

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics 

Thursday, 25 June 2015

How to provide multilingual support in Liferay custom portlet

Providing multilingual support in Liferay is very easy. Just need to follow few simple steps and we are all done.

Here are the steps needs to be performed:

1)  Modify portlet.xml file to specify the resource bundle entry
2)  Create properties file for the locate we need to support
3)  Use liferay-ui tld to show message
4)  Deploy and verify changes

Here are the detailed steps:

1)  Modify portlet.xml file to specify the resource bundle entry

    Add the entry "<resource-bundle>content.Language</resource-bundle>" inside the portlet tag. Tag specifies the location of the
    language file.
   
2)  Create properties file for the locate we need to support

    Need to create a key=value pair of properties file based on the locale.
   
    Ex: Language_es.properties
        Language.properties
   
    If we select a region whose corresponding file is not exist then value available inside "Language.properties" will be default as default.
    If we select "Spanish" then the value of the key available inside "Language_es.properties" will be shown to user.
   
3)  Use liferay-ui tld to show message

    On JSP we need to import "liferay-ui" taglib as shown below
   
    <%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
   
    Once tablib import is done we can use "liferay-ui" to show messages to the user. So label will be fetch from the language property file based
    on the locale selected.
   
    Here is the code snippet to use message:

    <liferay-ui:message key="message1" />  
   
   
4)  Deploy and verify changes  

    Yupee! we are done from the configuration part. Lets build and deploy latest war and check the JSP where we have used "liferay-ui" to show
    message. Add the Language portlet on the page and change the language(locale) to "Spanish" you will see value against the key mentioned inside "Language_es.properties"
    file.
   
    Ex: Here are the entries inside
    1)  Language_es.properties
        message1=I am spanish
    2) Language.properties
        message1=I am Default Message

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics    

Wednesday, 24 June 2015

How to do Liferay IPC using Public Render Parameter

How to share data among Liferay Portlets. Liferay provides multiple ways to share the data between more than two portlets. IPC (Inter Portlet Communication) is one of the ways.

Lets see how can we share data using Public Render Parameter:

There are three simple steps available

1)  Modify portlet.xml file and add variable to be shared
2)  Modify controller class to add / access shared variable
3)  Redeploy portlet and verify changes

Here are the detailed steps for doing same:

1)  Modify portlet.xml file and add variable to be shared 

  Here is the code snippet for portlet.xml file
   
    <portlet-app>
    <portlet>
       <portlet-name>FirstPortlet</portlet-name>
        :
        :
        <supported-public-render-parameter>studentName</supported-public-render-parameter>
   </portlet>
   <portlet>
       <portlet-name>SecondPortlet</portlet-name>
        :
        :
        <supported-public-render-parameter>studentName</supported-public-render-parameter>
   </portlet>

<public-render-parameter>
        <identifier>studentName</identifier>
        <qname xmlns:x="http://www.liferay.com/public-render-parameters">x:studentName</qname>
       </public-render-parameter>
        </portlet-app>

    We have used two portlets FirstPortlet and SecondPortlet. Both the Portlet's <portlet> tag contains attribute "<supported-public-render-parameter>"
    where we need to add entry of the parameter shared parameter. If we dont specify "<support..." entry that portlet will not be able to access shared variable.
   
    Outside the <portlet> tag we need to specify "<public-render-parameter>" which specifies the list of all the shared parameters. In our case
    we have provided "x:studentName" as the shared parameter.
   
2)  Modify controller class to add / access shared variable    

        We have two portlets. First and Second. In below snippet we can see that FirstPortlet sets the shared variable inside processAction method.
        Second portlet reads the shared variables value inside render phase.
   
        FirstController
actionResponse.setRenderParameter("studentName", "Test");
       
        SecondController
        String name  = ParamUtil.getString(renderRequest, "studentName");
LOGGER.info("Details -> " + name);

3)  Redeploy portlet and verify changes

    Now lets build the portlet and deploy it. Drop both the portlets on the same portal page. Perform some action on FirstPortlet so that value of "studentName" gets set.
    During render method of the SecondPortlet read the value and print the value on console.

Here is the Output we can see in console:        
        06:53:16,062 INFO  [SecondPortlet:42] Details -> Test

Cheers! You are done.

Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics