Chapter 20. XML of JEUS Web Services

Table of Contents

20.1. Overview
20.2. JAXB (Java Architecture for XML Binding)
20.2.1. Binding Compiler(XJC) Related Programming Techniques
20.2.2. Schemagen Programming Techniques
20.3. JAXP (Java Standard API for XML Processing)
20.3.1. StAX (Java Streaming APIs for XML Parser)

This chapter describes various XML related technologies provided by JEUS 8.

20.1. Overview

This chapter will first discuss about JAXB(Java Architecture for XML Binding) that enables the XML document information to be handled programmatically by binding the XML document to Java class, which is compiled from the schema. Next, it will discuss about StAX(Streaming APIs For XML) for which APIs are currently being added to JAXP.

  • JAXB(Java Architecture for XML Binding)

  • JAXP(Java API for XML Processing)

  • SJSXP(Sun Java Streaming XML Parser)

The following describes some terms used in Java object conversion and XML documents.

DivisionDescription
UnmarshallingProcess of converting XML document or XML content into objects(Java content tree) by using Java class
MarshallingProcess of converting a Java object (Java content tree) into an XML document or XML content

20.2. JAXB (Java Architecture for XML Binding)

An application related to an XML document that follows a schema must be able to create, modify, or read the document. Data binding for XML used in such application can be performed by using the SAX or DOM API, but keeping up with schema changes is not trivial. Thus, JAXB provides API and tools to automatically map XML documents to Java objects.

The following are JAXB functions.

  • Unmarshalling, the process of converting XML contents into Java object.

  • Accesses or modifies Java objects.

  • Marshalling, the process of converting Java objects into XML contents.

As previously stated, JAXB provides a developer with standardized and effective mapping between XML and Java codes. JAXB makes it easier to develop applications that use XML and web service technologies. In the following sections, the details of JAXB will be explained along with the tools provided by JAXB and example programs.

20.2.1. Binding Compiler(XJC) Related Programming Techniques

Java classes must already exist before converting XML contents into Java objects. The Java classes are created from the schema, and this process is called binding compilation.

This section discusses about XJC, the default binding compiler tool provided by JEUS 8 web services.

XJC

Execute the following command from the command line.

JEUS_HOME/bin$ xjc.cmd -help

Usage

Usage: xjc [-options ...] <schema file/URL/dir/jar> ...
           [-b <bindinfo>] ...
If dir is specified, all schema files in it will be compiled.
If jar is specified, /META-INF/sun-jaxb.episode binding file will be
compiled.
Options:
  -nv                :  do not perform strict validation of the input
                        schema(s)
  -extension         :  allow vendor extensions - do not strictly
                        follow the Compatibility Rules and App E.2
                        from the JAXB Spec
  -b <file/dir>      :  specify external bindings files (each <file>
                        must have its own -b)
                        If a directory is given, **/*.xjb is searched
  -d <dir>           :  generated files will go into this directory
  -p <pkg>           :  specifies the target package
  -httpproxy <proxy> :  set HTTP/HTTPS proxy. Format is
                        [user[:password]@]proxyHost:proxyPort
  -httpproxyfile <f> :  Works like -httpproxy but takes the argument
                        in a file to protect password
  -classpath <arg>   :  specify where to find user class files
  -catalog <file>    :  specify catalog files to resolve external
                        entity references support TR9401, XCatalog,
                        and OASIS XML Catalog format.
  -readOnly          :  generated files will be in read-only mode
  -npa               :  suppress generation of package level
                        annotations(**/package-info.java)
  -no-header         :  suppress generation of a file header with
                        timestamp
  -target 2.0        :  behave like XJC 2.0 and generate code that
                        doesnt use any 2.1 features.
  -xmlschema         :  treat input as W3C XML Schema (default)
  -relaxng           :  treat input as RELAX NG (experimental,
                        unsupported)
  -relaxng-compact   :  treat input as RELAX NG compact syntax
                        (experimental, unsupported)
  -dtd               :  treat input as XML DTD (experimental,
                        unsupported)
  -wsdl              :  treat input as WSDL and compile schemas inside
                        it(experimental,unsupported)
  -verbose           :  be extra verbose
  -quiet             :  suppress compiler output
  -help              :  display this help message
  -version           :  display version information


Extensions:
  -Xlocator          :  enable source location support for generated
                        code
  -Xsync-methods     :  generate accessor methods with the
                        'synchronized' keyword
  -mark-generated    :  mark the generated code as @javax.annotation.
                        Generated
  -episode <FILE>    :  generate the episode file for separate
                        compilation

Note

JEUS 8 web services also support ANT TASK of XJC. For more information, refer to JEUS Reference Book. "4.12. xjc" and JEUS Reference Book. "5.5.5. xjc".

Programming Using XJC ANT TASK

The following example shows how to programmatically handle contents of an XML document by converting the schema and XML documents into Java objects in memory through JAXB.

The following describes the overall flow.

  1. Converts an XML document into a Java object by unmarshalling.

  2. Programmatically processes the converted Java object.

  3. Converts the Java object into an XML document via marshalling (output is shown in the example).

The following is from the build.xml file of the example.

[Example 20.1] << build.xml >>

...
<project basedir="." default="run">
...
    <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
        <classpath refid="classpath" />
    </taskdef>
    <target name="compile" description="Compile all Java source
        files">
        <echo message="Compiling the schema..." />
        <mkdir dir="gen-src" />
        <xjc extension="true" schema="po.xsd" package="primer.myPo"
            destdir="gen-src">
            <produces dir="gen-src/primer.myPo" includes="**/*.java" />
        </xjc>
        <echo message="Compiling the java source files..." />
        <mkdir dir="classes" />
        <javac destdir="classes" debug="on">
            <src path="src" />
            <src path="gen-src" />
            <classpath refid="classpath" />
        </javac>
    </target>
    <target name="run" depends="compile" description="Run the sample
        app">
        <echo message="Running the sample application..." />
        <java classname="Main" fork="true">
            <classpath refid="classpath" />
        </java>
    </target>
