2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library 10. JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes Pull Parsing versus Push Parsing Comparing StAX to Other JAXP APIs Choosing between Cursor and Iterator APIs Comparing Cursor and Iterator APIs Resources, Namespaces, and Errors Error Reporting and Exception Handling Sun's Streaming XML Parser Implementation Streaming XML Parser Factories Implementation Returning String Representations Building and Running the Cursor Example Using NetBeans IDE Building and Running the Cursor Example Using Ant Instantiating anXMLEventAllocator Building and Running the Cursor-to-Event Example Using NetBeans IDE Building and Running the Cursor-to-Event Example Using Ant Building and Running the Event Example Using NetBeans IDE Building and Running the Event Example Using Ant Implementing theStreamFilter Class Building and Running the Filter Example Using NetBeans IDE Building and Running the Filter Example Using Ant Creating an Event Producer/Consumer Building and Running the Read-and-Write Example Using NetBeans IDE Building and Running the Read-and-Write Example Using Ant Further Information about StAX 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Example CodeThis section steps through the example StAX code included in the Java EE5 Tutorial bundle. All example directories used in this section are located inthetut-install/javaeetutorial5/examples/stax/ directory. The topics covered in this section are as follows: Example Code OrganizationThetut-install/javaeetutorial5/examples/stax/ directory contains the six StAX example directories:
All of the StAX examples except for the Writer example use anexample XML document,BookCatalog.xml. Example XML DocumentThe example XML document,BookCatalog.xml, used by most of the StAX example classes,is a simple book catalog based on the commonBookCatalogue namespace. The contentsofBookCatalog.xml are listed below: <?xml version="1.0" encoding="UTF-8"?><BookCatalogue xmlns="http://www.publishing.org"> <Book> <Title>Yogasana Vijnana: the Science of Yoga</Title> <author>Dhirendra Brahmachari</Author> <Date>1966</Date> <ISBN>81-40-34319-4</ISBN> <Publisher>Dhirendra Yoga Publications</Publisher> <Cost currency="INR">11.50</Cost> </Book> <Book> <Title>The First and Last Freedom</Title> <Author>J. Krishnamurti</Author> <Date>1954</Date> <ISBN>0-06-064831-7</ISBN> <Publisher>Harper & Row</Publisher> <Cost currency="USD">2.95</Cost> </Book></BookCatalogue> Cursor ExampleLocated in thetut-install/javaeetutorial5/examples/stax/cursor/ directory,CursorParse.java demonstrates using the StAX cursor API toread an XML document. In the Cursor example, the application instructs the parserto read the next event in the XML input stream by calling<code>next()</code>. Note that<code>next()</code> just returns an integer constant corresponding to underlying event wherethe parser is positioned. The application needs to call the relevant function toget more information related to the underlying event. You can imagine this approach as a virtual cursor moving across the XMLinput stream. There are various accessor methods which can be called when thatvirtual cursor is at a particular event. Stepping through EventsIn this example, the client application pulls the next event in the XMLstream by calling thenext method on the parser; for example: try { for (int i = 0 ; i < count ; i++) { // pass the file name.. all relative entity // references will be resolved against this as // base URI. XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename, new FileInputStream(filename)); // when XMLStreamReader is created, it is positioned // at START_DOCUMENT event. int eventType = xmlr.getEventType(); printEventType(eventType); printStartDocument(xmlr); // check if there are more events in the input stream while(xmlr.hasNext()) { eventType = xmlr.next(); printEventType(eventType); // these functions print the information about // the particular event by calling the relevant // function printStartElement(xmlr); printEndElement(xmlr); printText(xmlr); printPIData(xmlr); printComment(xmlr); } }}Note thatnext just returns an integer constant corresponding to the event underlyingthe current cursor location. The application calls the relevant function to get moreinformation related to the underlying event. There are various accessor methods which canbe called when the cursor is at particular event. Returning String RepresentationsBecause thenext method only returns integers corresponding to underlying event types, youtypically need to map these integers to string representations of the events; forexample: public final static String getEventTypeString(int eventType) { switch (eventType) { case XMLEvent.START_ELEMENT: return "START_ELEMENT"; case XMLEvent.END_ELEMENT: return "END_ELEMENT"; case XMLEvent.PROCESSING_INSTRUCTION: return "PROCESSING_INSTRUCTION"; case XMLEvent.CHARACTERS: return "CHARACTERS"; case XMLEvent.COMMENT: return "COMMENT"; case XMLEvent.START_DOCUMENT: return "START_DOCUMENT"; case XMLEvent.END_DOCUMENT: return "END_DOCUMENT"; case XMLEvent.ENTITY_REFERENCE: return "ENTITY_REFERENCE"; case XMLEvent.ATTRIBUTE: return "ATTRIBUTE"; case XMLEvent.DTD: return "DTD"; case XMLEvent.CDATA: return "CDATA"; case XMLEvent.SPACE: return "SPACE"; } return "UNKNOWN_EVENT_TYPE , " + eventType;}Building and Running the Cursor Example Using NetBeans IDEFollow these instructions to build and run the Cursor example on yourApplication Server instance using NetBeans IDE.
Building and Running the Cursor Example Using AntTo compile and run the Cursor example using Ant, in a terminalwindow, go to thetut-install/javaeetutorial5/examples/stax/cursor/ directory and type the following: ant run-cursor Cursor-to-Event ExampleLocated in thetut-install/javaeetutorial5/examples/stax/cursor2event/ directory,CursorApproachEventObject.java demonstrates how to get information returned byanXMLEvent object even when using the cursor API. The idea here is that the cursor API’sXMLStreamReader returns integer constants correspondingto particular events, while the event iterator API’sXMLEventReader returns immutable and persistent eventobjects.XMLStreamReader is more efficient, butXMLEventReader is easier to use, becauseall the information related to a particular event is encapsulated in a returnedXMLEvent object. However, the disadvantage of event approach is the extra overhead ofcreating objects for every event, which consumes both time and memory. With this mind,XMLEventAllocator can be used to get event information as anXMLEvent object, even when using the cursor API. Instantiating anXMLEventAllocatorThe first step is to create a newXMLInputFactory and instantiate anXMLEventAllocator: XMLInputFactory xmlif = XMLInputFactory.newInstance();System.out.println("FACTORY: " + xmlif);xmlif.setEventAllocator(new XMLEventAllocatorImpl());allocator = xmlif.getEventAllocator();XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename, new FileInputStream(filename));Creating an Event IteratorThe next step is to create an event iterator: int eventType = xmlr.getEventType();while(xmlr.hasNext()){ eventType = xmlr.next(); //Get all "Book" elements as XMLEvent object if(eventType == XMLStreamConstants.START_ELEMENT && xmlr.getLocalName().equals("Book")){ //get immutable XMLEvent StartElement event = getXMLEvent(xmlr).asStartElement(); System.out.println("EVENT: " + event.toString()); }}Creating the Allocator MethodThe final step is to create theXMLEventAllocator method: private static XMLEvent getXMLEvent(XMLStreamReader reader) throws XMLStreamException { return allocator.allocate(reader);}Building and Running the Cursor-to-Event Example Using NetBeans IDEFollow these instructions to build and run the Cursor-to-Event example on your ApplicationServer instance using NetBeans IDE.
Building and Running the Cursor-to-Event Example Using AntTo compile and run the Cursor-to-Event example using Ant, in a terminal window,go to thetut-install/javaeetutorial5/examples/stax/cursor2event/ directory and type the following: ant run-cursor2event Event ExampleLocated in thetut-install/javaeetutorial5/examples/stax/event/ directory,EventParse.java demonstrates how to use the StAXevent API to read an XML document. Creating an Input FactoryThe first step is to create a new instance ofXMLInputFactory: XMLInputFactory factory = XMLInputFactory.newInstance();System.out.println("FACTORY: " + factory);Creating an Event ReaderThe next step is to create an instance ofXMLEventReader: XMLEventReader r = factory.createXMLEventReader(filename, new FileInputStream(filename)); Creating an Event IteratorThe third step is to create an event iterator: XMLEventReader r = factory.createXMLEventReader(filename, new FileInputStream(filename));while(r.hasNext()) { XMLEvent e = r.nextEvent(); System.out.println(e.toString());}Getting the Event StreamThe final step is to get the underlying event stream: public final static String getEventTypeString(int eventType) { switch (eventType) { case XMLEvent.START_ELEMENT: return "START_ELEMENT"; case XMLEvent.END_ELEMENT: return "END_ELEMENT"; case XMLEvent.PROCESSING_INSTRUCTION: return "PROCESSING_INSTRUCTION"; case XMLEvent.CHARACTERS: return "CHARACTERS"; case XMLEvent.COMMENT: return "COMMENT"; case XMLEvent.START_DOCUMENT: return "START_DOCUMENT"; case XMLEvent.END_DOCUMENT: return "END_DOCUMENT"; case XMLEvent.ENTITY_REFERENCE: return "ENTITY_REFERENCE"; case XMLEvent.ATTRIBUTE: return "ATTRIBUTE"; case XMLEvent.DTD: return "DTD"; case XMLEvent.CDATA: return "CDATA"; case XMLEvent.SPACE: return "SPACE"; } return "UNKNOWN_EVENT_TYPE " + "," + eventType;}Returning the OutputWhen you run the Event example, theEventParse class is compiled, and theXML stream is parsed as events and returned toSTDOUT. For example,an instance of theAuthor element is returned as: <[’http://www.publishing.org’]::Author> Dhirendra Brahmachari</[’http://www.publishing.org’]::Author> Note in this example that the event comprises an opening and closing tag,both of which include the namespace. The content of the element isreturned as a string within the tags. Similarly, an instance of theCost element is returned as: <[’http://www.publishing.org’]::Cost currency=’INR’> 11.50</[’http://www.publishing.org’]::Cost> In this case, thecurrency attribute and value are returned in the openingtag for the event. Building and Running the Event Example Using NetBeans IDEFollow these instructions to build and run the Event example on yourApplication Server instance using NetBeans IDE.
Building and Running the Event Example Using AntTo compile and run the Event example using Ant, in a terminalwindow, go to thetut-install/javaeetutorial5/examples/stax/event/ directory and type the following: ant run-event Filter ExampleLocated in thetut-install/javaeetutorial5/examples/stax/filter/ directory,MyStreamFilter.java demonstrates how to use the StAX streamfilter API to filter out events not needed by your application. In thisexample, the parser filters out all events exceptStartElement andEndElement. Implementing theStreamFilter ClassTheMyStreamFilter class implementsjavax.xml.stream.StreamFilter: public class MyStreamFilter implements javax.xml.stream.StreamFilter {Creating an Input FactoryThe next step is to create an instance ofXMLInputFactory. In this case,various properties are also set on the factory: XMLInputFactory xmlif = null ;try { xmlif = XMLInputFactory.newInstance(); xmlif.setProperty( XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); xmlif.setProperty( XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); xmlif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);} catch (Exception ex) { ex.printStackTrace();}System.out.println("FACTORY: " + xmlif);System.out.println("filename = "+ filename);Creating the FilterThe next step is to instantiate a file input stream and createthe stream filter: FileInputStream fis = new FileInputStream(filename); XMLStreamReader xmlr = xmlif.createFilteredReader( xmlif.createXMLStreamReader(fis), new MyStreamFilter());int eventType = xmlr.getEventType();printEventType(eventType);while(xmlr.hasNext()) { eventType = xmlr.next(); printEventType(eventType); printName(xmlr,eventType); printText(xmlr); if (xmlr.isStartElement()) { printAttributes(xmlr); } printPIData(xmlr); System.out.println("-----------------------------");}Capturing the Event StreamThe next step is to capture the event stream. This is donein basically the same way as in the Event example. Filtering the StreamThe final step is to filter the stream: public boolean accept(XMLStreamReader reader) { if (!reader.isStartElement() && !reader.isEndElement()) return false; else return true;}Returning the OutputWhen you run the Filter example, theMyStreamFilter class is compiled, and theXML stream is parsed as events and returned toSTDOUT. For example,anAuthor event is returned as follows: EVENT TYPE(1):START_ELEMENTHAS NAME: AuthorHAS NO TEXTHAS NO ATTRIBUTES-----------------------------EVENT TYPE(2):END_ELEMENTHAS NAME: AuthorHAS NO TEXT----------------------------- Similarly, aCost event is returned as follows: EVENT TYPE(1):START_ELEMENTHAS NAME: CostHAS NO TEXTHAS ATTRIBUTES: ATTRIBUTE-PREFIX: ATTRIBUTE-NAMESP: nullATTRIBUTE-NAME: currencyATTRIBUTE-VALUE: USDATTRIBUTE-TYPE: CDATA-----------------------------EVENT TYPE(2):END_ELEMENTHAS NAME: CostHAS NO TEXT----------------------------- SeeIterator API andReading XML Streams for a more detailed discussion of StAX event parsing. Building and Running the Filter Example Using NetBeans IDEFollow these instructions to build and run the Filter example on yourApplication Server instance using NetBeans IDE.
Building and Running the Filter Example Using AntTo compile and run the Filter example using Ant, in a terminalwindow, go to thetut-install/javaeetutorial5/examples/stax/filter/ directory and type the following: ant run-filter Read-and-Write ExampleLocated in thetut-install/javaeetutorial5/examples/stax/readnwrite/ directory,EventProducerConsumer.java demonstrates how to use a StAX parsersimultaneously as both a producer and a consumer. The StAXXMLEventWriter API extends from theXMLEventConsumer interface, and is referredto as anevent consumer. By contrast,XMLEventReader is anevent producer. StAX supports simultaneous readingand writing, such that it is possible to read from one XML streamsequentially and simultaneously write to another stream. The Read-and-Write example shows how the StAX producer/consumer mechanism can be used toread and write simultaneously. This example also shows how a stream can bemodified and how new events can be added dynamically and then written toa different stream. Creating an Event Producer/ConsumerThe first step is to instantiate an event factory and then createan instance of an event producer/consumer: XMLEventFactory m_eventFactory = XMLEventFactory.newInstance();public EventProducerConsumer() {}...try { EventProducerConsumer ms = new EventProducerConsumer(); XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader( new java.io.FileInputStream(args[0])); XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter( System.out);Creating an IteratorThe next step is to create an iterator to parse the stream: while(reader.hasNext()) { XMLEvent event = (XMLEvent)reader.next(); if (event.getEventType() == event.CHARACTERS) { writer.add(ms.getNewCharactersEvent(event.asCharacters())); } else { writer.add(event); }}writer.flush();Creating a WriterThe final step is to create a stream writer in the formof a newCharacter event: Characters getNewCharactersEvent(Characters event) { if (event.getData().equalsIgnoreCase("Name1")) { return m_eventFactory.createCharacters( Calendar.getInstance().getTime().toString()); } //else return the same event else { return event; }}Returning the OutputWhen you run the Read-and-Write example, theEventProducerConsumer class is compiled, andthe XML stream is parsed as events and written back toSTDOUT. Theoutput is the contents of theBookCatalog.xml file described inExample XML Document. Building and Running the Read-and-Write Example Using NetBeans IDEFollow these instructions to build and run the Read-and-Write example on your ApplicationServer instance using NetBeans IDE.
Building and Running the Read-and-Write Example Using AntTo compile and run the Read-and-Write example using Ant, in a terminal window,go to thetut-install/javaeetutorial5/examples/stax/readnwrite/ directory and type the following: ant run-readnwrite Writer ExampleLocated in thetut-install/javaeetutorial5/examples/stax/writer/ directory,CursorWriter.java demonstrates how to use the StAX cursorAPI to write an XML stream. Creating the Output FactoryThe first step is to create an instance ofXMLOutputFactory: XMLOutputFactory xof = XMLOutputFactory.newInstance(); Creating a Stream WriterThe next step is to create an instance ofXMLStreamWriter: XMLStreamWriter xtw = null; Writing the StreamThe final step is to write the XML stream. Note that thestream is flushed and closed after the finalEndDocument is written: xtw = xof.createXMLStreamWriter(new FileWriter(fileName));xtw.writeComment("all elements here are explicitly in the HTML namespace");xtw.writeStartDocument("utf-8","1.0");xtw.setPrefix("html", "http://www.w3.org/TR/REC-html40");xtw.writeStartElement("http://www.w3.org/TR/REC-html40","html");xtw.writeNamespace("html", "http://www.w3.org/TR/REC-html40");xtw.writeStartElement("http://www.w3.org/TR/REC-html40","head");xtw.writeStartElement("http://www.w3.org/TR/REC-html40","title");xtw.writeCharacters("Frobnostication");xtw.writeEndElement();xtw.writeEndElement();xtw.writeStartElement("http://www.w3.org/TR/REC-html40","body");xtw.writeStartElement("http://www.w3.org/TR/REC-html40","p");xtw.writeCharacters("Moved to");xtw.writeStartElement("http://www.w3.org/TR/REC-html40","a");xtw.writeAttribute("href","http://frob.com");xtw.writeCharacters("here");xtw.writeEndElement();xtw.writeEndElement();xtw.writeEndElement();xtw.writeEndElement();xtw.writeEndDocument();xtw.flush();xtw.close();Returning the OutputWhen you run the Writer example, theCursorWriter class is compiled, and theXML stream is parsed as events and written to a file nameddist/CursorWriter-Output: <!--all elements here are explicitly in the HTML namespace--><?xml version="1.0" encoding="utf-8"?><html:html xmlns:html="http://www.w3.org/TR/REC-html40"><html:head><html:title>Frobnostication</html:title></html:head><html:body><html:p>Moved to <html:a href="http://frob.com">here</html:a></html:p></html:body></html:html> In the actualdist/CursorWriter-Output file, this stream is written without any line breaks;the breaks have been added here to make the listing easier to read.In this example, as with the object stream in the Event example, thenamespace prefix is added to both the opening and closing HTML tags. Addingthis prefix is not required by the StAX specification, but it is goodpractice when the final scope of the output stream is not definitively known. Building and Running the Writer Example Using NetBeans IDEFollow these instructions to build and run the Writer example on yourApplication Server instance using NetBeans IDE.
Building and Running the Writer Example Using AntTo compile and run the Writer example using Ant, in a terminalwindow, go to thetut-install/javaeetutorial5/examples/stax/writer/ directory and type the following: ant run-writer Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |