KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xalan > internal > xslt > Process


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package com.sun.org.apache.xalan.internal.xslt;
17
18 import java.io.FileOutputStream JavaDoc;
19 import java.io.FileWriter JavaDoc;
20 import java.io.PrintWriter JavaDoc;
21 import java.io.StringReader JavaDoc;
22 import java.util.Properties JavaDoc;
23 import java.util.ResourceBundle JavaDoc;
24 import java.util.Vector JavaDoc;
25
26 import javax.xml.parsers.DocumentBuilder JavaDoc;
27 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
28 import javax.xml.transform.OutputKeys JavaDoc;
29 import javax.xml.transform.Source JavaDoc;
30 import javax.xml.transform.Templates JavaDoc;
31 import javax.xml.transform.Transformer JavaDoc;
32 import javax.xml.transform.TransformerException JavaDoc;
33 import javax.xml.transform.TransformerFactory JavaDoc;
34 import javax.xml.transform.TransformerFactoryConfigurationError JavaDoc;
35 import javax.xml.transform.URIResolver JavaDoc;
36 import javax.xml.transform.dom.DOMResult JavaDoc;
37 import javax.xml.transform.dom.DOMSource JavaDoc;
38 import javax.xml.transform.sax.SAXResult JavaDoc;
39 import javax.xml.transform.sax.SAXSource JavaDoc;
40 import javax.xml.transform.sax.SAXTransformerFactory JavaDoc;
41 import javax.xml.transform.sax.TransformerHandler JavaDoc;
42 import javax.xml.transform.stream.StreamResult JavaDoc;
43 import javax.xml.transform.stream.StreamSource JavaDoc;
44
45 import com.sun.org.apache.xalan.internal.Version;
46 import com.sun.org.apache.xalan.internal.res.XSLMessages;
47 import com.sun.org.apache.xalan.internal.res.XSLTErrorResources;
48 import com.sun.org.apache.xml.internal.utils.DefaultErrorHandler;
49
50 import org.w3c.dom.Document JavaDoc;
51 import org.w3c.dom.Node JavaDoc;
52
53 import org.xml.sax.ContentHandler JavaDoc;
54 import org.xml.sax.EntityResolver JavaDoc;
55 import org.xml.sax.InputSource JavaDoc;
56 import org.xml.sax.XMLReader JavaDoc;
57 import org.xml.sax.helpers.XMLReaderFactory JavaDoc;
58
59 /**
60  * The main() method handles the Xalan command-line interface.
61  * @xsl.usage general
62  */

