WebService

Seit Java 6 ist die JAX-WS-API in der SE integriert. Ein Webservice stellt über ein Netzwerk die direkte Maschine-zu-Maschine-Interaktion bereit.

interface IHelloWorld


package de.snowbits.service;

import javax.jws.WebParam;
import javax.jws.WebService;

@WebService
public interface IHelloWorld {
	String sayHello(@WebParam(name="who") String who);
}
	

class HelloWorld


package de.snowbits.service;

import javax.jws.WebService;

@WebService(endpointInterface = "de.snowbits.service.IHelloWorld")
public class HelloWorld implements IHelloWorld {
	
	public String sayHello(String who) {
		return "Hello " + who;
	}
	
}
	

class HelloServer


package de.snowbits.service;

import javax.xml.ws.Endpoint;

public class HelloServer {
	
	public static void main(String... args) throws InterruptedException {
	    Endpoint endpoint = Endpoint.publish("http://localhost:5055/service.snowbits", new HelloWorld());

	    System.out.println(">>> Start Server");
	    Thread.sleep(1000 * 60);
	    System.out.println(">>> Close Server");	
	    
	    endpoint.stop();
	    System.exit(0);
	}
	
}
	

class HelloClient


package de.snowbits.service;

import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

public class HelloClient {

	public static void main(String... args) throws Exception {
		Service service = Service.create(new URL("http://localhost:5055/service.snowbits?wsdl"),
						 new QName("http://service.snowbits.de/", "HelloWorldService"));
		
		IHelloWorld port = service.getPort(IHelloWorld.class);
		System.out.println(port.sayHello("Max"));
		
		// Hello Max
	}
	
}
	

class HelloClientLogging


package de.snowbits.service;

import java.net.URL;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.ws.Binding;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.Handler;

import com.sun.xml.internal.ws.fault.ServerSOAPFaultException;

import de.snowbits.service.ExceptionResolver.Resolver;
import de.snowbits.service.SOAPStringHandler.StringHandler;

public class HelloClientLogging {
	
	@SuppressWarnings("rawtypes")
	public static void main(String... args) {
		try {
			Service service = Service.create(
					new URL("http://localhost:5055/service.snowbits?wsdl"), 
					new QName("http://service.snowbits.de/", 
					"HelloWorldService"));

			IHelloWorld port = service.getPort(IHelloWorld.class);
			SOAPStringHandler soapStringHandler = new SOAPStringHandler(StringHandler.RequestAndResponse);
			BindingProvider bindingProvider = (BindingProvider) port;
			Binding binding = bindingProvider.getBinding();
			List<Handler> handlerChain = binding.getHandlerChain();
			handlerChain.add(soapStringHandler);
			binding.setHandlerChain(handlerChain);			
						
			port.sayHello("Max und Moritz");
	
			System.out.println("Request:\n" + soapStringHandler.getRequestSOAP());
			System.out.println("Response:\n" + soapStringHandler.getResponseSOAP());
		} catch (ServerSOAPFaultException e) {
			// TODO: error handling server
			System.out.println("ServerSOAPFaultException: " + e.getMessage());
		} catch (Exception e) {
			ExceptionResolver resolver = new ExceptionResolver();
			Resolver error = resolver.resolve(e);
			// TODO: error handling client
			System.out.println("ConnectionError: " + resolver.isConnectionError());
			System.out.println(error.getResolverMessage());
		}
	}

}
	

Log Ausgabe


Request:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><S:Body><ns2:sayHello xmlns:ns2="http://service.snowbits.de/"><who>Max und Moritz</who></ns2:sayHello></S:Body></S:Envelope>
Response:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><S:Body><ns2:sayHelloResponse xmlns:ns2="http://service.snowbits.de/"><return>Hello Max und Moritz</return></ns2:sayHelloResponse></S:Body></S:Envelope>

	

class SOAPStringHandler


package de.snowbits.service;

import java.io.ByteArrayOutputStream;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class SOAPStringHandler implements SOAPHandler<SOAPMessageContext> {

	private String _requestSOAP;
	private String _responseSOAP;
	private ByteArrayOutputStream _baoStream;
	private StringHandler _stringHandler;

	public enum StringHandler {
		Request, Response, RequestAndResponse;
	}

	public SOAPStringHandler(StringHandler stringHandler) {
		_stringHandler = stringHandler;
	}

	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		writeMessage(context);
		return true;
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {			
		writeMessage(context);
		return true;
	}

	@Override
	public void close(MessageContext context) {

	}

	@Override
	public Set<QName> getHeaders() {
		return null;
	}

	public String getRequestSOAP() {
		return _requestSOAP;
	}

	public String getResponseSOAP() {
		return _responseSOAP;
	}
	
	public boolean isRequestSOAP() {
		return _requestSOAP != null;
	}
		
	public boolean isResponseSOAP() {
		return _responseSOAP != null;
	}

	private void writeMessage(SOAPMessageContext context) {
		Boolean property = (Boolean) context
				.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

		try {
			if (property.booleanValue()) {
				if (_stringHandler == StringHandler.Request || 
				    _stringHandler == StringHandler.RequestAndResponse) {
					_baoStream = new ByteArrayOutputStream();
					context.getMessage().writeTo(_baoStream);
					_requestSOAP = new String(_baoStream.toByteArray(), "UTF-8");
					_baoStream.close();
				}
			} else {
				if (_stringHandler == StringHandler.Response || 
				    _stringHandler == StringHandler.RequestAndResponse) {
					_baoStream = new ByteArrayOutputStream();
					context.getMessage().writeTo(_baoStream);
					_responseSOAP = new String(_baoStream.toByteArray(), "UTF-8");
					_baoStream.close();
				}
			}
		} catch (Exception e) {
			// TODO: handle for exception
			e.printStackTrace();
		}
	}

}
	

