KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > xalan > 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 /*
17  * $Id: Process.java,v 1.62 2004/02/23 10:29:35 aruny Exp $
18  */

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

69 public class Process
70 {
71   /**
72    * Prints argument options.
73    *
74    * @param resbundle Resource bundle
75    */

76   protected static void printArgOptions(ResourceBundle JavaDoc resbundle)
77   {
78     System.out.println(resbundle.getString("xslProc_option")); //"xslproc options: ");
79
System.out.println("\n\t\t\t" + resbundle.getString("xslProc_common_options") + "\n");
80     System.out.println(resbundle.getString("optionXSLTC")); //" [-XSLTC (use XSLTC for transformation)]
81
System.out.println(resbundle.getString("optionIN")); //" [-IN inputXMLURL]");
82
System.out.println(resbundle.getString("optionXSL")); //" [-XSL XSLTransformationURL]");
83
System.out.println(resbundle.getString("optionOUT")); //" [-OUT outputFileName]");
84

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

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

95     System.out.println(resbundle.getString("optionMEDIA"));
96     System.out.println(resbundle.getString("optionFLAVOR"));
97     System.out.println(resbundle.getString("optionDIAG"));
98     System.out.println(resbundle.getString("optionURIRESOLVER")); //" [-URIRESOLVER full class name (URIResolver to be used to resolve URIs)]");
99
System.out.println(resbundle.getString("optionENTITYRESOLVER")); //" [-ENTITYRESOLVER full class name (EntityResolver to be used to resolve entities)]");
100
waitForReturnKey(resbundle);
101     System.out.println(resbundle.getString("optionCONTENTHANDLER")); //" [-CONTENTHANDLER full class name (ContentHandler to be used to serialize output)]");
102

103     System.out.println("\n\t\t\t" + resbundle.getString("xslProc_xalan_options") + "\n");
104     
105     System.out.println(resbundle.getString("optionQC")); //" [-QC (Quiet Pattern Conflicts Warnings)]");
106

107     // System.out.println(resbundle.getString("optionQ")); //" [-Q (Quiet Mode)]"); // sc 28-Feb-01 commented out
108
System.out.println(resbundle.getString("optionTT")); //" [-TT (Trace the templates as they are being called.)]");
109
System.out.println(resbundle.getString("optionTG")); //" [-TG (Trace each generation event.)]");
110
System.out.println(resbundle.getString("optionTS")); //" [-TS (Trace each selection event.)]");
111
System.out.println(resbundle.getString("optionTTC")); //" [-TTC (Trace the template children as they are being processed.)]");
112
System.out.println(resbundle.getString("optionTCLASS")); //" [-TCLASS (TraceListener class for trace extensions.)]");
113
System.out.println(resbundle.getString("optionLINENUMBERS")); //" [-L use line numbers]"
114
System.out.println(resbundle.getString("optionINCREMENTAL"));
115     System.out.println(resbundle.getString("optionNOOPTIMIMIZE"));
116     System.out.println(resbundle.getString("optionRL"));
117         
118     System.out.println("\n\t\t\t" + resbundle.getString("xslProc_xsltc_options") + "\n");
119     System.out.println(resbundle.getString("optionXO"));
120     System.out.println(resbundle.getString("optionXD"));
121     waitForReturnKey(resbundle);
122     System.out.println(resbundle.getString("optionXJ"));
123     System.out.println(resbundle.getString("optionXP"));
124     System.out.println(resbundle.getString("optionXN"));
125     System.out.println(resbundle.getString("optionXX"));
126     System.out.println(resbundle.getString("optionXT"));
127   }
128   
129   /**
130    * Command line interface to transform an XML document according to
131    * the instructions found in an XSL stylesheet.
132    * <p>The Process class provides basic functionality for
133    * performing transformations from the command line. To see a
134    * list of arguments supported, call with zero arguments.</p>
135    * <p>To set stylesheet parameters from the command line, use
136    * <code>-PARAM name expression</code>. If you want to set the
137    * parameter to a string value, simply pass the string value
138    * as-is, and it will be interpreted as a string. (Note: if
139    * the value has spaces in it, you may need to quote it depending
140    * on your shell environment).</p>
141    *
142    * @param argv Input parameters from command line
143    */

144   public static void main(String JavaDoc argv[])
145   {
146     
147     // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off
148
boolean doStackDumpOnError = false;
149     boolean setQuietMode = false;
150     boolean doDiag = false;
151
152     // Runtime.getRuntime().traceMethodCalls(false);
153
// Runtime.getRuntime().traceInstructions(false);
154

155     /**
156      * The default diagnostic writer...
157      */

158     java.io.PrintWriter JavaDoc diagnosticsWriter = new PrintWriter JavaDoc(System.err, true);
159     java.io.PrintWriter JavaDoc dumpWriter = diagnosticsWriter;
160     ResourceBundle JavaDoc resbundle =
161       (XSLMessages.loadResourceBundle(
162         org.apache.xml.utils.res.XResourceBundle.ERROR_RESOURCES));
163     String JavaDoc flavor = "s2s";
164
165     if (argv.length < 1)
166     {
167       printArgOptions(resbundle);
168     }
169     else
170     {
171       boolean useXSLTC = false;
172       for (int i = 0; i < argv.length; i++)
173       {
174         if ("-XSLTC".equalsIgnoreCase(argv[i]))
175         {
176           useXSLTC = true;
177         }
178       }
179         
180       TransformerFactory JavaDoc tfactory;
181       if (useXSLTC)
182       {
183      String JavaDoc key = "javax.xml.transform.TransformerFactory";
184      String JavaDoc value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
185      Properties JavaDoc props = System.getProperties();
186      props.put(key, value);
187      System.setProperties(props);
188       }
189       
190       try
191       {
192         tfactory = TransformerFactory.newInstance();
193       }
194       catch (TransformerFactoryConfigurationError JavaDoc pfe)
195       {
196         pfe.printStackTrace(dumpWriter);
197         diagnosticsWriter.println(
198           XSLMessages.createMessage(
199             XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful.");
200

201         tfactory = null; // shut up compiler
202

203         doExit(-1);
204       }
205
206       boolean formatOutput = false;
207       boolean useSourceLocation = false;
208       String JavaDoc inFileName = null;
209       String JavaDoc outFileName = null;
210       String JavaDoc dumpFileName = null;
211       String JavaDoc xslFileName = null;
212       String JavaDoc treedumpFileName = null;
213       PrintTraceListener tracer = null;
214       String JavaDoc outputType = null;
215       String JavaDoc media = null;
216       Vector JavaDoc params = new Vector JavaDoc();
217       boolean quietConflictWarnings = false;
218       URIResolver JavaDoc uriResolver = null;
219       EntityResolver JavaDoc entityResolver = null;
220       ContentHandler JavaDoc contentHandler = null;
221       int recursionLimit=-1;
222
223       for (int i = 0; i < argv.length; i++)
224       {
225         if ("-XSLTC".equalsIgnoreCase(argv[i]))
226         {
227           // The -XSLTC option has been processed.
228
}
229         else if ("-TT".equalsIgnoreCase(argv[i]))
230         {
231           if (!useXSLTC)
232           {
233             if (null == tracer)
234               tracer = new PrintTraceListener(diagnosticsWriter);
235
236             tracer.m_traceTemplates = true;
237           }
238           else
239             printInvalidXSLTCOption("-TT");
240
241           // tfactory.setTraceTemplates(true);
242
}
243         else if ("-TG".equalsIgnoreCase(argv[i]))
244         {
245           if (!useXSLTC)
246           {
247             if (null == tracer)
248               tracer = new PrintTraceListener(diagnosticsWriter);
249
250             tracer.m_traceGeneration = true;
251           }
252           else
253             printInvalidXSLTCOption("-TG");
254
255           // tfactory.setTraceSelect(true);
256
}
257         else if ("-TS".equalsIgnoreCase(argv[i]))
258         {
259           if (!useXSLTC)
260           {
261             if (null == tracer)
262               tracer = new PrintTraceListener(diagnosticsWriter);
263
264             tracer.m_traceSelection = true;
265           }
266           else
267             printInvalidXSLTCOption("-TS");
268
269           // tfactory.setTraceTemplates(true);
270
}
271         else if ("-TTC".equalsIgnoreCase(argv[i]))
272         {
273           if (!useXSLTC)
274           {
275             if (null == tracer)
276               tracer = new PrintTraceListener(diagnosticsWriter);
277
278             tracer.m_traceElements = true;
279           }
280           else
281             printInvalidXSLTCOption("-TTC");
282
283           // tfactory.setTraceTemplateChildren(true);
284
}
285         else if ("-INDENT".equalsIgnoreCase(argv[i]))
286         {
287           int indentAmount;
288
289           if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
290           {
291             indentAmount = Integer.parseInt(argv[++i]);
292           }
293           else
294           {
295             indentAmount = 0;
296           }
297
298           // TBD:
299
// xmlProcessorLiaison.setIndent(indentAmount);
300
}
301         else if ("-IN".equalsIgnoreCase(argv[i]))
302         {
303           if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
304             inFileName = argv[++i];
305           else
306             System.err.println(
307               XSLMessages.createMessage(
308                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
309                 new Object JavaDoc[]{ "-IN" })); //"Missing argument for);
310
}
311         else if ("-MEDIA".equalsIgnoreCase(argv[i]))
312         {
313           if (i + 1 < argv.length)
314             media = argv[++i];
315           else
316             System.err.println(
317               XSLMessages.createMessage(
318                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
319                 new Object JavaDoc[]{ "-MEDIA" })); //"Missing argument for);
320
}
321         else if ("-OUT".equalsIgnoreCase(argv[i]))
322         {
323           if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
324             outFileName = argv[++i];
325           else
326             System.err.println(
327               XSLMessages.createMessage(
328                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
329                 new Object JavaDoc[]{ "-OUT" })); //"Missing argument for);
330
}
331         else if ("-XSL".equalsIgnoreCase(argv[i]))
332         {
333           if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
334             xslFileName = argv[++i];
335           else
336             System.err.println(
337               XSLMessages.createMessage(
338                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
339                 new Object JavaDoc[]{ "-XSL" })); //"Missing argument for);
340
}
341         else if ("-FLAVOR".equalsIgnoreCase(argv[i]))
342         {
343           if (i + 1 < argv.length)
344           {
345             flavor = argv[++i];
346           }
347           else
348             System.err.println(
349               XSLMessages.createMessage(
350                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
351                 new Object JavaDoc[]{ "-FLAVOR" })); //"Missing argument for);
352
}
353         else if ("-PARAM".equalsIgnoreCase(argv[i]))
354         {
355           if (i + 2 < argv.length)
356           {
357             String JavaDoc name = argv[++i];
358
359             params.addElement(name);
360
361             String JavaDoc expression = argv[++i];
362
363             params.addElement(expression);
364           }
365           else
366             System.err.println(
367               XSLMessages.createMessage(
368                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
369                 new Object JavaDoc[]{ "-PARAM" })); //"Missing argument for);
370
}
371         else if ("-E".equalsIgnoreCase(argv[i]))
372         {
373
374           // TBD:
375
// xmlProcessorLiaison.setShouldExpandEntityRefs(false);
376
}
377         else if ("-V".equalsIgnoreCase(argv[i]))
378         {
379           diagnosticsWriter.println(resbundle.getString("version") //">>>>>>> Xalan Version "
380
+ Version.getVersion() + ", " +
381
382           /* xmlProcessorLiaison.getParserDescription()+ */
383           resbundle.getString("version2")); // "<<<<<<<");
384
}
385         else if ("-QC".equalsIgnoreCase(argv[i]))
386         {
387           if (!useXSLTC)
388             quietConflictWarnings = true;
389           else
390             printInvalidXSLTCOption("-QC");
391         }
392         else if ("-Q".equalsIgnoreCase(argv[i]))
393         {
394           setQuietMode = true;
395         }
396         else if ("-DIAG".equalsIgnoreCase(argv[i]))
397         {
398           doDiag = true;
399         }
400         else if ("-XML".equalsIgnoreCase(argv[i]))
401         {
402           outputType = "xml";
403         }
404         else if ("-TEXT".equalsIgnoreCase(argv[i]))
405         {
406           outputType = "text";
407         }
408         else if ("-HTML".equalsIgnoreCase(argv[i]))
409         {
410           outputType = "html";
411         }
412         else if ("-EDUMP".equalsIgnoreCase(argv[i]))
413         {
414           doStackDumpOnError = true;
415
416           if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
417           {
418             dumpFileName = argv[++i];
419           }
420         }
421         else if ("-URIRESOLVER".equalsIgnoreCase(argv[i]))
422         {
423           if (i + 1 < argv.length)
424           {
425             try
426             {
427               uriResolver = (URIResolver JavaDoc) ObjectFactory.newInstance(
428                 argv[++i], ObjectFactory.findClassLoader(), true);
429
430               tfactory.setURIResolver(uriResolver);
431             }
432             catch (ObjectFactory.ConfigurationError cnfe)
433             {
434               System.err.println(
435                 XSLMessages.createMessage(
436                   XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
437                   new Object JavaDoc[]{ "-URIResolver" }));
438               doExit(-1);
439             }
440           }
441           else
442           {
443             System.err.println(
444               XSLMessages.createMessage(
445                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
446                 new Object JavaDoc[]{ "-URIResolver" })); //"Missing argument for);
447
doExit(-1);
448           }
449         }
450         else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i]))
451         {
452           if (i + 1 < argv.length)
453           {
454             try
455             {
456               entityResolver = (EntityResolver JavaDoc) ObjectFactory.newInstance(
457                 argv[++i], ObjectFactory.findClassLoader(), true);
458             }
459             catch (ObjectFactory.ConfigurationError cnfe)
460             {
461               System.err.println(
462                 XSLMessages.createMessage(
463                   XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
464                   new Object JavaDoc[]{ "-EntityResolver" }));
465               doExit(-1);
466             }
467           }
468           else
469           {
470             System.err.println(
471               XSLMessages.createMessage(
472                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
473                 new Object JavaDoc[]{ "-EntityResolver" })); //"Missing argument for);
474
doExit(-1);
475           }
476         }
477         else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i]))
478         {
479           if (i + 1 < argv.length)
480           {
481             try
482             {
483               contentHandler = (ContentHandler JavaDoc) ObjectFactory.newInstance(
484                 argv[++i], ObjectFactory.findClassLoader(), true);
485             }
486             catch (ObjectFactory.ConfigurationError cnfe)
487             {
488               System.err.println(
489                 XSLMessages.createMessage(
490                   XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
491                   new Object JavaDoc[]{ "-ContentHandler" }));
492               doExit(-1);
493             }
494           }
495           else
496           {
497             System.err.println(
498               XSLMessages.createMessage(
499                 XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
500                 new Object JavaDoc[]{ "-ContentHandler" })); //"Missing argument for);
501
doExit(-1);
502           }
503         }
504         else if ("-L".equalsIgnoreCase(argv[i]))
505         {
506           if (!useXSLTC)
507             useSourceLocation = true;
508           else
509             printInvalidXSLTCOption("-L");
510         }
511         else if ("-INCREMENTAL".equalsIgnoreCase(argv[i]))
512         {
513           if (!useXSLTC)
514             tfactory.setAttribute
515               ("http://xml.apache.org/xalan/features/incremental",
516                java.lang.Boolean.TRUE);
517           else
518             printInvalidXSLTCOption("-INCREMENTAL");
519         }
520         else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i]))
521         {
522           // Default is true.
523
//
524
// %REVIEW% We should have a generalized syntax for negative
525
// switches... and probably should accept the inverse even
526
// if it is the default.
527
if (!useXSLTC)
528             tfactory.setAttribute
529               ("http://xml.apache.org/xalan/features/optimize",
530                java.lang.Boolean.FALSE);
531           else
532             printInvalidXSLTCOption("-NOOPTIMIZE");
533     }
534         else if ("-RL".equalsIgnoreCase(argv[i]))
535         {
536           if (!useXSLTC)
537           {
538             if (i + 1 < argv.length)
539               recursionLimit = Integer.parseInt(argv[++i]);
540             else
541               System.err.println(
542                 XSLMessages.createMessage(
543                   XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
544                   new Object JavaDoc[]{ "-rl" })); //"Missing argument for);
545
}
546           else
547           {
548             if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
549              i++;
550              
551             printInvalidXSLTCOption("-RL");
552           }
553         }
554         // Generate the translet class and optionally specify the name
555
// of the translet class.
556
else if ("-XO".equalsIgnoreCase(argv[i]))
557         {
558           if (useXSLTC)
559           {
560             if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
561             {
562               tfactory.setAttribute("generate-translet", "true");
563               tfactory.setAttribute("translet-name", argv[++i]);
564             }
565             else
566               tfactory.setAttribute("generate-translet", "true");
567           }
568           else
569           {
570             if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
571              i++;
572             printInvalidXalanOption("-XO");
573           }
574         }
575         // Specify the destination directory for the translet classes.
576
else if ("-XD".equalsIgnoreCase(argv[i]))
577         {
578           if (useXSLTC)
579           {
580             if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
581               tfactory.setAttribute("destination-directory", argv[++i]);
582             else
583               System.err.println(
584                 XSLMessages.createMessage(
585                   XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
586                   new Object JavaDoc[]{ "-XD" })); //"Missing argument for);
587

588           }
589           else
590           {
591             if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
592              i++;
593              
594             printInvalidXalanOption("-XD");
595           }
596         }
597         // Specify the jar file name which the translet classes are packaged into.
598
else if ("-XJ".equalsIgnoreCase(argv[i]))
599         {
600           if (useXSLTC)
601           {
602             if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
603             {
604               tfactory.setAttribute("generate-translet", "true");
605               tfactory.setAttribute("jar-name", argv[++i]);
606             }
607             else
608               System.err.println(
609                 XSLMessages.createMessage(
610                   XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
611                   new Object JavaDoc[]{ "-XJ" })); //"Missing argument for);
612
}
613           else
614           {
615             if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
616              i++;
617              
618             printInvalidXalanOption("-XJ");
619           }
620         
621         }
622         // Specify the package name prefix for the generated translet classes.
623
else if ("-XP".equalsIgnoreCase(argv[i]))
624         {
625           if (useXSLTC)
626           {
627             if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
628               tfactory.setAttribute("package-name", argv[++i]);
629             else
630               System.err.println(
631                 XSLMessages.createMessage(
632                   XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
633                   new Object JavaDoc[]{ "-XP" })); //"Missing argument for);
634
}
635           else
636           {
637             if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
638              i++;
639              
640             printInvalidXalanOption("-XP");
641           }
642         
643         }
644         // Enable template inlining.
645
else if ("-XN".equalsIgnoreCase(argv[i]))
646         {
647           if (useXSLTC)
648           {
649             tfactory.setAttribute("enable-inlining", "true");
650           }
651           else
652             printInvalidXalanOption("-XN");
653         }
654         // Turns on additional debugging message output
655
else if ("-XX".equalsIgnoreCase(argv[i]))
656         {
657           if (useXSLTC)
658           {
659             tfactory.setAttribute("debug", "true");
660           }
661           else
662             printInvalidXalanOption("-XX");
663         }
664         // Create the Transformer from the translet if the translet class is newer
665
// than the stylesheet.
666
else if ("-XT".equalsIgnoreCase(argv[i]))
667         {
668           if (useXSLTC)
669           {
670             tfactory.setAttribute("auto-translet", "true");
671           }
672           else
673             printInvalidXalanOption("-XT");
674         }
675         else
676           System.err.println(
677             XSLMessages.createMessage(
678               XSLTErrorResources.ER_INVALID_OPTION, new Object JavaDoc[]{ argv[i] })); //"Invalid argument:);
679
}
680       
681       // Print usage instructions if no xml and xsl file is specified in the command line
682
if (inFileName == null && xslFileName == null)
683       {
684         System.err.println(resbundle.getString("xslProc_no_input"));
685         doExit(-1);
686       }
687
688       // Note that there are usage cases for calling us without a -IN arg
689
// The main XSL transformation occurs here!
690
try
691       {
692         long start = System.currentTimeMillis();
693
694         if (null != dumpFileName)
695         {
696           dumpWriter = new PrintWriter JavaDoc(new FileWriter JavaDoc(dumpFileName));
697         }
698
699         Templates JavaDoc stylesheet = null;
700
701         if (null != xslFileName)
702         {
703           if (flavor.equals("d2d"))
704           {
705
706             // Parse in the xml data into a DOM
707
DocumentBuilderFactory JavaDoc dfactory =
708               DocumentBuilderFactory.newInstance();
709
710             dfactory.setNamespaceAware(true);
711
712             DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
713             Node JavaDoc xslDOM = docBuilder.parse(new InputSource JavaDoc(xslFileName));
714
715             stylesheet = tfactory.newTemplates(new DOMSource JavaDoc(xslDOM,
716                     xslFileName));
717           }
718           else
719           {
720             // System.out.println("Calling newTemplates: "+xslFileName);
721
stylesheet = tfactory.newTemplates(new StreamSource JavaDoc(xslFileName));
722             // System.out.println("Done calling newTemplates: "+xslFileName);
723
}
724         }
725
726         PrintWriter JavaDoc resultWriter;
727         StreamResult JavaDoc strResult;
728
729         if (null != outFileName)
730         {
731           strResult = new StreamResult JavaDoc(new FileOutputStream JavaDoc(outFileName));
732           // One possible improvement might be to ensure this is
733
// a valid URI before setting the systemId, but that
734
// might have subtle changes that pre-existing users
735
// might notice; we can think about that later -sc r1.46
736
strResult.setSystemId(outFileName);
737         }
738         else
739         {
740           strResult = new StreamResult JavaDoc(System.out);
741       // We used to default to incremental mode in this case.
742
// We've since decided that since the -INCREMENTAL switch is
743
// available, that default is probably not necessary nor
744
// necessarily a good idea.
745
}
746
747         SAXTransformerFactory JavaDoc stf = (SAXTransformerFactory JavaDoc) tfactory;
748         
749         // This is currently controlled via TransformerFactoryImpl.
750
if (!useXSLTC && useSourceLocation)
751            stf.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
752
753         // Did they pass in a stylesheet, or should we get it from the
754
// document?
755
if (null == stylesheet)
756         {
757           Source JavaDoc source =
758             stf.getAssociatedStylesheet(new StreamSource JavaDoc(inFileName), media,
759                                         null, null);
760
761           if (null != source)
762             stylesheet = tfactory.newTemplates(source);
763           else
764           {
765             if (null != media)
766               throw new TransformerException JavaDoc(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object JavaDoc[]{inFileName, media})); //"No stylesheet found in: "
767
// + inFileName + ", media="
768
// + media);
769
else
770               throw new TransformerException JavaDoc(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object JavaDoc[]{inFileName})); //"No xml-stylesheet PI found in: "
771
//+ inFileName);
772
}
773         }
774
775         if (null != stylesheet)
776         {
777           Transformer JavaDoc transformer = flavor.equals("th") ? null : stylesheet.newTransformer();
778
779           // Override the output format?
780
if (null != outputType)
781           {
782             transformer.setOutputProperty(OutputKeys.METHOD, outputType);
783           }
784
785           if (transformer instanceof org.apache.xalan.transformer.TransformerImpl)
786           {
787             org.apache.xalan.transformer.TransformerImpl impl = (org.apache.xalan.transformer.TransformerImpl)transformer;
788             TraceManager tm = impl.getTraceManager();
789
790             if (null != tracer)
791               tm.addTraceListener(tracer);
792
793             impl.setQuietConflictWarnings(quietConflictWarnings);
794
795             // This is currently controlled via TransformerFactoryImpl.
796
if (useSourceLocation)
797               impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
798
799         if(recursionLimit>0)
800           impl.setRecursionLimit(recursionLimit);
801
802             // sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions
803
// impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter );
804
}
805
806           int nParams = params.size();
807
808           for (int i = 0; i < nParams; i += 2)
809           {
810             transformer.setParameter((String JavaDoc) params.elementAt(i),
811                                      (String JavaDoc) params.elementAt(i + 1));
812           }
813
814           if (uriResolver != null)
815             transformer.setURIResolver(uriResolver);
816
817           if (null != inFileName)
818           {
819             if (flavor.equals("d2d"))
820             {
821
822               // Parse in the xml data into a DOM
823
DocumentBuilderFactory JavaDoc dfactory =
824                 DocumentBuilderFactory.newInstance();
825
826               dfactory.setCoalescing(true);
827               dfactory.setNamespaceAware(true);
828
829               DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder();
830
831               if (entityResolver != null)
832                 docBuilder.setEntityResolver(entityResolver);
833
834               Node JavaDoc xmlDoc = docBuilder.parse(new InputSource JavaDoc(inFileName));
835               Document JavaDoc doc = docBuilder.newDocument();
836               org.w3c.dom.DocumentFragment JavaDoc outNode =
837                 doc.createDocumentFragment();
838
839               transformer.transform(new DOMSource JavaDoc(xmlDoc, inFileName),
840                                     new DOMResult JavaDoc(outNode));
841
842               // Now serialize output to disk with identity transformer
843
Transformer JavaDoc serializer = stf.newTransformer();
844               Properties JavaDoc serializationProps =
845                 stylesheet.getOutputProperties();
846
847               serializer.setOutputProperties(serializationProps);
848
849               if (contentHandler != null)
850               {
851                 SAXResult JavaDoc result = new SAXResult JavaDoc(contentHandler);
852
853                 serializer.transform(new DOMSource JavaDoc(outNode), result);
854               }
855               else
856                 serializer.transform(new DOMSource JavaDoc(outNode), strResult);
857             }
858             else if (flavor.equals("th"))
859             {
860               for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior
861
{
862               // System.out.println("Testing the TransformerHandler...");
863

864               // ===============
865
XMLReader JavaDoc reader = null;
866
867               // Use JAXP1.1 ( if possible )
868
try
869               {
870                 javax.xml.parsers.SAXParserFactory JavaDoc factory =
871                   javax.xml.parsers.SAXParserFactory.newInstance();
872
873                 factory.setNamespaceAware(true);
874
875                 javax.xml.parsers.SAXParser JavaDoc jaxpParser =
876                   factory.newSAXParser();
877
878                 reader = jaxpParser.getXMLReader();
879               }
880               catch (javax.xml.parsers.ParserConfigurationException JavaDoc ex)
881               {
882                 throw new org.xml.sax.SAXException JavaDoc(ex);
883               }
884               catch (javax.xml.parsers.FactoryConfigurationError JavaDoc ex1)
885               {
886                 throw new org.xml.sax.SAXException JavaDoc(ex1.toString());
887               }
888               catch (NoSuchMethodError JavaDoc ex2){}
889               catch (AbstractMethodError JavaDoc ame){}
890
891               if (null == reader)
892               {
893                 reader = XMLReaderFactory.createXMLReader();
894               }
895               
896               if (!useXSLTC)
897                 stf.setAttribute(org.apache.xalan.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL,
898                    Boolean.TRUE);
899                  
900               TransformerHandler JavaDoc th = stf.newTransformerHandler(stylesheet);
901               
902               reader.setContentHandler(th);
903               reader.setDTDHandler(th);
904               
905               if(th instanceof org.xml.sax.ErrorHandler JavaDoc)
906                 reader.setErrorHandler((org.xml.sax.ErrorHandler JavaDoc)th);
907               
908               try
909               {
910                 reader.setProperty(
911                   "http://xml.org/sax/properties/lexical-handler", th);
912               }
913               catch (org.xml.sax.SAXNotRecognizedException JavaDoc e){}
914               catch (org.xml.sax.SAXNotSupportedException JavaDoc e){}
915               try
916               {
917                 reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
918                                   true);
919               } catch (org.xml.sax.SAXException JavaDoc se) {}
920         
921               th.setResult(strResult);
922               
923               reader.parse(new InputSource JavaDoc(inFileName));
924               }
925             }
926             else
927             {
928               if (entityResolver != null)
929               {
930                 XMLReader JavaDoc reader = null;
931
932                 // Use JAXP1.1 ( if possible )
933
try
934                 {
935                   javax.xml.parsers.SAXParserFactory JavaDoc factory =
936                     javax.xml.parsers.SAXParserFactory.newInstance();
937
938                   factory.setNamespaceAware(true);
939
940                   javax.xml.parsers.SAXParser JavaDoc jaxpParser =
941                     factory.newSAXParser();
942
943                   reader = jaxpParser.getXMLReader();
944                 }
945                 catch (javax.xml.parsers.ParserConfigurationException JavaDoc ex)
946                 {
947                   throw new org.xml.sax.SAXException JavaDoc(ex);
948                 }
949                 catch (javax.xml.parsers.FactoryConfigurationError JavaDoc ex1)
950                 {
951                   throw new org.xml.sax.SAXException JavaDoc(ex1.toString());
952                 }
953                 catch (NoSuchMethodError JavaDoc ex2){}
954                 catch (AbstractMethodError JavaDoc ame){}
955
956                 if (null == reader)
957                 {
958                   reader = XMLReaderFactory.createXMLReader();
959                 }
960
961                 reader.setEntityResolver(entityResolver);
962
963                 if (contentHandler != null)
964                 {
965                   SAXResult JavaDoc result = new SAXResult JavaDoc(contentHandler);
966
967                   transformer.transform(
968                     new SAXSource JavaDoc(reader, new InputSource JavaDoc(inFileName)),
969                     result);
970                 }
971                 else
972                 {
973                   transformer.transform(
974                     new SAXSource JavaDoc(reader, new InputSource JavaDoc(inFileName)),
975                     strResult);
976                 }
977               }
978               else if (contentHandler != null)
979               {
980                 SAXResult JavaDoc result = new SAXResult JavaDoc(contentHandler);
981
982                 transformer.transform(new StreamSource JavaDoc(inFileName), result);
983               }
984               else
985               {
986                 // System.out.println("Starting transform");
987
transformer.transform(new StreamSource JavaDoc(inFileName),
988                                       strResult);
989                 // System.out.println("Done with transform");
990
}
991             }
992           }
993           else
994           {
995             StringReader JavaDoc reader =
996               new StringReader JavaDoc("<?xml version=\"1.0\"?> <doc/>");
997
998             transformer.transform(new StreamSource JavaDoc(reader), strResult);
999           }
1000        }
1001        else
1002        {
1003          diagnosticsWriter.println(
1004            XSLMessages.createMessage(
1005              XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful.");
1006
doExit(-1);
1007        }
1008        
1009    // close output streams
1010
if (null != outFileName && strResult!=null)
1011    {
1012      java.io.OutputStream JavaDoc out = strResult.getOutputStream();
1013      java.io.Writer JavaDoc writer = strResult.getWriter();
1014      try
1015      {
1016            if (out != null) out.close();
1017            if (writer != null) writer.close();
1018      }
1019      catch(java.io.IOException JavaDoc ie) {}
1020    }
1021
1022        long stop = System.currentTimeMillis();
1023        long millisecondsDuration = stop - start;
1024
1025        if (doDiag)
1026        {
1027            Object JavaDoc[] msgArgs = new Object JavaDoc[]{ inFileName, xslFileName, new Long JavaDoc(millisecondsDuration) };
1028            String JavaDoc msg = XSLMessages.createMessage("diagTiming", msgArgs);
1029            diagnosticsWriter.println('\n');
1030            diagnosticsWriter.println(msg);
1031        }
1032          
1033      }
1034      catch (Throwable JavaDoc throwable)
1035      {
1036        while (throwable
1037               instanceof org.apache.xml.utils.WrappedRuntimeException)
1038        {
1039          throwable =
1040            ((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
1041        }
1042
1043        if ((throwable instanceof NullPointerException JavaDoc)
1044                || (throwable instanceof ClassCastException JavaDoc))
1045          doStackDumpOnError = true;
1046
1047        diagnosticsWriter.println();
1048
1049        if (doStackDumpOnError)
1050          throwable.printStackTrace(dumpWriter);
1051        else
1052        {
1053          DefaultErrorHandler.printLocation(diagnosticsWriter, throwable);
1054          diagnosticsWriter.println(
1055            XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null)
1056            + " (" + throwable.getClass().getName() + "): "
1057            + throwable.getMessage());
1058        }
1059
1060        // diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful.");
1061
if (null != dumpFileName)
1062        {
1063          dumpWriter.close();
1064        }
1065
1066        doExit(-1);
1067      }
1068
1069      if (null != dumpFileName)
1070      {
1071        dumpWriter.close();
1072      }
1073
1074      if (null != diagnosticsWriter)
1075      {
1076
1077        // diagnosticsWriter.close();
1078
}
1079
1080      // if(!setQuietMode)
1081
// diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done");
1082
// else
1083
// diagnosticsWriter.println(""); //"Xalan: done");
1084
}
1085  }
1086  
1087  /** It is _much_ easier to debug under VJ++ if I can set a single breakpoint
1088   * before this blows itself out of the water...
1089   * (I keep checking this in, it keeps vanishing. Grr!)
1090   * */

