Showing posts with label web service. Show all posts
Showing posts with label web service. Show all posts

Wednesday, September 12, 2012

SOAP for Android

As you know Android does not support SOAP. The reason for that might be, SOAP is complicated on mobile clients. Generating code from WSDL is cumbersome and finally communicating in SOAP means more network traffic which is something to consider in hand-held devices. As a result using REST with JSON is a sensible approach. Because, its flexible in data type returns. JSON is lightweight and simple to parse. JSON is the preferred method of data interchange on hand-held devices.

Still if you have to use SOAP, here are couple of examples using ksoap2 . Ksoap2 is an API for SOAP on Android.

Example 1

This could be an example of primitive return type in ksoap2.

Lets assume we have to authenticate to a system before calling any business web methods. After authentication the system will give us valid JSESSIONID.  The target system provides a web method from which we can login then,  it will return us valid JSESSIONID. This id will be send along with any further method calls to identify us as a valid user.

You can see how to pass primitive data to a web method and parse primitive result from that.

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.util.Log;

public class LoginUtil {
    //Name of the method we want to call
    public static String METHOD_NAME = "login";
    public static String SOAP_ACTION = NAMESPACE + METHOD_NAME;
    //The name space (you can get this from WSDL)
    public static String NAMESPACE = "http://webservice.web.security.com/";

    public static String lognToThesystem(String username,String password, String host, String port) {
       SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);       
        //Setting the property to be passed to the web service method
        PropertyInfo propInfoUsername = new PropertyInfo();
        propInfoUsername.name = "arg0";
        propInfoUsername.type = PropertyInfo.STRING_CLASS;

        request.addProperty(propInfoUsername, username);
       //Setting the property to be passed to the web service method      
        PropertyInfo propInfoPassword = new PropertyInfo();
        propInfoPassword.name = "arg1";
        propInfoPassword.type = PropertyInfo.STRING_CLASS;

        request.addProperty(propInfoPassword, password);

        String url = "http://" + host + ":" + port + "/app/ws/login?wsdl";
      
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
        SoapPrimitive resultsRequestSOAP = null;
        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            //Since we know the result is of type primitive then, cast it to SoapPrimitive
            resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
        }
        return resultsRequestSOAP == null ? "" : resultsRequestSOAP.toString();
    }
}

Example 2

Now we are going to look at a more complex example. In the previous example we obtained a JSESSIONID. We want to call a method (getAllUsers) but we have to provide the JSESSIONID with this request otherwise the system wont let us call the aforementioned method. The return type of this request call is not primitive and consists of complex objects. This method returns all the users with the condition that  if any of their properties have changed between fromDate and toDate (this is just the business rule). The constructor of this class receives all the necessary data needed for this method call.

You can see how to pass Date to a web service method and parse a list of objects return from that. Also you can see how to add a header property to the request.

Return type object:

public class WebServiceEntity {
    private long id;
    private String name;
    private int type;
   
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getType() {
        return type;
    }
    public void setType(int type) {
        this.type = type;
    }
}

Caller class:

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Vector;

import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalDate;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.util.Log;

import com.vahid.dto.WebServiceEntity;

public class GeneralRecords {
    private final String NAMESPACE = "http://webservice.web.vahid.com/";
    private final String METHOD_NAME = "getAllUsers";
    private final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
    private String jsessionId;
    private String url;
    private Date fromDate;
    private Date toDate;
    private Vector<SoapObject> result = null;
  
    public GeneralRecords(String jsessionId,String host, String port, Date fromDate, Date toDate) {
        this.jsessionId = jsessionId;
        this.fromDate = fromDate;
        this.toDate = toDate;
        this.url = "http://" + host + ":" + port + "/service/vahid/general?wsdl";
    }

public List<WebServiceEntity> getAllEntiites() {
        //Create a soap object
        SoapObject soapObject = new SoapObject(NAMESPACE, MethodName);
       //Defining the fromDate property
        PropertyInfo propFromCal = new PropertyInfo();
        propFromCal.name = "arg0";
        propFromCal.type = MarshalDate.DATE_CLASS;
      
        soapObject.addProperty(propFromCal, fromDate);
        //Defining the toDate property
        PropertyInfo propToCal = new PropertyInfo();
        propToCal.name = "arg1";
        propToCal.type = MarshalDate.DATE_CLASS;

        soapObject.addProperty(propToCal, toDate);
      
         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
         envelope.setOutputSoapObject(soapObject);
//Use MaeshalDate so that the system knows how to serialize and deserialize objects you are trying to pass through the web service
         MarshalDate md = new MarshalDate();
         md.register(envelope);
     
         //Make the call to target web service
         HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
         Object response = null;
         try {
             //Create a list and assign all the necessary header properties. In our case we only need JSESSIONID
             List headers = new ArrayList();
             HeaderProperty jsessionIdProperty = new HeaderProperty("Cookie", "JSESSIONID="     +            jsessionId);
             headers.add(jsessionIdProperty);
             androidHttpTransport.call(SOAP_ACTION, envelope, headers);
             response = envelope.getResponse();
         } catch (Exception e) {
             Log.e("Error", e.getMessage());
         }

         if (response instanceof SoapObject) {
             result = new Vector();
             result.add((SoapObject) response);
         } else if (response instanceof Vector) {
             result = (Vector<SoapObject>) response;
         }
         //Retrieve object from soap
         List<WebServiceEntity> webServiceEntity = new ArrayList<WebServiceEntity>();
         for (SoapObject soap : result) {
             WebServiceEntity wse = new WebServiceEntity();
             wse.setId(Long.parseLong(soap.getProperty(0).toString()));
             wse.setName(soap.getProperty(1).toString());
             wse.setType(Integer.parseInt(soap.getProperty(2).toString()));
             webServiceEntity.add(wse);
         }
         return webServiceEntity;
    }
}

Tuesday, July 3, 2012

A complication with embedding Axis2 in a webapp

There was a need to develop a web service in our web project in order to make it interoperable with other system specially written in languages other than Java. We had number of options to choose from such as Metro which is part of GlashFish Community and Axis2 which is from The Apache Software Foundation.
We carried out a memory test. We developed a class with a method returning a byte[10000000] worth of data. Then exposing them with both Metro and Axis2. Our web service clients called the services in a loop of 100 with Thread.Sleep(1000) in between of each call. With the aid of VisualVM which offers JVM profiling and monitoring we monitored the memory usage and garbage collection. Both services were used just out of the box (without any additional configuration and tuning). They were almost the same in terms of memory usage. Annotation is the beauty of Metro. If you have your class then your are 2 steps from making your class act as a service. First annotate the class with @WebService and second annotate a method with @WebMethod. That's All. Isn't it easy!
 Here is a simple guide Building a simple Metro application you can give it a try.

With regard to ease of use, Axis2 was a bit problematic. I'm going to explain more on the problem and the approach I took to solve it.

The problem:

When my class was ready, I added axis2 Servlet to web.xml. Then,  exposing the class by adding service.xml to the folder hierarchy under WEB-INF as:
WEB-INF
     |---->services
       |---->myApp
         |---->META-INF
           |---->service.xml

 service.xml defines the the description of the service. At the final step, I tried to add all the necessary jar files to the classpath of the server. Everything seemed ok but the service was not deployed. There was no error in the logs. I checked my service by trying to checkout the WSDL on the browser. The response was an error indicating "No service is available at this URL" or "The service cannot be found for the endpoint reference (EPR) " without any further clue or any other exceptions on the server.

The solution:

 axis2-web is a "collection of JSPs that make up the Axis2 administration application "

I tried to list my service by using axis2-web at the address below by deploying the application in my Servlet engine.

http://address:port/context/services/listServices

After calling the address above I found out there is a missing class causing malfunction. Although nothing was in the log files indicating ClassNotFoundException