63 public class Process
64 {
65   /**
66    * Prints argument options.
67    *
68    * @param resbundle Resource bundle
69    */

70   protected static void printArgOptions(ResourceBundle JavaDoc resbundle)
71   {
72     System.out.println(resbundle.getString("xslProc_option")); //"xslproc options: ");
73
System.out.println("\n\t\t\t" + resbundle.getString("xslProc_common_options") + "\n");
74     System.out.println(resbundle.getString("optionXSLTC")); //" [-XSLTC (use XSLTC for transformation)]
75
System.out.println(resbundle.getString("optionIN")); //" [-IN inputXMLURL]");
76
System.out.println(resbundle.getString("optionXSL")); //" [-XSL XSLTransformationURL]");
77
System.out.println(resbundle.getString("optionOUT")); //" [-OUT outputFileName]");
78

79     // System.out.println(resbundle.getString("optionE")); //" [-E (Do not expand entity refs)]");
80
System.out.println(resbundle.getString("optionV")); //" [-V (Version info)]");
81

82     // System.out.println(resbundle.getString("optionVALIDATE")); //" [-VALIDATE (Set whether validation occurs. Validation is off by default.)]");
83
System.out.println(resbundle.getString("optionEDUMP")); //" [-EDUMP {optional filename} (Do stackdump on error.)]");
84
System.out.println(resbundle.getString("optionXML")); //" [-XML (Use XML formatter and add XML header.)]");
85
System.out.println(resbundle.getString("optionTEXT")); //" [-TEXT (Use simple Text formatter.)]");
86
System.out.println(resbundle.getString("optionHTML")); //" [-HTML (Use HTML formatter.)]");
87
System.out.println(resbundle.getString("optionPARAM")); //" [-PARAM name expression (Set a stylesheet parameter)]");
88

89     System.out.println(resbundle.getString("optionMEDIA"));
90     System.out.println(resbundle.getString("optionFLAVOR"));
91     System.out.println(resbundle.getString("optionDIAG"));
92     System.out.println(resbundle.getString("optionURIRESOLVER")); //" [-URIRESOLVER full class name (URIResolver to be used to resolve URIs)]");
93
System.out.println(resbundle.getString("optionENTITYRESOLVER")); //" [-ENTITYRESOLVER full class name (EntityResolver to be used to resolve entities)]");
94
waitForReturnKey(resbundle);
95     System.out.println(resbundle.getString("optionCONTENTHANDLER")); //" [-CONTENTHANDLER full class name (ContentHandler to be used to serialize output)]");
96

97     System.out.println("\n\t\t\t" + resbundle.getString("xslProc_xsltc_options") + "\n");
98     System.out.println(resbundle.getString("optionXO"));
99     System.out.println(resbundle.getString("optionXD"));
100     waitForReturnKey(resbundle);
101     System.out.println(resbundle.getString("optionXJ"));
102     System.out.println(resbundle.getString("optionXP"));
103     System.out.println(resbundle.getString("optionXN"));
104     System.out.println(resbundle.getString("optionXX"));
105     System.out.println(resbundle.getString("optionXT"));
106   }
107   
108   /**
109    * Command line interface to transform an XML document according to
110    * the instructions found in an XSL stylesheet.
111    * <p>The Process class provides basic functionality for
112    * performing transformations from the command line. To see a
113    * list of arguments supported, call with zero arguments.</p>
114    * <p>To set stylesheet parameters from the command line, use
115    * <code>-PARAM name expression</code>. If you want to set the
116    * parameter to a string value, simply pass the string value
117    * as-is, and it will be interpreted as a string. (Note: if
118    * the value has spaces in it, you may need to quote it depending
119    * on your shell environment).</p>
120    *
121    * @param argv Input parameters from command line
122    */

123   public static void _main(String JavaDoc argv[])
124   {
125     
126     boolean doStackDumpOnError = false;
127     boolean setQuietMode = false;
128     boolean doDiag = false;
129
130
131     /**
132      * The default diagnostic writer...
133      */

134     java.io.PrintWriter JavaDoc diagnosticsWriter = new PrintWriter JavaDoc(System.err, true);
135     java.io.PrintWriter JavaDoc dumpWriter = diagnosticsWriter;
136     ResourceBundle JavaDoc resbundle =
137       (XSLMessages.loadResourceBundle(
138         com.sun.org.apache.xml.internal.utils.res.XResourceBundle.ERROR_RESOURCES));
139     String JavaDoc flavor = "s2s";
140
141     if (argv.length < 1)
142     {
143       printArgOptions(resbundle);
144     }
145     else
146     {
147       // since xsltc is the default transformer
148
boolean useXSLTC = true;
149       for (int i = 0; i < argv.length; i++)
150       {
151         if ("-XSLTC".equalsIgnoreCase(argv[i]))
152         {
153           useXSLTC = true;
154         }
155       }
156         
157       TransformerFactory JavaDoc tfactory;
158       // Since xsltc is the default transformer
159
String JavaDoc key = "javax.xml.transform.TransformerFactory";
160       String JavaDoc value = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
161       Properties JavaDoc props = System.getProperties();
162       props.put(key, value);
163       System.setProperties(props);
164       
165       try
166       {
167         tfactory = TransformerFactory.newInstance();
168       }
169       catch (TransformerFactoryConfigurationError JavaDoc pfe)
170       {
171         pfe.printStackTrace(dumpWriter);
172         diagnosticsWriter.println(
173           XSLMessages.createMessage(
174             XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful.");
175

176         tfactory = null; // shut up compiler
177

178         doExit(-1);
179       }
180
181       boolean formatOutput = false;
182       boolean useSourceLocation = false;
183       String JavaDoc inFileName = null;
184       String JavaDoc outFileName = null;
185       String JavaDoc dumpFileName = null;
186       String JavaDoc xslFileName = null;
187       String JavaDoc treedumpFileName = null;
188       String JavaDoc outputType = null;
189       String JavaDoc media = null;
190       Vector JavaDoc params = new Vector JavaDoc();
191       boolean quietConflictWarnings = false;
192       URIResolver JavaDoc uriResolver = null;
193       EntityResolver JavaDoc entityResolver = null;
194       ContentHandler JavaDoc contentHandler = null;
195       int recursionLimit=-1;
196
197       for (int i = 0; i < argv.length; i++)
198       {
199         if ("-XSLTC".equalsIgnoreCase(argv[i]))
200         {
201           // The -XSLTC option has been processed.
202
}
203         else if ("-INDENT".equalsIgnoreCase(argv[i]))
204         {
205           int indentAmount;
206
207           if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
208           {
209             indentAmount = Integer.parseInt(argv[++i]);
210           }
211           else
212           {
213             indentAmount = 0;
214           }
215
216           // TBD:
217
// xmlProcessorLiaison.setIndent(indentAmount);
218
}
219         else if ("-IN".equalsIgnoreCase(argv[i]))
220         {
221           if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
222             inFileName = argv[++i];
223           else
224             System.err.println(
225               XSLMessages.createMessage(
226                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
227                 new Object JavaDoc[]{ "-IN" })); //"Missing argument for);
228
}
229         else if ("-MEDIA".equalsIgnoreCase(argv[i]))
230         {
231           if (i + 1 < argv.length)
232             media = argv[++i];
233           else
234             System.err.println(
235               XSLMessages.createMessage(
236                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
237                 new Object JavaDoc[]{ "-MEDIA" })); //"Missing argument for);
238
}
239         else if ("-OUT".equalsIgnoreCase(argv[i]))
240         {
241           if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
242             outFileName = argv[++i];
243           else
244             System.err.println(
245               XSLMessages.createMessage(
246                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
247                 new Object JavaDoc[]{ "-OUT" })); //"Missing argument for);
248
}
249         else if ("-XSL".equalsIgnoreCase(argv[i]))
250         {
251           if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
252             xslFileName = argv[++i];
253           else
254             System.err.println(
255               XSLMessages.createMessage(
256                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
257                 new Object JavaDoc[]{ "-XSL" })); //"Missing argument for);
258
}
259         else if ("-FLAVOR".equalsIgnoreCase(argv[i]))
260         {
261           if (i + 1 < argv.length)
262           {
263             flavor = argv[++i];
264           }
265           else
266             System.err.println(
267               XSLMessages.createMessage(
268                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
269                 new Object JavaDoc[]{ "-FLAVOR" })); //"Missing argument for);
270
}
271         else if ("-PARAM".equalsIgnoreCase(argv[i]))
272         {
273           if (i + 2 < argv.length)
274           {
275             String JavaDoc name = argv[++i];
276
277             params.addElement(name);
278
279             String JavaDoc expression = argv[++i];
280
281             params.addElement(expression);
282           }
283           else
284             System.err.println(
285               XSLMessages.createMessage(
286                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
287                 new Object JavaDoc[]{ "-PARAM" })); //"Missing argument for);
288
}
289         else if ("-E".equalsIgnoreCase(argv[i]))
290         {
291
292           // TBD:
293
// xmlProcessorLiaison.setShouldExpandEntityRefs(false);
294
}
295         else if ("-V".equalsIgnoreCase(argv[i]))
296         {
297           diagnosticsWriter.println(resbundle.getString("version") //">>>>>>> Xalan Version "
298
+ Version.getVersion() + ", " +
299
300           resbundle.getString("version2")); // "<<<<<<<");
301
}
302         else if ("-Q".equalsIgnoreCase(argv[i]))
303         {
304           setQuietMode = true;
305         }
306         else if ("-DIAG".equalsIgnoreCase(argv[i]))
307         {
308           doDiag = true;
309         }
310         else if ("-XML".equalsIgnoreCase(argv[i]))
311         {
312           outputType = "xml";
313         }
314         else if ("-TEXT".equalsIgnoreCase(argv[i]))
315         {
316           outputType = "text";
317         }
318         else if ("-HTML".equalsIgnoreCase(argv[i]))
319         {
320           outputType = "html";
321         }
322         else if ("-EDUMP".equalsIgnoreCase(argv[i]))
323         {
324           doStackDumpOnError = true;
325
326           if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
327           {
328             dumpFileName = argv[++i];
329           }
330         }
331         else if ("-URIRESOLVER".equalsIgnoreCase(argv[i]))
332         {
333           if (i + 1 < argv.length)
334           {
335             try
336             {
337               uriResolver = (URIResolver JavaDoc) ObjectFactory.newInstance(
338                 argv[++i], ObjectFactory.findClassLoader(), true);
339
340               tfactory.setURIResolver(uriResolver);
341             }
342             catch (ObjectFactory.ConfigurationError cnfe)
343             {
344               System.err.println(
345                 XSLMessages.createMessage(
346                   XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
347                   new Object JavaDoc[]{ "-URIResolver" }));
348               doExit(-1);
349             }
350           }
351           else
352           {
353             System.err.println(
354               XSLMessages.createMessage(
355                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
356                 new Object JavaDoc[]{ "-URIResolver" })); //"Missing argument for);
357
doExit(-1);
358           }
359         }
360         else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i]))
361         {
362           if (i + 1 < argv.length)
363           {
364             try
365             {
366               entityResolver = (EntityResolver JavaDoc) ObjectFactory.newInstance(
367                 argv[++i], ObjectFactory.findClassLoader(), true);
368             }
369             catch (ObjectFactory.ConfigurationError cnfe)
370             {
371               System.err.println(
372                 XSLMessages.createMessage(
373                   XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
374                   new Object JavaDoc[]{ "-EntityResolver" }));
375               doExit(-1);
376             }
377           }
378           else
379           {
380             System.err.println(
381               XSLMessages.createMessage(
382                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
383                 new Object JavaDoc[]{ "-EntityResolver" })); //"Missing argument for);
384
doExit(-1);
385           }
386         }
387         else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i]))
388         {
389           if (i + 1 < argv.length)
390           {
391             try
392             {
393               contentHandler = (ContentHandler JavaDoc) ObjectFactory.newInstance(
394                 argv[++i], ObjectFactory.findClassLoader(), true);
395             }
396             catch (ObjectFactory.ConfigurationError cnfe)
397             {
398               System.err.println(
399                 XSLMessages.createMessage(
400                   XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
401                   new Object JavaDoc[]{ "-ContentHandler" }));
402               doExit(-1);
403             }
404           }
405           else
406           {
407             System.err.println(
408               XSLMessages.createMessage(
409                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
410                 new Object JavaDoc[]{ "-ContentHandler" })); //"Missing argument for);
411
doExit(-1);
412           }
413         }
414         // Generate the translet class and optionally specify the name
415
// of the translet class.
416
else if ("-XO".equalsIgnoreCase(argv[i]))
417         {
418           if (useXSLTC)
419           {
420             if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
421             {
422               tfactory.setAttribute("generate-translet", "true");
423               tfactory.setAttribute("translet-name", argv[++i]);
424             }
425             else
426               tfactory.setAttribute("generate-translet", "true");
427           }
428           else
429           {
430             if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
431              i++;
432             printInvalidXalanOption("-XO");
433           }
434         }
435         // Specify the destination directory for the translet classes.
436
else if ("-XD".equalsIgnoreCase(argv[i]))
437         {
438           if (useXSLTC)
439           {
440             if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
441               tfactory.setAttribute("destination-directory", argv[++i]);
442             else
443               System.err.println(
444                 XSLMessages.createMessage(
445                   XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
446                   new Object JavaDoc[]{ "-XD" })); //"Missing argument for);
447

448           }
449           else
450           {
451             if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
452              i++;
453              
454             printInvalidXalanOption("-XD");
455           }
456         }
457         // Specify the jar file name which the translet classes are packaged into.
458
else if ("-XJ".equalsIgnoreCase(argv[i]))
459         {
460           if (useXSLTC)
461           {
462             if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
463             {
464               tfactory.setAttribute("generate-translet", "true");
465               tfactory.setAttribute("jar-name", argv[++i]);
466             }
467             else
468               System.err.println(
469                 XSLMessages.createMessage(
470                   XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
471                   new Object JavaDoc[]{ "-XJ" })); //"Missing argument for);
472
}
473           else
474           {
475             if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
476              i++;
477              
478             printInvalidXalanOption("-XJ");
479           }
480         
481         }
482         // Specify the package name prefix for the generated translet classes.
483
else if ("-XP".equalsIgnoreCase(argv[i]))
484         {
485           if (useXSLTC)
486           {
487             if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
488               tfactory.setAttribute("package-name", argv[++i]);
489             else
490               System.err.println(
491                 XSLMessages.createMessage(
492                   XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
493                   new Object JavaDoc[]{ "-XP" })); //"Missing argument for);
494
}
495           else
496           {
497             if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
498              i++;
499              
500             printInvalidXalanOption("-XP");
501           }
502         
503         }
504         // Enable template inlining.
505
else if ("-XN".equalsIgnoreCase(argv[i]))
506         {
507           if (useXSLTC)
508           {
509             tfactory.setAttribute("enable-inlining", "true");
510           }
511           else
512             printInvalidXalanOption("-XN");
513         }
514         // Turns on additional debugging message output
515
else if ("-XX".equalsIgnoreCase(argv[i]))
516         {
517           if (useXSLTC)
518           {
519             tfactory.setAttribute("debug", "true");
520           }
521           else
522             printInvalidXalanOption("-XX");
523         }
524         // Create the Transformer from the translet if the translet class is newer
525
// than the stylesheet.
526
else if ("-XT".equalsIgnoreCase(argv[i]))
527         {
528           if (useXSLTC)
529           {
530             tfactory.setAttribute("auto-translet", "true");
531           }
532           else
533             printInvalidXalanOption("-XT");
534         }
535         else
536           System.err.println(
537             XSLMessages.createMessage(
538               XSLTErrorResources.ER_INVALID_OPTION, new Object JavaDoc[]{ argv[i] })); //"Invalid argument:);
539
}
540       
541       // Print usage instructions if no xml and xsl file is specified in the command line
542
if (inFileName == null && xslFileName == null)
543       {
544         System.err.println(resbundle.getString("xslProc_no_input"));
545         doExit(-1);
546       }
547
548       // Note that there are usage cases for calling us without a -IN arg
549
// The main XSL transformation occurs here!
550
try
551       {
552         long start = System.currentTimeMillis();
553
554         if (null != dumpFileName)
555         {
556           dumpWriter = new PrintWriter JavaDoc(new FileWriter JavaDoc(dumpFileName));
557         }
558
559         Templates JavaDoc stylesheet = null;
560
561         if (null != xslFileName)
562         {
563           if (flavor.equals("d2d"))
564           {
565
566             // Parse in the xml data into a DOM
567
DocumentBuilderFactory JavaDoc dfactory =
568               DocumentBuilderFactory.newInstance();
569
570             dfactory.setNamespaceAware(true);
571
572             DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
573             Node JavaDoc xslDOM = docBuilder.parse(new InputSource JavaDoc(xslFileName));
574
575             stylesheet = tfactory.newTemplates(new DOMSource JavaDoc(xslDOM,
576                     xslFileName));
577           }
578           else
579           {
580             stylesheet = tfactory.newTemplates(new StreamSource JavaDoc(xslFileName));
581           }
582         }
583
584         PrintWriter JavaDoc resultWriter;
585         StreamResult JavaDoc strResult;
586
587         if (null != outFileName)
588         {
589           strResult = new StreamResult JavaDoc(new FileOutputStream JavaDoc(outFileName));
590           // One possible improvement might be to ensure this is
591
// a valid URI before setting the systemId, but that
592
// might have subtle changes that pre-existing users
593
// might notice; we can think about that later -sc r1.46
594
strResult.setSystemId(outFileName);
595         }
596         else
597         {
598           strResult = new StreamResult JavaDoc(System.out);
599       // We used to default to incremental mode in this case.
600
// We've since decided that since the -INCREMENTAL switch is
601
// available, that default is probably not necessary nor
602
// necessarily a good idea.
603
}
604
605         SAXTransformerFactory JavaDoc stf = (SAXTransformerFactory JavaDoc) tfactory;
606         
607
608         // Did they pass in a stylesheet, or should we get it from the
609
// document?
610
if (null == stylesheet)
611         {
612           Source JavaDoc source =
613             stf.getAssociatedStylesheet(new StreamSource JavaDoc(inFileName), media,
614                                         null, null);
615
616           if (null != source)
617             stylesheet = tfactory.newTemplates(source);
618           else
619           {
620             if (null != media)
621               throw new TransformerException JavaDoc(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object JavaDoc[]{inFileName, media})); //"No stylesheet found in: "
622
// + inFileName + ", media="
623
// + media);
624
else
625               throw new TransformerException JavaDoc(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object JavaDoc[]{inFileName})); //"No xml-stylesheet PI found in: "
626
//+ inFileName);
627
}
628         }
629
630         if (null != stylesheet)
631         {
632           Transformer JavaDoc transformer = flavor.equals("th") ? null : stylesheet.newTransformer();
633
634           // Override the output format?
635
if (null != outputType)
636           {
637             transformer.setOutputProperty(OutputKeys.METHOD, outputType);
638           }
639
640
641           int nParams = params.size();
642
643           for (int i = 0; i < nParams; i += 2)
644           {
645             transformer.setParameter((String JavaDoc) params.elementAt(i),
646                                      (String JavaDoc) params.elementAt(i + 1));
647           }
648
649           if (uriResolver != null)
650             transformer.setURIResolver(uriResolver);
651
652           if (null != inFileName)
653           {
654             if (flavor.equals("d2d"))
655             {
656
657               // Parse in the xml data into a DOM
658
DocumentBuilderFactory JavaDoc dfactory =
659                 DocumentBuilderFactory.newInstance();
660
661               dfactory.setCoalescing(true);
662               dfactory.setNamespaceAware(true);
663
664               DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
665
666               if (entityResolver != null)
667                 docBuilder.setEntityResolver(entityResolver);
668
669               Node JavaDoc xmlDoc = docBuilder.parse(new InputSource JavaDoc(inFileName));
670               Document JavaDoc doc = docBuilder.newDocument();
671               org.w3c.dom.DocumentFragment JavaDoc outNode =
672                 doc.createDocumentFragment();
673
674               transformer.transform(new DOMSource JavaDoc(xmlDoc, inFileName),
675                                     new DOMResult JavaDoc(outNode));
676
677               // Now serialize output to disk with identity transformer
678
Transformer JavaDoc serializer = stf.newTransformer();
679               Properties JavaDoc serializationProps =
680                 stylesheet.getOutputProperties();
681
682               serializer.setOutputProperties(serializationProps);
683
684               if (contentHandler != null)
685               {
686                 SAXResult JavaDoc result = new SAXResult JavaDoc(contentHandler);
687
688                 serializer.transform(new DOMSource JavaDoc(outNode), result);
689               }
690               else
691                 serializer.transform(new DOMSource JavaDoc(outNode), strResult);
692             }
693             else if (flavor.equals("th"))
694             {
695               for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior
696
{
697               // System.out.println("Testing the TransformerHandler...");
698

699               // ===============
700
XMLReader JavaDoc reader = null;
701
702               // Use JAXP1.1 ( if possible )
703
try
704               {
705                 javax.xml.parsers.SAXParserFactory JavaDoc factory =
706                   javax.xml.parsers.SAXParserFactory.newInstance();
707
708                 factory.setNamespaceAware(true);
709
710                 javax.xml.parsers.SAXParser JavaDoc jaxpParser =
711                   factory.newSAXParser();
712
713                 reader = jaxpParser.getXMLReader();
714               }
715               catch (javax.xml.parsers.ParserConfigurationException JavaDoc ex)
716               {
717                 throw new org.xml.sax.SAXException JavaDoc(ex);
718               }
719               catch (javax.xml.parsers.FactoryConfigurationError JavaDoc ex1)
720               {
721                 throw new org.xml.sax.SAXException JavaDoc(ex1.toString());
722               }
723               catch (NoSuchMethodError JavaDoc ex2){}
724               catch (AbstractMethodError JavaDoc ame){}
725
726               if (null == reader)
727               {
728                 reader = XMLReaderFactory.createXMLReader();
729               }
730               
731                  
732               TransformerHandler JavaDoc th = stf.newTransformerHandler(stylesheet);
733               
734               reader.setContentHandler(th);
735               reader.setDTDHandler(th);
736               
737               if(th instanceof org.xml.sax.ErrorHandler JavaDoc)
738                 reader.setErrorHandler((org.xml.sax.ErrorHandler JavaDoc)th);
739               
740               try
741               {
742                 reader.setProperty(
743                   "http://xml.org/sax/properties/lexical-handler", th);
744               }
745               catch (org.xml.sax.SAXNotRecognizedException JavaDoc e){}
746               catch (org.xml.sax.SAXNotSupportedException JavaDoc e){}
747               try
748               {
749                 reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
750                                   true);
751               } catch (org.xml.sax.SAXException JavaDoc se) {}
752         
753               th.setResult(strResult);
754               
755               reader.parse(new InputSource JavaDoc(inFileName));
756               }
757             }
758             else
759             {
760               if (entityResolver != null)
761               {
762                 XMLReader JavaDoc reader = null;
763
764                 // Use JAXP1.1 ( if possible )
765
try
766                 {
767                   javax.xml.parsers.SAXParserFactory JavaDoc factory =
768                     javax.xml.parsers.SAXParserFactory.newInstance();
769
770                   factory.setNamespaceAware(true);
771
772                   javax.xml.parsers.SAXParser JavaDoc jaxpParser =
773                     factory.newSAXParser();
774
775                   reader = jaxpParser.getXMLReader();
776                 }
777                 catch (javax.xml.parsers.ParserConfigurationException JavaDoc ex)
778                 {
779                   throw new org.xml.sax.SAXException JavaDoc(ex);
780                 }
781                 catch (javax.xml.parsers.FactoryConfigurationError JavaDoc ex1)
782                 {
783                   throw new org.xml.sax.SAXException JavaDoc(ex1.toString());
784                 }
785                 catch (NoSuchMethodError JavaDoc ex2){}
786                 catch (AbstractMethodError JavaDoc ame){}
787
788                 if (null == reader)
789                 {
790                   reader = XMLReaderFactory.createXMLReader();
791                 }
792
793                 reader.setEntityResolver(entityResolver);
794
795                 if (contentHandler != null)
796                 {
797                   SAXResult JavaDoc result = new SAXResult JavaDoc(contentHandler);
798
799                   transformer.transform(
800                     new SAXSource JavaDoc(reader, new InputSource JavaDoc(inFileName)),
801                     result);
802                 }
803                 else
804                 {
805                   transformer.transform(
806                     new SAXSource JavaDoc(reader, new InputSource JavaDoc(inFileName)),
807                     strResult);
808                 }
809               }
810               else if (contentHandler != null)
811               {
812                 SAXResult JavaDoc result = new SAXResult JavaDoc(contentHandler);
813
814                 transformer.transform(new StreamSource JavaDoc(inFileName), result);
815               }
816               else
817               {
818                 transformer.transform(new StreamSource JavaDoc(inFileName),
819                                       strResult);
820               }
821             }
822           }
823           else
824           {
825             StringReader JavaDoc reader =
826               new StringReader JavaDoc("<?xml version=\"1.0\"?> <doc/>");
827
828             transformer.transform(new StreamSource JavaDoc(reader), strResult);
829           }
830         }
831         else
832         {
833           diagnosticsWriter.println(
834             XSLMessages.createMessage(
835               XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful.");
836
doExit(-1);
837         }
838         
839     // close output streams
840
if (null != outFileName && strResult!=null)
841     {
842       java.io.OutputStream JavaDoc out = strResult.getOutputStream();
843       java.io.Writer JavaDoc writer = strResult.getWriter();
844       try
845       {
846             if (out != null) out.close();
847             if (writer != null) writer.close();
848       }
849       catch(java.io.IOException JavaDoc ie) {}
850     }
851
852         long stop = System.currentTimeMillis();
853         long millisecondsDuration = stop - start;
854
855         if (doDiag)
856         {
857             Object JavaDoc[] msgArgs = new Object JavaDoc[]{ inFileName, xslFileName, new Long JavaDoc(millisecondsDuration) };
858             String JavaDoc msg = XSLMessages.createMessage("diagTiming", msgArgs);
859             diagnosticsWriter.println('\n');
860             diagnosticsWriter.println(msg);
861         }
862           
863       }
864       catch (Throwable JavaDoc throwable)
865       {
866         while (throwable
867                instanceof com.sun.org.apache.xml.internal.utils.WrappedRuntimeException)
868         {
869           throwable =
870             ((com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) throwable).getException();
871         }
872
873         if ((throwable instanceof NullPointerException JavaDoc)
874                 || (throwable instanceof ClassCastException JavaDoc))
875           doStackDumpOnError = true;
876
877         diagnosticsWriter.println();
878
879         if (doStackDumpOnError)
880           throwable.printStackTrace(dumpWriter);
881         else
882         {
883           DefaultErrorHandler.printLocation(diagnosticsWriter, throwable);
884           diagnosticsWriter.println(
885             XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null)
886             + " (" + throwable.getClass().getName() + "): "
887             + throwable.getMessage());
888         }
889
890         // diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful.");
891
if (null != dumpFileName)
892         {
893           dumpWriter.close();
894         }
895
896         doExit(-1);
897       }
898
899       if (null != dumpFileName)
900       {
901         dumpWriter.close();
902       }
903
904       if (null != diagnosticsWriter)
905       {
906
907         // diagnosticsWriter.close();
908
}
909
910     }
911   }
912   
913   /** It is _much_ easier to debug under VJ++ if I can set a single breakpoint
914    * before this blows itself out of the water...
915    * (I keep checking this in, it keeps vanishing. Grr!)
916    * */

917   static void doExit(int i)
918   {
919     System.exit(i);
920   }
921   
922   /**
923    * Wait for a return key to continue
924    *
925    * @param resbundle The resource bundle
926    */

927   private static void waitForReturnKey(ResourceBundle JavaDoc resbundle)
928   {
929     System.out.println(resbundle.getString("xslProc_return_to_continue"));
930     try
931     {
932       while (System.in.read() != '\n');
933     }
934     catch (java.io.IOException JavaDoc e) { }
935   }
936   
937   /**
938    * Print a message if an option cannot be used with -XSLTC.
939    *
940    * @param option The option String
941    */

942   private static void printInvalidXSLTCOption(String JavaDoc option)
943   {
944     System.err.println(XSLMessages.createMessage("xslProc_invalid_xsltc_option", new Object JavaDoc[]{option}));
945   }
946   
947   /**
948    * Print a message if an option can only be used with -XSLTC.
949    *
950    * @param option The option String
951    */

952   private static void printInvalidXalanOption(String JavaDoc option)
953   {
954     System.err.println(XSLMessages.createMessage("xslProc_invalid_xalan_option", new Object JavaDoc[]{option}));
955   }
956 }
957
Popular Tags