论坛首页 Java企业应用论坛

JAXB特性(读书)

浏览 7030 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-04-21  
这个星期要做Biztalk跟Java应用XML交互,研究一下JAXB相关资料,先收集一下有空了回头整理分类
附件中有一个简单的JAXB中文教程希望对大家有用



   <<SOA Using Java Web Serivce>>关于JAX-WS的特性描述和我的一些理解。

    JAXB 2.0 defines a standard Java/XML binding from Java representations to XML Schema components and vice versa.

    JAX-RPC defined its own Java/XML binding—independent of JAXB 1.0. JAX-WS 2.0 (the successor to JAX-RPC) no longer defines a Java/XML binding. That task has been delegated to JAXB 2.0.
引用

    Java/XML binding又可以称为type mapping,它是通过 serializer and a deserializer来实现,serializer将java类的实例转换成XML实例,deserializer则相反。当时binding和 mapping是有区别的。If a Java/XML map sends each Java programming element to a unique XML Schema component (i.e., it defines a function), I call it a Java/XML binding.(因为一个class可能被映射到不同的XML Schema Type)


    Using this terminology, JAXB 2.0 is best thought of as a Java/XML binding tool. That is because the annotations on the Java classes used by JAXB 2.0 define a binding. Each class maps to a unique XML Schema component based on its annotations.

    The goal of JAXB 2.0 is to provide a higher level of abstraction than Java implementations of SAX,DOM, XPath, or other approaches to manipulating XML in the Java programming language.
Binding XML Schema to Java Representations

    JAXB 2.0 implementations provide a schema compiler that generates JAXB schema-derived Java program elements from an XML schema.

对于complex types,例如:

   
<xs:element name="foo" type="Bar" maxOccurs="unbounded"/>

可以被映射成List<Bar> or Bar[],

    对于simple types,builtin XML Schema types like xs:string—are mapped to the corresponding Java primitives or holder classes (e.g., java.lang.String, java.lang .Integer, int).

     
Mapping Java Types to XML Schema

       JAXB implementations provide a schema generator that creates schema

from existing classes using the standard map.

       mapping annotations are provided (see Section 2.4.3) that enable you to tell the schema generator how to match fields and classes with XML


Mapping Annotations

schema generator采用两个输入:类和映射注释来生成相应的schema,例如:

public class PurchaseOrder {

// ...

@XmlElement(name="orderNum")})

String getPurchaseOrderNumber();

void setPurchaseOrderNumber();

};

<xs:element name="orderNum" type="xs:string"/>


       Another use for mapping annotations is controlling a binary data encoding—i.e., how binary data such as images are encoded.

      
引用
mapping annotations的用于在serialization子系统中,同时用于deployment子系统中。



Binding Language

      
引用
主要用在将通过binding language将已经有schema绑定到的定的Java Class中,而不用缺省的JAXB annotations。

       The JAXB 2.0 binding language provides an analogous feature for annotating XML that enables you to customize the Java representation of XML Schema.通过binding language 通过注释XML来客户化Java representation of XML Schema。

       The binding language is part of the deployment subsystem within the JWS framework.不象mapping annotations,binding语言是不被JAXB runtime使用,它是deployment subsystem的一部分,不会被serialization subsystem使用。所以binding declarations用来设计mapping annotations并且最终控制serialization subsystem。


Unlike annotations, which are always inline with the Java source code, the binding language customizations, called binding declarations, can be provided either inline with the XML schema (i.e., inline annotated schema) or in a separate configuration file (i.e., external binding declaration).

       Binding declarations have scope.

Globe Scope
<jaxb:globalBindings>

<jaxb:javaType name="long" xmlType="xs:date"

parseMethod="pkg.MyDatatypeConverter.myParseDate"

printMethod="pkg.MyDatatypeConverter.myPrintDate"/>

</jaxb:javaType>

</jaxb:globalBindings>

引用

       上面意味着XML instances of type xs:date将被映射到java long类型,而缺省的状态是映射到javax.xml.datatype.XMLGregorianCalendar.


       The parseMethod and printMethod attributes tell JAXB where to find the methods that can marshal this type mapping. The xmlType specified here must be an XML atomic datatype

Component Scope

<xs:complexType name="foo">

<xs:sequence>

<xs:element name="po" type="javector:PurchaseOrder" maxOccurs="unbounded"/>

<xs:annotation><xs:appinfo>

<jaxb:dom/>

</xs:appinfo></xs:annotation>

</xs:element>

</xs:sequence>

</xs:complexType>

    上面的例子表明: the element named po gets mapped to a DOM—specifically, an instance of org.w3c.dom.Element. Mapping to a DOM can be useful when you don’t want to use the JAXB 2.0 binding.

    In between global and component scope are two other levels: definition scope and schema scope.

    An External Binding File That References Its Associated Schema Using XPath Expressions

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"

xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0">

<jaxb:bindings schemaLocation=".../mySchema.xsd">

<jaxb:bindings node="//xs:complexType[@name='foo']">

<jaxb:bindings node=".//xs:element[@name='po']">

<jaxb:dom/>

</jaxb:bindings>

</jaxb:bindings>

</jaxb:bindings>

</jaxb:bindings>


Binding Run-time Framework (Marshal/Unmarshal)

       The JAXB 2.0 binding run-time framework is the heart of the serialization subsystem for a JWS implementation. The binding run-time framework implements the marshal and unmarshal operations.

       The following steps indicate how the binding run-time framework interfaces with the JAX-WS 2.0 invocation architecture to invoke a Web service deployed in a JWS-compliant application:

1. The JWS application receives a SOAP message at a deployed endpoint.

2. Based on the configuration of the SOAP binding (javax.xml.ws.soap.SOAPBinding) for the endpoint, JAX-WS prepares an instance of the message context (javax.xml.ws.handler.soap.SOAPMessageContext),which includes a SAAJ representation of the message.

3. JAXB may be required to provide MTOM/XOP27 processing in order to create the SAAJ representation of the message. Such processing may be deferred until required. That is, for performance reasons, MTOM processing may be deferred until an application actually requests access to a part of the SOAP message requiring MTOM processing to be realized as a SAAJ instance.

4. JAX-WS invokes the handlers. During handler processing, the application has SAAJ interface access to the SOAP message contents. As discussed in the preceding step, SAAJ access may trigger MTOM processing, which is handled by the JAXB run-time binding framework

5. After the request handlers are finished, the JAXB runtime unmarshals the SOAP message contents into a request bean. Although the request bean is defined by JAX-WS, based on the parameter and return type packaging of the deployment, JAXB implements the binding of the request bean to the SOAP message request.

6. The request bean, constructed by the JAXB runtime, contains the Java objects that are passed as parameters to the Java method that implements the Web service. JAX-WS invokes the method using these parameters.

7. JAX-WS hands off the Java object returned from the method invocation and uses it to create an instance of the response bean.

8. JAXB marshals the response bean.

9. As in step 2, based on the SOAP binding configuration for the endpoint,JAX-WS updates the message context to include a SAAJ representation of the response. This is a SAAJ interface on top of the response bean.

10. JAX-WS invokes the response handlers.

11. Prior to transmitting the response message, JAX-WS invokes the JAXB runtime as necessary to provide MTOM processing for the message.

12. JAX-WS hands off the response message to the protocol transport.




从wire到web service的过程中,将发生两个操作:

1.  JAX-WS将desterilizes请求消息到infoset representation with a SAAJ interface,因为SAAJ是基于DOM的,所以可以使用STaX或者其它基于pull parser的DOM实现提供按需解析infoset

2.  第二个操作中JAXB runtime unmarshels这个infoset representation到JAXB-annotated program elements.

Second, although MTOM processing is actually part of the first serialization (creating an infoset representation from the serialized wire format), it is handled by the JAXB runtime on behalf of JAX-WS.(由JAXB runtime实现)

Third, all handler processing occurs before JAXB unmarshalling and after JAXB marshalling from/to the infoset representation of the SOAP message.


