Web Services Programming Java Web Services Programming Dickson
Web Services Programming Java Web Services Programming Dickson K. W. Chiu Ph. D, SMIEEE Deitel et al. , Java Web Services for Experienced Programmers 1
Java Web Services Development Pack (JWSDP) n n Now integrated into J 2 EE 1. 4 Provides a convenient all-in-one package Geared for developers Contains n n n n JAXP (Java API for XML Processing) JAX-RPC (Java API for XML-based RPC) SAAJ (SOAP with Attachments API for Java) JAXR (Java API for XML Registries) … JAXM (Java API for XML Messaging) See: http: //java. sun. com/webservices/ Dickson Chiu 2005 2
JAX-RPC and JAXM n n Both based on SOAP with Attachments For web service programming Sun recommends JAX-RPC – easier to program SAAJ / JAXM n n Interoperability (e. g. calling other clients) Non-blocking option Dickson Chiu 2005 3
JAX-RPC n n n Java™ API for XML-based RPC requests and responses represented using SOAP Both Web service endpoints and clients use JAXRPC Services are described using WSDL Key technology for Web Services in the upcoming J 2 EE 1. 4 platform Dickson Chiu 2005 4
Remote Procedure Call (RPC) RPC, COM, CORBA, RMI: n Synchronous communication - calling process blocks until there is a response n Tightly coupled - client must find recipients and know method arguments n Non persistent Dickson Chiu 2005 5
JAX-RPC Design Goal n Easy to use programming model n n Hides all the plumbing – complexity of SOAP messaging SOAP and WSDL-based interoperability n n Interoperate with any SOAP compliant peers Extensibility and Modularity n n Defining a service Using a service Support future versions of XML specification, i. e. , XMLP (SOAP 1. 2 and beyond) Message handler architecture Dickson Chiu 2005 6
JAX-RPC Architecture Diagram Dickson Chiu 2005 7
What happen during an RPC? n n n n To call a remote procedure, the Hello. Client program invokes a method on a stub, a local object that represents the remote service. The stub invokes routines in the JAX-RPC runtime system. The runtime system converts the remote method call into a SOAP message and then transmits the message as an HTTP request. When the server receives the HTTP request, the JAX-RPC runtime system extracts the SOAP message from the request and translates it into a method call. The JAX-RPC runtime system invokes the method on the tie object. The tie object invokes the method on the implementation of the Hello. World service. The runtime system on the server converts the method's response into a SOAP message and then transmits the message back to the client as an HTTP response. On the client, the JAX-RPC runtime system extracts the SOAP message from the HTTP response and then translates it into a method response for the Hello. Client program. Dickson Chiu 2005 8
What happen during an RPC? Dickson Chiu 2005 9
Service Description and WSDL JAX-RPC describes a Web Service as a collection of remote interfaces and methods Tools are used to convert between WSDL documents and sets of Java remote interfaces WSDL describes a Web Service as a collection of ports and operations n n n JAX-RPC service endpoint mapped to WSDL service description WSDL enables export of a JAX-RPC service endpoint across heterogeneous environments JAX-RPC specifies the standard WSDL<-> Java mapping: n n n Mapping between service endpoint interface and WSDL definitions Binding to specific protocol and transport XML <-> Java data types Dickson Chiu 2005 10
WSDL Mapping n n wsdl: port. Type mapped into a Java Interface (Service Definition Interface) that extends java. rmi. Remote wsdl: operation mapped into a method of the Service definition interface wsdl: message's are mapped into parameters of the method wsdl: type's of wsdl: message's are mapped into the types of the parameters Dickson Chiu 2005 11
WSDL Mapping Example <!---------- WSDL Document -------------------> <message name=”Get. Last. Trade. Price. Input”> <part name=”ticker. Symbol” type=”xsd: string”/> </message> <message name=”Get. Last. Trade. Price. Output”? <part name=”result” type=”xsd: float”/> </message> <port. Type name=”Stock. Quote. Provider”> <operation name=”Get. Last. Trade. Price” parameter. Order=”ticker. Symbol”> <input message=”tns: Get. Last. Trade. Price. Input”/> <output message=”tns: Get. Last. Trade. Price. Output”/> </operation> </port. Type> public interface Stock. Quote. Provider extends java. rmi. Remote { float get. Last. Trade. Price(String ticker. Symbol) throws java. rmi. Remote. Exception; } Dickson Chiu 2005 12
Supported Java Type See J 2 EE tutorial n Note: all objects are passed by copy n Java primitive types n String, Date, Calendar, Big. Integer, Big. Decimal n Multi-dimensional Java arrays n JAX-RPC value type – classes you’ve written for your applications, based on the above n Java. Bean Components – also based on the above Dickson Chiu 2005 13
Developing a JAX-RPC Web Service 1. 2. 3. 4. Define service endpoint Implement Service endpoint Compile code and generate WSDL Packaging WAR and deploy Dickson Chiu 2005 14
0. Setting the Port If you do not use the default port 8080, edit: n <INSTALL>/j 2 eetutorial 14/examples/common/build. properties n <INSTALL>/j 2 eetutorial 14/examples/jaxrpc/staticstub/ config-wsdl. xml n <INSTALL>/j 2 eetutorial 14/examples/jaxrpc/ dynamicproxy/config-wsdl. xml n <INSTALL>/j 2 eetutorial 14/examples/jaxrpc/appclient/ config-wsdl. xml n <INSTALL>/j 2 eetutorial 14/examples/jaxrpc/webclient/ config-wsdl. xml n <INSTALL>/j 2 eetutorial 14/examples/jaxrpc/ webclient/web/response. jsp n <INSTALL>/j 2 eetutorial 14/examples/security/ basicauthclient/Secure. Hello. wsdl n <INSTALL>/j 2 eetutorial 14/examples/security/ mutualauthclient/Secure. Hello. wsdl Dickson Chiu 2005 15
1. Service Endpoint Definition n Specified in Service Definition Interface n n n Could be generated from WSDL document using a tool or Could be written in Java programming language directly No assumption about type of client that would use this service definition interface package hello; import java. rmi. Remote. Exception; public interface Hello. IF extends Remote { public String say. Hello(String s) throws Remote. Exception; } Dickson Chiu 2005 16
2. Service Implementation n n Service implementation class is an ordinary Java class Invocation done inside the servlet container n n n JAX-RPC defines Servlet-based Endpoint model Other endpoint models (e. g. , stateless session beans) will be defined in J 2 EE 1. 4 / EJB 2. 1 Optional Service. Lifecycle interface for initialization and destruction callbacks package hello; public class Hello. Impl implements Hello. IF { public String message = new String("Hello "); public String say. Hello(String s) { package hello; return new String(message + s); import java. rmi. Remote. Exception; } public interface Hello. IF extends } Remote { } Dickson Chiu 2005 public String say. Hello(String s) throws Remote. Exception; 17
3. Compiling / WSDL generation n n Use the ant tool simplifies the job Compile Hello. IF. java and Hello. Impl. java, go to the <INSTALL>/j 2 eetutorial 14/examples/jaxrpc/helloservice/ directory and type the following: ant build n n n compile-service: compiles Hello. IF. java and Hello. Impl. java, writing the class files to the build subdirectory generate-wsdl: runs wscompile, creating My. Hello. Service. wsdl and mapping. xml Customize wsdl generation with config-interface. xml <? xml version="1. 0" encoding="UTF-8"? > <configuration xmlns="http: //java. sun. com/xml/ns/jax-rpc/ri/config"> <service name="My. Hello. Service" target. Namespace="urn: Foo" type. Namespace="urn: Foo" package. Name="helloservice"> <interface name="helloservice. Hello. IF"/> </service> </configuration> Dickson Chiu 2005 18
4. Packaging the WAR file (i) n Use Deploytool to create a standalone WAR module Dickson Chiu 2005 19
4. Packaging the WAR file (ii) n Use Deploytool to create a standalone WAR module Dickson Chiu 2005 20
4. Packaging the WAR file (iii) n n Enter context root Add alias “hello” Update the endpoint address to hello (see previous slide) Save and Deploy Dickson Chiu 2005 21
4’. Another way to deploy the WAR file n To create the WAR file that contains the service code: n n asant create-war Set your admin port, username, and password in <INSTALL>/j 2 eetutorial 14/examples/common/build. properties. n To deploy the WAR file: n n asant deploy-war Note this may create different naming Dickson Chiu 2005 22
JAX-RPC Clients n n n Independent of how an XML based RPC service (service endpoint) is implemented on the server side Generates a Java based client side representation for a service from WSDL document Not tied to a specific XML based protocol, transport or any JAX-RPC implementation specific mechanism Can use either J 2 SE or J 2 EE 3 programming modes: n n n Static stub-based – least dynamic, easiest to program - you know everything about the services and pre-generate the stub Dynamic proxy - call location dynamic (URL/service/name), information about the service by looking up WSDL document at run time (but signature of method fixed) Dynamic invocation interface (DII) – everything dynamic, but more tedious and more time to set up a call Dickson Chiu 2005 23
WSDL Generated <? xml version="1. 0" encoding="UTF-8"? > <definitions name="My. Hello. Service" target. Namespace="urn: Foo" xmlns: tns="urn: Foo" xmlns="http: //schemas. xmlsoap. org/wsdl/" xmlns: xsd="http: //www. w 3. org/2001/XMLSchema" xmlns: soap="http: //schemas. xmlsoap. org/wsdl/soap/"> <types/> <message name="Hello. IF_say. Hello"> <part name="String_1" type="xsd: string"/></message> <message name="Hello. IF_say. Hello. Response"> <part name="result" type="xsd: string"/></message> <port. Type name="Hello. IF"> <operation name="say. Hello" parameter. Order="String_1"> <input message="tns: Hello. IF_say. Hello"/> <output message="tns: Hello. IF_say. Hello. Response"/></operation></port. Type> <binding name="Hello. IFBinding" type="tns: Hello. IF"> <soap: binding transport="http: //schemas. xmlsoap. org/soap/http" style="rpc"/> <operation name="say. Hello"> <soap: operation soap. Action=""/> <input> <soap: body encoding. Style="http: //schemas. xmlsoap. org/soap/encoding/" use="encoded" namespace="urn: Foo"/></input> <output> <soap: body encoding. Style="http: //schemas. xmlsoap. org/soap/encoding/" use="encoded" namespace="urn: Foo"/></output></operation></binding> <service name="My. Hello. Service"> <port name="Hello. IFPort" binding="tns: Hello. IFBinding"> <soap: address location="REPLACE_WITH_ACTUAL_URL"/></port></service></definitions> Dickson Chiu 2005 24
WSDL Mapping - binding, port, service n n n wsdl: service is mapped into an implementation of javax. xml. rpc. Service interface JAX-RPC runtime provides the implementation A javax. xml. rpc. Service class acts as a factory of either n n n Instance of a generated stub class Dynamic proxy for a service port Instance of the object javax. xml. rpc. Call for the dynamic invocation of a remote operation on a service port Dickson Chiu 2005 25
Static Stub - Client Code package staticstub; import javax. xml. rpc. Stub; Generated by wscompile before public class Hello. Client { writing this program (i. e. , static private String endpoint. Address; and implementation-specific) public static void main(String[] args) { System. out. println("Endpoint address = " + args[0]); try { Stub stub = (Stub) (new My. Hello. Service_Impl(). get. Hello. IFPort()); stub. _set. Property(javax. xml. rpc. Stub. ENDPOINT_ADDRESS_ PROPERTY, args[0]); Hello. IF hello = (Hello. IF) stub; System. out. println(hello. say. Hello("Duke!")); } catch (Exception ex) { ex. print. Stack. Trace(); } } } // output – “Hello Duke!” Dickson Chiu 2005 26
Static Stub – build and run n To automate the rest of the steps, go to the <INSTALL>/j 2 eetutorial 14/examples/jaxrpc/staticstub/ directory and type the following: asant build n n generate-stubs: wscompile -gen: client -d build -classpath build config-wsdl. xml <configuration xmlns="http: //java. sun. com/xml/ns/jaxrpc/ri/config"> <wsdl location="http: //localhost: 8080/hellojaxrpc/hello? WSDL“ package. Name="staticstub"/> </configuration> compile-client: compiles src/Hello. Client. java and writes the class file to the build subdirectory. package-client: packages the files created by the generate-stubs and compile-client tasks into the dist/client. jar file. Run the client - asant run Dickson Chiu 2005 27
Dynamic Proxy-based Client n Client calls a remote procedure through a dynamic proxy n n n Client gets information about the service by looking up its WSDL document at runtime - call location (URL/service/name) But the signature (parameters and their types) of the method is fixed The Service class that is created during runtime Similar usage of asant However, only the service endpoint interface class of the sample target is used but not the generated stub Dickson Chiu 2005 28
Example Dynamic Proxy-based Client package dynamicproxy; Service. Factory service. Factory = Service. Factory. new. Instance(); import java. net. URL; import javax. xml. rpc. Service; import javax. xml. rpc. JAXRPCException; import javax. xml. namespace. QName; import javax. xml. rpc. Service. Factory; import dynamicproxy. Hello. IF; Service hello. Service = service. Factory. create. Service(hello. Wsdl. Url, new QName(name. Space. Uri, service. Name)); dynamicproxy. Hello. IF my. Proxy = (dynamicproxy. Hello. IF) hello. Service. get. Port (new QName(name. Space. Uri, port. Name), dynamicproxy. Hello. IF. class); public class Hello. Client { public static void main(String[] args) { try { String Url. String = args[0] + "? WSDL"; String name. Space. Uri = "urn: Foo"; String service. Name = "My. Hello. Service"; String port. Name = "Hello. IFPort"; System. out. println("Url. String = " + Url. String); System. out. println(my. Proxy. say. Hello(“Buzz”)); } catch (Exception ex) { ex. print. Stack. Trace(); } } } URL hello. Wsdl. Url = new URL(Url. String); Dickson Chiu 2005 29
Dynamic Invocation Interface (DII) Client n n n Dynamic invocation of an operation on the target service endpoint Enables broker model Client finds (through search criteria) from a UDDI directory and invokes a service during runtime through a broker n n n Note: the code in the following example does not show the lookup and simply hardcode the services in strings Used when service definition interface is not known until runtime Set all operation and parameters during runtime From the Service object create Call object first Similar usage of asant Dickson Chiu 2005 30
DII Client Example package dii; import javax. xml. rpc. Call; import javax. xml. rpc. Service; import javax. xml. rpc. JAXRPCException; import javax. xml. namespace. QName; import javax. xml. rpc. Service. Factory; import javax. xml. rpc. Parameter. Mode; Service. Factory factory = Service. Factory. new. Instance(); Service service = factory. create. Service(new QName(qname. Service)); QName port = new QName(qname. Port); Call call = service. create. Call(port); call. set. Target. Endpoint. Address(args[0]); call. set. Property(Call. SOAPACTION_USE_PROPERTY, new Boolean(true)); call. set. Property(Call. SOAPACTION_URI_PROPERTY, ""); call. set. Property(ENCODING_STYLE_PROPERTY, URI_ENCODING); public class Hello. Client { private static String qname. Service = "My. Hello. Service"; private static String qname. Port = "Hello. IF"; private static String BODY_NAMESPACE_VALUE = QName QNAME_TYPE_STRING = new QName(NS_XSD, "urn: Foo"; "string"); private static String ENCODING_STYLE_PROPERTY call. set. Return. Type(QNAME_TYPE_STRING); = call. set. Operation. Name(new "javax. xml. rpc. encodingstyle. namespace. uri"; QName(BODY_NAMESPACE_VALUE, "say. Hello")); private static String NS_XSD = call. add. Parameter(“String_1”, QNAME_TYPE_STRING, "http: //www. w 3. org/2001/XMLSchema"; Parameter. Mode. IN); private static String URI_ENCODING = String[] params = { "Murph!" }; "http: //schemas. xmlsoap. org/soap/encoding/"; String result = (String) call. invoke(params); System. out. println(result); public static void main(String[] args) { } catch (Exception ex) { System. out. println("Endpoint address = " + ex. print. Stack. Trace(); args[0]); } } } Dickson Chiu 2005 31
JAXM n n n Java API for XML Messaging Java support for sending and receiving SOAP XML document oriented messages Two JAXM API Programming Models n n n Point-to-point model – simpler JAXM Provider-based" (like a "messaging server") model supports Asynchronous messaging Design Goals n n Build on SOAP with Attachments Add support to plug higher-level messaging protocols (e. g. , eb. XML) Design for easy porting of applications from one container to another – specifically from web containers to that of J 2 EE Don’t attempt to build a full-fledged messaging API (e. g. , JMS) Dickson Chiu 2005 32
JAXM Point-to-Point Model n n n Synchronous Request-response interaction Calling process blocks until there is a response Connection established directly to the ultimate recipient n n No persistence can be difficult to scale Dickson Chiu 2005 33
JAXM Provider Model n n Asynchronous (or Synchronous you choose) Sender is not blocked, Receiver does not have to be available Reliable - Message can be stored and forwarded (routed) until it can be delivered JAXM Provider works behind the scene Dickson Chiu 2005 34
JAXM Provider n n n Offers message routing and reliable messaging as all messages go through it Assign message identifiers and keeping track of messages JAXM client makes JAXM method calls, and the provider (working with container) makes everything happen JAXM providers are responsible for producing an error message and sending it to the offending JAXM client when receiving a malformed message Responsibility of JAXM application to consume error messages and take corrective actions Dickson Chiu 2005 35
JAXM client Not using JAXM provider n n n Using JAXM provider Just a standalone J 2 SE n Maintains a connection with application JAXM provider, and all messages go through the Point to point operation provider Establishes a connection directly with the service n JAXM client deployed in a web or EJB container (using a URL) n Message. Driven. Bean Synchronous only n JAXMServlet Request/response n Send and receive messages interaction synchronously or asynchronously Dickson Chiu 2005 36
JAXM vs. JMS Differences n JAXM provider could be lightweight while JMS provider is usually heavyweight n JAXM supports standalone mode while JMS does not n JAXM client is interoperable over any SOAP compatible client while JMS client is interoperable only with other JMS client over the same messaging system n Delivery endpoint model is different Similarities n Both supports Messaging Provider model n n n Reliable, secure message delivery Routing Both supports asynchronous message delivery Dickson Chiu 2005 37
Using SAAJ API to call a Web Service n Steps 1. 2. 3. 4. 5. 6. n n n Create SOAP message Populate SOAP message Add attachments (optional) Initialize SOAP connection Send SOAP message Analyze response message Code based on J 2 EE tutorial p. 398 request. java Library files required: H: /Sun/Appserver/lib/j 2 ee. jar; H: /Sun/Appserver/lib/saajimpl. jar; H: SunApp. Serverlibendorsedxerces. Impl. jar; H: SunApp. Serverlibendorseddom. jar; . Example based on URL: n http: //www. mindreef. net/tide/scopeit/start. do? referer=xmethods&url=http : //services. xmethods. net/soap/urn: xmethods-delayed-quotes. wsdl Dickson Chiu 2005 38
SAAJ Example Code import javax. xml. soap. *; import java. util. *; import java. net. URL; public class Request { public static void main(String[] args) { try { SOAPConnection. Factory soap. Connection. Factory = SOAPConnection. Factory. new. Instance(); SOAPConnection connection = soap. Connection. Factory. create. Connection(); SOAPFactory soap. Factory = SOAPFactory. new. Instance(); Message. Factory factory = Message. Factory. new. Instance(); SOAPMessage message = factory. create. Message(); SOAPHeader header = message. get. SOAPHeader(); SOAPBody body = message. get. SOAPBody(); header. detach. Node(); Dickson Chiu 2005 39
SAAJ Example Code (2) Name body. Name = soap. Factory. create. Name( "get. Quote", "m", "urn: xmethods-delayed-quotes"); SOAPBody. Element body. Element = body. add. Body. Element(body. Name); Name name = soap. Factory. create. Name("symbol"); SOAPElement symbol = body. Element. add. Child. Element(name); symbol. add. Text. Node(args[0]); URL endpoint = new URL("http: //64. 124. 140. 30: 9090/soap"); SOAPMessage response = connection. call(message, endpoint); connection. close(); <SOAP-ENV: Envelope xmlns: SOAP-ENV= response. write. To(System. out); } catch (Exception ex) { ex. print. Stack. Trace(); } } } "http: //schemas. xmlsoap. org/soap/envelope/"> <SOAP-ENV: Body> <m: get. Quote xmlns: m=" urn: xmethods-delayedquotes"> <symbol>XXXX</symbol> </m: get. Quote> </SOAP-ENV: Body> </SOAP-ENV: Envelope> Dickson Chiu 2005 40
SAAJ Result Message <soap: Envelope soap: encoding. Style="http: //schemas. xmlsoap. org/soap/encoding/" xmlns: soap="http: //schemas. xmlsoap. org/soap/envelope/" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xmlns: xsd="http: //www. w 3. org/2001/XMLSchema" xmlns: soapenc="http: //schemas. xmlsoap. org/soap/encoding/"> <soap: Body> <n: get. Quote. Response xmlns: n="urn: xmethods-delayed-quotes"> <Result xsi: type="xsd: float">4. 15</Result> </n: get. Quote. Response> </soap: Body> </soap: Envelope> Dickson Chiu 2005 41
Adding Attachment with SAAJ // We're using a HTTP image repository here // to get the data for an image URL url = new URL ("http: //images. wombats. com/w. jpg"); // Create a JAF Data. Handler with this URL Data. Handler dh = new Data. Handler(url); // Create and Add an Attachment. Part message. add. Attachment. Part( message. create. Attachment. Part(dh)); Dickson Chiu 2005 42
Summary – Calling Web Services in Java n Use JAX-RPC n n Static Stub – you know everything about the services and pre-generate the stub Dynamic Proxy – call location dynamic (URL/service/name), information about the service by looking up WSDL document at run time (but signature of method fixed) DII – everything lookup at run time, i. e. , call and parameters prepared at runtime Send SOAP messages with SAAJ n n for most flexibility target is not RPC Dickson Chiu 2005 43
- Slides: 43