Thursday, 9 July 2015

How to use Liferay AUI's Autocomplete feature

Liferay bundle comes with the AUI module loaded by default. AUI supports many of the client side components one of them is "Autocomplete".

Here are the steps to use AUI autocomplete feature

1) Download and Extract "alloy-1.5.1" (required if bundle is not Liferay,lets say creating dynamic web project)
2) Create JSP file to add aui's js & corresponding stylesheet
3) Load "aui-autocomplete" module on JSP
4)  Run & Verify

Here are the steps in detailed:

1) Download and Extract "alloy-1.5.1" (required if bundle is not Liferay,lets say creating dynamic web project)

This steps is required only if you are not using Liferay's bundle. Liferay bundle has AUI available by default.
For our example we have used "alloy-1.5.1". Lets download and copy our content to the location "{c:}\alloy-1.5.1".


2) Create JSP file to add aui's js & corresponding stylesheet

In order to use AUI components we need to import below files onto our JSP

We have created dynamic web project with the name "student". We have copied "{c:}\alloy-1.5.1\build" to the location "/student/WebContent/js/build" path.

Once its copied to the above path use below statements to include aui.js & "aui-ski-classic-all-min.css" like below:

<script src="/student/js/build/aui/aui.js" type="text/javascript"></script>
<link rel="stylesheet" href="/student/js/build/aui-skin-classic/css/aui-skin-classic-all-min.css" type="text/css" media="screen" />

3) Load "aui-autocomplete" module on JSP

Once "aui.js" is included on our JSP we need to load one of the modules from AUI.

Here is the code snippet to load "aui-autocomplete"

<script type="text/javascript">
AUI().use('aui-autocomplete',function (A) {
var studentData = [
 ['45', 'Scott', 'scott@test.com'],
 ['26', 'Micheal', 'micheal@test.com'],
 ['47', 'Peter', 'peter@test.com']      
];

new A.AutoComplete(
 {
contentBox: '#studentList',
delimChar: ',',
dataSource: studentData,
schema: {
 resultFields: ['id', 'studentName', 'studentEmail']
},
matchKey: 'studentEmail',
typeAhead: true
 }).render();
 });
</script>

We have use an example of student. In our example we have created "studentData" list with three different values i.e. "id","studentName","studentEmail".

We have created sample data with the same structure which is available in "studentData". During auto complete user may use one of these values to fetch student data.
Property, "matchKey" is the one through which we can specify which key to be used for auto complete feature.

4)  Run & Verify

By default when we load the JSP it will look something like this:



When we type "p..." it will show the matching email address starting with "P" letter. Here is the snippet for same:


When we click on the dropdown next to the textbox it shows all the record we have provided in the "studentData". Here is the snippet for the same:



Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Wednesday, 8 July 2015

How does a request Url is mapped to a specific Servlet in Java

The "<url-pattern>" element of a "<servlet-mapping>" or a "<filter-mapping>" associates a filter or servlet with a set of URLs. Which servlet should get called can be checked from the entry of web.xml file.

There are two steps to check which Url will mapped to which Servlet

1) Look for the corresponding entry of Url inside web.xml (deployment descriptor)
2) See the rules for mapping inside web.xml

Lets see how Url is being mapped to correct Servlet.

1) Look for the corresponding entry of Url inside web.xml (deployment descriptor)

Inside web.xml file there is a specific tag available called "<url-pattern>", this is the tag used to map any request to a specific "Servlet".

Here are three sample entries of three different Servlets.

<servlet>
<description></description>
<display-name>Marks</display-name>
<servlet-name>Marks</servlet-name>
<servlet-class>com.registration.Marks</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Marks</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>

<servlet>
<description></description>
<display-name>StudentData1</display-name>
<servlet-name>StudentData1</servlet-name>
<servlet-class>com.registration.StudentData1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentData1</servlet-name>
<url-pattern>/StudentData</url-pattern>
</servlet-mapping>

