Archive

Archive for the ‘webservice’ Category

How to Call WebService ( WSDL Based ) using Apache HttpConnection

February 1, 2013 Leave a comment

Here we are going to see how to call WSDL based WebService using Apache HttpConnection ( org.apache.commons.httpclient.HttpConnection ) object with minimum information.

Here I have passed request xml with EndPoint URI to call the webservice.

Steps 1:
I have created simple Webservice with 3 operation using Java. Then wrapped this class as WAR file and deployed in Weblogic Server to get the WSDL.

CustomerService.java

package com.wordpress.rathinasaba.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService(name="CustomerService", serviceName="CustomerSvc")
public class CustomerService {
	
	@WebMethod(operationName="sayHello")
	public String sayHello(String name){
		System.out.println("---- Sayhello service----");
		return "Hello "+name+" !!!!";
	}

	@WebMethod(operationName="checkStatus")
	public String serviceStatus(String serviceName){
		System.out.println("---- service Status -----");
		if("SMS".equalsIgnoreCase(serviceName)){
			return "Active";
		} else if("GPRS".equalsIgnoreCase(serviceName)){
			return "InActive";
		} else if("MMS".equalsIgnoreCase(serviceName)){
			return "Active";
		}else{
			return "Active";
		}
	}
	
	@WebMethod(operationName="updateAddress")
	public String updateAddress(String address){
		System.out.println("---- Update Address Service ----");
		return "Success";
	}
}

 
Steps 2:
Deploy the WAR file created from the above CustomerService.java class in Weblogic server to get WSDL file.

http://localhost:8011/CustomerSvc/CustomerService?WSDL

 
Steps 3:  
CustomerSvcClient.java
Created a Client Java class to call the created WebService using Apache HttpConnection object with minimum information.

package com.wordpress.rathinasaba.ws.client;

import java.io.IOException;

import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public class CustomerSvcClient {
	
	private static final String host="localhost";
	private static final String port="8011";
	
	public static String invokeCustomerSvc(String payload,String endpointURL){
		 String wellformedrequest=null;
         String serviceResponse=null;
         HttpConnection httpConn=null;
         try {
			if (!payload.toUpperCase().contains("</SOAPENV:BODY>")) {
			   
			     String soapEnvHeader =
			         "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
			         "   <soapenv:Body>";
			     String body = payload;
			     String soapEnvFooter = " </soapenv:Body>\n" +"</soapenv:Envelope>";
			     wellformedrequest = soapEnvHeader.concat(body).concat(soapEnvFooter);
			 } else {
			     wellformedrequest = payload;
			 }
			 
			 /**
			  * Creating Http Connection to call WebService Over HTTP Protocol
			  */
			println(" ---- Creating HTTP Connection ----");
			httpConn=new HttpConnection(host,Integer.parseInt(port));
			httpConn.open();
			PostMethod postMethod=new PostMethod();
			 /**
			  * Set Endpoint URL
			  */
			postMethod.setPath(endpointURL);
			postMethod.setRequestEntity(new StringRequestEntity(wellformedrequest, "application/soap+xml", "utf-8"));
			postMethod.execute(new HttpState(), httpConn);
			println("HTTP Response Status :"+postMethod.getStatusLine().toString());
			serviceResponse=postMethod.getResponseBodyAsString();
			println("Service Response :"+serviceResponse);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			httpConn.releaseConnection();
		}
         return serviceResponse;
	}
	
	private static void println(Object content){
		System.out.println(content);
	}
	
	private static String getSayHelloRequest(){
		String sayHelloRequest="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://com/wordpress/rathinasaba/ws\">" +
						"			<soapenv:Header/>" +
						"			<soapenv:Body>" +
						"      			<ws:sayHello>" +
						"         			<ws:name>Rathina Sabapathy</ws:name>" +
						"     			 </ws:sayHello>" +
						"   		</soapenv:Body>" +
						"       </soapenv:Envelope>";
	
		return sayHelloRequest;
	}
	
	private static String getSayHelloRequestOne(){
		String sayHelloRequest="<ws:sayHello xmlns:ws=\"http://com/wordpress/rathinasaba/ws\">" +
				"         <ws:name>Rathina Sabapathy</ws:name>" +
				"      </ws:sayHello>";
		return sayHelloRequest;
	}
	
	private static String getCheckStatusRequest(){
		String statusRequest="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://com/wordpress/rathinasaba/ws\">" +
							"   <soapenv:Header/>" +
							"   <soapenv:Body>" +
							"      <ws:checkStatus>" +
							"         <ws:serviceName>SMS</ws:serviceName>" +
							"      </ws:checkStatus>" +
							"   </soapenv:Body>" +
							"</soapenv:Envelope>";
		return statusRequest;
	}
	
	private static String getUpdateAddressRequest(){
		String statusRequest="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://com/wordpress/rathinasaba/ws\">" +
				"			   <soapenv:Header/>" +
				"				   <soapenv:Body>" +
				"				      <ws:updateAddress>" +
				"				         <ws:address>Adyar,Chennai</ws:address>" +
				"				      </ws:updateAddress>" +
				"				   </soapenv:Body>" +
				"				</soapenv:Envelope>";
		return statusRequest;
	}
	
	public static void main(String[] args) {
		String endpointURL="http://localhost:8011/CustomerSvc/CustomerService";
		
		/**
		 * 1. Call SayHello Service With SOAP body and Without SOAP body
		 */
		invokeCustomerSvc(getSayHelloRequest(), endpointURL);
		invokeCustomerSvc(getSayHelloRequestOne(), endpointURL);
		
		/**
		 * 2. Call CheckStatus Service
		 */
		invokeCustomerSvc(getCheckStatusRequest(), endpointURL);
		
		/**
		 * 3. Call UpdateAddress Service
		 */
		invokeCustomerSvc(getUpdateAddressRequest(), endpointURL);
	}

}
Advertisements