Validation

       JAXB 2.0 validation during unmarshalling can be activated by providing an instance of a JAXP 1.3 javax.xml.validation.Schema to the Unmarshaller.setSchema () method.

       通过设置javax.xml.validation.Schema给Unmarshaller.setSchema ()方法来实现。

       When validation is enabled, the default behavior is to throw an unchecked exception when the first error is encountered. However, one can change this behavior by defining and setting a javax.xml.bind.ValidationEventHandler using the Unmarshaller.setEventHandler () method.Using this approach, when a validation error occurs, the event handler is called. The event handler can be written so that it aggregates all the errors reported during unmarshalling and reports them at once.


Portability

       JAXB 2.0 portability is achieved using the mapping annotations. The run-time marshaller from any JAXB implementation must be able to serialize a JAXB-annotated class to an instance of its target schema. Likewise, the run-time unmarshaller must be able to deserialize a schema instance to an instance of the JAXB annotated class.

This is important because it means that one can deploy a Web service built from JAXB-annotated classes to any JAXB 2.0 platform (e.g., SAP Netweaver, JBoss, GlassFish) without having to recompile the schema and/or refactor the Web service to use vendor-specific implementation classes.

通过JAXB-annotated class使得不需要重新recompile the schema,可以部署WS到不同的JAXB 2.0平台。


Marshal Event Callbacks

       Callbacks enable application-specific processing during serialization.You can define processing to occur either before serialization (just after target creation) or immediately after serialization. This is a useful feature for setting properties outside of the serialization process.

One use case I’ve encountered involved unmarshalling XML into an existing POJO that combines data from multiple sources. For example, you could have a customer object that you annotate so that it can be unmarshalled from a SOAP message containing customer information. However, if not all of the customer data (e.g., transaction history) is available in the SOAP message; you may want to load the rest of the object’s data from another source (e.g., SAP). In such situations, you can use an event callback to load the SAP data after the unmarshalling is finished.


Partial Binding

       The javax.xml.bind.Binder class supports partial binding of an XML document. This enables one, for example, to create a JAXB binding of a SOAP header without processing the body. Potentially, this capability could be very useful from a performance perspective if you could harness it to only update a particular SOAP header element when doing handler processing.

Imagine, for example, that one wants to create a handler to mark a SOAP header element named myapp:persisted as true to indicate that the entire SOAP message has been persisted to permanent storage. The following indicates how that might be accomplished with the partial binding mechanism:

org.w3c.dom.Element persistedElt = ... // get from SOAP header

Binder<org.w3c.dom.Node> myBinder = jaxbContext.createBinder();

PersistedValueClass perVC = (PersistedValueClass) myBinder.unmarshal(persistedElt);

perVC.setPersisted(true);

myBinder.updateXML(perVC); // updates the XML infoset


Binary Data Encoding (MTOM or WS-I)

JAXB 2.0 supports two types of binary data encoding: MTOM/XOP and WSIAP.

       MTOM is the W3C standard titled “SOAP Message Transmission Optimization Mechanism” It describes a standard procedure for taking content out of the XML infoset, compressing it, packaging it as a MIME attachment, and replacing it with a reference in the infoset. The packaging encoding used with MTOM is XOP, another W3C recommendation titled “XML-binary Optimized Packaging” [XOP]. XOP replaces base64-encoded content with a xop:include element that references the respective MIME part encoded as a binary octet stream. If data is already available as a binary octet stream, it can be placed directly in an XOP package.

       WSIAP is the WS-I Attachments Profile Version 1.0 [WSIAP]. WSIAP clarifies SOAP Messages with Attachments [SwA]. SwA was the industry’s first attempt to standardize an approach to treating binary data as SOAP message attachments. Support for WSIAP is built into a number of products, so it is important for JWS to support it. However, the industry now seems to be converging on MTOM/XOP as the primary standard.

       JAXB uses annotations to specify which Java properties in a class should be serialized using MTOM or WSIAP. For MTOM, the @XmlMimeType annotation lets you specify how a binary (e.g., java.awt.Image) Java property gets bound to a schema element decorated with the xmime:content-Type attribute. The xmime:contentType attribute [XMIME] is used to indicate the content type of an XML element with type xs:base64Binary or xs:hexBinary. For WSIAP, the @XmlAttachmentRef annotation plays the same role.
   发表时间:2008-04-21  