1091  static void doExit(int i)
1092  {
1093    System.exit(i);
1094  }
1095  
1096  /**
1097   * Wait for a return key to continue
1098   *
1099   * @param resbundle The resource bundle
1100   */

1101  private static void waitForReturnKey(ResourceBundle JavaDoc resbundle)
1102  {
1103    System.out.println(resbundle.getString("xslProc_return_to_continue"));
1104    try
1105    {
1106      while (System.in.read() != '\n');
1107    }
1108    catch (java.io.IOException JavaDoc e) { }
1109  }
1110  
1111  /**
1112   * Print a message if an option cannot be used with -XSLTC.
1113   *
1114   * @param option The option String
1115   */

1116  private static void printInvalidXSLTCOption(String JavaDoc option)
1117  {
1118    System.err.println(XSLMessages.createMessage("xslProc_invalid_xsltc_option", new Object JavaDoc[]{option}));
1119  }
1120  
1121  /**
1122   * Print a message if an option can only be used with -XSLTC.
1123   *
1124   * @param option The option String
1125   */

1126  private static void printInvalidXalanOption(String JavaDoc option)
1127  {
1128    System.err.println(XSLMessages.createMessage("xslProc_invalid_xalan_option", new Object JavaDoc[]{option}));
1129  }
1130}
1131
Popular Tags