Monday, September 24, 2012

Creating basic webservice example

Basic webservice example the manual way using axis2 and testing using SOAP UI

Apache Axis2 is a Web Service engine for deploying the web services, you can find more information about it at its official http://axis.apache.org/axis2/java/core/.
Pre-requisites:

Now unzip and copy axis2.war into Tomcat's webapps directory, start the Tomcat server and navigate to http://localhost:8080/axis2, you should see the below welcome page




For accessing the Administration page you need the credentials admin/axis2 for doing all the necessary administrative activities.
When we click on services link you can see one Version service which dislpays the version which comes by default in the axis2 war bundle.
There are two types of approaches while developing web services, they are:
a) Code first (also called as bottom-up approach): In this approach we will start programming the classes and business logic as java code and then generate the web service contract(wsdl)
b) Contract first (also called as top-bottom approach): In this approach we will start generating class stubs from the WSDL.
We will go with the code first approach which is the most preferred way so let us quickly get into the example
1) Create a project with package and META-INF folders within it as shown below
2) Write the service class first through which we are going to service, let us write a program which validates whether the given number is a palindrome or not PalindromeService.java.
package com.palin;
public class PalindromeService {
  public String isPalindrome(int number) {
    String palin=null;
    try {
      int tempNumber = number;
      int reverse = 0;
      for (int i = 0; i <= number; i++) {
        int temp = number % 10;
        number = number / 10;
        reverse = reverse * 10 + temp;
        i = 0;
      }
      if (tempNumber == reverse) {
        palin="Palindrome";
      } else {
        palin="Not Palindrome!";
      }
    } catch (Exception e) {
      palin="Invalid number!";
    }
    return palin;
  }
}
Create the service descriptor i.e, services.xml (and place in location:WEB-INF)
<service name="PalinServ">
<transports>
    <transport>http</transport>
</transports>
<parameter name="ServiceClass" locked="xsd:false">com.palin.PalindromeService</parameter>
<operation name="isPalindrome">
    <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
</service>
The <service> tag is used to define the services, we can even declare the scope for it. We can have multiple services in single services.xml file.
The <transport> tag is used to declare which senders/listeners for SOAP over different protocols like FTP, SMTP, HTTPS, HTTP etc. Here I have used just http. If we are not going to declare any transport, then all the transports that are available in the default axis2.xml file are accepted by default. These can be found in the %TOMCAT_HOME%\webapps\axis2\WEB-INF\conf\axis2.xml with <transportSender> tag.

The <parameter> tag is used to define our service class along with the package name.

The <operation> tag is used to define our method which we are going to expose. All the methods which we wish to publish or do the service are treated as operations in the service descriptor, here isPalindrome is our operation.
RPCMessageReceiver is the messageReceiver which is the most commonly used one for receiving messages.
3) Now we are going to compile the class, create an axis archive file (.aar) as shown below
4) Now copy the PalinServ.aar into webapps/axis2/WEB-INF/services directory and restart your Tomcat and check this url http://localhost:8080/axis2/services/listServices we should be able to see our service along with the default Version service as shown below.
We can see our service name under Service Description section and our method under Available Operations section as shown above.
We can see the .wsdl file url under the Service EPR (endpoint) section but we need to append ?wsdl to its end like http://localhost:8080/axis2/services/PalinServ?wsdl
As the previous version should not get effected, it supports all its previous ones SOAP 1.1, SOAP 1.2 that is the reason why you will be seeing more than one endpoints.

Now, for testing whether you webservice is working or not, see this post http://helptodeveloper.blogspot.com/2012/09/testing-webservice-or-wsdl-with-soap-ui.html.

If you don't have any tools for testing your webservice; you can do manually, look in this post http://helptodeveloper.blogspot.com/2012/09/testing-webservices-manually-with-raw.html on how to test.

Tuesday, December 20, 2011

Jasper report printing at client side,Java,Struts,jasper reports, print at client side,Ajax


Hi friends,

