Search in sources :

Example 1 with XdmNode

use of net.sf.saxon.s9api.XdmNode in project nifi by apache.

the class EvaluateXQuery method writeformattedItem.

void writeformattedItem(XdmItem item, ProcessContext context, OutputStream out) throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException, IOException {
    if (item.isAtomicValue()) {
        out.write(item.getStringValue().getBytes(UTF8));
    } else {
        // item is an XdmNode
        XdmNode node = (XdmNode) item;
        switch(node.getNodeKind()) {
            case DOCUMENT:
            case ELEMENT:
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                final Properties props = getTransformerProperties(context);
                transformer.setOutputProperties(props);
                transformer.transform(node.asSource(), new StreamResult(out));
                break;
            default:
                out.write(node.getStringValue().getBytes(UTF8));
        }
    }
}
Also used : Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Properties(java.util.Properties) XdmNode(net.sf.saxon.s9api.XdmNode)

Example 2 with XdmNode

use of net.sf.saxon.s9api.XdmNode in project ddf by codice.

the class DynamicSchemaResolver method createTinyBinary.

private byte[] createTinyBinary(String xml) throws XMLStreamException, SaxonApiException {
    SaxonDocBuilder builder = new SaxonDocBuilder(processor);
    XmlReader xmlReader = new XmlReader();
    xmlReader.addHandler(builder);
    xmlReader.setStripNamespaces(true);
    xmlReader.read(IOUtils.toInputStream(xml));
    XdmNode node = builder.getDocument();
    TinyTree tinyTree = ((TinyDocumentImpl) node.getUnderlyingNode()).getTree();
    TinyBinary tinyBinary = new TinyBinary(tinyTree, StandardCharsets.UTF_8);
    return tinyBinary.getBytes();
}
Also used : TinyDocumentImpl(net.sf.saxon.tree.tiny.TinyDocumentImpl) TinyTree(net.sf.saxon.tree.tiny.TinyTree) TinyBinary(lux.xml.tinybin.TinyBinary) XmlReader(lux.xml.XmlReader) XdmNode(net.sf.saxon.s9api.XdmNode) SaxonDocBuilder(lux.xml.SaxonDocBuilder)

Example 3 with XdmNode

use of net.sf.saxon.s9api.XdmNode in project ddf by codice.

the class XpathFilterCollector method collect.

@Override
public void collect(int docId) throws IOException {
    Document doc = this.context.reader().document(docId);
    BytesRef binaryValue = doc.getBinaryValue(LUX_XML_FIELD_NAME);
    if (binaryValue != null) {
        byte[] bytes = binaryValue.bytes;
        // Lux update chain
        if (bytes.length > 4 && bytes[0] == 'T' && bytes[1] == 'I' && bytes[2] == 'N') {
            TinyBinary tb = new TinyBinary(bytes, TinyBinaryField.UTF8);
            XdmNode node = new XdmNode(tb.getTinyDocument(config));
            try {
                selector.setContextItem(node);
                XdmItem result = selector.evaluateSingle();
                if (result != null && result.size() > 0 && !(result.isAtomicValue() && !((XdmAtomicValue) result).getBooleanValue())) {
                    super.collect(docId);
                }
            } catch (SaxonApiException e) {
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unable to evaluate xpath: " + xpath, e);
            }
        }
    }
}
Also used : TinyBinary(lux.xml.tinybin.TinyBinary) Document(org.apache.lucene.document.Document) XdmNode(net.sf.saxon.s9api.XdmNode) SaxonApiException(net.sf.saxon.s9api.SaxonApiException) BytesRef(org.apache.lucene.util.BytesRef) SolrException(org.apache.solr.common.SolrException) XdmItem(net.sf.saxon.s9api.XdmItem)

Example 4 with XdmNode

use of net.sf.saxon.s9api.XdmNode in project sirix by sirixdb.

the class TestNodeWrapperS9ApiXSLT method saxonTransform.

/**
 * Transform source document with the given stylesheet.
 *
 * @param xml
 *          Source xml file.
 * @param stylesheet
 *          Stylesheet to transform sourc xml file.
 * @throws SaxonApiException
 *           Exception from Saxon in case anything goes wrong.
 */
@Ignore("Not a test, utility method only")
public void saxonTransform(final File xml, final File stylesheet) throws SaxonApiException {
    final Processor proc = new Processor(false);
    final XsltCompiler comp = proc.newXsltCompiler();
    final XsltExecutable exp = comp.compile(new StreamSource(stylesheet));
    final XdmNode source = proc.newDocumentBuilder().build(new StreamSource(xml));
    final Serializer out = new Serializer();
    out.setOutputProperty(Serializer.Property.METHOD, "xml");
    out.setOutputProperty(Serializer.Property.INDENT, "yes");
    out.setOutputFile(new File(TestHelper.PATHS.PATH1.getFile(), "books1.html"));
    final XsltTransformer trans = exp.load();
    trans.setInitialContextNode(source);
    trans.setDestination(out);
    trans.transform();
}
Also used : Processor(net.sf.saxon.s9api.Processor) StreamSource(javax.xml.transform.stream.StreamSource) XsltTransformer(net.sf.saxon.s9api.XsltTransformer) XsltCompiler(net.sf.saxon.s9api.XsltCompiler) XdmNode(net.sf.saxon.s9api.XdmNode) File(java.io.File) XsltExecutable(net.sf.saxon.s9api.XsltExecutable) Serializer(net.sf.saxon.s9api.Serializer) Ignore(org.junit.Ignore)

Example 5 with XdmNode

use of net.sf.saxon.s9api.XdmNode in project jmeter by apache.

the class XPathUtil method computeAssertionResultUsingSaxon.

/**
 * @param result The result of xpath2 assertion
 * @param xmlFile XML data
 * @param xPathQuery XPath Query
 * @param namespaces Space separated set of prefix=namespace
 * @param isNegated invert result
 * @throws SaxonApiException when the parser has problems with the given xml or xpath query
 * @throws FactoryConfigurationError when the parser can not be instantiated
 */
public static void computeAssertionResultUsingSaxon(AssertionResult result, String xmlFile, String xPathQuery, String namespaces, Boolean isNegated) throws SaxonApiException, FactoryConfigurationError {
    // generating the cache key
    final ImmutablePair<String, String> key = ImmutablePair.of(xPathQuery, namespaces);
    // check the cache
    XPathExecutable xPathExecutable;
    if (StringUtils.isNotEmpty(xPathQuery)) {
        xPathExecutable = XPATH_CACHE.get(key);
    } else {
        log.warn("Error : {}", JMeterUtils.getResString("xpath2_extractor_empty_query"));
        return;
    }
    try (StringReader reader = new StringReader(xmlFile)) {
        // We could instantiate it once but might trigger issues in the future
        // Sharing of a DocumentBuilder across multiple threads is not recommended.
        // However, in the current implementation sharing a DocumentBuilder (once
        // initialized)
        // will only cause problems if a SchemaValidator is used.
        net.sf.saxon.s9api.DocumentBuilder builder = PROCESSOR.newDocumentBuilder();
        XdmNode xdmNode = builder.build(new SAXSource(new InputSource(reader)));
        if (xPathExecutable != null) {
            XPathSelector selector = null;
            try {
                Document doc;
                doc = XPathUtil.makeDocumentBuilder(false, false, false, false).newDocument();
                XObject xObject = XPathAPI.eval(doc, xPathQuery, getPrefixResolverForXPath2(doc, namespaces));
                selector = xPathExecutable.load();
                selector.setContextItem(xdmNode);
                XdmValue nodes = selector.evaluate();
                boolean resultOfEval = true;
                int length = nodes.size();
                // In case we need to extract everything
                if (length == 0) {
                    resultOfEval = false;
                } else if (xObject.getType() == XObject.CLASS_BOOLEAN) {
                    resultOfEval = Boolean.parseBoolean(nodes.itemAt(0).getStringValue());
                }
                result.setFailure(isNegated ? resultOfEval : !resultOfEval);
                result.setFailureMessage(isNegated ? "Nodes Matched for " + xPathQuery : "No Nodes Matched for " + xPathQuery);
            } catch (ParserConfigurationException | TransformerException e) {
                // NOSONAR Exception handled by return
                result.setError(true);
                result.setFailureMessage("Exception: " + e.getMessage() + " for:" + xPathQuery);
            } finally {
                if (selector != null) {
                    try {
                        selector.getUnderlyingXPathContext().setContextItem(null);
                    } catch (Exception e) {
                        // NOSONAR Ignored on purpose
                        result.setError(true);
                        result.setFailureMessage("Exception: " + e.getMessage() + " for:" + xPathQuery);
                    }
                }
            }
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) Document(org.w3c.dom.Document) XdmNode(net.sf.saxon.s9api.XdmNode) XMLStreamException(javax.xml.stream.XMLStreamException) SAXException(org.xml.sax.SAXException) TransformerException(javax.xml.transform.TransformerException) SaxonApiException(net.sf.saxon.s9api.SaxonApiException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) XdmValue(net.sf.saxon.s9api.XdmValue) SAXSource(javax.xml.transform.sax.SAXSource) XPathSelector(net.sf.saxon.s9api.XPathSelector) StringReader(java.io.StringReader) XPathExecutable(net.sf.saxon.s9api.XPathExecutable) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) XObject(org.apache.xpath.objects.XObject) TransformerException(javax.xml.transform.TransformerException)

Aggregations

XdmNode (net.sf.saxon.s9api.XdmNode)8 SaxonApiException (net.sf.saxon.s9api.SaxonApiException)5 IOException (java.io.IOException)3 StringReader (java.io.StringReader)3 TransformerException (javax.xml.transform.TransformerException)3 SAXSource (javax.xml.transform.sax.SAXSource)3 Processor (net.sf.saxon.s9api.Processor)3 XdmItem (net.sf.saxon.s9api.XdmItem)3 XdmValue (net.sf.saxon.s9api.XdmValue)3 InputSource (org.xml.sax.InputSource)3 SAXException (org.xml.sax.SAXException)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 XMLStreamException (javax.xml.stream.XMLStreamException)2 StreamSource (javax.xml.transform.stream.StreamSource)2 TinyBinary (lux.xml.tinybin.TinyBinary)2 Serializer (net.sf.saxon.s9api.Serializer)2 XPathExecutable (net.sf.saxon.s9api.XPathExecutable)2 XPathSelector (net.sf.saxon.s9api.XPathSelector)2 XsltCompiler (net.sf.saxon.s9api.XsltCompiler)2 XsltExecutable (net.sf.saxon.s9api.XsltExecutable)2