Debian Codegraph @

net/sf/saxon/functions/ParseXmlFragment.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.functions;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.Version;
13 import net.sf.saxon.event.Builder;
14 import net.sf.saxon.event.ProxyReceiver;
15 import net.sf.saxon.event.Receiver;
16 import net.sf.saxon.event.Sender;
17 import net.sf.saxon.expr.Callable;
18 import net.sf.saxon.expr.PackageData;
19 import net.sf.saxon.expr.XPathContext;
20 import net.sf.saxon.expr.parser.Location;
21 import net.sf.saxon.lib.ParseOptions;
22 import net.sf.saxon.om.*;
23 import net.sf.saxon.style.StylesheetPackage;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.tree.tiny.TinyBuilder;
26 import net.sf.saxon.type.SchemaType;
27 import net.sf.saxon.value.StringValue;
28 import org.xml.sax.InputSource;
29 import org.xml.sax.XMLReader;
30
31 import javax.xml.transform.sax.SAXSource;
32 import java.io.StringReader;
33 import java.util.ArrayList;
34 import java.util.List;
35
36 public class ParseXmlFragment extends SystemFunction implements Callable {
37
38 /**
39 * Evaluate the expression
40 *
41 * @param context the dynamic evaluation context
42 * @param arguments the values of the arguments, supplied as SequenceIterators
43 * @return the result of the evaluation, in the form of a SequenceIterator
44 * @throws net.sf.saxon.trans.XPathException
45 * if a dynamic error occurs during the evaluation of the expression
46 */
47 public ZeroOrOne<NodeInfo> call(XPathContext context, Sequence[] arguments) throws XPathException {
48 StringValue input = (StringValue) arguments[0].head();
49 return input == null ? ZeroOrOne.empty() : new ZeroOrOne<>(evalParseXml(input, context));
50 }
51
52 private NodeInfo evalParseXml(StringValue inputArg, XPathContext context) throws XPathException {
53 NodeInfo node = null;
54 final String baseURI = getStaticBaseUriString();
55 ParseXml.RetentiveErrorHandler errorHandler = new ParseXml.RetentiveErrorHandler();
56
57 int attempt = 0;
58 while (attempt++ < 3) {
59 try {
60 Controller controller = context.getController();
61 if (controller == null) {
62 throw new XPathException("parse-xml-fragment() function is not available in this environment");
63 }
64 Configuration configuration = controller.getConfiguration();
65 final StringReader fragmentReader = new StringReader(inputArg.getStringValue());
66
67 String skeleton = "<!DOCTYPE z [<!ENTITY e SYSTEM \"http://www.saxonica.com/parse-xml-fragment/actual.xml\">]>\n<z>&e;</z>";
68 StringReader skeletonReader = new StringReader(skeleton);
69
70 InputSource is = new InputSource(skeletonReader);
71 is.setSystemId(baseURI);
72 SAXSource source = new SAXSource(is);
73 XMLReader reader;
74 if (attempt == 1234) {
75 reader = configuration.getSourceParser();
76 if (reader.getEntityResolver() != null) {
77 continue;
78 // we don't want to overwrite the existing EntityResolver; try again
79 // with a clean parser
80 }
81 } else {
82 //try {
83 reader = Version.platform.loadParserForXmlFragments();// SAXParserFactoryImpl.newInstance().newSAXParser().getXMLReader();
84 /*} catch (ParserConfigurationException | SAXException e) {
85 throw XPathException.makeXPathException(e);
86 } */
87
88 }
89
90 source.setXMLReader(reader);
91 source.setSystemId(baseURI);
92
93 Builder b = controller.makeBuilder();
94 if (b instanceof TinyBuilder) {
95 ((TinyBuilder) b).setStatistics(controller.getConfiguration().getTreeStatistics().FN_PARSE_STATISTICS);
96 }
97 Receiver s = b;
98 ParseOptions options = new ParseOptions();
99 List<Boolean> safetyCheck = new ArrayList<>();
100 reader.setEntityResolver((publicId, systemId) -> {
101 if ("http://www.saxonica.com/parse-xml-fragment/actual.xml".equals(systemId)) {
102 safetyCheck.add(true);
103 InputSource is1 = new InputSource(fragmentReader);
104 is1.setSystemId(baseURI);
105 return is1;
106 } else {
107 return null;
108 }
109 });
110 PackageData pd = getRetainedStaticContext().getPackageData();
111 if (pd instanceof StylesheetPackage) {
112 options.setSpaceStrippingRule(((StylesheetPackage) pd).getSpaceStrippingRule());
113 if (((StylesheetPackage) pd).isStripsTypeAnnotations()) {
114 s = configuration.getAnnotationStripper(s);
115 }
116 } else {
117 options.setSpaceStrippingRule(IgnorableSpaceStrippingRule.getInstance());
118 }
119 options.setErrorHandler(errorHandler);
120
121 s.setPipelineConfiguration(b.getPipelineConfiguration());
122
123 options.addFilter(OuterElementStripper::new);
124
125 try {
126 Sender.send(source, s, options);
127 } catch (XPathException e) {
128 // this might be because the EntityResolver wasn't called - see bug 4127
129 if (safetyCheck.isEmpty()) {
130 // This means our entity resolver wasn't called. Make one more try, using the
131 // built-in platform default parser; then give up.
132 if (attempt == 2) {
133 XPathException xe = new XPathException("The configured XML parser cannot be used by fn:parse-xml-fragment(), because it ignores the supplied EntityResolver", "FODC0006");
134 errorHandler.captureRetainedErrors(xe);
135 xe.maybeSetContext(context);
136 throw xe;
137 } else {
138 continue;
139 }
140 } else {
141 throw e;
142 }
143 }
144
145 node = b.getCurrentRoot();
146 b.reset();
147 } catch (XPathException err) {
148 XPathException xe = new XPathException("First argument to parse-xml-fragment() is not a well-formed and namespace-well-formed XML fragment. XML parser reported: " +
149 err.getMessage(), "FODC0006");
150 errorHandler.captureRetainedErrors(xe);
151 xe.maybeSetContext(context);
152 throw xe;
153 }
154 }
155 return node;
156 }
157
158 /**
159 * Filter to remove the element wrapper added to the document to satisfy the XML parser
160 */
161
162 private static class OuterElementStripper extends ProxyReceiver {
163
164 public OuterElementStripper(Receiver next) {
165 super(next);
166 }
167
168 private int level = 0;
169 private boolean suppressStartContent = false;
170
171 /**
172 * Notify the start of an element
173 * @param elemName integer code identifying the name of the element within the name pool.
174 * @param typeCode integer code identifying the element's type within the name pool.
175 * @param location location of the origin of the event
176 * @param properties properties of the element node
177 */
178 @Override
179 public void startElement(NodeName elemName, SchemaType typeCode, Location location, int properties) throws XPathException {
180 if (level > 0) {
181 super.startElement(elemName, typeCode, location, properties);
182 } else {
183 // The Linked Tree builder rejects two calls on startContent(), so we must suppress the next one
184 suppressStartContent = true;
185 }
186 level++;
187 }
188
189 @Override
190 public void startContent() throws XPathException {
191 if (!suppressStartContent) {
192 super.startContent();
193 }
194 suppressStartContent = false;
195 }
196
197 /**
198 * End of element
199 */
200 @Override
201 public void endElement() throws XPathException {
202 level--;
203 if (level > 0) {
204 super.endElement();
205 }
206 }
207 }
208 }
209
210 //Copyright (c) 2012 Saxonica Limited.