1 JAXB The Java Architecture for XML Binding Bibliography: - JAXB User’s Guide from Sun Microsystems - Java and XML Data Binding by McLaughlin.

Slides:



Advertisements
Similar presentations
J0 1 Marco Ronchetti - Web architectures – Laurea Specialistica in Informatica – Università di Trento Java XML parsing.
Advertisements

Exceptions Session 21. Memory Upload Creating Exceptions Using exceptions to control object creation and validation.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Chapter 1: Computer Systems
Software Development Tools COMP220/COMP285 Seb Coope Ant and XML: Getting Started These slides are mainly based on “Java Development with Ant” - E. Hatcher.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
JAXB Java Architecture for XML Binding Andy Fanton Khalid AlBayat.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Writing Enterprise Applications with J2EE (Sixth lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
14-Jun-15 DOM. SAX and DOM SAX and DOM are standards for XML parsers-- program APIs to read and interpret XML files DOM is a W3C standard SAX is an ad-hoc.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Using JAXB Revisited. 2 An XSDL Document for an ItemList
Outline Java program structure Basic program elements
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Fonts and colors Times New Roman “quotes” Trebuchet "quotes" yellow blue pink green violet.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
29-Jun-15 JAXB Java Architecture for XML Binding.
JAXB Java Architecture for XML Bindings. What is JAXB? JAXB defines the behavior of a standard set of tools and interfaces that automatically generate.
Internet Technologies JAXB Java API for XML Binding JavaMail.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Web Services with Apache CXF Part 2: JAXB and WSDL to Java Robert Thornton.
Using Ant to build J2EE Applications Kumar
AIXM Viewer Implementation Presentation to AIXM Users’ Conference, Federal Aviation Administration, Washington D.C., Feb 27-March 1, By: Mark Austin,
1 Lecture 22 George Koutsogiannakis Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
1 3. Implementing Web Services 1.Create SOAP proxy interfaces and WSDL based service descriptions 2.Register/publish services 3.Stores service descriptions.
Understanding the CORBA Model. What is CORBA?  The Common Object Request Broker Architecture (CORBA) allows distributed applications to interoperate.
Java: Chapter 1 Computer Systems Computer Programming II.
1 Computer Systems -- Introduction  Chapter 1 focuses on:  the structure of a Java application  basic program elements  preparing and executing a program.
The Java Programming Language
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Java API for XML Processing (JAXP) Dr. Rebhi S. Baraka Advanced Topics in Information Technology (SICT 4310) Department of Computer.
Sheet 1XML Technology in E-Commerce 2001Lecture 3 XML Technology in E-Commerce Lecture 3 DOM and SAX.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 RMI.
1 BUILDING JAVA PROGRAMS CHAPTER 6 FILE PROCESSING.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
Web Services with Apache CXF Part 2: JAXB and WSDL to Java Robert Thornton.
CS 157B: Database Management Systems II February 18 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Computer Science 209 Software Development Handing Errors and Creating Documentation.
Chapter 3 Objects and Classes. Objects Object – a data type with structure, state, and operations to access and manipulate state - an instance of a class.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
CSC Java Programming, Fall, 2008 Week 3: Objects, Classes, Strings, Text I/O, September 11.
JAXB (Java Architecture for XML Binding) Internet Computing KUT ( Youn-Hee Han.
7-Mar-16 Simple API XML.  SAX and DOM are standards for XML parsers-- program APIs to read and interpret XML files  DOM is a W3C standard  SAX is an.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 9.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
1 Introduction SAX. Objectives 2  Simple API for XML  Parsing an XML Document  Parsing Contents  Parsing Attributes  Processing Instructions  Skipped.
JAXB The Java Architecture for XML Binding Notes taken from the JAXB User’s Guide from Sun Microsystems.
The Java API for XML Binding. The Need for Data Binding To support unmarshlling to convert XML data into Java objects. To support marshalling to convert.
Chapter No. : 1 Introduction to Java.
Web Services-JAX-RPC JAX-RPC enables a Web Service endpoint to be developed using either a Java Servlet or Enterprise JavaBeans (EJB) component model.
Software Development Java Classes and Methods
Objects, Classes, Program Constructs
Using Jsoup to Parse HTML
Data Modeling II XML Schema & JAXB Marc Dumontier May 4, 2004
Accessing Files in Java
null, true, and false are also reserved.
Exception Handling Contents
A type is a collection of values
Presentation transcript:

1 JAXB The Java Architecture for XML Binding Bibliography: - JAXB User’s Guide from Sun Microsystems - Java and XML Data Binding by McLaughlin

2 JAXB Like SAX and DOM in that the application developer does not have to parse the XML Unlike SAX and DOM it is tied to a particular document schema Fast like SAX In memory representation like DOM but without all the general tree manipulation facilities

3 JAXB An XML Document is an instance of a schema A Java object is an instance of a class JAXB reads a schema and produces a class Previously, the only schema supported was the Document Type Definition (DTD) Currently, the only schema supported is XSDL

4 In general - Data Binding involves: Source generation From constraints to code Unmarshalling Reading Marshalling Writing Binding Schemas Details about how the XML is to be mapped to Java classes (very important with DTD’s)

5 JAXB Augments the standard DTD by providing type conversion : With JAXB we can make sure that Java converts this to a BigDecimal automatically

6 The Binding Schema JAXB requires that we use a DTD AND a “Binding Schema” The Binding Schema is an XML document JAXB DTD Binding Schema.java file(s) javac.class files javac

7 The Binding Schema The binding schema contains instructions on how to bind a schema to classes. It might say that : –this attribute (in the XML document) should be treated as an int –this element’s content is a BigDecimal –this element’s content is a String –this element should be treated as a class –and so on …

8 Running Old JAXB with DTD’s C:\McCarthy\www\95-733\examples\jaxb>java -jar D:\jaxb\jaxb-1.0-ea\lib\jaxb-xjc-1.0-ea.jar -help Usage: xjc [ ] [ -d ] [ -roots ] Options: -d Specify the destination directory for the Java output -roots Designate one or more root elements (comma separated) -version Print the compiler's version number and exit -help Print this message and exit

9 Book.xml The Catcher in the Rye J.D. Salinger If you really want to hear about it...

10 Book.dtd

11 A minimal binding schema Book.xjc

12 Run old JAXB C:\McCarthy\www\95-733\examples\jaxb>java -jar D:\jaxb\jaxb-1.0-ea\lib\jaxb-xjc-1.0-ea.jar book0.dtd book.xjc.\Book.java C:\McCarthy\www\95-733\examples\jaxb>

13 Resulting Book.java file import java.io.IOException; import java.io.InputStream; import javax.xml.bind.ConversionException; import javax.xml.bind.Dispatcher; import javax.xml.bind.InvalidAttributeException; import javax.xml.bind.LocalValidationException; import javax.xml.bind.MarshallableRootElement; import javax.xml.bind.Marshaller; import javax.xml.bind.MissingContentException; import javax.xml.bind.RootElement; import javax.xml.bind.StructureValidationException; import javax.xml.bind.UnmarshalException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.Validator; import javax.xml.marshal.XMLScanner; import javax.xml.marshal.XMLWriter;

14 public class Book extends MarshallableRootElement implements RootElement { private String _Title; private String _Author; private String _Chapter; public String getTitle() { return _Title; } public void setTitle(String _Title) { this._Title = _Title; if (_Title == null) { invalidate(); }

15 public String getAuthor() { return _Author; } public void setAuthor(String _Author) { this._Author = _Author; if (_Author == null) { invalidate(); } public String getChapter() { return _Chapter; } public void setChapter(String _Chapter) { this._Chapter = _Chapter; if (_Chapter == null) { invalidate(); }

16 public void validateThis() throws LocalValidationException { if (_Title == null) { throw new MissingContentException("title"); } if (_Author == null) { throw new MissingContentException("author"); } if (_Chapter == null) { throw new MissingContentException("chapter"); } public void validate(Validator v) throws StructureValidationException { }

17 public void marshal(Marshaller m) throws IOException { XMLWriter w = m.writer(); w.start("book"); w.leaf("title", _Title.toString()); w.leaf("author", _Author.toString()); w.leaf("chapter", _Chapter.toString()); w.end("book"); } public void unmarshal(Unmarshaller u) throws UnmarshalException { XMLScanner xs = u.scanner(); Validator v = u.validator(); xs.takeStart("book"); while (xs.atAttribute()) { String an = xs.takeAttributeName(); throw new InvalidAttributeException(an); }

18 if (xs.atStart("title")) { xs.takeStart("title"); String s; if (xs.atChars(XMLScanner.WS_COLLAPSE)) { s = xs.takeChars(XMLScanner.WS_COLLAPSE); } else { s = ""; } try { _Title = String.valueOf(s); } catch (Exception x) { throw new ConversionException("title", x); } xs.takeEnd("title"); } if (xs.atStart("author")) { xs.takeStart("author"); String s; if (xs.atChars(XMLScanner.WS_COLLAPSE)) { s = xs.takeChars(XMLScanner.WS_COLLAPSE); } else { s = ""; }

19 try { _Author = String.valueOf(s); } catch (Exception x) { throw new ConversionException("author", x); } xs.takeEnd("author"); } if (xs.atStart("chapter")) { xs.takeStart("chapter"); String s; if (xs.atChars(XMLScanner.WS_COLLAPSE)) { s = xs.takeChars(XMLScanner.WS_COLLAPSE); } else { s = ""; } try { _Chapter = String.valueOf(s); } catch (Exception x) { throw new ConversionException("chapter", x); } xs.takeEnd("chapter"); }

20 xs.takeEnd("book"); } public static Book unmarshal(InputStream in) throws UnmarshalException { return unmarshal(XMLScanner.open(in)); } public static Book unmarshal(XMLScanner xs) throws UnmarshalException { return unmarshal(xs, newDispatcher()); } public static Book unmarshal(XMLScanner xs, Dispatcher d) throws UnmarshalException { return ((Book) d.unmarshal(xs, (Book.class))); }

21 public boolean equals(Object ob) { if (this == ob) { return true; } if (!(ob instanceof Book)) { return false; } Book tob = ((Book) ob); if (_Title!= null) { if (tob._Title == null) { return false; } if (!_Title.equals(tob._Title)) { return false; } } else { if (tob._Title!= null) { return false; }

22 if (_Author!= null) { if (tob._Author == null) { return false; } if (!_Author.equals(tob._Author)) { return false; } } else { if (tob._Author!= null) { return false; } if (_Chapter!= null) { if (tob._Chapter == null) { return false; } if (!_Chapter.equals(tob._Chapter)) { return false; }

23 } else { if (tob._Chapter!= null) { return false; } return true; } public int hashCode() { int h = 0; h = ((127 *h)+((_Title!= null)?_Title.hashCode(): 0)); h = ((127 *h)+((_Author!= null)?_Author.hashCode(): 0)); h = ((127 *h)+((_Chapter!= null)?_Chapter.hashCode(): 0)); return h; }

24 public String toString() { StringBuffer sb = new StringBuffer("<<book"); if (_Title!= null) { sb.append(" title="); sb.append(_Title.toString()); } if (_Author!= null) { sb.append(" author="); sb.append(_Author.toString()); } if (_Chapter!= null) { sb.append(" chapter="); sb.append(_Chapter.toString()); } sb.append(">>"); return sb.toString(); }

25 public static Dispatcher newDispatcher() { Dispatcher d = new Dispatcher(); d.register("book", (Book.class)); d.freezeElementNameMap(); return d; }

26 A Driver Program // demo JAXB import java.io.*; public class TestJaxb { public static void main(String args[]) throws java.io.FileNotFoundException, javax.xml.bind.UnmarshalException, java.io.IOException { DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream(args[0]))); DataOutputStream out = new DataOutputStream( new FileOutputStream(args[1]));

27 // read in the book Book catcher = Book.unmarshal(in); // change its title catcher.setTitle("Gone With The Wind"); // write out the book catcher.marshal(out); }

28 Compile and Run C:\McCarthy\www\95-733\examples\jaxb>javac Book.java C:\McCarthy\www\95-733\examples\jaxb>javac TestJaxb.java C:\McCarthy\www\95-733\examples\jaxb>java TestJaxb book.xml out.xml

29 Out.xml Gone With The Wind J.D. Salinger If you really want to hear about it...

30 Using the new JAXB

31 An XSDL Document for an ItemList <xsd:element ref="item" minOccurs="0" maxOccurs="3"/>

32

33 A Document Instance <itemList xmlns:xsi=' xsi:noNamespaceSchemaLocation="itemList.xsd"> pen 5 eraser 7 stapler 2

34 An Ant Build file <!– adapted from Sun’s jaxb build file 

35 <javadoc packagenames="itemListAPI" sourcepath="." destdir="docs/api" windowtitle="Generated Interfaces for itemList.xsd">

36

37

38 Running the build D:\McCarthy\www\95-733\examples\struts1\src\VO>ant generate Buildfile: build.xml generate: [echo] Compiling the schema... [xjc] Compiling file:/D:/McCarthy/www/95-733/examples/struts1/src/VO/itemL ist.xsd [xjc] Writing output to D:\McCarthy\www\95-733\examples\struts1\src\VO [javadoc] Generating Javadoc [javadoc] Javadoc execution [javadoc] Loading source files for package itemListAPI... [javadoc] Constructing Javadoc information... [javadoc] Standard Doclet version [javadoc] Building tree for all the packages and classes... [javadoc] Building index for all the packages and classes... [javadoc] Building index for all classes... [echo] Compiling the java source files... [javac] Compiling 42 source files to D:\McCarthy\www\95-733\examples\struts1 \src\VO BUILD SUCCESSFUL

39 Viewing the docs

40 Write the client import java.io.File; import java.io.IOException; import java.math.BigDecimal; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.UnmarshalException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.util.ValidationEventCollector; // import java content classes generated by binding compiler import itemListAPI.*;

41 public class Main { // This sample application demonstrates how to enable validation during // the unmarshal operations. public static void main( String[] args ) { try { // create a JAXBContext capable of handling classes generated into // the itemListAPI package JAXBContext jc = JAXBContext.newInstance( "itemListAPI" ); // create an Unmarshaller Unmarshaller u = jc.createUnmarshaller(); // enable validation u.setValidating( true );

42 // in this example, we will allow the Unmarshaller's default // ValidationEventHandler to receive notification of warnings // and errors which will be sent to System.out. The default // ValidationEventHandler will cause the unmarshal operation // to fail with an UnmarshalException after encountering the // first error or fatal error. // unmarshal an invalid itemList instance document into a tree of Java // content objects composed of classes from the itemListAPI package. ItemList itemList = (ItemList)u.unmarshal( new File( "itemList.xml" ) ); java.util.List list = itemList.getItem(); System.out.println("The length of the list is " + list.size());

43 int n = list.size(); for(int k = 0; k < n; k++) { ItemType it = (ItemType)list.get(k); String st = it.getName(); System.out.println(st); } } catch( UnmarshalException ue ) { // The JAXB specification does not mandate how the JAXB provider // must behave when attempting to unmarshal invalid XML data. In // those cases, the JAXB provider is allowed to terminate the // call to unmarshal with an UnmarshalException. System.out.println( "Caught UnmarshalException" ); } catch( JAXBException je ) { je.printStackTrace(); }

44 Running the Client D:\McCarthy\www\95-733\examples\struts1\src\VO>ant JustJavaRun Buildfile: build.xml JustJavaRun: [echo] java runtime [java] The length of the list is 3 [java] pen [java] eraser [java] stapler BUILD SUCCESSFUL Total time: 2 seconds