1 / 98

CPE3010 Lecture 5

CPE3010 Lecture 5. Java and Web Services. Java and Web Services. Many Java gurus/ developers HATE XML and Web services. - too slow, too high an overhead, and “back to the future” because RPC is used and real objects can not be passed. Also no leasing in UDDI (yet).

gilda
Download Presentation

CPE3010 Lecture 5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CPE3010 Lecture 5 • Java and Web Services

  2. Java and Web Services • Many Java gurus/ developers HATE XML and Web services. • - too slow, too high an overhead, and “back to the future” because RPC is used and real objects can not be passed. Also no leasing in UDDI (yet). • BUT, Web Services are THE ONLY GAME IN TOWN, so Sun offers Java frameworks/ APIs for dealing with Web Services • - Java APIs for XML Processing and Web Services: JAXB, JAX- RPC • - J2EE 1.4 provides support for web services through the JAX-RPC 1.1 API. It also supports JSR 109, that builds on JAX-RPC.

  3. Java APIs for XML Processing & Web Services • Document-oriented • Java API for XML Processing (JAXP) -- processes XML documents using various parsers • Java Architecture for XML Binding (JAXB) -- processes XML documents using schema-derived JavaBeans component classes • SOAP with Attachments API for Java (SAAJ) -- sends SOAP messages over the Internet in a standard way • Procedure-oriented • Java API for XML-based RPC (JAX-RPC) -- sends SOAP method calls to remote parties over the Internet and receives the results • Java API for XML Registries (JAXR) -- provides a standard way to access business registries and share information

  4. Using Java and Web Services

  5. Present and Future Java APIs

  6. Java APIs • Not used extensively: • Java API for XML Processing (JAXP) parsing and processing XML documents and a transformation engine supporting XSLT; • Java API for XML Registries (JAXR) defines Java APIs for accessing XML registries. It will support both ebXML registries and repositories and UDDI; • Java API for XML Messaging (JAXM) provides Java support for sending and receiving SOAP messages; • Used extensively: • Java Architecture for XML Binding (JAXB) makes it easy to map XML data into Java objects; • Java API for Remote Procedure Call (JAX-RPC), a procedure call is transmitted as XML.

  7. JAXP • - parses data as a stream of events or builds an object representation of it. • - supports XSLT (XML Stylesheet Language Transformations), providing control over the presentation of the data and enabling you to convert the data to other XML documents or to other formats, such as HTML. • - provides namespace support. • - allows you to use any XML-compliant parser from within your application • - also allows you to plug in an XSL processor, to control how your XML data is displayed.

  8. Example Using JAXP • http://java.sun.com/developer/technicalArticles/xml/brazil/index.html

  9. SAX API – Simple XML Parsing • Event-based parser that reads an XML document from beginning to end. Each time it recognizes a syntax construction, it notifies the application that is running it by calling methods from the ContentHandler interface. • For example, when the parser comes to a less than symbol ("<"), it calls the startElement method; when it comes to character data, it calls the characters method; when it comes to the less than symbol followed by a slash ("</"), it calls the endElement method, and so on.

  10. Running XML Example • <priceList>    • <coffee>      • <name>Mocha Java</name>      • <price>11.95</price>    • </coffee>    • <coffee>      • <name>Sumatra</name>      • <price>12.50</price>    • </coffee> • </priceList>

  11. SAX Example • <priceList>   [parser calls startElement]    • <coffee>    [parser calls startElement]      • <name>Mocha Java</name>    [parser calls startElement,  characters, and endElement]      • <price>11.95</price>    [parser calls startElement, characters, and endElement]    • </coffee>    [parser calls endElement]

  12. SAX, cont’d. • You need to write a subclass implementing the appropriate methods to get the functionality you want. • To get the price per pound for Mocha Java, write a class extending DefaultHandler (the default implementation of ContentHandler) to implement the methods startElement and characters. • Create a SAXParser object from a SAXParserFactory object. You would call the method parse on it, passing it the price list and an instance of your new handler class (with its new implementations of the methods startElement and characters). In this example, price list is a file, but parse can also take other input sources, an InputStream object, a URL, or an InputSource object. • SAXParserFactory factory = SAXParserFactory.newInstance(); • SAXParser saxParser = factory.newSAXParser(); • saxParser.parse("priceList.xml", handler);

  13. SAX, cont’d. • The result of calling the method parse depends on how the methods in handler were implemented. • The SAX parser will go through the file priceList.xml line by line, calling the appropriate methods. • In addition to the methods already mentioned, the parser will call other methods such as startDocument, endDocument, ignorableWhiteSpace, and processingInstructions, but these methods have default implementations and do nothing.

  14. SAX, cont’d. • The following implements the methods characters and startElement so that they find the price for Mocha Java and print it out. • These methods work together to look for the name element, the characters "Mocha Java", and the price element immediately following Mocha Java. • These methods use three flags to keep track of which conditions have been met.

  15. SAX Example, cont’d. • public void startElement(..., String elementName, ...) • {   if(elementName.equals("name")){     inName = true;   } • else if(elementName.equals("price") && inMochaJava ) • {     inPrice = true;     inName = false;   } } • public void characters(char [] buf, int offset, int len) • {   String s = new String(buf, offset, len);    • if (inName && s.equals("Mocha Java")) • {     inMochaJava = true;     inName = false;   } • else if (inPrice) • {     System.out.println("The price of Mocha Java is: " + s);      • inMochaJava = false;      • inPrice = false;     }   } }

  16. SAX, cont’d. • Once the parser has come to the Mocha Java coffee element, here is the relevant state after the following method calls: • next invocation of startElement -- inName is true • next invocation of characters -- inMochaJava is true • next invocation of startElement -- inPrice is true • next invocation of characters -- prints price

  17. SAX, cont’d. • SAX parser can perform validation while parsing, to check that the data follows the rules specified in the XML document's schema. A SAX parser will validate if it is created by a SAXParserFactory that has validation turned on. This is done for the SAXParserFactory object factory in the following line of code. • factory.setValidating(true); • The parser knows which schema to use for validation by an XML document. The schema for the price list is priceList.DTD, so the DOCTYPE declaration should be similar to this: • <!DOCTYPE PriceList SYSTEM "priceList.DTD">

  18. Object Model Parsing • Document Object Model (DOM), defined by W3C, is a set of interfaces for building an object representation, in the form of a tree, of a parsed XML document. • Once you build the DOM, you manipulate it with DOM methods such as insert and remove, as other tree data structures. Unlike SAX, a DOM parser allows random access to pieces of data in an XML document. • With a SAX parser, you can only read an XML document, but with a DOM parser, you can build an object representation and manipulate it in memory, adding a new element or deleting one.

  19. DOM, cont’d. • In the previous example, SAX looked for one piece of data in a document. Using a DOM parser would have required having the whole document object model in memory, which is generally less efficient for searches involving just a few items, if the document is large. • The next example adds a new coffee to the price list using a DOM parser. We cannot use a SAX parser for modifying the price list because it only reads data. • Add Kona coffee to the price list. Read the XML price list file into a DOM and tinsert the new coffee element, with its name and price. The following code fragment creates a DocumentBuilderFactory object, which is then used to create the DocumentBuilder object builder. The code then calls the parse method on builder, passing it the file priceList.xml.

  20. DOM Example • DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); • DocumentBuilder builder = factory.newDocumentBuilder(); • Document document = builder.parse("priceList.xml");

  21. DOM Example, cont’d. • document is DOM representation of the price list. • The following code adds a new coffee (with the name "Kona" and a price of "13.50") to the price list. • Because we want to add the new coffee right before the coffee whose name is "Mocha Java", first get a list of the coffee elements and iterate through the list to find "Mocha Java". • Using the Node interface in org.w3c.dom, the code creates a Node object for the new coffee element and the name and price elements. The name and price elements contain character data, so the code creates a Text object for each of them and appends the text nodes to the nodes representing the name and price elements.

  22. DOM Example, cont’d. • Node rootNode = document.getDocumentElement(); • NodeList list = document.getElementsByTagName("coffee"); • // Loop through the list. • for (int i=0; i < list.getLength(); i++) • {   thisCoffeeNode = list.item(i);    • Node thisNameNode = thisCoffeeNode.getFirstChild();    • if (thisNameNode == null) continue;    • if (thisNameNode.getFirstChild() == null) continue;    • if (! thisNameNode.getFirstChild() instanceof org.w3c.dom.Text) continue;    • String data = thisNameNode.getFirstChild().getNodeValue();    • if (! data.equals("Mocha Java")) continue;   

  23. DOM Example, cont’d. • //We're at the Mocha Java node. Create and insert the new element.    • Node newCoffeeNode = document.createElement("coffee");    • Node newNameNode = document.createElement("name");    • Text tnNode= document.createTextNode("Kona");    • newNameNode.appendChild(tnNode);    • Node newPriceNode = document.createElement("price");    • Text tpNode = document.createTextNode("13.50");    • newPriceNode.appendChild(tpNode);    • newCoffeeNode.appendChild(newNameNode);    • newCoffeeNode.appendChild(newPriceNode);    • rootNode.insertBefore(newCoffeeNode, thisCoffeeNode);    • break; }

  24. DOM Output to XML • To transform the DOM tree to an XML document, the following code first creates a Transformer object that will perform the transformation. • TransformerFactory transFactory =         TransformerFactory.newInstance(); • Transformer transformer = transFactory.newTransformer(); • Using the DOM tree root node, the following code constructs a DOMSource object as the source of the transformation. • DOMSource source = new DOMSource(document);

  25. DOM Output, cont’d. • The following code creates a StreamResult object to take the results of the transformation and transforms the tree into an XML file. • File newXML = new File("newXML.xml"); • FileOutputStream os = new FileOutputStream(newXML); • StreamResult result = new StreamResult(os); • transformer.transform(source, result);

  26. JAXB • JAXB compiles an XML schema into one or more classes. The generated classes handle all the details of XML parsing and formatting, they ensure that the constraints expressed in the schema are enforced, and in many cases they are much more efficient than using SAX or DOM.

  27. JAXB Binding

  28. JAXB, cont’d. • JAXB generates Java classes from XML schemas. JAXB provides methods for unmarshalling an XML instance document into a content tree of Java objects, and then marshalling the content tree back into an XML document. • JAXB hides the details and gets rid of the extra steps in SAX and DOM-- JAXB classes describe only the relationships defined in the schemas.

  29. JAXB Architecture

  30. JAXB Summary • Generate and compile JAXB classes from a source schema, and build an application that implements these classes • Run the application to unmarshal, process, validate, and marshal XML content through the JAXB binding framework

  31. JAXB Steps • Generate classes. An XML schema is used as input to the JAXB binding compiler to generate JAXB classes based on that schema. • Compile classes. All of the generated classes, source files, and application code must be compiled. • Unmarshal. XML documents written according to the constraints in the source schema are unmarshalled. • Generate content tree. The unmarshalling process generates a content tree of data objects instantiated from the generated JAXB classes; this content tree represents the structure and content of the source XML documents. • Validate (optional). Validation of the source before generating the content tree. • Process content. The client application can modify the XML data represented by the Java content tree by means of interfaces generated by the binding compiler. • Marshal. The processed content tree is marshalled out to one or more XML output documents. The content may be validated before marshalling.

  32. JAXB Details • javax.xml.bind defines abstract classes and interfaces used directly with content classes. • javax.xml.bind defines the Unmarshaller, Validator, and Marshaller classes. • JAXBContext is the entry point to JAXB. A JAXBContext instance manages the binding relationship between XML element names to Java content interfaces for a JAXB implementation to be used by the unmarshal, marshal and validation operations. • javax.xml.bind also defines validation event and exception classes. • javax.xml.bind.util contains utility classes to manage marshalling, unmarshalling, and validation events. • javax.xml.bind.helper provides partial default implementations for some of the javax.xml.bind interfaces. Implementations of JAXB can extend these classes and implement the abstract methods. These APIs are not intended to be directly used by applications using JAXB architecture.

  33. JAXB Details • The JAXBContext class provides an abstraction for managing the information necessary for unmarshal, marshal and validate. • JAXBContext jc = JAXBContext.newInstance( "com.acme.foo:com.acme.bar" ); • The contextPath parameter contains a list of packages that contain schema-derived interfaces-- the interfaces generated by the JAXB binding compiler. This parameter initializes the JAXBContext object to enable management of the schema-derived interfaces. • The JAXB provider implementation must supply an implementation class containing a method with the following signature: • public static JAXBContext createContext( String contextPath, ClassLoader classLoader ) throws JAXBException;

  34. Unmarshalling • The Unmarshaller class in the javax.xml.bind package converts XML data into a tree of Java objects. The unmarshal method for a schema allows for any global XML element declared in the schema to be unmarshalled as the root of an instance document. • The JAXBContext object allows the merging of global elements across a set of schemas (listed in the contextPath). Since each schema can belong to distinct namespaces, the unification of schemas to an unmarshalling context should be namespace-independent. A client application can unmarshal XML documents that are instances of any of the schemas listed in the contextPath:

  35. Unmarshalling, cont’d. • JAXBContext jc = JAXBContext.newInstance(   "com.acme.foo:com.acme.bar" ); • Unmarshaller u = jc.createUnmarshaller(); • FooObject fooObj =   (FooObject)u.unmarshal( new File( "foo.xml" ) ); // ok • BarObject barObj =   (BarObject)u.unmarshal( new File( "bar.xml" ) ); // ok • BazObject bazObj =   (BazObject)u.unmarshal( new File( "baz.xml" ) );   // error, "com.acme.baz" not in contextPath

  36. Marshalling • The Marshaller class converts a Java content tree back into XML data. • A simple example that unmarshals an XML document and then marshals it back out is a follows:

  37. Marshalling, cont’d. • JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" ); // unmarshal from foo.xml • Unmarshaller u = jc.createUnmarshaller(); • FooObject fooObj =   (FooObject)u.unmarshal( new File( "foo.xml" ) ); // marshal to System.out • Marshaller m = jc.createMarshaller(); • m.marshal( fooObj, System.out );

  38. JAXB Examples • http://java.sun.com/webservices/docs/1.4/tutorial/doc/index.html

  39. JAXB Customisation • Reasons for modifying default bindings: • Create API documentation for the schema-derived JAXB classes, etc.; add Javadoc annotations. • Provide meaningful names : • To resolve name collisions. • To provide names for typesafe enumeration constants. • To provide better names for the Java representation of unnamed model groups when they are bound to a Java property or class. • To provide more meaningful package names. • Overriding default bindings; for example: • Specify that a model group should be bound to a class rather than a list. • Specify that a fixed attribute can be bound to a Java constant. • Override the specified default binding of XML Schema built-in datatypes to Java datatypes.

  40. JAX-RPC • JAX-RPC builds Web services and clients that use remote procedure calls and XML. • In JAX-RPC, a remote procedure call is represented by an XML-based protocol such as SOAP. • Although SOAP messages are complex, the JAX-RPC API hides this complexity from the application developer. • On the server side, the developer specifies the remote procedures by defining methods in a Java interface. The developer also codes one or more classes that implement those methods. • A client creates a proxy, a local object representing the service, and then invokes methods on the proxy. With JAX-RPC, the developer does not generate or parse SOAP messages. It is the JAX-RPC runtime system that converts the API calls and responses to and from SOAP messages.

  41. JAX-RPC • In JAX-RPC, a remote procedure call is represented by an XML-based protocol such as SOAP. The SOAP specification defines the envelope structure, encoding rules, and conventions for representing remote procedure calls and responses. • These calls and responses are transmitted as SOAP messages (XML files) over HTTP. JAX-RPC API hides SOAP complexityfrom the application developer. • On the server side, the developer specifies the remote procedures by defining methods in an interface. The developer also codes one or more classes that implement the methods. • A client creates a proxy (a local object representing the service) and then simply invokes methods on the proxy. • With JAX-RPC, the developer does not generate or parse SOAP messages. JAX-RPC runtime converts the API calls and responses to and from SOAP messages.

  42. JAX-RPC

  43. Developing a JAX-RPC Web Service • The starting point for developing a JAX-RPC Web service is the service endpoint interface. A service endpoint interface (SEI) is a Java interface that declares the methods that a client can invoke on the service. • Use the SEI, the wscompile tool, and two configuration files to generate the WSDL specification of the Web service and the stubs that connect a Web service client to the JAX-RPC runtime. Together, wscompile, the deploytool utility, and the Application Server provide the Application Server’s implementation of JAX-RPC.

  44. Summary of Steps • These are the basic steps for creating the Web service and client: • 1. Code the SEI and implementation class and interface configuration file. • 2. Compile the SEI and implementation class. • 3. Use wscompile to generate the files required to deploy the service. • 4. Use deploytool to package the files into a WAR file. • 5. Deploy the WAR file. The tie classes (which are used to communicate with clients) are generated by the Application Server during deployment. • 6. Code the client class and WSDL configuration file. • 7. Use wscompile to generate and compile the stub files. • 8. Compile the client class. • 9. Run the client.

  45. JAX-RPC: Overview

  46. JAX-RPC: Service Side Use Cases

  47. JAX-RPC: Service Side • Service endpoint definition starts with a Java service endpoint interface. • Service developer can map a WSDL document to a Java service endpoint interface. • Once JAX-RPC service endpoint is defined and implemented, deployment requires server-side JAX-RPC runtime. • Deployment includes generation of artifacts (skeleton or tie class) based on the service endpoint interface. • During deployment, the tool configures one or more protocol bindings for this service endpoint. • A binding ties an abstract service endpoint definition to a specific protocol and transport. An example of a binding is SOAP over HTTP.

  48. JAX-RPC: Service Side Runtime

  49. JAX-RPC: Client Side Use Cases

  50. JAX-RPC Client Side • Client uses the WSDL document to import the service. • A WSDL-to-Java mapping tool generates client side artifacts (includes stub class, service endpoint interface and additional classes) for the service and its ports. • Note that a service client may use dynamic invocation interface (DII) or a dynamic proxy mechanism instead of a generated stub class to invoke a remote method on a service endpoint.

More Related