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);
}
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();
}
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);
}
}
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;
}
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);
}
}
}
Aggregations