...
</project>


The following describes the 'Main.java' file in the example.

[Example 20.2] << Main.java >>

Schema schema = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI).
    newSchema(new File("src/conf/ts.xsd"));

JAXBContext jc = JAXBContext.newInstance("com.tmaxsoft");

//
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema(schema);

...

//
Marshaller marshaller = jc.createMarshaller();
marshaller.setSchema(schema);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

...


Create a JAXBContext object by using the package name of the Java classes, which were created by using the XJC ANT TASK mapping in the build.xml file. Use it to create the Unmarshaller and Marshaller. In addition, create a schema object that determines whether the XML document is implemented according to the schema, and register it with the Unmarshaller and Marshaller.

[Example 20.3] << Main.java (continued) >>

Object ts = unmarshaller.unmarshal(new File("src/conf/tsInput.xml"));
TmaxSoftType tst = (TmaxSoftType) ((JAXBElement) ts).getValue();
Address address = tst.getAddress1();
address.setName("John Bob");
address.setStreet("242 Main Street");
address.setCity("Beverly Hills");


Unmarshal an XML document, called 'poInput.xml'. Modify the unmarshalled Java object.

[Example 20.4] << Main.java (continued) >>

marshaller.marshal(ts, System.out);


Output(marshal) to the console.

20.2.2. Schemagen Programming Techniques

JEUS 8 web services provide a tool to create a particular XML schema from user-implemented Java classes and XJC, a schema compiler that creates a Java class from the schema. The tool is called schema generator, and this section discusses Schemagen, the default schema generator provided by JEUS 8 web services.

Schemagen

Execute the following command from the command line.

JEUS_HOME/bin$ schemagen.cmd -help

Usage:

Usage: schemagen [-options ...] <java files>
Options:
    -d <path>         :  specify where to place processor and javac
                         generated class files
    -cp <path>        :  specify where to find user specified files
    -classpath <path> :  specify where to find user specified files
    -episode <file>   :  generate episode file for separate
                         compilation
    -version          :  display version information
    -help             :  display this usage message

Note

JEUS 8 web services also supports ANT TASK for Schemagen. For more information, refer to JEUS Reference Book. "4.13. schemagen" and JEUS Reference Book. "5.5.6. schemagen".

Programming with Schemagen ANT TASK

The following describes the overall flow.

  1. Create a schema at the source level by processing Java sources with Schemagen.

  2. Compile Java sources.

  3. Create a Java object by programmatically entering data for the compiled Java sources.

  4. Marshal (outputs of the example) the Java object by using the already created schema.

The following is a part of the build.xml file of the example.

[Example 20.5] << build.xml >>

...
<project basedir="." default="run">
...
    <taskdef name="schemagen"
        classname="com.sun.tools.jxc.SchemaGenTask">
        <classpath refid="classpath" />
    </taskdef>
    <target name="compile"
        description="Compile all Java source files">
        <echo message="Generating schemas..." />
        <mkdir dir="schemas" />
        <schemagen destdir="schemas">
            <src path="src" />
            <classpath refid="classpath" />
        </schemagen>
        <echo message="Compiling the java source files..." />
        <mkdir dir="classes" />
        <javac destdir="classes" debug="on">
            <src path="src" />
            <classpath refid="classpath" />
        </javac>
    </target>
    <target name="run" depends="compile"
        description="Run the sample app">
        <echo message="Running the sample application..." />
        <java classname="Main" fork="true">
            <classpath refid="classpath" />
        </java>
    </target>
...
</project>


The following are Java classes that represent the same schema in the example.

  • BusinessCard.java

  • Address.java

  • jaxb.index

  • package-info.java

  • Main.java

The following describes briefly about the 'Main.java' file.

[Example 20.6] << Main.java >>

BusinessCard card =
    new BusinessCard("John Doe", "Sr. Widget Designer", "Acme, Inc.",
        new Address(null, "123 Widget Way", "Anytown", "MA", (short) 12345),
        "123.456.7890", null, "123.456.7891", "John.Doe@Acme.ORG");

JAXBContext context = JAXBContext.newInstance(BusinessCard.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(card, new FileOutputStream(new File("src/conf/bcard.xml")));

...

Create a Java object by using the compiled Java classes, and register a Marshaller to marshal them to the bcard.xml file.


[Example 20.7] << Main.java (continued) >>

Unmarshaller um = context.createUnmarshaller();
Schema schema = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI)
        .newSchema(Main.class.getResource("schema1.xsd"));
um.setSchema(schema);
Object bce = um.unmarshal(new File("src/conf/bcard.xml"));
m.marshal(bce, System.out);


Create an Unmarshaller through the generated schema file, and unmarshal the marshalled bcard.xml file and output (marshal) to the console.

20.3. JAXP (Java Standard API for XML Processing)

Since XML and Java are platform independent, they are used together in various instances. JEUS 8 web services support Java standard API for handling XML documents. The standard is compliant with the standard(http://jcp.org/en/jsr/detail?id=206) for handling XML documents from JCP, a Java standard organization. The following are the key JAXP APIs.

  • SAX

  • DOM

  • TrAX

  • DOM

  • StAX

20.3.1. StAX (Java Streaming APIs for XML Parser)

JEUS 8 web services also support a Java streaming method that is used to parse XMLs. It is compliant with the API standard(http://www.jcp.org/en/jsr/detail?id=173) for Java streaming XML parser from JCP, a Java standard organization.