<servlet>
<description></description>
<display-name>StudentData</display-name>
<servlet-name>StudentData</servlet-name>
<servlet-class>com.registration.StudentData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentData</servlet-name>
<url-pattern>/StudentData/*</url-pattern>
</servlet-mapping>

<servlet>
<description></description>
<display-name>Registration</display-name>
<servlet-name>Registration</servlet-name>
<servlet-class>com.registration.Registration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registration</servlet-name>
<url-pattern>/StudentData/Registration/*</url-pattern>
</servlet-mapping>

We have three servlets called

1) Marks
2) StudentData
3) Registration

For every servlet we have declared a corresponding <servlet-mapping> entry which will relate Url -> Servlet with the help of "<url-pattern>" element of "<servlet-mapping>".


2) See the rules for mapping inside web.xml

Here are the mapping rules which container follows for mapping to any Url with a specific Servlet.

The container,

i)   gives precedence to an exact path match over to wildcard path match
ii)  prefers to match the longest pattern
iii) prefers path matches over filetype matches

3) Lets see some examples of Url -> Servlet mapping (Assuming web.xml entry mentioned in point #1)

http://student.com/student/StudentData1 matches to "StudentData1" servelt (Rule #i)
http://student.com/student/StudentData/abc matches to "StudentData" servelt (wild card match)
http://student.com/student/StudentData/Registration matches to "Registration" servlet (Rule #ii)
http://studnet.com/student/abc.jsp    matches to "StudentData" Servlet (Rule #iii)
http://student.com/studnet/StudentData/Registration/abc matches to "Registration" servelt


Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Sunday, 5 July 2015

How to post data using Ajax HTTP "POST" method in Java

Ajax is usefule when user wants to save some of the data in a database without submittin a whole form.

Lets see the steps to post / send data to server side using AJAX call.

1) Create a Servlet to iterate data coming from JSP
2) Create a JSP to call Ajax function
3) Write Ajax function to place a request to server side along with dynamic data
4) Run and Verify

We will see an example of posting institute details dynamically.

Lets see the steps in detailed:

1) Create a Servlet to iterate data coming from JSP

Our servlet's doPost method will be called when Ajax request is submitted from the "index.jsp" file. It will read two values "instituteName" and "location" which is passed from the client side / JSP.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Institute Name is : " + request.getParameter("instituteName"));
System.out.println("Location of Institute is : " + request.getParameter("location"));

PrintWriter out = response.getWriter();
out.print("Post Success");
}



2) Create a JSP to call Ajax function

Here is the code snippet of the index.jsp:

<form name="studnet" method="get" action="/ajaxtest">
<div><b>Institute Details</b> : 
<input type="button" value="Post Institutes" onclick='postInstituteNames("/ajaxtest/SubmitForm")' /></div>
<div id="institute"></div>
</form>


When user clicks on the "Post Institutes" button "postInstituteNames()" js function will be triggered.

3) Write Ajax function to place a request to server side along with dynamic data

<script type="text/javascript">
  function postInstituteNames(requestURL)
  {
      //Need to create a XMLHttpRequest object which will place a request to the server
      var xmlhttpobj;
      if (window.XMLHttpRequest){
       xmlhttpobj = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
      } else {
       xmlhttpobj = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
      }
      //1st parameter depicts HTTP method in our case its a POST
      //3rd parameter is true means its an asynchronous POST request
      xmlhttpobj.open("POST", requestURL, true);
       
      //When readyState is 4 then get the server output if any
      xmlhttpobj.onreadystatechange = function() {
          if (xmlhttpobj.readyState == 4) {
              if (xmlhttpobj.status == 200) {
                  document.getElementById("institute").innerHTML = xmlhttpobj.responseText;                 
              }
              else {
                  alert('Data Unavailable!');
              }
          }
      };
      
      xmlhttpobj.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 
 //Passing two values "instituteName" & "location" to the server side which eventually can be saved by our servlet in the database.
      xmlhttpobj.send("instituteName=ABC&location=USA");
  }
  
</script>

4) Run and Verify

In our dynamic web application our index.jsp will look like below, when user hits the URL:


Once user clicks on the "Post institutes" button Ajax request will be triggered and names of the Institutes will be posted to the server. Server response will be shown back to the JSP.



If server is down / some failure happens at that time HTTP status will not be "200" and in that case below alter will be shown to the user.



Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Saturday, 4 July 2015

How to fetch data using Ajax HTTP "GET" method in Java

Many a times user like to see dynamic data (data coming from the server) without loosing the existing data filled on the form. In Java it is possible to achieve using Ajax call.

Lets see the steps to get the data from server side using AJAX call.

1) Create a Servlet to return dynamic data
2) Create a JSP to show dynamic data
3) Write Ajax function to place a request to server side and show data on client side
4) Run and Verify

We will see an example of fetching institute details dynamically based on the user operation.

Lets see the steps in detailed:

1) Create a Servlet to return dynamic data

Our servlet's doGet method returns hard coded values of the Institute which will be shown by the browser to the end user. Instead of hard coded value you can read data from the file system / database etc. For demo purpose I have used hard coded value to keep the things simple.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("1) ABC </br> 2) XYZ </br> 3) PQR </br>");
}


2) Create a JSP to show dynamic data

Here is the code snippet of the index.jsp:

<form name="studnet" method="get" action="/student">
<div><b>Institute Details</b> : 
<input type="button" value="Get Institutes" onclick='fetchInstituteNames("/student/Register")' /></div>
<div id="institute"></div>
</form> 


When user clicks on the "Get Institutes" button "fetchInstituteNames()" js function will be triggered.

3) Write Ajax function to place a request to server side and show data on client side

<script type="text/javascript">
function fetchInstituteNames(requestURL)
{
   //Need to create a XMLHttpRequest object which will place a request to the server
   var xmlhttpobj;
   if (window.XMLHttpRequest){
    xmlhttpobj = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
   } else {
    xmlhttpobj = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
   }
   //1st parameter depicts HTTP method in our case its a GET
   //3rd parameter is true means its an asynchronous GET request
   xmlhttpobj.open("GET", requestURL, true);
    
   //When readyState is 4 then get the server output
   xmlhttpobj.onreadystatechange = function() {
       if (xmlhttpobj.readyState == 4) {
           if (xmlhttpobj.status == 200) {
               document.getElementById("institute").innerHTML = xmlhttpobj.responseText;                
           }
           else {
               alert('Data Unavailable!');
           }
       }
   };
   xmlhttp.send(null);
}

</script>

4) Run and Verify

In our dynamic web application our index.jsp will look like below, when user hits the URL:


Once user clicks on the "Get institutes" button Ajax request will be triggered and names of the Institutes will be returned from the server. Which will be shown on the JSP page via "fetchInstituteNames" js function.


Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Thursday, 2 July 2015

How to use Liferay AUI Dialog

Liferay AUI provides the inbuilt support of dialogbox. It is highly flexible and many things we can control with the help of properties of the AUI dialog.

Here is an example how to use AUI dialog.

function registerStudent() {
AUI().use('aui-dialog',
function(A) {
studentRegisterationDialog = new A.Dialog({
bodyContent : 'Please click on the Register button to proceed',
title: 'Student Registration',
buttons: [
 {
handler: function() {
 alert('You just clicked register');
 studentRegisterationDialog.close();
},
label: 'Register'
 },
 {
handler: function() {
 alert('You just clicked Register Later');
 studentRegisterationDialog.close();
},
label: 'Later'
 }
],
centered: true,
modal: false,
width: 500,
height: 400
}).render();
}
);
}

In this example once user calls the function "registerStudent()" at that time a dialog will appear with two options

1) Register
2) Later

Once user clicks on the "Register" or "Later" corresponding "handler" will be called and user's action will be registered.

Here are few more properties which you may controlled for AUI Dialog.

resizable: true/false
draggable: true/false
destroyOnClose: true/false

Here is the snapshot for our example "registerStudent"




Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

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