ocewsd6_studyguide_mikalaizaikin

107
Oracle Certified Expert, Java Platform, Enterprise Edition 6 Web Services Developer Study Guide Next Oracle Certified Expert, Java Platform, Enterprise Edition 6 Web Services Developer Study Guide Mikalai Zaikin IBA JV Belarus Minsk <NZaikin[at]iba.by> Copyright © 2012 Mikalai Zaikin Redistribution of this document is permitted as long as it is not used for profits. July 2012 Revision History Revision $Revision: 120 $ $Date: 2012-07-21 22:34:48 +0300 (сб, 21 Ліп 2012) $ $Author: mzaikin $ $Id: ocewsd6-guide.xml 120 2012-07-21 19:34:48Z mzaikin $ Abstract The purpose of this document is to help in preparation for Java Platform, Enterprise Edition 6 Web Services Developer Certified Expert Exam (CX-310-232). This document should NOT be used as the only study material for "Oracle Certified Expert Web Services Developer for Java EE6" test (a.k.a. SCDJWS 6). It covers the Beta Test objectives, which may not match the Production Test objectives. I tried to make this document as much accurate as possible, but if you find any error, please let me know. Preface I. Exam Objectives 1. Create an SOAP web service in a servlet container 1.1. Create a web service starting from a WSDL file using JAX-WS 1.1.1. Use wsimport tool to generate artifacts from WSDL 1.1.2. Use external and embedded <jaxws:package>, <jaxws:enableWrapperStyle>, <jaxws:class> customizations 1.1.3. Use JAXB customizations to configure mapping. 1.1.4. Build the web service implementation using the above artifacts. 1.1.5. Access MessageContext.SERVLET_CONTEXT from the injected @WebServiceContext 1.1.6. Configure deployment descriptors ( web.xml, webservices.xml) for URL patterns, HTTP security, container authorization, caller authentication, and message protection. JAX-WS runtime may also be configured to perform message layer authentication and protection. 1.1.7. Compile and package the web service into a WAR file 1.1.8. Deploy the web service into a Java EE servlet container 1.2. Create a web service starting from a WSDL file using JAX-WS 1.2.1. Use @WebService to indicate a service 1.2.2. Use @WebMethod, @WebMethod(exclude) to indicate service methods 1.2.3. Use @SOAPBinding to select doc/lit, doc/bare, rpc/lit style of web service 1.2.4. Use @Oneway where the service doesn't have any response 1.2.5. Use @WebParam, and @WebResult to customize parameter and operation names 1.2.6. Use checked exceptions to indicate service specific faults. 1.2.7. Use wsgen tool to generate artifacts in Java EE5 (optional in Java EE6, as artifacts are generated at run time). 1.2.8. Configure deployment descriptors ( web.xml, webservices.xml) for URL patterns, HTTP security, container authorization, caller authentication, and message protection. JAX-WS runtime may also be configured to perform message layer authentication and protection. 1.2.9. Compile and package the web service into a WAR file 1.2.10. Deploy the web service into a Java EE servlet container 2. Create a RESTful web service in a servlet container 2.1. Create a web service using JAX-RS, refer to Jersey implementation for examples 2.1.1. Annotate a class with a @Path annotation to respond to URI templates. 2.1.2. Annotate the class's methods to respond to HTTP requests using the corresponding JAX-RS annotations ( @GET, @POST, etc.). 2.1.3. Use the JAX-RS @Consumes and @Produces annotations to specify the input and output formats for the RESTful web service. 2.1.4. Use @PathParam, @QueryParam, @MatrixParam and @HeaderParam to extract request data. 2.1.5. Use the UriInfo and UriBuilder to create URIs that refer to resources in the service. 2.1.6. Use ResponseBuilder to create response with customized status and additional metadata. 2.1.7. Implement a MessageBodyReader and MessageBodyWriter to add support for custom request and response data types 2.1.8. Implement ExceptionMapper to map a custom Exception to a response. 2.1.9. Use Request to add support for HTTP preconditions. 2.1.10. Implement the functionality of the JAX-RS resource's methods. 2.1.11. Use @Path on a method to define a subresource. 2.1.12. Configure deployment descriptor ( web.xml) for base URL pattern, HTTP security (via security-constraints in web.xml) 2.1.13. Compile and package 2.1.14. Deploy the web service in a Java EE servlet container 3. Create a SOAP based web service implemented by an EJB component 3.1. Create a web service starting from a WSDL file using JAX-WS converted by Web2PDFConvert.com

Upload: rogerwu

Post on 03-Nov-2014

124 views

Category:

Documents


1 download

TRANSCRIPT

Oracle Certified Expert, Java Platform, Enterprise Edition 6 Web Services Developer Study Guide Next

Oracle Certified Expert, Java Platform, Enterprise Edition 6 Web Services Developer Study GuideMikalai ZaikinIBA JV Belarus Minsk

Copyright 2012 Mikalai Zaikin Redistribution of this document is permitted as long as it is not used for profits. July 2012Revision History Revision $Revision: 120 $ $Date: 2012-07-21 22:34:48 +0300 (, 21 2012) $ $Id: ocewsd6-guide.xml 120 2012-07-21 19:34:48Z mzaikin $

$Author: mzaikin $

Abstract The purpose of this document is to help in preparation for Java Platform, Enterprise Edition 6 Web Services Developer Certified Expert Exam (CX-310-232). This document should NOT be used as the only study material for "Oracle Certified Expert Web Services Developer for Java EE6" test (a.k.a. SCDJW S 6). It covers the Beta Test objectives, w hich may not match the Production Test objectives. I tried to make this document as much accurate as possible, but if you find any error, please let me know . Preface I. Exam Objectives 1. Create an SOAP w eb service in a servlet container 1.1. Create a w eb service starting from a W SDL file using JAX-W S 1.1.1. Use wsimport tool to generate artifacts from W SDL 1.1.2. Use external and embedded , , customizations 1.1.3. Use JAXB customizations to configure mapping. 1.1.4. Build the w eb service implementation using the above artifacts. 1.1.5. Access MessageContext.SERVLET_CONTEXT from the injected @WebServiceContext 1.1.6. Configure deployment descriptors ( web.xml, webservices.xml) for URL patterns, HTTP security, container authorization, caller authentication, and message protection. JAX-W S runtime may also be configured to perform message layer authentication and protection. 1.1.7. Compile and package the w eb service into a W AR file 1.1.8. Deploy the w eb service into a Java EE servlet container 1.2. Create a w eb service starting from a W SDL file using JAX-W S 1.2.1. Use @WebService to indicate a service 1.2.2. Use @WebMethod, @WebMethod(exclude) to indicate service methods 1.2.3. Use @SOAPBinding to select doc/lit, doc/bare, rpc/lit style of w eb service 1.2.4. Use @Oneway w here the service doesn't have any response 1.2.5. Use @WebParam, and @WebResult to customize parameter and operation names 1.2.6. Use checked exceptions to indicate service specific faults. 1.2.7. Use wsgen tool to generate artifacts in Java EE5 (optional in Java EE6, as artifacts are generated at run time). 1.2.8. Configure deployment descriptors ( web.xml, webservices.xml) for URL patterns, HTTP security, container authorization, caller authentication, and message protection. JAX-W S runtime may also be configured to perform message layer authentication and protection. 1.2.9. Compile and package the w eb service into a W AR file 1.2.10. Deploy the w eb service into a Java EE servlet container 2. Create a RESTful w eb service in a servlet container 2.1. Create a w eb service using JAX-RS, refer to Jersey implementation for examples 2.1.1. Annotate a class w ith a @Path annotation to respond to URI templates. 2.1.2. Annotate the class's methods to respond to HTTP requests using the corresponding JAX-RS annotations ( @GET, @POST, etc.). 2.1.3. Use the JAX-RS @Consumes and @Produces annotations to specify the input and output formats for the RESTful w eb service. 2.1.4. Use @PathParam, @QueryParam, @MatrixParam and @HeaderParam to extract request data. 2.1.5. Use the UriInfo and UriBuilder to create URIs that refer to resources in the service. 2.1.6. Use ResponseBuilder to create response w ith customized status and additional metadata. 2.1.7. Implement a MessageBodyReader and MessageBodyWriter to add support for custom request and response data types 2.1.8. Implement ExceptionMapper to map a custom Exception to a response. 2.1.9. Use Request to add support for HTTP preconditions. 2.1.10. Implement the functionality of the JAX-RS resource's methods. 2.1.11. Use @Path on a method to define a subresource. 2.1.12. Configure deployment descriptor ( web.xml) for base URL pattern, HTTP security (via security-constraints in web.xml) 2.1.13. Compile and package 2.1.14. Deploy the w eb service in a Java EE servlet container 3. Create a SOAP based w eb service implemented by an EJB component 3.1. Create a w eb service starting from a W SDL file using JAX-W S

converted by Web2PDFConvert.com

3.1.1. Use wsimport tool to generate artifacts and use customization files for w simports if needed 3.1.2. Create an EJB w eb service implementations using annotations ( @Stateless or @Singleton) 3.1.3. Configure deployment descriptors ( ejb-jar.xml, webservices.xml) for transactions, etc. 3.1.4. Configure container role based access control via method-permissions in ejb-jar.xml or via access control annotations on EJB. 3.1.5. Configure caller authentication and message protection; either by Servlet Container via web.xml, and/or by JAX-W S message processing runtime. 3.1.6. Compile and package the w eb service into a EAR/W AR file (Java EE 6 - W AR can also have EJBs). 3.1.7. Deploy the w eb service into a Java EE container. 3.2. Create a w eb service starting from a Java source using JAX-W S 3.2.1. 3.2.2. 3.2.3. 3.2.4. 3.2.5. 3.2.6. Use wsgen tool to generate artifacts in Java EE5 from EJB classes (optional in Java EE 6 - as artifacts are generated at run time). Configure deployment descriptors ( ejb-jar.xml, webservices.xml) for transactions, etc. Configure container role based access control via method-permissions in ejb-jar.xml or via access control annotations on EJB. Configure caller authentication and message protection; either by Servlet Container via web.xml, and/or by JAX-W S message processing runtime. Compile and package the w eb service into a W AR/EAR file. Deploy the w eb service into a Java EE container.

