Debian Codegraph @

net/sf/saxon/jaxp/AbstractTransformerImpl.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.jaxp;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.event.Receiver;
13 import net.sf.saxon.expr.JPConverter;
14 import net.sf.saxon.expr.XPathContext;
15 import net.sf.saxon.expr.parser.ExplicitLocation;
16 import net.sf.saxon.expr.parser.RoleDiagnostic;
17 import net.sf.saxon.lib.NamespaceConstant;
18 import net.sf.saxon.om.Item;
19 import net.sf.saxon.om.Sequence;
20 import net.sf.saxon.s9api.*;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.type.JavaExternalObjectType;
23 import net.sf.saxon.value.EmptySequence;
24 import net.sf.saxon.value.ObjectValue;
25 import net.sf.saxon.value.UntypedAtomicValue;
26 import org.w3c.dom.Node;
27 import org.xml.sax.XMLFilter;
28
29 import javax.xml.parsers.DocumentBuilderFactory;
30 import javax.xml.parsers.ParserConfigurationException;
31 import javax.xml.transform.Result;
32 import javax.xml.transform.dom.DOMResult;
33 import javax.xml.transform.sax.SAXResult;
34 import javax.xml.transform.stream.StreamResult;
35 import java.io.File;
36 import java.io.FileNotFoundException;
37 import java.io.FileOutputStream;
38 import java.io.IOException;
39 import java.net.URI;
40 import java.net.URISyntaxException;
41 import java.util.HashMap;
42 import java.util.Map;
43 import java.util.Properties;
44
45 /**
46 * Saxon implementation of the JAXP Transformer interface.
47 * <p>Since Saxon 9.6, JAXP interfaces are implemented as a layer above the s9api interface</p>
48 */
49 abstract class AbstractTransformerImpl extends IdentityTransformer {
50
51 private XsltExecutable xsltExecutable;
52 private Map<String, Object> parameters = new HashMap<>(8);
53
54 protected AbstractTransformerImpl(XsltExecutable e) {
55 super(e.getProcessor().getUnderlyingConfiguration());
56 this.xsltExecutable = e;
57 }
58
59 @SuppressWarnings("ResultOfMethodCallIgnored")
60 protected Destination makeDestination(final Result outputTarget) throws XPathException {
61 Destination destination;
62
63 if (outputTarget instanceof StreamResult) {
64 StreamResult sr = (StreamResult) outputTarget;
65 if (sr.getOutputStream() != null) {
66 destination = xsltExecutable.getProcessor().newSerializer(sr.getOutputStream());
67 } else if (sr.getWriter() != null) {
68 destination = xsltExecutable.getProcessor().newSerializer(sr.getWriter());
69 } else if (sr.getSystemId() != null) {
70 URI uri;
71 try {
72 uri = new URI(sr.getSystemId());
73 } catch (URISyntaxException e) {
74 throw new XPathException("System ID in Result object is not a valid URI: " + sr.getSystemId(), e);
75 }
76 if (!uri.isAbsolute()) {
77 try {
78 uri = new File(sr.getSystemId()).getAbsoluteFile().toURI();
79 } catch (Exception e) {
80 // if we fail, we'll get another exception
81 }
82 }
83 File file = new File(uri);
84 try {
85 if ("file".equals(uri.getScheme()) && !file.exists()) {
86 File directory = file.getParentFile();
87 if (directory != null && !directory.exists()) {
88 directory.mkdirs();
89 }
90 file.createNewFile();
91 }
92 } catch (IOException err) {
93 throw new XPathException("Failed to create output file " + uri, err);
94 }
95 FileOutputStream stream;
96 try {
97 stream = new FileOutputStream(file);
98 } catch (FileNotFoundException e) {
99 throw new XPathException("Failed to create output file", e);
100 }
101 destination = xsltExecutable.getProcessor().newSerializer(stream);
102 ((Serializer) destination).setCloseOnCompletion(true);
103 } else {
104 throw new IllegalArgumentException("StreamResult supplies neither an OutputStream nor a Writer");
105 }
106 // Copy the local (API-defined) output properties to the Serializer.
107 // (The stylesheet-defined properties will be copied later)
108 Properties localOutputProperties = getLocalOutputProperties();
109 for (String key : localOutputProperties.stringPropertyNames()) {
110 QName propertyName = QName.fromClarkName(key);
111 if (!(propertyName.getNamespaceURI().equals(NamespaceConstant.SAXON) && propertyName.getLocalName().equals("next-in-chain"))) {
112 ((Serializer) destination).setOutputProperty(QName.fromClarkName(key),
113 localOutputProperties.getProperty(key));
114 }
115 }
116 } else if (outputTarget instanceof SAXResult) {
117 destination = new SAXDestination(((SAXResult) outputTarget).getHandler());
118 } else if (outputTarget instanceof DOMResult) {
119 Node root = ((DOMResult) outputTarget).getNode();
120 if (root == null) {
121 try {
122 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
123 dbf.setNamespaceAware(true);
124 root = dbf.newDocumentBuilder().newDocument();
125 ((DOMResult) outputTarget).setNode(root);
126 } catch (ParserConfigurationException e) {
127 throw new XPathException(e);
128 }
129 }
130 destination = new DOMDestination(root);
131 } else if (outputTarget instanceof Receiver) {
132 destination = new ReceivingDestination((Receiver)outputTarget);
133 } else {
134 return null;
135 }
136 return destination;
137 }
138
139
140
141 /**
142 * Add a parameter for the transformation.
143 * <p>Pass a qualified name as a two-part string, the namespace URI
144 * enclosed in curly braces ({}), followed by the local name. If the
145 * name has a null URL, the String only contain the local name. An
146 * application can safely check for a non-null URI by testing to see if the
147 * first character of the name is a '{' character.</p>
148 * <p>For example, if a URI and local name were obtained from an element
149 * defined with &lt;xyz:foo
150 * xmlns:xyz="http://xyz.foo.com/yada/baz.html"/&gt;,
151 * then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo".
152 * Note that no prefix is used.</p>
153 *
154 * @param name The name of the parameter, which may begin with a
155 * namespace URI in curly braces ({}).
156 * @param value The value object. This can be any valid Java object. It is
157 * up to the processor to provide the proper object coersion or to simply
158 * pass the object on for use in an extension.
159 * @throws NullPointerException If value is null.
160 * @throws IllegalArgumentException If the supplied value cannot be converted to the declared
161 * type of the corresponding stylesheet parameter
162 */
163 @Override
164 public void setParameter(String name, Object value) {
165 if (name == null) {
166 throw new NullPointerException("Transformer.setParameter() - name is null");
167 }
168 if (value == null) {
169 throw new NullPointerException("Transformer.setParameter() - value is null");
170 }
171 parameters.put(name, value);
172 QName qName = QName.fromClarkName(name);
173 XsltExecutable.ParameterDetails details = xsltExecutable.getGlobalParameters().get(qName);
174 if (details == null) {
175 // no parameter with this name is defined; we can simply ignore it
176 return;
177 }
178 Configuration config = getConfiguration();
179 net.sf.saxon.value.SequenceType required = details.getUnderlyingDeclaredType();
180 Sequence<?> converted;
181 try {
182 if (value instanceof Sequence) {
183 converted = (Sequence)value;
184 } else if (value instanceof String) {
185 converted = new UntypedAtomicValue((String) value);
186 } else if (required.getPrimaryType() instanceof JavaExternalObjectType) {
187 converted = new ObjectValue<>(value);
188 } else {
189 JPConverter converter = JPConverter.allocate(value.getClass(), null, config);
190 XPathContext context = getUnderlyingController().newXPathContext();
191 converted = converter.convert(value, context);
192 }
193 if (converted == null) {
194 converted = EmptySequence.getInstance();
195 }
196
197 if (required != null && !required.matches(converted, config.getTypeHierarchy())) {
198 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.VARIABLE, qName.toString(), -1);
199 converted = config.getTypeHierarchy().applyFunctionConversionRules(
200 converted, required, role, ExplicitLocation.UNKNOWN_LOCATION);
201 }
202 } catch (XPathException e) {
203 throw new IllegalArgumentException(e);
204 }
205
206 setConvertedParameter(qName, XdmValue.wrap(converted));
207 }
208
209 protected abstract void setConvertedParameter(QName name, XdmValue value);
210
211 /**
212 * Get a parameter that was explicitly set with setParameter.
213 * <p>This method does not return a default parameter value, which
214 * cannot be determined until the node context is evaluated during
215 * the transformation process.</p>
216 *
217 * @param name of <code>Object</code> to get
218 * @return A parameter that has been set with setParameter, or null if no parameter
219 * with this name has been set.
220 */
221 @Override
222 public Object getParameter(String name) {
223 return parameters.get(name);
224 }
225
226 /**
227 * Clear all parameters set with setParameter.
228 */
229 @Override
230 public void clearParameters() {
231 parameters.clear();
232 }
233
234 /**
235 * Get the output properties defined in the unnamed xsl:output declaration(s) within
236 * the stylesheet
237 * @return the values of output properties set in the stylesheet
238 */
239
240 @Override
241 protected Properties getStylesheetOutputProperties() {
242 return xsltExecutable.getUnderlyingCompiledStylesheet().getPrimarySerializationProperties().getProperties();
243 }
244
245 /**
246 * Get the underlying s9api implementation class representing the compled stylesheet
247 * which this transformer is executing
248 * @return the underlying s9api XsltExecutable
249 */
250
251 public XsltExecutable getUnderlyingXsltExecutable() {
252 return xsltExecutable;
253 }
254
255 /**
256 * Get the internal Saxon Controller instance that implements this transformation.
257 * Note that the Controller interface will not necessarily remain stable in future releases
258 * @return the underlying Saxon Controller instance
259 */
260
261 public abstract Controller getUnderlyingController();
262
263 /**
264 * Create a JAXP XMLFilter which allows this transformation to be added to a SAX pipeline
265 *
266 * @return the transformation in the form of an XMLFilter. If the originating <code>TransformerFactory</code>
267 * was an <code>StreamingTransformerFactory</code> and the stylesheet is streamable, then this XMLFilter
268 * will operate in streaming mode.
269 */
270
271 public abstract XMLFilter newXMLFilter();
272
273
274 }
275