Friday, 19 June 2015

Consume web service Liferay

Hi
This post is the result of completion of my assignment.
My requirement was to consume web service and display cities as country provided by user.

I am using 
Liferay 6.2 CE
Tomcat 7
java      1.7.0_71
liferay-portal-6.2.0-ce-ga1
liferay-plugins-sdk-6.2.0

This is a simple portlet in which I am consuming web service provided by some third party.

URL: http://www.webservicex.net/globalweather.asmx?WSDL 

First I created simple plug in project, suppose name of the project is "webservice".
To use web service we have to follow the steps described by LiferayCookBook,
chapter 8,
section 8.1.2, page number 143.
Very good book for Liferay developer, written by
You can download this book from here 
 
** Right click on the project  "webservice" then 
new -> others -> web services -> web services client -> next.
Give URL(webservice URL) Service definition field and then finish.

Create action class and put its entry in <portlet-class> tag in portlet.xml then start coding.


first my view.js 
 
<%@ page import="com.liferay.portal.kernel.util.Validator" %>
<%@ page import="java.util.List" %>

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

<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">

<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
 
<portlet:defineObjects />

<portlet:actionURL var="webServiceConsumeURL" name="webServiceCountry" />

<aui:form name="fm" method="POST" action="<%= webServiceConsumeURL %>">
       <aui:input name="country" label="Country Name: " inlineLabel="true" />
    <aui:button type="submit" value="press" onclick="return validateCountryName();"/>
</aui:form>


<%
    List<String> cities = (List<String>)renderRequest.getAttribute("cities");
    if(Validator.isNotNull(cities) && !cities.isEmpty()){
        %>
            <table id="example">
                <thead>
                  <tr><th>Cities Name</th></tr>
                </thead>
                <tbody>
                    <%
                        for(String city : cities){
                            %>
                                  <tr><td><%= city %></td></tr>
                              <%
                        }
                      %>
                </tbody>
            </table>
        <%
    }
    else if(Validator.isNotNull(cities) && cities.isEmpty()){            //if country name is not found then display that no data
        out.println("Results not found");
    }
%>

<script>

    $(function(){
        $("#example").dataTable();        //data table to dislay cities name if result is there
    })
 
    function validateCountryName(){
        var countryName = $.trim($('#<portlet:namespace />country').val());            //avoid country name space only
        var countryNameLength =  countryName.length;
        if(parseInt(countryNameLength)>0)
            return true;
        else{
            alert("Please enter country name")                    //do not allow to leave country name as empty
            return false;
        }
    }
 
    $('#<portlet:namespace />country').bind('keyup blur',function(){
        var node = $(this);
        node.val(node.val().replace(/[^a-zA-Z\s]/g,'') );    //only character and space allowed as country name
    });
 
</script>
 
I created action URL and then user will enter country name, I provided some validation using jQuery to validate country name.


Now my action class

package com.web.service.consume;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.rpc.ServiceException;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import NET.webserviceX.www.GlobalWeather;
import NET.webserviceX.www.GlobalWeatherLocator;
import NET.webserviceX.www.GlobalWeatherSoap;

import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

public class WebServiceConsume extends MVCPortlet {
   
    public void webServiceCountry(ActionRequest actionRequest, ActionResponse actionResponse)
    throws IOException, PortletException {
       
        String countryName = ParamUtil.getString(actionRequest, "country").trim();            //removing leading and trailing spaces
        GlobalWeather locator = new GlobalWeatherLocator();                                    //creating object of GlobalWeatherLocator
        GlobalWeatherSoap gwSoap = null;
        try {
            gwSoap = locator.getGlobalWeatherSoap();                                        //getting soap object
        }
        catch (ServiceException e) {
            e.printStackTrace();
        }
        String xml = gwSoap.getCitiesByCountry(countryName);                                //getting cities using country name
        DocumentBuilder builder = null;
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        }
        catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(xml));                    //as value is in tag format but as string
        Document doc = null;
        try {
            doc = builder.parse(src);                                    //parsing value
        }
        catch (SAXException e) {
            e.printStackTrace();
        }
        List<String> cities = new ArrayList<String>();
       
        for(int i=0; i<doc.getElementsByTagName("City").getLength() ; i++){
            String city = doc.getElementsByTagName("City").item(i).getTextContent();                //retrieving values as city and country
            String country = doc.getElementsByTagName("Country").item(i).getTextContent();
            if(countryName.equalsIgnoreCase(country)){
                cities.add(city);
            }
        }
        actionRequest.setAttribute("cities", cities);                    //cities list added to attributes so we can get that in our view.jsp
    }

}
These classes generated automatically if you use web service link as I described above **
Thanks

No comments:

Post a Comment