Call Webservice using JAX-WS’s Dynamic Dispatch Interface( JAX-WS DII method )

December 29, 2011 Leave a comment

In this post we will see how to call web service from Java main method using JAX-WS’s DII( Dynamic Invocation Interface ) technique.

1. Required Libraries :
JDK6

2. WSDL file Snapshot

WSDL file

WSDL file

3. Java class to call WebService using JAX-WS’s DII method

package com.room.jaxws.sample;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;

public class JAXWS_DII_Client {
	
	final String WSDL_ENDPOINT_URL="http://localhost:8001/services/SayHello/SayHello";
	public String invokeWebService(String inputMsg){
		String responseStr=null;
		try {
			/**
			 *  Define the service.
			 */
			QName operationName = new QName("http://com.test.ws","sayHello");
			QName portQName = new QName("http://com.test.ws","SayHelloHTTPPort");
			Service svc = Service.create(operationName);
			svc.addPort(portQName,SOAPBinding.SOAP11HTTP_BINDING,WSDL_ENDPOINT_URL);
			
			/**
			 *  Create the dynamic invocation object from this service.
			 */
			Dispatch<Source> dispatch = svc.createDispatch(portQName,Source.class,Service.Mode.PAYLOAD);
			
			ByteArrayInputStream bais = new ByteArrayInputStream(inputMsg.getBytes());
			Source input = new StreamSource(bais);

			/**
			 *  Invoking WebService
			 */
			Source response = dispatch.invoke(input);
			
			/**
			 *  Process the response.
			 */
			StreamResult result = new StreamResult(new ByteArrayOutputStream());
			Transformer trans = TransformerFactory.newInstance().newTransformer();
			trans.transform(response, result);
			ByteArrayOutputStream baos = (ByteArrayOutputStream) result.getOutputStream();

			/**
			 *  Write out the response content to string.
			 */
			responseStr = new String(baos.toByteArray());
			System.out.println("Response : ->"+responseStr);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		return responseStr;
	}
	
	public static void main(String[] args) {
        try {      
            
          String input="<sayHello xmlns=\"http://com.test.ws\">" +
          		"        	  <name>Test</name>" +
          		"        	  </sayHello>" ;
          		
          JAXWS_DII_Client jax_ws_client=new JAXWS_DII_Client();
          String response=jax_ws_client.invokeWebService(input);
          System.out.println("----- Response ----->:"+response);
            
        }
        catch (Throwable t) {
            t.printStackTrace();
        }
    }

}

Calling Web service using Axis without client stubs (DII method)

August 17, 2010 3 comments

Here i have given code for invoking web service using axis1.4 libraries without generating client stubs from the WSDL file.

Requirement:
1. JDK1.5 and above
2. Axis library jars.
activation.jar
axis.jar
axis-ant.jar
commons-discovery-0.2.jar
commons-logging-1.0.4.jar
jaxrpc.jar
log4j-1.2.8.jar
mail.jar
saaj.jar
wsdl4j-1.5.1

WSDL URL to be invoked using axis client is
http://localhost:8001/SayHello/SayHello?WSDL



Axis Client Code:

This is the Client code used to invoke the axis web service using Dynamic Invocation Interface ( DII ) technique.


import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;

import org.apache.axis.Constants;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;

public class AxisClient {

	private static final String WSDL_URL="http://localhost:8001/SayHello/SayHello?WSDL";

	public void callSayHelloWSUsingAxis(String payload){
		try {
			System.out.println("***** Calling WebService using Axis ( DII method) *******");
			Service service=new Service();
			Call call=(Call)service.createCall();
			call.setTargetEndpointAddress(new URL(WSDL_URL));
			call.setOperationName(new QName("http://com/test/ws/sample", "sayHello"));
			call.addParameter("name",Constants.XSD_STRING, ParameterMode.IN);
			call.setReturnType(Constants.XSD_STRING);

			Object[] payloadObjectArr=new Object[1];
			payloadObjectArr[0]=payload;
			String response=(String)call.invoke(payloadObjectArr);
			System.out.println("Web Service Response :"+response);
		}catch (RemoteException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		System.out.println("***** Calling Web Service from Main method *********");
		AxisClient client=new AxisClient();
		client.callSayHelloWSUsingAxis("AxisClient");
	}
}

Web service response :

***** Calling Web Service from Main method *********
***** Calling WebService using Axis ( DII method) *******
Web Service Response :Hello AxisClient !!!

Calling Web Service from Java Client using JAX-WS libraries

August 13, 2010 1 comment

Objective:
Calling Web Service from java client stubs.

Requirement :
JDK6 or JDK5 and jaxws library jars

Calling web service from java :

1. Create client ( Consumer ) stub codes from the WSDL URL given by the web service deployment using soap-ui tool or ant build.

2. Here I have created the stub code using WSIMPORT ant task of jaxws library .

sample build.properties

wls.home=E:/Softwares/BEA/wlserver/server
wsdl.file=http://localhost:8001/SayHello/SayHello?WSDL
jax-ws.home=E:/Softwares/jaxws-ri


Sample build.xml to create the web service client stubs

<?xml version="1.0"?>

<project default="wsimport" basedir=".">

	<property file="build.properties" />
	<property name="src" value="${basedir}/src"/>
	
	<!--setting the classpath for jax-ws library files-->
	<echo message="JAX-WS HOME: ${jax-ws.home}"/>
	<path id="jax-ws.classpath">
		<fileset dir="${jax-ws.home}/lib">
			<include name="**/*.jar"/>
		</fileset>
	</path>
	<!--Create client stub classes from wsdl file-->
	<echo message="WSDL FILE: ${wsdl.file}"/>
	<taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport" classpathref="jax-ws.classpath"/>
	<target name="wsimport">	
		<wsimport
		    wsdl="${wsdl.file}"
		    destdir="${src}"
		    keep="true"
		    verbose="on"
		    wsdlLocation="${wsdl.file}"
		    package="com.test.ws.sample.client.stub"/>
	</target>

</project>

3. The client stub classes are created while running the build script like shown below

Buildfile: E:\Eclipse3.6WS\SampleWS\wsimport-build.xml
     [echo] JAX-WS HOME: E:/Softwares/jaxws-ri
     [echo] WSDL FILE: http://localhost:8001/SayHello/SayHello?WSDL
wsimport:
 [wsimport] Consider using <depends>/<produces> so that wsimport won't do unnecessary compilation
 [wsimport] command line: wsimport -d E:\Eclipse3.6WS\SampleWS\src -keep -verbose http://localhost:8001/SayHello/SayHello?WSDL -p com.test.ws.sample.client.stub -wsdllocation http://localhost:8001/SayHello/SayHello?WSDL
 [wsimport] parsing WSDL...
 [wsimport] generating code...
 [wsimport] com\test\ws\sample\client\stub\ObjectFactory.java
 [wsimport] com\test\ws\sample\client\stub\SayHello.java
 [wsimport] com\test\ws\sample\client\stub\SayHelloResponse.java
 [wsimport] com\test\ws\sample\client\stub\SayHelloService.java
 [wsimport] com\test\ws\sample\client\stub\SayHello_Type.java
 [wsimport] com\test\ws\sample\client\stub\package-info.java
BUILD SUCCESSFUL
Total time: 5 seconds

4. Write an entry point class by composing the generated stub classes to get response of exposed operation by passing the apropriate input parameter.

import com.test.ws.sample.client.stub.SayHello;
import com.test.ws.sample.client.stub.SayHelloService;

public class TestSayHelloWS {

	public static void main(String[] args) {
		SayHelloService service=new SayHelloService();
		SayHello operation=service.getSayHelloSoapPort();
		String response=operation.sayHello("Sabapathy");
		System.out.println("Response :"+response);
	}
}
Categories: webservice Tags:

Building Web Service

February 26, 2010 1 comment

Objective :

Building simple web service example in java

Requirement :

JDK6 ( JDK 6 defaultly has the Web Service artifact )

Web Service Description:
Web service is a software system that is designed to support interoperable machine to machine interaction over the network. It is exposed the operations in an interface which is a WSDL(Web Service Description language ) file.

Web services are platform-independent and language -independent, since they use standard XML languages.

Web services are uses open protocols (HTTP) for transmitting the messages (such as request and response ) over the web. It can be used by other applications

Building Webservice :

1. Write a Sample Class by annotating the class by @WebService and annotate the method by @WebMethod which is to be exposed as web service operation.

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService(name="sayHello",
			targetNamespace="http://com.test.ws",
			portName="SayHelloPort",
			serviceName="SayHelloService")
public class SayHello {

	@WebMethod
	public String sayHello(String name){
		return !isEmpty(name)? "Hello "+name+" !!!":"Hello there !!!";
	}

	private boolean isEmpty(String text){
		return text==null || "".equals(text.trim());
	}
}

2. By using the ant task you can build as a web service module.There are some ant task like axis,jaxws and weblogic ant tasks to build the web service. Here i have used weblogic’s JWSC ant task to build the web service module.

Use this build.xml file to create webservice module.

<?xml version="1.0"?>

<project default="install" basedir=".">

	<property file="build.properties" />
	src" value="${basedir}/src"/>
	<property name="dist" value="dist"/>
	<property name="dist" value="dist"/>

	<echo message="WLS HOME: ${wls.home}"/>
	<path id="classpath">
		<pathelement location="${wls.home}/lib/weblogic.jar"/>
	</path>
	<target name="clean">
		<delete dir="${basedir}/${dist}"/>
	</target>
	<target name="init" depends="clean">
		<mkdir dir="${basedir}/${dist}"/>
	</target>

	<!-- weblogic <span class="hiddenSpellError" pre="weblogic ">jwsc</span> ant task class used to create webservice artifact from java file-->
	<taskdef name="jwsc" classname="weblogic.wsee.tools.anttasks.JwscTask" classpathref="classpath"/>
	<target name="install" depends="init">
		<jwsc srcdir="${src}" destdir="${dist}" verbose="on" debug="on">
			<module contextPath="SayHello" name="SayHello">
				<jws file="com/test/ws/sample/SayHello.java"/>
			</module>
		</jwsc>
	</target>
</project>

3. Run this build script ,SayHello.war file will be created.
4. Deploy the SayHello.war file in Weblogic server.
5. After successful deployment , WSDL file will be generated.

Categories: webservice Tags: