Web Services Programming Java Web Services Programming 1
Web Services Programming Java Web Services Programming 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 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) … Dickson Chiu 2005 CSIT 600 c p 1 -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
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
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
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
JAX-RPC Architecture Diagram
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.
What happen during an RPC?
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 CSIT 600 c p 1 -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
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; }
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 CSIT 00 c p 1 -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
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 CSIT 600 c p 115
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; }
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 { } public String say. Hello(String s) throws Remote. Exception;
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>
4. Packaging the WAR file (i) n Use Deploytool to create a standalone WAR module
4. Packaging the WAR file (ii) n Use Deploytool to create a standalone WAR module Dickson Chiu 2005 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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 CSIT 600 c p 1 -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
JAXB Java Architecture for XML Binding
Outline n n n What is JAXB? Benefits of JAXB Implementation Components Goals of JAXB Binding Process Demo
JAXB Overview n n n JAXB provides an easy way to bind XML schemas to Java representations. JAXB makes it easy to incorporate XML functions into Java applications without having to know much about the particulars of XML. The binding framework facilitates the unmarshalling of XML documents into Java content trees and vice versa.
General JAXB Overview
Isolating the Binding from the Implementation process provides some benefits: n n n The size of the JAXB binding implementation is small and efficient as compared to SAX and DOM. One could focus on writing schemas and generating JAXB packages which could be shared among different applications. JAXB bindings can be customized to suit the users’ particular needs e. g. customizing package, interface or property names.
Goals of JAXB n n Makes it easier to use Java applications to read, process and output XML data. Provides flexible, extensible, platform-neutral formats and protocols for structuring and exchanging information. Easy to access and modify XML documents within Java programs. Ability to customize the binding of existing schema to Java representations
…Goals and Uses of JAXB n n Portability &Provide clean “round-tripping”. Access configuration values from a properties file stored in XML format. Create tools to manipulate configuration properties file represented in XML format. Update data received in the form of XML document without having to write SAX event handlers.
Core JAXB Components
Core Components of JAXB Implementation • • XML Schema Binding Declarations Binding Compiler Binding Framework Implementation Schema-Derived Classes Java Application XML Input Documents XML Output Documents
JAXB Binding Process
Steps in the JAXB Binding Process n n n n Generate Classes Compile Classes Unmarshal Generate Content Tree Validate (Optional) Process Content Marshal
The Java Architecture For XML Binding (JAXB)
Motivation for JAXB n The main purpose of XML Schema is: n n Validation of XML documents Any other purposes? n n Hint 1: determinism requirement Hint 2: the “default” attribute has nothing to do with validation <xs: attribute name="country" use=“optional” default="Israel“ /> n Answer: Given a valid XML document, its schema defines a unique data model
Motivation for JAXB n n Problem: How to manipulate this data model? DOM (data object model) solution: n n Pros: simple, general (a schema is not even required) Cons: no types, no compile-time checking DOM pseudo-code example root. get. Child("Address"). get. Child("Number"). get. Te xt()n I wish to write … returns a string root. get. Address(). get. Number() returns a number
JAXB solution: Mapping XML Schema to Java interfaces Binding Compiler Source schema Java interfaces Pros: preserve types, compile-time checking Cons: complex, specific to a certain schema
<xs: complex. Type name="Address. Type"> <xs: sequence> <xs: element name="Number" type="xs: unsigned. Int"/> <xs: element name="Street" type="xs: string"/> </xs: sequence> Binding Compiler </xs: complex. Type> public interface Address. Type { long get. Number(); void set. Number(long value); } String get. Street(); void set. Street(String value); Must be nonnegative Must be non-null
Talk Outline n How is XML Schema mapped to Java interfaces? n n What is the default mapping? How to customize this mapping? Second part of the lecture How do I use those Java interfaces? n Next slides and a Demo!
Main Features n n n Unmarshal: xml objects Create / Read / Update / Delete objects Validate objects Marshal: objects xml No roundtrip guarantees n n n Marshal( Unmarshal(xml) ) ≠ xml We found that order is not always preserved But usually roundtrip holds
Step 1: Create XML Schema Demo. xsd <xs: element name="Person" type="Person. Type"/> <xs: complex. Type name="Person. Type"> <xs: sequence> <xs: element name=“Name" type="xs: string"/> <xs: element name="Address" type="Address. Type" min. Occurs="1" max. Occurs="unbounded"/> </xs: sequence> </xs: complex. Type> <xs: complex. Type name="Address. Type"> <xs: sequence> <xs: element name="Number" type="xs: unsigned. Int"/> <xs: element name="Street" type="xs: string"/> </xs: sequence> </xs: complex. Type>
Step 2: Create XML Document Demo. xml <Person xmlns: xsi="http: //www. w 3. org/2001/XMLSchemainstance" xsi: no. Namespace. Schema. Location="C: JAXB Demodemo. xsd"> <Name>Sharon Krisher</Name> <Address> <Street>Iben Gevirol</Street> <Number>57</Number> </Address> <Address> Check that your XML conforms to the Schema <Street>Moshe Sharet</Street>
Step 3: Run the binding compiler n %JWSDP_HOME%jaxbbinxjc -p demo. xsd n A package named demo is created n (in the directory demo) The package contains (among other things): n n interface Address. Type interface Person. Type
Address. Type and Person. Type public interface Address. Type { long get. Number(); void set. Number(long value); String get. Street(); void set. Street(String value); } public interface Person. Type { String get. Name(); void set. Name(String value); /* List of Address. Type */ java. util. List get. Address(); In } Java 1. 5: Must be nonnegative Must be non-null Must contain at least one item
Step 4: Create Context n n The context is the entry point to the API Contains methods to create Marshaller, Unmarshaller and Validator instances AXBContext context = JAXBContext. new. Instance("demo"); The package name is demo (Recall: xjc -p demo. xsd)
Step 5: Unmarshal: xml -> objects Unmarshaller unmarshaller = context. create. Unmarshaller(); unmarshaller. set. Validating(true); Enable validation of xml according to the schema while unmarshalling Person. Type person = (Person. Type) unmarshaller. unmarshal( new File. Input. Stream("demo. xml") );
Step 6: Read System. out. println("Person name=" + person. get. Name() ); Address. Type address = (Address. Type) person. get. Address(). get(0); System. out. println("First Address: " + " Street=" + address. get. Street() + " Number=" + address. get. Number() );
Step 7: Manipulate objects // Update person. set. Name("Yoav Zibin"); // Delete List address. List = person. get. Address(); address. List. clear(); What happens if we validate there? // Create Object. Factory object. Factory = new Object. Factory(); Address. Type new. Addr = part of the demo package object. Factory. create. Address. Type(); new. Addr. set. Street("Hanoter"); uses the factory pattern
Step 8: Validate on-demand Validator validator = context. create. Validator(); validator. validate(new. Addr); Check that we have set Street and Number, and that Number is non-negative validator. validate(person); Check that we have set Name, and that Address contains at least one item
Step 9: Marshal: objects -> xml Marshaller marshaller = context. create. Marshaller(); marshaller. set. Property(Marshaller. JAXB_FORMATTED_ OUTPUT, Boolean. TRUE); marshaller. marshal(person, output. xml new File. Output. Stream("output. xml")); <Person> <Name>Yoav Zibin</Name> <Address> <Street>Hanoter</Stre et>
And now, the Demo!
First Part Summary
Similar Technologies n Liquid XML Data Binding n n Relaxer n n Similar to JAXB Supports all Schema constructs In addition to Java: C#, C++, Visual Basic 6 Instead of Schema uses Relax Castor. org
Second Part Outline n n Validation Mapping XML Schema to Java n n Naming Java Properties Simple and Complex Types Customization of the default mapping
Validation Constraints n Three categories of constraints n Type constraints: Legal values in simple types n n Local structural constraints n n E. g. , in every address, number is a non-negative integer E. g. , in every person, address contains at least one item Global structural constraints n E. g. , ID and IDREF
Validation n Three forms of validation n n Unmarshal time validation (at unmarshal time) On-demand validation (at any chosen point in time) n n n Fail-fast validation (at all times) n n validate. Root(object) vs. validate(object) validate. Root includes global constraint checking Currently not implemented Checks that the value provided to a set method is legal When validation errors occur an event is raised (no exception) and validation continues, so that several validation errors can be handled. Default handler raises an exception on first error
Unsupported Schema Concepts n n n Substitution groups Type substitutions (xsi: type, block) Key, keyref, and unique any. Attribute No support for XPath or any other query langauge
Element vs. Type n An element also has a qualified name <xs: element name=“ugly_man" type="Person. Type"/> <xs: element name=“pretty_woman" an empty interface which marks type="Person. Type"/> the existence of a… static QName <xs: complex. Type name="Person. Type"> </xs: complex. Type> interface Ugly. Man extends Person. Type, Element {} interface Pretty. Woman extends Person. Type, n. Element When is{}the difference important? (next) interface Person. Type { … }
n Marshal: When must I use elements? marshaller. marshal(Object, Output. Stream) E. g. , when we marshal a Person. Type: <Name>Sharon Krisher</Name> <Address> n General content <Street>Iben Gevirol</Street> <Number>57</Number> </Address> <xs: any /> must be an element, otherwise the resulting output is not a legal XML Object get. Any(); void set. Any(Object element. Or. Value);
Naming n Problem: sometimes XML names n n n are not legal java names do not comply to java naming standards The binding compiler creates proper names XML Name Class Name Method Name mixed. Case. Name Mixed. Case. Name get. Mixed. Case. Name name-with-dash Name. With. Dash get. Name. With. Dash aa_bb-cc Aa. Bb. Cc get. Aa. Bb. Cc
Java Properties n Local schema components are mapped to: n Simple property (get, set) n String get. Name(); void set. Name(String n With customization: is. Set. Name , unset. Name value); List property n java. util. List Indexed property (next) get. Address(); In Java 1. 5: List<Address. Typ e>
Indexed Property n Used instead of a list property when a proper customization is applied Address. Type[] get. Address(); void set. Address(Address. Type[] value); Address. Type get. Address(int index); void set. Address(int index, Address. Type value);
General Content Property n The most general content property n n n Can represent any content, however complex A list that can contain element interfaces and values Used for “problematic cases” : n n Name collisions due to derivation Mixed content Another example: <xs: any Each item can be max. Occurs="unbounded"/> n some element or value List get. Any();
Simple Types (partial diagram) Simple. Type Primtive ID/IDREF date integer List Union List Next (1) String/Object Calenda r Big. Integer int Restriction Represente d as validation constraints max. Inclusive Enumeration Next (2)
Simple Type: Union <xs: complex. Type name="Date"> <xs: sequence> <xs: element name="Month"> <xs: simple. Type> <xs: union member. Types="xs: int xs: string"/> </xs: simple. Type> </xs: element> </xs: sequence> </xs: complex. Type> Public interface Date { Object get. Month(); void set. Month(Object); } Common supertype of (Integer, String) is Object
Type Safe Enumeration <xs: simple. Type name="USState"> <xs: restriction base="xs: NCName"> <xs: enumeration value="AK"/> <xs: enumeration value="NY"/> </xs: restriction> </xs: simple. Type> public class USState { protected USSate(String v) {…} public static final USState AK = …; public static final USState NY = …; public String get. Value(); public static USState from. Value(String v) {…}
XML Schema Type System Any Simple. Type Complex. Type finishe d Simple. Content Complex. Content *Extension *Sequence * Choice Extension Restriction (* ) Represented as a Java interface The interface extends the base type’s Attributes * All Elements abstract * use nillable * default min. Occurs fixed Represente max. Occur s d as Java
Complex Types n n Represented as a Java interface Anonymous type n n n An interface is created. The name is derived from the name of the schema element + “Type”, e. g Foo. Type Abstract types: no create method in Object. Factory
Complex Type: Simple Content <xs: complex. Type name=“International. Price"> <xs: simple. Content> <xs: extension base="xs: int"> <xs: attribute name="currency“ type="xs: string"/> </xs: extension> </xs: simple. Content> </xs: complex. Type> interface International. Price { int get. Value(); void set. Value(int); String get. Currency(); void set. Currency(String);
Complex Type: Aggregation <xs: element name="A" type="xs: int"/> <xs: complex. Type name="Foo"> <xs: sequence> <xs: element ref="A"/> <xs: sequence> <xs: element ref="B"/> <xs: element ref="C"/> </xs: sequence> interface Foo { </xs: sequence> </xs: complex. Type> int get. A(); void set. A(int); </xs: sequence> int get. B(); void set. B(int); </xs: complex. Type> int get. C(); void set. C(int);
Complex Type: Mixed Content <xs: complex. Type name=“Letter. Body" mixed="true"> <xs: sequence> <xs: element name="name" XML fragment type="xs: string"/> Dear Mr. <name>Robert Smith</name> … </xs: sequence> interface Letter. Body { Letter. Body lb = Object. Factory. create. Letter. Body(); </xs: complex. Type> Name extends Listinterface gcl = lb. get. Content(); Element { Mr. "); gcl. add("Dear String get. Value(); gcl. add(Object. Factory. create. Letter. Body. Name("Robert The list may contain void set. Value(String); Smith")); elements and strings } …
Complex Type: Choice <xs: complex. Type name="Foo. Bar. Type"> The <xs: choice> programmer <xs: element name="Foo" is type="xs: int"/> responsible <xs: element name="Bar" Defa to only set type="xs: string"/> ult public interface Foo. Bar. Type Customization (Not one of Foo </xs: choice> { implemented public interfaceyet) Foo. Bar. Type or Bar int get. Foo(); {</xs: complex. Type> void set. Foo(int value); Object get. Foo. Or. Bar(); String get. Bar(); void set. Bar(String value); set. Foo. Or. Bar(Object); Common supertype } of (Integer, String) is Object boolean is. Set. Foo(); void unset. Foo(); Similar to union
When max. Occurs>1 <xs: complex. Type name="Foo. Bar. Type"> <xs: choice max. Occurs="unbounded"> <xs: element name="Foo" type="xs: int"/> <xs: element name="Bar" type="xs: string"/> </xs: choice> </xs: complex. Type> public interface Foo. Bar. Type { interface Foo extends Element {…} interface Bar extends Element {…} // Items are instances of Foo and Bar List get. Foo. Or. Bar(); } a sequence: List For get. Foo. And. Bar()
Complex Type: All n n Mapped like Sequence Can’t have max. Occurs > 1 No way to specify the order of elements Round trip doesn’t hold (order is not preserved): XML ≠ XML unmarshal Objects in memory marshal
Nillable elements <xs: element name=“age" type=“xs: int" nillable="true"/> Integer get. Age(); void set. Age(Integer value); Java: set. Age( new Integer(25) ) or set. Age(null) XML: <age>25</age> <age xsi: nil="true"/> or
Customization n Used to augment the default mapping Customizations declared via special xml tags May appear inside the source schema or in a separate file
Uses of Customization n Change default names of interfaces and properties n n For a specific schema construct For an entire namespace n n n Add a suffix or a prefix Change the types of properties Add javadoc declarations
Software Engineering Issues n Weak Typing Our suggestions: n n n Marshal / Unmarshal : Object Element IDREF: Object Identifiable Sometimes JAXB doesn’t allow us to control the order of elements n n Example 1: xs: all Example 2: next slide
Element Order Example <xs: complex. Type name=“ABType"> <xs: choice> <xs: sequence> <xs: element name="A" type="xs: int"/> <xs: element name="B" type="xs: string"/> </xs: sequence> <xs: element name="B" type="xs: string"/> <xs: element name="A" type="xs: int"/> public interface ABType { </xs: sequence> int get. A(); void set. A(int value); </xs: choice> String get. B(); void set. B(String value); </xs: complex. Type> obj. set. A(5); obj. set. B(“a”); What happens when we No obj? marshal roundtrip
It’s the programmer’s fault n Taken from JAXB specification: n n “The caller must be sure …” “There is an expectation …” “User is responsible …” “… unexpected behavior may occur. ” Question: What is the output? xs: choice between Foo and Bar obj. set. Age(42); 42 obj. set. Foo(42); obj. unset. Age(); obj. set. Bar("A"); System. out. println( obj. is. Set. Foo() ); ); System. out. println( obj. get. Age()
XML Registries Source: Java. TM API for XML Registries Specification
Outline n n n What is an XML Registry Overview of JAXR Implementation in JWSDP: Demo 103
What is a registry? n n A registry is a key component in any Web Service architecture because it provides the ability to publish, discover and utilize web services. We can think of a registry as a centralized place to store information about available web services. 104
Functionality of a registry n Registry as Electronic Yellow Pages n n Registry as a Database of Relatively Static Data n n Providers advertise their services and consumers discover them. Provides a way to store relatively static information reliably and to enable sharing of such information. Registry as an Electronic Bulletin Board n Provide means to exchange dynamic content between parties. 105
Registry use case scenario 106
Registry use case scenario XML Specification 1 Developer Check existing math services Metadata 3 Register information about the math service Registry Br 2 Service implementation on i t ec ice n 5 onserv c sh ess i l tab acc s E nd a ow Do se in w fo nl , Q rm oa 4 ue at d s ry io e n rv ic e Client 107
Existing Registry Specifications n JAXR meant to be the confluence of the various registry specifications 108
Java™ API for XML Registries (JAXR) n n n A standard Java™ API for accessing diverse and heterogeneous business Registries. A unified information model for describing business registry content Provides multi-layered API abstractions: n n n Simple, high level, business API Flexible, low level, generic API Enabling technology for web services and peer-to-peer computing in the J 2 EE™ platform 109
JAXR API Architecture 110
JAXR Client n n The JAXR client may be any standalone Java application or a Java 2 Enterprise Edition (J 2 EE) enterprise component. The JAXR client uses the JAXR API to access a registry via a JAXR provider. 111
Interface Connection n n A Connection object represents a client session with a registry provider using a JAXR provider. It maintains state information for a specific connection. 112
Interface Registry. Service n n Is the principal interface implemented by a JAXR provider. A registry client can get this interface from its Connection to a JAXR provider. 113
Capability-specific Interfaces n n Provide specific capabilities such as: b Life cycle management b Query management Capability specific interfaces are usually named xx. Manager where xx represents the specific capability provided by that interface. 114
JAXR Provider b n Is an implementation of the JAXR API. A JAXR client accesses a registry via a JAXR provider. The Figure shows JAXR provider as the union of n n n JAXR pluggable provider, and Registry-specific JAXR providers. JAXR pluggable provider implements features of the JAXR API that are independent of any specific registry type. 115
Registry Provider n n Registry providers are shown as the bottom layer in the architecture. These are implementations of various registry specifications such as eb. XML and UDDI. 116
Main Interfaces Defined by the JAXR API These are access interfaces which define how objects in the information model are submitted to the registry and subsequently managed. 117
JAXR Information Model n n Describes what type of objects reside in the registry. Based upon eb. XML Registry Information Model Enhanced for UDDI support Improves upon and unifies concepts from both eb. XML and UDDI 118
JAXR Information Model An abstract base class used by Groups logically related most classes. It provides Registry. Objects together minimal metadata for registry objects. It also provides Classifies a Registry. Object methods accessing related instancefor using a classification objects that provide additional scheme. dynamic metadata for the registry object. Represents a taxonomy that may be used to classify or categorize Registry. Object instances. Defines the hierarchical tree structure and detailed elements of a classification scheme s Registry. Objects that provide information on organizations such as a Submitting Organization. Each Organization instance may have a reference to a parent Organization. An Organization may have a set of Service instances. 119
Role of Concepts in Representing Taxonomy Structure b Concept instances are used to represent taxonomy elements and their structural relationship with each other in order to describe an internal taxonomy. 120
Internal Classification b When a Classification instance uses a Concept within an internal Classification. Scheme then it is referred to as an internal Classification. 121
External Classification b b b When a Classification instance uses a value within an external Classification. Scheme then it is referred to as an external Classification. Here the structure of the taxonomy is not available internally to the registry and consequently there is no Concept instance. Instead, the name and value attributes of the Classification are used to pin-point the Book Publishers taxonomy element. 122
Multiple Classifications 123
Object Association An Association is defined between a new version of the NAICS Classification. Scheme and an older version of the NAICS Classification. Scheme. 124
Intramural Association The association is between two objects that are owned by the same user that is defining the Association. 125
Extramural Association Either or both objects that are being associated are owned by a user different from the user defining the Association. 126
Information Model Inheritance View 127
JAXR Implementation in JWSDP: Demo n n n Starting the registry server Starting Xindice database Using the Registry Browser and the Indri tool n n n Adding a service (to the local registry) Querying the registry Defining our own taxonomy 128
Defining Our Own Taxonomy n n JAXR provider can add user-defined taxonomies for use by JAXR clients. The mechanisms clients use to add and administer these taxonomies are implementation -specific. Uses a simple file-based approach to provide taxonomies to the JAXR client. These files are read at run time, when the JAXR provider starts up. The taxonomy structure is defined by the JAXR Predefined Concepts DTD, which can be 129
n n For example, the file jaxrconcepts. xml contains the taxonomies for the implementation of JAXR in JWSDP. The entries in the jaxrconcepts. xml file look like this: n n n n <Predefined. Concepts> <JAXRClassification. Scheme id="sch. Id" name="sch. Name"> <JAXRConcept id="sch. Id/con. Code" name="con. Name" parent="parent. Id" code="con. Code"></JAXRConcept>. . . </JAXRClassification. Scheme> </Predefined. Concepts> 130
n To add a user-defined taxonomy, we follow these steps. n n n Publish the JAXRClassification. Scheme element for the taxonomy as a Classification. Scheme object in the registry that you will be accessing. In an XML file, define a taxonomy structure that is compliant with the JAXR Predefined Concepts DTD. Enter each JAXRConcept element in our taxonomy XML file by specifying the following four attributes: n n n id is the JAXRClassification. Scheme id value, followed by a / separator, followed by the code of the JAXRConcept element name is the name of the JAXRConcept element parent is the immediate parent id (either the 131 Classification. Scheme id or that of the parent
n To add the user-defined taxonomy structure to the JAXR provider, specify the system property com. sun. xml. registry. user. Taxonomy. File names when we run the client program. 132
- Slides: 132