I have developed one project which is customised Jasper Reports with export and print options.
I haven't get any problem for export options.
Coming to Print, i found that it is printing at server end.
So to eliminate that problem i found one solution that will be printing at client side.

For this solution i have used Jasper Report object and Ajax functionality.
The code is like this:
1) In my JSP




<input type="button" class="button_submit" value="print" onclick="javascript:print();">


Handler: For a "Print" Button you need to add onclick listener function print();


function print()

{
/* ========== AJAX Initializtion ========== */
xmlhttp = false;
if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
/* ========== AJAX Initializtion ========== */

if (xmlhttp!=null) {
url = "/mms/reports";
xmlhttp.onreadystatechange= function () { getWorkReqDivs(xmlhttp); };
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Cache-Control","no-cache, private, max-age=0");
xmlhttp.send(null);

} else {
alert("Your browser does not support XMLHTTP.");
}
}
function getWorkReqDivs(httpRequest1)
{
if(httpRequest1.readyState==4)
{
if(httpRequest1.status==200)
{
var result = httpRequest1.responseText;
var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
var content_vlue=result;
var docprint= window.open("", "", disp_setting);
docprint.document.open();
docprint.document.write(&lthtml>);
docprint.document.write(<body onLoad="self.print()">&lt

/body>

&lt
/html>);

docprint.document.write(content_vlue);

docprint.document.close();
docprint.focus();

}
}
}

This script is used to get the Jasper Report in HTML format as responseText. So this text is added in window.open().It looks like print preview.In onload itself print dialog box will come to ask print.


Struts-config.xml



<action path="/mms/reports" type="com.km.bp.mms.jsperReports.printAction"> 
<forward name="print" path="/WEB-INF/jsp/jasperReports/print.jsp"/>
</action>


Java Class: (printAction.java)


JRHtmlExporter exporter = new JRHtmlExporter();

String jrept = "indentReport.jrxml";

String reportFileName = JasperCompileManager.compileReportToFile(request.getRealPath("/reports") + "/" + jrept);


java.util.Map parameters = new java.util.HashMap();

Connection con = MMSDB.getConnection();String fromDatet="01/01/2010";String toDate="28/02/2010";

parameters.put("fromDate", fromDatet);parameters.put("toDate", toDate);

File reportFile = new File(reportFileName);if (!reportFile.exists()) {throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first.");
}

JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con);

PrintWriter out = response.getWriter();response.setContentType("text/html");

exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

exporter.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER, out);

HashMap fontMap = new HashMap();

exporter.setParameter(JRHtmlExporterParameter.FONT_MAP, fontMap);

exporter.setParameter(JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);

exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);

exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);

exporter.setParameter(JRHtmlExporterParameter.IS_WRAP_BREAK_WORD, Boolean.TRUE);

request.setAttribute("exportIndentObject", exporter);

return mapping.findForward("print");}

}


  



Jsp File :(print.jsp)( The following Jsp is the responseText of the Ajax Call)


<%@page import="net.sf.jasperreports.engine.export.JRHtmlExporter" %>

< % JRHtmlExporter export = (JRHtmlExporter) request.getAttribute("exportIndentObject"); session.setAttribute("exportIndentObject", export); JRHtmlExporter export1 = (JRHtmlExporter) session.getAttribute("exportIndentObject"); export.exportReport(); %>








Tuesday, January 25, 2011

Calling Procedures from Java

Google Map with multiple Markers used to locate different locations .
We can show a map with image and contact details like following




Tuesday, November 9, 2010

Comparing collection objects

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

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

/**
 *
 * @author sowjanya.g
 */
public class compare {

    public static void main(String args[]){

        employee e = null;
        List al=new ArrayList();
        e=new employee("sowji","sowji@gmail.com",24);
        al.add(e);
        e=new employee("sowji1","sowji1@gmail.com",30);
        al.add(e);
        boolean checkFlag = false;
        for(employee emp: al){
            if(emp.getMailId().equals("sowji1@gmail.com")){
                checkFlag = true;
                break;
            }
        }
        System.out.println("Check Flag:=="+checkFlag);
        if(!checkFlag){           
            e=new employee("sowji2","sowji1@gmail.com",40);
            al.add(e);
        }
       
        for(employee emp: al){
            System.out.println("email Id:=="+emp.getMailId());
        }


    }

}
class employee
{
    String name;
    String mailId;
    int age;

    public employee(String name,String mail,int age)
    {
        this.name=name;
        this.mailId=mail;
        this.age=age;
    }
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getMailId() {
        return mailId;
    }

    public void setMailId(String mailId) {
        this.mailId = mailId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Java Code for sorting objects in collection classes using Comparator

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

/**
 *
 * @author sowjanya.g
 */


import java.util.Arrays;
import java.util.Comparator;

    /*

    Java Comparator example.
    This Java Comparator example describes how java.util.Comparator
    interface is implemented to compare Java user defined classe's objects.
    These Java Comparator is passed to Collection's sorting
    method ( for example Collections.sort method)to perform sorting of Java user defined classe's objects.

    */


    /*

    java.util.Comparator interface declares two methods,
    1) public int compare(Object object1, Object object2) and
    2) boolean equals(Object object)

    */

    /*
    We will compare objects of the Person class using custom comparators
    on the basis of person age and name.
    */

class Person{
    private int age;
    private String name;
    public void setAge(int age){
        this.age=age;
    }

    public int getAge(){
        return this.age;
    }

    public void setName(String name){
        this.name=name;
    }

    public String getName(){
        return this.name;
    }
}

/*

User defined java comaprator.
To create custom java comparator Implement Comparator interface and
define compare method.
The below given comparator compares persons on the basis of their age.

*/

class AgeComparator implements Comparator{

    public int compare(Object emp1, Object emp2){
        //parameter are of type Object, so we have to downcast it to Person objects
        int emp1Age = ( (Person) emp1).getAge();
        int emp2Age = ( (Person) emp2).getAge();
        if( emp1Age > emp2Age ){
            return 1;
        }
        else if( emp1Age < emp2Age ){
            return -1;
        }
        else{
            return 0;
        }
    }

}

/* The below given comparator compares persons on the basis of their name. */

class NameComparator implements Comparator{

    public int compare(Object emp1, Object emp2){
        //parameter are of type Object, so we have to downcast it to Person objects
        String emp1Name = ( (Person) emp1 ).getName();
        String emp2Name = ( (Person) emp2 ).getName();
        //uses compareTo method of String class to compare names of the person
        return emp1Name.compareTo(emp2Name);
    }

}

/*

This Java comparator example compares persons on the basis of

their age and name and sort it in that order.

*/

public class JavaComparatorExample{

    public static void main(String args[]){

        /*    Person array which will hold persons */

        Person person[] = new Person[2];
        //set different attributes of the individual person.
        person[0] = new Person();
        person[0].setAge(40);
        person[0].setName("Joe");

        person[1] = new Person();
        person[1].setAge(20);
        person[1].setName("Mark");

        System.out.println("Order of person before sorting is");
        //print array as is.
        for(int i=0; i < person.length; i++){
            System.out.println( "Person " + (i+1) + " name :: " +
                    "" + person[i].getName() + ", Age :: " + person[i].getAge());
        }

        /*

        Sort method of the Arrays class sorts the given array.
        Signature of the sort method is,
        static void sort(Object[] object, Comparator comparator)
        IMPORTANT: All methods defined by Arrays class are static. Arrays class
        serve as a utility class.

        */

        /*    Sorting array on the basis of person age by passing AgeComparator    */

        Arrays.sort(person, new AgeComparator());
        System.out.println("\n\nOrder of person after sorting by person age is");
        for(int i=0; i < person.length; i++){
            System.out.println( "Person " + (i+1) + " name :: " +
                    "" + person[i].getName() + ", Age :: " + person[i].getAge());
        }

        /*    Sorting array on the basis of person Name by passing NameComparator */

        Arrays.sort(person, new NameComparator());
        System.out.println("\n\nOrder of person after sorting by person name is");
        for(int i=0; i < person.length; i++){
            System.out.println( "Person " + (i+1) + " name :: " +
                    "" + person[i].getName() + ", Age :: " + person[i].getAge());
        }
    }

}

Java Code for sorting objects in collection classes using Comparable interface

package javaapplication1;

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

/**
*
* @author sowjanya.g
*/
public class Main {

public static void main(String[] args) {
ArrayList al=new ArrayList();

person p1=new person("sowjanya","sowji1.gutla@gmail.com","24");
person p2=new person("lavanya","ll.gutla@gmail.com","24");
person p3=new person("chaithu","chaithu1.gutla@gmail.com","24");
person p4=new person("avinash","zzzzi.moram@gmail.com","24");

al.add(p1);
al.add(p4);
al.add(p3);
al.add(p2);

System.out.println("al---before--"+al);

Collections.sort(al);

System.out.println("al----after---"+al);
}
}


class person implements Comparable
{
String name;
String mailId;
String age;

public int compareTo(Object o)
{
person per=(person)o;
return mailId.compareTo(per.getMailId());
}


person(String name1,String mail,String age1)
{
name=name1;
mailId=mail;
age=age1;
}
// method used to know the o/p as strings instead objects
@Override
public String toString()
{
return "Name: "+name+"---mailId--"+mailId+"---age--"+age;
}



public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getMailId() {
return mailId;
}
public void setMailId(String mailId) {
this.mailId = mailId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

Wednesday, October 6, 2010

Google Map with multiple markers

Google Map with multiple Markers used to locate different locations .
We can show a map with image and contact details like following


Example for Placing multiple markers with image on a Google Map

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
 <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" type="text/javascript"></script>
 <style type="text/css">
#map{
  height: 150%;
  width: 100%;
    }
 </style>

<script type="text/javascript">

    var map;
    var geocoder;
       var xml;
       var markers;
       var mapopt;
       var address;
    var    markeraddress;
    var k=0;
   
     // On page load, call this function
   function load()
   {
     // Create new map object
      map = new GMap2(document.getElementById("map")); 
      map.addControl(new GMapTypeControl());
      map.setMapType(G_SATELLITE_MAP);
      map.addControl(new GLargeMapControl3D());
      // Create new geocoding object
      geocoder = new GClientGeocoder();
      var latlonarr=new Array();
      var arselected = new Array(); 
      var length1=0;
      var loopcount=0;
      var sw=0;
     
        arselected[0]="Bhoopalpally Phase -II,Hanamkonda,Warangal";
        arselected[1]="Gopalan arcade.4th flore,1st Main,Kasturi Nagar,Bangalore,KA";
        arselected[2]="Sri Mobiles,No 2,24th Main,JP Nagar 1st Phase,Bangalore,KA";
        arselected[3]="#33,RK  Mutt Road,Ulsoor,Bangalore 560008,KA";
        arselected[4]="Minnu Tour & Travels No 74,Nagavarapalya,CV Raman Nagar,Bangalore,KA";
        arselected[5]="Fazal Technologies,No 89,Fazal Manor,Richmond Road,Bangalore,KA";
        arselected[6]="Neon Electronics,No 335/,Gokul Complex,Sampige Road,Malleshwaram,Bangalore,KA";
        arselected[7]="Canadian International School Survey No.420,Yelahanka,Bangalore,KA";
        arselected[8]="485,6th 'D' Cross,Koramangala 6th Block,Bangalore,KA";
        arselected[9]="Salarpuria Infinity, 3rd Floor #5,Bannerghatta Road ,Bangalore-560029,KA";
        arselected[10]="BMTC,central offices,K.H.Road,Shanthi nagar,Bangalore-560027";
        arselected[11]="57-A, 21st K M, Hosur Road, Bommasandra Industrial Area,Bangalore,KA";
        arselected[12]="63/8.Maruthi Layout,Near Rajaram Factory,2nd Phase,Peenya Industrial Area,Bangalore,KA";
        arselected[13]="Plot 1&2, KIADB Industrial area, Attibele,Bangalore,KA";
        arselected[14]="Apt 203, Scion Enclave, Govindappa Lane, Off 80 ft rd,Indira nagar,Bangalore,KA";
        
          var address=new Array();
        var exact_address=new Array();
          var exact=new Array();
        var j;
        var count=0;
        var marker=new Array();
        var exact_add=new Array();
        var xmlfl="<markers>";
        var s=0;
        var km=0;
        var url="'http://www.google.com','google','width=400,height=400'";
         for (var i = 0; i < arselected.length; i++)
          {
            address[i]= arselected[i];
            var len=address[i].split(',').length;
            exact=address[i].split(',');
            for(var k=0;k<3;k++)
            {
               exact_add[k]=exact[parseInt(len)-(parseInt(k)+1)];
            }
           
            exact_add.reverse();
            exact_address[i]=exact_add;
            s=i+1;
                xmlfl+="<marker address=\""+exact_address[i]+"\">";
                xmlfl+="<AlphaCharacter>"+s+"</AlphaCharacter></marker>";
              }
            xmlfl+="</markers>";
            document.getElementById("sample").innerHTML="";
            document.getElementById("sample").innerHTML=xmlfl;
            markers =document.getElementById("sample").getElementsByTagName("marker");
            for (var i = 0; i < exact_address.length; i++)
            { 
                    markeraddress = markers[i].getAttribute("address");
                  geocoder.getLocations(markeraddress,addToMap);
                 document.getElementById("loop").value=i;           
            }
               
         function addToMap(response)
                       {
                            
                              place = response.Placemark[0];
                             point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
                             latlonarr[km]=point;
                             km++;
                            sendpoint(point);                                     
                   }
                function sendpoint(point)
                {
                             var numberedIcon = new GIcon(G_DEFAULT_ICON)
                            var ar=address[loopcount];
                            map.setCenter(point, 13);
                             numberedIcon.image = "http://www.geocodezip.com/mapIcons/marker.png"
                            var k=document.getElementById("loop").value;
                             markerOptions = { icon:numberedIcon, clickable:true,title:ar,position:loopcount}
                             mapopt= { icon:numberedIcon, clickable:true,title:ar,position:loopcount};
                             marker= new GMarker(point,mapopt);
                            map.addOverlay(marker);
                            loopcount++;   
                }
                GEvent.addListener(map,"click",function(marker,markerOptions,ar)
                                           { 
                                                   var html="";
                                                   var ra="";
                                                   var sowji=0;
                                                for(var siri=0;siri<15;siri++)
                                                {
                                                   if(latlonarr[siri]==ar)
                                                   {
                                                      sowji=siri;
                                                      ra=address[siri-1];
                                                    } 
                                                }
                                               
                                                 html=ra+"<br><img src=\"im/css.jpg\"  height=\"160px\" width=\"240px\"/>For More Information <a href=javascript:popupwin("+url+")><b>click<b></a>";
                                                marker.openInfoWindowHtml(html,{maxWidth:200},markerOptions);
                                            });
              }
             
    function popupwin(url)
    {
        newwindow=window.open(url);
        if (window.focus) {newwindow.focus();}
    }
    </script>

  </head>
 <body onLoad="load()">

<input type="hidden" name="loop" id="loop">
<div id="map"></div>

<div id="sample" style="display=none"></div>

<div id=addr123 style="display:block">
1.Kalyan Meher Kotay, 15/15,25th Cross,JayaNagar 6th Main Rd,BANGALORE,KA;<br>
2.Gopalan arcade.4th flore,1st Main,Kasturi Nagar,Bangalore,KA;<br>

                     
</div>

</body>
</html>