我选择XJC其中几个较为常用的参数翻译:
• -d <dir>:把生成的文件存入这个目录
• -p <package>:把生成的文件存入这个包
• -nv:不要对输入模式进行严格的验证
• -httpproxy <proxy>:使用代理的时候用这个命令。格式如下:[user[:password]@]proxyHost[:proxyPort]
• -classpath <arg>:如果有必要的话,指定classpath
• -readOnly:如果你的操作系统支持这个的话,生成只读源代码文件

详细的参数如下(from JavaEE教程By SUN)
JAXB Compiler Options

The JAXB XJC schema binding compiler transforms, or binds, a source XML schema to a set of
JAXB content classes in the Java programming language. The compiler, xjc, is provided in two
flavors in the Application Server: xjc.sh (Solaris/Linux) and xjc.bat (Windows). Both xjc.sh
and xjc.bat take the same command-line options. You can display quick usage instructions by
invoking the scripts without any options, or with the -help switch. The syntax is as follows:

xjc [-options ...] schema
The xjc command line options are as follows:
-nv Do not perform strict validation of the input schema or schemas. By
default, xjc performs strict validation of the source schema before
processing.Note that this does not mean the binding compiler will not
perform any validation; it simply means that it will perform less-strict
validation.

-extension By default, the XJC binding compiler strictly enforces the rules outlined
in the Compatibility chapter of the JAXB Specification. In the default
(strict) mode, you are also limited to using only the binding
customizations defined in the specification. By using the -extension
switch, you will be allowed to use the JAXB Vendor Extensions.

-b file Specify one or more external binding files to process. (Each binding file
must have its own -b switch.) The syntax of the external binding files is
extremely flexible. You may have a single binding file that contains
customizations for multiple schemas or you can break the
customizations into multiple bindings files. In addition, the ordering of
the schema files and binding files on the command line does not matter.

-d dir By default, xjc will generate Java content classes in the current directory.
Use this option to specify an alternate output directory. The directory
must already exist; xjc will not create it for you.

-p package Specify an alternate output directory. By default, the XJC binding
compiler will generate the Java content classes in the current directory.
The output directory must already exist; the XJC binding compiler will
not create it for you.

-proxy proxy Specify the HTTP/HTTPS proxy. The format is
[user[:password]@]proxyHost[:proxyPort]. The old -host and -port
options are still supported by the Reference Implementation for
backwards compatibility, but they have been deprecated.

-classpath arg Specify where to find client application class files used by the
<jxb:javaType> and <xjc:superClass> customizations.

-catalog file
Specify catalog files to resolve external entity references. Supports
TR9401, XCatalog, andOASIS XML Catalog format. For more
information, see the XML Entity and URI Resolvers document or
examine the catalog-resolver sample application.

-readOnly
Force the XJC binding compiler to mark the generated Java sources
read-only. By default, the XJC binding compiler does not write-protect
the Java source files it generates.

-npa Suppress the generation of package level annotations into
**/package-info.java. Using this switch causes the generated code to
internalize those annotations into the other generated classes.

-xmlschema Treat input schemas as W3C XML Schema (default). If you do not
specify this switch, your input schemas will be treated as W3C XML
Schema.

-help Display a brief summary of the compiler switches.

-version Display the compiler version information.

-Xlocator Enable source location support for generated code.

-Xsync-methods Generate accessor methods with the synchronized keyword.

-mark-generated Mark the generated code with the -@javax.annotation.Generated
annotation.

-quiet Suppress compiler output, such as progress information and warnings.

0 请登录后投票
   发表时间:2008-04-21  
我觉得用XStream可能还更容易控制一点
0 请登录后投票
   发表时间:2008-04-21  
wl95421 写道
我觉得用XStream可能还更容易控制一点


现在就是对JAXB Customizations这块还不是很明白,既然可以用XJC直接由Schema生成对应的java接口和class
还需要这个干什么
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics