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

Tuesday 9 June 2015

Popup liferay

Hi
In this post I created a simple MVC portlet in which I will render a jsp in my popup. When this popup submitted then it hits action class and then return to first jsp and popup will disappear.

portlet.xml
    <portlet>
        <portlet-name>pop-up-jsp</portlet-name>
        <display-name>Pop Up Jsp</display-name>
        <portlet-class>com.pop.up.PopUpJSP</portlet-class>
        <init-param>
            <name>view-template</name>
            <value>/html/popupjsp/view.jsp</value>
        </init-param>

        <expiration-cache>0</expiration-cache>
        <supports>
            <mime-type>text/html</mime-type>
            <portlet-mode>view</portlet-mode>
        </supports>
        <portlet-info>
            <title>Pop Up Jsp</title>
            <short-title>Pop Up Jsp</short-title>
            <keywords></keywords>
        </portlet-info>
        <security-role-ref>
            <role-name>administrator</role-name>
        </security-role-ref>
        <security-role-ref>
            <role-name>guest</role-name>
        </security-role-ref>
        <security-role-ref>
            <role-name>power-user</role-name>
        </security-role-ref>
        <security-role-ref>
            <role-name>user</role-name>
        </security-role-ref>
    </portlet>

My jsp pages folder as mentioned in portlet.xml file
<init-param>
            <name>view-template</name>
            <value>/html/popupjsp/view.jsp</value>
</init-param>


view.jsp

<%@ page import="com.liferay.portal.kernel.util.ParamUtil"%>
<%@ page import="javax.portlet.PortletURL"%>
<%@ page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="theme" %>

<portlet:defineObjects />
<theme:defineObjects />
<h1>Popup portlet</h1>
<%
    PortletURL popupURL = renderResponse.createRenderURL();
    popupURL.setWindowState(LiferayWindowState.POP_UP);
    popupURL.setParameter("paramOne","valOne");
    popupURL.setParameter("paramTwo","valTwo");
    popupURL.setParameter("redirectURL",themeDisplay.getURLCurrent());
    popupURL.setParameter("jspPage", "/html/popupjsp/popup.jsp");
    String popUpFunction = "javascript:openPopup('"+popupURL.toString()+"');";
%>
<a href="<%= popUpFunction %>">Press here To see popup</a>

<script>
function openPopup(){
      var URL = '<%=popupURL%>';
       AUI().use('liferay-util-window', 'aui-io-deprecated', function(A) {
        modal=Liferay.Util.openWindow({
        dialog: {
        id:'discountpage',
        centered: true,
        modal: true,
        width: 550,
        height: 650,
        },
        uri: URL
        });
       
       });
      }                                        
</script>
Here I am creating a render url and setting some parameters that I can access in my popup jsp page.
I created one java script function which is called by href tag and this javascript function is calling render url and hence popup would appear.

popup.jsp
<%@page import="javax.portlet.ActionRequest"%>
<%@ page import="javax.portlet.PortletURL"%>

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

<portlet:defineObjects />

<%
    String paramOne = renderRequest.getParameter("paramOne");
    String paramTwo = renderRequest.getParameter("paramTwo");
    String redirectURL = renderRequest.getParameter("redirectURL");
    out.println("paramone: "+paramOne);
    out.println("paramtwo: "+paramTwo);
    PortletURL actionMethodURL = renderResponse.createActionURL();
    actionMethodURL.setParameter(ActionRequest.ACTION_NAME, "redirectToViewJsp");
%>

<aui:form method="POST" action="<%= actionMethodURL.toString() %>" target="_parent">
    <aui:input name="redirectURL" type="hidden" value="<%=redirectURL %>" />
    <aui:input name="myName" type="text" />   
    <aui:button type="submit" value="Save" />
</aui:form>

Here I created one aui form and I set one hidden variable to send the value of redirectURL which we are getting from view.jsp page as this I will set in action class as sendRedirect method to send it to finally to view.jsp page.

Finally my action class

package com.pop.up;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;

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

/**
 * Portlet implementation class PopUpJSP
 */
public class PopUpJSP extends MVCPortlet {

    public void redirectToViewJsp(ActionRequest actionRequest, ActionResponse actionResponse)
    throws IOException, PortletException {
        String redirectURL = ParamUtil.getString(actionRequest, "redirectURL");
        String myName = ParamUtil.getString(actionRequest, "myName");
        actionResponse.sendRedirect(redirectURL);
        System.out.println("redirectToViewJsp action class param value: : "+myName);
       
    }
}

In action class I am fetching two variables and then one I simply used to print purpose and other one to redirect to a desire jsp
Thanks

Saturday 6 June 2015

pyramid in C

This is first time I am writing a post in C language.
This pyramid code is very succinct and I also tried to explain it.

#include<stdio.h>
#include<conio.h>
int main()
{
    int n, i, j, k;
    printf("Please enter the value of n : ");
    scanf("%d",&n);
    for(i=-n ; i<=n ; i++){


        k = i;
        if(k<0){
            k = -k;
        }


        for( j=0 ; j<=n ; j++){
            if(j>k)
                printf(" *");
            else
                printf(" ");
        }


    printf("\n");
    }


return 0;
}

It will prints pyramid shape made up of star(*);
Explanation
Here I am taking input an integer value from user and storing it into variable n.
The number of rows is calculated as 2*n + 1.
If the input is n=3 then total number of rows are 7
         *
        * *
       * * *
      * * * *
       * * *
        * *
         *