4. Create a RESTful w eb service implemented by an EJB component 4.1. Create a w eb service using JAX-RS from EJB classes. 4.1.1. Annotate an enterprise bean class w ith a @Path annotation to respond to URL patterns. 4.1.2. Annotate the class's methods to respond to HTTP requests using the corresponding JAX-RS annotations ( @GET, @POST, etc.). 4.1.3. Use the JAX-RS @Produces and @Consumes annotations to specify the input and output resources for the RESTful w eb service. 4.1.4. Implement the functionality of the JAX-W S resource's methods. 4.1.5. Configure container role based access control via method-permissions in ejb-jar.xml or via access control annotations on EJB. 4.1.6. Configure caller authentication (for access control protected methods) and message protection by Servlet Container via web.xml. 4.1.7. Compile and package. 4.1.8. Deploy the w eb service in a Java EE servlet container. 5. Configure Java EE security for a SOAP w eb service 5.1. Configure security requirements of service using Java EE-container based security (overlaps w ith steps in other tasks - repeated here for convenience) 5.1.1. Configure security requirements through deployment descriptors ( web.xml, webservices.xml) for a Servlet-based w eb service endpoint: container authorization, caller authentication, and message protection. JAX-W S runtime may also be configured to perform message layer authentication and protection. 5.1.2. Configure security requirements through deployment descriptors ( ejb-jar.xml, webservices.xml) for EJB-based w eb service endpoint: 5.1.3. Configure security requirements through deployment descriptor ( web.xml) for JAX-RS based w eb service endpoint. 6. Create a w eb service client for a SOAP based w eb service 6.1. Create a standalone client. 6.1.1. Use wsimport to generate artifacts. 6.1.2. Create a client application using these artifacts. 6.1.3. Package and deploy accordingly. 6.2. Create a client in a managed component in a EE container. 6.2.1. Use wsimport to generate artifacts. 6.2.2. Using @WebserviceRef in the client application. 6.2.3. Package and deploy accordingly. 7. Create a w eb service client for a RESTful w eb service 7.1. 7.2. 7.3. 7.4. 7.5. 7.6. Use Use Use Use Use Use a brow ser to access a JAX-RS resource the java.net.* APIs to access a JAX-RS resource. java.net.Authenticator to access a secure JAX-RS resource. Ajax to access a JAX-RS resource. the Jersey client API to access a JAX-RS resource. the JAX-W S HTTP binding to access a JAX-RS resource.

8. Create a SOAP based w eb service using Java SE platform. 8.1. Create a w eb service starting from a W SDL file using JAX-W S. 8.1.1. Use wsimport tool to generate artifacts and use customization files for w simports if needed. 8.1.2. Build the w eb service implementation using the above artifacts. 8.1.3. Use Endpoint API to configure and deploy it in Java SE 6 platform. 8.2. Create a w eb service starting from a Java source using JAX-W S. 8.2.1. Use wsgen tool to generate artifacts in Java EE5 (optional in Java EE6 - as artifacts are generated at run time) 8.2.2. Use Endpoint API to configure and deploy it in Java SE 6 platform. 9. Create handlers for SOAP w eb services. 9.1. Configure SOAP and logical handlers on the server side. 9.1.1. Use @HandlerChain annotation. 9.1.2. Use deployment descriptors. 9.2. Configure SOAP and logical handlers on the client side. 9.2.1. Use deployment descriptors. 9.2.2. Use programmatic API. 10. Create low -level SOAP w eb services. 10.1. Describe the functions and capabilities of the APIs included w ithin JAXP. 10.2. Describe the functions and capabilities of JAXB, including the JAXB process flow , such as XML-to-Java and Java-to-XML, and the binding and validation mechanisms provided by JAXB. 10.3. Use Provider API to create a w eb service. 10.3.1. Process the entire SOAP message, using the SAAJ APIs. 10.3.2. Process only the SOAP body, using JAXB. 10.4. Use Dispatch API to create a dynamic w eb service client.

converted by Web2PDFConvert.com

11. Use MTOM and MIME in a SOAP w eb service. 11.1. Use MTOM on the service. 11.1.1. 11.1.2. 11.1.3. 11.1.4. 11.1.5. 11.1.6. Use Use Use Use Use Use

@MTOM annotation w ith a w eb service.MTOM policy in W SDL. MTOM in the deployment descriptors MTOMFeature w ith javax.xml.ws.Endpoint API swaRef in W SDL. MIME binding in W SDL

11.2. Use MTOM on the client. 11.2.1. Use MTOMFeature w ith getPort() methods. 11.2.2. Use MTOM in the deployment descriptors. 11.2.3. Sending any additional attachments using MessageContext properties. 12. Use W S-Addressing w ith a SOAP w eb service 12.1. Use Addressing on the service 12.1.1. 12.1.2. 12.1.3. 12.1.4. 12.1.5. 12.1.6. Use Use Use Use Use Use

@Addressing annotation w ith a w eb service wsam:Addressing policy in W SDLAddressing in the deployment descriptors AddressingFeature w ith javax.xml.ws.Endpoint API. @Action and @FaultAction on the service methods.

WebServiceContext.getEndpointReference()

12.2. Use Addressing on the client. 12.2.1. 12.2.2. 12.2.3. 12.2.4. Use Use Use Use

AddressingFeature w ith getPort() methods.Addressing in the deployment descriptors

BindingProvider.getEndpointReference() getPort(EndpointReference) methods.

13. Configure Message Level security for a SOAP w eb service 13.1. Select the appropriate Security Profile for your service. The selection w ould be based on a match of the Protection guarantees offered by the profile and those required by the service. 13.2. Configure Username/Passw ord callbacks required by the Username Token Profile. 13.3. Configure any server side Validators as maybe applicable for the profile. There are defaults in GlassFish for most of them. 13.4. Optimize interaction betw een client and server by using W S-SecureConversation. 14. Apply best practices to design and implement w eb services. 14.1. 14.2. 14.3. 14.4. II. Appendices 1. To be added 1.1. To be addedNext Preface

Use different encoding schemes - fast infoset. Use GZIP for optimiziing message sizes. Use catalog mechanism for W SDL access. Refer to W S-I sample app for best practices.

Hosting provided by PerfoHost: KVM VPS provider. See PefoHost's KVM VPS vs OpenVZ/Virtuozzo vs XEN VPS comparative chart. CRM-exporter: Vehicle Database Script 1999-2011

converted by Web2PDFConvert.com

Prev

Chapter 1. Create an SOAP web service in a servlet container Part I. Exam Objectives

Next

Chapter 1. Create an SOAP web service in a servlet container 1.1. Create a web service starting from a WSDL file using JAX-WS1.1.1. Use wsimport tool to generate artifacts from WSDLJAX-W S provides the wsgen and wsimport command-line tools to generate portable artifacts for JAX-W S w eb services. W hen creating JAX-W S w eb services, you can start w ith either a W SDL file or an implementation bean class. If you start w ith an implementation bean class, use the wsgen command-line tool to generate all the w eb services provider artifacts, including a W SDL file if requested. If you start w ith a WSDL file, use the wsimport command-line tool to generate all the w eb services artifacts for either the server or the client. The wsimport command-line tool processes the W SDL file w ith schema definitions to generate the portable artifacts, w hich include the service class, the service endpoint interface class, and the JAXB 2.1 classes for the corresponding XML schema. The wsimport tool generates JAX-W S portable artifacts, such as: Service Endpoint Interface (SEI) Service Exception class mapped from wsdl:fault (if any) Async Reponse Bean derived from response wsdl:message (if any) JAXB generated value types (mapped Java classes from schema types) Syntax:

wsimport [options]

Options:

-d Specify w here to place generated output files

-b Specify external JAX-W S or JAXB binding files or additional schema files (Each must have its ow n -b)

-B Pass this option to JAXB schema compiler.

-keepKeep generated source code files. It is enabled w hen -s option.

-pSpecifying a target package via this command-line option, overrides any w sdl and schema binding customization for package name and the default package name algorithm defined in the specification.

-s Specify w here to place generated source code files. -keep is turned on w ith this option.

-wsdllocation @WebServiceClient.wsdlLocation value.Multiple JAX-W S and JAXB binding files can be specified using -b option and they can be used to customize various things like package names, bean names, etc. Example:

wsimport -p stockquote http://java.boot.by/StockQuote?wsdlThis w ill generate the Java artifacts and compile them by importing the http://java.boot.by/StockQuote?wsdl

1.1.2. Use external and embedded , , customizationsExternal Binding Declaration External binding files are semantically equivalent to embedded binding declarations. W hen wsimport processes the W SDL document for w hich there is an external binding file, it internalizes the binding declarations defined in the external binding file on the nodes in the W SDL document they target using the wsdlLocation attribute. The embedded binding declarations can exist in a W SDL file and an external binding file targeting that W SDL, but wsimport may give an error if, upon embedding the binding declarations defined in the external binding files, the resulting W SDL document contains conflicting binding declarations. Embedded Binding Declarations Embedded binding declarations follow different rules compared to the binding declarations declared in the external binding file. Here are some important facts and rules as defined in the JAX-W S 2.0 specification: An embedded binding declaration is specified by using the jaxws:bindings element as a W SDL extension. W hen a jaxws:bindings element is used as a W SDL extension, it must not have a node attribute. The binding declaration must not have a child element w hose qualified name is jaxws:bindings. A binding declaration embedded in a W SDL can only affect the W SDL element it extends. Here's an example of embedded binding declarations in the W SDL:

... ...

converted by Web2PDFConvert.com

