Search in sources :

Example 1 with XPathEvaluator

use of net.sf.saxon.xpath.XPathEvaluator in project webmagic by code4craft.

the class Xpath2Selector method init.

private void init() throws XPathExpressionException {
    XPathEvaluator xPathEvaluator = new XPathEvaluator();
    xPathEvaluator.setNamespaceContext(XPath2NamespaceContext.INSTANCE);
    xPathExpression = xPathEvaluator.compile(xpathStr);
}
Also used : XPathEvaluator(net.sf.saxon.xpath.XPathEvaluator)

Example 2 with XPathEvaluator

use of net.sf.saxon.xpath.XPathEvaluator in project camel by apache.

the class SaxonConverterTest method setUp.

@Before
public void setUp() throws Exception {
    super.setUp();
    exchange = new DefaultExchange(context);
    evaluator = new XPathEvaluator();
    doc = evaluator.getConfiguration().buildDocumentTree(new StringSource(CONTENT)).getRootNode();
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) XPathEvaluator(net.sf.saxon.xpath.XPathEvaluator) StringSource(org.apache.camel.StringSource) Before(org.junit.Before)

Example 3 with XPathEvaluator

use of net.sf.saxon.xpath.XPathEvaluator in project carbon-business-process by wso2.

the class XPathExpressionRuntime method evaluate.

private Object evaluate(String exp, EvaluationContext evalCtx, QName type) {
    try {
        XPathFactory xpf = new XPathFactoryImpl();
        JaxpFunctionResolver funcResolve = new JaxpFunctionResolver(evalCtx);
        xpf.setXPathFunctionResolver(funcResolve);
        XPathEvaluator xpe = (XPathEvaluator) xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolve);
        xpe.setBackwardsCompatible(true);
        xpe.setNamespaceContext(evalCtx.getNameSpaceContextOfTask());
        XPathExpression xpathExpression = xpe.compile(exp);
        Node contextNode = evalCtx.getRootNode() == null ? DOMUtils.newDocument() : evalCtx.getRootNode();
        Object evalResult = xpathExpression.evaluate(contextNode, type);
        if (evalResult != null && log.isDebugEnabled()) {
            log.debug("Expression " + exp + " generate result " + evalResult + " - type=" + evalResult.getClass().getName());
            if (evalCtx.getRootNode() != null) {
                log.debug("Was using context node " + DOMUtils.domToString(evalCtx.getRootNode()));
            }
        }
        return evalResult;
    } catch (XPathFactoryConfigurationException e) {
        log.error("Exception occurred while creating XPathFactory.", e);
        throw new XPathProcessingException("Exception occurred while creating XPathFactory.", e);
    } catch (XPathExpressionException e) {
        String msg = "Error evaluating XPath expression: " + exp;
        log.error(msg, e);
        throw new XPathProcessingException(msg, e);
    } catch (ParserConfigurationException e) {
        String msg = "XML Parsing error.";
        log.error(msg, e);
        throw new XPathProcessingException(msg, e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new XPathProcessingException(e.getMessage(), e);
    }
}
Also used : XPathFactoryImpl(net.sf.saxon.xpath.XPathFactoryImpl) XPathEvaluator(net.sf.saxon.xpath.XPathEvaluator) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) HumanTaskRuntimeException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 4 with XPathEvaluator

use of net.sf.saxon.xpath.XPathEvaluator in project ph-schematron by phax.

the class PSXPathBoundSchema method _createXPathContext.

@Nonnull
private XPath _createXPathContext() {
    final MapBasedNamespaceContext aNamespaceContext = getNamespaceContext();
    final XPath aXPathContext = XPathHelper.createNewXPath(m_aXPathFactory, m_aXPathVariableResolver, m_aXPathFunctionResolver, aNamespaceContext);
    if ("net.sf.saxon.xpath.XPathEvaluator".equals(aXPathContext.getClass().getName())) {
        // Saxon implementation special handling
        final XPathEvaluator aSaxonXPath = (XPathEvaluator) aXPathContext;
        // Since 9.7.0-4 it must implement NamespaceResolver
        aSaxonXPath.setNamespaceContext(new SaxonNamespaceContext(aNamespaceContext));
        // Wrap the PSErrorHandler to a ErrorListener
        aSaxonXPath.getConfiguration().setErrorListener(new PSErrorListener(getErrorHandler()));
    }
    return aXPathContext;
}
Also used : MapBasedNamespaceContext(com.helger.xml.namespace.MapBasedNamespaceContext) XPath(javax.xml.xpath.XPath) SaxonNamespaceContext(com.helger.schematron.saxon.SaxonNamespaceContext) XPathEvaluator(net.sf.saxon.xpath.XPathEvaluator) PSErrorListener(com.helger.schematron.xslt.util.PSErrorListener) Nonnull(javax.annotation.Nonnull)

