Web Services Development with the Apache Web Services Toolkit Odysseas Pentakalos, Ph.D. Chief Technical Officer SYSNET International, Inc. odysseas@sysnetint.com Copyright 2005 SYSNET International, Inc. 1 Developing Web Services with Axis Introduction to Axis Styles Supported Client Development Architecture Advanced Features UDDI and juddi WS-Addressing WS-Reliable Messaging Transactions Copyright 2005 SYSNET International, Inc. 2 Java Web Services 1
Apache Axis Copyright 2005 SYSNET International, Inc. 3 Brief History of Axis (TD) Apache Extensible Interaction System IBM contributes SOAP4J to Apache in 1999 Apache SOAP is released Toolkit for developing SOAP 1.1 clients/servers Monolithic architecture No support for other transports (some SMTP) Axis 1.0 is released in October 2002 Axis 1.2.x is the current release Work currently underway for Axis 2.0 Copyright 2005 SYSNET International, Inc. 4 Java Web Services 2
Axis: What do you get? Toolkit for building clients/servers Support for SOAP 1.1/1.2 Simple stand-alone server Server that plugs into servlet container Support for WSDL 1.1 Tool for monitoring SOAP messages Copyright 2005 SYSNET International, Inc. 5 Features Chains of message processing components Flexible extensibility: Custom header processing Logging Extensible transport framework Clean separation between transport and engine Transport support for various protocols Extensible type mapping system Support for all basic data types Automatic serialization/deserialization of Java Beans Support for development of custom serial./deserial. Copyright 2005 SYSNET International, Inc. 6 Java Web Services 3
Axis Client APIs Generated Stubs: Generate stubs from WSDL using provided tools. Use of web services is totally transparent to the application Dynamic Stubs: Stubs are generated at runtime as opposed to development time Dynamic Invocation: Build the request dynamically using the Call object Copyright 2005 SYSNET International, Inc. 7 Generated Stub Client WSDL2Java tool generates stubs and skeletons based on WSDL java org.apache.axis.wsdl.wsdl2java http://localhost:8080/axis/calculator.jws?wsdl CalculatorLocator locator = new CalculatorLocator(); Calculator stub = locator.getcalculator(); stub.add(number1, number2); Copyright 2005 SYSNET International, Inc. 8 Java Web Services 4
Dynamic Invocation The SOAP call is constructed dynamically at runtime public class TestClient { public static void main(string [] args) { String endpoint = "http://ws.apache.org/axis/services/echo"; Service service = new Service(); Call call = (Call) service.createcall(); call.settargetendpointaddress( new java.net.url(endpoint) ); call.setoperationname(new QName("http://soapinterop.org/", echostring")); String ret = (String) call.invoke( new Object[] { "Hello!" } ); System.out.println("Sent 'Hello!', got '" + ret + "'"); Copyright 2005 SYSNET International, Inc. 9 Dynamic Stub Client Stub is generated on the fly from the service interface Calculator calcport = (Calculator) service.getport(calculator.class); double sum = calcport.add(number1, number2); Copyright 2005 SYSNET International, Inc. 10 Java Web Services 5
Supported WS Styles RPC Style: SOAP RPC conventions with the SOAP data model Document Style: most interoperable style where body is an XML fragment Wrapped Style: like document style but root element corresponds to method name Message Style: Axis-specific where pure XML is passed to method Copyright 2005 SYSNET International, Inc. 11 RPC Web Service Style RPC/encoded style was very popular but due to interoperability issues, WS-I disallows it Root element corresponds to method name Parameters are encoded using SOAP encoding <soap:envelope> <soap:body> <addnumbers> <x xsi:type= xsd:int >5</x> <y xsi:type= xsd:float >5.0</y> </addnumbers> </soap:body> </soap:envelope> Copyright 2005 SYSNET International, Inc. 12 Java Web Services 6
Document Web Service Style Now becoming the most popular style based on WS-I recommendation public void method(purchaseorder po) <soap:envelope xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"> <soap:body> <myns:purchaseorderxmlns:myns="http://commerce.com/po" > <item>sk001</item> <quantity>1</quantity> <description>sushi Knife</description> </myns:purchaseorder> </soap:body> </soap:envelope> Copyright 2005 SYSNET International, Inc. 13 Wrapped Web Service Style Like document literal since SOAP body is defined in the WSDL schema public void purchaseorder(string item, int quantity, String description) <soap:envelope xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"> <soap:body> <myns:purchaseorder xmlns:myns="http://commerce.com/po"> <item>sk001</item> <quantity>1</quantity> <description>sushi Knife</description> </myns:purchaseorder> </soap:body> </soap:envelope> Copyright 2005 SYSNET International, Inc. 14 Java Web Services 7
Message Web Service Style XML passed to service Four supported method signatures: public Element[] method(element[] bodies); public SOAPBodyElement[] method(soapbodyelement[] bodies); public Document method(document body); public void method(soapenvelope req, SOAPEnvelope resp); Copyright 2005 SYSNET International, Inc. 15 Axis Architecture: MessageContext MessageContext provides a uniform context in the processing of chains of handlers Request Message Properties Response Message Hard-wired properties Copyright 2005 SYSNET International, Inc. 16 Java Web Services 8
Axis Architecture: Handlers Concept of Handler is central to the extensible architecture of Axis public interface Handler extends Serializable { public void init(); public void cleanup(); public void invoke(messagecontext msgcontext) throws AxisFault; } Copyright 2005 SYSNET International, Inc. 17 Axis Architecture: Handler Example init() method from LogHandler: public void init() { super.init(); } Object opt = this.getoption("loghandler.writetoconsole"); if (opt!= null && opt instanceof String && "true".equalsignorecase((string)opt)) writetoconsole = true; opt = this.getoption("loghandler.filename"); if (opt!= null && opt instanceof String) filename = (String)opt; Copyright 2005 SYSNET International, Inc. 18 Java Web Services 9
Axis Architecture: Handler Example invoke() method from LogHandler: public void invoke(messagecontext msgcontext) throws AxisFault { log.debug("enter: LogHandler::invoke"); if (msgcontext.getpastpivot() == false) { start = System.currentTimeMillis(); } else { logmessages(msgcontext); } log.debug("exit: LogHandler::invoke"); } Copyright 2005 SYSNET International, Inc. 19 Axis Architecture: Simple Chains Simple Chains: a sequence of one or more handlers that should be processed in sequence Handler 1 Handler 2 Copyright 2005 SYSNET International, Inc. 20 Java Web Services 10
Axis Architecture: Targeted Chain Targeted Chain: special purpose chain that consists of a request handler, a pivot handler and a response handler Request Handler Pivot Handler Response Handler Copyright 2005 SYSNET International, Inc. 21 Axis Architecture: Server-Side Processing Copyright 2005 SYSNET International, Inc. 22 Java Web Services 11
Example Axis Server Configuration Global Configuration section <globalconfiguration> <parameter name="disableprettyxml" value="true"/> <requestflow> <handler type="java:org.apache.axis.handlers.jwshandler"> <parameter name="scope" value="session"/> </handler> <handler type="java:org.apache.axis.handlers.jwshandler"> <parameter name="scope" value="request"/> <parameter name="extension" value=".jwr"/> </handler> </requestflow> <responseflow/> </globalconfiguration> Copyright 2005 SYSNET International, Inc. 23 Example Axis Server Configuration Service section <service name="adminservice" provider="java:msg"> <namespace>http://xml.apache.org/axis/wsdd/</namespace> <parameter name="allowedmethods" value="adminservice"/> <parameter name="enableremoteadmin" value="false"/> <parameter name="classname" value="org.apache.axis.utils.admin"/> </service> Copyright 2005 SYSNET International, Inc. 24 Java Web Services 12
Axis Architecture: Client-Side Processing Copyright 2005 SYSNET International, Inc. 25 JWS: Instant Deployment Drop-and-play style deployment Axis locates, compiles and invokes the service as needed URL for following service is: http://localhost:8080/axis/calculator.jws % copy Calculator.java <webapp-root>/axis/calculator.jws Copyright 2005 SYSNET International, Inc. 26 Java Web Services 13
Deployment via Descriptors For more deployment control use the deployment descriptors in wsdd file. Can specify scoping, handlers and chains and custom encoders/decoders <deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"> <service name="myservice" provider="java:rpc"> <parameter name="classname" value="samples.userguide.example3.myservice"/> <parameter name="allowedmethods" value="*"/> </service> </deployment> Copyright 2005 SYSNET International, Inc. 27 XML/Java Type Mapping Support for basic data types All XML schema data-types map to their reasonable Java equivalent types Support for Java Collections Some Java collections are supported but interop is limited Support for Java Beans Support is built-into Axis through BeanSerializer Support for custom data type serialization/deserialization Copyright 2005 SYSNET International, Inc. 28 Java Web Services 14
Custom Serialization 1. Develop the custom serializer/deserializer (implement Serializer/Deserializer interfaces) 2. Register type mapping through deployment descriptor <typemapping qname="ns:local" xmlns:ns="somenamespace" languagespecifictype="java:my.java.thingy" serializer="my.java.serializerfactory" deserializer="my.java.deserializerfactory" encodingstyle="http://schemas.xmlsoap.org/soap/enco ding/"/> Copyright 2005 SYSNET International, Inc. 29 Supported Transports HTTP JMS Mail (SMTP/POP3) Java Copyright 2005 SYSNET International, Inc. 30 Java Web Services 15
Monitoring SOAP messages tcpmon % java org.apache.axis.utils.tcpmon [listenport targethost targetport] Copyright 2005 SYSNET International, Inc. 31 UDDI and juddi Copyright 2005 SYSNET International, Inc. 32 Java Web Services 16
UDDI and SOA The registry is central to the SOA architecture SOA Registry Publish Find Service Provider Bind Service Consumer Copyright 2005 SYSNET International, Inc. 33 UDDI History Originally defined for the purpose of providing a public business and service registry First few versions came out through UDDI.org UDDI v3.0 is an OASIS standard Currently private registries are more popular in support of SOA-based applications Copyright 2005 SYSNET International, Inc. 34 Java Web Services 17
UDDI Scenarios Design time use Developer searches through the private registry for existing services that can take part in an orchestrated application Interest is in the functionality but not the specific instances Run time use Application searches through the private registry for the service but focus is now on implementations of it Copyright 2005 SYSNET International, Inc. 35 UDDI Categorization To support searching across a number of dimensions, UDDI allows for categorization Includes a number of built-in schemes: North American Industry Classification System (NAICS) Universal Standard Products and Services Classification (UNSPSC) ISO 3166 for geographic location classification <categorybag> <keyedreference keyname= Custom Software Services keyvalue= 54133 tmodelkey= uuid:c0b9fe13-179f-413d-8a5b-5004db8e5bb2 /> Copyright 2005 SYSNET International, Inc. 36 Java Web Services 18
UDDI Datatypes businessentity: represents any provider of a service. Includes name, description, contact information. It can be categorized with multiple keyreferences businessservice: represents a single service that is owned by a single businessentity. It can be categorized with multiple keyreferences bindingtemplate: describes the technical information about a deployed implementation of a web services. Includes an access point and a reference to a tmodel. Copyright 2005 SYSNET International, Inc. 37 UDDI Datatypes (cont.) tmodel: Used in many different different ways in UDDI. Used for representing value sets such as identification and categorization systems Used to define the technical interface of a web service publisherassertion: represents an association between two business entities. Copyright 2005 SYSNET International, Inc. 38 Java Web Services 19
Using UDDI A UDDI registry is exposed as a web service UDDI Inquiry API: defines find and get operations against the registry UDDI Publication API: defines operations for adding, updating and removing content from the registry Clients can be developed: UDDI4J: open source Java API JAX-RPC: a client application can be generated via the WSDL JAXR: standard API for access to registries such as ebxml and UDDI. Copyright 2005 SYSNET International, Inc. 39 juddi Architecture Is implemented as a J2EE web application so can be deployed on any J2EE web container Requires an external database for persisting the entries of the registry Scripts are included for various standard RDBMS Provides default authenticator but includes a pluggable-interface that will allow integration into existing authentication scheme Provide default UUID generator Copyright 2005 SYSNET International, Inc. 40 Java Web Services 20
juddi Architecture Sequence diagram of request processing Copyright 2005 SYSNET International, Inc. 41 Installation Configure juddi (juddi.properties) Specify and configure DataSource juddi.datasource=java:comp/env/jdbc/juddidb Configure API URLs juddi.proxy.inquiryurl=http://localhost:8080/juddi/inquiry Configure Authenticator Module Configure UUIDGen Module Copy juddi.war to the web containers deployment directory Copyright 2005 SYSNET International, Inc. 42 Java Web Services 21
Using juddi Copyright 2005 SYSNET International, Inc. 43 WSDL to UDDI mapping Copyright 2005 SYSNET International, Inc. 44 Java Web Services 22
Using juddi through UDDI4j Configure the proxy UDDIProxy proxy = new UDDIProxy(); proxy.setinquiryurl("http://localhost:8080/juddi/inquiry"); proxy.setpublishurl("https://localhost:8080/juddi/publish ); Find a business BusinessList bl = proxy.find_business( sysnet", null, 0); Copyright 2005 SYSNET International, Inc. 45 WS-Addressing Copyright 2005 SYSNET International, Inc. 46 Java Web Services 23
Why do we need Addressing? To find a Web Service you need a URL. Simple right? Address the web service with the URL, set the action in the HTTP headers and you are set. How about intermediaries? How about SOAP over non-http protocol? How about dynamically generated web services? Copyright 2005 SYSNET International, Inc. 47 Basic Concepts: Endpoint References Endpoint references: Dynamic generation and customization of service endpoint descriptions. Referencing and description of specific service instances that are created as the result of stateful interactions. Flexible and dynamic exchange of endpoint information in tightly coupled environments where communicating parties share a set of common assumptions about specific policies or protocols that are used during the interaction. Copyright 2005 SYSNET International, Inc. 48 Java Web Services 24
Endpoint Reference Definition An Endpoint Reference consists of: Address: is a URI and identifies the address of the endpoint ReferenceParameters: XML elements that are necessary in order to successfully interact with the web service Metadata: provides an extensible container for metadata that describes the endpoint <wsa:endpointreference xmlns:wsa="http://www.w3.org/2005/03/addressing"> <wsa:address>http://example.com/fabrikam/acct</wsa:address> </wsa:endpointreference> Copyright 2005 SYSNET International, Inc. 49 Message Information Headers Message Information Headers: headers to allow messages to be addressed to an endpoint all within the SOAP message. To: The URL of the target service <wsa:to>http://localhost/myservicetest</wsa:to> From: The ERP of the message s sender. <wsa:from> <wsa:address>http://localhost/yourservice</wsa:address> </wsa:from> Copyright 2005 SYSNET International, Inc. 50 Java Web Services 25
Message Information Headers ReplyTo: The ERP to which the response should be sent to. FaultTo: The ERP to which the SOAP fault should be sent to. MessageID: Is a URI that uniquely identifies the message Action: Takes the place of the SOAPAction RelatesTo: Element that indicates the MessageID of the caller. Copyright 2005 SYSNET International, Inc. 51 Axis WS-Addressing Implementation Originally implemented as a pair of Axis handlers (client-side and server-side) Now also includes a pair of JAX-RPC handlers thereby reducing dependency on Axis Current implementation is a little behind the current spec Copyright 2005 SYSNET International, Inc. 52 Java Web Services 26
Using Axis WS-Addressing Client-side example from docs. private static AddressingHeaders setupaddressing() throws Exception { AddressingHeaders headers = new AddressingHeaders(); Action a = new Action(new URI("urn:action")); headers.setaction(a); EndpointReference epr = new EndpointReference("http://www.apache.org"); headers.setfaultto(epr); return headers; } Copyright 2005 SYSNET International, Inc. 53 Using Axis WS-Addressing (cont.) Client-side example from docs. public static void main(string[] args) throws Exception { Service service = new Service(); Call call = (Call) service.createcall(); AddressingHeaders headers = setupaddressing(); call.setproperty(constants.env_addressing_request_headers, headers); call.settargetendpointaddress(new java.net.url(url)); call.setoperationname(new QName( "http://localhost:8080/axis/services/version", "getversion")); String ret = (String) call.invoke(new Object[] {}); System.out.println("Sent 'Hello!', got '" + ret + "'"); } Copyright 2005 SYSNET International, Inc. 54 Java Web Services 27
WS-Addressing Deployment Axis addressing deployment descript <?xml version="1.0" encoding="utf-8"?> <deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"> <handler name="addr" type="java:org.apache.axis.message.addressing.handler.addressinghandler" /> <service name="addressedversion" provider="java:rpc"> <requestflow> <handler type="addr"/> </requestflow> <responseflow> <handler type="addr"/> </responseflow> <parameter name="allowedmethods" value="getversion"/> <parameter name="classname" value="org.apache.axis.version"/> </service> </deployment> Copyright 2005 SYSNET International, Inc. 55 WS-Reliable Messaging Copyright 2005 SYSNET International, Inc. 56 Java Web Services 28
Why do we need Reliable Messaging? Network failures may prevent messages from being delivered Middleware failures may cause messages from being delivered Intermittent failures may cause duplicates Routing delays may cause out of order delivery Copyright 2005 SYSNET International, Inc. 57 WS-Reliable Messaging Concepts Sequence: reliable messaging is enforced within the context of a sequence between two endpoints Acknowledgments: an ack from the server indicates the sequence range of messages received Delivery Assurance Policy: endpoints can negotiate the delivery policy Copyright 2005 SYSNET International, Inc. 58 Java Web Services 29
Reliable Messaging Model Initial Sender Ultimate Receiver Application Source Application Source Send Delivery RM Source Transmit Acknowledge RM Destination Receive Copyright 2005 SYSNET International, Inc. 59 Reliable Messaging Protocol Endpoint A Create Sequence Create Sequence Response (Identifier) Sequence (Identifier, MessageNumber=1) Sequence (Identifier, MessageNumber=2) Sequence (Identifier, MessageNumber=3, LastMessage) Sequence Ack. (Identifier, Range=1,3) Sequence (Identifier, MessageNumber=2) Sequence Ack. (Identifier, Range=1..3) Terminate Sequence Endpoint B Copyright 2005 SYSNET International, Inc. 60 Java Web Services 30
Sequence Message <wsrm:sequence...> <wsu:identifier> [URI] </wsu:identifier> <wsrm:messagenumber> [unsignedlong] </wsrm:messagenumber> <wsrm:lastmessage/>? <wsu:expires> [datetime] </wsu:expires>?... </wsrm:sequence> Copyright 2005 SYSNET International, Inc. 61 Sequence Example <wsrm:sequence> <wsu:identifier> http://fabrikam123.com/abc </wsu:identifier> <wsrm:messagenumber>10</wsrm:messagenumber> <wsrm:lastmessage/> </wsrm:sequence> Copyright 2005 SYSNET International, Inc. 62 Java Web Services 31
Sequence Acknowledgement <wsrm:sequenceacknowledgement...> <wsu:identifier> [URI] </wsu:identifier> [ <wsrm:acknowledgementrange... Upper="[unsignedLong]" Lower="[unsignedLong]"/> + <wsrm:nack>[unsignedlong]</wsrm:nack> + ]... <wsrm:sequenceacknowledgement> Copyright 2005 SYSNET International, Inc. 63 Sequence Ack Example <wsrm:sequenceacknowledgement> <wsu:identifier> http://fabrikam123.com/abc </wsu:identifier> <wsrm:acknowledgementrange Upper="2" Lower="1"/> <wsrm:acknowledgementrange Upper="6" Lower="4"/> <wsrm:acknowledgementrange Upper="10" Lower="8"/> </wsrm:sequenceacknowledgement> Copyright 2005 SYSNET International, Inc. 64 Java Web Services 32
Create Sequence Message Request <wsrm:createsequence...>... </wsrm:createsequence> Response <wsrm:createsequenceresponse...> <wsu:identifier> [URI] </wsu:identifier>... </wsrm:createsequenceresponse> Copyright 2005 SYSNET International, Inc. 65 Sequence Termination <wsrm:terminatesequence...> <wsu:identifier> [URI] </wsu:identifier>... </wsrm:terminatesequence> Copyright 2005 SYSNET International, Inc. 66 Java Web Services 33
Sandesha Architecture High-level architecture of Sandesha Copyright 2005 SYSNET International, Inc. 67 Sandesha Architecture on Axis Interaction between the Sandesha Architecture and Axis Copyright 2005 SYSNET International, Inc. 68 Java Web Services 34
Using Sandesha on the Client public static void main(string[] args) { try { Service service = new Service(); Call call = (Call) service.createcall(); SandeshaContext ctx = new SandeshaContext(); ctx.addnewsequececontext(call, targeturl, "urn:wsrm:echostring",constants.clientproperties.in_out); call.setoperationname(new QName("http://tempuri.org/", "echostring")); call.addparameter("text", XMLType.XSD_STRING, ParameterMode.IN); call.addparameter("seq", XMLType.XSD_STRING, ParameterMode.IN); call.setreturntype(org.apache.axis.encoding.xmltype.xsd_string); ctx.setlastmessage(call); String ret = (String) call.invoke(new Object[] {"Sandesha Echo 1", "abcdef"}); System.out.println("The Response for First Messsage is :" + ret); ctx.endsequence(call); } catch (Exception e) { Copyright 2005 SYSNET International, Inc. 69 Synchronous Scenario Copyright 2005 SYSNET International, Inc. 70 Java Web Services 35
Transactions Copyright 2005 SYSNET International, Inc. 71 Why do we need Transactions? In an application based on an orchestration of Web Services all services involved in an operation must come to an undisputed resolution. Typical ACID semantics are useful for some but long-running transactions need different transactional support. Copyright 2005 SYSNET International, Inc. 72 Java Web Services 36
Atomic Transactions Atomicity: on completion either all actions or none are completed. Consistency: consistency in the system is preserved after processing multiple concurrent transactions Isolation: intermediate states of the system are not observable outside the transaction Durability: if a transaction commits, the changes are preserved even after a system failure Copyright 2005 SYSNET International, Inc. 73 Business Transactions Long-running transactions: transactions may take hours, days or weeks to complete Need to be able to select a subset of the original participants before a commit Compensating transactions: operations that are used to restore the state in case of a failure Copyright 2005 SYSNET International, Inc. 74 Java Web Services 37
Standards and scope WS-Coordination: allows a distributed system to establish a group of participants around an activity participants can register interest in participating in the outcome Coordination protocol can vary but operates upon completion of the activity WS-Atomic: Handles ACID transactions and defines variations of 2PC WS-Business Activity: Allows for the definition of nested scopes of operations Allows for the definition of compensating transactions Copyright 2005 SYSNET International, Inc. 75 Coordinator Copyright 2005 SYSNET International, Inc. 76 Java Web Services 38
Coordination Context Before services can participate in a transaction they need to establish a CoordinationContext. The response includes an identifier, an expiration time and an endpoint reference to the registration service. <soapenv:envelope xmlns:soapenv= http://schemas.xmlsoap.org/soap/envelope xmlns:wscoor= http://schemas.xmlsoap.org/ws/2002/09/wscoor > <soapenv:body> <wscoor:createcoordinationcontext> <wscoor:coordinationtype> http://schemas.xmlsoap.org/ws/2002/09/wsat </wscoor:coordinationtype> </wscoor:createcoordinationcontext> </soapenv:body> </soapenv:envelope> Copyright 2005 SYSNET International, Inc. 77 Interactions for Coordination Copyright 2005 SYSNET International, Inc. 78 Java Web Services 39
Kandula Goal is to provide complete support for: WS-Coordination WS-Atomic Transaction WS-Business Activity Currently provides support for WS-Coordination and part of WS-Atomic Transaction Provides interfaces between the web services tx context and the underlying service-specific context Copyright 2005 SYSNET International, Inc. 79 Using Kandula Copyright 2005 SYSNET International, Inc. 80 Java Web Services 40
Sequence of interactions Copyright 2005 SYSNET International, Inc. 81 References 1. The specifications of course 2. ws.apache.org 3. Web Services Platform Architecture, by Weerawarana, Curbera, Leymann, Storey and Ferguson, Prentice Hall, 2005 4. Building Web Services with Java, Graham, Davis, et al., Sams Publishing, 2005 Copyright 2005 SYSNET International, Inc. 82 Java Web Services 41
Conclusion Any questions? Copyright 2005 SYSNET International, Inc. 83 Java Web Services 42