Thursday, October 6, 2011

Apache CXF – Web Service With Jboss 5.1 - Android Client


Apche CXF is an open source service frame work. CXF helps you build and develop services using frontend programming APIs, like JAX-WS and JAX-RS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI.
• Web Services Standards Support: CXF supports a variety of web service standards including SOAP, the WS-I Basic Profile, WSDL, WS-Addressing, WS-Policy, WS-ReliableMessaging, WS-Security, WS-SecurityPolicy, WS-SecureConverstation, and WS-Trust (partial).
• CXF implements the JAX-WS APIs (TCK compliant). CXF JAX-WS support includes some extensions to the standard that make it significantly easier to use, compared to the reference implementation: It will automatically generate code for request and response bean classes, and does not require a WSDL for simple cases.
It also includes a “simple frontend” which allows creation of clients and endpoints without annotations. CXF supports both contract first development with WSDL and code first development starting from Java. For REST, CXF also supports a JAX-RS (TCK compliant) frontend. • Ease of use: CXF is designed to be intuitive and easy to use. There are simple APIs to quickly build code-first services, Maven plug-ins to make tooling integration easy, JAX-WS API support, Spring 2.x XML support to make configuration a snap, and much more.
• Binary and Legacy Protocol Support: CXF has been designed to provide a pluggable architecture that supports not only XML but also non-XML type bindings, such as JSON and CORBA, in combination with any type of transport.
You can download CXF from here
Now let us have a sample. This POC will help you create a web service, one service will send a java object to server and another service will send you back a java object
First of all you need to load cxf file to your container for that you can create a xml file like below and inculde in your web.xml
jboss-cxf.xml
 <?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:jaxws="http://cxf.apache.org/jaxws"       xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">         <import resource="classpath:META-INF/cxf/cxf.xml" />       <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />       <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />       <bean id="MyServiceBean" class="com.services.MyServiceImpl" />       <jaxws:endpoint id="myService" implementor="#MyServiceBean" address="/MyService" /> </beans> 
MyService.java
import javax.jws.WebService;

/**
 *
 * Interface for Employee Service
 *
 * @author	Praveenkumar K
 * @version	last updated : Aug 1, 2011
 * @see
 *
*/
@WebService
public interface MyService {
   /**
    *
    * uploadEmployee service will update employee in local database
    *
    * @param employee
    * @return
    */
   public int uploadEmployee(Employee emp);
   /**
    *
    * getEmployee service fetches the employee details againist a employee id
    *
    * @param empId
    * @return
    */
   public Emplolyee getEmployee(String empId);

}
MyServiceImpl.java
import javax.jws.WebService;

/**
 *
 * Implementation class for Employee Service
 *
 * @author	Praveenkumar K
 * @version	last updated : Aug 1, 2011
 * @see
 *
*/
@WebService(endpoint="com.service.MyService")
public interface MyServiceImple {
   /**
    *
    * uploadEmployee service will update employee in local database
    *
    * @param employee
    * @return
    */
   public int uploadEmployee(Employee emp){
     //ensert to data base
   }
   /**
    *
    * getEmployee service fetches the employee details againist a employee id
    *
    * @param empId
    * @return
    */
   public Emplolyee getEmployee(String empId){
    //get Employee from db
  }

}
web.xml
 ecomm-web-util

  contextConfigLocation
  WEB-INF/jboss-cxf.xml

  spring-config
  classpath:application-context-webutil.xml

  org.springframework.web.context.ContextLoaderListener

  CXFServlet
  <!--  CXF Servlet  -->
  org.apache.cxf.transport.servlet.CXFServlet
  1

  CXFServlet
  /*

  index.jsp

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
*//**
 *
 * EmployeeClient
 *
 * @author	Praveenkumar K
 * @version	last updated : Aug 8, 2011
 * @see
 *
 *//*
public final class MyClient
{

   private static final String serviceURL = "http://localhost:8080/myapp/MyService";

   public static void main(String args[]) throws Exception {

       JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

       factory.getInInterceptors().add(new LoggingInInterceptor());
       factory.getOutInterceptors().add(new LoggingOutInterceptor());
       factory.setServiceClass(MyService.class);
       factory.setAddress(serviceURL);
       MyService client = (MyService) factory.create();
       /**Upload Employee details*/
       Employee emp = client.getEmployee("124");
       Employee emp = null;
       emp = new Employee();
       emp .setEmployeeId("124");
       emp .setUserId("1111");
       int empid = client.uploadEmployee(emp );
       System.out.println("return token"+empid);

       System.exit(0);

   }

}
Posted in Uncategorized | Leave a comment

Call SOAP Web Service from Android application

This article will cover how to call a soap web service from your android application.
Here I am giving you a sample calculator application. Let us see the WSDL file of the web service
 <?xml version="1.0" encoding="UTF-8" ?>
 <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://cts.calc.com" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:ax21="http://cts.calc.com/xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://cts.calc.com">