Example 5 with XPathEvaluator

use of net.sf.saxon.xpath.XPathEvaluator in project nifi by apache.

the class EvaluateXPath method onTrigger.

@Override
@SuppressWarnings("unchecked")
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final List<FlowFile> flowFiles = session.get(50);
    if (flowFiles.isEmpty()) {
        return;
    }
    final ComponentLog logger = getLogger();
    final XMLReader xmlReader;
    try {
        xmlReader = XMLReaderFactory.createXMLReader();
    } catch (SAXException e) {
        logger.error("Error while constructing XMLReader {}", new Object[] { e });
        throw new ProcessException(e.getMessage());
    }
    if (!context.getProperty(VALIDATE_DTD).asBoolean()) {
        xmlReader.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                return new InputSource(new StringReader(""));
            }
        });
    }
    final XPathFactory factory = factoryRef.get();
    final XPathEvaluator xpathEvaluator = (XPathEvaluator) factory.newXPath();
    final Map<String, XPathExpression> attributeToXPathMap = new HashMap<>();
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (!entry.getKey().isDynamic()) {
            continue;
        }
        final XPathExpression xpathExpression;
        try {
            xpathExpression = xpathEvaluator.compile(entry.getValue());
            attributeToXPathMap.put(entry.getKey().getName(), xpathExpression);
        } catch (XPathExpressionException e) {
            // should not happen because we've already validated the XPath (in XPathValidator)
            throw new ProcessException(e);
        }
    }
    final XPathExpression slashExpression;
    try {
        slashExpression = xpathEvaluator.compile("/");
    } catch (XPathExpressionException e) {
        logger.error("unable to compile XPath expression due to {}", new Object[] { e });
        session.transfer(flowFiles, REL_FAILURE);
        return;
    }
    final String destination = context.getProperty(DESTINATION).getValue();
    final QName returnType;
    switch(context.getProperty(RETURN_TYPE).getValue()) {
        case RETURN_TYPE_AUTO:
            if (DESTINATION_ATTRIBUTE.equals(destination)) {
                returnType = STRING;
            } else if (DESTINATION_CONTENT.equals(destination)) {
                returnType = NODESET;
            } else {
                throw new IllegalStateException("The only possible destinations should be CONTENT or ATTRIBUTE...");
            }
            break;
        case RETURN_TYPE_NODESET:
            returnType = NODESET;
            break;
        case RETURN_TYPE_STRING:
            returnType = STRING;
            break;
        default:
            throw new IllegalStateException("There are no other return types...");
    }
    flowFileLoop: for (FlowFile flowFile : flowFiles) {
        final AtomicReference<Throwable> error = new AtomicReference<>(null);
        final AtomicReference<Source> sourceRef = new AtomicReference<>(null);
        session.read(flowFile, new InputStreamCallback() {

            @Override
            public void process(final InputStream rawIn) throws IOException {
                try (final InputStream in = new BufferedInputStream(rawIn)) {
                    final List<Source> rootList = (List<Source>) slashExpression.evaluate(new SAXSource(xmlReader, new InputSource(in)), NODESET);
                    sourceRef.set(rootList.get(0));
                } catch (final Exception e) {
                    error.set(e);
                }
            }
        });
        if (error.get() != null) {
            logger.error("unable to evaluate XPath against {} due to {}; routing to 'failure'", new Object[] { flowFile, error.get() });
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }
        final Map<String, String> xpathResults = new HashMap<>();
        for (final Map.Entry<String, XPathExpression> entry : attributeToXPathMap.entrySet()) {
            Object result = null;
            try {
                result = entry.getValue().evaluate(sourceRef.get(), returnType);
                if (result == null) {
                    continue;
                }
            } catch (final XPathExpressionException e) {
                logger.error("failed to evaluate XPath for {} for Property {} due to {}; routing to failure", new Object[] { flowFile, entry.getKey(), e });
                session.transfer(flowFile, REL_FAILURE);
                continue flowFileLoop;
            }
            if (returnType == NODESET) {
                List<Source> nodeList = (List<Source>) result;
                if (nodeList.isEmpty()) {
                    logger.info("Routing {} to 'unmatched'", new Object[] { flowFile });
                    session.transfer(flowFile, REL_NO_MATCH);
                    continue flowFileLoop;
                } else if (nodeList.size() > 1) {
                    logger.error("Routing {} to 'failure' because the XPath evaluated to {} XML nodes", new Object[] { flowFile, nodeList.size() });
                    session.transfer(flowFile, REL_FAILURE);
                    continue flowFileLoop;
                }
                final Source sourceNode = nodeList.get(0);
                if (DESTINATION_ATTRIBUTE.equals(destination)) {
                    try {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        doTransform(sourceNode, baos);
                        xpathResults.put(entry.getKey(), baos.toString("UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        throw new ProcessException(e);
                    } catch (TransformerException e) {
                        error.set(e);
                    }
                } else if (DESTINATION_CONTENT.equals(destination)) {
                    flowFile = session.write(flowFile, new OutputStreamCallback() {

                        @Override
                        public void process(final OutputStream rawOut) throws IOException {
                            try (final OutputStream out = new BufferedOutputStream(rawOut)) {
                                doTransform(sourceNode, out);
                            } catch (TransformerException e) {
                                error.set(e);
                            }
                        }
                    });
                }
            } else if (returnType == STRING) {
                final String resultString = (String) result;
                if (DESTINATION_ATTRIBUTE.equals(destination)) {
                    xpathResults.put(entry.getKey(), resultString);
                } else if (DESTINATION_CONTENT.equals(destination)) {
                    flowFile = session.write(flowFile, new OutputStreamCallback() {

                        @Override
                        public void process(final OutputStream rawOut) throws IOException {
                            try (final OutputStream out = new BufferedOutputStream(rawOut)) {
                                out.write(resultString.getBytes("UTF-8"));
                            }
                        }
                    });
                }
            }
        }
        if (error.get() == null) {
            if (DESTINATION_ATTRIBUTE.equals(destination)) {
                flowFile = session.putAllAttributes(flowFile, xpathResults);
                final Relationship destRel = xpathResults.isEmpty() ? REL_NO_MATCH : REL_MATCH;
                logger.info("Successfully evaluated XPaths against {} and found {} matches; routing to {}", new Object[] { flowFile, xpathResults.size(), destRel.getName() });
                session.transfer(flowFile, destRel);
                session.getProvenanceReporter().modifyAttributes(flowFile);
            } else if (DESTINATION_CONTENT.equals(destination)) {
                logger.info("Successfully updated content for {}; routing to 'matched'", new Object[] { flowFile });
                session.transfer(flowFile, REL_MATCH);
                session.getProvenanceReporter().modifyContent(flowFile);
            }
        } else {
            logger.error("Failed to write XPath result for {} due to {}; routing original to 'failure'", new Object[] { flowFile, error.get() });
            session.transfer(flowFile, REL_FAILURE);
        }
    }
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) InputSource(org.xml.sax.InputSource) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) BufferedOutputStream(org.apache.nifi.stream.io.BufferedOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) XPathEvaluator(net.sf.saxon.xpath.XPathEvaluator) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) SAXException(org.xml.sax.SAXException) XPathFactory(javax.xml.xpath.XPathFactory) BufferedInputStream(org.apache.nifi.stream.io.BufferedInputStream) StringReader(java.io.StringReader) List(java.util.List) ArrayList(java.util.ArrayList) OutputStreamCallback(org.apache.nifi.processor.io.OutputStreamCallback) BufferedOutputStream(org.apache.nifi.stream.io.BufferedOutputStream) XMLReader(org.xml.sax.XMLReader) TransformerException(javax.xml.transform.TransformerException) FlowFile(org.apache.nifi.flowfile.FlowFile) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) QName(javax.xml.namespace.QName) BufferedInputStream(org.apache.nifi.stream.io.BufferedInputStream) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AtomicReference(java.util.concurrent.atomic.AtomicReference) EntityResolver(org.xml.sax.EntityResolver) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ComponentLog(org.apache.nifi.logging.ComponentLog) XPathExpressionException(javax.xml.xpath.XPathExpressionException) XPathFactoryConfigurationException(javax.xml.xpath.XPathFactoryConfigurationException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TransformerException(javax.xml.transform.TransformerException) ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException) ProcessException(org.apache.nifi.processor.exception.ProcessException) SAXSource(javax.xml.transform.sax.SAXSource) Relationship(org.apache.nifi.processor.Relationship) InputStreamCallback(org.apache.nifi.processor.io.InputStreamCallback) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

XPathEvaluator (net.sf.saxon.xpath.XPathEvaluator)5 SaxonNamespaceContext (com.helger.schematron.saxon.SaxonNamespaceContext)1 PSErrorListener (com.helger.schematron.xslt.util.PSErrorListener)1 MapBasedNamespaceContext (com.helger.xml.namespace.MapBasedNamespaceContext)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 StringReader (java.io.StringReader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Nonnull (javax.annotation.Nonnull)1 QName (javax.xml.namespace.QName)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 Source (javax.xml.transform.Source)1 TransformerException (javax.xml.transform.TransformerException)1