Debian Codegraph @

net/sf/saxon/java/JavaPlatform.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.java;
9
10 import com.saxonica.ee.bytecode.util.GeneratedClassLoader;
11 import net.sf.saxon.Configuration;
12 import net.sf.saxon.Platform;
13 import net.sf.saxon.dom.DOMEnvelope;
14 import net.sf.saxon.dom.DOMObjectModel;
15 import net.sf.saxon.event.PipelineConfiguration;
16 import net.sf.saxon.expr.StaticContext;
17 import net.sf.saxon.expr.parser.RetainedStaticContext;
18 import net.sf.saxon.expr.sort.*;
19 import net.sf.saxon.functions.FunctionLibraryList;
20 import net.sf.saxon.lib.ModuleURIResolver;
21 import net.sf.saxon.lib.StandardModuleURIResolver;
22 import net.sf.saxon.lib.StringCollator;
23 import net.sf.saxon.om.NamespaceResolver;
24 import net.sf.saxon.regex.ARegularExpression;
25 import net.sf.saxon.regex.JavaRegularExpression;
26 import net.sf.saxon.regex.RegularExpression;
27 import net.sf.saxon.resource.StandardCollectionFinder;
28 import net.sf.saxon.trans.XPathException;
29 import net.sf.saxon.type.ExternalObjectType;
30 import net.sf.saxon.xpath.JAXPXPathStaticContext;
31 import org.xml.sax.SAXException;
32 import org.xml.sax.XMLReader;
33
34 import javax.xml.namespace.NamespaceContext;
35 import javax.xml.parsers.ParserConfigurationException;
36 import javax.xml.parsers.SAXParserFactory;
37 import javax.xml.transform.Source;
38 import javax.xml.transform.TransformerFactoryConfigurationError;
39 import javax.xml.transform.stream.StreamSource;
40 import java.text.CollationKey;
41 import java.text.Collator;
42 import java.util.*;
43
44 /**
45 * Implementation of the Platform class containing methods specific to the Java platform
46 * (as distinct from .NET). This is a singleton class with no instance data.
47 */
48 public class JavaPlatform implements Platform {
49
50 /**
51 * The constructor is called during the static initialization of the Configuration
52 */
53
54 public JavaPlatform() {
55 }
56
57
58 /**
59 * Checks if the supplied static context is an instance of the JAXP static context.
60 * On Java we create namespace information from the JAXP XPath static context.
61 * On the .NET platform we do nothing.
62 * @param retainedStaticContext
63 * @param sc
64 * @return boolean
65 * @since 9.7.0.5
66 *
67 */
68
69 public boolean JAXPStaticContextCheck(RetainedStaticContext retainedStaticContext, StaticContext sc){
70 if(sc instanceof JAXPXPathStaticContext && !(((JAXPXPathStaticContext) sc).getNamespaceContext() instanceof NamespaceResolver)){
71 setNamespacesFromJAXP(retainedStaticContext, (JAXPXPathStaticContext) sc);
72 return true;
73 }
74 return false;
75 }
76
77 /**
78 * Create namespace information from the JAXP XPath static context. This
79 * case needs special treatment because the JAXP static context holds namespace information
80 * using a NamespaceContext object, which (absurdly) offers no way to iterate over all the
81 * contained namespaces.
82 *
83 * @param retainedStaticContext
84 * @param sc JAXP static context
85 */
86
87 private void setNamespacesFromJAXP(RetainedStaticContext retainedStaticContext, JAXPXPathStaticContext sc) {
88 final NamespaceContext nc = sc.getNamespaceContext();
89 retainedStaticContext.setNamespaces(new Map<String, String>() {
90 public void clear() { }
91
92 public int size() {
93 throw new UnsupportedOperationException();
94 }
95
96 public boolean isEmpty() {
97 throw new UnsupportedOperationException();
98 }
99
100 public boolean containsKey(Object key) {
101 return nc.getNamespaceURI(key.toString()) != null;
102 }
103
104 public boolean containsValue(Object value) {
105 throw new UnsupportedOperationException();
106 }
107
108 public String get(Object key) {
109 return nc.getNamespaceURI(key.toString());
110 }
111
112 public String put(String key, String value) {
113 throw new UnsupportedOperationException();
114 }
115
116 public String remove(Object key) {
117 throw new UnsupportedOperationException();
118 }
119
120 public void putAll(Map<? extends String, ? extends String> m) {
121 throw new UnsupportedOperationException();
122 }
123
124 public Set<String> keySet() {
125 throw new UnsupportedOperationException();
126 }
127
128 public Collection<String> values() {
129 throw new UnsupportedOperationException();
130 }
131
132 public Set<Entry<String, String>> entrySet() {
133 throw new UnsupportedOperationException();
134 }
135 });
136
137 }
138
139 /**
140 * Perform platform-specific initialization of the configuration
141 */
142
143 public void initialize(Configuration config) {
144 config.registerExternalObjectModel(DOMEnvelope.getInstance());
145 config.registerExternalObjectModel(DOMObjectModel.getInstance());
146 config.setCollectionFinder(new StandardCollectionFinder());
147 }
148
149 /**
150 * Return true if this is the Java platform
151 */
152
153 public boolean isJava() {
154 return true;
155 }
156
157 /**
158 * Return true if this is the .NET platform
159 */
160
161 public boolean isDotNet() {
162 return false;
163 }
164
165 /**
166 * Get the platform version
167 */
168
169 public String getPlatformVersion() {
170 return "Java version " + System.getProperty("java.version");
171 }
172
173 /**
174 * Get a suffix letter to add to the Saxon version number to identify the platform
175 */
176
177 public String getPlatformSuffix() {
178 return "J";
179 }
180
181
182 /**
183 * Get a parser by instantiating the SAXParserFactory
184 *
185 * @return the parser (XMLReader)
186 */
187
188 public XMLReader loadParser() {
189 XMLReader parser;
190 try {
191 parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
192 } catch (ParserConfigurationException err) {
193 throw new TransformerFactoryConfigurationError(err);
194 } catch (SAXException err) {
195 throw new TransformerFactoryConfigurationError(err);
196 }
197 return parser;
198 }
199
200 /**
201 * Get a parser suitable for parsing XML fragments
202 *
203 * <p>For background, see bugs 4127 and 4253. The problem is that to implement parse-xml-fragment(),
204 * we need to set an EntityResolver on the returned parser. But if an Apache catalog resolver is
205 * in use, the JAXP system properties may be set so that JAXP returns a custom XMLReader supplied
206 * by the catalog resolver, and that XMLReader ignores any attempt to set an EntityResolver. So
207 * we bypass JAXP and try to load the built-in parser within the JDK, which we know we can trust;
208 * only if this fails (presumably because this is not the Oracle JDK) do we fall back to using a
209 * JAXP-supplied parser. And if this turns out to ignore {@code setEntityResolver()} calls, we're
210 * hosed.
211 * </p>
212 *
213 * @return the parser (XMLReader)
214 */
215 public XMLReader loadParserForXmlFragments() {
216 try {
217 Class<?> factoryClass = Class.forName("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
218 SAXParserFactory factory = (SAXParserFactory) factoryClass.newInstance();
219 return factory.newSAXParser().getXMLReader();
220 } catch (Exception e) {
221 // no action; try the JAXP loading mechanism
222 }
223 return loadParser();
224 }
225
226 /**
227 * Convert a StreamSource to either a SAXSource or a PullSource, depending on the native
228 * parser of the selected platform
229 *
230 * @param pipe the pipeline configuration
231 * @param input the supplied StreamSource
232 * @param validation indicates whether schema validation is required
233 * @param dtdValidation indicates whether DTD validation is required
234 * @param stripspace indicates whether whitespace text nodes should be stripped
235 * @return the PullSource or SAXSource, initialized with a suitable parser, or the original
236 * input Source, if now special handling is required or possible. This implementation
237 * always returns the original input unchanged.
238 */
239
240 public Source getParserSource(PipelineConfiguration pipe, StreamSource input, int validation,
241 boolean dtdValidation, int stripspace) {
242 return input;
243 }
244
245 /**
246 * Obtain a collation with a given set of properties. The set of properties is extensible
247 * and variable across platforms. Common properties with example values include lang=ed-GB,
248 * strength=primary, case-order=upper-first, ignore-modifiers=yes, alphanumeric=yes.
249 * Properties that are not supported are generally ignored; however some errors, such as
250 * failing to load a requested class, are fatal.
251 *
252 * @param config the configuration object
253 * @param props the desired properties of the collation
254 * @param uri the collation URI
255 * @return a collation with these properties
256 * @throws XPathException if a fatal error occurs
257 */
258
259 /*@Nullable*/
260 public StringCollator makeCollation(Configuration config, Properties props, String uri) throws XPathException {
261 return JavaCollationFactory.makeCollation(config, uri, props);
262 }
263
264 /**
265 * Given a collation, determine whether it is capable of returning collation keys.
266 * The essential property of collation keys
267 * is that if two values are equal under the collation, then the collation keys are
268 * equal under the equals() method.
269 *
270 * @param collation the collation, provided as a Comparator
271 * @return true if this collation can supply collation keys
272 */
273
274 public boolean canReturnCollationKeys(StringCollator collation) {
275 return !(collation instanceof SimpleCollation) ||
276 ((SimpleCollation) collation).getComparator() instanceof Collator;
277 }
278
279 /**
280 * Given a collation, get a collation key. The essential property of collation keys
281 * is that if two values are equal under the collation, then the collation keys are
282 * compare correctly under the equals() method.
283 *
284 * @throws ClassCastException if the collation is not one that is capable of supplying
285 * collation keys (this should have been checked in advance)
286 */
287
288 public AtomicMatchKey getCollationKey(SimpleCollation namedCollation, String value) {
289 CollationKey ck = ((Collator) namedCollation.getComparator()).getCollationKey(value);
290 return new CollationMatchKey(ck);
291 }
292
293 /**
294 * No ICU features
295 */
296
297 public boolean hasICUCollator() {
298 return false;
299 }
300
301 public boolean hasICUNumberer() {
302 return false;
303 }
304
305 /**
306 * If available, make a collation using the ICU-J Library
307 *
308 * @param uri the collation URI (which will always be a UCA collation URI as defined in XSLT 3.0)
309 * @param config the Saxon configuration
310 * @return the collation, or null if not available
311 * @throws XPathException if the URI is malformed in some way
312 */
313
314 public StringCollator makeUcaCollator(String uri, Configuration config) throws XPathException {
315 UcaCollatorUsingJava collator = new UcaCollatorUsingJava(uri);
316 if ("yes".equals(collator.getProperties().getProperty("numeric"))) {
317 return new AlphanumericCollator(collator);
318 } else {
319 return collator;
320 }
321 }
322
323 /**
324 * Compile a regular expression
325 *
326 *
327 * @param config the Saxon configuration
328 * @param regex the regular expression as a string
329 * @param flags the value of the flags attribute
330 * @param hostLanguage one of "XSD10", "XSD11", "XP20" or "XP30". Also allow combinations, e.g. "XP20/XSD11".
331 * @param warnings if supplied, may capture warnings from the regular expression compiler
332 * @return the compiled regular expression
333 * @throws net.sf.saxon.trans.XPathException
334 * if the regular expression or the flags are invalid
335 */
336 public RegularExpression compileRegularExpression(Configuration config, CharSequence regex, String flags, String hostLanguage, List<String> warnings) throws XPathException {
337 // recognize "!" as a flag to mean: use native Java regex syntax
338 if (flags.contains("!")) {
339 // undocumented
340 return new JavaRegularExpression(regex, flags.replace("!", ""));
341 } else {
342 // recognize implementation-defined flags following a semicolon in the flags string
343 boolean useJava = false;
344 boolean useSaxon = false;
345 int semi = flags.indexOf(';');
346 if (semi >= 0) {
347 useJava = flags.indexOf('j', semi) >= 0;
348 useSaxon = flags.indexOf('s', semi) >= 0;
349 flags = flags.substring(0, semi);
350 }
351 if ("J".equals(config.getDefaultRegexEngine()) && !useSaxon) {
352 useJava = true;
353 }
354 if (useJava) {
355 return new JavaRegularExpression(regex, flags);
356 } else {
357 return new ARegularExpression(regex, flags, hostLanguage, warnings, config);
358 }
359 }
360 }
361
362 /**
363 * Add the platform-specific function libraries to a function library list. This version
364 * of the method does nothing
365 *
366 * @param list the function library list that is to be extended
367 * @param config the Configuration
368 * @param hostLanguage the host language, for example Configuration.XQUERY
369 */
370
371 public void addFunctionLibraries(FunctionLibraryList list, Configuration config, int hostLanguage) {
372 // do nothing
373 }
374
375 public ExternalObjectType getExternalObjectType(Configuration config, String uri, String localName) {
376 throw new UnsupportedOperationException("getExternalObjectType for Java");
377 }
378
379 /**
380 * Return the name of the directory in which the software is installed (if available)
381 *
382 * @param edition The edition of the software that is loaded ("HE", "PE", or "EE")
383 * @param config the Saxon configuration
384 * @return the name of the directory in which Saxon is installed, if available, or null otherwise
385 */
386
387 public String getInstallationDirectory(String edition, Configuration config) {
388 try {
389 return System.getenv("SAXON_HOME");
390 } catch (SecurityException e) {
391 return null;
392 }
393 }
394
395 /**
396 * Register all the external object models that are provided as standard
397 * with the relevant edition of Saxon for this Configuration
398 *
399 * @since 9.3
400 */
401
402 public void registerAllBuiltInObjectModels(Configuration config) {
403 // No action for Saxon-HE
404 }
405
406 /**
407 * Set the default XML parser to be loaded by the SAXParserFactory on this platform.
408 * Needed because the Apache catalog resolver uses the SAXParserFactory to instantiate
409 * a parser, and if not customized this causes a failure on the .NET platform.
410 *
411 * @since 9.4
412 */
413
414 public void setDefaultSAXParserFactory(Configuration config) {
415 // No action for Saxon on Java
416 }
417
418 public ModuleURIResolver makeStandardModuleURIResolver(Configuration config) {
419 return new StandardModuleURIResolver(config);
420 }
421
422
423 //#if BYTECODE==true
424 /**
425 * Return the class loader required to load the bytecode generated classes
426 * @param config The saxon configuration
427 * @param thisClass The class object generated
428 * @return the class loader object
429 * @since 9.6.0.3
430 */
431 public ClassLoader makeGeneratedClassLoader(Configuration config, Class thisClass) {
432 ClassLoader parentClassLoader = config.getDynamicLoader().getClassLoader();
433 if (parentClassLoader == null) {
434 parentClassLoader = Thread.currentThread().getContextClassLoader();
435 }
436 if (parentClassLoader == null) {
437 parentClassLoader = thisClass.getClassLoader();
438 }
439 return new GeneratedClassLoader(parentClassLoader);
440 }
441 //#endif
442
443
444 }
445