The above W SDL file excerpt show s the wsdl:portType customization. jaxws:bindings appears as extension element of portType. It customizes the class name of the generated service endpoint interface. W ithout this customization, or by default, the service endpoint interface class is named after the wsdl:portType name. The binding declaration jaxws:class customizes the generated class to be named MathUtil instead of AddNumberImpl. Package Customization By default wscompile generates W SDL artifacts in a package computed from the W SDL targetNamespace. For example, a W SDL file w ith the targetNamespace http://java.boot.by w ithout any package customization w ill be mapped to the by.boot.java package. To customize the default package mapping you w ould use a jaxws:package customization on the wsdl:definitions node or it can directly appear inside the top level bindings element. An important thing to note is that -p option on command-line wsimport tool ( package attribute on wsimport Ant task), overrides the jaxws:package customization, it also overrides the schema package customization specified using JAXB schema customization. For example:

Mathutil package ...

or:

Mathutil package ...

Wrapper Style

wsimport by default applies w rapper style rules to the abstract operation defined in the wsdl:portType, and if an operation qualifies the Java method signature is generated accordingly. W rapper style Java method generation can be disabled by using jaxws:enableWrapperStyle. jaxws:enableWrapperStyle can appear on the toplevel bindings element (w ith @wsdlLocation attribute), it can also appear on the follow ing target nodes: wsdl:definitions: global scope, applies to all the wsdl:operations of all wsdl:portType attributes. wsdl:portType applies to all the wsdl:operations in the portType. wsdl:operation applies to only this wsdl:operation.For example:

true false ...

In the example above the w rapper style is disabled for the addNumbers operation in AddNumbersImpl portType. This is because wsimport processes this binding in the follow ing order: first wsdl:operation, then its parent wsdl:portType, and finally wsdl:definitions. Here wsdl:operation addNumbers has this customization disabled so this is w hat is applied by wsimport to generate a bare Java method signature. Class Customization The generated class for wsdl:portType, wsdl:fault, soap:headerfault, and wsdl:server can be customized using the jaxws:class binding declaration.

The Service Endpoint Interface Class

wscompile w ill generate the service endpoint interface class MathUtil instead of the default AddNumbersImpl in this example:

converted by Web2PDFConvert.com

Perform mathematical computations ...

The Exception Class

wsimport w ill generate the MathUtilException class instead of the default AddNumbersExeption in this example:

Exception generated during computation

The Service Class

wsimport w ill generate MathUtilService instead of the default AddNumbersService in this example:

Service to perform mathematical computations

1.1.3. Use JAXB customizations to configure mapping.Inline CustomizationsCustomizations to JAXB bindings made by means of inline binding declarations in an XML schema file take the form of elements embedded in schema elements ( xsd: is the XML schema namespace prefix, as defined in W 3C XML Schema Part 1: Structures). The general form for inline customizations is show n below :

. . binding declarations . .

Customizations are applied at the location at w hich they are declared in the schema. For example, a declaration at the level of a particular element w ould apply to that element only. Note that the XML Schema namespace prefix must be used w ith the and declaration tags. In the example above, xsd: is used as the namespace prefix, so the declarations are tagged and .

External Binding Customization FilesCustomizations to JAXB bindings made by means of an external file containing binding declarations take the general form show n below :

*

schemaLocation is a URI reference to the remote schema. node is an XPath 1.0 expression that identifies the schema node w ithin schemaLocation to w hich the given binding declaration is associated.For example, the first schemaLocation/node declaration in a JAXB binding declarations file specifies the schema name and the root schema node:

A subsequent schemaLocation/node declaration, say for a simpleType element named ZipCodeType in the above schema, w ould take the form:

Customization files containing binding declarations are passed to the JAXB Binding compiler, xjc, using the follow ing syntax:

xjc -b

converted by Web2PDFConvert.com

w here is the name of binding customization file, and is the name of the schema(s) you w ant to pass to the binding compiler. You can have a single binding file that contains customizations for multiple schemas, or you can break the customizations into multiple bindings files:

xjc schema1.xsd schema2.xsd schema3.xsd -b bindings123.xjb

xjc schema1.xsd schema2.xsd schema3.xsd -b bindings1.xjb -b bindings2.xjb -b bindings3.xjbNote that the ordering of schema files and binding files on the command line does not matter, although each binding customization file must be preceded by its ow n -b sw itch on the command line.

1.1.4. Build the web service implementation using the above artifacts.blah-blah

1.1.5. Access MessageContext.SERVLET_CONTEXT from the injected @WebServiceContextjavax.xml.ws.WebServiceContextThe javax.xml.ws.WebServiceContext interface makes it possible for an endpoint implementation object and potentially any other objects that share its execution context to access information pertaining to the request being served. The WebServiceContext is treated as an injectable resource that can be set at the time an endpoint is initialized. The WebServiceContext object w ill then use thread-local information to return the correct information regardless of how many threads are concurrently being used to serve requests addressed to the same endpoint object. In Java SE, the resource injection denoted by the WebServiceContext annotation is REQUIRED to take place only w hen the annotated class is an endpoint implementation class. The follow ing code show s a simple endpoint implementation class w hich requests the injection of its WebServiceContext:

@WebService public class Test { @Resource private WebServiceContext context; public String reverse(String inputString) { MessageContext mc = context.getMessageContext(); ServletContext servletContext = (ServletContext) mc.get(MessageContext.SERVLET_CONTEXT); ... } }The @javax.annotation.Resource annotation defined by JSR-250 is used to request injection of the WebServiceContext. Then invoke the getMessageContext() method and w ork w ith the MessageContext object.

1.1.6. Configure deployment descriptors (web.xml, webservices.xml) for URL patterns, HTTP security, container authorization, caller authentication, and message protection. JAX-WS runtime may also be configured to perform message layer authentication and protection.URL patterns The web.xml file contains information about the structure and external dependencies of w eb components in the module and describes how the components are used at run time. For Java API for XML-Based Web Services (JAX-W S) applications, you can customize the URL pattern in the web.xml file. W hen you package a JAX-W S application as a w eb service, the w eb service is contained w ithin a Web ARchive (W AR) file or a W AR module w ithin an enterprise archive (EAR) file. A JAX-W S enabled W AR file contains the follow ing items: A WEB-INF/web.xml file that describes configuration and deployment information for the w eb components that comprise a w eb application. Annotated classes that implement the w eb services contained in the application module including the service endpoint implementation class. JAXB classes. (Optional) Web Services Description Language (W SDL) documents that describe the w eb services contained in the application module. (Optional) XML schema files. (Optional) utility classes. (Optional) w eb service clients. The default URL pattern is defined by the @WebService.serviceName attribute that is contained in your w eb service implementation class. W hen the W SDL file that is associated w ith your service implementation class contains a single port definition, you can choose to use the default URL pattern or you can customize the URL pattern w ithin the web.xml file. W hen the W SDL file that is associated w ith your service implementation class contains multiple port definitions w ithin the same service definition, customized URL patterns are required. If you use the default URL pattern w hen the service implementation class contains multiple port definitions, then multiple service implementation classes are mapped to the same URL pattern w hich results in an error condition. You must edit the web.xml file and customize the URL patterns for each service definition. Each port maps to a w eb service implementation class and to its ow n custom URL pattern. By customizing the URL pattern in the web.xml file, you correct conflicting URL pattern definitions. 1. Determine if custom URL patterns are required or desired. Custom URL patterns are only required w hen the W SDL file for your JAX-W S w eb service contains multiple port definitions w ithin a single service. Otherw ise, you may optionally define custom URL patterns. 2. To customize the URL pattern for a service implementation class, edit the web.xml file and provide a and corresponding entry for each JAX-W S w eb service implementation class for w hich a custom URL pattern is desired. You must define the value w ithin the entry. The follow ing example illustrates the required URL pattern customizations w hen the W SDL file associated w ith the service implementation class has multiple port definitions. The follow ing excerpt is from a sample w eb service implementation classes:

package by.boot.java; @WebService(serviceName="EchoService", portName="SOAP11EchoServicePort") public class EchoServiceSOAP11{ ... }

package by.boot.java; @WebService(serviceName="EchoService", portName="SOAP12EchoServicePort") public class EchoServiceSOAP12{ ... }

converted by Web2PDFConvert.com

The follow ing excerpt is from the W SDL file associated w ith the EchoServiceSOAP11 w eb service implementation class. Each port in the W SDL file maps to a portName in the w eb service implementation class:

... ...

In this scenario, because there are multiple port definitions w ithin the W SDL file, you must customize the URL pattern by editing the web.xml file. Specify custom URL patterns for each service. The follow ing excerpt is from a sample web.xml file that demonstrates setting up a servlet:

by.boot.java.EchoServiceSOAP11 by.boot.java.EchoServiceSOAP11 1 by.boot.java.EchoServiceSOAP11 /EchoServiceSOAP11 by.boot.java.EchoServiceSOAP12 by.boot.java.EchoServiceSOAP12 1 by.boot.java.EchoServiceSOAP12 /EchoServiceSOAP12

Basic Authentication with JAX-WS W hen a service that is constrained by HTTP basic authentication is requested, the server requests a user name and passw ord from the client and verifies that the user name and passw ord are valid by comparing them against a database of authorized users. Annotating the Service In this example, annotations are used to specify w hich users are authorized to access w hich methods of this service. In this simple example, the @RolesAllowed annotation is used to specify that users in the application role of basicUser are authorized access to the sayHello(String name) method. This application role must be linked to a group of users on the Application Server. The code snippet is as follow s:

import javax.jws.WebMethod; import javax.jws.WebService; import javax.annotation.security.RolesAllowed; @WebService() public class Hello { private String message = new String("Hello, "); @WebMethod() @RolesAllowed("basicUser") public String sayHello(String name) { return message + name + "."; } }The @RolesAllowed annotation specifies that only users in the role of basicUser w ill be allow ed to access the sayHello(String name) method. A @RolesAllowed annotation implicitly declares a role that w ill be referenced in the application, therefore, no @DeclareRoles annotation is required. Adding Security Elements to the Deployment Descriptor To enable basic authentication for the service, add security elements to the application deployment descriptor, WEB-INF/web.xml. The security elements that need to be added to the deployment descriptor include the and elements:

com.sun.xml.ws.transport.http.servlet.WSServletContextListener HelloService HelloService com.sun.xml.ws.transport.http.servlet.WSServlet HelloService /hello

