Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 99 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
99
Dung lượng
1,59 MB
Nội dung
357 Chapter 16 ✦ Xalan } catch (TransformerException e) { System.err.println(“Error: “ + e); } } public void processingInstruction( String target, String instruction ){ eventString +=”ProcessingInstruction() Event - Target:” + target + “ Instruction:” + instruction + “\r\n”; } public void startDocument() { eventString +=”StartDocument() Event \r\n”; } public void startPrefixMapping( String prefix, String uri ) { eventString +=”startPrefixMapping() Event - Prefix:” + prefix + “ URI:” + uri + “\r\n”; } public void startElement(String uri, String localname, String qname, Attributes attributes){ eventString += “startElement() Event: “ + localname + “\r\n”; for (int i = 0; i < attributes.getLength(); i++) { eventString += “Attribute Name: “+ attributes.getLocalName(i)+”\r\n”; eventString += “Attribute Value: “ + attributes.getValue(i)+”\r\n”; } } public void endPrefixMapping( String prefix ) { eventString += “endPrefixMapping() Event - Prefix:” + prefix + “\r\n”; } public void characters(char[] cdata, int start, int length){ String textvalue = new String(cdata, start, length); if (!textvalue.trim().equals(“”)){ eventString += “Text: “+ textvalue + “\r\n”; } } public void ignorableWhitespace( char[] cdata, int start, int end ) { eventString += “ignorableWhitespace() Event \r\n”; } public void endElement(String uri, String local, String qName){ eventString += “endElement() Event: “ + local + “\r\n”; } Continued g538292 ch16.qxd 8/18/03 8:44 AM Page 357 358 Part III ✦ XML Web Applications Using J2EE Listing 16-6 (continued) public void skippedEntity( String name ) { eventString += “skippedEntity() Event(): “ + name; } public void endDocument(){ eventString += “endDocument() Event”; System.out.println(eventString); } } For the SAX example, a new instance of TransformerFactory is created. Because the transformation code is dealing with SAX for this example, it needs to contain a ContentHandler, which will catch SAX events. To do this, the code explicitly casts the TransformerFactory to an instance of SAXTransformerFactory. The ContentHandler that is defined in the SAXResult cannot be null, so the TransformerHandler lets us create a ContentHandler that the SAXResult can use in the transformation. Next, the transformation is processed, passing data to the SAXResult. The ContentHandler that is contained in the SAXResult object reacts to the transformation just as it would an XMLReader class, and passes through the document, catching events as it encounters them in the SAXResult object. TransformerFactory tFactory = TransformerFactory.newInstance(); String XMLSource = “AmazonMacbethSpanish.xml”; String XSLSource = “XMLtoQuotes.xsl”; SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory); TransformerHandler tHandler = saxTFactory.newTransformerHandler(new StreamSource(“XMLtoQuotes.xsl”)); SAXResult saxResult = new SAXResult(tHandler); Transformer transformer = tFactory.newTransformer(new StreamSource(XSLSource)); transformer.transform(new StreamSource(XMLSource), saxResult); The rest of the classes that gather information about SAX events are the same as the classes that were reviewed in Listing 15-3 in Chapter 15. g538292 ch16.qxd 8/18/03 8:44 AM Page 358 359 Chapter 16 ✦ Xalan Summary In this chapter, you were introduced to Xalan: ✦ An introduction to Apache Xalan ✦ How to download and install Xalan ✦ Transforming XML documents in J2EE ✦ Passing transformed data to the screen ✦ Passing transformed data to the file system ✦ Using the stylesheet reference in XML documents for transformation ✦ Transforming XML documents to DOM objects ✦ Transforming XML documents to SAX objects In the next chapter, I get into the XML APIs that are included as part of the Sun Java Web Services Developer Pack (WSDP). I’ve actually included Java API for XML Processing (JAXP) code in this chapter, but haven’t called your attention to it because I wanted to focus on Xalan. Sun’s Java Web Services Developer Pack forms the basis of many tools and code libraries, and I’ll explain each component and illustrate the highlights with examples. ✦✦✦ g538292 ch16.qxd 8/18/03 8:44 AM Page 359 g538292 ch16.qxd 8/18/03 8:44 AM Page 360 XML APIs from Sun S un’s Java Web Services Developer Pack (Java WSDP) is a great tool for J2EE developers working with any XML applications, not just Web services. Most of the APIs in the Web Services Developer Pack started as XML JCP (Java Community Process) API initiatives. JCPS are projects created by Sun to standardize popular and often used interfaces for common tasks in J2EE. The APIs that were developed as a result of the XML JCPS were originally rolled into the Sun Java XML Pack. The XML Pack has not been updated since summer 2002, but it can still be downloaded from http://java.sun.com/xml/downloads/javaxmlpack. html. The APIs in the Java XML Pack were then rolled into the Java Web Services Developer Pack in the fall of 2002. The Java Web Services Developer Pack contains several interface APIs for XML functionality from the Java XML Pack, and some new APIs specifically for Web Service Functions. In this chapter we’ll show examples of the Java API for XML Processing (JAXP), Java Architecture for XML Binding (JAXB), and the Java Server Pages Standard Tag Library (JSTL). We’ll dive into the details of each API and provide Java code examples (and JSP page examples for the JSTL). In addition, we’ll be using these APIs in examples in the rest of the J2EE XML parts of this book. We’ll also introduce you to the Web Service APIs in the Java Web Services Developer Pack. These are the Java API for XML Messaging (JAXM), the Java API for XML Registries (JAXR), Java WSDP Registry Server, Java API for XML-Based RPC (JAX- RPC), and the SOAP with Attachments API for Java (SAAJ). We cover the Web Service APIs in more detail and provide Web Service API code examples in Chapter 33. 17 17 CHAPTER ✦✦✦✦ In This Chapter Sun’s Java Web Services Developer Pack (WSDP) Developing with the Java API for XML Processing (JAXP) Java Architecture for XML Binding (JAXB) Java Server Pages Standard Tag Library (JSTL) Examples using JAXP, JAXB, and JSTL ✦✦✦✦ g538292 ch17.qxd 8/18/03 8:44 AM Page 361 362 Part III ✦ XML Web Applications Using J2EE About the Java Community Process The Java Community Process (JCP) is where all of Sun’s non-core Java specifica- tions are developed. The JCP process develops Java language specifications based on public input. The specification development process is very similar to the W3C process, with the exception that W3C Recommendations are language-neutral and JCP specifications are specific to Java. JCP Specifications begin life as Java Specification Requests (JSRs). JSRs are descriptions of proposed new and changed features that evolve into final specifications. More information on JSP proposals and JCP involvement can be found at http://www.jcp.org/en/participation/ overview. There are five development stages and one maintenance stage that a JSR goes through in its lifetime: ✦ Review: After a new JSR is submitted, it is posted on the Web. The first stage is a brief period when anyone can review and comment on a new JSR Web posting. The result of this process is a draft specification. ✦ Community Review: After the initial review is complete, members review and comment on the draft specification. A Java Community Process Member is a company, organization, or individual that has signed the Java Specification Participation Agreement (JSPA), an agreement between Sun Microsystems and the company, organization or individual under which par- ticipation in the Java Community Process is permitted. ✦ Public Review: After the Community review, the public can review and com- ment on the draft Specification. ✦ Final Draft Proposal: The Review, Community Review and Public Review pro- duce a draft Specification that is used to build a Reference Implementation (RI) and a Technology Compatibility Kit (TCK). A Reference Implementation is a “proof of concept” implementation of a Specification in Java, and a Technology Compatibility Kit contains development tools, documentation, and implementation tests to ensure compatibility with a specification. ✦ Final Release: Final Draft Proposals are approved by an Executive Committee (EC) EC members are nominated and elected by JCP members. A current listing of EC members can be found at http://www.jcp.org/en/ participation/committee. ✦ Maintenance Review: At the time that a Specification is approved, a Maintenance Lead is appointed to oversee ongoing maintenance of a specifi- cation. An e-mail address is published with the specification that JCP mem- bers and the public can send information about errata and request clarification, interpretation, and enhancements to the Specification. It’s up to the maintenance lead to decide if any further information or development requires a new version of the specification as part of the Maintenance Review process. g538292 ch17.qxd 8/18/03 8:44 AM Page 362 363 Chapter 17 ✦ XML APIs from Sun There are hundreds of JSRs currently at various stages of completion. A listing of JSRs by development stage can be found at http://www.jcp.org/en/jsr/ overview. Each JSR includes a reference implementation. In the Case of the Java Web Services Developer Pack, the Java APIs that have been developed as compo- nents in the pack are a result of the reference implementation. Some of the JSRs have their own specific and unique functionality. Other JSRs such as the Java API for XML Processing (JAXP) specification act as proxies between sup- ported tools such as parsers and transformation engines and are designed to shield developers from having to recode Java when a new version of a J2EE tool comes out. For example, a J2EE developer that has written a parsing interface to a DOM 1 parser could theoretically move to a DOM 2 or SAX parser with no change to their Java source code, changing the JAXP pluggable reference from DOM1 to any other JAXP-compliant parser could facilitate the move. Introduction to the Sun Java Web Services Developer Pack The Java Web Service Developer Pack (WSDP) is downloadable from Sun at http://java.sun.com/webservices/webservicespack.html. The current version of the WSDP is compatible with JDK 1.3.1 and higher. It is has been tested on Solaris 8 and 9, Windows 2000 Professional, Windows XP Professional, and RedHat Linux 7.2. Check the readme file for issues regarding configuration, compati- bility, and enhancements to your existing JDK environment. Outlined below are WSDP, the APIs, and their associated benefits. JAXP (Java API for XML Processing) The Java API for XML Processing (JAXP) supports processing of XML documents using DOM 1, 2, and some of DOM 3, SAX 1 and 2, and XSLT. JAXP enables applica- tions to change the processor that is used to parse and transform XML documents without changing the underlying source code for the application that is doing the parsing or transformation. JAXP also supports the W3C XML Schema 1.0 Recommendation and an XSLT compiler (XSLTC). JAXB (Java Architecture for XML Binding) JAXB automates mapping between XML documents and Java objects, making ele- ments and attributes classes, properties and methods by marshalling and unmar- shalling them in a customized XML document. g538292 ch17.qxd 8/18/03 8:44 AM Page 363 364 Part III ✦ XML Web Applications Using J2EE JAXM (Java API for XML Messaging) JAXM provides an Interface for SOAP messages, including SOAP with attachments. Because JAXM is based on XML, the messaging format can be changed to other message standards that support XML formats. JSTL (Java Server Pages Standard Tag Library) JSTL consists of four custom Java Server Page (JSP) tag libraries called the core, XML, I18N & Formatting and database access libraries. All are based on the JSP 1.2 API. The core JSP library supports basic HTM page generation features. The XML library contains support for XML functionality, such as transformations and pars- ing. The database access library contains support for database access functions, and the I18N & Formatting library contains functionality for internationalization and formatting of Web pages. JAX-RPC (Java API for XML-Based RPC) JAX-RPC provides an Interface for XML messages using an RPC transport, including, but not limited to, SOAP calls over RPC to Web Services. JAXR (Java API for XML Registries) JAXR provides an interface for XML registries, supporting UDDI and OASIS/U.N./ CEFACT ebXML Registry and Repository standards, among others. Java WSDP Registry Server The Java WSDP Registry Server implements Version 2 of the UDDI (Universal Description, Discovery and Integration) specification. It provides a registry that is compatible with JAXR (Java API for XML Registries). The Java WSDP Registry Server can be used as a standalone UDDI server and also as a testing tool for JAXR applications. SAAJ (SOAP with Attachments API for Java) SAAJ provides support for producing, sending, and receiving SOAP messages with attachments. Sun’s SAAJ library provides an interface to the features and capa- bilities described in the W3C SOAP 1.1 attachment note, which have not changed g538292 ch17.qxd 8/18/03 8:44 AM Page 364 365 Chapter 17 ✦ XML APIs from Sun much in their current form. The current W3C specification is the W3C SOAP 1.2 Attachment Feature, currently in the Working Draft stage of the W3C Recommen- dation process. The W3C SOAP 1.2 Attachment Feature Working Draft states that a SOAP message may include attachments directly in the W3C SOAP body structure. The SOAP body and header may contain only XML content. Non-XML data must be contained in an attachment under the SOAP body. This provides facilities for pro- viding binary information and non-XML data in a SOAP envelope. SOAP and SOAP attachments are covered in more detail in Chapter 23, “Web Service Concepts,” and Chapter 24, “SOAP.” Developing with JAXP (Java API for XML Processing) As mentioned in the introduction, the Java API for XML Processing (JAXP) supports processing of XML documents using DOM 1, 2, and some of DOM 3, SAX 1 and 2, and XSLT. If you’re using JDK 1.4 or higher, JAXP is included in the distribution of the JDK, and may be older than the Web Services Developer Pack (WSDP) version. To overwrite the JDK version of JAXP with the WSDP version of JAXP, copy the files in C:\<jwsdp install drive>\jaxp-1.2.2\lib\endorsed to <JAVA_HOME>\jre\lib\endorsed. To change the reference in the JDK to the WSDP version without overwriting the JDK JAXP distri- bution files, set the java.endorsed.dirs system property to C:\<jwsdp install drive>\jaxp-1.2.2\lib\endorsed. JAXP enables applications to change the processor that is used to parse and trans- form XML documents without changing the underlying source code for the applica- tion that is doing the parsing or transformation. To show you how this actually happens, let’s refer back to the first Xalan example in Chapter 16. I actually used JAXP code, which Xalan supports, to process the transformation. Listing 17-1 shows the code used to extract a subset of the XML document shown in Listing 16-1 using XSL transformation. The code reads through an XML document using SAX behind the scenes and transforms the data using the specified stylesheet. The code also instantiates TransformerFactory for the transformation, which is a JAXP class for integration with a transformation engine. By default in Xalan, the JAXP “pluggable” interface connects to the Xalan transfor- mation engine, and the Xerxes SAX parser to facilitate Xalan transformations. Note Cross- Reference g538292 ch17.qxd 8/18/03 8:44 AM Page 365 [...]... TransformerFactory.newInstance(); String XMLSource = “C:/jdk1.3.1_01/bin/XMLBookSource/XMLDocs/ AmazonMacbethSpanish .xml ; String XSLSource = “C:/jdk1.3.1_01/bin/XMLBookSource/XMLDocs/ XMLtoQuotes.xsl”; String ResultOutput = “C:/temp/ResultOutput .XML ; Transformer transformer = tFactory.newTransformer(new StreamSource(XSLSource)); transformer.transform(new StreamSource(XMLSource), new StreamResult(ResultOutput));... an xml: prefix of you get the following message when JAXB generates classes: “The prefix xml cannot be bound to any namespace other than its usual namespace; neither can the namespace for xml be bound to any prefix other than xml .” Listing 17-2: The JAXB Example W3C Schema AmazonMacbethSpanish.xsd < ?xml version=”1.0” encoding=”UTF-8”?> XML APIs from Sun Developing with JAXB (Java Architecture for XML Binding) JAXB automates mapping between XML documents and Java objects JAXB marshalling generates an XML document from a Java object that represents an XML document JAXB unmarshalling turns an XML document into a Java object JAXB relies on Schemas to specify marshalling and unmarshalling formats for XML documents You... schema and XML document references that used an xml: namespace prefix have been removed Tip JAXB 1.0 appears not to recognize xml: prefixes on attribute names such as xml: lang and others, even though they are well-formed and valid XML with correct namespace references Hopefully this is a JAXB 1.0 issue and will be fixed in future versions You will need to remove any schema references and XML document... 17-3 shows an example XML that validated to the schema in Listing 17-2 Listing 17-3: The Example XML Document AmazonMacbethSpanish .xml < ?xml version=”1.0” encoding=”ISO-8 859 -1”?> When the hurlyburly’s done, / When the battle’s lost and won. Chapter 17 ✦ XML APIs from Sun . TransformerFactory.newInstance(); String XMLSource = “C:/jdk1.3.1_01/bin/XMLBookSource/XMLDocs/ AmazonMacbethSpanish .xml ; String XSLSource = “C:/jdk1.3.1_01/bin/XMLBookSource/XMLDocs/ XMLtoQuotes.xsl”; String. the XML JCPS were originally rolled into the Sun Java XML Pack. The XML Pack has not been updated since summer 2002, but it can still be downloaded from http://java.sun.com /xml/ downloads/javaxmlpack. html events are the same as the classes that were reviewed in Listing 15- 3 in Chapter 15. g538292 ch16.qxd 8/18/03 8:44 AM Page 358 359 Chapter 16 ✦ Xalan Summary In this chapter, you were introduced