Debian Codegraph @

net/sf/saxon/trans/CommandLineOptions.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.trans;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.Builder;
12 import net.sf.saxon.expr.number.RegularGroupFormatter;
13 import net.sf.saxon.functions.AccessorFn;
14 import net.sf.saxon.lib.*;
15 import net.sf.saxon.regex.EmptyString;
16 import net.sf.saxon.s9api.*;
17 import net.sf.saxon.tree.util.FastStringBuffer;
18 import net.sf.saxon.type.SchemaException;
19 import net.sf.saxon.value.DayTimeDurationValue;
20 import net.sf.saxon.value.NumericValue;
21 import org.xml.sax.InputSource;
22 import org.xml.sax.XMLReader;
23
24 import javax.xml.transform.Source;
25 import javax.xml.transform.TransformerException;
26 import javax.xml.transform.sax.SAXSource;
27 import javax.xml.transform.stream.StreamSource;
28 import java.io.File;
29 import java.math.BigDecimal;
30 import java.text.Collator;
31 import java.util.*;
32
33 /**
34 * This is a helper class for classes such as net.sf.saxon.Transform and net.sf.saxon.Query that process
35 * command line options
36 */
37 public class CommandLineOptions {
38
39 public static final int TYPE_BOOLEAN = 1;
40 public static final int TYPE_FILENAME = 2;
41 public static final int TYPE_CLASSNAME = 3;
42 public static final int TYPE_ENUMERATION = 4;
43 public static final int TYPE_INTEGER = 5;
44 public static final int TYPE_QNAME = 6;
45 public static final int TYPE_FILENAME_LIST = 7;
46 public static final int TYPE_DATETIME = 8;
47 public static final int TYPE_STRING = 9;
48 public static final int TYPE_INTEGER_PAIR = 10;
49
50 public static final int VALUE_REQUIRED = 1 << 8;
51 public static final int VALUE_PROHIBITED = 2 << 8;
52
53 /*@NotNull*/ HashMap<String, Integer> recognizedOptions = new HashMap<>();
54 /*@NotNull*/ HashMap<String, String> optionHelp = new HashMap<>();
55 /*@NotNull*/ protected Properties namedOptions = new Properties();
56 /*@NotNull*/ Properties configOptions = new Properties();
57 /*@NotNull*/ Map<String, Set<String>> permittedValues = new HashMap<>();
58 /*@NotNull*/ Map<String, String> defaultValues = new HashMap<>();
59 /*@NotNull*/ List<String> positionalOptions = new ArrayList<>();
60 /*@NotNull*/ Properties paramValues = new Properties();
61 /*@NotNull*/ Properties paramExpressions = new Properties();
62 /*@NotNull*/ Properties paramFiles = new Properties();
63 /*@NotNull*/ Properties serializationParams = new Properties();
64
65 /**
66 * Set the permitted options.
67 *
68 * @param option A permitted option.
69 * @param optionProperties of this option, for example whether it is mandatory
70 * @param helpText message to be output if the user needs help concerning this option
71 */
72
73 public void addRecognizedOption(String option, int optionProperties, String helpText) {
74 recognizedOptions.put(option, optionProperties);
75 optionHelp.put(option, helpText);
76 if ((optionProperties & 0xff) == TYPE_BOOLEAN) {
77 setPermittedValues(option, new String[]{"on", "off"}, "on");
78 }
79 }
80
81 /**
82 * Set the permitted values for an option
83 *
84 * @param option the option keyword
85 * @param values the set of permitted values
86 * @param defaultValue the default value if the option is supplied but no value is given. May be null if no
87 * default is defined.
88 */
89
90 public void setPermittedValues(String option, String[] values, /*@Nullable*/ String defaultValue) {
91 Set<String> valueSet = new HashSet<>(Arrays.asList(values));
92 permittedValues.put(option, valueSet);
93 if (defaultValue != null) {
94 defaultValues.put(option, defaultValue);
95 }
96 }
97
98 /**
99 * Display a list of the values permitted for an option with type enumeration
100 *
101 * @param permittedValues the set of permitted values
102 * @return the set of values as a string, pipe-separated
103 */
104
105 private static String displayPermittedValues(/*@NotNull*/ Set<String> permittedValues) {
106 FastStringBuffer sb = new FastStringBuffer(20);
107 for (String val : permittedValues) {
108 if ("".equals(val)) {
109 sb.append("\"\"");
110 } else {
111 sb.append(val);
112 }
113 sb.append('|');
114 }
115 sb.setLength(sb.length() - 1);
116 return sb.toString();
117 }
118
119 /**
120 * Set the options actually present on the command line
121 *
122 * @param args the options supplied on the command line
123 * @throws XPathException if an unrecognized or invalid option is found
124 */
125
126 public void setActualOptions(/*@NotNull*/ String[] args) throws XPathException {
127 for (String arg : args) {
128 if ("-".equals(arg)) {
129 positionalOptions.add(arg);
130 } else if (arg.charAt(0) == '-') {
131 String option;
132 String value = "";
133 if (arg.length() > 5 && arg.charAt(1) == '-') {
134 // --featureKey:value format
135 int colon = arg.indexOf(':');
136 if (colon > 0 && colon < arg.length() - 1) {
137 option = arg.substring(2, colon);
138 value = arg.substring(colon + 1);
139 configOptions.setProperty(option, value);
140 } else if (colon > 0 && colon == arg.length() - 1) {
141 option = arg.substring(2, colon);
142 configOptions.setProperty(option, "");
143 } else {
144 option = arg.substring(2);
145 configOptions.setProperty(option, "true");
146 }
147 } else {
148 int colon = arg.indexOf(':');
149 if (colon > 0 && colon < arg.length() - 1) {
150 option = arg.substring(1, colon);
151 value = arg.substring(colon + 1);
152 } else {
153 option = arg.substring(1);
154 }
155 if (recognizedOptions.get(option) == null) {
156 throw new XPathException("Command line option -" + option +
157 " is not recognized. Options available: " + displayPermittedOptions());
158 }
159 if (namedOptions.getProperty(option) != null) {
160 throw new XPathException("Command line option -" + option + " appears more than once");
161 } else if ("?".equals(value)) {
162 displayOptionHelp(option);
163 throw new XPathException("No processing requested");
164 } else {
165 if ("".equals(value)) {
166 int prop = recognizedOptions.get(option);
167 if ((prop & VALUE_REQUIRED) != 0) {
168 String msg = "Command line option -" + option + " requires a value";
169 if (permittedValues.get(option) != null) {
170 msg += ": permitted values are " + displayPermittedValues(permittedValues.get(option));
171 }
172 throw new XPathException(msg);
173 }
174 String defaultValue = defaultValues.get(option);
175 if (defaultValue != null) {
176 value = defaultValue;
177 }
178 } else {
179 int prop = recognizedOptions.get(option);
180 if ((prop & VALUE_PROHIBITED) != 0) {
181 String msg = "Command line option -" + option + " does not expect a value";
182 throw new XPathException(msg);
183 }
184 }
185 Set<String> permitted = permittedValues.get(option);
186 if (permitted != null && !permitted.contains(value)) {
187 throw new XPathException("Bad option value " + arg +
188 ": permitted values are " + displayPermittedValues(permitted));
189 }
190 namedOptions.setProperty(option, value);
191 }
192 }
193 } else {
194 // handle keyword=value options
195 int eq = arg.indexOf('=');
196 if (eq >= 1) {
197 String keyword = arg.substring(0, eq);
198 String value = "";
199 if (eq < arg.length() - 1) {
200 value = arg.substring(eq + 1);
201 }
202 char ch = arg.charAt(0);
203 if (ch == '!' && eq >= 2) {
204 serializationParams.setProperty(keyword.substring(1), value);
205 } else if (ch == '?' && eq >= 2) {
206 paramExpressions.setProperty(keyword.substring(1), value);
207 } else if (ch == '+' && eq >= 2) {
208 paramFiles.setProperty(keyword.substring(1), value);
209 } else {
210 paramValues.setProperty(keyword, value);
211 }
212 } else {
213 positionalOptions.add(arg);
214 }
215 }
216 }
217 }
218
219 /**
220 * Test whether there is any keyword=value option present
221 *
222 * @return true if there are any keyword=value options
223 */
224
225 public boolean definesParameterValues() {
226 return !serializationParams.isEmpty() ||
227 !paramExpressions.isEmpty() ||
228 !paramFiles.isEmpty() ||
229 !paramValues.isEmpty();
230 }
231
232 /**
233 * Prescan the command line arguments to see if any of them imply use of a schema-aware processor
234 *
235 * @return true if a schema-aware processor is needed
236 */
237
238 public boolean testIfSchemaAware() {
239 return getOptionValue("sa") != null ||
240 getOptionValue("outval") != null ||
241 getOptionValue("val") != null ||
242 getOptionValue("vlax") != null ||
243 getOptionValue("xsd") != null ||
244 getOptionValue("xsdversion") != null;
245 }
246
247 /**
248 * Apply options to the Configuration
249 *
250 * @param processor the s9api Processor object
251 * @throws javax.xml.transform.TransformerException
252 * if invalid options are present
253 */
254
255 public void applyToConfiguration(/*@NotNull*/ final Processor processor) throws TransformerException {
256
257 Configuration config = processor.getUnderlyingConfiguration();
258
259 for (Enumeration e = configOptions.propertyNames(); e.hasMoreElements(); ) {
260 String name = (String) e.nextElement();
261 String value = configOptions.getProperty(name);
262 String fullName = "http://saxon.sf.net/feature/" + name;
263 if (!name.startsWith("parserFeature?") && !name.startsWith("parserProperty?")) {
264 Feature<?> f = Feature.byName(fullName);
265 if (f == null) {
266 throw new XPathException("Unknown configuration feature " + name);
267 }
268 Object typedValue;
269 if (f.type == Boolean.class) {
270 typedValue = Configuration.requireBoolean(name, value);
271 } else if (f.type == Integer.class) {
272 typedValue = Integer.valueOf(value);
273 } else if (f.type == String.class) {
274 typedValue = value;
275 } else {
276 throw new XPathException("Property --" + name + " cannot be supplied as a string");
277 }
278 }
279 try {
280 processor.getUnderlyingConfiguration().setConfigurationProperty(fullName, value);
281 } catch (IllegalArgumentException err) {
282 throw new XPathException("Incorrect value for --" + name + ": " + err.getMessage());
283 }
284 }
285
286 String value = getOptionValue("catalog");
287 if (value != null) {
288 if (getOptionValue("r") != null) {
289 throw new XPathException("Cannot use -catalog and -r together");
290 }
291 if (getOptionValue("x") != null) {
292 throw new XPathException("Cannot use -catalog and -x together");
293 }
294 if (getOptionValue("y") != null) {
295 throw new XPathException("Cannot use -catalog and -y together");
296 }
297 StringBuilder sb = new StringBuilder();
298 if ((getOptionValue("u") != null) || isImplicitURI(value)) {
299 for (String s : value.split(";")) {
300 Source sourceInput = null;
301 try {
302 sourceInput = config.getURIResolver().resolve(s, null);
303 } catch (TransformerException e) {
304 // no action - try the standard URI resolver instead
305 }
306 if (sourceInput == null) {
307 sourceInput = config.getSystemURIResolver().resolve(s, null);
308 }
309 sb.append(sourceInput.getSystemId()).append(';');
310 }
311
312 } else {
313 for (String s : value.split(";")) {
314 File catalogFile = new File(s);
315 if (!catalogFile.exists()) {
316 throw new XPathException("Catalog file not found: " + s);
317 }
318 sb.append(catalogFile.toURI().toASCIIString()).append(';');
319 }
320 }
321 value = sb.toString();
322
323 try {
324 config.getClass("org.apache.xml.resolver.CatalogManager", false, null);
325 XmlCatalogResolver.setCatalog(value, config, getOptionValue("t") != null);
326 } catch (XPathException err) {
327 throw new XPathException("Failed to load Apache catalog resolver library", err);
328 }
329 }
330
331 value = getOptionValue("cr");
332 if (value != null) {
333 Object resolver = config.getInstance(value, null);
334 if (!(resolver instanceof CollectionURIResolver)) {
335 throw new XPathException("Class specified using -cr is not a CollectionURIResolver");
336 }
337 processor.setConfigurationProperty(Feature.COLLECTION_URI_RESOLVER, (CollectionURIResolver)resolver);
338 }
339
340 value = getOptionValue("dtd");
341 if (value != null) {
342 if ("on".equals(value)) {
343 config.setBooleanProperty(Feature.DTD_VALIDATION, true);
344 config.getParseOptions().setDTDValidationMode(Validation.STRICT);
345 } else if ("off".equals(value)) {
346 config.setBooleanProperty(Feature.DTD_VALIDATION, false);
347 config.getParseOptions().setDTDValidationMode(Validation.SKIP);
348 } else if ("recover".equals(value)) {
349 config.setBooleanProperty(Feature.DTD_VALIDATION, true);
350 config.setBooleanProperty(Feature.DTD_VALIDATION_RECOVERABLE, true);
351 config.getParseOptions().setDTDValidationMode(Validation.LAX);
352 }
353 }
354
355 value = getOptionValue("ea");
356 if (value != null) {
357 boolean on = Configuration.requireBoolean("ea", value);
358 config.getDefaultXsltCompilerInfo().setAssertionsEnabled(on);
359 }
360
361 value = getOptionValue("expand");
362 if (value != null) {
363 boolean on = Configuration.requireBoolean("expand", value);
364 config.getParseOptions().setExpandAttributeDefaults(on);
365 }
366
367 value = getOptionValue("ext");
368 if (value != null) {
369 boolean on = Configuration.requireBoolean("ext", value);
370 config.setBooleanProperty(Feature.ALLOW_EXTERNAL_FUNCTIONS, on);
371 }
372
373 value = getOptionValue("l");
374 if (value != null) {
375 boolean on = Configuration.requireBoolean("l", value);
376 config.setBooleanProperty(Feature.LINE_NUMBERING, on);
377 }
378
379 value = getOptionValue("m");
380 if (value != null) {
381 config.setConfigurationProperty(Feature.MESSAGE_EMITTER_CLASS, value);
382 }
383
384 value = getOptionValue("opt");
385 if (value != null) {
386 config.setConfigurationProperty(Feature.OPTIMIZATION_LEVEL, value);
387 }
388
389 value = getOptionValue("or");
390 if (value != null) {
391 Object resolver = config.getInstance(value, null);
392 if (resolver instanceof OutputURIResolver) {
393 config.setConfigurationProperty(Feature.OUTPUT_URI_RESOLVER, (OutputURIResolver) resolver);
394 } else {
395 throw new XPathException("Class " + value + " is not an OutputURIResolver");
396 }
397 }
398
399 value = getOptionValue("outval");
400 if (value != null) {
401 Boolean isRecover = "recover".equals(value);
402 config.setConfigurationProperty(Feature.VALIDATION_WARNINGS, isRecover);
403 config.setConfigurationProperty(Feature.VALIDATION_COMMENTS, isRecover);
404 }
405
406 value = getOptionValue("r");
407 if (value != null) {
408 config.setURIResolver(config.makeURIResolver(value));
409 }
410
411 value = getOptionValue("strip");
412 if (value != null) {
413 config.setConfigurationProperty(Feature.STRIP_WHITESPACE, value);
414 }
415
416 value = getOptionValue("T");
417 if (value != null) {
418 config.setCompileWithTracing(true);
419 }
420
421 value = getOptionValue("TJ");
422 if (value != null) {
423 boolean on = Configuration.requireBoolean("TJ", value);
424 config.setBooleanProperty(Feature.TRACE_EXTERNAL_FUNCTIONS, on);
425 }
426
427 value = getOptionValue("tree");
428 if (value != null) {
429 if ("linked".equals(value)) {
430 config.setTreeModel(Builder.LINKED_TREE);
431 } else if ("tiny".equals(value)) {
432 config.setTreeModel(Builder.TINY_TREE);
433 } else if ("tinyc".equals(value)) {
434 config.setTreeModel(Builder.TINY_TREE_CONDENSED);
435 }
436 }
437
438 value = getOptionValue("val");
439 if (value != null) {
440 if ("strict".equals(value)) {
441 processor.setConfigurationProperty(Feature.SCHEMA_VALIDATION, Validation.STRICT);
442 } else if ("lax".equals(value)) {
443 processor.setConfigurationProperty(Feature.SCHEMA_VALIDATION, Validation.LAX);
444 }
445 }
446
447 value = getOptionValue("warnings");
448 if (value != null) {
449 if ("silent".equals(value)) {
450 processor.setConfigurationProperty(Feature.RECOVERY_POLICY,
451 Configuration.RECOVER_SILENTLY);
452 } else if ("recover".equals(value)) {
453 processor.setConfigurationProperty(Feature.RECOVERY_POLICY,
454 Configuration.RECOVER_WITH_WARNINGS);
455 } else if ("fatal".equals(value)) {
456 processor.setConfigurationProperty(Feature.RECOVERY_POLICY,
457 Configuration.DO_NOT_RECOVER);
458 }
459 }
460
461 value = getOptionValue("x");
462 if (value != null) {
463 processor.setConfigurationProperty(Feature.SOURCE_PARSER_CLASS, value);
464 }
465
466 value = getOptionValue("xi");
467 if (value != null) {
468 boolean on = Configuration.requireBoolean("xi", value);
469 processor.setConfigurationProperty(Feature.XINCLUDE, on);
470 }
471
472 value = getOptionValue("xmlversion");
473 if (value != null) {
474 processor.setConfigurationProperty(Feature.XML_VERSION, value);
475 }
476
477 value = getOptionValue("xsdversion");
478 if (value != null) {
479 processor.setConfigurationProperty(Feature.XSD_VERSION, value);
480 }
481
482 value = getOptionValue("xsiloc");
483 if (value != null) {
484 boolean on = Configuration.requireBoolean("xsiloc", value);
485 processor.setConfigurationProperty(Feature.USE_XSI_SCHEMA_LOCATION, on);
486 }
487
488 value = getOptionValue("y");
489 if (value != null) {
490 processor.setConfigurationProperty(Feature.STYLE_PARSER_CLASS, value);
491 }
492
493 // The init option must be done last
494
495 value = getOptionValue("init");
496 if (value != null) {
497 Initializer initializer = (Initializer) config.getInstance(value, null);
498 initializer.initialize(config);
499 }
500
501 }
502
503 /**
504 * Display the list the permitted options
505 *
506 * @return the list of permitted options, as a string
507 */
508
509 public String displayPermittedOptions() {
510 String[] options = new String[recognizedOptions.size()];
511 options = new ArrayList<>(recognizedOptions.keySet()).toArray(options);
512 Arrays.sort(options, Collator.getInstance());
513 FastStringBuffer sb = new FastStringBuffer(100);
514 for (String opt : options) {
515 sb.append(" -");
516 sb.append(opt);
517 }
518 return sb.toString();
519 }
520
521 /**
522 * Display help for a specific option on the System.err output (in response to -opt:?)
523 *
524 * @param option: the option for which help is required
525 */
526
527 private void displayOptionHelp(String option) {
528 System.err.println("Help for -" + option + " option");
529 int prop = recognizedOptions.get(option);
530 if ((prop & VALUE_PROHIBITED) == 0) {
531 switch (prop & 0xff) {
532 case TYPE_BOOLEAN:
533 System.err.println("Value: on|off");
534 break;
535 case TYPE_INTEGER:
536 System.err.println("Value: integer");
537 break;
538 case TYPE_FILENAME:
539 System.err.println("Value: file name");
540 break;
541 case TYPE_FILENAME_LIST:
542 System.err.println("Value: list of file names, semicolon-separated");
543 break;
544 case TYPE_CLASSNAME:
545 System.err.println("Value: Java fully-qualified class name");
546 break;
547 case TYPE_QNAME:
548 System.err.println("Value: QName in Clark notation ({uri}local)");
549 break;
550 case TYPE_STRING:
551 System.err.println("Value: string");
552 break;
553 case TYPE_INTEGER_PAIR:
554 System.err.println("Value: int,int");
555 break;
556 case TYPE_ENUMERATION:
557 String message = "Value: one of ";
558 message += displayPermittedValues(permittedValues.get(option));
559 System.err.println(message);
560 break;
561 default:
562 break;
563 }
564 }
565 System.err.println("Meaning: " + optionHelp.get(option));
566 }
567
568 /**
569 * Get the value of a named option. Returns null if the option was not present on the command line.
570 * Returns "" if the option was present but with no value ("-x" or "-x:").
571 *
572 * @param option the option keyword
573 * @return the option value, or null if not specified.
574 */
575
576 public String getOptionValue(String option) {
577 return namedOptions.getProperty(option);
578 }
579
580 /**
581 * Get the options specified positionally, that is, without a leading "-"
582 *
583 * @return the list of positional options
584 */
585
586 /*@NotNull*/
587 public List<String> getPositionalOptions() {
588 return positionalOptions;
589 }
590
591 public void setParams(Processor processor, ParamSetter paramSetter)
592 throws SaxonApiException {
593 for (Enumeration e = paramValues.propertyNames(); e.hasMoreElements(); ) {
594 String name = (String) e.nextElement();
595 String value = paramValues.getProperty(name);
596 paramSetter.setParam(QName.fromClarkName(name), new XdmAtomicValue(value, ItemType.UNTYPED_ATOMIC));
597 }
598 applyFileParameters(processor, paramSetter);
599 for (Enumeration e = paramExpressions.propertyNames(); e.hasMoreElements(); ) {
600 String name = (String) e.nextElement();
601 String value = paramExpressions.getProperty(name);
602 // parameters starting with "?" are taken as XPath expressions
603 XPathCompiler xpc = processor.newXPathCompiler();
604 XPathExecutable xpe = xpc.compile(value);
605 XdmValue val = xpe.load().evaluate();
606 paramSetter.setParam(QName.fromClarkName(name), val);
607 }
608 }
609
610 private void applyFileParameters(Processor processor, ParamSetter paramSetter) throws SaxonApiException {
611 boolean useURLs = "on".equals(getOptionValue("u"));
612 for (Enumeration e = paramFiles.propertyNames(); e.hasMoreElements(); ) {
613 String name = (String) e.nextElement();
614 String value = paramFiles.getProperty(name);
615 List<Source> sourceList = new ArrayList<>();
616 loadDocuments(value, useURLs, processor, true, sourceList);
617 if (!sourceList.isEmpty()) {
618 List<XdmNode> nodeList = new ArrayList<>(sourceList.size());
619 DocumentBuilder builder = processor.newDocumentBuilder();
620 for (Source s : sourceList) {
621 nodeList.add(builder.build(s));
622 }
623 XdmValue nodes = new XdmValue(nodeList);
624 paramSetter.setParam(QName.fromClarkName(name), nodes);
625 } else {
626 paramSetter.setParam(QName.fromClarkName(name), XdmEmptySequence.getInstance());
627 }
628 }
629 }
630
631 /**
632 * Set any output properties appearing on the command line in the form {@code !indent=yes}
633 * as properties of the supplied {@code Serializer}
634 * @param serializer the supplied {@code Serializer}, whose serialization properties
635 * are to be modified.
636 */
637
638 public void setSerializationProperties(Serializer serializer) {
639 for (Enumeration e = serializationParams.propertyNames(); e.hasMoreElements(); ) {
640 String name = (String) e.nextElement();
641 String value = serializationParams.getProperty(name);
642 // parameters starting with "!" are taken as output properties
643 // Allow the prefix "!saxon:" instead of "!{http://saxon.sf.net}"
644 if (name.startsWith("saxon:")) {
645 name = "{" + NamespaceConstant.SAXON + "}" + name.substring(6);
646 }
647 serializer.setOutputProperty(QName.fromClarkName(name), value);
648 }
649 }
650
651 public interface ParamSetter {
652 void setParam(QName qName, XdmValue value);
653 }
654
655
656 /**
657 * Apply XSLT 3.0 static parameters to a compilerInfo. Actually this sets all parameter values,
658 * whether static or dynamic. This is possible because the stylesheet is compiled for once-only use.
659 * However, file-valued params (+name=value) are always handled as dynamic parameters because
660 * of potential problems with exported SEF files.
661 *
662 * @param compiler The XsltCompiler object into which the parameters are copied
663 * @throws SaxonApiException if invalid options are found
664 */
665
666 public void applyStaticParams(XsltCompiler compiler)
667 throws SaxonApiException {
668 Processor processor = compiler.getProcessor();
669 for (Enumeration e = paramValues.propertyNames(); e.hasMoreElements(); ) {
670 String name = (String) e.nextElement();
671 String value = paramValues.getProperty(name);
672 compiler.setParameter(QName.fromClarkName(name), new XdmAtomicValue(value, ItemType.UNTYPED_ATOMIC));
673 }
674 for (Enumeration e = paramExpressions.propertyNames(); e.hasMoreElements(); ) {
675 String name = (String) e.nextElement();
676 String value = paramExpressions.getProperty(name);
677 // parameters starting with "?" are taken as XPath expressions
678 XPathCompiler xpc = processor.newXPathCompiler();
679 XPathExecutable xpe = xpc.compile(value);
680 XdmValue val = xpe.load().evaluate();
681 compiler.setParameter(QName.fromClarkName(name), val);
682 }
683
684 }
685
686 /**
687 * Apply XSLT 3.0 file-valued parameters to an XSLT transformer. Most parameters are applied
688 * before compilation, so that the compiler can take advantage of knowing their values; but
689 * file-valued parameters (provided as +name=value) are deferred until run-time because of
690 * complications storing their values in a SEF file.
691 *
692 * @param transformer The Xslt30Transformer object into which the parameters are copied
693 * @throws SaxonApiException if invalid options are found
694 */
695
696 public void applyFileParams(Processor processor, Xslt30Transformer transformer) throws SaxonApiException {
697 if (!paramFiles.isEmpty()) {
698 Map<QName, XdmValue> params = new HashMap<>();
699 applyFileParameters(processor, params::put);
700 transformer.setStylesheetParameters(params);
701 }
702 }
703
704
705 /**
706 * Load a document, or all the documents in a directory, given a filename or URL
707 *
708 * @param sourceFileName the name of the source file or directory
709 * @param useURLs true if the filename argument is to be treated as a URI
710 * @param processor the Saxon s9api Processor
711 * @param useSAXSource true if the method should use a SAXSource rather than a StreamSource
712 * @param sources an empty list which the method will populate.
713 * If sourceFileName represents a single source document, a corresponding XdmNode is
714 * added to the list. If sourceFileName represents a directory, multiple XdmNode
715 * objects, one for each file in the directory, are added to the list
716 * @return true if the supplied sourceFileName was found to be a directory
717 * @throws SaxonApiException if access to documents fails
718 */
719
720 /*@Nullable*/
721 public static boolean loadDocuments(String sourceFileName, boolean useURLs,
722 Processor processor, boolean useSAXSource, List<Source> sources)
723 throws SaxonApiException {
724
725 Source sourceInput;
726 XMLReader parser;
727 Configuration config = processor.getUnderlyingConfiguration();
728 if (useURLs || isImplicitURI(sourceFileName)) {
729 try {
730 sourceInput = config.getURIResolver().resolve(sourceFileName, null);
731 if (sourceInput == null) {
732 sourceInput = config.getSystemURIResolver().resolve(sourceFileName, null);
733 }
734 } catch (TransformerException e) {
735 throw new SaxonApiException(e);
736 }
737 sources.add(sourceInput);
738 return false;
739 } else if (sourceFileName.equals("-")) {
740 // take input from stdin
741 if (useSAXSource) {
742 parser = config.getSourceParser();
743 sourceInput = new SAXSource(parser, new InputSource(System.in));
744 } else {
745 sourceInput = new StreamSource(System.in);
746 }
747 sources.add(sourceInput);
748 return false;
749 } else {
750 File sourceFile = new File(sourceFileName);
751 if (!sourceFile.exists()) {
752 throw new SaxonApiException("Source file " + sourceFile + " does not exist");
753 }
754 if (sourceFile.isDirectory()) {
755 parser = config.getSourceParser();
756 String[] files = sourceFile.list();
757 if (files != null) {
758 for (String file1 : files) {
759 File file = new File(sourceFile, file1);
760 if (!file.isDirectory()) {
761 if (useSAXSource) {
762 InputSource eis = new InputSource(file.toURI().toString());
763 sourceInput = new SAXSource(parser, eis);
764 // it's safe to use the same parser for each document, as they
765 // will be processed one at a time.
766 } else {
767 sourceInput = new StreamSource(file.toURI().toString());
768 }
769 sources.add(sourceInput);
770 }
771 }
772 }
773 return true;
774 } else {
775 if (useSAXSource) {
776 InputSource eis = new InputSource(sourceFile.toURI().toString());
777 sourceInput = new SAXSource(config.getSourceParser(), eis);
778 } else {
779 sourceInput = new StreamSource(sourceFile.toURI().toString());
780 }
781 sources.add(sourceInput);
782 return false;
783 }
784 }
785 }
786
787 public static boolean isImplicitURI(String name) {
788 return name.startsWith("http:") ||
789 name.startsWith("https:") ||
790 name.startsWith("file:") ||
791 name.startsWith("classpath:");
792 }
793
794 public static void loadAdditionalSchemas(/*@NotNull*/ Configuration config, String additionalSchemas)
795 throws SchemaException {
796 StringTokenizer st = new StringTokenizer(additionalSchemas, File.pathSeparator);
797 while (st.hasMoreTokens()) {
798 String schema = st.nextToken();
799 File schemaFile = new File(schema);
800 if (!schemaFile.exists()) {
801 throw new SchemaException("Schema document " + schema + " not found");
802 }
803 config.addSchemaSource(new StreamSource(schemaFile));
804 }
805 }
806
807 private static DayTimeDurationValue milliSecond = new DayTimeDurationValue(1, 0, 0, 0, 0, 1000);
808
809 public static String showExecutionTimeNano(long nanosecs) {
810 if (nanosecs < 1e9) {
811 // time less than one second
812 return (nanosecs/1e6) + "ms";
813 } else {
814 try {
815 double millisecs = nanosecs/1e6;
816 DayTimeDurationValue d = milliSecond.multiply(millisecs);
817 long days = ((NumericValue) d.getComponent(AccessorFn.Component.DAY)).longValue();
818 long hours = ((NumericValue) d.getComponent(AccessorFn.Component.HOURS)).longValue();
819 long minutes = ((NumericValue) d.getComponent(AccessorFn.Component.MINUTES)).longValue();
820 BigDecimal seconds = ((NumericValue) d.getComponent(AccessorFn.Component.SECONDS)).getDecimalValue();
821 FastStringBuffer fsb = new FastStringBuffer(256);
822 if (days > 0) {
823 fsb.append(days + "days ");
824 }
825 if (hours > 0) {
826 fsb.append(hours + "h ");
827 }
828 if (minutes > 0) {
829 fsb.append(minutes + "m ");
830 }
831 fsb.append(seconds + "s");
832 return fsb + " (" + nanosecs / 1e6 + "ms)";
833 } catch (XPathException e) {
834 return nanosecs / 1e6 + "ms";
835 }
836
837 }
838 }
839
840 public static String showMemoryUsed() {
841 long value = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
842 return new RegularGroupFormatter(3, ",", EmptyString.THE_INSTANCE).format(new FastStringBuffer(value + ""));
843 }
844
845
846 public static String getCommandName(Object command) {
847 String s = command.getClass().getName();
848 if (s.startsWith("cli.Saxon.Cmd.DotNet")) {
849 s = s.substring("cli.Saxon.Cmd.DotNet".length());
850 }
851 return s;
852 }
853
854 }
855