KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > spi > xml > cookies > TransformableSupport


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19 package org.netbeans.spi.xml.cookies;
20
21 import java.io.IOException JavaDoc;
22 import java.io.PrintWriter JavaDoc;
23 import java.io.StringWriter JavaDoc;
24 import java.net.URL JavaDoc;
25 import java.security.ProtectionDomain JavaDoc;
26 import java.security.CodeSource JavaDoc;
27
28 import org.xml.sax.EntityResolver JavaDoc;
29 import org.xml.sax.XMLReader JavaDoc;
30 import org.xml.sax.InputSource JavaDoc;
31 import org.xml.sax.SAXException JavaDoc;
32 import org.xml.sax.SAXParseException JavaDoc;
33 import org.xml.sax.SAXNotRecognizedException JavaDoc;
34 import org.xml.sax.SAXNotSupportedException JavaDoc;
35 import javax.xml.parsers.SAXParser JavaDoc;
36 import javax.xml.parsers.SAXParserFactory JavaDoc;
37 import javax.xml.parsers.ParserConfigurationException JavaDoc;
38 import javax.xml.transform.TransformerFactory JavaDoc;
39 import javax.xml.transform.Transformer JavaDoc;
40 import javax.xml.transform.Source JavaDoc;
41 import javax.xml.transform.Result JavaDoc;
42 import javax.xml.transform.ErrorListener JavaDoc;
43 import javax.xml.transform.TransformerException JavaDoc;
44 import javax.xml.transform.TransformerConfigurationException JavaDoc;
45 import javax.xml.transform.URIResolver JavaDoc;
46 import javax.xml.transform.sax.SAXSource JavaDoc;
47 import javax.xml.transform.stream.StreamSource JavaDoc;
48
49 import org.openide.filesystems.FileObject;
50
51 import org.netbeans.api.xml.cookies.*;
52 import org.netbeans.api.xml.services.UserCatalog;
53
54 /**
55  * Perform Transform action on XML document.
56  * Default implementation of {@link TransformableCookie} cookie.
57  *
58  * @author Libor Kramolis
59  */

60 public final class TransformableSupport implements TransformableCookie {
61
62     // associated source
63
private final Source JavaDoc source;
64     /** cached TransformerFactory instance. */
65     private static TransformerFactory JavaDoc transformerFactory;
66     
67     
68     /**
69      * Create new TransformableSupport for given data object.
70      * @param source Supported <code>Source</code>.
71      */

72     public TransformableSupport (Source JavaDoc source) {
73         if (source == null) throw new NullPointerException JavaDoc();
74         this.source = source;
75     }
76
77     /**
78      * Transform this object by XSL Transformation.
79      *
80      * @param transformSource source of transformation.
81      * @param outputResult result of transformation.
82      * @param notifier optional listener (<code>null</code> allowed)
83      * giving judgement details.
84      * @throws TransformerException if an unrecoverable error occurs during the course of the transformation
85      */

86     public void transform (Source JavaDoc transformSource, Result JavaDoc outputResult, CookieObserver notifier) throws TransformerException JavaDoc {
87         try {
88             if ( Util.THIS.isLoggable() ) /* then */ {
89                 Util.THIS.debug ("TransformableSupport.transform");
90                 Util.THIS.debug (" transformSource = " + transformSource.getSystemId());
91                 Util.THIS.debug (" outputResult = " + outputResult.getSystemId());
92             }
93
94             
95             Source JavaDoc xmlSource = source;
96
97             if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug (" xmlSource = " + xmlSource.getSystemId());
98
99             // prepare transformer == parse stylesheet, errors may occur
100
Transformer JavaDoc transformer = newTransformer (transformSource);
101             
102             // transform
103
if (notifier != null) {
104
105                 // inform user about used implementation
106

107                 ProtectionDomain JavaDoc domain = transformer.getClass().getProtectionDomain();
108                 CodeSource JavaDoc codeSource = domain.getCodeSource();
109                 if (codeSource == null) {
110                     notifier.receive(new CookieMessage(Util.THIS.getString("BK000", transformer.getClass().getName())));
111                 } else {
112                     URL JavaDoc location = codeSource.getLocation();
113                     notifier.receive(new CookieMessage(Util.THIS.getString("BK001", location, transformer.getClass().getName())));
114                 }
115
116                 Proxy proxy = new Proxy (notifier);
117                 transformer.setErrorListener (proxy);
118             }
119             transformer.transform (xmlSource, outputResult);
120             
121         } catch (Exception JavaDoc exc) { // TransformerException, ParserConfigurationException, SAXException, FileStateInvalidException
122
if ( Util.THIS.isLoggable() ) /* then */ {
123                 Util.THIS.debug (" EXCEPTION during transformation: " + exc.getClass().getName(), exc);
124                 Util.THIS.debug (" exception's message = " + exc.getLocalizedMessage());
125
126                 Throwable JavaDoc tempExc = unwrapException (exc);
127                 Util.THIS.debug (" wrapped exception = " + tempExc.getLocalizedMessage());
128             }
129
130             TransformerException JavaDoc transExcept = null;
131             Object JavaDoc detail = null;
132             
133             if ( exc instanceof TransformerException JavaDoc ) {
134                 transExcept = (TransformerException JavaDoc)exc;
135                 if ( ( notifier != null ) &&
136                      ( exc instanceof TransformerConfigurationException JavaDoc ) ) {
137                     detail = new DefaultXMLProcessorDetail (transExcept);
138                 }
139             } else if ( exc instanceof SAXParseException JavaDoc ) {
140                 transExcept = new TransformerException JavaDoc (exc);
141                 if ( notifier != null ) {
142                     detail = new DefaultXMLProcessorDetail ((SAXParseException JavaDoc)exc);
143                 }
144             } else {
145                 transExcept = new TransformerException JavaDoc (exc);
146                 if ( notifier != null ) {
147                     detail = new DefaultXMLProcessorDetail (transExcept);
148                 }
149             }
150
151             if ( ( notifier != null ) &&
152                  ( detail != null ) ) {
153                 CookieMessage message = new CookieMessage
154                     (message(exc),
155                      CookieMessage.FATAL_ERROR_LEVEL,
156                      detail);
157                 notifier.receive (message);
158             }
159
160             if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug ("--> throw transExcept: " + transExcept);
161
162             throw transExcept;
163         } // catch (Exception exc)
164
}
165
166
167     //
168
// utils
169
//
170

171     private static Throwable JavaDoc unwrapException (Throwable JavaDoc exc) {
172         Throwable JavaDoc wrapped = null;
173         if (exc instanceof TransformerException JavaDoc) {
174             wrapped = ((TransformerException JavaDoc) exc).getException();
175         } else if (exc instanceof SAXException JavaDoc) {
176             wrapped = ((SAXException JavaDoc) exc).getException();
177         } else {
178             return exc;
179         }
180
181         if ( wrapped == null ) {
182             return exc;
183         }
184
185         return unwrapException (wrapped);
186     }
187
188     private static URIResolver JavaDoc getURIResolver () {
189         UserCatalog catalog = UserCatalog.getDefault();
190         URIResolver JavaDoc res = (catalog == null ? null : catalog.getURIResolver());
191         return res;
192     }
193
194     private static TransformerFactory JavaDoc getTransformerFactory () {
195         if ( transformerFactory == null ) {
196             transformerFactory = TransformerFactory.newInstance();
197             transformerFactory.setURIResolver (getURIResolver()); //!!! maybe that it should be set every call if UsersCatalog instances are dynamic
198
}
199         return transformerFactory;
200     }
201
202
203     private static Transformer JavaDoc newTransformer (Source JavaDoc xsl) throws TransformerConfigurationException JavaDoc {
204         return getTransformerFactory().newTransformer (xsl);
205     }
206
207     /**
208      * Extract message from exception or use exception name.
209      */

210     private static String JavaDoc message(Throwable JavaDoc t) {
211         String JavaDoc msg = t.getLocalizedMessage();
212         return (msg!=null ? msg : new ExceptionWriter(t).toString());
213     }
214
215     /**
216      * Print first four exception lines.
217      */

218     private static class ExceptionWriter extends PrintWriter JavaDoc {
219         private int counter = 4;
220         private Throwable JavaDoc t;
221          
222         public ExceptionWriter(Throwable JavaDoc t) {
223             super(new StringWriter JavaDoc());
224             this.t = t;
225         }
226         
227         public void println(String JavaDoc s) {
228             if (counter-- > 0) super.println(s);
229         }
230
231         public void println(Object JavaDoc o) {
232             if (counter-- > 0) super.println(o);
233         }
234         
235         public String JavaDoc toString() {
236             t.printStackTrace(this);
237             flush();
238             return ((StringWriter JavaDoc)out).getBuffer().toString();
239         }
240     }
241
242     //
243
// class Proxy
244
//
245

246     private static class Proxy implements ErrorListener JavaDoc {
247         
248         private final CookieObserver peer;
249         
250         public Proxy (CookieObserver peer) {
251             if (peer == null) {
252                 throw new NullPointerException JavaDoc();
253             }
254             this.peer = peer;
255         }
256         
257         public void error (TransformerException JavaDoc tex) throws TransformerException JavaDoc {
258             report (CookieMessage.ERROR_LEVEL, tex);
259         }
260         
261         public void fatalError (TransformerException JavaDoc tex) throws TransformerException JavaDoc {
262             report (CookieMessage.FATAL_ERROR_LEVEL, tex);
263
264             throw tex;
265         }
266         
267
268         public void warning (TransformerException JavaDoc tex) throws TransformerException JavaDoc {
269             report (CookieMessage.WARNING_LEVEL, tex);
270         }
271
272         private void report (int level, TransformerException JavaDoc tex) throws TransformerException JavaDoc {
273             if ( Util.THIS.isLoggable() ) /* then */ {
274                 Util.THIS.debug ("[TransformableSupport::Proxy]: report [" + level + "]: ", tex);
275                 Util.THIS.debug (" exception's message = " + tex.getLocalizedMessage());
276
277                 Throwable JavaDoc tempExc = unwrapException (tex);
278                 Util.THIS.debug (" wrapped exception = " + tempExc.getLocalizedMessage());
279             }
280
281             Throwable JavaDoc unwrappedExc = unwrapException (tex);
282             CookieMessage message = new CookieMessage (
283                 message(unwrappedExc),
284                 level,
285                 new DefaultXMLProcessorDetail (tex)
286             );
287
288             peer.receive (message);
289         }
290         
291     } // class Proxy
292

293 }
294
Popular Tags