1 / 38

Web Services Basic Training

Web Services Basic Training. Srinivas Kandula Vijayan Srinivasan. Agenda. Environment Setup XML Namespaces DTD / Schema JAXP DOM SAX JAXB Marshaling Un-Marshaling XSD -> Java Utilities Web Services WSDL SOAP REST. Environment Setup. Compiler JDK 1.6 IDE

alvis
Télécharger la présentation

Web Services Basic Training

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. Web Services Basic Training Srinivas Kandula Vijayan Srinivasan

  2. Agenda • Environment Setup • XML • Namespaces • DTD / Schema • JAXP • DOM • SAX • JAXB • Marshaling • Un-Marshaling • XSD -> Java Utilities • Web Services • WSDL • SOAP • REST

  3. Environment Setup • Compiler • JDK 1.6 • IDE • Eclipse Java EE – Helios • Additional Plugins • SVN Plugin - Subclipse • Maven Plugin - M2Eclipse CoreM2Eclipse Extras • SOAP Test Plugin – SoapUI • Application Server • jboss-4.2.3.GA • Example Source Code • Available at Google Code

  4. XML What is XML? • XML stands for EXtensible Markup Language • XML is a markup language much like HTML • XML was designed to carry data, not to display data • XML is a W3C Recommendation Pros • Platform and system independent • XML tags are not predefined. You must define your own tags • XML is designed to be self-descriptive • Validations are possible through DTD and XML Schema • Many Built-In Parsers are available in almost all popular languages Cons • Self-descriptive nature results a bigger payload compare to its competitive formats • JSON • YAML

  5. Example XML <?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE bookstore SYSTEM “Book.dtd"> <bookstore>   <book category="COOKING">    <title lang="en">Everyday Italian</title>    <author>Giada De Laurentiis</author>    <year>2005</year>    <price>30.00</price>  </book> <book category="WEB">    <title lang="en">Learning XML</title>    <author>Erik T. Ray</author>    <year>2003</year>    <price>39.95</price>  </book> </bookstore>

  6. DTD • DTD • The purpose of a DTD (Document Type Definition) is to define the legal building blocks of an XML document. • A DTD defines the document structure with a list of legal elements and attributes. <!DOCTYPE bookstore[ <!ELEMENT bookstore(book*)> <!ELEMENT book(title, author, year, price)><!ELEMENT title(#PCDATA)><!ELEMENT author(#PCDATA)><!ELEMENT year(#PCDATA)><!ELEMENT price(#PCDATA)> <!ATTLIST book category CDATA #REQUIRED><!ATTLIST title lang CDATA #IMPLIED> ]>

  7. Schema <?xmlversion="1.0" encoding="ISO-8859-1" ?> <xs:schemaxmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name=“book">  <xs:complexType>    <xs:sequence>      <xs:element name="title“ type=“xs:string”/>      <xs:element name=“author" type=“xs:string"/>       <xs:element name=“year” type=“xs:string”/>       <xs:element name="price" type="xs:decimal"/>    </xs:sequence>  </xs:complexType></xs:element><xs:element name=“bookstore”> <xs:complexType>    <xs:sequence> <xs:element ref=“book" maxOccurs="unbounded“> <xs:sequence> <xs:complexType>

  8. JAXP • Java API for XML Processing • JAXP enables applications to parse, transform, validate and query XML documents using an API • JAXP provides API which is independent of a particular XML processor implementation • Parser can be changed without recompiling the code using set of system properties • SAX • DOM • XSD • XSL • XPATH

  9. SAX • SAX stand for Simple API for XML • SAX is an event-driven, serial-access mechanism for accessing/processing XML documents • Parser triggers the Callback’s: startElement(), characters(), endElement() etc., while parsing the xml document. • Steps involved in Parsing XML file using SAX • Create a SAX Parser instance • Register callback implementation and implement the callbacks • Fastest and least memory-intensive • This is used only if we want to read data and have the application act on it

  10. Sample SAX import java.io.File; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; publicclass TestSAXParsing { publicstaticvoid main(String[] args) { try { // Get SAX Parser Factory SAXParserFactory factory = SAXParserFactory.newInstance(); // Turn on validation, and turn off namespaces factory.setValidating(true); factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); parser.parse(new File("books.xml"), new MyHandler()); } catch (ParserConfigurationException e) { System.out.println("The underlying parser does not support " + " the requested features."); } catch (FactoryConfigurationError e) { System.out.println("Error occurred obtaining SAX Parser Factory."); } catch (Exception e) { e.printStackTrace(); } } }

  11. MyHandler import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; publicclass MyHandler extends DefaultHandler { publicvoid startDocument() throws SAXException { } publicvoid endDocument() throws SAXException { } publicvoid startElement(String namespaceURI, String localName, String qName, Attributes attributes) { System.out.print(qName + ":"); } publicvoid endElement(String name) throws SAXException { System.out.println(); } publicvoid characters(char buf[], int offset, int len) throws SAXException { String s = new String(buf, offset, len); System.out.print(s); } }

  12. DOM • DOM stands for Document Object Model • A DOM for XML is an object model that exposes the contents of an XML document • Behind the scene it uses SAX Parser to construct the DOM Object • Mainly used when you want to manipulate the XML content during runtime • DOM can be memory intensive when it comes to very large XML document

  13. Sample DOM publicclassDOMParser { publicstaticvoid main(String[] args) { Document document=parse("books.xml"); Node node=document.getDocumentElement(); print(node,0); } privatestaticvoid print(Node node, int level) { if(node.getNodeType()==3){ return; } for(inti=0;i<level;i++){ System.out.print("\t"); } System.out.println(node.getNodeName()); if(node.hasChildNodes()){ NodeListnodeList=node.getChildNodes(); for(inti=0;i<nodeList.getLength();i++){ print(nodeList.item(i),level+1); } } } }

  14. Sample DOM publicstatic Document parse(String fileName) { Document document = null; // Initiate DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // To get a validating parser factory.setValidating(false); // To get one that understands namespaces factory.setNamespaceAware(true); try { // Get DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // Parse and load into memory the Document document = builder.parse( new File(fileName)); return document; } catch (SAXParseException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } returnnull; }

  15. JAXB • Framework for processing XML documents • Mandates Schema for XML document • Convert Java objects to XML and Vice versa. • Generate the Java type information (Classes) using Binding compiler (xjc) for accessing elements, attributes and other content in a typesafe way. • JAXWS uses JAXB internally for message parsing

  16. JAXB Binding Process Steps 1 2 4 3

  17. Advantages of JAXB over JAXP • JAXB allows Java developers to access and process XML data without having to know XML or XML processing. • For example, there's no need to create or use a SAX parser or write callback methods. • JAXB presents the XML document to the program in a Java format.

  18. Examples • JAXB2 • Create Java Classes from XSD • Unmarshal • Marshal • Castor • Create Java Classes from XSD • Unmarshal • Marshal

  19. Comparisons • JAXB • Standard from Sun • No Reflection • Better performance • Castor • Nonstandard • Uses reflection • Can be used for any POJO • Better Memory Management

  20. What is Web Service? • A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. • It has an interface described in a machine processable format (specifically WSDL). • Typically communication happens using HTTP with an XML serialization in conjunction with other Web-related standards (SOAP / REST).

  21. Client – Service Communication Client Service SOAP JAX-WS Runtime JAX-WS Runtime

  22. An Example • The client program bundles the Holiday request information into a SOAP message. • This SOAP message is sent to the Web Service as the body of an HTTP POST request. • The Holiday Web Service unpacks the SOAP request and converts it into a command that the application can understand. The application processes the information as required and creates response with the details of the Holiday. • Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request. • The client program unpacks the SOAP message to obtain the results of the Holiday.

  23. WSDL • WSDL stands for Web Services Definition Language • WSDL describes following aspect of service endpoints • Allowed operations • Return values of the operations • Data types of the service parameters

  24. UDDI • The Universal Description, Discovery, and Integration (UDDI) standard for publishing and discovering information about web services. • UDDI is a single conceptual registry distributed among many nodes that replicate the participating businesses' data with one another. • It attempted to cover both the business and development aspects of publishing and locating information associated with a piece of software on a global scale. • UDDI is similar to an Internet search engine for business processes.

  25. Cont.. • Service provider describes its service using WSDL. This definition is published to a directory of services. • Service consumer issues one or more queries to the directory to locate a service and determine how to communicate with that service. • Part of the WSDL provided by the service provider is passed to the service consumer. This tells the service consumer what the requests and responses are for the service provider. • The service consumer uses the WSDL to send a request to the service provider. • The service provider provides the expected response to the service consumer.

  26. Advantages of Web services • Application can be broken into smaller and loosely coupled programs. • Standardized and well-defined interfaces. • Loosely coupled programs makes the architecture very extensible • Increases interoperability, resulting in lower maintanancecosts • Increases reusability

  27. Simple Object Access Protocol (SOAP) • SOAP is a simple XML-based protocol to let applications exchange information over HTTP. • SOAP messages are sent either as payload of a HTTP POST request and response, or as a SOAP message in the response to a HTTP GET. • SOAP is fundamentally a stateless, one-way message exchange paradigm, but applications can create more complex interaction patterns (e.g., request/response, request/multiple responses, etc.) • SOAP provides the framework by which application-specific information may be conveyed in an extensible manner. • SOAP provides a full description of the required actions taken by a SOAP node on receiving a SOAP message.

  28. SOAP Message Structure Transport protocol MIME header SOAP ENVELOPE SOAP HEADER SOAP BODY FAULT Attachment

  29. JAX-WS • Java API for XML Web Services • It is a technology/API for building web services and clients that communicate using SOAP messages over HTTP • The runtime system converts the API calls and responses to and from SOAP messages • It enables clients to invoke web services developed across heterogeneous platforms. Likewise, JAX-WS web service endpoints can be invoked by heterogeneous clients. • Requires SOAP and WSDL standards for this cross-platform interoperability

  30. Implementing SOAP based Web Services • Contract First • Spring Web Services • Contract Last • CXF Web Services

  31. Spring Web Service

  32. CXF Architecture

  33. Representational State Transfer (REST) • REST is a set of principles that define how Web standards, such as HTTP and URIs, are supposed to be used. • Design Principles • Use HTTP methods explicitly. • Be stateless. • Expose directory structure-like URIs. • Transfer XML, JavaScript Object Notation (JSON), or both.

  34. REST Example • To Create a resource on the server POST /users HTTP/1.1 Host: Host: myserver Content-Type: application/xml <?xml version="1.0"?> <user> <name>RAM</name> </user> • To Retrieve a resource on server GET /users/Robert HTTP/1.1 Host: myserver Accept: application/xml

  35. Cont… • HTTP PUT request PUT /users/Robert HTTP/1.1 Host: myserver Content-Type: application/xml <?xml version="1.0"?> <user> <name>Bob</name> </user> • HTTP Delete request DELETE /users/Robert HTTP/1.1 Host: myserver

  36. References • http://cxf.apache.org/docs/writing-a-service-with-spring.html • http://static.springsource.org/spring-ws/sites/1.5/reference/html/tutorial.html • http://www.w3schools.com/ • http://cxf.apache.org/docs/cxf-architecture.html

  37. Question/Answer

  38. Thank You !

More Related