Presentacipon de JAXB

download Presentacipon de JAXB

of 48

Transcript of Presentacipon de JAXB

  • 8/10/2019 Presentacipon de JAXB

    1/48

    The Java

    Architecture ForXML Binding (JAXB)

    By:Yoav Zibin

    Sharon Krisher

  • 8/10/2019 Presentacipon de JAXB

    2/48

    Motivation for JAXB

    The main purpose of XML Schemais: Validationof XML documents

    Any other purposes? Hint 1: determinism requirement

    Hint 2: the default attribute has nothingto dowith validation

  • 8/10/2019 Presentacipon de JAXB

    3/48

    Motivation for JAXB

    Problem: How to manipulate this data model?

    DOM(data object model) solution:

    Pros:simple, general (a schema is not even required) Cons:no types, no compile-time checking

    I wish to write

    root.getChild("Address").getChild("Number").getText()

    DOMpseudo-code example

    root.getAddress().getNumber()

    returns a number

    returns a string

  • 8/10/2019 Presentacipon de JAXB

    4/48

    Binding Compiler

    Javainterface

    s

    Sourceschema

    JAXB solution:

    Mapping XML Schema to Java interfaces

    Pros:preserve types, compile-time checking

    Cons:complex, specific to a certain schema

  • 8/10/2019 Presentacipon de JAXB

    5/48

    Binding Compiler

    public interfaceAddressType{

    longgetNumber();

    void setNumber(longvalue);

    StringgetStreet();

    void setStreet(Stringvalue);

    }

    Must be non-negative

    Must be non-null

  • 8/10/2019 Presentacipon de JAXB

    6/48

  • 8/10/2019 Presentacipon de JAXB

    7/48

    Main Features

    Unmarshal:xmlobjects

    Create / Read / Update / Delete objects

    Validateobjects

    Marshal:objectsxml

    No roundtripguarantees Marshal( Unmarshal(xml) ) xml

    We found that order is not always preserved

    But usually roundtrip holds

  • 8/10/2019 Presentacipon de JAXB

    8/48

    Step 1: Create XML Schema

  • 8/10/2019 Presentacipon de JAXB

    9/48

    Step 2: Create XML Document

    Sharon Krisher

    Iben Gevirol

    57

    Moshe Sharet89

    Check that your XML conforms to the Schema

    Demo.xml

  • 8/10/2019 Presentacipon de JAXB

    10/48

    Step 3: Run the binding compiler

    %JWSDP_HOME%\jaxb\bin\xjc -p demodemo.xsd

    A package named demois created

    (in the directory demo) The package contains (among other things):

    interfaceAddressType

    interface PersonType

  • 8/10/2019 Presentacipon de JAXB

    11/48

    AddressType and PersonType

    public interfaceAddressType{

    long getNumber();

    void setNumber(long value);

    String getStreet();void setStreet(String value);

    }

    public interface PersonType{

    String getName();

    void setName(String value);

    /* List ofAddressType*/

    java.util.List getAddress();

    }

    In Java1.5:List

    Must contain at least one item

    Must be non-negative

    Must be non-null

    Must be non-null

  • 8/10/2019 Presentacipon de JAXB

    12/48

    Step 4: Create Context

    The context is the entry point to the API

    Contains methods to create Marshaller,

    Unmarshaller and Validator instances

    JAXBContext context= JAXBContext.newInstance("demo");

    The package name is demo

    (Recall: xjc -p demodemo.xsd)

  • 8/10/2019 Presentacipon de JAXB

    13/48

    Step 5: Unmarshal: xml -> objects

    Unmarshallerunmarshaller=

    context.createUnmarshaller();

    unmarshaller.setValidating(true);

    PersonTypeperson=

    (PersonType) unmarshaller.unmarshal(

    new FileInputStream("demo.xml") );

    Enable validation of xml

    according to the

    schema whileunmarshalling

  • 8/10/2019 Presentacipon de JAXB

    14/48

    Step 6: Read

    System.out.println("Person name=" +

    person.getName() );

    AddressTypeaddress= (AddressType)

    person.getAddress().get(0);

    System.out.println("First Address: " +

    " Street=" + address.getStreet() +" Number=" + address.getNumber() );

  • 8/10/2019 Presentacipon de JAXB

    15/48

    Step 7: Manipulate objects

    // Update

    person.setName("Yoav Zibin");

    // Delete

    ListaddressList=person.getAddress();

    addressList.clear();

    part of the demo package

    uses the factory pattern

    // Create

    ObjectFactoryobjectFactory= new ObjectFactory();

    AddressTypenewAddr= objectFactory.createAddressType();

    newAddr.setStreet("Hanoter");

    newAddr.setNumber(5);

    addressList.add( newAddr);

    What happens if we validate there?

  • 8/10/2019 Presentacipon de JAXB

    16/48

    Step 8: Validate on-demand

    Validatorvalidator= context.createValidator();

    validator.validate(newAddr);

    validator.validate(person);

    Check that we have set StreetandNumber,

    and thatNumberis non-negative

    Check that we have setName, and thatAddress

    contains at least one item

  • 8/10/2019 Presentacipon de JAXB

    17/48

    Step 9: Marshal: objects -> xml

    Marshallermarshaller= context.createMarshaller();

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,

    Boolean.TRUE);

    marshaller.marshal(person,new FileOutputStream("output.xml"));

    Yoav Zibin

    Hanoter

    5

    output.xml

  • 8/10/2019 Presentacipon de JAXB

    18/48

    And now, the Demo!

  • 8/10/2019 Presentacipon de JAXB

    19/48

    First Part Summary

  • 8/10/2019 Presentacipon de JAXB

    20/48

    Similar Technologies

    Liquid XML Data Binding

    Similar to JAXB

    Supports all Schemaconstructs

    In addition to Java: C#, C++, Visual Basic 6

    Relaxer

    Instead of Schemauses Relax

    Castor.org

  • 8/10/2019 Presentacipon de JAXB

    21/48

    Second Part Outline

    Validation

    MappingXML Schema to Java

    Naming

    Java Properties

    Simple and Complex Types

    Customization of the default mapping

  • 8/10/2019 Presentacipon de JAXB

    22/48

    Validation Constraints

    Three categories of constraints

    Type constraints: Legal values in simple types

    E.g., in every address, numberis a non-negativeinteger

    Local structural constraints E.g., in every person, addresscontains at least

    one item Global structural constraints

    E.g., ID and IDREF

  • 8/10/2019 Presentacipon de JAXB

    23/48

    Validation

    Three forms of validation Unmarshal timevalidation (at unmarshal time)

    On-demandvalidation (at any chosen point in time) validateRoot(object) vs. validate(object) validateRoot includes global constraint checking

    Fail-fastvalidation (at all times) Currently not implemented

    Checks that the value provided to a set method is legal

    When validation errors occur an event is raised(no exception) and validation continues, so thatseveral validation errors can be handled.

    Default handler raises an exception on first error

  • 8/10/2019 Presentacipon de JAXB

    24/48

    Unsupported Schema Concepts

    Substitution groups

    Type substitutions (xsi:type, block)

    Key, keyref, and unique

    anyAttribute

    No support for XPath or any other query

    langauge

  • 8/10/2019 Presentacipon de JAXB

    25/48

    Element vs. Type

    An element also has a qualified name

    When is the difference important? (next)

    interface UglyManextends PersonType, Element{}interface PrettyWoman extends PersonType, Element{}

    interface PersonType{ }

    an empty interface which marks

    the existence of a static QName

  • 8/10/2019 Presentacipon de JAXB

    26/48

    When must I use elements?

    Marshal:

    General content

    marshaller.marshal(Object, OutputStream)

    must be an element,

    otherwise the resulting

    output is not a legal XML

    ObjectgetAny();

    void setAny(Object elementOrValue);

    Sharon Krisher

    Iben Gevirol

    57

    E.g., when we marshal a PersonType:

  • 8/10/2019 Presentacipon de JAXB

    27/48

    Naming

    Problem: sometimes XML names

    are not legaljava names

    do not comply to java naming standards

    The binding compiler creates proper

    names

    XML Name Class Name Method Name

    mixedCaseName MixedCaseName getMixedCaseName

    name-with-dash NameWithDash getNameWithDash

    aa_bb-cc AaBbCc getAaBbCc

  • 8/10/2019 Presentacipon de JAXB

    28/48

    Java Properties

    Local schema components are mapped to:

    Simple property (get, set)

    With customization: isSetName, unsetName

    List property

    Indexed property (next)

    java.util.ListgetAddress();

    StringgetName();

    void setName(Stringvalue);

    In Java1.5:

    List

  • 8/10/2019 Presentacipon de JAXB

    29/48

    Indexed Property

    Used instead of a list property when a

    proper customization is applied

    AddressType[] getAddress();

    void setAddress(AddressType[] value);

    AddressTypegetAddress(int index);

    void setAddress(int index,AddressTypevalue);

  • 8/10/2019 Presentacipon de JAXB

    30/48

    General Content Property

    The most general content property

    Can represent any content, however complex

    A list that can contain element interfaces and values Used for problematic cases :

    Name collisions due to derivation

    Mixedcontent

    Another example:

    ListgetAny();

    Each item can be

    some element or

    value

  • 8/10/2019 Presentacipon de JAXB

    31/48

    Simple Types (partial diagram)

    SimpleType

    Primtive List Union Restriction

    ID/IDREF

    maxInclusive

    Enumeration

    date

    integer

    int

    Calendar

    BigInteger

    int

    String/Object

    ListRepresented as

    validation

    constraints

    Next (1)

    Next (2)

  • 8/10/2019 Presentacipon de JAXB

    32/48

    Simple Type: Union

    Public interface Date {ObjectgetMonth();

    void setMonth(Object);

    }

    Common supertype of(Integer, String) isObject

  • 8/10/2019 Presentacipon de JAXB

    33/48

    Type Safe Enumeration

    public class USState{protected USSate(String v) {}

    public static final USStateAK= ;public static final USStateNY= ;

    public StringgetValue();

    public static USStatefromValue(Stringv) {}}

  • 8/10/2019 Presentacipon de JAXB

    34/48

    XML Schema Type System

    Any

    SimpleType ComplexType

    SimpleContent ComplexContent Sequence Choice All

    Extension Extension

    RestrictionAttributes

    use

    default

    fixed

    Elements

    abstractnillable

    minOccurs

    maxOccurs

    finishedRepresented as

    a Java interface

    The interface

    extendsthe base

    types interface Represented as

    Java properties

    *

    * *

    ( ) Next*

    **

    *

  • 8/10/2019 Presentacipon de JAXB

    35/48

    Complex Types

    Represented as a Java interface

    Anonymous type

    An interface is created.

    The name is derived from the name of the

    schema element + Type, e.g Foo FooType

    Abstract types: no create method inObjectFactory

  • 8/10/2019 Presentacipon de JAXB

    36/48

    Complex Type:Simple Content

    interface InternationalPrice{

    intgetValue();

    void setValue(int);

    StringgetCurrency();

    void setCurrency(String);

    }

  • 8/10/2019 Presentacipon de JAXB

    37/48

    Complex Type:Aggregation

    interface Foo{

    intgetA(); void setA(int);intgetB(); void setB(int);

    intgetC(); void setC(int);

    }

  • 8/10/2019 Presentacipon de JAXB

    38/48

    Complex Type:Mixed Content

  • 8/10/2019 Presentacipon de JAXB

    39/48

    Complex Type: Choice

    public interface FooBarType{

    ObjectgetFooOrBar();

    void setFooOrBar(Object);

    }

    Common supertype of(Integer, String) isObject

    Similar tounion

    public interface FooBarType{

    intgetFoo();

    void setFoo(intvalue);

    StringgetBar();

    void setBar(Stringvalue);

    boolean isSetFoo();

    void unsetFoo();

    boolean isSetBar();

    void unsetBar();

    }

    The programmer

    is responsible to

    only set one ofFoo or Bar

    Default

    Customization (Not implemented yet)

  • 8/10/2019 Presentacipon de JAXB

    40/48

    When maxOccurs>1

    public interface FooBarType {

    interface Fooextends Element{}

    interface Barextends Element{}

    // Items are instances of Fooand BarListgetFooOrBar();

    }

    For asequence: ListgetFooAndBar()

    The programmer needs to make sure that

    the list contains sequences of.

  • 8/10/2019 Presentacipon de JAXB

    41/48

    Complex Type:All

    Mapped like Sequence

    Cant have maxOccurs > 1

    No way to specify the orderof elements Round tripdoesnt hold (orderis not preserved):

    XML

    Objects

    in

    memoryXML

    unmarshal

    marshal

  • 8/10/2019 Presentacipon de JAXB

    42/48

    Nillable elements

    IntegergetAge();void setAge(Integervalue);

    XML: 25 or

    setAge

    (null

    )

    Java:setAge

    ( newInteger

    (25) )

    or

  • 8/10/2019 Presentacipon de JAXB

    43/48

    Customization

    Used to augment the default mapping

    Customizations declared via special xml

    tags

    May appear inside the source schema or

    in a separate file

  • 8/10/2019 Presentacipon de JAXB

    44/48

    Uses of Customization

    Change default names of interfaces and

    properties

    For a specific schema construct For an entire namespace

    Add a suffix or a prefix

    Change the types of propertiesAdd javadoc declarations

  • 8/10/2019 Presentacipon de JAXB

    45/48

    Software Engineering Issues

    Weak Typing

    Our suggestions:

    Marshal / Unmarshal : Object Element IDREF: Object Identifiable

    Sometimes JAXB doesnt allow us to

    control the order of elements Example 1: xs:all

    Example 2: next slide

  • 8/10/2019 Presentacipon de JAXB

    46/48

    Element Order Example

  • 8/10/2019 Presentacipon de JAXB

    47/48

    Its the programmers fault

    Taken from JAXB specification:

    The caller must be sure

    There is an expectation User is responsible

    unexpected behavior may occur.

    42obj.setAge(42);

    obj.unsetAge();

    System.out.println( obj.getAge() );

    Question: What is the output ?

    obj.setFoo(42);

    obj.setBar("A");

    System.out.println( obj.isSetFoo() );

    xs:choice between Fooand Bar

    true

  • 8/10/2019 Presentacipon de JAXB

    48/48

    The END

    Any questions?