class ExceptionResolver, Resolver


package de.snowbits.service;

public class ExceptionResolver {

	private boolean _connectionError;
	
	public final Resolver resolve(Exception e) {
		Throwable cause = e.getCause();
		
		if (e instanceof java.net.UnknownHostException || 
			(cause != null && cause instanceof java.net.UnknownHostException)) {
			_connectionError = true;
			return new Resolver(true, e.getClass().getSimpleName(), e.getMessage());
		} else if (e instanceof javax.xml.ws.WebServiceException && 
			   (e.getMessage() != null && e.getMessage().indexOf("Connection refused: connect") != -1)) {
			_connectionError = true;
			return new Resolver(true, e.getClass().getSimpleName(), e.getMessage());
		} else if (e instanceof java.net.ConnectException || 
			   (cause != null && cause instanceof java.net.ConnectException)) {
			_connectionError = true;
			return new Resolver(true, e.getClass().getSimpleName(),	e.getMessage());
		}

		// TODO: more exception resolving			
			
		return new Resolver(false, e.getClass().getSimpleName(), e.getMessage());
	}
	
	public boolean isConnectionError() {
		return _connectionError;
	}

	public class Resolver {
		
		private String _exception;
		private String _message;
		private boolean _resolve;
		
		public Resolver(boolean resolve, String exception, String message) {
			_resolve = resolve;
			_exception = exception;
			_message = message;
		}

		public boolean isResolve() {
			return _resolve;
		}
		
		public String getException() {
			return _exception;
		}
		
		public String getMessage() {
			return _message;
		}
		
		public String getResolverMessage() {
			return _resolve ? 
				"Exception Resolve: [exception: " + getException() + "; message: " +
				(getMessage() == null ? "" : getMessage()) + "]" : 
				"Exception Resolve: can not resolve the passed exception: " +
				"[exception: " + getException() + "; message: " +
				(getMessage() == null ? "" : getMessage()) + "]";				
		}
		
	}	
}
	

class ResHelloBean


package de.snowbits.service;


import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class ResHelloBean {
	
	protected String message;
	protected String name;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getName() {
		return name;
	}

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

}
	

interface ResHello


package de.snowbits.service;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.WebParam.Mode;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.jws.soap.SOAPBinding.Use;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

@WebService(name="ResWSHello", targetNamespace="http://service2.snowbits.de", 
            wsdlLocation="http://localhost:5055/service2.snowbits?wsdl")
@SOAPBinding(style=Style.RPC, use=Use.LITERAL)
public interface ResHello {

	String TARGET_NAMESPACE       = "http://service2.snowbits.de";
	String TARGET_NAMESPACE_TYPES = TARGET_NAMESPACE + "/service/types";

	@WebMethod(operationName="getResHello")
	@RequestWrapper(targetNamespace=TARGET_NAMESPACE_TYPES, className="java.lang.String")
	@ResponseWrapper(targetNamespace=TARGET_NAMESPACE_TYPES, className="de.snowbits.service.ResHelloBean")
	@WebResult(targetNamespace=TARGET_NAMESPACE_TYPES, name="ResHello")
	public ResHelloBean getResHello(@WebParam(targetNamespace=TARGET_NAMESPACE_TYPES, 
	                                         name="name", mode=Mode.IN) String name);

}
	

class ResHelloImpl


package de.snowbits.service;

import javax.jws.WebService;

@WebService(endpointInterface="de.snowbits.service.ResHello", 
            targetNamespace=ResHello.TARGET_NAMESPACE, 
            portName="ResHelloPort", serviceName="ResHelloService")
public class ResHelloImpl implements ResHello {

	@Override
	public ResHelloBean getResHello(String name) {
		ResHelloBean result = new ResHelloBean();
		result.setMessage("Hello");
		result.setName(name);
		
		return result;
	}

}
	

class ResHelloServer


package de.snowbits.service;

import javax.xml.ws.Endpoint;

public class ResHelloServer {
	
	public static void main(String[] args) throws InterruptedException {
		Endpoint endpoint = Endpoint.publish("http://localhost:5055/service2.snowbits/ResHelloService",
				                             new ResHelloImpl());
		
	    System.out.println(">>> Start Server");
	    Thread.sleep(1000 * 60);
	    System.out.println(">>> Close Server");	
	    
	    endpoint.stop();
	    System.exit(0);		
	}
	
}
	

Stub generieren


C:\>"%JAVA_HOME%"\bin\wsimport http://localhost:5055/service2.snowbits/ResHelloService?wsdl -d d:\\temp\src\ -p de.snowbits.service.stub -verbose -keep -Xnocompile	
WSDL wird geparst ...



Code wird generiert ...

de\snowbits\service\stub\ObjectFactory.java
de\snowbits\service\stub\ResHelloBean.java
de\snowbits\service\stub\ResHelloService.java
de\snowbits\service\stub\ResWSHello.java
de\snowbits\service\stub\package-info.java
	

class ResHelloClient


package de.snowbits.service;

import javax.xml.ws.WebServiceRef;

import de.snowbits.service.stub.ResHelloBean;
import de.snowbits.service.stub.ResHelloService;
import de.snowbits.service.stub.ResWSHello;

public class ResHelloClient {

	@WebServiceRef(wsdlLocation = "http://localhost:5055/service2.snowbits/ResHelloService?wsdl")
	private ResHelloService service;

	public void runClient(String yourName) {
		service = new ResHelloService();
		ResWSHello port = service.getResHelloPort();
		ResHelloBean response = port.getResHello(yourName);
		
		System.out.println(response.getMessage() + " " + response.getName());		
	}
	
	public static void main(String[] args) {
		ResHelloClient client = new ResHelloClient();
		client.runClient("Struwwelpeter");
		
		// Hello Struwwelpeter
	}
	
}
	

wsdl http://localhost:5055/service2.snowbits/ResHelloService?wsdl


<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. -->
<!-- Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. -->
<definitions targetNamespace="http://service2.snowbits.de" name="ResHelloService">
	<types>
		<xsd:schema>
			<xsd:import namespace="http://service2.snowbits.de" schemaLocation="http://localhost:5055/service2.snowbits/ResHelloService?xsd=1"/>
		</xsd:schema>
	</types>
	<message name="getResHello">
		<part name="name" type="xsd:string"/>
	</message>
	<message name="getResHelloResponse">
		<part name="ResHello" type="tns:resHelloBean"/>
	</message>
	<portType name="ResWSHello">
		<operation name="getResHello">
			<input wsam:Action="http://service2.snowbits.de/ResWSHello/getResHelloRequest" message="tns:getResHello"/>
			<output wsam:Action="http://service2.snowbits.de/ResWSHello/getResHelloResponse" message="tns:getResHelloResponse"/>
		</operation>
	</portType>
	<binding name="ResHelloPortBinding" type="tns:ResWSHello">
		<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
		<operation name="getResHello">
			<soap:operation soapAction=""/>
			<input>
				<soap:body use="literal" namespace="http://service2.snowbits.de"/>
			</input>
			<output>
				<soap:body use="literal" namespace="http://service2.snowbits.de"/>
			</output>
		</operation>
	</binding>
	<service name="ResHelloService">
		<port name="ResHelloPort" binding="tns:ResHelloPortBinding">
			<soap:address location="http://localhost:5055/service2.snowbits/ResHelloService"/>
		</port>
	</service>
</definitions>
	

xsd http://localhost:5055/service2.snowbits/ResHelloService?xsd=1


<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. -->
<xs:schema version="1.0" targetNamespace="http://service2.snowbits.de">
	<xs:element name="resHelloBean" type="tns:resHelloBean"/>
	<xs:complexType name="resHelloBean">
		<xs:sequence>
			<xs:element name="message" type="xs:string" minOccurs="0"/>
			<xs:element name="name" type="xs:string" minOccurs="0"/>
		</xs:sequence>
	</xs:complexType>
</xs:schema>
	

code Snippets


public class SOAPStringHandler implements SOAPHandler<SOAPMessageContext> {
	...
	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		System.out.println("Message Outbound Property: " + context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY));
		System.out.println("HTTP Request Method:       " + context.get(MessageContext.HTTP_REQUEST_METHOD));
		System.out.println("Path Info:                 " + context.get(MessageContext.PATH_INFO));
		System.out.println("Query String:              " + context.get(MessageContext.QUERY_STRING));
		System.out.println("HTTP Response Code:        " + context.get(MessageContext.HTTP_RESPONSE_CODE));
		System.out.println("Reference Parameters:      " + context.get(MessageContext.REFERENCE_PARAMETERS));
		System.out.println("WSDL Description:          " + context.get(MessageContext.WSDL_DESCRIPTION));
		System.out.println("WSDL Interface:            " + context.get(MessageContext.WSDL_INTERFACE));
		System.out.println("WSDL Operation:            " + context.get(MessageContext.WSDL_OPERATION));
		System.out.println("WSDL Port:                 " + context.get(MessageContext.WSDL_PORT));
		System.out.println("WSDL Service:              " + context.get(MessageContext.WSDL_SERVICE));		
		...
		return true;
	}
	...
}
	

Top


Example
Sitemap Kontakt Impressum