converted by Web2PDFConvert.com

SecurityConstraint WRCollection /hello basicUser NONE BASIC file

Linking Roles to Groups The role of basicUser has been defined for this application, but there is no group of basicUser defined for the Application Server. To map the role that is defined for the application ( basicUser) to a group that is defined on the Application Server ( user), add a element to the runtime deployment descriptor, WEB-INF/sun-web.xml, as show n below :

/helloservice basicUser user

Client Sample client against the secured w eb service:

import javax.xml.ws.WebServiceRef; import javax.xml.ws.BindingProvider; public class HelloClient { @WebServiceRef(wsdlLocation="http://localhost:8080/helloservice/hello?wsdl") static HelloService service; public static void main(String[] args) { try { Hello port = service.getHelloPort(); // Cast the proxy to a BindingProvider BindingProvider prov = (BindingProvider) port; prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "mikalai"); prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "secret"); String response = port.sayHello("Mikalai"); } catch(Exception e) { e.printStackTrace(); } } }There is one tricky aspect to the client: the use of the wsimport utility to generate the JAX-W S artifacts. The problem is that the w eb service's W SDL is also secured and therefore requires authentication for access. There are w orkarounds, of course. One option is to generate the W SDL locally by using the wsgen utility on the SIB. Another option is to get the W SDL from a nonsecure version of the service. The locally saved W SDL and its XSD are then fed into wsimport to generate the artifacts. The client application HelloClient uses the BindingProvider constants as keys for the username and passw ord. JAX-W S runrime expects the lookup keys for the username and passw ord to be the strings:

javax.xml.ws.security.auth.username javax.xml.ws.security.auth.passwordThese are the values of the BindingProvider constant USERNAME_PROPERTY and the constant PASSWORD_PROPERTY, respectively.

1.1.7. Compile and package the web service into a WAR fileblah-blah

1.1.8. Deploy the web service into a Java EE servlet containerblah-blahPrev Part I. Exam Objectives Up Home Next 1.2. Create a web service starting from a WSDL file using JAX-WS

Hosting provided by PerfoHost: KVM VPS provider. See PefoHost's KVM VPS vs OpenVZ/Virtuozzo vs XEN VPS comparative chart. CRM-exporter: Vehicle Database Script 1999-2011

converted by Web2PDFConvert.com

Prev

1.2. Create a web service starting from a WSDL file using JAX-WS Chapter 1. Create an SOAP web service in a servlet container

Next

1.2. Create a web service starting from a WSDL file using JAX-WS1.2.1. Use @WebService to indicate a serviceYou can use the @WebService and @WebMethod annotations on a service endpoint implementation to specify Java methods that you w ant to expose as Java API for XMLBased Web Services (JAX-W S) w eb services. JAX-W S technology enables the implementation of w eb services based on both the standard service endpoint interface and a Provider interface. W hen developing a JAX-W S Web service starting from existing Java classes, know n as the bottom-up approach, you must annotate the class w ith either the @WebService or @WebServiceProvider annotation to initially define the class as a w eb service. Using the Provider interface is the dynamic approach to defining your JAX-W S services. To use the Provider interface, your class must implement the javax.xml.ws.Provider interface, and contain the @WebServiceProvider annotation. The Provider interface has one method, the invoke method, w hich uses generics in the Java programming language to control both the input and output types w hen w orking w ith various messages or message payloads. To describe your w eb services using the service endpoint interface (SEI) approach, initially define a w eb service, annotate the Java class w ith the @WebService annotation. How ever, you can also selectively annotate the individual methods w ith @WebMethod annotation to control how these methods are exposed as w eb services operations.

@javax.jws.WebService marks a Java class as implementing a w eb service, or a Java interface as defining a w eb service interface:

@Retention(value=RetentionPolicy.RUNTIME) @Target({TYPE}) public @interface WebService { String name() default ""; String targetNamespace() default ""; String serviceName() default ""; String wsdlLocation() default ""; String endpointInterface() default ""; String portName() default ""; };Table 1.1. @javax.jws.WebServiceMember-Value Meaning The name of the web service. Used as the name of the wsdl:portType when mapped to WSDL 1.1. The XML namespace used for the WSDL and XML elements generated from this web service. The service name of the web service. Used as the name of the wsdl:service when mapped to WSDL 1.1. Not allowed on interfaces. Default The simple name of the Java class or interface. Implementation-defined, as described in JAX-RPC 1.1. Typically derived from the package containing the web service. The simple name of the Java class + "Service".

name targetNamespace

serviceName

wsdlLocation

The location of a pre-defined WSDL describing the service. The wsdlLocation is a URL (relative or absolute) that refers to a pre-existing WSDL file. The presence of a wsdlLocation value indicates that the service implementation bean is implementing a pre-defined WSDL contract. The JSR-181 tool MUST instead provide feedback if the service implementation bean is inconsistent with the portType and bindings declared in this WSDL. Note that a single WSDL file might contain multiple portTypes and multiple bindings. The annotations on the service implementation bean determine the specific portType and bindings that correspond to the web service. The complete name of the service endpoint interface defining the service's abstract web service contract. This annotation allows the developer to separate the interface contract from the implementation. If this annotation is present, the service endpoint interface is used to determine the abstract WSDL contract (portType and bindings). The service endpoint interface MAY include JSR-181 annotations to customize the mapping from Java to WSDL. The service implementation bean MAY implement the service endpoint interface, but is not REQUIRED to do so. Not allowed on interfaces.

None.

endpointInterface

None - the web service contract is generated from annotations on the service implementation bean. If a service endpoint interface is required by the target environment, it will be generated into an implementation-defined package with an implementation-defined name.

portName

The port name of the Web Service. Used as the name of the wsdl:port when mapped to WSDL 1.1. Not allowed on interfaces.

@WebService.name + "Port"

Example:

/** * Annotated Implementation Object */ @WebService( name = "EchoService", targetNamespace = "http://www.openuri.org/2004/04/HelloWorld"converted by Web2PDFConvert.com

) public class EchoServiceImpl { @WebMethod public String echo(String input) { return input; } }Use the follow ing best practices for defining w eb services: To define a basic w eb service, annotate the Java class w ith the @WebService annotation. To define your w eb services using an explicit SEI, add the @WebService annotation to a Java implementation class and explicitly reference a Java interface using the @WebService.endpointInterface attribute. To define your w eb services using an implicit SEI, add the @WebService annotation to a Java implementation class and do not define the @WebService.endpointInterface attribute. Provide a reference to a W SDL file in the @WebService.wsdlLocation attribute. By specifying a pre-defined W SDL file, performance is improved. Additionally, any discrepancies betw een the W SDL file and the annotations are reported to you by the runtime environment. W hen you use an explicit SEI, all public methods in the SEI and inherited classes are alw ays exposed. You only need to add @WebMethod annotations if you w ant to further customize the methods that are already exposed. If you define an implicit SEI, follow these rules to ensure that your methods are exposed consistently: Add an @WebService annotation to your implementation class and all its superclasses that contain methods that you w ant to expose. Adding an @WebService annotation to a class exposes all public methods in that class. If you w ant more granular control and expose only certain methods from a class that is annotated w ith the @WebService annotation, you can use the @WebMethod annotation on selected individual methods. The @WebMethod.exclude attribute is one of the criteria that is used to determine w hether a method is exposed as an operation. The default value for this attribute is false. To ensure that a method is exposed, annotate it w ith the @WebMethod annotation. If you w ant to make sure that a method is NOT exposed, annotate it w ith the @WebService(exclude=true) annotation.

1.2.2. Use @WebMethod, @WebMethod(exclude) to indicate service [email protected] customizes a method that is exposed as a w eb w ervice operation.

@Retention(value=RetentionPolicy.RUNTIME) @Target({METHOD}) public @interface WebMethod { String operationName() default ""; String action() default "" ; };The @WebMethod annotation includes the follow ing member-value pairs: Table 1.2. @javax.jws.WebMethodMember-Value Meaning Name of the wsdl:operation matching this method. The action for this operation. For SOAP bindings, this determines the value of the SOAPAction header. Marks a method to NOT be exposed as a web method. Used to stop an inherited method from being exposed as part of this web service. If this element is specified, other elements MUST NOT be specified for the @WebMethod. This member-value is not allowed on endpoint interfaces. Default The name of the Java method. ""

operationName action exclude

false

Java source:

@WebService public class MyWebService { @WebMethod(operationName = "echoString", action="urn:EchoString") public String echo(String input) { return input; } }Resulting W SDL:

converted by Web2PDFConvert.com

NOTE: Beginning w ith Sun and HP JDK Version 1.6 containing JAX-W S tooling Version 2.1.6, the behavior of the JAX-W S runtime environment and tooling has changed how it interprets the JAX-W S specification regarding exposing methods as w eb services operations. W hen the w eb service does not specify a pre-existing W SDL file, the JAX-W S tooling behavior that generates a W SDL file has changed. This change does not affect w eb services that reference a W SDL file. The change in semantics might affect w eb services that do not reference a W SDL file or a SEI, and they rely on the JAX-W S runtime environment to create a W SDL file. Using the NEW interpretation, a method in an implicit SEI and its superclasses are only exposed under the follow ing conditions: The method has an @WebMethod or @WebMethod(exclude=false) annotation. The method has no @WebMethod annotations, but the containing class has an @WebService annotation. Using the LEGACY interpretation, a method in an implicit SEI and its superclasses are only exposed under the follow ing conditions: The method has an @WebMethod or @WebMethod(exclude=false) annotation and the containing class has an @WebService annotation. The method has no @WebMethod annotations, but the containing class has a @WebService annotation and no other methods have @WebMethod or @WebMethod(exclude=false) annotations on it. Example:

public class Base { @WebMethod(exclude=false) public void superMethod1(String s) {...} public String superMethod2(String s) {...} }

@WebService(targetNamespace="foo") public class BeanImpl extends Base { @WebMethod(exclude=false) public void method1(String s) {...} public String method2(String s) {...} }Before JAX-W S 2.1.6, the only exposed method w ould be:

public void method1(String s) {...}In JAX-W S 2.1.6 and later the follow ing methods w ill be exposed:

public void superMethod1(String s) {...} public void method1(String s) {...} public String method2(String s) {...}

1.2.3. Use @SOAPBinding to select doc/lit, doc/bare, rpc/lit style of web [email protected] specifies the mapping of the w eb service onto the SOAP message protocol. The SOAPBinding annotation has a target of TYPE and METHOD. The annotation may be placed on a method if and only if the SOAPBinding.style is DOCUMENT. Implementations MUST report an error if the SOAPBinding annotation is placed on a method w ith a SOAPBinding.style of RPC. Methods that do not have a SOAPBinding annotation accept the SOAPBinding behavior defined onthe type. The @SOAPBinding annotation includes the follow ing member-value pairs: Table 1.3. @javax.jws.soap.SOAPBindingMember-Value Meaning Defines the encoding style for messages send to and from the web service. One of DOCUMENT or RPC. Defines the formatting style for messages sent to and from the web service. One of LITERAL or ENCODED. Determines whether method parameters represent the entire message body, or whether the parameters are elements wrapped inside a top-level element named after the operation. Default

style use parameterStyle

DOCUMENT LITERAL WRAPPED

@Retention(value=RetentionPolicy.RUNTIME) @Target({TYPE, METHOD})

converted by Web2PDFConvert.com

public @interface SOAPBinding { public enum Style { DOCUMENT, RPC }; public enum Use { LITERAL, ENCODED }; public enum ParameterStyle { BARE, WRAPPED } Style style() default Style.DOCUMENT; Use use() default Use.LITERAL; ParameterStyle parameterStyle() default ParameterStyle.WRAPPED; }RPC/LITERAL Java source:

@WebService(targetNamespace="http://www.openuri.org/jsr181/SoapBindingExample1") @SOAPBinding( style = SOAPBinding.Style.RPC, use = SOAPBinding.Use.LITERAL) public class ExampleService { @WebMethod public String concat(String first, String second, String third) { return first + second + third; } }Resulting W SDL:

Source objects are low level objects that hold XML documents. Each Source implementation provides methods that access the stored XML documents and manipulate its contents. The follow ing objects implement the Source interface: DOMSource SAXSource StreamSource Dispatch Dispatch objects can use javax.xml.soap.SOAPMessage objects w hen the follow ing conditions are true:the Dispatch object is using the SOAP binding. the Dispatch object is using message mode.

Dispatch Dispatch objects can use objects that implement the javax.activation.DataSource interface w hen the follow ing conditions are true:the Dispatch object is using the HTTP binding. the Dispatch object is using message mode.

DataSource objects provide a mechanism for w orking w ith MIME typed data from a variety of sources including URLs, files, and byte arrays. DispatchW hile Dispatch objects are intended to be low level API that allow s you to w ork w ith raw messages, they also allow you to w ork w ith JAXB objects. To w ork w ith JAXB objects a Dispatch object must be passed a JAXBContext that know s how to marshal and unmarshal the JAXB objects in use. The JAXBContext is passed

converted by Web2PDFConvert.com

w hen the Dispatch object is created. You can pass any JAXB object understood by the JAXBContext object as the parameter to the invoke(...) method. You can also cast the returned message into any JAXB object understood by the JAXBContext object. Code fragment below demonstrates how to make a POST request to http://java.boot.by/rest/acceptPO w ith the XML as the body of the POST request read from a poXML String:

private void acceptPO() { Service service = Service.create(serviceName); service.addPort(portName, HTTPBinding.HTTP_BINDING, endpointAddress + "/acceptPO"); Dispatch dispatcher = service.createDispatch(qname, Source.class, Service.Mode.PAYLOAD); Map requestContext = dispatcher.getRequestContext(); requestContext.put(MessageContext.HTTP_REQUEST_METHOD, "POST"); Source result = dispatcher.invoke(new StreamSource(new StringReader(poXML))); printSource(result); }

Code fragment below demonstrates how to make a similar POST request, but it sends and returns JAXB-generated objects rather than handling strings directly:

private void acceptPOJAXB() throws JAXBException { JAXBContext jc = ... Service service = Service.create(serviceName); service.addPort(portName, HTTPBinding.HTTP_BINDING, endpointAddress + "/acceptPO"); Dispatch dispatcher = service.createDispatch(qname, jc, Service.Mode.PAYLOAD); Map requestContext = dispatcher.getRequestContext(); requestContext.put(MessageContext.HTTP_REQUEST_METHOD, "POST"); JAXBElement order = new ObjectFactory().createPurchaseOrderDocument(createPO()); JAXBElement response = (JAXBElement)dispatcher.invoke(order); PurchaseOrderStatus result= response.getValue(); System.out.println("Order id is : " + result.getOrderid()); System.out.println("Timestamp is : " + result.getTimestamp()); }

Code fragment below demonstrates how to make a similar PUT request using the Dispatch interface:

private void updatePO() { Service service = Service.create(serviceName); service.addPort(portName, HTTPBinding.HTTP_BINDING, endpointAddress + "/updatePO"); Dispatch dispatcher = service.createDispatch(qname, Source.class, Service.Mode.PAYLOAD); Map requestContext = dispatcher.getRequestContext(); requestContext.put(MessageContext.HTTP_REQUEST_METHOD, "PUT"); Source result = dispatcher.invoke(new StreamSource(new StringReader(poXML))); printSource(result); }

Prev 7.5. Use the Jersey client API to access a JAX-RS resource.

Up Home

Next Chapter 8. Create a SOAP based web service using Java SE platform.

Hosting provided by PerfoHost: KVM VPS provider. See PefoHost's KVM VPS vs OpenVZ/Virtuozzo vs XEN VPS comparative chart. CRM-exporter: Vehicle Database Script 1999-2011

converted by Web2PDFConvert.com

Prev

Chapter 8. Create a SOAP based web service using Java SE platform. Part I. Exam Objectives

Next

Chapter 8. Create a SOAP based web service using Java SE platform. 8.1. Create a web service starting from a WSDL file using JAX-WS.8.1.1. Use wsimport tool to generate artifacts and use customization files for wsimports if needed.The wsimport command-line tool processes an existing Web Services Description Language (W SDL) file and generates the required portable artifacts for developing Java API for XML-Based Web Services (JAX-W S) w eb service applications. The wsimport command-line tool supports the top-dow n approach to developing JAX-W S w eb services. W hen you start w ith an existing W SDL file, use the wsimport command-line tool to generate the required JAX-W S portable artifacts. The wsimport tool reads an existing W SDL file and generates the follow ing portable artifacts: Service Endpoint Interface (SEI) - The SEI is the annotated Java representation of the W SDL file for the w eb service. This interface is used for implementing JavaBeans endpoints or creating dynamic proxy client instances.

javax.xml.ws.Service extension class - This is a generated class that extends the javax.xml.ws.Service class. This class is used to configure and create bothdynamic proxy and dispatch instances. Java Architecture for XML Binding (JAXB) beans that are required to model the w eb service data. Exception class mapped from wsdl:fault (if any). Async Reponse Bean derived from response wsdl:message (if any). Syntax:

wsimport [options]

-d directorySpecify w here to place generated output files.

-b pathSpecifies the external JAX-W S or JAXB binding files. You can specify multiple JAX-W S and JAXB binding files by using the -b option; how ever, each file must be specified w ith its ow n -b option.

-keepKeep generated files.

-pSpecifying a target package via this command-line option, overrides any w sdl and schema binding customization for package name and the default package name algorithm defined in the specification.

-s directorySpecify w here to place generated source files.

-wsdllocation locationThe w sdl URI passed thru this option w ill be used to set the value of @WebService.wsdlLocation and @WebServiceClient.wsdlLocation annotation elements on the generated SEI and Service interface. Multiple JAX-W S and JAXB binding files can be specified using -b option and they can be used to customize various things like package names, bean names, etc. Examples: This command generates JAX-W S portable artifacts for http://example.org/stock?wsdl in to the generated directory:

wsimport -d generated http://example.org/stock?wsdlThis command generates JAX-W S artifacts for stock.wsdl and uses the customization files stock.xml (JAX-W S customization file) and stock.xjb (JAXB customization file) in the process:

wsimport stock.wsdl -b stock.xml -b stock.xjb

8.1.2. Build the web service implementation using the above artifacts.For SOAP-based services, the W SDL represents the contract. This model has a single overarching paradigm: the W SDL defines the primary features of the contract for the service, and implementation-independent contracts are one of the cornerstone necessities of SOA. The contract is not an afterthought, but rather a central concern. W ith this model, you w rite the W SDL yourself by hand, generate a Java code shell for the service implementation, and then fill in the business logic for the service implementation. This method is also sometimes referred to as "Contract First." You start by taking a preexisting abstract W SDL and pointing it to a tool such as wsimport that produces a service endpoint interface in addition to Java classes that represent the schema definitions and message parts specified in the W SDL. Once the endpoint interface has been generated, w rite a Java class that implements that interface. The basic steps are as follow s: 1. W rite a W SDL representing the service you w ant to deploy. 2. Generate client-side code using wsimport. Among other things, this w ill generate a service interface for each portType.

converted by Web2PDFConvert.com

3. Implement each interface by w riting your w eb service implementation class. That means doing something like this:

@WebService( endpointInterface="by.boot.java.MyGeneratedInterface", wsdlLocation="/META-INF/wsdl/MyWsdl.wsdl" ) public class MyService implements MyGeneratedInterface { ... }4. Deploy the service endpoint implementation to a JAX-W S-compatible container. In this example, the endpoint interface is specified as a fully qualified name of the interface that wsimport generated, w ritten as a string. The W SDL location property allow s you to specify either a relative or an absolute URI. If relative, it must be in META-INF/wsdl. On a practical level, your organization might benefit from having a published W SDL released early in the project, so that client- and server-side development teams can w ork independently. Another key benefit to starting from W SDL is that XML schema affords a far richer set of data types than many programming languages. Starting from W SDL, you can offer a set of type options, maximizing interoperability.

8.1.3. Use Endpoint API to configure and deploy it in Java SE 6 platform.The Endpoint class can be used to create and publish w eb service endpoints. An endpoint consists of an object that acts as the w eb service implementation (called here implementor) plus some configuration information, e.g. a Binding. Implementor and binding are set w hen the endpoint is created and cannot be modified later. Their values can be retrieved using the getImplementor and getBinding methods respectively. Other configuration information may be set at any time after the creation of an Endpoint but before its publication. Endpoints can be created using the follow ing static methods on Endpoint:

create(Object implementor)Creates and returns an Endpoint for the specified implementor. If the implementor specifies a binding using the javax.xml.ws.BindingType annotation it MUST be used else a default binding of SOAP 1.1 / HTTP binding MUST be used.

Endpoint endpoint = Endpoint.create(new ExamplePort()); endpoint.publish("http://localhost:8080/exampleApp/ExampleService");

create(Object implementor, WebServiceFeature... features)Same as the above create() method. The created Endpoint is configured w ith the w eb service features. These features override the corresponding features that are specied in W SDL, if present.

create(String bindingID, Object implementor)Creates and returns an Endpoint for the specified binding and implementor. If the bindingID is null and no binding information is specified via the javax.xml.ws.BindingType annotation then a default SOAP 1.1 / HTTP binding MUST be used.

create(String bindingID, Object implementor, WebServiceFeature... features)Same as the above create() method. The created Endpoint is configured w ith the w eb service features. These features override the corresponding features that are specied in W SDL, if present.

publish(String address, Object implementor)Creates and publishes an Endpoint for the given implementor. The binding is chosen by default based on the URL scheme of the provided address (w hich must be a URL). If a suitable binding if found, the endpoint is created then published as if the Endpoint.publish(String address) method had been called. The created Endpoint is then returned as the value of the method. The follow ing code provides an example of its use:

// assume Test is an endpoint implementation class annotated with @WebService Test test = new Test(); Endpoint e = Endpoint.publish("http://localhost:8080/test", test);

publish(String address, Object implementor, WebServiceFeature... features)Same as the above publish() method. The created Endpoint is congured w ith the w eb service features. These features override the corresponding features that are specied in W SDL, if present. An Endpoint is in one of three states: not published (the default), published or stopped. Published endpoints are active and capable of receiving incoming requests and dispatching them to their implementor. Non published endpoints are inactive. Stopped endpoint w ere in the published until some time ago, then got stopped. Stopped endpoints cannot be published again. Publication of an Endpoint can be achieved by invoking one of the follow ing methods:

publish(String address)Publishes the endpoint at the specified address (a URL). The address MUST use a URL scheme compatible w ith the endpoint's binding.

publish(Object serverContext)Publishes the endpoint using the specified server context. The server context MUST contain address information for the resulting endpoint and it MUST be compatible w ith the endpoint's binding. The follow ing example show s the use of the publish(Object) method using a hypothetical HTTP server API that includes the HttpServer and HttpContext classes:

// assume Test is an endpoint implementation class annotated with @WebService Test test = new Test();

converted by Web2PDFConvert.com

HttpServer server = HttpServer.create(new InetSocketAddress(8080), 10); server.setExecutor(Executor.newFixedThreadPool(10)); server.start(); HttpContext context = server.createContext("/test"); Endpoint endpoint = Endpoint.create(SOAPBinding.SOAP11HTTP_BINDING, test); endpoint.publish(context);

Prev 7.6. Use the JAX-WS HTTP binding to access a JAX-RS resource.

Up Home

Next 8.2. Create a web service starting from a Java source using JAX-WS.

Hosting provided by PerfoHost: KVM VPS provider. See PefoHost's KVM VPS vs OpenVZ/Virtuozzo vs XEN VPS comparative chart. CRM-exporter: Vehicle Database Script 1999-2011

converted by Web2PDFConvert.com

Prev

8.2. Create a web service starting from a Java source using JAX-WS. Chapter 8. Create a SOAP based web service using Java SE platform.

Next

8.2. Create a web service starting from a Java source using JAX-WS.8.2.1. Use wsgen tool to generate artifacts in Java EE5 (optional in Java EE6 - as artifacts are generated at run time)The wsgen command-line tool generates the necessary portable artifacts required for Java API for XML Web Services (JAX-W S) applications w hen starting from Java code. This tool w ill generate a W SDL file only w hen requested. W hen using a bottoms-up approach to develop JAX-W S w eb services and you are starting from a service endpoint implementation, use the wsgen tool to generate the required JAX-W S portable artifacts. The wsgen tool accepts a properly annotated service endpoint implementation using the @WebService annotation as input and generates the follow ing portable artifacts: any additional Java Architecture for XML Binding (JAXB) classes that are required to marshal and unmarshal the message contents. a W SDL file if the optional -wsdl argument is specified. The wsgen tool does not automatically generate the W SDL file. The command line syntax is:

wsgen [options] service_implementation_classThe service_implementation_class name is the only parameter that is required. The follow ing parameters are optional for the wsgen command:

-classpath Specifies the location of the service implementation class.

-cp This is the same as -classpath .

-d Specifies w here to place the generated output files.

-extensionSpecifies w hether to allow custom extensions for functionality not specified by the JAX-W S specification. Use of the extensions can result in applications that are not portable or do not interoperate w ith other implementations.

-keepSpecifies w hether to keep the generated source files.

-r This parameter is only used in conjunction w ith the -wsdl parameter. Specifies w here to place the generated W SDL file.

-s Specifies the directory to place the generated source files.

-wsdl [:protocol]By default, wsgen does not generate a W SDL file. This optional parameter causes wsgen to generate a W SDL file and is typically only used to allow a developer to review a W SDL file before the endpoint is deployed. The protocol is optional and specifies the protocol used in the wsdl:binding. Valid values for protocol are soap 1.1 and Xsoap 1.2. The default value is soap 1.1. The Xsoap 1.2 value is not standard and can only be used in conjunction w ith the -extension option.

-servicename This parameter is only used in conjunction w ith the -wsdl option. Specifies a wsdl:service name to be generated in the W SDL file. For example:

-servicename "{http://mynamespace/}MyService"

-portnameThis parameter is only used in conjunction w ith the -wsdl option. Specifies a wsdl:port name to be generated in the W SDL file. For example:

-portname "{http://mynamespace/}MyPort"Note that you must run wsgen against a Java class that has already been compiled (not against the source program), and if you specify a directory in w hich the tool should place generated files such as the W SDL, that directory must exist before you run the program. Also, you must run the tool against an implementation class, and not an interface.

8.2.2. Use Endpoint API to configure and deploy it in Java SE 6 platform.blah-blahPrev Chapter 8. Create a SOAP based web service using Java SE platform. Up Home Next Chapter 9. Create handlers for SOAP web services.

Hosting provided by PerfoHost: KVM VPS provider. See PefoHost's KVM VPS vs OpenVZ/Virtuozzo vs XEN VPS comparative chart. CRM-exporter: Vehicle Database Script 1999-2011

converted by Web2PDFConvert.com

Prev

Chapter 9. Create handlers for SOAP web services. Part I. Exam Objectives

Next

Chapter 9. Create handlers for SOAP web services.The handler framew ork allow s interception of a message at various points in its transmission. Handlers are simple Java bean classes that implement a handler contract and can be associated w ith w eb service endpoints and w eb service clients. W ith outgoing messages, handlers are invoked before a message is sent to the w ire. W ith incoming messages, handlers are invoked before the receiving application receives the message. The same handler implementation is used for both incoming and outgoing messages. JAX-W S provides tw o levels of handlers: Logical handlers deal w ith the payload level of the message. Logical handlers can be used for building non-functional behavior, such as logging and caching, that is common across protocols. Protocol handlers deal w ith protocol information, such as SOAP headers. Logical handlers Example below show s a logical handler skeleton. The main method is the handleMessage method. The close method is to clean up any resources that handler invocation might have consumed. The handleFault method is invoked if an error condition occurs, for example, if a response message contains a fault.

import javax.xml.ws.handler.LogicalHandler; import javax.xml.ws.handler.LogicalMessageContext; import javax.xml.ws.handler.MessageContext; public class HelloMessengerLogicalHandler implements LogicalHandler { public void close(MessageContext ctx) { } public boolean handleFault(LogicalMessageContext ctx) { return false; } public boolean handleMessage(LogicalMessageContext ctx) { return false; } }

The handleMessage method (and handleFault) return a boolean. Returning true from the handleMessage method tells the JAX-W S run time that processing should move to the next handler in the chain. Returning false tells the JAX-W S run time that processing of the handler chain should end. The parameter to handleMessage is a LogicalMessageContext. It is an extension of java.util.Map and contains pairs of context properties. There are properties for items such as W SDL element names and attachment information (if any). Since handlers are invoked for both incoming and outgoing messages, a useful property is the MESSAGE_OUTBOUND_PROPERTY defined on the MessageContext interface, w hich gives you the direction of the message:

Boolean outbound = ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);Another useful property is the message itself:

LogicalMessage message = ctx.getMessage();You can get the payload as XML data by using the javax.xml.transform.Source:

Source payload = message.getPayload();Alternatively, you can get the payload as JAXB objects:

Object jaxbPayload = message.getPayload(jaxbContext);In either case, you get the payload. In the case of SOAP, the payload is the contents of the SOAP:Body, either in XML form ( javax.xml.transform.Source) or in JAXB form ( java.lang.Object). Protocol handlers The primary reason for w riting a SOAP handler is to manipulate SOAP headers. Example below show s an example of a SOAP handler skeleton:

import import import import import

java.util.Set; javax.xml.namespace.QName; javax.xml.ws.handler.MessageContext; javax.xml.ws.handler.soap.SOAPHandler; javax.xml.ws.handler.soap.SOAPMessageContext;

public class HelloMessengerProtocolHandler implements SOAPHandler { public Set getHeaders() { return null; }converted by Web2PDFConvert.com

public void close(MessageContext ctx) { } public boolean handleFault(SOAPMessageContext ctx) { return false; } public boolean handleMessage(SOAPMessageContext ctx) { return false; } }

The SOAP handler skeleton has the familiar methods of close, handleFault, and handleMessage. The parameter to handleFault and handleMessage, how ever, is now SOAPMessageContext instead of LogicalMessageContext. In addition, the getHeaders method is a new method to implement. The getHeaders method returns the set of the header names that the handler understands. The JAX-W S run time calls this method to determine w hether the handler can process SOAP headers that must be understood (as indicated by the SOAP mustUnderstand attribute). It does not call this method to filter handler invocation. All handlers in a chain are called for all messages. The SOAPMessageContext class adds a few properties to the context map that are SOAP-specific, such as roles. The getMessage method returns a SOAPMessage, w hich is an SAAJ class. By using the SOAPMessage, you can programmatically examine or modify SOAP message headers.

9.1. Configure SOAP and logical handlers on the server side.9.1.1. Use @HandlerChain annotation.W ith JAX-W S, you can declaratively specify a w eb service handler chain by using the @javax.jws.HandlerChain annotation. Example below show s how to apply a handler chain to the HelloMessenger w eb service:

import javax.jws.HandlerChain; import javax.jws.WebService; @WebService @HandlerChain(file = "handler-chain.xml") public class HelloMessenger { public String sayHello(String name) { return String.format("Hello %s", name); } }The HelloMessenger w eb service contains a class-level @HandlerChain annotation, w hich specifies that the handler configuration should be loaded from the handlerchain.xml file that is available in the class path. Example below show s the handler-chain.xml file in its entirety:

HelloMessengerProtocolHandler

The XML file tells the JAX-W S run time to use the HelloMessengerProtocolHandler to handle incoming and outgoing messages.

9.1.2. Use deployment descriptors.The webservices.xml deployment descriptor file w as introduced by the first version of [JSR 109] to define the set of w eb services that are to be deployed in a container. How ever, w ith JAX-W S, the use of webservices.xml is optional since the annotations can be used to specify most of the information specified in this deployment descriptor. W hen you are deploying JAX-W S w eb services, the only reason you should use webservices.xml is to override or augment the annotation member attributes or w hen you do not w ant to use annotations because you don't w ant to modify the Java source code. One situation, w here you might w ant to override or augment annotations, occurs w hen you w ant to deploy a handler w ith a w eb service endpoint that has not been annotated for a handler. Alternatively, the endpoint may have been annotated for a handler, but you w ish to use a different handler. One w ay to deal w ith this is to edit the source code to update or add the @HandlerChain annotation. But perhaps you do not have access or authority to modify the source code. Or perhaps you think it is a bad idea to have multiple versions of the same source code just so you can support using the endpoint w ith different handlers. In such a situation, you can deploy the endpoint w ith a custom webservices.xml to specify the handler chain. Example below show s the Hello w eb service endpoint w ith an @HandlerChain annotation that specifies the myhandler.xml handler configuration file:

@HandlerChain(file="myhandler.xml") @WebService public class Hello { @Resource WebServiceContext context; public String sayHello(String s) { String appendString = (String) context.getMessageContext().get(HelloHandler.APPEND_STRING); return "Hello: " + s + "[appended by handler: " + appendString + "]"; }converted by Web2PDFConvert.com

}The myhandler.xml file is show n in below . Notice that it specifies the handler class HelloHandler.

HelloHandler

Now , suppose you w ould prefer to deploy this endpoint w ith the handler class ImprovedHelloHandler. You could do that by bundling the webservices.xml file show n below in the WEB-INF directory of the W AR module (or, if this w ere an EJB endpoint, in the META-INF directory). The webservices.xml overrides the @HandlerChain annotation:

HelloService Hello ns1:HelloService ns1:HelloPort Hello myhandler ImprovedHelloHandler

In this webservices.xml deployment descriptor, notice the handler-chains element in the bottom half of the listing. Here, the handler-class element specifies ImprovedHelloHandler. W hen using the webservice.xml, it is important to understand how the port-component names match up w ith the annotations. In other w ords, port-component-name relates to @WebService.name; wsdl-service relates to @WebService.serviceName; wsdl-port relates to @WebService.portName; and service-endpoint-interface relates to @WebService.endpointInterface.Prev 8.2. Create a web service starting from a Java source using JAX-WS. Up Home Next 9.2. Configure SOAP and logical handlers on the client side.

Hosting provided by PerfoHost: KVM VPS provider. See PefoHost's KVM VPS vs OpenVZ/Virtuozzo vs XEN VPS comparative chart. CRM-exporter: Vehicle Database Script 1999-2011

converted by Web2PDFConvert.com

Prev

9.2. Configure SOAP and logical handlers on the client side. Chapter 9. Create handlers for SOAP web services.

Next

9.2. Configure SOAP and logical handlers on the client side.9.2.1. Use deployment descriptors.The declarative configuration w orks for proxy clients only and w orks in the same w ay as for the endpoint example. That is, you simply add an annotation to the client-side generated SEI, w hich enables the handlers for all proxies and dispatch clients that are generated by using any ports on the SEI.

9.2.2. Use programmatic API.The programmatic configuration w orks for all JAX-W S services, generated service interfaces, and the generic service. Handlers are added to the client-side service by using the follow ing method:

Service.setHandlerResolver(HandlerResolver handlerResolver);Example below show s the HelloClientWithHandler class that programmatically adds the HelloMessengerProtocolHandler to the client-side SEI:

import import import import import import

HelloMessenger; HelloMessengerService; java.util.Collections; java.util.List; javax.xml.ws.handler.HandlerResolver; javax.xml.ws.handler.PortInfo;

public class HelloClientWithHandler { public static void main(String... args) throws Exception { HelloMessengerService service = new HelloMessengerService(); service.setHandlerResolver(new HandlerResolver() { public List getHandlerChain(PortInfo inf) { return Collections.singletonList(new HelloMessengerProtocolHandler()); } }); HelloMessenger port = service.getHelloMessengerPort(); String message = port.sayHello("Mikalai"); System.out.println(message); } }The highlighted code show s the relevant handler configuration code. The application creates a new anonymous inner HandlerResolver that returns a singleton list that contains an instance of the HelloMessengerProtocolHandler. An advantage of the programmatic approach is that you are not required to change generated code.Prev Chapter 9. Create handlers for SOAP web services. Up Home Next Chapter 10. Create low-level SOAP web services.

Hosting provided by PerfoHost: KVM VPS provider. See PefoHost's KVM VPS vs OpenVZ/Virtuozzo vs XEN VPS comparative chart. CRM-exporter: Vehicle Database Script 1999-2011

converted by Web2PDFConvert.com

Prev

Chapter 10. Create low-level SOAP web services. Part I. Exam Objectives

Next

Chapter 10. Create low-level SOAP web services. 10.1. Describe the functions and capabilities of the APIs included within JAXP.The Java API for XML Processing (JAXP) is for processing XML data using applications w ritten in the Java programming language. JAXP leverages the parser standards Simple API for XML Parsing (SAX) and Document Object Model (DOM) so that you can choose to parse your data as a stream of events or to build an object representation of it. JAXP also supports the Extensible Stylesheet Language Transformations (XSLT) standard, giving you 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. JAXP also provides namespace support, allow ing you to w ork w ith DTDs that might otherw ise have naming conflicts. Finally, as of version 1.4, JAXP implements the Streaming API for XML (StAX) standard. Designed to be flexible, JAXP allow s you to use any XML-compliant parser from w ithin your application. It does this w ith w hat is called a pluggability layer, w hich lets you plug in an implementation of the SAX or DOM API. The pluggability layer also allow s you to plug in an XSL processor, letting you control how your XML data is displayed. The main JAXP APIs are defined in the javax.xml.parsers package. That package contains vendor-neutral factory classes, SAXParserFactory, DocumentBuilderFactory, and TransformerFactory, w hich give you a SAXParser, a DocumentBuilder, and an XSLT transformer, respectively. DocumentBuilder, in turn, creates a DOM-compliant Document object. Simple API for XML APIs To start the process, an instance of the SAXParserFactory class is used to generate an instance of the SAXParser. Figure 10.1. SAX APIs

The parser w raps a SAXReader object. W hen the parser's parse() method is invoked, the reader invokes one of several callback methods implemented in the application. Those methods are defined by the interfaces ContentHandler, ErrorHandler, DTDHandler, and EntityResolver. Here is a summary of the key SAX APIs:

SAXParserFactoryA SAXParserFactory object creates an instance of the parser determined by the system property, javax.xml.parsers.SAXParserFactory.

SAXParserThe SAXParser interface defines several kinds of parse() methods. In general, you pass an XML data source and a DefaultHandler object to the parser, w hich processes the XML and invokes the appropriate methods in the handler object.

SAXReaderThe SAXParser w raps a SAXReader. Typically, you do not care about that, but every once in a w hile you need to get hold of it using SAXParser's getXMLReader() so that you can configure it. It is the SAXReader that carries on the conversation w ith the SAX event handlers you define.

DefaultHandlerNot show n in the diagram, a DefaultHandler implements the ContentHandler, ErrorHandler, DTDHandler, and EntityResolver interfaces (w ith null methods), so you can override only the ones you are interested in.

ContentHandlerMethods such as startDocument, endDocument, startElement, and endElement are invoked w hen an XML tag is recognized. This interface also defines the methods characters() and processingInstruction(), w hich are invoked w hen the parser encounters the text in an XML element or an inline processing instruction, respectively.

ErrorHandlerMethods error(), fatalError(), and warning() are invoked in response to various parsing errors. The default error handler throw s an exception for fatal errors and ignores other errors (including validation errors). This is one reason you need to know something about the SAX parser, even if you are using the DOM. Sometimes, the application may be able to recover from a validation error. Other times, it may need to generate an exception. To ensure the correct handling, you w ill need to supply your ow n error handler to the parser.

DTDHandlerDefines methods you w ill generally never be called upon to use. Used w hen processing a DTD to recognize and act on declarations for an unparsed entity.

EntityResolverThe resolveEntity method is invoked w hen the parser must identify data identified by a URI. In most cases, a URI is simply a URL, w hich specifies the location of a document, but in some cases the document may be identified by a URN - a public identifier, or name, that is unique in the w eb space. The public identifier may be specified in addition to the URL. The EntityResolver can then use the public identifier instead of the URL to find the document - for example, to access a local copy of the document if one exists.

W hen to Use SAXconverted by Web2PDFConvert.com

W hen to Use SAXSAX is fast and efficient, but its event model makes it most useful for state-independent filtering. For example, a SAX parser calls one method in your application w hen an element tag is encountered and calls a different method w hen text is found. If the processing you are doing is state-independent (meaning that it does not depend on the elements that have come before), then SAX w orks fine. On the other hand, for state-dependent processing, w here the program needs to do one thing w ith the data under element A but something different w ith the data under element B, then a pull parser such as the Streaming API for XML (StAX) w ould be a better choice. W ith a pull parser, you get the next node, w hatever it happens to be, at any point in the code that you ask for it. So it is easy to vary the w ay you process text (for example), because you can process it multiple places in the program. SAX requires much less memory than DOM, because SAX does not construct an internal representation (tree structure) of the XML data, as a DOM does. Instead, SAX simply sends data to the application as it is read; your application can then do w hatever it w ants to do w ith the data it sees. Pull parsers and the SAX API both act like a serial I/O stream. You see the data as it streams in, but you cannot go back to an earlier position or leap ahead to a different position. In general, such parsers w ork w ell w hen you simply w ant to read data and have the application act on it. But w hen you need to modify an XML structure - especially w hen you need to modify it interactively - an in-memory structure makes more sense. DOM is one such model. How ever, although DOM provides many pow erful capabilities for large-scale documents (like books and articles), it also requires a lot of complex coding. For simpler applications, that complexity may w ell be unnecessary. For faster development and simpler applications, one of the object-oriented XML-programming standards, such as JDOM (http://w w w .jdom.org) and DOM4J (http://dom4j.org/), might make more sense.

Parsing an XML File Using SAXThe follow ing code sets up the parser and gets it started:

static public void main(String[] args) throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(new MyHandler()); xmlReader.parse(fileURL); }These lines of code create a SAXParserFactory instance, as determined by the setting of the javax.xml.parsers.SAXParserFactory system property. The factory to be created is set up to support XML namespaces by setting setNamespaceAware to true, and then a SAXParser instance is obtained from the factory by invoking its newSAXParser() method. Then you obtain an XMLReader instance for your parser by invoking your SAXParser instance's getXMLReader() method. The XMLReader then registers the MyHandler class as its content handler, so that the actions performed by the parser w ill be those of the startDocument(), startElement(), and endDocument(), etc methods. Finally, the XMLReader tells the parser w hich document to parse by passing it the location of the XML file in question, in the form of the file URL. The SAXParserFactory can be set up such that it uses a validating parser instead of the default non-validating parser:

SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(true); SAXParser saxParser = spf.newSAXParser();Document Object Model APIs You use the javax.xml.parsers.DocumentBuilderFactory class to get a DocumentBuilder instance, and you use that instance to produce a Document object that conforms to the DOM specification. The builder you get, in fact, is determined by the system property javax.xml.parsers.DocumentBuilderFactory, w hich selects the factory implementation that is used to produce the builder. (The platform's default value can be overridden from the command line.) Figure 10.2. DOM APIs

You can also use the DocumentBuilder.newDocument() method to create an empty Document that implements the org.w3c.dom.Document interface. Alternatively, you can use one of the builder's parse methods to create a Document from existing XML data.

W hen to Use DOMThe Document Object Model standard is, above all, designed for documents (for example, articles and books). In addition, the JAXP 1.4.2 implementation supports XML Schema, something that can be an important consideration for any given application. On the other hand, if you are dealing w ith simple data structures and if XML Schema is not a big part of your plans, then you may find that one of the more object-oriented standards, such as JDOM or dom4j, is better suited for your purpose. From the start, DOM w as intended to be language-neutral. Because it w as designed for use w ith languages such as C and Perl, DOM does not take advantage of Java's objectoriented features. That fact, in addition to the distinction betw een documents and data, also helps to account for the w ays in w hich processing a DOM differs from processing a JDOM or dom4j structure.

Parsing an XML File Using DOM

converted by Web2PDFConvert.com

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true; DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new File(filename));Extensible Stylesheet Language Transformations APIs A TransformerFactory object is instantiated and used to create a Transformer. The source object is the input to the transformation process. A source object can be created from a SAX reader, from a DOM, or from an input stream. Figure 10.3. XSLT APIs

Similarly, the result object is the result of the transformation process. That object can be a SAX event handler, a DOM, or an output stream. W hen the transformer is created, it can be created from a set of transformation instructions, in w hich case the specified transformations are carried out. If it is created w ithout any specific instructions, then the transformer object simply copies the source to the result. Streaming API for XML APIs StAX is the latest API in the JAXP family, and provides an alternative to SAX, DOM, TrAX, and DOM for developers looking to do high-performance stream filtering, processing, and modification, particularly w ith low memory and limited extensibility requirements. To summarize, StAX provides a standard, bidirectional pull parser interface for streaming XML processing, offering a simpler programming model than SAX and more efficient memory management than DOM. StAX enables developers to parse and modify XML streams as events, and to extend XML information models to allow application-specific additions.

Comparing StAX to Other JAXP APIsAs an API in the JAXP family, StAX can be compared, among other APIs, to SAX, TrAX, and JDOM. Of the latter tw o, StAX is not as pow erful or flexible as TrAX or JDOM, but neither does it require as much memory or processor load to be useful, and StAX can, in many cases, outperform the DOM-based APIs. W ith this in mind, the closest comparisons can be made betw een StAX and SAX, and it is here that StAX offers features that are beneficial in many cases; some of these include: StAX-enabled clients are generally easier to code than SAX clients. W hile it can be argued that SAX parsers are marginally easier to w rite, StAX parser code can be smaller and the code necessary for the client to interact w ith the parser simpler. StAX is a bidirectional API, meaning that it can both read and w rite XML documents. SAX is read only, so another API is needed if you w ant to w rite XML documents. SAX is a push API, w hereas StAX is pull. Table 10.1. XML Parser API Feature SummaryFeature API Type Ease of Use XPath Capability CPU and Memory Efficiency Forward Only Read XML Write XML Create, Read, Update, Delete StAX Pull, streaming High No Good Yes Yes Yes No SAX Push, streaming Medium No Good Yes Yes No No DOM In memory tree High Yes Varies No Yes Yes Yes TrAX XSLT Rule Medium Yes Varies No Yes Yes No

The StAX API exposes methods for iterative, event-based processing of XML documents. XML documents are treated as a filtered series of events, and infoset states can be stored in a procedural fashion. Moreover, unlike SAX, the StAX API is bidirectional, enabling both reading and w riting of XML documents. The StAX API is really tw o distinct API sets: a cursor API and an iterator API.converted by Web2PDFConvert.com

Cursor APIAs the name implies, the StAX cursor API represents a cursor w ith w hich you can w alk an XML document from beginning to end. This cursor can point to one thing at a time, and alw ays moves forw ard, never backw ard, usually one infoset element at a time. The tw o main cursor interfaces are XMLStreamReader and XMLStreamWriter. XMLStreamReader includes accessor methods for all possible information retrievable from the XML Information model, including document encoding, element names, attributes, namespaces, text nodes, start tags, comments, processing instructions, document boundaries, and so forth; for example:

public interface XMLStreamReader { public int next() throws XMLStreamException; public boolean hasNext() throws XMLStreamException; public String getText(); public String getLocalName(); public String getNamespaceURI(); // ... other methods not shown }You can call methods on XMLStreamReader, such as getText and getName, to get data at the current cursor location. XMLStreamWriter provides methods that correspond to StartElement and EndElement event types; for example:

public interface XMLStreamWriter { public void writeStartElement(String localName) throws XMLStreamException; public void writeEndElement() throws XMLStreamException; public void writeCharacters(String text) throws XMLStreamException; // ... other methods not shown }The cursor API mirrors SAX in many w ays. For example, methods are available for directly accessing string and character information, and integer indexes can be used to access attribute and namespace information. As w ith SAX, the cursor API methods return XML information as strings, w hich minimizes object allocation requirements.

Iterator APIThe StAX iterator API represents an XML document stream as a set of discrete event objects. These events are pulled by the application and provided by the parser in the order in w hich they are read in the source XML document. The base iterator interface is called XMLEvent, and there are subinterfaces for each event type. The primary parser interface for reading iterator events is XMLEventReader, and the primary interface for w riting iterator events is XMLEventWriter. The XMLEventReader interface contains five methods, the most important of w hich is nextEvent, w hich returns the next event in an XML stream. XMLEventReader implements java.util.Iterator, w hich means that returns from XMLEventReader can be cached or passed into routines that can w ork w ith the standard Java Iterator; for example:

public interface XMLEventReader extends Iterator { public XMLEvent nextEvent() throws XMLStreamException; public boolean hasNext(); public XMLEvent peek() throws XMLStreamException; ... }Similarly, on the output side of the iterator API, you have:

public interface XMLEventWriter { public void flush() throws XMLStreamException; public void close() throws XMLStreamException; public void add(XMLEvent e) throws XMLStreamException; public void add(Attribute attribute) throws XMLStreamException; ... }Comparing Cursor and Iterator APIsBefore choosing betw een the cursor and iterator APIs, you should note a few things that you can do w ith the iterator API that you cannot do w ith the cursor API: Objects created from the XMLEvent subclasses are immutable, and can be used in arrays, lists, and maps, and can be passed through your applications even after the parser has moved on to subsequent events. You can create subtypes of XMLEvent that are either completely new information items or extensions of existing items but w ith additional methods. You can add and remove events from an XML event stream in much simpler w ays than w ith the cursor API. Similarly, keep some general recommendations in mind w hen making your choice: If you are programming for a particularly memory-constrained environment, like Java ME, you can make smaller, more efficient code w ith the cursor API. If performance is your highest priority for exa