KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > j2ee > blueprints > opc > webservicebroker > provider > BrokerTransformer


1 /*
2 * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * - Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * - Redistribution in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in
13 * the documentation and/or other materials provided with the
14 * distribution.
15 *
16 * Neither the name of Sun Microsystems, Inc. or the names of
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific prior written permission.
19 *
20 * This software is provided "AS IS," without a warranty of any
21 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
22 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
24 * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
25 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
26 * DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
27 * OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
28 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
29 * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
30 * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
31 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
32 *
33 * You acknowledge that Software is not designed, licensed or intended
34 * for use in the design, construction, operation or maintenance of
35 * any nuclear facility.
36 */

37
38 package com.sun.j2ee.blueprints.opc.webservicebroker.provider;
39
40 import java.io.*;
41 import java.util.*;
42 import org.w3c.dom.*;
43 import org.xml.sax.*;
44 import javax.xml.parsers.*;
45 import org.xml.sax.helpers.*;
46 import javax.xml.transform.*;
47 import javax.xml.transform.dom.*;
48 import javax.xml.transform.stream.*;
49
50 public class BrokerTransformer {
51     
52     public static final String JavaDoc ACTIVITY_INVOICE = "http://java.sun.com/blueprints/schemas/invoice-activity.xsd";
53     public static final String JavaDoc AIRLINE_INVOICE = "http://java.sun.com/blueprints/schemas/invoice-airline.xsd";
54     public static final String JavaDoc LODGING_INVOICE = "http://java.sun.com/blueprints/schemas/invoice-lodging.xsd";
55     public static final String JavaDoc XSL_CLASSPATH_BASE = "/com/sun/j2ee/blueprints/opc/webservicebroker/provider/";
56     
57     public static final String JavaDoc ACTIVITY_XSL = "invoice-activity.xsl";
58     public static final String JavaDoc AIRLINE_XSL = "invoice-airline.xsl";
59     public static final String JavaDoc LODGING_XSL = "invoice-lodging.xsl";
60
61     
62     private String JavaDoc transformedDoc = null;
63     private ByteArrayOutputStream bos = null;
64     private CharArrayWriter caw = null;
65     private SAXParser parser = null;
66     private HashMap transformers = null;
67     private TransformerFactory transformerFactory = null;
68     
69     /**
70      * The InputSource provided to this class needs to be read
71      * 2 times. We need to read the source to determine what document
72      * transformation needs to be perfomed (e.g. which style sheet
73      * to apply) and then we need to transform the actuall document.
74      * In order to do this we coppy the InputSource to a ByteArrayOutputStream
75      * so that we can create a new InputSource whenever we need to do something
76      * with the doucment.
77      */

78     
79     public BrokerTransformer() {
80         SAXParserFactory sparserFactory = SAXParserFactory.newInstance();
81          try {
82             sparserFactory.setValidating(true);
83             sparserFactory.setNamespaceAware(true);
84             parser = sparserFactory.newSAXParser();
85             // create Transfromers
86
addTransformer(ACTIVITY_XSL);
87             addTransformer(AIRLINE_XSL);
88             addTransformer(LODGING_XSL);
89         } catch (Exception JavaDoc ex) {
90            System.err.println("BrokerTransformer initizalization error: " + ex);
91         }
92     }
93     
94     private void addTransformer(String JavaDoc name) {
95         if (transformers == null) transformers = new HashMap();
96         if (transformerFactory == null) {
97                transformerFactory = TransformerFactory.newInstance();
98         }
99         StreamSource tranformerXSL =
100                     new StreamSource(getClass().getResourceAsStream(
101                                    XSL_CLASSPATH_BASE + name));
102         try {
103             Transformer tempTransfomer =
104                    transformerFactory.newTransformer(tranformerXSL);
105                     transformers.put(name, tempTransfomer);
106         } catch (TransformerConfigurationException fcx) {}
107
108     }
109     
110     private void init(InputSource in) {
111         try {
112             transformedDoc = null;
113             caw = new CharArrayWriter();
114             Reader reader = in.getCharacterStream();
115             // copy InputSource to CharArrayWriter the so we can re-create the InputSource
116
caw = new CharArrayWriter();
117             long total =0;
118             char [] buff = new char[1024];
119             while (true) {
120                 int read = reader.read(buff,0,buff.length);
121                 total += read;
122                 if (read <=0) break;
123                 caw.write(buff,0, read);
124             }
125             caw.close();
126             reader.close();
127         } catch (java.io.IOException JavaDoc iox) {
128             iox.printStackTrace();
129         }
130     }
131     
132     public String JavaDoc transform(InputSource is) {
133         // Make a local copy of the InputSource so we can use it twice
134
init(is);
135         try {
136             // find out the document type and based on that apply the correct
137
// transformation
138
parser.parse(new InputSource(new CharArrayReader(caw.toCharArray())),
139                         new DefaultHandler() {
140                                  private boolean foundFirst = false;
141                                 public void startElement(String JavaDoc namespace,
142                                                               String JavaDoc name,
143                                                               String JavaDoc qName,
144                                                               Attributes attrs) {
145                                    if (!foundFirst) {
146                                       if ( name.equals("Invoice") ) {
147                                         String JavaDoc schemaLocation = attrs.getValue("xsi:schemaLocation");
148                                         if (schemaLocation.endsWith( AIRLINE_INVOICE)) {
149                                             doXSLTTransformation((Transformer)transformers.get(AIRLINE_XSL));
150                                         } else if (schemaLocation.endsWith( ACTIVITY_INVOICE)) {
151                                             doXSLTTransformation((Transformer)transformers.get(ACTIVITY_XSL));
152                                         } else if (schemaLocation.endsWith( LODGING_INVOICE)) {
153                                             doXSLTTransformation((Transformer)transformers.get(LODGING_XSL));
154                                         }
155                                 }
156                          }
157                     }
158             });
159         } catch (org.xml.sax.SAXException JavaDoc ex) {
160             System.err.println("BrokerTransformer error: " + ex);
161         } catch (IOException iox) {
162             System.err.println("BrokerTransformer error: " + iox);
163         }
164         return transformedDoc;
165     }
166     
167     private void doXSLTTransformation (Transformer transformer) {
168         StreamSource in = new StreamSource(new CharArrayReader(caw.toCharArray()));
169         ByteArrayOutputStream bos = new ByteArrayOutputStream();
170         StreamResult result = new StreamResult(new ByteArrayOutputStream());
171           try {
172             if (transformer != null) {
173                 transformer.transform(in,result);
174                 String JavaDoc enc = transformer.getOutputProperty(OutputKeys.ENCODING);
175                  transformedDoc =
176                      ((ByteArrayOutputStream)result.getOutputStream()).toString(enc);
177             } else {
178                 System.err.println("BrokerTransformer error: Transformer not set");
179             }
180         } catch (Exception JavaDoc ex) {
181             ex.printStackTrace();
182         }
183     }
184 }
185
Popular Tags