<wsdl:documentation>Please Type your service description here</wsdl:documentation>
 <wsdl:types>
 <xs:schema xmlns:ax22="http://cts.calc.com/xsd" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://cts.calc.com">
<xs:import namespace="http://cts.calc.com/xsd" />
 <xs:element name="doService">
 <xs:complexType>
 <xs:sequence>
<xs:element minOccurs="0" name="c" nillable="true" type="ax22:Calculator" />
</xs:sequence>
</xs:complexType>
</xs:element>
 <xs:element name="doServiceResponse">
 <xs:complexType>
 <xs:sequence>
<xs:element minOccurs="0" name="return" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
 <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://cts.calc.com/xsd">
 <xs:complexType name="Calculator">
 <xs:sequence>
<xs:element minOccurs="0" name="a" type="xs:int" />
<xs:element minOccurs="0" name="b" type="xs:int" />
<xs:element minOccurs="0" name="operator" nillable="true" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>
</wsdl:types>
 <wsdl:message name="doServiceRequest">
<wsdl:part name="parameters" element="ns:doService" />
</wsdl:message>
 <wsdl:message name="doServiceResponse">
<wsdl:part name="parameters" element="ns:doServiceResponse" />
</wsdl:message>
 <wsdl:portType name="CalcServicePortType">
 <wsdl:operation name="doService">
<wsdl:input message="ns:doServiceRequest" wsaw:Action="urn:doService" />
<wsdl:output message="ns:doServiceResponse" wsaw:Action="urn:doServiceResponse" />
</wsdl:operation>
</wsdl:portType>
 <wsdl:binding name="CalcServiceSoap11Binding" type="ns:CalcServicePortType">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
 <wsdl:operation name="doService">
<soap:operation soapAction="urn:doService" style="document" />
 <wsdl:input>
<soap:body use="literal" />
</wsdl:input>
 <wsdl:output>
<soap:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
 <wsdl:binding name="CalcServiceSoap12Binding" type="ns:CalcServicePortType">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
 <wsdl:operation name="doService">
<soap12:operation soapAction="urn:doService" style="document" />
 <wsdl:input>
<soap12:body use="literal" />
</wsdl:input>
 <wsdl:output>
<soap12:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
 <wsdl:binding name="CalcServiceHttpBinding" type="ns:CalcServicePortType">
<http:binding verb="POST" />
<wsdl:operation name="doService">
<http:operation location="CalcService/doService" />
<wsdl:input>
<mime:content type="text/xml" part="doService" />
</wsdl:input>
 <wsdl:output>
<mime:content type="text/xml" part="doService" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="CalcService">
<wsdl:port name="CalcServiceHttpSoap11Endpoint" binding="ns:CalcServiceSoap11Binding">
<soap:address location="http://localhost:8080/CalcService1.5/services/CalcService.CalcServiceHttpSoap11Endpoint/" />
</wsdl:port>
 <wsdl:port name="CalcServiceHttpSoap12Endpoint" binding="ns:CalcServiceSoap12Binding">
<soap12:address location="http://localhost:8080/CalcService1.5/services/CalcService.CalcServiceHttpSoap12Endpoint/" />
</wsdl:port>
 <wsdl:port name="CalcServiceHttpEndpoint" binding="ns:CalcServiceHttpBinding">
<http:address location="http://localhost:8080/CalcService1.5/services/CalcService.CalcServiceHttpEndpoint/" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
 
This web service is expecting a payload Calculator.xml
<Calculator>
           <a>2</a>
           <b>5</b>
           <operator>+</operator>
    </Calculator>
The classes should be like this

public class Calculator {
 private int a;
 private int b;
 private String operator;

 public int getA() {
  return a;
 }

 public void setA(int a) {
  this.a = a;
 }

 public int getB() {
  return b;
 }

 public void setB(int b) {
  this.b = b;
 }

 public String getOperator() {
  return operator;
 }

 public void setOperator(String operator) {
  this.operator = operator;
 }
}

---------------------------------------------------------------

public interface CalcInt {
  public int doService(Calculator c);
}

-------------------------------------------------------------------

public class CalcService implements CalcInt {

	public int doService(Calculator c) {
	  try{
		if(c.getOperator()!=null && c.getOperator().equals("+"))
			return c.getA()+c.getB();
		else if(c.getOperator()!=null && c.getOperator().equals("-"))
			return c.getA()-c.getB();
		else if(c.getOperator()!=null && c.getOperator().equals("*"))
			return c.getA()*c.getB();
		else if(c.getOperator()!=null && c.getOperator().equals("/"))
			return c.getA()/c.getB();
		return 0;
          }catch(Exception e){

	    e.printStackTrace();
	  }
	}


Now let us see the Android application .Here I mentioned step by step process ok
1. Create an android application by the help of your IDE (eclipse) with activity name Calculate.
2. Edit AndroidManifest.xml give permission inside the manifest tag
<uses-permission android:name="android.permission.INTERNET" 
/>
3. Edit main.xml in layout and one more xml for calulator view calcview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
   <include android:id="@+id/calcview" layout="@layout/calcview" />
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>
-------------------calcview.xml------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
  android:layout_height="match_parent">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
  android:layout_height="match_parent">

 <TableRow android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
   android:layout_height="wrap_content">

  <EditText android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numeric="integer|decimal"></EditText>

  <Spinner android:layout_height="wrap_content" android:id="@+id/spinner1"
   android:layout_width="wrap_content"></Spinner>
  <EditText android:id="@+id/editText2"
   android:numeric="integer|decimal"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"></EditText>
 </TableRow>
 <TableRow android:id="@+id/tableRow2"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">

  <Button android:id="@+id/button1"
   android:onClick="doCalculation"
      android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Calculate"></Button>
 </TableRow>
 <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content"
  android:layout_height="wrap_content">
  <EditText android:id="@+id/editText3" android:layout_width="wrap_content"
   android:layout_height="wrap_content"></EditText>
 </TableRow>

</TableLayout>
</LinearLayout>
 4. Now let us include the ksoap2 API for SOAP . Douwnload jar file from the following location and map with your project (Add library in build path in eclipse).
5. Create Calculator class which implements KvmSerializable
import java.util.Hashtable;

import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;

public class Calculator implements KvmSerializable{
 public int a;
 public int b;
 public String operator;

 public Calculator(){}

     public Calculator(int a1, int b1, String operator1) {

         a = a1;
         b = b1;
         operator = operator1;
     }

     public Object getProperty(int arg0) {

         switch(arg0)
         {
         case 0:
             return a;
         case 1:
             return b;
         case 2:
             return operator;
         }

         return null;
     }

     public int getPropertyCount() {
         return 3;
     }

     public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
         switch(index)
         {
         case 0:
             info.type = PropertyInfo.INTEGER_CLASS;
             info.name = "a";
             break;
         case 1:
             info.type = PropertyInfo.INTEGER_CLASS;
             info.name = "b";
             break;
         case 2:
             info.type = PropertyInfo.STRING_CLASS;
             info.name = "operator";
             break;
         default:break;
         }
     }

     public void setProperty(int index, Object value) {
         switch(index)
         {
         case 0:
             a = Integer.parseInt(value.toString());
             break;
         case 1:
             b = Integer.parseInt(value.toString());
             break;
         case 2:
             operator = value.toString();
             break;
         default:
             break;
         }
     }

}
6. Now the major part: Edit the Calculate activity class and call the webservice
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class Calculate extends Activity  {
    /** Called when the activity is first created. */

   static Spinner operator = null;
   private static final String SOAP_ACTION = "doService";
 private static final String METHOD_NAME = "doService";
 private static final String NAMESPACE = "http://cts.calc.com";
 private static final String URL =
  "http://10.230.139.74:8080/CalcService1.5/services/CalcService?wsdl";
 private SoapObject resultRequestSOAP = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        operator = (Spinner)findViewById(R.id.spinner1);
        String array_spinner[]  =  new String[4];
        array_spinner[0] = "+";
        array_spinner[1] = "-";
        array_spinner[2] = "*";
        array_spinner[3] = "/";
        ArrayAdapter<?> adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, array_spinner);
        operator.setAdapter(adapter);

    }

    public void doCalculation(View view){
     String firstNo =
   ((EditText) findViewById(R.id.editText1))
   .getText().toString();
  String secondNo =
   ((EditText) findViewById(R.id.editText2))
   .getText().toString();
  String operator = ((Spinner) findViewById(R.id.spinner1)).getSelectedItem().toString();
  callWebService(firstNo,secondNo,operator );
    }

    public String callWebService(String firstNo, String secondNo,String operator ){
     String result = "0";
     try {
      SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
      AndroidHttpTransport androidHttpTransport =
       new AndroidHttpTransport(URL);

   PropertyInfo p1 = new PropertyInfo();
   Calculator C = new Calculator();
   C.a=Integer.parseInt(firstNo);
   C.b=Integer.parseInt(secondNo);
   C.operator=operator;

   p1.setName("C");
         p1.setValue(C);
         p1.setType(C.getClass());
         request.addProperty(p1);

   SoapSerializationEnvelope envelope =
    new SoapSerializationEnvelope(SoapEnvelope.VER11);

   envelope.dotNet=true;
   envelope.setOutputSoapObject(request);

   // Make the soap call.
   androidHttpTransport.call(SOAP_ACTION, envelope);

   Object results =(Object)envelope.getResponse();
   //to get the data String resultData=result.getProperty(0).toString();
   String temp = results.toString();
   if(temp.equals("0")){
    temp = "The result is 0";
   }
   System.out.println("Result"+temp);
   /** Show the suggestions in a text area field called
    * lblStatus */
   ((TextView) findViewById(R.id.editText3)).setText(temp
     .toString());
  } catch (Exception aE) {
   System.out.println(aE.toString());

   ((TextView) findViewById(R.id.editText3)).setText(aE.getMessage());
   aE.printStackTrace();
  }

     return result;
    }

}
END
Posted in Uncategorized | 11 Comments

No comments:

Post a Comment