Debian Codegraph @

net/sf/saxon/Transform.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon;
9
10 import net.sf.saxon.expr.instruct.Executable;
11 import net.sf.saxon.expr.instruct.GlobalContextRequirement;
12 import net.sf.saxon.expr.instruct.TerminationException;
13 import net.sf.saxon.lib.*;
14 import net.sf.saxon.s9api.*;
15 import net.sf.saxon.style.StylesheetPackage;
16 import net.sf.saxon.trace.AbstractTraceListener;
17 import net.sf.saxon.trace.Instrumentation;
18 import net.sf.saxon.trace.TimingCodeInjector;
19 import net.sf.saxon.trace.TimingTraceListener;
20 import net.sf.saxon.trans.CommandLineOptions;
21 import net.sf.saxon.trans.CompilerInfo;
22 import net.sf.saxon.trans.LicenseException;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.trans.packages.PackageDetails;
25 import net.sf.saxon.trans.packages.PackageLibrary;
26 import net.sf.saxon.value.DateTimeValue;
27 import org.xml.sax.InputSource;
28 import org.xml.sax.XMLReader;
29
30 import javax.xml.transform.OutputKeys;
31 import javax.xml.transform.Source;
32 import javax.xml.transform.TransformerException;
33 import javax.xml.transform.TransformerFactoryConfigurationError;
34 import javax.xml.transform.sax.SAXSource;
35 import javax.xml.transform.stream.StreamSource;
36 import java.io.File;
37 import java.io.FileOutputStream;
38 import java.net.URI;
39 import java.net.URISyntaxException;
40 import java.util.*;
41
42 /**
43 * This <b>Transform</b> class is the command-line entry point to the Saxon XSLT Processor.
44 * <p>It is possible to subclass this class to provide a customized command line interface. In writing such
45 * a subclass:</p>
46 * <ul>
47 * <li>The {@link #main} method should instantiate the class and call the {@link #doTransform} method, passing the
48 * argument list. The argument list can be augmented or modified if required: for example, by adding a -config
49 * argument to cause the configuration to be initialized from a configuration file.</li>
50 * <li>The {@link #initializeConfiguration} method can be implemented to customize the configuration in which
51 * the transformation will run.</li>
52 * </ul>
53 */
54
55 public class Transform {
56
57 protected Processor processor;
58 protected XsltCompiler compiler;
59 protected boolean useURLs = false;
60 protected boolean showTime = false;
61 protected int repeat = 1;
62 /*@Nullable*/ protected String sourceParserName = null;
63 protected boolean schemaAware = false;
64 protected boolean allowExit = true;
65 protected boolean run = true;
66
67 /**
68 * Main program, can be used directly from the command line.
69 * <p>The format is:</p>
70 * <p>java net.sf.saxon.Transform [options] <I>source-file</I> <I>style-file</I> &gt;<I>output-file</I></p>
71 * <p>followed by any number of parameters in the form {keyword=value}... which can be
72 * referenced from within the stylesheet.</p>
73 * <p>This program applies the XSL style sheet in style-file to the source XML document in source-file.</p>
74 *
75 * @param args List of arguments supplied on operating system command line
76 */
77
78 public static void main(String args[]) {
79 // the real work is delegated to another routine so that it can be used in a subclass
80 new Transform().doTransform(args, "java net.sf.saxon.Transform");
81 }
82
83 /**
84 * Set the options that are recognized on the command line. This method can be overridden in a subclass
85 * to define additional command line options.
86 *
87 * @param options the CommandLineOptions in which the recognized options are to be registered.
88 */
89
90 public void setPermittedOptions(CommandLineOptions options) {
91 options.addRecognizedOption("a", CommandLineOptions.TYPE_BOOLEAN,
92 "Use <?xml-stylesheet?> processing instruction to identify stylesheet");
93 options.addRecognizedOption("catalog", CommandLineOptions.TYPE_FILENAME | CommandLineOptions.VALUE_REQUIRED,
94 "Use specified catalog file to resolve URIs");
95 options.addRecognizedOption("config", CommandLineOptions.TYPE_FILENAME | CommandLineOptions.VALUE_REQUIRED,
96 "Use specified configuration file");
97 options.addRecognizedOption("cr", CommandLineOptions.TYPE_CLASSNAME | CommandLineOptions.VALUE_REQUIRED,
98 "Use specified collection URI resolver class");
99 options.addRecognizedOption("diag", CommandLineOptions.TYPE_FILENAME,
100 "Display runtime diagnostics");
101 options.addRecognizedOption("dtd", CommandLineOptions.TYPE_ENUMERATION,
102 "Validate using DTD");
103 options.setPermittedValues("dtd", new String[]{"on", "off", "recover"}, "on");
104 options.addRecognizedOption("ea", CommandLineOptions.TYPE_BOOLEAN,
105 "Enable assertions");
106 options.addRecognizedOption("expand", CommandLineOptions.TYPE_BOOLEAN,
107 "Expand attribute defaults from DTD or Schema");
108 options.addRecognizedOption("explain", CommandLineOptions.TYPE_FILENAME,
109 "Display compiled expression tree and optimization decisions in human-readable form");
110 options.addRecognizedOption("export", CommandLineOptions.TYPE_FILENAME,
111 "Display compiled expression tree and optimization decisions for exportation");
112 options.addRecognizedOption("ext", CommandLineOptions.TYPE_BOOLEAN,
113 "Allow calls to Java extension functions and xsl:result-document");
114 options.addRecognizedOption("im", CommandLineOptions.TYPE_QNAME | CommandLineOptions.VALUE_REQUIRED,
115 "Name of initial mode");
116 options.addRecognizedOption("init", CommandLineOptions.TYPE_CLASSNAME,
117 "User-supplied net.sf.saxon.lib.Initializer class to initialize the Saxon Configuration");
118 options.addRecognizedOption("it", CommandLineOptions.TYPE_QNAME,
119 "Name of initial template");
120 options.addRecognizedOption("jit", CommandLineOptions.TYPE_BOOLEAN,
121 "Just-in-time compilation");
122 options.addRecognizedOption("l", CommandLineOptions.TYPE_BOOLEAN,
123 "Maintain line numbers for source documents");
124 options.addRecognizedOption("lib", CommandLineOptions.TYPE_FILENAME_LIST | CommandLineOptions.VALUE_REQUIRED,
125 "List of file names of library packages used by the stylesheet");
126 options.addRecognizedOption("license", CommandLineOptions.TYPE_BOOLEAN,
127 "Check for local license file");
128 options.addRecognizedOption("m", CommandLineOptions.TYPE_CLASSNAME,
129 "Use named class to handle xsl:message output");
130 options.addRecognizedOption("nogo", CommandLineOptions.TYPE_BOOLEAN,
131 "Compile only, no evaluation");
132 options.addRecognizedOption("now", CommandLineOptions.TYPE_DATETIME | CommandLineOptions.VALUE_REQUIRED,
133 "Run with specified current date/time");
134 options.addRecognizedOption("o", CommandLineOptions.TYPE_FILENAME | CommandLineOptions.VALUE_REQUIRED,
135 "Use specified file for primary output");
136 options.addRecognizedOption("opt", CommandLineOptions.TYPE_STRING | CommandLineOptions.VALUE_REQUIRED,
137 "Enable/disable optimization options [-]cfgjklmrsvwx");
138 options.addRecognizedOption("or", CommandLineOptions.TYPE_CLASSNAME | CommandLineOptions.VALUE_REQUIRED,
139 "Use named OutputURIResolver class");
140 options.addRecognizedOption("outval", CommandLineOptions.TYPE_ENUMERATION | CommandLineOptions.VALUE_REQUIRED,
141 "Action when validation of output file fails");
142 options.setPermittedValues("outval", new String[]{"recover", "fatal"}, null);
143 options.addRecognizedOption("p", CommandLineOptions.TYPE_BOOLEAN,
144 "Recognize query parameters in URI passed to doc()");
145
146 options.addRecognizedOption("quit", CommandLineOptions.TYPE_BOOLEAN | CommandLineOptions.VALUE_REQUIRED,
147 "Quit JVM if transformation fails");
148 options.addRecognizedOption("r", CommandLineOptions.TYPE_CLASSNAME | CommandLineOptions.VALUE_REQUIRED,
149 "Use named URIResolver class");
150 options.addRecognizedOption("relocate", CommandLineOptions.TYPE_BOOLEAN,
151 "Produce relocatable packages");
152 options.addRecognizedOption("repeat", CommandLineOptions.TYPE_INTEGER | CommandLineOptions.VALUE_REQUIRED,
153 "Run N times for performance measurement");
154 options.addRecognizedOption("s", CommandLineOptions.TYPE_FILENAME | CommandLineOptions.VALUE_REQUIRED,
155 "Source file for primary input");
156 options.addRecognizedOption("sa", CommandLineOptions.TYPE_BOOLEAN,
157 "Run in schema-aware mode");
158 options.addRecognizedOption("scmin", CommandLineOptions.TYPE_FILENAME,
159 "Pre-load schema in SCM format");
160 options.addRecognizedOption("strip", CommandLineOptions.TYPE_ENUMERATION | CommandLineOptions.VALUE_REQUIRED,
161 "Handling of whitespace text nodes in source documents");
162 options.setPermittedValues("strip", new String[]{"none", "all", "ignorable"}, null);
163 options.addRecognizedOption("t", CommandLineOptions.TYPE_BOOLEAN,
164 "Display version and timing information, and names of output files");
165 options.addRecognizedOption("target", CommandLineOptions.TYPE_ENUMERATION | CommandLineOptions.VALUE_REQUIRED,
166 "Target Saxon edition for execution via -export");
167 options.setPermittedValues("target", new String[]{"EE", "PE", "HE", "JS", "JS2"}, null);
168 options.addRecognizedOption("T", CommandLineOptions.TYPE_CLASSNAME,
169 "Use named TraceListener class, or standard TraceListener");
170 options.addRecognizedOption("TB", CommandLineOptions.TYPE_FILENAME,
171 "Trace hotspot bytecode generation to specified XML file");
172 options.addRecognizedOption("TJ", CommandLineOptions.TYPE_BOOLEAN,
173 "Debug binding and execution of extension functions");
174 options.setPermittedValues("TJ", new String[]{"on", "off"}, "on");
175 options.addRecognizedOption("Tlevel", CommandLineOptions.TYPE_STRING,
176 "Level of detail for trace listener output");
177 options.setPermittedValues("Tlevel", new String[]{"none", "low", "normal", "high"}, "normal");
178 options.addRecognizedOption("Tout", CommandLineOptions.TYPE_FILENAME,
179 "File for trace listener output");
180 options.addRecognizedOption("TP", CommandLineOptions.TYPE_FILENAME,
181 "Use profiling trace listener, with specified output file");
182 options.addRecognizedOption("threads", CommandLineOptions.TYPE_INTEGER | CommandLineOptions.VALUE_REQUIRED,
183 "Run stylesheet on directory of files divided in N threads");
184 options.addRecognizedOption("tree", CommandLineOptions.TYPE_ENUMERATION | CommandLineOptions.VALUE_REQUIRED,
185 "Use specified tree model for source documents");
186 options.setPermittedValues("tree", new String[]{"linked", "tiny", "tinyc"}, null);
187 options.addRecognizedOption("traceout", CommandLineOptions.TYPE_FILENAME | CommandLineOptions.VALUE_REQUIRED,
188 "File for output of trace() and -T output");
189 options.addRecognizedOption("u", CommandLineOptions.TYPE_BOOLEAN,
190 "Interpret filename arguments as URIs");
191 options.setPermittedValues("u", new String[]{"on", "off"}, "on");
192 options.addRecognizedOption("val", CommandLineOptions.TYPE_ENUMERATION | CommandLineOptions.VALUE_REQUIRED,
193 "Apply validation to source documents");
194 options.setPermittedValues("val", new String[]{"strict", "lax"}, "strict");
195 options.addRecognizedOption("versionmsg", CommandLineOptions.TYPE_BOOLEAN,
196 "No longer used");
197 options.addRecognizedOption("warnings", CommandLineOptions.TYPE_ENUMERATION | CommandLineOptions.VALUE_REQUIRED,
198 "Handling of recoverable dynamic errors");
199 options.setPermittedValues("warnings", new String[]{"silent", "recover", "fatal"}, null);
200 options.addRecognizedOption("x", CommandLineOptions.TYPE_CLASSNAME | CommandLineOptions.VALUE_REQUIRED,
201 "Use named XMLReader class for parsing source documents");
202 options.addRecognizedOption("xi", CommandLineOptions.TYPE_BOOLEAN,
203 "Expand XInclude directives in source documents");
204 options.addRecognizedOption("xmlversion", CommandLineOptions.TYPE_ENUMERATION | CommandLineOptions.VALUE_REQUIRED,
205 "Indicate whether XML 1.1 is supported");
206 options.setPermittedValues("xmlversion", new String[]{"1.0", "1.1"}, null);
207 options.addRecognizedOption("xsd", CommandLineOptions.TYPE_FILENAME_LIST | CommandLineOptions.VALUE_REQUIRED,
208 "List of schema documents to be preloaded");
209 options.addRecognizedOption("xsdversion", CommandLineOptions.TYPE_ENUMERATION | CommandLineOptions.VALUE_REQUIRED,
210 "Indicate whether XSD 1.1 is supported");
211 options.setPermittedValues("xsdversion", new String[]{"1.0", "1.1"}, null);
212 options.addRecognizedOption("xsiloc", CommandLineOptions.TYPE_BOOLEAN,
213 "Load schemas named in xsi:schemaLocation (default on)");
214 options.addRecognizedOption("xsl", CommandLineOptions.TYPE_FILENAME | CommandLineOptions.VALUE_REQUIRED,
215 "Main stylesheet file");
216 options.addRecognizedOption("y", CommandLineOptions.TYPE_CLASSNAME | CommandLineOptions.VALUE_REQUIRED,
217 "Use named XMLReader class for parsing stylesheet and schema documents");
218 options.addRecognizedOption("?", CommandLineOptions.VALUE_PROHIBITED,
219 "Display command line help text");
220
221 }
222
223
224 class TransformThread extends Thread {
225 private File outputDir;
226 private XsltExecutable sheet;
227 private CommandLineOptions options;
228 private Logger traceDestination;
229 private List<Source> sources;
230 private int start;
231
232 TransformThread(int i, XsltExecutable st, List<Source> s, File out, CommandLineOptions opt, Logger trace) {
233 start = i;
234 sheet = st;
235 sources = s;
236 options = opt;
237 outputDir = out;
238 traceDestination = trace;
239 }
240
241 public long getStart() {
242 return start;
243 }
244
245 @Override
246 public void run() {
247 try {
248 processDirectory(sources, sheet, outputDir, options, traceDestination);
249 } catch (Exception err) {
250 err.printStackTrace();
251 }
252 }
253
254 }
255
256
257 /**
258 * Support method for main program. This support method can also be invoked from subclasses
259 * that support the same command line interface
260 *
261 * @param args the command-line arguments
262 * @param command the form of the command as written by the user. Not used, retained for backwards compatibility
263 */
264
265 public void doTransform(String args[], String command) {
266
267 Configuration config;
268 String sourceFileName = null;
269 String styleFileName = null;
270 String packageCatalogName = null;
271 File outputFile = null;
272 String outputFileName = null;
273 boolean useAssociatedStylesheet;
274 boolean wholeDirectory = false;
275 boolean dtdValidation = false;
276 String styleParserName = null;
277 boolean explain = false;
278 boolean export = false;
279 String explainOutputFileName = null;
280 String exportOutputFileName = null;
281 String additionalSchemas = null;
282 Logger traceDestination = null; // project:preconditions
283 TraceListener traceListener = null;
284 boolean closeTraceDestination = false;
285 TransformThread[] th = null;
286 int threadCount = 0;
287 boolean jit = true;
288
289 CommandLineOptions options = new CommandLineOptions();
290 setPermittedOptions(options);
291 try {
292 options.setActualOptions(args);
293 } catch (XPathException err) {
294 quit(err.getMessage(), 2);
295 }
296
297
298 schemaAware = false;
299 String configFile = options.getOptionValue("config");
300 if (configFile != null) {
301 try {
302 config = Configuration.readConfiguration(new StreamSource(configFile));
303 initializeConfiguration(config);
304 processor = new Processor(config);
305 schemaAware = config.isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XSLT);
306 } catch (XPathException e) {
307 quit(e.getMessage(), 2);
308 }
309 }
310
311 if (processor == null && !schemaAware) {
312 schemaAware = options.testIfSchemaAware();
313 }
314
315 if (processor == null) {
316 processor = new Processor(true);
317 config = processor.getUnderlyingConfiguration();
318 initializeConfiguration(config);
319 //config.setVersionWarning(true); // unless suppressed by command line options
320 try {
321 setFactoryConfiguration(schemaAware, null);
322 CompilerInfo defaultCompilerInfo = config.getDefaultXsltCompilerInfo();
323 if (schemaAware) {
324 defaultCompilerInfo.setSchemaAware(true);
325 } else {
326 defaultCompilerInfo.setSchemaAware(false);
327 }
328 } catch (Exception err) {
329 err.printStackTrace();
330 quit(err.getMessage(), 2);
331 }
332 }
333
334 config = processor.getUnderlyingConfiguration();
335
336 // Process the named options
337
338 try {
339
340 // Apply those options which simply update the Configuration
341
342 options.applyToConfiguration(processor);
343
344 // Now create the XsltCompiler (it will pick up options from the configuration)
345
346 compiler = processor.newXsltCompiler();
347
348 // Apply options that are processed locally
349
350 allowExit = !"off".equals(options.getOptionValue("quit"));
351
352 useAssociatedStylesheet = "on".equals(options.getOptionValue("a"));
353
354 String value = options.getOptionValue("explain");
355 if (value != null) {
356 explain = true;
357 processor.setConfigurationProperty(Feature.TRACE_OPTIMIZER_DECISIONS, true);
358 jit = false;
359 compiler.setJustInTimeCompilation(jit);
360 if (!"".equals(value)) {
361 explainOutputFileName = value;
362 }
363 }
364 value = options.getOptionValue("export");
365 if (value != null) {
366 export = true;
367 jit = false;
368 compiler.setJustInTimeCompilation(jit);
369 if (!"".equals(value)) {
370 exportOutputFileName = value;
371 }
372 }
373
374 value = options.getOptionValue("target");
375 if (value != null) {
376 compiler.setTargetEdition(value);
377 }
378 value = options.getOptionValue("relocate");
379 if (value != null && !"off".equals(value)) {
380 compiler.setRelocatable(true);
381 }
382
383 value = options.getOptionValue("jit");
384 if (value != null) {
385 if ("on".equals(value) && exportOutputFileName == null && run) {
386 if (export) {
387 jit = false;
388 System.err.println("Warning: -jit:on is ignored when -export:on is set");
389 } else {
390 jit = true;
391 }
392 } else if ("off".equals(value)) {
393 jit = false;
394 }
395 compiler.setJustInTimeCompilation(jit);
396
397 }
398
399 value = options.getOptionValue("lib");
400 if (value != null) {
401 StringTokenizer st = new StringTokenizer(value, File.pathSeparator);
402 Set<File> packs = new HashSet<>();
403 while (st.hasMoreTokens()) {
404 String n = st.nextToken();
405 packs.add(new File(n));
406 }
407 PackageLibrary lib = null;
408 try {
409 lib = new PackageLibrary(compiler.getUnderlyingCompilerInfo(), packs);
410 } catch (XPathException e) {
411 quit(e.getMessage(), 2);
412 }
413 compiler.getUnderlyingCompilerInfo().setPackageLibrary(lib);
414 }
415
416 value = options.getOptionValue("o");
417 if (value != null) {
418 outputFileName = value;
419 }
420
421 value = options.getOptionValue("nogo");
422 if (value != null) {
423 if (jit) {
424 jit = false;
425 System.err.println("Warning: -jit:on is ignored when -nogo is set");
426 }
427 run = false;
428 compiler.setJustInTimeCompilation(false);
429 }
430
431 value = options.getOptionValue("p");
432 if ("on".equals(value)) {
433 config.setParameterizedURIResolver();
434 useURLs = true;
435 }
436
437 value = options.getOptionValue("repeat");
438 if (value != null) {
439 try {
440 repeat = Integer.parseInt(value);
441 } catch (NumberFormatException err) {
442 badUsage("Bad number after -repeat");
443 }
444 }
445
446 value = options.getOptionValue("s");
447 if (value != null) {
448 sourceFileName = value;
449 }
450
451 value = options.getOptionValue("threads");
452 if (value != null) {
453 threadCount = Integer.parseInt(value);
454 }
455
456 value = options.getOptionValue("t");
457 if (value != null) {
458 System.err.println(config.getProductTitle());
459 System.err.println(Version.platform.getPlatformVersion());
460 processor.setConfigurationProperty(Feature.TIMING, true);
461 showTime = true;
462 }
463
464 value = options.getOptionValue("T");
465 if (value != null) {
466
467 if ("".equals(value)) {
468 traceListener = new net.sf.saxon.trace.XSLTTraceListener();
469 } else {
470 traceListener = config.makeTraceListener(value);
471 }
472 processor.setConfigurationProperty(Feature.TRACE_LISTENER, traceListener);
473 processor.setConfigurationProperty(Feature.LINE_NUMBERING, true);
474
475 String dest = options.getOptionValue("Tout");
476 if (dest != null) {
477 traceListener.setOutputDestination(new StandardLogger(new File(dest)));
478 }
479
480 value = options.getOptionValue("Tlevel");
481 if (value != null && traceListener instanceof AbstractTraceListener) {
482 switch (value) {
483 case "none":
484 ((AbstractTraceListener) traceListener).setLevelOfDetail(0);
485 break;
486 case "low":
487 ((AbstractTraceListener) traceListener).setLevelOfDetail(1);
488 break;
489 case "normal":
490 ((AbstractTraceListener) traceListener).setLevelOfDetail(2);
491 break;
492 case "high":
493 ((AbstractTraceListener) traceListener).setLevelOfDetail(3);
494 break;
495 }
496 }
497
498 }
499
500 value = options.getOptionValue("TB");
501 if (value != null) {
502 // Trace hotspot byte code generation and produce a report.
503 config.setBooleanProperty(Feature.MONITOR_HOT_SPOT_BYTE_CODE, true);
504 }
505
506 value = options.getOptionValue("TP");
507 if (value != null) {
508 traceListener = new TimingTraceListener();
509 processor.setConfigurationProperty(Feature.TRACE_LISTENER, traceListener);
510 processor.setConfigurationProperty(Feature.LINE_NUMBERING, true);
511 compiler.getUnderlyingCompilerInfo().setCodeInjector(new TimingCodeInjector());
512 if (!value.isEmpty()) {
513 traceListener.setOutputDestination(
514 new StandardLogger(new File(value)));
515 }
516 }
517
518 value = options.getOptionValue("traceout");
519 if (value == null) {
520 if (traceDestination == null) {
521 traceDestination = config.getLogger();
522 }
523 } else {
524 switch (value) {
525 case "#err":
526 traceDestination = new StandardLogger();
527 break;
528 case "#out":
529 traceDestination = new StandardLogger(System.out);
530 break;
531 case "#null":
532 traceDestination = null;
533 break;
534 default:
535 traceDestination = new StandardLogger(new File(value));
536 closeTraceDestination = true;
537 break;
538 }
539 }
540
541 value = options.getOptionValue("u");
542 if (value != null) {
543 useURLs = "on".equals(value);
544 }
545
546 value = options.getOptionValue("x");
547 if (value != null) {
548 sourceParserName = value;
549 processor.setConfigurationProperty(Feature.SOURCE_PARSER_CLASS, sourceParserName);
550 }
551
552 value = options.getOptionValue("xsd");
553 if (value != null) {
554 additionalSchemas = value;
555 }
556
557 value = options.getOptionValue("xsdversion");
558 if (value != null) {
559 processor.setConfigurationProperty(Feature.XSD_VERSION, value);
560 }
561
562 value = options.getOptionValue("xsl");
563 if (value != null) {
564 styleFileName = value;
565 }
566
567 value = options.getOptionValue("y");
568 if (value != null) {
569 styleParserName = value;
570 processor.setConfigurationProperty(Feature.STYLE_PARSER_CLASS, value);
571 }
572
573 value = options.getOptionValue("?");
574 if (value != null) {
575 badUsage("");
576 }
577
578
579 // Check for a license if appropriate
580
581 if (!config.getEditionCode().equals("HE")) {
582 String lic = options.getOptionValue("license");
583 if (lic == null || "on".equals(lic)) {
584 config.displayLicenseMessage();
585 } else {
586 config.disableLicensing();
587 }
588 }
589
590
591 //compilerInfo.setRecoveryPolicy(config.getRecoveryPolicy());
592
593 // Apply options defined locally in a subclass
594
595 applyLocalOptions(options, config);
596
597 // Check consistency of selected options
598
599 if (options.getOptionValue("it") != null && useAssociatedStylesheet) {
600 badUsage("-it and -a options cannot be used together");
601 }
602
603 List<String> positional = options.getPositionalOptions();
604 int currentPositionalOption = 0;
605
606 if (run && options.getOptionValue("it") == null && sourceFileName == null) {
607 if (positional.size() == currentPositionalOption) {
608 badUsage("No source file name");
609 }
610 sourceFileName = positional.get(currentPositionalOption++);
611 }
612
613 if (!useAssociatedStylesheet && styleFileName == null) {
614 if (positional.size() == currentPositionalOption) {
615 badUsage("No stylesheet file name");
616 }
617 styleFileName = positional.get(currentPositionalOption++);
618 }
619
620 if (currentPositionalOption < positional.size()) {
621 badUsage("Unrecognized option: " + positional.get(currentPositionalOption));
622 }
623
624 // config.displayLicenseMessage();
625 // if (schemaAware) {
626 // config.checkLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XSLT, "schema-aware XSLT", -1);
627 // }
628
629 // if (traceListener instanceof AbstractTraceListener && traceDestination != null) {
630 // traceListener.setOutputDestination(traceDestination);
631 // }
632
633 value = options.getOptionValue("scmin");
634 if (value != null) {
635 config.importComponents(new StreamSource(value));
636 }
637
638 if (additionalSchemas != null) {
639 CommandLineOptions.loadAdditionalSchemas(config, additionalSchemas);
640 }
641
642 options.applyStaticParams(compiler);
643
644 List<Source> sources = new ArrayList<>();
645 if (sourceFileName != null) {
646 boolean useSAXSource = sourceParserName != null || dtdValidation;
647 wholeDirectory = CommandLineOptions.loadDocuments(sourceFileName, useURLs, processor, useSAXSource, sources);
648
649 sources = preprocess(sources);
650 if (wholeDirectory) {
651 if (outputFileName == null) {
652 quit("To process a directory, -o must be specified", 2);
653 } else if (outputFileName.equals(sourceFileName)) {
654 quit("Output directory must be different from input", 2);
655 } else {
656 outputFile = new File(outputFileName);
657 if (!outputFile.isDirectory()) {
658 quit("Input is a directory, but output is not", 2);
659 }
660 }
661 }
662 }
663
664 if (outputFileName != null && !wholeDirectory) {
665 outputFile = new File(outputFileName);
666 if (outputFile.isDirectory()) {
667 quit("Output is a directory, but input is not", 2);
668 }
669 }
670
671 if (useAssociatedStylesheet) {
672 if (wholeDirectory) {
673 processDirectoryAssoc(sources, outputFile, options, traceDestination);
674 } else {
675 processFileAssoc(sources.get(0), null, outputFile, options,
676 traceDestination);
677 }
678 } else {
679
680 long startTime = now();
681
682 boolean isURI = useURLs || CommandLineOptions.isImplicitURI(styleFileName);
683 XsltExecutable sheet = null;
684
685 Source styleSource = null;
686 XMLReader styleParser = null;
687
688 if (isURI) {
689 styleSource = config.getURIResolver().resolve(styleFileName, null);
690 if (styleSource == null) {
691 styleSource = config.getSystemURIResolver().resolve(styleFileName, null);
692 }
693 } else if (styleFileName.equals("-")) {
694 // take input from stdin
695 String sysID = new File(System.getProperty("user.dir")).toURI().toASCIIString();
696 if (styleParserName == null) {
697 styleSource = new StreamSource(System.in, sysID);
698 } else if (Version.platform.isJava()) {
699 styleParser = config.getStyleParser();
700 final InputSource inputSource = new InputSource(System.in);
701 inputSource.setSystemId(sysID);
702 styleSource = new SAXSource(styleParser, inputSource);
703 } else {
704 styleSource = new StreamSource(System.in, sysID);
705 }
706 } else {
707 PackageLibrary library = config.getDefaultXsltCompilerInfo().getPackageLibrary();
708 PackageDetails details = library.findDetailsForAlias(styleFileName);
709 if (details != null) {
710 XsltPackage pack = compiler.obtainPackageWithAlias(styleFileName);
711 sheet = pack.link();
712 } else {
713 File sheetFile = new File(styleFileName);
714 if (!sheetFile.exists()) {
715 quit("Stylesheet file " + sheetFile + " does not exist", 2);
716 }
717 if (styleParserName == null) {
718 styleSource = new StreamSource(sheetFile.toURI().toString());
719 } else {
720 InputSource eis = new InputSource(sheetFile.toURI().toString());
721 styleParser = config.getStyleParser();
722 styleSource = new SAXSource(styleParser, eis);
723 }
724 }
725 }
726
727 if (styleSource == null && sheet == null) {
728 quit("URIResolver for stylesheet file must return a Source", 2);
729 }
730
731
732 if (sheet == null) {
733 int repeatComp = repeat;
734 if (repeatComp > 20) {
735 repeatComp = 20;
736 }
737 for (int j = 0; j < repeatComp; j++) {
738 // Repeat loop is to get reliable performance data
739
740 ///////////////////////////////////////
741 sheet = compiler.compile(styleSource);
742 ///////////////////////////////////////
743 if (schemaAware) {
744 int licenseId = sheet.getUnderlyingCompiledStylesheet().
745 getTopLevelPackage().getLocalLicenseId();
746 config.checkLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XSLT, "schema-aware XSLT", licenseId);
747 }
748 if (styleParser != null) {
749 config.reuseStyleParser(styleParser);
750 // pointless, because the Configuration won't be used again; but we want to set a good example
751 }
752 if (showTime) {
753 long endTime = now();
754 System.err.println("Stylesheet compilation time: " + CommandLineOptions.showExecutionTimeNano(endTime - startTime));
755 startTime = endTime;
756 }
757 }
758 }
759
760 if (explain) {
761 Serializer out;
762 if (explainOutputFileName == null) {
763 out = processor.newSerializer(System.err);
764 } else {
765 out = processor.newSerializer(new File(explainOutputFileName));
766 }
767 out.setOutputProperty(Serializer.Property.METHOD, "xml");
768 out.setOutputProperty(Serializer.Property.INDENT, "yes");
769 out.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
770 if (config.isLicensedFeature(Configuration.LicenseFeature.PROFESSIONAL_EDITION)) {
771 out.setOutputProperty(Serializer.Property.SAXON_INDENT_SPACES, "2");
772 }
773 sheet.explain(out);
774 }
775 if (export) {
776 sheet.export(new FileOutputStream(exportOutputFileName));
777 if (showTime) {
778 System.err.println("Stylesheet exported to: " + new File(exportOutputFileName).getAbsolutePath());
779 }
780 }
781
782 if (run) {
783
784 try {
785 if (wholeDirectory) {
786 if ((threadCount > 0) && (sources.size() > 1)) {
787 if (threadCount > sources.size()) {
788 threadCount = sources.size();
789 }
790
791 //calculate sources per thread
792 int sourcesPerThread = (int) Math.floor(sources.size() / threadCount);
793
794 //split remainder of sources amongst rem threads
795 int rem = sources.size() % threadCount;
796 th = new TransformThread[threadCount];
797 // long elapsedTime = System.nanoTime();
798 for (int i = 0, j = 0, z = 0; i < sources.size(); j++, i += sourcesPerThread + z) {
799 z = j < rem ? 1 : 0; //split remainder of sources amongst rem threads
800 th[j] = new TransformThread(i, sheet, sources.subList(i, i + sourcesPerThread + z), outputFile, options, traceDestination);
801 th[j].start();
802 }
803 for (TransformThread aTh : th) {
804 aTh.join();
805 }
806 // elapsedTime = System.nanoTime() - elapsedTime;
807 // System.out.println("Total Elapsed Time: "+elapsedTime/1e6 + "ms");
808
809
810 } else {
811 processDirectory(sources, sheet, outputFile, options, traceDestination);
812 }
813 } else {
814 Source source = sources == null || sources.isEmpty() ? null : sources.get(0);
815 processFile(source, sheet, outputFile, options, traceDestination);
816 }
817 } finally {
818 if (closeTraceDestination && traceDestination != null) {
819 traceDestination.close();
820 }
821 }
822
823 }
824 if (options.getOptionValue("TB")!=null) {
825 // report on hotspot bytecode generation
826 config.createByteCodeReport(options.getOptionValue("TB"));
827 }
828 }
829 } catch (TerminationException err) {
830 quit(err.getMessage(), 1);
831 } catch (SaxonApiException err) {
832 //err.printStackTrace();
833 quit(err.getMessage(), 2);
834 } catch (TransformerException | LicenseException | TransformerFactoryConfigurationError err) {
835 //err.printStackTrace();
836 quit("Transformation failed: " + err.getMessage(), 2);
837 } catch (Exception err2) {
838 err2.printStackTrace();
839 quit("Fatal error during transformation: " + err2.getClass().getName() + ": " +
840 (err2.getMessage() == null ? " (no message)" : err2.getMessage()), 2);
841 }
842 }
843
844
845 /**
846 * Customisation hook called immediately after the Configuration
847 * object is instantiated. The intended purpose of this hook is to allow
848 * a subclass to supply an OEM license key programmatically, but it can also
849 * be used for other initialization of the Configuration. This method is
850 * called before analyzing the command line options, so configuration settings
851 * made at this stage may be overridden when the command line options are processed.
852 * However, if a configuration file is used, the settings defined in the configuration
853 * file will have been applied.
854 *
855 * @param config the Configuration object
856 */
857
858 protected void initializeConfiguration(Configuration config) {
859 // no action: provided for subclasses to override
860 }
861
862 /**
863 * Customisation hook called immediately after the Configuration
864 * object is instantiated. This hook is retained for backwards
865 * compatibility but it is recommended to implement {@link #initializeConfiguration}
866 * in preference. This method is called after {@link #initializeConfiguration},
867 * but only if the configuration was not created using a configuration file.
868 * The default implementation does nothing.
869 *
870 * @param schemaAware True if the transformation is to be schema-aware
871 * @param className Always null.
872 * @throws LicenseException can be thrown if there is no valid license available
873 */
874
875 public void setFactoryConfiguration(boolean schemaAware, String className) throws LicenseException {
876 // no action
877 }
878
879 /**
880 * Customisation hook: apply options defined locally in a subclass. This method
881 * allows a subclass to recognize and implement command line options that are not recognized
882 * by the superclass. To prevent Saxon rejecting such options as errors, the method
883 * {@link #setPermittedOptions} must be overridden in the subclass to add details of
884 * options recognized in the subclass.
885 *
886 * @param options the CommandLineOptions. This will contain details of all the options
887 * that were specified on the command line. Those that are recognized by the standard Saxon
888 * command line interface will already have been processed; other options can now be processed
889 * by the subclass.
890 * @param config the Saxon Configuration
891 */
892
893 protected void applyLocalOptions(CommandLineOptions options, Configuration config) {
894 // no action: provided for subclasses to override
895 }
896
897
898 /**
899 * Preprocess the list of sources. This method exists so that it can be
900 * overridden in a subclass, typically to handle kinds of Source implemented as
901 * extensions to the basic Saxon capability
902 *
903 * @param sources the list of Source objects
904 * @return a revised list of Source objects
905 * @throws XPathException if a Source object is not recognized
906 */
907
908 public List<Source> preprocess(List<Source> sources) throws XPathException {
909 return sources;
910 }
911
912 /**
913 * Get the configuration.
914 *
915 * @return the Saxon configuration
916 */
917
918 protected Configuration getConfiguration() {
919 return processor.getUnderlyingConfiguration();
920 }
921
922 /**
923 * Exit with a message
924 *
925 * @param message The message to be output
926 * @param code The result code to be returned to the operating
927 * system shell
928 */
929
930 protected void quit(String message, int code) {
931 System.err.println(message);
932 if (allowExit) {
933 System.exit(code);
934 } else {
935 throw new RuntimeException(message);
936 }
937 }
938
939 /**
940 * Process each file in the source directory using its own associated stylesheet
941 *
942 * @param sources The sources in the directory to be processed
943 * @param outputDir The directory in which output files are to be
944 * created
945 * @param options Command line options
946 * @param traceDestination output destination for fn:trace() calls
947 * @throws Exception when any error occurs during a transformation
948 */
949
950 private void processDirectoryAssoc(List<Source> sources, File outputDir,
951 CommandLineOptions options, Logger traceDestination)
952 throws Exception {
953
954 int failures = 0;
955 for (Source source : sources) {
956 String localName = getLocalFileName(source);
957 try {
958 processFileAssoc(source, localName, outputDir, options, traceDestination);
959 } catch (SaxonApiException err) {
960 failures++;
961 System.err.println("While processing " + localName +
962 ": " + err.getMessage() + '\n');
963 }
964 }
965 if (failures > 0) {
966 throw new XPathException(failures + " transformation" +
967 (failures == 1 ? "" : "s") + " failed");
968 }
969 }
970
971 /**
972 * Make an output file in the output directory, with filename extension derived from the
973 * media-type produced by the stylesheet
974 *
975 * @param directory The directory in which the file is to be created
976 * @param localName The local name of the file within the
977 * directory, excluding the file type suffix
978 * @param sheet The Templates object identifying the stylesheet -
979 * used to determine the output method, and hence the suffix to be
980 * used for the filename
981 * @return The newly created file
982 */
983
984 private File makeOutputFile(File directory, String localName, XsltExecutable sheet) {
985 String mediaType = sheet.getUnderlyingCompiledStylesheet().getPrimarySerializationProperties().getProperty(OutputKeys.MEDIA_TYPE);
986 String suffix = ".xml";
987 if ("text/html".equals(mediaType)) {
988 suffix = ".html";
989 } else if ("text/plain".equals(mediaType)) {
990 suffix = ".txt";
991 }
992 String prefix = localName;
993 if (localName.endsWith(".xml") || localName.endsWith(".XML")) {
994 prefix = localName.substring(0, localName.length() - 4);
995 }
996 return new File(directory, prefix + suffix);
997 }
998
999
1000 /**
1001 * Process a single source file using its associated stylesheet(s)
1002 *
1003 * @param sourceInput Identifies the source file to be transformed
1004 * @param localName The local name of the file within the
1005 * directory, excluding the file type suffix
1006 * @param outputFile The output file to contain the results of the
1007 * transformation
1008 * @param options Command line options
1009 * @param traceDestination Destination for trace output
1010 * @throws SaxonApiException If the transformation fails
1011 */
1012
1013 private void processFileAssoc(Source sourceInput, String localName, File outputFile,
1014 CommandLineOptions options, Logger traceDestination)
1015 throws SaxonApiException {
1016 if (showTime) {
1017 System.err.println("Processing " + sourceInput.getSystemId() + " using associated stylesheet");
1018 }
1019 long startTime = now();
1020
1021 XdmNode sourceDoc = processor.newDocumentBuilder().build(sourceInput);
1022
1023 Source style = compiler.getAssociatedStylesheet(sourceDoc.asSource(), null, null, null);
1024 XsltExecutable sheet = compiler.compile(style);
1025
1026 if (showTime) {
1027 System.err.println("Prepared associated stylesheet " + style.getSystemId());
1028 }
1029
1030 Xslt30Transformer transformer = newTransformer(sheet, options, traceDestination);
1031
1032 File outFile = outputFile;
1033 if (outFile != null && outFile.isDirectory()) {
1034 outFile = makeOutputFile(outFile, localName, sheet);
1035 }
1036
1037 Serializer serializer =
1038 outputFile == null ?
1039 transformer.newSerializer(System.out) :
1040 transformer.newSerializer(outFile);
1041 try {
1042 options.setSerializationProperties(serializer);
1043 } catch (IllegalArgumentException e) {
1044 quit(e.getMessage(), 2);
1045 }
1046
1047 transformer.setGlobalContextItem(sourceDoc);
1048 transformer.applyTemplates(sourceDoc, serializer);
1049
1050
1051 if (showTime) {
1052 long endTime = now();
1053 System.err.println("Execution time: " + CommandLineOptions.showExecutionTimeNano(endTime - startTime));
1054 }
1055 }
1056
1057 /**
1058 * Create a new Transformer. This method is protected so it can be overridden in a subclass, allowing additional
1059 * options to be set on the Transformer
1060 *
1061 * @param sheet The XsltExecutable object representing the compiled stylesheet
1062 * @param options The commmand line options
1063 * @param traceDestination destination for trace output
1064 * @return the newly constructed Controller to be used for the transformation
1065 * @throws SaxonApiException if any error occurs
1066 */
1067
1068 protected Xslt30Transformer newTransformer(
1069 XsltExecutable sheet, CommandLineOptions options, Logger traceDestination) throws SaxonApiException {
1070 final Xslt30Transformer transformer = sheet.load30();
1071 final Map<QName, XdmValue> params = new HashMap<>();
1072 Executable exec = transformer.getUnderlyingController().getExecutable();
1073 transformer.setTraceFunctionDestination(traceDestination);
1074 String initialMode = options.getOptionValue("im");
1075 if (initialMode != null) {
1076 transformer.setInitialMode(QName.fromClarkName(initialMode));
1077 }
1078
1079 String now = options.getOptionValue("now");
1080 if (now != null) {
1081 try {
1082 DateTimeValue currentDateTime = (DateTimeValue)DateTimeValue.makeDateTimeValue(
1083 now, getConfiguration().getConversionRules()).asAtomic();
1084 transformer.getUnderlyingController().setCurrentDateTime(currentDateTime);
1085 } catch (XPathException e) {
1086 throw new SaxonApiException("Failed to set current time", e);
1087 }
1088 }
1089 // Code to enable/disable assertions at run-time is relevant only when we're running pre-compiled packages
1090 if ("on".equals(options.getOptionValue("ea"))) {
1091 transformer.getUnderlyingController().setAssertionsEnabled(true);
1092 } else if ("off".equals(options.getOptionValue("ea"))) {
1093 transformer.getUnderlyingController().setAssertionsEnabled(true);
1094 }
1095 return transformer;
1096 }
1097
1098 /**
1099 * Get current time in nanoseconds
1100 *
1101 * @return the current time in nanoseconds (since VM startup)
1102 */
1103
1104 protected static long now() {
1105 return System.nanoTime();
1106 }
1107
1108 /**
1109 * Process each file in the source directory using the same supplied stylesheet
1110 *
1111 * @param sources The sources in the directory to be processed
1112 * @param sheet The Templates object identifying the stylesheet
1113 * @param outputDir The directory in which output files are to be
1114 * created
1115 * @param options Command line options
1116 * @param traceDestination Destination for output from fn:trace() calls
1117 * @throws SaxonApiException when any error occurs during a
1118 * transformation
1119 */
1120
1121 private void processDirectory(List<Source> sources, XsltExecutable sheet, File outputDir, CommandLineOptions options,
1122 Logger traceDestination)
1123 throws SaxonApiException {
1124 int failures = 0;
1125 for (Source source : sources) {
1126 String localName = getLocalFileName(source);
1127 try {
1128 File outputFile = makeOutputFile(outputDir, localName, sheet);
1129 processFile(source, sheet, outputFile, options, traceDestination);
1130 } catch (SaxonApiException err) {
1131 failures++;
1132 System.err.println("While processing " + localName + ": " + err.getMessage() + '\n');
1133 }
1134 }
1135 if (failures > 0) {
1136 throw new SaxonApiException(failures + " transformation" +
1137 (failures == 1 ? "" : "s") + " failed");
1138 }
1139 }
1140
1141 private static String getLocalFileName(Source source) {
1142 try {
1143 String path = new URI(source.getSystemId()).getPath();
1144 while (true) {
1145 int sep = path.indexOf('/');
1146 if (sep < 0) {
1147 return path;
1148 } else {
1149 path = path.substring(sep + 1);
1150 }
1151 }
1152 } catch (URISyntaxException err) {
1153 throw new IllegalArgumentException(err.getMessage());
1154 }
1155 }
1156
1157 /**
1158 * Process a single file using a supplied stylesheet
1159 *
1160 * @param source The source XML document to be transformed (maybe null if an initial template
1161 * is specified)
1162 * @param sheet The Templates object identifying the stylesheet
1163 * @param outputFile The output file to contain the results of the
1164 * transformation
1165 * @param options The command line options
1166 * @param traceDestination Destination for output from fn:trace() function
1167 * @throws SaxonApiException If the transformation fails
1168 */
1169
1170 protected void processFile(/*@Nullable*/ Source source, XsltExecutable sheet, /*@Nullable*/ File outputFile, CommandLineOptions options,
1171 Logger traceDestination)
1172 throws SaxonApiException {
1173
1174 long totalTime = 0;
1175 int runs = 0;
1176 int halfway = repeat / 2 - 1;
1177 for (int r = 0; r < repeat; r++) { // repeat is for internal testing/timing
1178 if (showTime) {
1179 String msg = "Processing ";
1180 if (source != null) {
1181 msg += source.getSystemId();
1182 } else {
1183 msg += " (no source document)";
1184 }
1185 String initialMode = options.getOptionValue("im");
1186 if (initialMode != null) {
1187 msg += " initial mode = " + initialMode;
1188 }
1189 String initialTemplate = options.getOptionValue("it");
1190 if (initialTemplate != null) {
1191 msg += " initial template = " + (initialTemplate.isEmpty() ? "xsl:initial-template" : initialTemplate);
1192 }
1193 System.err.println(msg);
1194 }
1195 long startTime = now();
1196 if (r == halfway) {
1197 runs = 0;
1198 totalTime = 0;
1199 }
1200 runs++;
1201
1202 if (r < halfway) {
1203 traceDestination = null;
1204 }
1205 Xslt30Transformer transformer = newTransformer(sheet, options, traceDestination);
1206 Serializer serializer;
1207 if (outputFile == null) {
1208 transformer.setBaseOutputURI(new File(System.getProperty("user.dir")).toURI().toASCIIString());
1209 serializer = transformer.newSerializer(System.out);
1210 }else {
1211 serializer = transformer.newSerializer(outputFile);
1212 }
1213 try {
1214 options.setSerializationProperties(serializer);
1215 } catch (IllegalArgumentException e) {
1216 quit(e.getMessage(), 2);
1217 }
1218
1219 boolean buildResultTree;
1220 String buildTreeProperty = serializer.getOutputProperty(Serializer.Property.BUILD_TREE);
1221 if ("yes".equals(buildTreeProperty)) {
1222 buildResultTree = true;
1223 } else if ("no".equals(buildTreeProperty)) {
1224 buildResultTree = false;
1225 } else {
1226 String method = serializer.getOutputProperty(Serializer.Property.METHOD);
1227 buildResultTree = !("json".equals(method) || "adaptive".equals(method));
1228 }
1229
1230 String initialTemplate = options.getOptionValue("it");
1231
1232 if (source != null) {
1233 PreparedStylesheet pss = sheet.getUnderlyingCompiledStylesheet();
1234 GlobalContextRequirement requirement = pss.getGlobalContextRequirement();
1235 boolean buildSourceTree;
1236 if (requirement == null) {
1237 buildSourceTree = initialTemplate != null ||
1238 !transformer.getUnderlyingController().getInitialMode().isDeclaredStreamable();
1239 } else {
1240 buildSourceTree = !requirement.isAbsentFocus();
1241 }
1242 if (buildSourceTree) {
1243 DocumentBuilder builder = processor.newDocumentBuilder();
1244 StylesheetPackage top = pss.getTopLevelPackage();
1245 if (!top.isStripsTypeAnnotations()) {
1246 int validationMode = getConfiguration().getSchemaValidationMode();
1247 if (validationMode == Validation.STRICT) {
1248 builder.setSchemaValidator(processor.getSchemaManager().newSchemaValidator());
1249 } else if (validationMode == Validation.LAX) {
1250 SchemaValidator validator = processor.getSchemaManager().newSchemaValidator();
1251 validator.setLax(true);
1252 builder.setSchemaValidator(validator);
1253 }
1254 }
1255 builder.setDTDValidation(getConfiguration().getBooleanProperty(Feature.DTD_VALIDATION));
1256 builder.setWhitespaceStrippingPolicy(sheet.getWhitespaceStrippingPolicy());
1257 if (getConfiguration().getBooleanProperty(Feature.DTD_VALIDATION_RECOVERABLE)) {
1258 source = new AugmentedSource(source, getConfiguration().getParseOptions());
1259 }
1260 XdmNode node = builder.build(source);
1261 transformer.setGlobalContextItem(node, true);
1262 source = node.asSource();
1263 }
1264 }
1265
1266 options.applyFileParams(processor, transformer);
1267
1268 if (initialTemplate != null) {
1269 QName initialTemplateName;
1270 if (initialTemplate.isEmpty()) {
1271 initialTemplateName = new QName("xsl", NamespaceConstant.XSLT, "initial-template");
1272 } else {
1273 initialTemplateName = QName.fromClarkName(initialTemplate);
1274 }
1275 if (buildResultTree) {
1276 transformer.callTemplate(initialTemplateName, serializer);
1277 } else {
1278 XdmValue result = transformer.callTemplate(initialTemplateName);
1279 serializer.serializeXdmValue(result);
1280 }
1281 } else {
1282 if (buildResultTree) {
1283 transformer.applyTemplates(source, serializer);
1284 } else {
1285 XdmValue result = transformer.applyTemplates(source);
1286 serializer.serializeXdmValue(result);
1287 }
1288 }
1289
1290 long endTime = now();
1291 totalTime += endTime - startTime;
1292 if (showTime) {
1293 System.err.println("Execution time: " + CommandLineOptions.showExecutionTimeNano(endTime - startTime));
1294 System.err.println("Memory used: " + CommandLineOptions.showMemoryUsed());
1295 if (repeat > 1) {
1296 System.err.println("-------------------------------");
1297 Runtime.getRuntime().gc();
1298 }
1299 if (Instrumentation.ACTIVE) {
1300 Instrumentation.report();
1301 Instrumentation.reset();
1302 }
1303 }
1304 if (repeat == 999999 && totalTime > 60000) {
1305 break;
1306 }
1307 }
1308 if (repeat > 1) {
1309 System.err.println("*** Average execution time over last " + runs + " runs: " +
1310 CommandLineOptions.showExecutionTimeNano(totalTime / runs));
1311 }
1312 }
1313
1314
1315 /**
1316 * Report incorrect usage of the command line, with a list of the options and arguments that are available
1317 *
1318 * @param message The error message
1319 */
1320 protected void badUsage(String message) {
1321 if (!"".equals(message)) {
1322 System.err.println(message);
1323 }
1324 if (!showTime) {
1325 System.err.println(getConfiguration().getProductTitle());
1326 }
1327 System.err.println("Usage: see http://www.saxonica.com/documentation/index.html#!using-xsl/commandline");
1328 System.err.println("Format: " + CommandLineOptions.getCommandName(this) + " options params");
1329 CommandLineOptions options = new CommandLineOptions();
1330 setPermittedOptions(options);
1331 System.err.println("Options available:" + options.displayPermittedOptions());
1332 System.err.println("Use -XYZ:? for details of option XYZ");
1333 System.err.println("Params: ");
1334 System.err.println(" param=value Set stylesheet string parameter");
1335 System.err.println(" +param=filename Set stylesheet document parameter");
1336 System.err.println(" ?param=expression Set stylesheet parameter using XPath");
1337 System.err.println(" !param=value Set serialization parameter");
1338 if (allowExit) {
1339 if ("".equals(message)) {
1340 System.exit(0);
1341 } else {
1342 System.exit(2);
1343 }
1344 } else {
1345 throw new RuntimeException(message);
1346 }
1347 }
1348
1349
1350 }
1351