Similarly if input value is 6 then number of rows are 13.
Here I started a loop
for(i=-n ; i<=n ; i++)
then you can observe as n=3
then loop start from -3 and rotate upto +3.
then -3 to +3 is 7 times rotation.
Then I am storing value of i variable into another variable namely k and each time checking that if value of k is negative then
I simply made it positive.
if(k<0){
            k = -k;
}


Again a loop always rotate from 0 to n times means in this case it is 4 times each.
for( j=0 ; j<=n ; j++)
And each time checking the value of j is greater than k or not. if true then print " *". Here I added single space before * else pattern will not in proper format and if j is less than k then print only space.
If you observe that first time for n=3, value of k=-3 and we made it k=3(plus 3) and it enters inner loop where value of j start with 0 always and reach upto 3 and loop terminate. for first time if(j>k) condition fails and will executes else part hence one space.
Till false condition else executes will prints space. So first it prints only single star. In second time value of k=-2 hence(k=-k)  it becomes k=2 then this time two times * will print after two times of space.

As value of i increases from -3 to +3 value of k first increase and then decrease because of checking condition less than zero and then make it positive. First more number of spaces and gradually number of space decrease and then increase.
Feel free to ask questions, I will try to post more programs and more interview and basic question as generally ask in interview but we don't know and these all are easy.
Hope this post helpful.
Thanks
md asif aftab
Liferay developer
TranIT mPower Labs Pvt ltd.

Tuesday 2 June 2015

Dynamically loading only div of jsp

Hi
Today in this post I will describe how to load a div only of a jsp page.
In one of my project I have to display a table with out reloading page, so simple idea is to use Ajax call and fetch data from action class and display here.
I wrote Ajax method and hits serveResource method and then fetching user data from user table by passing some value from jsp to action class. In serveResource method I fetched data from user_ table and created one Json array and the returned to jsp page.
Up to here each and every thing is good but complexity arises when I want to set values from success part of Ajax call to my table. For each data I have to create tr and td and then add data inside it.
I can do this but my mam said that don't use this just go to serveResource method and then add data to session and then fetch that data to a div which is already present inside your jsp and just reload that div only. By following describe by mam is help me to avoid to create any Json array and then setting tr and td from my JavaScript function.
Now the time for code.
jsp page
<portlet:resourceURL var="usersToDisplayURL">
    <portlet:param name="<%= Constants.CMD %>" value="fetchingUsersDisplay" />
</portlet:resourceURL>


1. User userLists = (User)portletSession.getAttribute("usersValueFromActionClass");
2.  portletSession.removeAttribute("usersValueFromActionClass");
3. <a onclick="usersFunc(<%= userLists.getUserId() %>)">Press Here</a>
4. <div id="outerDiv" style="display:none">
    <div id="innerDiv"  style="display:none">
        <table id="<portlet:namespace />Table1">
            <thead>
                <tr>
                    <th>User€™s name</th>
                    <th>email</th>
                    <th>user create date</th>
                    <th>Age</th>
                    <th>Job title</th>

                </tr>
            </thead>
            <tbody>
                <%    
                      List<User> users = (List<User>)portletSession.getAttribute("activeListUser");
                      if(Validator.isNotNull(users)){
                          for(int k=0;k<users.size();k++){
                              User usr = (User)users.get(k);
                                  %>
                                  <tr>
                                    <td><%= k+1 %></td>
                                    <td><%= usr.getFullName() %></td>
                                    <td><%= usr.getEmailAddress() %></td>
                                    <td><%= usr.getCreateDate() %></td>                             
                                    <td><%= gender %></td>  
                                    <td><%= usr.getJobTitle() %></td>
                                  </tr>
                              <%
                          }
                      }
                  %>
            </tbody>
        </table>
    </div>
</div>


<aui:script>
function displayDatatable() {
        var table = $('#userListTable').dataTable({
            "bLengthChange": true,
            "iDisplayLength": 10,
            "bFilter":          false,
            "pagingType": "simple",
           
        });
    }


function usersFunc(num){      
         AUI().use('aui-base','aui-io-request-deprecated', function(A){
                A.io.request('<%= usersToDisplayURL %>',{
                                dataType: 'json',
                                method: 'GET',
                                data: { usersId: num },
                                on: {
                                         success: function() {
                                             $("#outerDiv").show();
                                             jQuery("#outerDiv").load(location.href+" #innerDiv", function(){
                                                    displayDatatable();
                                                $("#innerDiv").show();
                                                });
                                         },
                                         error: function(data){
                                               console.log("error");
                                           }
                                    }
                     });
              });   
     }

</aui:script>

my java class

@SuppressWarnings("unchecked")
    public void fetchingUsersDisplay(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
    throws PortalException, SystemException{
        HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(resourceRequest);
        String usersIndex = PortalUtil.getOriginalServletRequest(httpReq).getParameter("usersId");
        PortletSession portletSession = resourceRequest.getPortletSession();
        List<User> users = (List<User>)portletSession.getAttribute("usersListVal"+usersIndex);
        portletSession.setAttribute("activeListUser", users);
       
    }


My requirement was to display total users on different conditions and in different different ways. I am setting this values by using session on different variables. Here I don't want to mention all these conditions. So getting userid from first list is just to make my code considerable and succinct.
I am setting in session and then reload only div which is already there but hidden.

Thanks