Debian Codegraph @

net/sf/saxon/trans/ConfigurationReader.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
11 import net.sf.saxon.Configuration;
12 import net.sf.saxon.Version;
13 import net.sf.saxon.event.ContentHandlerProxy;
14 import net.sf.saxon.expr.Expression;
15 import net.sf.saxon.expr.instruct.ResultDocument;
16 import net.sf.saxon.expr.parser.ExplicitLocation;
17 import net.sf.saxon.expr.parser.Token;
18 import net.sf.saxon.expr.parser.XPathParser;
19 import net.sf.saxon.functions.ResolveURI;
20 import net.sf.saxon.lib.*;
21 import net.sf.saxon.om.*;
22 import net.sf.saxon.sxpath.IndependentContext;
23 import net.sf.saxon.trans.packages.PackageDetails;
24 import net.sf.saxon.trans.packages.PackageLibrary;
25 import net.sf.saxon.trans.packages.VersionedPackageName;
26 import net.sf.saxon.tree.util.FastStringBuffer;
27 import net.sf.saxon.type.SchemaException;
28 import org.xml.sax.*;
29
30 import javax.xml.transform.ErrorListener;
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.IOException;
38 import java.net.URI;
39 import java.net.URISyntaxException;
40 import java.util.*;
41
42 /**
43 * Class used to read a config.xml file and transfer all settings from the file to the Configuration
44 */
45
46 public class ConfigurationReader implements ContentHandler, NamespaceResolver {
47
48 private int level = 0;
49 private String section = null;
50 private String subsection = null;
51 private FastStringBuffer buffer = new FastStringBuffer(100);
52 protected Configuration config;
53 private ClassLoader classLoader = null;
54 private List<XPathException> errors = new ArrayList<>();
55 private Locator locator;
56 private Stack<List<String[]>> namespaceStack = new Stack<>();
57 private PackageLibrary packageLibrary;
58 private PackageDetails currentPackage;
59 private Configuration baseConfiguration;
60
61 public ConfigurationReader() {
62 }
63
64 /**
65 * Set the ClassLoader to be used for dynamic loading of the configuration, and for dynamic loading
66 * of other classes used within the configuration. By default the class loader of this class is used.
67 *
68 * @param classLoader the ClassLoader to be used
69 */
70
71 public void setClassLoader(ClassLoader classLoader) {
72 this.classLoader = classLoader;
73 }
74
75 /**
76 * Set a base Configuration to be used by the new Configuration. The new Configuration
77 * shares a NamePool and document number allocator with the base Configuration
78 *
79 * @param base the base configuration to be used
80 */
81
82 public void setBaseConfiguration(Configuration base) {
83 this.baseConfiguration = base;
84 }
85
86 /**
87 * Create a Configuration based on the contents of this configuration file
88 *
89 * @param source the Source of the configuration file
90 * @return the constructed Configuration
91 * @throws XPathException if a failure occurs, typically an invalid configuration file
92 */
93
94 public Configuration makeConfiguration(Source source) throws XPathException {
95 InputSource is;
96 XMLReader parser = null;
97 if (source instanceof NodeInfo) {
98 ContentHandlerProxy proxy = new ContentHandlerProxy() {
99 @Override
100 public void startDocument(int properties) throws XPathException {
101 try {
102 getUnderlyingContentHandler().startDocument();
103 } catch (SAXException e) {
104 throw XPathException.makeXPathException(e);
105 }
106 }
107
108 @Override
109 public void endDocument() throws XPathException {
110 try {
111 getUnderlyingContentHandler().endDocument();
112 } catch (SAXException e) {
113 throw XPathException.makeXPathException(e);
114 }
115 }
116 };
117 proxy.setUnderlyingContentHandler(this);
118 proxy.setPipelineConfiguration(((NodeInfo) source).getConfiguration().makePipelineConfiguration());
119 proxy.open();
120 proxy.startDocument(0);
121 ((NodeInfo) source).copy(proxy, CopyOptions.ALL_NAMESPACES, ExplicitLocation.UNKNOWN_LOCATION);
122 proxy.endDocument();
123 proxy.close();
124 if (baseConfiguration != null) {
125 config.importLicenseDetails(baseConfiguration);
126 }
127 return config;
128 } else if (source instanceof SAXSource) {
129 parser = ((SAXSource) source).getXMLReader();
130 is = ((SAXSource) source).getInputSource();
131 } else if (source instanceof StreamSource) {
132 is = new InputSource(source.getSystemId());
133 is.setCharacterStream(((StreamSource) source).getReader());
134 is.setByteStream(((StreamSource) source).getInputStream());
135 } else {
136 throw new XPathException("Source for configuration file must be a StreamSource or SAXSource or NodeInfo");
137 }
138 if (parser == null) {
139 // Don't use the parser from the pool, it might be validating
140 parser = Version.platform.loadParser();
141 try {
142 parser.setFeature("http://xml.org/sax/features/namespaces", true);
143 parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
144 } catch (SAXNotRecognizedException | SAXNotSupportedException e) {
145 throw new TransformerFactoryConfigurationError(e);
146 }
147 }
148 try {
149 parser.setContentHandler(this);
150 parser.parse(is);
151 } catch (IOException e) {
152 throw new XPathException("Failed to read config file", e);
153 } catch (SAXException e) {
154 throw new XPathException("Failed to parse config file", e);
155 }
156
157 if (!errors.isEmpty()) {
158 ErrorListener listener;
159 if (config == null) {
160 listener = new StandardErrorListener();
161 } else {
162 listener = config.getErrorListener();
163 }
164 try {
165 for (XPathException err : errors) {
166 listener.warning(err);
167 }
168 } catch (TransformerException e) {
169 //
170 }
171 throw errors.get(0);
172 }
173 if (baseConfiguration != null) {
174 config.importLicenseDetails(baseConfiguration);
175 }
176 return config;
177 }
178
179 public void setDocumentLocator(Locator locator) {
180 this.locator = locator;
181 }
182
183 public void startDocument() {
184 namespaceStack.push(new ArrayList<>());
185 }
186
187 public void endDocument() {
188 namespaceStack.pop();
189 if (config != null) {
190 config.getDefaultXsltCompilerInfo().setPackageLibrary(packageLibrary);
191 }
192 }
193
194 public void startPrefixMapping(String prefix, String uri) {
195 namespaceStack.peek().add(new String[]{prefix, uri});
196 }
197
198 public void endPrefixMapping(String prefix) {
199
200 }
201
202 public void startElement(String uri, String localName, String qName, Attributes atts) {
203 buffer.setLength(0);
204 if (NamespaceConstant.SAXON_CONFIGURATION.equals(uri)) {
205 if (level == 0) {
206 if (!"configuration".equals(localName)) {
207 error(localName, null, null, "configuration");
208 }
209 String edition = atts.getValue("edition");
210 if (edition == null) {
211 edition = "HE";
212 }
213 switch (edition) {
214 case "HE":
215 config = new Configuration();
216 break;
217 case "PE":
218 config = Configuration.makeLicensedConfiguration(classLoader, "com.saxonica.config.ProfessionalConfiguration");
219 break;
220 case "EE":
221 config = Configuration.makeLicensedConfiguration(classLoader, "com.saxonica.config.EnterpriseConfiguration");
222 break;
223 default:
224 error("configuration", "edition", edition, "HE|PE|EE");
225 config = new Configuration();
226 break;
227 }
228
229 if (baseConfiguration != null) {
230 config.setNamePool(baseConfiguration.getNamePool());
231 config.setDocumentNumberAllocator(baseConfiguration.getDocumentNumberAllocator());
232 }
233
234 packageLibrary = new PackageLibrary(config.getDefaultXsltCompilerInfo());
235 String licenseLoc = atts.getValue("licenseFileLocation");
236 if (licenseLoc != null && !edition.equals("HE")) {
237 String base = locator.getSystemId();
238 try {
239 URI absoluteLoc = ResolveURI.makeAbsolute(licenseLoc, base);
240 config.setConfigurationProperty(FeatureKeys.LICENSE_FILE_LOCATION, absoluteLoc.toString());
241 } catch (Exception err) {
242 errors.add(new XPathException("Failed to process license at " + licenseLoc, err));
243 }
244 }
245 String label = atts.getValue("label");
246 if (label != null) {
247 config.setLabel(label);
248 }
249 config.getDynamicLoader().setClassLoader(classLoader);
250 }
251 if (level == 1) {
252 section = localName;
253 if ("global".equals(localName)) {
254 readGlobalElement(atts);
255 } else if ("serialization".equals(localName)) {
256 readSerializationElement(atts);
257 } else if ("xquery".equals(localName)) {
258 readXQueryElement(atts);
259 } else if ("xslt".equals(localName)) {
260 readXsltElement(atts);
261 } else if ("xsltPackages".equals(localName)) {
262 // no action until later;
263 } else if ("xsd".equals(localName)) {
264 readXsdElement(atts);
265 } else if ("resources".equals(localName)) {
266 // no action until later
267 } else if ("collations".equals(localName)) {
268 // no action until later
269 } else if ("localizations".equals(localName)) {
270 readLocalizationsElement(atts);
271 } else {
272 error(localName, null, null, null);
273 }
274 } else if (level == 2) {
275 subsection = localName;
276 switch (section) {
277 case "resources":
278 if ("fileExtension".equals(localName)) {
279 readFileExtension(atts);
280 }
281 // no action until endElement()
282 break;
283 case "collations":
284 if (!"collation".equals(localName)) {
285 error(localName, null, null, "collation");
286 } else {
287 readCollation(atts);
288 }
289 break;
290 case "localizations":
291 if (!"localization".equals(localName)) {
292 error(localName, null, null, "localization");
293 } else {
294 readLocalization(atts);
295 }
296 break;
297 case "xslt":
298 if ("extensionElement".equals(localName)) {
299 readExtensionElement(atts);
300 } else {
301 error(localName, null, null, null);
302 }
303 break;
304 case "xsltPackages":
305 if ("package".equals(localName)) {
306 readXsltPackage(atts);
307 }
308 break;
309 }
310 } else if (level == 3) {
311 if ("package".equals(subsection)) {
312 if ("withParam".equals(localName)) {
313 readWithParam(atts);
314 } else {
315 error(localName, null, null, null);
316 }
317 }
318 }
319 } else {
320 errors.add(new XPathException("Configuration elements must be in namespace " + NamespaceConstant.SAXON_CONFIGURATION));
321 }
322 level++;
323 namespaceStack.push(new ArrayList<>());
324 }
325
326 private void readGlobalElement(Attributes atts) {
327 Properties props = new Properties();
328 for (int i = 0; i < atts.getLength(); i++) {
329 String name = atts.getLocalName(i);
330 String value = atts.getValue(i);
331 if (!value.isEmpty() && atts.getURI(i).isEmpty()) {
332 props.put(name, value);
333 }
334 }
335 props.put("#element", "global");
336 applyProperty(props, "allowExternalFunctions", FeatureKeys.ALLOW_EXTERNAL_FUNCTIONS);
337 applyProperty(props, "allowMultiThreading", FeatureKeys.ALLOW_MULTITHREADING);
338 applyProperty(props, "allowOldJavaUriFormat", FeatureKeys.ALLOW_OLD_JAVA_URI_FORMAT);
339 applyProperty(props, "allowSyntaxExtensions", FeatureKeys.ALLOW_SYNTAX_EXTENSIONS);
340 applyProperty(props, "collationUriResolver", FeatureKeys.COLLATION_URI_RESOLVER_CLASS);
341 applyProperty(props, "collectionUriResolver", FeatureKeys.COLLECTION_URI_RESOLVER_CLASS);
342 applyProperty(props, "compileWithTracing", FeatureKeys.COMPILE_WITH_TRACING);
343 applyProperty(props, "debugByteCode", FeatureKeys.DEBUG_BYTE_CODE);
344 applyProperty(props, "debugByteCodeDirectory", FeatureKeys.DEBUG_BYTE_CODE_DIR);
345 applyProperty(props, "defaultCollation", FeatureKeys.DEFAULT_COLLATION);
346 applyProperty(props, "defaultCollection", FeatureKeys.DEFAULT_COLLECTION);
347 applyProperty(props, "defaultRegexEngine", FeatureKeys.DEFAULT_REGEX_ENGINE);
348 applyProperty(props, "displayByteCode", FeatureKeys.DISPLAY_BYTE_CODE);
349 applyProperty(props, "dtdValidation", FeatureKeys.DTD_VALIDATION);
350 applyProperty(props, "dtdValidationRecoverable", FeatureKeys.DTD_VALIDATION_RECOVERABLE);
351 applyProperty(props, "eagerEvaluation", FeatureKeys.EAGER_EVALUATION);
352 applyProperty(props, "entityResolver", FeatureKeys.ENTITY_RESOLVER_CLASS);
353 applyProperty(props, "errorListener", FeatureKeys.ERROR_LISTENER_CLASS);
354 applyProperty(props, "environmentVariableResolver", FeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER_CLASS);
355 applyProperty(props, "expandAttributeDefaults", FeatureKeys.EXPAND_ATTRIBUTE_DEFAULTS);
356 applyProperty(props, "generateByteCode", FeatureKeys.GENERATE_BYTE_CODE);
357 applyProperty(props, "ignoreSAXSourceParser", FeatureKeys.IGNORE_SAX_SOURCE_PARSER);
358 applyProperty(props, "lineNumbering", FeatureKeys.LINE_NUMBERING);
359 applyProperty(props, "markDefaultedAttributes", FeatureKeys.MARK_DEFAULTED_ATTRIBUTES);
360 applyProperty(props, "maxCompiledClasses", FeatureKeys.MAX_COMPILED_CLASSES);
361 applyProperty(props, "monitorHotSpotByteCode", FeatureKeys.MONITOR_HOT_SPOT_BYTE_CODE);
362 applyProperty(props, "optimizationLevel", FeatureKeys.OPTIMIZATION_LEVEL);
363 applyProperty(props, "parser", FeatureKeys.SOURCE_PARSER_CLASS);
364 applyProperty(props, "preEvaluateDoc", FeatureKeys.PRE_EVALUATE_DOC_FUNCTION);
365 applyProperty(props, "preferJaxpParser", FeatureKeys.PREFER_JAXP_PARSER);
366 applyProperty(props, "recognizeUriQueryParameters", FeatureKeys.RECOGNIZE_URI_QUERY_PARAMETERS);
367 applyProperty(props, "schemaValidation", FeatureKeys.SCHEMA_VALIDATION_MODE);
368 applyProperty(props, "serializerFactory", FeatureKeys.SERIALIZER_FACTORY_CLASS);
369 applyProperty(props, "sourceResolver", FeatureKeys.SOURCE_RESOLVER_CLASS);
370 applyProperty(props, "stableCollectionUri", FeatureKeys.STABLE_COLLECTION_URI);
371 applyProperty(props, "stableUnparsedText", FeatureKeys.STABLE_UNPARSED_TEXT);
372 applyProperty(props, "standardErrorOutputFile", FeatureKeys.STANDARD_ERROR_OUTPUT_FILE);
373 applyProperty(props, "streamability", FeatureKeys.STREAMABILITY);
374 applyProperty(props, "streamingFallback", FeatureKeys.STREAMING_FALLBACK);
375 applyProperty(props, "stripSpace", FeatureKeys.STRIP_WHITESPACE);
376 applyProperty(props, "styleParser", FeatureKeys.STYLE_PARSER_CLASS);
377 applyProperty(props, "suppressEvaluationExpiryWarning", FeatureKeys.SUPPRESS_EVALUATION_EXPIRY_WARNING);
378 applyProperty(props, "suppressXPathWarnings", FeatureKeys.SUPPRESS_XPATH_WARNINGS);
379 applyProperty(props, "suppressXsltNamespaceCheck", FeatureKeys.SUPPRESS_XSLT_NAMESPACE_CHECK);
380 applyProperty(props, "thresholdForHotspotByteCode", FeatureKeys.THRESHOLD_FOR_HOTSPOT_BYTE_CODE);
381 applyProperty(props, "timing", FeatureKeys.TIMING);
382 applyProperty(props, "traceExternalFunctions", FeatureKeys.TRACE_EXTERNAL_FUNCTIONS);
383 applyProperty(props, "traceListener", FeatureKeys.TRACE_LISTENER_CLASS);
384 applyProperty(props, "traceListenerOutputFile", FeatureKeys.TRACE_LISTENER_OUTPUT_FILE);
385 applyProperty(props, "traceOptimizerDecisions", FeatureKeys.TRACE_OPTIMIZER_DECISIONS);
386 applyProperty(props, "treeModel", FeatureKeys.TREE_MODEL_NAME);
387 applyProperty(props, "unparsedTextUriResolver", FeatureKeys.UNPARSED_TEXT_URI_RESOLVER_CLASS);
388 applyProperty(props, "uriResolver", FeatureKeys.URI_RESOLVER_CLASS);
389 applyProperty(props, "usePiDisableOutputEscaping", FeatureKeys.USE_PI_DISABLE_OUTPUT_ESCAPING);
390 applyProperty(props, "useTypedValueCache", FeatureKeys.USE_TYPED_VALUE_CACHE);
391 applyProperty(props, "validationComments", FeatureKeys.VALIDATION_COMMENTS);
392 applyProperty(props, "validationWarnings", FeatureKeys.VALIDATION_WARNINGS);
393 applyProperty(props, "versionOfXml", FeatureKeys.XML_VERSION);
394 applyProperty(props, "xInclude", FeatureKeys.XINCLUDE);
395 }
396
397 private void applyProperty(Properties props, String propertyName, String featureKey) {
398 String value = props.getProperty(propertyName);
399 if (value != null) {
400 try {
401 config.setConfigurationProperty(featureKey, value);
402 } catch (IllegalArgumentException e) {
403 String message = e.getMessage();
404 if (message.startsWith(featureKey)) {
405 message = message.replace(featureKey, "Value");
406 }
407 if (message.startsWith("Unknown configuration property")) {
408 message = "Property not available in Saxon-" + config.getEditionCode();
409 }
410 error(props.getProperty("#element"), propertyName, value, message);
411 }
412 }
413 }
414
415 private void readSerializationElement(Attributes atts) {
416 Properties props = new Properties();
417 for (int i = 0; i < atts.getLength(); i++) {
418 String uri = atts.getURI(i);
419 String name = atts.getLocalName(i);
420 String value = atts.getValue(i);
421 if (value.isEmpty()) {
422 continue;
423 }
424 try {
425 ResultDocument.setSerializationProperty(props,
426 uri, name, value, this, false, config);
427 } catch (XPathException e) {
428 errors.add(e);
429 }
430 }
431 config.setDefaultSerializationProperties(props);
432 }
433
434 private void readCollation(Attributes atts) {
435 Properties props = new Properties();
436 String collationUri = null;
437 for (int i = 0; i < atts.getLength(); i++) {
438 if (atts.getURI(i).isEmpty()) {
439 String name = atts.getLocalName(i);
440 String value = atts.getValue(i);
441 if (value.isEmpty()) {
442 continue;
443 }
444 if ("uri".equals(name)) {
445 collationUri = value;
446 } else {
447 props.put(name, value);
448 }
449 }
450 }
451 if (collationUri == null) {
452 errors.add(new XPathException("collation specified with no uri"));
453 }
454 StringCollator collator = null;
455 try {
456 collator = Version.platform.makeCollation(config, props, collationUri);
457 } catch (XPathException e) {
458 errors.add(e);
459 }
460 config.registerCollation(collationUri, collator);
461
462 }
463
464 private void readLocalizationsElement(Attributes atts) {
465 for (int i = 0; i < atts.getLength(); i++) {
466 if (atts.getURI(i).isEmpty()) {
467 String name = atts.getLocalName(i);
468 String value = atts.getValue(i);
469 if ("defaultLanguage".equals(name) && !value.isEmpty()) {
470 config.setConfigurationProperty(FeatureKeys.DEFAULT_LANGUAGE, value);
471 }
472 if ("defaultCountry".equals(name) && !value.isEmpty()) {
473 config.setConfigurationProperty(FeatureKeys.DEFAULT_COUNTRY, value);
474 }
475 }
476 }
477 }
478
479 private void readLocalization(Attributes atts) {
480 String lang = null;
481 Properties properties = new Properties();
482 for (int i = 0; i < atts.getLength(); i++) {
483 if (atts.getURI(i).isEmpty()) {
484 String name = atts.getLocalName(i);
485 String value = atts.getValue(i);
486 if ("lang".equals(name) && !value.isEmpty()) {
487 lang = value;
488 } else if (!value.isEmpty()) {
489 properties.setProperty(name, value);
490 }
491 }
492 }
493 if (lang != null) {
494 LocalizerFactory factory = config.getLocalizerFactory();
495 if (factory != null) {
496 factory.setLanguageProperties(lang, properties);
497 }
498 }
499 }
500
501 private void readFileExtension(Attributes atts) {
502 String extension = atts.getValue("", "extension");
503 String mediaType = atts.getValue("", "mediaType");
504 if (extension == null) {
505 error("fileExtension", "extension", null, null);
506 }
507 if (mediaType == null) {
508 error("fileExtension", "mediaType", null, null);
509 }
510 config.registerFileExtension(extension, mediaType);
511 }
512
513 /**
514 * Process details of XSLT extension elements. Overridden in Saxon-PE configuration reader
515 *
516 * @param atts the attributes of the extensionElement element in the configuration file
517 */
518
519 protected void readExtensionElement(Attributes atts) {
520 XPathException err = new XPathException("Extension elements are not available in Saxon-HE");
521 err.setLocator(ExplicitLocation.makeFromSax(locator));
522 errors.add(err);
523 }
524
525 protected void readXsltPackage(Attributes atts) {
526 String name = atts.getValue("name");
527 if (name == null) {
528 String attName = "exportLocation";
529 String location = atts.getValue("exportLocation");
530 URI uri = null;
531 if (location == null) {
532 attName = "sourceLocation";
533 location = atts.getValue("sourceLocation");
534 }
535 if (location == null) {
536 error("package", attName, null, null);
537 }
538 try {
539 uri = ResolveURI.makeAbsolute(location, locator.getSystemId());
540 } catch (URISyntaxException e) {
541 error("package", attName, location, "Requires a valid URI.");
542 }
543 File file = new File(uri);
544 try {
545 packageLibrary.addPackage(file);
546 } catch (XPathException e) {
547 error(e);
548 }
549 } else {
550 String version = atts.getValue("version");
551 if (version == null) {
552 version = "1";
553 }
554 VersionedPackageName vpn = null;
555 PackageDetails details = new PackageDetails();
556 try {
557 vpn = new VersionedPackageName(name, version);
558 } catch (XPathException err) {
559 error("package", "version", version, null);
560 }
561 details.nameAndVersion = vpn;
562 currentPackage = details;
563 String sourceLoc = atts.getValue("sourceLocation");
564 StreamSource source = null;
565 if (sourceLoc != null) {
566 try {
567 source = new StreamSource(
568 ResolveURI.makeAbsolute(sourceLoc, locator.getSystemId()).toString());
569 } catch (URISyntaxException e) {
570 error("package", "sourceLocation", sourceLoc, "Requires a valid URI.");
571 }
572 details.sourceLocation = source;
573 }
574 String exportLoc = atts.getValue("exportLocation");
575 if (exportLoc != null) {
576 try {
577 source = new StreamSource(
578 ResolveURI.makeAbsolute(exportLoc, locator.getSystemId()).toString());
579 } catch (URISyntaxException e) {
580 error("package", "exportLocation", exportLoc, "Requires a valid URI.");
581 }
582 details.exportLocation = source;
583 }
584 String priority = atts.getValue("priority");
585 if (priority != null) {
586 try {
587 details.priority = Integer.parseInt(priority);
588 } catch (NumberFormatException err) {
589 error("package", "priority", priority, "Requires an integer.");
590 }
591 }
592 details.baseName = atts.getValue("base");
593 details.shortName = atts.getValue("shortName");
594
595 packageLibrary.addPackage(details);
596 }
597 }
598
599 protected void readWithParam(Attributes atts) {
600 if (currentPackage.exportLocation != null) {
601 error("withParam", null, null, "Not allowed when @exportLocation exists");
602 }
603 String name = atts.getValue("name");
604 if (name == null) {
605 error("withParam", "name", null, null);
606 }
607 QNameParser qp = new QNameParser(this);
608 qp.setAcceptEQName(true);
609 StructuredQName qName = null;
610 try {
611 qName = qp.parse(name);
612 } catch (XPathException e) {
613 error("withParam", "name", name, "Requires valid QName");
614 }
615 String select = atts.getValue("select");
616 if (select == null) {
617 error("withParam", "select", null, null);
618 }
619 IndependentContext env = new IndependentContext(config);
620 env.setNamespaceResolver(this);
621 XPathParser parser = new XPathParser();
622 GroundedValue<?> value = null;
623 try {
624 Expression exp = parser.parse(select, 0, Token.EOF, env);
625 value = exp.iterate(env.makeEarlyEvaluationContext()).materialize();
626 } catch (XPathException e) {
627 error(e);
628 }
629 if (currentPackage.staticParams == null) {
630 currentPackage.staticParams = new HashMap<>();
631 }
632 currentPackage.staticParams.put(qName, value);
633 }
634
635
636 private void readXQueryElement(Attributes atts) {
637 Properties props = new Properties();
638 for (int i = 0; i < atts.getLength(); i++) {
639 String name = atts.getLocalName(i);
640 String value = atts.getValue(i);
641 if (!value.isEmpty() && atts.getURI(i).isEmpty()) {
642 props.put(name, value);
643 }
644 }
645 props.put("#element", "xquery");
646 applyProperty(props, "allowUpdate", FeatureKeys.XQUERY_ALLOW_UPDATE);
647 applyProperty(props, "constructionMode", FeatureKeys.XQUERY_CONSTRUCTION_MODE);
648 applyProperty(props, "defaultElementNamespace", FeatureKeys.XQUERY_DEFAULT_ELEMENT_NAMESPACE);
649 applyProperty(props, "defaultFunctionNamespace", FeatureKeys.XQUERY_DEFAULT_FUNCTION_NAMESPACE);
650 applyProperty(props, "emptyLeast", FeatureKeys.XQUERY_EMPTY_LEAST);
651 applyProperty(props, "inheritNamespaces", FeatureKeys.XQUERY_INHERIT_NAMESPACES);
652 applyProperty(props, "moduleUriResolver", FeatureKeys.MODULE_URI_RESOLVER_CLASS);
653 applyProperty(props, "preserveBoundarySpace", FeatureKeys.XQUERY_PRESERVE_BOUNDARY_SPACE);
654 applyProperty(props, "preserveNamespaces", FeatureKeys.XQUERY_PRESERVE_NAMESPACES);
655 applyProperty(props, "requiredContextItemType", FeatureKeys.XQUERY_REQUIRED_CONTEXT_ITEM_TYPE);
656 applyProperty(props, "schemaAware", FeatureKeys.XQUERY_SCHEMA_AWARE);
657 applyProperty(props, "staticErrorListener", FeatureKeys.XQUERY_STATIC_ERROR_LISTENER_CLASS);
658 applyProperty(props, "version", FeatureKeys.XQUERY_VERSION);
659 }
660
661 private void readXsltElement(Attributes atts) {
662 Properties props = new Properties();
663 for (int i = 0; i < atts.getLength(); i++) {
664 String name = atts.getLocalName(i);
665 String value = atts.getValue(i);
666 if (!value.isEmpty() && atts.getURI(i).isEmpty()) {
667 props.put(name, value);
668 }
669 }
670 props.put("#element", "xslt");
671 applyProperty(props, "disableXslEvaluate", FeatureKeys.DISABLE_XSL_EVALUATE);
672 applyProperty(props, "enableAssertions", FeatureKeys.XSLT_ENABLE_ASSERTIONS);
673 applyProperty(props, "initialMode", FeatureKeys.XSLT_INITIAL_MODE);
674 applyProperty(props, "initialTemplate", FeatureKeys.XSLT_INITIAL_TEMPLATE);
675 applyProperty(props, "messageEmitter", FeatureKeys.MESSAGE_EMITTER_CLASS);
676 applyProperty(props, "outputUriResolver", FeatureKeys.OUTPUT_URI_RESOLVER_CLASS);
677 applyProperty(props, "recoveryPolicy", FeatureKeys.RECOVERY_POLICY_NAME);
678 applyProperty(props, "resultDocumentThreads", FeatureKeys.RESULT_DOCUMENT_THREADS);
679 applyProperty(props, "schemaAware", FeatureKeys.XSLT_SCHEMA_AWARE);
680 applyProperty(props, "staticErrorListener", FeatureKeys.XSLT_STATIC_ERROR_LISTENER_CLASS);
681 applyProperty(props, "staticUriResolver", FeatureKeys.XSLT_STATIC_URI_RESOLVER_CLASS);
682 applyProperty(props, "strictStreamability", FeatureKeys.STRICT_STREAMABILITY);
683 applyProperty(props, "styleParser", FeatureKeys.STYLE_PARSER_CLASS);
684 applyProperty(props, "version", FeatureKeys.XSLT_VERSION);
685 //applyProperty(props, "versionWarning", FeatureKeys.VERSION_WARNING);
686 }
687
688 private void readXsdElement(Attributes atts) {
689 Properties props = new Properties();
690 for (int i = 0; i < atts.getLength(); i++) {
691 String name = atts.getLocalName(i);
692 String value = atts.getValue(i);
693 if (!value.isEmpty() && atts.getURI(i).isEmpty()) {
694 props.put(name, value);
695 }
696 }
697 props.put("#element", "xsd");
698 applyProperty(props, "assertionsCanSeeComments", FeatureKeys.ASSERTIONS_CAN_SEE_COMMENTS);
699 applyProperty(props, "implicitSchemaImports", FeatureKeys.IMPLICIT_SCHEMA_IMPORTS);
700 applyProperty(props, "multipleSchemaImports", FeatureKeys.MULTIPLE_SCHEMA_IMPORTS);
701 applyProperty(props, "occurrenceLimits", FeatureKeys.OCCURRENCE_LIMITS);
702 applyProperty(props, "schemaUriResolver", FeatureKeys.SCHEMA_URI_RESOLVER_CLASS);
703 applyProperty(props, "thresholdForCompilingTypes", FeatureKeys.THRESHOLD_FOR_COMPILING_TYPES);
704 applyProperty(props, "useXsiSchemaLocation", FeatureKeys.USE_XSI_SCHEMA_LOCATION);
705 applyProperty(props, "version", FeatureKeys.XSD_VERSION);
706 }
707
708 private void error(String element, String attribute, String actual, String required) {
709 XPathException err;
710 if (attribute == null) {
711 err = new XPathException("Invalid configuration element " + element);
712 } else if (actual == null) {
713 err = new XPathException("Missing configuration property " +
714 element + "/@" + attribute);
715 } else {
716 err = new XPathException("Invalid configuration property " +
717 element + "/@" + attribute + ". Supplied value '" + actual + "'. " + required);
718 }
719 err.setLocator(ExplicitLocation.makeFromSax(locator));
720 errors.add(err);
721 }
722
723 protected void error(XPathException err) {
724 err.setLocator(ExplicitLocation.makeFromSax(locator));
725 errors.add(err);
726 }
727
728 protected void errorClass(String element, String attribute, String actual, Class required, Exception cause) {
729 XPathException err = new XPathException("Invalid configuration property " +
730 element + (attribute == null ? "" : "/@" + attribute) +
731 ". Supplied value '" + actual +
732 "', required value is the name of a class that implements '" + required.getName() + "'", cause);
733 err.setLocator(ExplicitLocation.makeFromSax(locator));
734 errors.add(err);
735 }
736
737 public void endElement(String uri, String localName, String qName) {
738 if (level == 3 && "resources".equals(section)) {
739 String content = buffer.toString();
740 if (!content.isEmpty()) {
741 if ("externalObjectModel".equals(localName)) {
742 try {
743 ExternalObjectModel model = (ExternalObjectModel) config.getInstance(content, null);
744 config.registerExternalObjectModel(model);
745 } catch (XPathException | ClassCastException e) {
746 errorClass("externalObjectModel", null, content, ExternalObjectModel.class, e);
747 }
748 } else if ("extensionFunction".equals(localName)) {
749 try {
750 ExtensionFunctionDefinition model = (ExtensionFunctionDefinition) config.getInstance(content, null);
751 config.registerExtensionFunction(model);
752 } catch (XPathException | ClassCastException | IllegalArgumentException e) {
753 errorClass("extensionFunction", null, content, ExtensionFunctionDefinition.class, e);
754 }
755 } else if ("schemaDocument".equals(localName)) {
756 try {
757 Source source = getInputSource(content);
758 config.addSchemaSource(source);
759 } catch (SchemaException e) {
760 errors.add(XPathException.makeXPathException(e));
761 } catch (XPathException e) {
762 errors.add(e);
763 }
764 } else if ("schemaComponentModel".equals(localName)) {
765 try {
766 Source source = getInputSource(content);
767 config.importComponents(source);
768 } catch (XPathException e) {
769 errors.add(e);
770 }
771 } else if ("fileExtension".equals(localName)) {
772 // already done at startElement time
773 } else {
774 error(localName, null, null, null);
775 }
776 }
777 }
778 level--;
779 buffer.setLength(0);
780 namespaceStack.pop();
781 }
782
783 private Source getInputSource(String href) throws XPathException {
784 try {
785 String base = locator.getSystemId();
786 URI abs = ResolveURI.makeAbsolute(href, base);
787 return new StreamSource(abs.toString());
788 } catch (URISyntaxException e) {
789 throw new XPathException(e);
790 }
791 }
792
793 public void characters(char ch[], int start, int length) {
794 buffer.append(ch, start, length);
795 }
796
797 public void ignorableWhitespace(char ch[], int start, int length) {
798
799 }
800
801 public void processingInstruction(String target, String data) {
802
803 }
804
805 public void skippedEntity(String name) {
806
807 }
808
809 /////////////////////////////////////////////////////
810 // Implement NamespaceResolver
811 /////////////////////////////////////////////////////
812
813 /**
814 * Get the namespace URI corresponding to a given prefix. Return null
815 * if the prefix is not in scope.
816 *
817 * @param prefix the namespace prefix. May be the zero-length string, indicating
818 * that there is no prefix. This indicates either the default namespace or the
819 * null namespace, depending on the value of useDefault.
820 * @param useDefault true if the default namespace is to be used when the
821 * prefix is "". If false, the method returns "" when the prefix is "".
822 * @return the uri for the namespace, or null if the prefix is not in scope.
823 * The "null namespace" is represented by the pseudo-URI "".
824 */
825
826 public String getURIForPrefix(String prefix, boolean useDefault) {
827 for (int i = namespaceStack.size() - 1; i >= 0; i--) {
828 List<String[]> list = namespaceStack.get(i);
829 for (String[] pair : list) {
830 if (pair[0].equals(prefix)) {
831 return pair[1];
832 }
833 }
834 }
835 return null;
836 }
837
838 /**
839 * Get an iterator over all the prefixes declared in this namespace context. This will include
840 * the default namespace (prefix="") and the XML namespace where appropriate
841 */
842
843 public Iterator<String> iteratePrefixes() {
844 Set<String> prefixes = new HashSet<>();
845 for (List<String[]> list : namespaceStack) {
846 for (String[] pair : list) {
847 prefixes.add(pair[0]);
848 }
849 }
850 return prefixes.iterator();
851 }
852 }
853