Download presentation
1
Web Services with Apache CXF
Part 2: JAXB and WSDL to Java Robert Thornton
2
This is a training, NOT a presentation Please ask questions
Notes This is a training, NOT a presentation Please ask questions This is being recorded Prerequisites Maven, Spring, and Web Application Development Web Services, Part I: SOAP A general familiarity with XML simple and complex schema types.
3
Objectives At the end of this presentation, the participant will be able to: Understand the role of JAXB as a web service data binding solution. Model data entities using JAXB annotations. Understand the purpose and usage of the CXF WSDL2Java tool. Be able to use WSDL2Java to generate a client proxy in a stand-alone Java application. Be able to configure Spring to manage and consume a generated WSDL2Java client proxy .
4
Web Services with Apache CXF
Java XML Binding Modeling Web Service Messages with JAXB
5
Java and XML The Marriage of XML and Java:
XML is a data markup language. Used for long or short-term data storage. Useful for data transfer between vastly different architectures. Particularly useful for web service architectures. Java is an object-oriented programming language. Unmarshalls (reads) data from existing XML into Java data objects. Performs manipulations on Java objects via services. Marshalls (writes) Java objects into a new XML representation. XML is platform agnostic. Can be strongly typed through use of an XML schema.
6
Java and XML: Choices, choices….
The marriage of Java and XML has produced a large family of technologies, strategies, and libraries: DOM XML Beans StAX JDOM JAXP XStream DOM4J and many more…. JAXB
7
Java and XML: Overview Most Java XML strategies fall into three spaces: DOM (Document Object Model) Entire document model is held in memory as nodes in a document tree. Streaming An event-based API for operating on each piece of the XML document individually and in sequence. Often used to stream XML for building DOM trees or construct XML Object bindings. XML-to-Object Binding XML types and elements are bound to Java types and fields. In practice, most solutions use some combination of these. DOM – When to use? JDOM DOM4J Streaming – When to use? SAX StAX XML Object Binding – When to use? JAXB – Java API for XML Binding XML Objects Java web service solutions typically use an XML object binding solution.
8
JAXB: A Data Binding Solution
The JAXB API is the standard solution provided by the JDK for Java XML data binding: Java classes are bound to XML types, elements, and attributes through Java annotations. A XML streaming event-based (StAX) parser is used to parse XML documents and construct Java objects as well as to write Java objects back to XML. The XJC tool (included in the JDK) can generate JAXB annotated classes from an existing XML Schema. The Schemagen tool (also included in the JDK) can generate an XML schema from JAXB annotated classes.
9
JAXB and Web Services As a data modeling API, JAXB is particularly useful to web services, because: XML is the most common form of data transport. Annotated Java classes can be made to represent XML schema types. JAXB APIs can unmarshall XML into Java data objects and back again. Fits into an RPC-style of service method invocation with POJO parameters and results. * Note that the CXF web service framework automatically handles the marshalling and unmarshalling of XML data to and from JAXB annotated Java classes.
10
JAXB: Marshalling and Unmarshalling
Although CXF handles the marshalling and unmarshalling of serviced XML, it can be helpful to know how CXF does it. A web service developer occasionally needs to experiment with how JAXB annotations affect the parsing and rendering of XML. A web service developer often needs to debug issues that arise from data being marshalled or unmarshalled incorrectly. The JAXB Marshalling/Unmarshalling APIs can be used to apply additional validation or to generate a schema.
11
JAXB makes unmarshalling from XML easy:
JAXB: Unmarshalling JAXB makes unmarshalling from XML easy: // Just create a JAXB context for your Java data classes JAXBContext jaxb = JAXBContext.newInstance(myClasses); // Then unmarshall the XML document into instances of // those classes. MyClass obj = (MyClass) jaxb.createUnmarshaller().unmarshall(xml) The Unmarshaller can accept XML input as a character stream, a file, a DOM node, or several other input types. Classes passed to the JAXBContext cannot be interfaces, etc.
12
Marshalling objects into XML is just as easy:
JAXB: Marshalling Marshalling objects into XML is just as easy: // Create a JAXB context for your Java data classes JAXBContext jaxb = JAXBContext.newInstance(myClasses); // Marshall your Java object hierarchy into an XML document. jaxb.createMarshaller().marshall(myObject, output); The Marshaller can serialize the XML to a character stream, a file, a DOM node, or several other output types.
13
JAXB: The Context Instances of the JAXBContext class effectively represent an “in-memory” schema of your data: It is a registry of all the classes that can be bound to XML types. It is a factory for Marshaller and Unmarshaller instances. It can be supplied listeners and a Schema for additional validation. It can be used to generate an XML Schema from your JAXB annotated classes. Relate to how CXF uses JAXBContext
14
JAXB: Non-annotated Class Demo
XML Output without JAXB Annotations Show source POJO Show sample XML output
15
JAXB: Annotations Although JAXB can bind almost any Java data object with little or no annotations, annotations are typically desirable, for example: They can tell JAXB whether to unmarshal a field into an attribute or an element. They can inform JAXB of ID fields, element order, and other schema constraints. They can be used to identify or customize schema types, element names, attribute names, element wrapping, etc.
16
JAXB: Common Annotations
JAXB defines many annotations to customize Java XML data binding. Here are just a few: @XmlRootElement @XmlElementRef @XmlElement @XmlElementRefs @XmlAttribute @XmlTransient @XmlElementWrapper These and more can be found in the following package: javax.xml.bind.annotation <insert link to docs or tutorial> @XmlType = Binds a java class to an XML type @XmlRootElement = Identifies an class as being a potential XML document root element. @XmlElement = Identifies a non-static member field as an XML element. (for simple or complex types) @XmlAttribute = Identifies a non-static member field as an XML attribute. (for simple types) @XmlID = Identifies a property as being a unique identifier within the context of an XML document. @XmlElementWrapper = Most often used on collection fields, it identifies the element that wraps that field. @XmlElementRef = Identifies a Java class that can be used for unmarshalling an XML element to a field. (*for complex types) @XmlElementRefs = A container for one or annotations. @XmlList = Used to unmarshal a whitespace-delimited XML attribute or element into a list. (*for simple types only) @XmlTransient = Used to mark a property as not being bound to any XML types.
17
JAXB: Non-annotated Class Demo
XML Output with JAXB Annotations Show source POJO Show annotations Show sample XML output Compare with previous, non-annotated demo
18
JAXB: Rules and Conventions
Some general rules about JAXB annotations: Concrete classes must have a public default no-arg constructor. Properties that reference interfaces must be annotated with one or annotations that identify the possible concrete types. Annotations may be placed on the fields or on the setters but not on both. By convention, annotating fields is preferable for simple POJOs. Properties not bound to XML values must be annotated Note that annotating fields causes JAXB to set the value directly on the field. The setter will not be called. (Verify whether mixed annotations are allowed.)
19
Lab 1: JAXB Data Binding Apache CXF: SOAP: Lab 1
20
Web Services with Apache CXF
WSDL to Java Consuming 3rd Party Web Services
21
Using a client JAR prepared by the service provider.
WSDL 2 Java Third-party SOAP web services are typically consumed in one of two ways: Using a client JAR prepared by the service provider. Contains the necessary Java classes and stubs for accessing the web service. Using a WSDL-to-Java tool. Automatically generates the necessary Java classes and stubs from a published web service descriptor, or WSDL. Cover WSDL to Java generically
22
WSDL to Java: Code Generation
What is generated by a WSDL to Java tool? A service client. Will extend javax.xml.ws.Service and/or be annotated with One or more service endpoint interfaces. Will have annotation Model classes bound to any complex XML types used by the service. Will have with JAXB annotations. Cover JAXB and service port stubs from WSDL What will be generated? Service client class (extends javax.xml.ws.Service) – How to use Endpoint interfaces annotated) – can be used JAXB model classes (JAXB annotated)
23
WSDL to Java: Code Generation
Demos A Generated Web Service Client A Generated Endpoint Interface Generated JAXB Model Classes Demo (In NetBeans) On Services tab, right-click on “Other” and “Add Web Service…” Supply a WSDL: Remind class that the endpoint url is the WSDL url without the ?wsdl query. Click OK. Show the two endpoints Expand geoipservice-asmx -> GeoIPServiceSoap12 -> GetGeoIP Right-click GeoIP node and “Test Method” Supply an IP Address in the “Value” column: Click “Submit” and expand the GeoIP result. Compare WSDL to generated code in .netbeans/7.0/config/WebServices Open cached WSDL: ./geoipservice-asmx/catalog/ Point out the schema Point out the SOAP 1.2 endpoint and endpoint URL Open the service client: ./geoipservice-asmx/jaxws/GeoIPService-src.jar/net/webservicex/GeoIPService.java Open the SOAP 1.2 endpoint interface: ./GeoIPServiceSoap.java Open the JAXB model class: ./GeoIP.java
24
WSDL 2 Java: Code Generation
Client code generation is cool, but … When do you use it? Build-time generation Generate as part of build so you don’t own the code. Can make tweaks to generated code. When to use? WSDL changing or don’t want to manage generated source
25
WSDL to Java: Code Generation
Option #1: One-time generation Run command-line tools and copy to project. wsimport (JDK) wsdl2java (CXF) IDE Web Service Client Wizards When to use? Need to customize what is generated Want to avoid dependence on build tools One time generation Command line tools to generate source, copy into project JDK tools CXF tools IDE to generate and copy into project. When to use? Want to tweak what is generated, etc.
26
WSDL to Java: Code Generation
Option #2: Build-time generation Using Maven Plugins: org.codehaus.mojo:jaxws-maven-plugin Uses the JDK wsimport tool org.apache.cxf:cxf-codegen-plugin Uses the CXF wsdl2java tool When to use? Need to stay up-to-date with a changing WSDL. Don’t need to tweak generated code Don’t want to own or manage the generated source code. Build-time generation Generate as part of build so you don’t own the code. Can make tweaks to generated code. When to use? WSDL changing or don’t want to manage generated source
27
WSDL to Java: Code Generation
Due to its rich Spring integration, the Java Stack recommends the CXF wsdl2java tool to consume third-party SOAP services. Maven Usage: <plugin> <groupId>org.apache.cxf</groupId> <artifactId>cxf-codegen-plugin</artifactId> <executions>...</executions> </plugin> CXF Codegen plugin Maven artifact info Goal(s) Configuration Intro to lab
28
Maven execution: <execution> <id>wsdl2java</id>
<phase>generate-sources</phase> <goals><goal>wsdl2java</goal></goals> <configuration> <wsdlOptions> <wsdlOption> <wsdl>${wsdlUrl}</wsdl> </wsdlOption> </wsdlOptions> </configuration> </execution>
29
Lab 2: Using WSDL to Java WSDL to Java: Lab 2
30
WSDL to Java: Spring Integration
Managing the generated endpoint with Spring: When the generated stubs aren’t enough. Need to apply security (WSS4J/Spring Security) Need to apply additional in/out interceptors Stack namespace handler: <stack-ws:consume/> To simplify common security and configuration needs CXF namespace handler: <jaxws:client/> For more advanced client configuration. When to use Spring/CXF/Stack to consume the endpoint Which interface to give the consume namespace handler Demo Spring integration test that consumes the endpoint and injects it into an integration test.
31
WSDL to Java: Spring Configuration
Attributes to <stack-ws:consume/> service-class The bean name of the endpoint implementation class. endpoint The published endpoint service address. user, password, password-type For user authentication. Both plain text and digest passwords are supported. wam-authenticator, wam-cookie-resolver-ref Provides authentication through WAM ssl-trust-server Specifies whether the server’s SSL cert should be automatically trusted.
32
WSDL to Java: Spring Configuration
Example Usage: <stack-ws:consume service-class="org.lds.MyService" endpoint=" <stack-ws:in-interceptors> <bean idref="customInInterceptor2"/> </stack-ws:in-interceptors> <stack-ws:out-interceptors> <bean idref="customOutInterceptor1"/> </stack-ws:out-interceptors> </stack-ws:consume>
33
WSDL to Java: Spring Integration
Demo Using an endpoint interface generated by WSDL to Java in a Spring integration test.
34
Conclusion The standard Java APIs can be used to model your data for use by web services. The JDK, CXF, and the Java Stack provide code generation and configuration utilities to make it easier to consume third-party web services. For more information about JAXB and CXF, please visit the links on the following page.
35
Resources On the web: http://cxf.apache.org Java 6 API Documentation
JDK 6 Programmer Guides Java Stack Documentation
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.