View Javadoc
1   /*
2    * reserved comment block
3    * DO NOT REMOVE OR ALTER!
4    */
5   /*
6    * Copyright 2001-2004 The Apache Software Foundation.
7    *
8    * Licensed under the Apache License, Version 2.0 (the "License");
9    * you may not use this file except in compliance with the License.
10   * You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  /*
21   * $Id: TemplatesImpl.java,v 1.8 2007/03/26 20:12:27 spericas Exp $
22   */
23  
24  package com.sun.org.apache.xalan.internal.xsltc.trax;
25  
26  import com.sun.org.apache.xalan.internal.XalanConstants;
27  import java.io.IOException;
28  import java.io.ObjectInputStream;
29  import java.io.ObjectOutputStream;
30  import java.io.Serializable;
31  import java.util.Properties;
32  import java.security.AccessController;
33  import java.security.PrivilegedAction;
34  
35  import javax.xml.XMLConstants;
36  import javax.xml.transform.Templates;
37  import javax.xml.transform.Transformer;
38  import javax.xml.transform.TransformerConfigurationException;
39  import javax.xml.transform.URIResolver;
40  
41  import com.sun.org.apache.xalan.internal.xsltc.DOM;
42  import com.sun.org.apache.xalan.internal.xsltc.Translet;
43  import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
44  import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet;
45  import com.sun.org.apache.xalan.internal.xsltc.runtime.Hashtable;
46  import com.sun.org.apache.xalan.internal.utils.ObjectFactory;
47  import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
48  
49  /**
50   * @author Morten Jorgensen
51   * @author G. Todd Millerj
52   * @author Jochen Cordes <Jochen.Cordes@t-online.de>
53   * @author Santiago Pericas-Geertsen
54   */
55  public final class TemplatesImpl implements Templates, Serializable {
56      static final long serialVersionUID = 673094361519270707L;
57      public final static String DESERIALIZE_TRANSLET = "jdk.xml.enableTemplatesImplDeserialization";
58  
59      /**
60       * Name of the superclass of all translets. This is needed to
61       * determine which, among all classes comprising a translet,
62       * is the main one.
63       */
64      private static String ABSTRACT_TRANSLET
65          = "com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet";
66  
67      /**
68       * Name of the main class or default name if unknown.
69       */
70      private String _name = null;
71  
72      /**
73       * Contains the actual class definition for the translet class and
74       * any auxiliary classes.
75       */
76      private byte[][] _bytecodes = null;
77  
78      /**
79       * Contains the translet class definition(s). These are created when
80       * this Templates is created or when it is read back from disk.
81       */
82      private Class[] _class = null;
83  
84      /**
85       * The index of the main translet class in the arrays _class[] and
86       * _bytecodes.
87       */
88      private int _transletIndex = -1;
89  
90      /**
91       * Contains the list of auxiliary class definitions.
92       */
93      private Hashtable _auxClasses = null;
94  
95      /**
96       * Output properties of this translet.
97       */
98      private Properties _outputProperties;
99  
100     /**
101      * Number of spaces to add for output indentation.
102      */
103     private int _indentNumber;
104 
105     /**
106      * This URIResolver is passed to all Transformers.
107      * Declaring it transient to fix bug 22438
108      */
109     private transient URIResolver _uriResolver = null;
110 
111     /**
112      * Cache the DTM for the stylesheet in a thread local variable,
113      * which is used by the document('') function.
114      * Use ThreadLocal because a DTM cannot be shared between
115      * multiple threads.
116      * Declaring it transient to fix bug 22438
117      */
118     private transient ThreadLocal _sdom = new ThreadLocal();
119 
120     /**
121      * A reference to the transformer factory that this templates
122      * object belongs to.
123      */
124     private transient TransformerFactoryImpl _tfactory = null;
125 
126     private boolean _useServicesMechanism;
127 
128     /**
129      * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element.
130      */
131     private String _accessExternalStylesheet = XalanConstants.EXTERNAL_ACCESS_DEFAULT;
132 
133     static final class TransletClassLoader extends ClassLoader {
134         TransletClassLoader(ClassLoader parent) {
135             super(parent);
136         }
137 
138         /**
139          * Access to final protected superclass member from outer class.
140          */
141         Class defineClass(final byte[] b) {
142             return defineClass(null, b, 0, b.length);
143         }
144     }
145 
146 
147     /**
148      * Create an XSLTC template object from the bytecodes.
149      * The bytecodes for the translet and auxiliary classes, plus the name of
150      * the main translet class, must be supplied.
151      */
152     protected TemplatesImpl(byte[][] bytecodes, String transletName,
153         Properties outputProperties, int indentNumber,
154         TransformerFactoryImpl tfactory)
155     {
156         _bytecodes = bytecodes;
157         init(transletName, outputProperties, indentNumber, tfactory);
158     }
159 
160     /**
161      * Create an XSLTC template object from the translet class definition(s).
162      */
163     protected TemplatesImpl(Class[] transletClasses, String transletName,
164         Properties outputProperties, int indentNumber,
165         TransformerFactoryImpl tfactory)
166     {
167         _class     = transletClasses;
168         _transletIndex = 0;
169         init(transletName, outputProperties, indentNumber, tfactory);
170     }
171 
172     private void init(String transletName,
173         Properties outputProperties, int indentNumber,
174         TransformerFactoryImpl tfactory) {
175         _name      = transletName;
176         _outputProperties = outputProperties;
177         _indentNumber = indentNumber;
178         _tfactory = tfactory;
179         _useServicesMechanism = tfactory.useServicesMechnism();
180         _accessExternalStylesheet = (String) tfactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
181     }
182     /**
183      * Need for de-serialization, see readObject().
184      */
185     public TemplatesImpl() { }
186 
187     /**
188      *  Overrides the default readObject implementation since we decided
189      *  it would be cleaner not to serialize the entire tranformer
190      *  factory.  [ ref bugzilla 12317 ]
191      *  We need to check if the user defined class for URIResolver also
192      *  implemented Serializable
193      *  if yes then we need to deserialize the URIResolver
194      *  Fix for bugzilla bug 22438
195      */
196     private void  readObject(ObjectInputStream is)
197       throws IOException, ClassNotFoundException
198     {
199         SecurityManager security = System.getSecurityManager();
200         if (security != null){
201             String temp = SecuritySupport.getSystemProperty(DESERIALIZE_TRANSLET);
202             if (temp == null || !(temp.length()==0 || temp.equalsIgnoreCase("true"))) {
203                 ErrorMsg err = new ErrorMsg(ErrorMsg.DESERIALIZE_TRANSLET_ERR);
204                 throw new UnsupportedOperationException(err.toString());
205             }
206         }
207 
208         is.defaultReadObject();
209         if (is.readBoolean()) {
210             _uriResolver = (URIResolver) is.readObject();
211         }
212 
213         _tfactory = new TransformerFactoryImpl();
214     }
215 
216 
217     /**
218      *  This is to fix bugzilla bug 22438
219      *  If the user defined class implements URIResolver and Serializable
220      *  then we want it to get serialized
221      */
222     private void writeObject(ObjectOutputStream os)
223         throws IOException, ClassNotFoundException {
224         os.defaultWriteObject();
225         if (_uriResolver instanceof Serializable) {
226             os.writeBoolean(true);
227             os.writeObject((Serializable) _uriResolver);
228         }
229         else {
230             os.writeBoolean(false);
231         }
232     }
233 
234     /**
235      * Return the state of the services mechanism feature.
236      */
237     public boolean useServicesMechnism() {
238         return _useServicesMechanism;
239     }
240 
241      /**
242      * Store URIResolver needed for Transformers.
243      */
244     public synchronized void setURIResolver(URIResolver resolver) {
245         _uriResolver = resolver;
246     }
247 
248     /**
249      * The TransformerFactory must pass us the translet bytecodes using this
250      * method before we can create any translet instances
251      *
252      * Note: This method is private for security reasons. See
253      * CR 6537898. When merging with Apache, we must ensure
254      * that the privateness of this method is maintained (that
255      * is why it wasn't removed).
256      */
257     private synchronized void setTransletBytecodes(byte[][] bytecodes) {
258         _bytecodes = bytecodes;
259     }
260 
261     /**
262      * Returns the translet bytecodes stored in this template
263      *
264      * Note: This method is private for security reasons. See
265      * CR 6537898. When merging with Apache, we must ensure
266      * that the privateness of this method is maintained (that
267      * is why it wasn't removed).
268      */
269     private synchronized byte[][] getTransletBytecodes() {
270         return _bytecodes;
271     }
272 
273     /**
274      * Returns the translet bytecodes stored in this template
275      *
276      * Note: This method is private for security reasons. See
277      * CR 6537898. When merging with Apache, we must ensure
278      * that the privateness of this method is maintained (that
279      * is why it wasn't removed).
280      */
281     private synchronized Class[] getTransletClasses() {
282         try {
283             if (_class == null) defineTransletClasses();
284         }
285         catch (TransformerConfigurationException e) {
286             // Falls through
287         }
288         return _class;
289     }
290 
291     /**
292      * Returns the index of the main class in array of bytecodes
293      */
294     public synchronized int getTransletIndex() {
295         try {
296             if (_class == null) defineTransletClasses();
297         }
298         catch (TransformerConfigurationException e) {
299             // Falls through
300         }
301         return _transletIndex;
302     }
303 
304     /**
305      * The TransformerFactory should call this method to set the translet name
306      */
307     protected synchronized void setTransletName(String name) {
308         _name = name;
309     }
310 
311     /**
312      * Returns the name of the main translet class stored in this template
313      */
314     protected synchronized String getTransletName() {
315         return _name;
316     }
317 
318     /**
319      * Defines the translet class and auxiliary classes.
320      * Returns a reference to the Class object that defines the main class
321      */
322     private void defineTransletClasses()
323         throws TransformerConfigurationException {
324 
325         if (_bytecodes == null) {
326             ErrorMsg err = new ErrorMsg(ErrorMsg.NO_TRANSLET_CLASS_ERR);
327             throw new TransformerConfigurationException(err.toString());
328         }
329 
330         TransletClassLoader loader = (TransletClassLoader)
331             AccessController.doPrivileged(new PrivilegedAction() {
332                 public Object run() {
333                     return new TransletClassLoader(ObjectFactory.findClassLoader());
334                 }
335             });
336 
337         try {
338             final int classCount = _bytecodes.length;
339             _class = new Class[classCount];
340 
341             if (classCount > 1) {
342                 _auxClasses = new Hashtable();
343             }
344 
345             for (int i = 0; i < classCount; i++) {
346                 _class[i] = loader.defineClass(_bytecodes[i]);
347                 final Class superClass = _class[i].getSuperclass();
348 
349                 // Check if this is the main class
350                 if (superClass.getName().equals(ABSTRACT_TRANSLET)) {
351                     _transletIndex = i;
352                 }
353                 else {
354                     _auxClasses.put(_class[i].getName(), _class[i]);
355                 }
356             }
357 
358             if (_transletIndex < 0) {
359                 ErrorMsg err= new ErrorMsg(ErrorMsg.NO_MAIN_TRANSLET_ERR, _name);
360                 throw new TransformerConfigurationException(err.toString());
361             }
362         }
363         catch (ClassFormatError e) {
364             ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_CLASS_ERR, _name);
365             throw new TransformerConfigurationException(err.toString());
366         }
367         catch (LinkageError e) {
368             ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name);
369             throw new TransformerConfigurationException(err.toString());
370         }
371     }
372 
373     /**
374      * This method generates an instance of the translet class that is
375      * wrapped inside this Template. The translet instance will later
376      * be wrapped inside a Transformer object.
377      */
378     private Translet getTransletInstance()
379         throws TransformerConfigurationException {
380         try {
381             if (_name == null) return null;
382 
383             if (_class == null) defineTransletClasses();
384 
385             // The translet needs to keep a reference to all its auxiliary
386             // class to prevent the GC from collecting them
387             AbstractTranslet translet = (AbstractTranslet) _class[_transletIndex].newInstance();
388             translet.postInitialization();
389             translet.setTemplates(this);
390             translet.setServicesMechnism(_useServicesMechanism);
391             translet.setAllowedProtocols(_accessExternalStylesheet);
392             if (_auxClasses != null) {
393                 translet.setAuxiliaryClasses(_auxClasses);
394             }
395 
396             return translet;
397         }
398         catch (InstantiationException e) {
399             ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name);
400             throw new TransformerConfigurationException(err.toString());
401         }
402         catch (IllegalAccessException e) {
403             ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name);
404             throw new TransformerConfigurationException(err.toString());
405         }
406     }
407 
408     /**
409      * Implements JAXP's Templates.newTransformer()
410      *
411      * @throws TransformerConfigurationException
412      */
413     public synchronized Transformer newTransformer()
414         throws TransformerConfigurationException
415     {
416         TransformerImpl transformer;
417 
418         transformer = new TransformerImpl(getTransletInstance(), _outputProperties,
419             _indentNumber, _tfactory);
420 
421         if (_uriResolver != null) {
422             transformer.setURIResolver(_uriResolver);
423         }
424 
425         if (_tfactory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) {
426             transformer.setSecureProcessing(true);
427         }
428         return transformer;
429     }
430 
431     /**
432      * Implements JAXP's Templates.getOutputProperties(). We need to
433      * instanciate a translet to get the output settings, so
434      * we might as well just instanciate a Transformer and use its
435      * implementation of this method.
436      */
437     public synchronized Properties getOutputProperties() {
438         try {
439             return newTransformer().getOutputProperties();
440         }
441         catch (TransformerConfigurationException e) {
442             return null;
443         }
444     }
445 
446     /**
447      * Return the thread local copy of the stylesheet DOM.
448      */
449     public DOM getStylesheetDOM() {
450         return (DOM)_sdom.get();
451     }
452 
453     /**
454      * Set the thread local copy of the stylesheet DOM.
455      */
456     public void setStylesheetDOM(DOM sdom) {
457         _sdom.set(sdom);
458     }
459 }