protected void configureBuilder(XPathBuilder builder) { if (resultType != null) { builder.setResultQName(resultType); } if (isUseSaxon()) { builder.enableSaxon(); } else { if (xpathFactory != null) { builder.setXPathFactory(xpathFactory); } if (objectModelUri != null) { builder.setObjectModelUri(objectModelUri); } } }
@Override public Expression createExpression(CamelContext camelContext, Annotation annotation, LanguageAnnotation languageAnnotation, Class<?> expressionReturnType) { String xpath = getExpressionFromAnnotation(annotation); Class<?> resultType = getResultType(annotation); if (resultType.equals(Object.class)) { resultType = expressionReturnType; } XPathBuilder builder = XPathBuilder.xpath(xpath, resultType); NamespacePrefix[] namespaces = getExpressionNameSpacePrefix(annotation); if (namespaces != null) { for (NamespacePrefix namespacePrefix : namespaces) { builder = builder.namespace(namespacePrefix.prefix(), namespacePrefix.uri()); } } // Set the header name that we want the XPathBuilder to apply the XPath expression to String headerName = getHeaderName(annotation); if (ObjectHelper.isNotEmpty(headerName)) { builder.setHeaderName(headerName); } return builder; }
@Override public RouteBuilder getRouteBuilder() { XPathBuilder xPathBuilder = new XPathBuilder("/order/item"); return new RouteBuilder() { @Override public void configure() throws Exception { from("file:src/test/data/camel/splitter?noop=true") .split(xPathBuilder) .parallelProcessing() .setHeader("LineItemId") .xpath("/item/@id", String.class) .to("file:target/data/camel/splitter?fileName=" + "${in.header.LineItemId}-${date:now:yyyyMMddHHmmssSSSSS}.xml"); } }; }
private String evaluateXPath(String expression, Message message) { XPathBuilder xpath = XPathBuilder.xpath(expression); if (namespaces != null) xpath.setNamespaces(namespaces); return xpath.evaluate(camelContext, message.getBody(), String.class); }
@Override protected void configureExpression(CamelContext camelContext, Expression expression) { boolean isSaxon = getSaxon() != null && getSaxon(); boolean isLogNamespaces = getLogNamespaces() != null && getLogNamespaces(); if (documentType != null) { setProperty(expression, "documentType", documentType); } if (resultType != null) { setProperty(expression, "resultType", resultType); } if (isSaxon) { ObjectHelper.cast(XPathBuilder.class, expression).enableSaxon(); } if (xpathFactory != null) { setProperty(expression, "xPathFactory", xpathFactory); } if (objectModel != null) { setProperty(expression, "objectModelUri", objectModel); } if (isLogNamespaces) { ObjectHelper.cast(XPathBuilder.class, expression).setLogNamespaces(true); } if (ObjectHelper.isNotEmpty(getHeaderName())) { ObjectHelper.cast(XPathBuilder.class, expression).setHeaderName(getHeaderName()); } // moved the super configuration to the bottom so that the namespace init picks up the newly set XPath Factory super.configureExpression(camelContext, expression); }
@Override protected void configurePredicate(CamelContext camelContext, Predicate predicate) { boolean isSaxon = getSaxon() != null && getSaxon(); boolean isLogNamespaces = getLogNamespaces() != null && getLogNamespaces(); if (documentType != null) { setProperty(predicate, "documentType", documentType); } if (resultType != null) { setProperty(predicate, "resultType", resultType); } if (isSaxon) { ObjectHelper.cast(XPathBuilder.class, predicate).enableSaxon(); } if (xpathFactory != null) { setProperty(predicate, "xPathFactory", xpathFactory); } if (objectModel != null) { setProperty(predicate, "objectModelUri", objectModel); } if (isLogNamespaces) { ObjectHelper.cast(XPathBuilder.class, predicate).setLogNamespaces(true); } if (ObjectHelper.isNotEmpty(getHeaderName())) { ObjectHelper.cast(XPathBuilder.class, predicate).setHeaderName(getHeaderName()); } // moved the super configuration to the bottom so that the namespace init picks up the newly set XPath Factory super.configurePredicate(camelContext, predicate); }
public Predicate createPredicate(String expression) { expression = loadResource(expression); XPathBuilder builder = XPathBuilder.xpath(expression); configureBuilder(builder); return builder; }
public Expression createExpression(String expression) { expression = loadResource(expression); XPathBuilder builder = XPathBuilder.xpath(expression); configureBuilder(builder); return builder; }
protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { //ensure stream is spooled to disk context.getStreamCachingStrategy().setSpoolDirectory("target/tmp"); context.getStreamCachingStrategy().setSpoolThreshold(-1); from("seda:parallel?concurrentConsumers=5").streamCaching() .split(XPathBuilder.xpath("//person/city")) .to("mock:result"); } }; }
public void testExpressionExpectationOfHeader() throws InterruptedException { MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); resultEndpoint.reset(); resultEndpoint.expectedHeaderReceived("number", 123); template.sendBodyAndHeader("direct:a", "<foo><id>123</id></foo>", "number", XPathBuilder.xpath("/foo/id", Integer.class)); resultEndpoint.assertIsSatisfied(); }
private void encrypt(Exchange exchange, Document document, OutputStream stream, Key dataEncryptionKey, XMLCipher keyCipher, Key keyEncryptionKey) throws Exception { XMLCipher xmlCipher = XMLCipher.getInstance(xmlCipherAlgorithm); xmlCipher.init(XMLCipher.ENCRYPT_MODE, dataEncryptionKey); if (secureTag.equalsIgnoreCase("")) { embedKeyInfoInEncryptedData(document, keyCipher, xmlCipher, dataEncryptionKey, keyEncryptionKey); document = xmlCipher.doFinal(document, document.getDocumentElement()); } else { XPathBuilder xpathBuilder = new XPathBuilder(secureTag); xpathBuilder.setNamespaceContext(getNamespaceContext()); NodeList nodeList = xpathBuilder.evaluate(exchange, NodeList.class); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); document = node.getOwnerDocument(); embedKeyInfoInEncryptedData(node.getOwnerDocument(), keyCipher, xmlCipher, dataEncryptionKey, keyEncryptionKey); Document temp = xmlCipher.doFinal(node.getOwnerDocument(), (Element) node, getSecureTagContents()); document.importNode(temp.getDocumentElement().cloneNode(true), true); } } try { DOMSource source = new DOMSource(document); InputStream sis = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, source); IOHelper.copy(sis, stream); } finally { stream.close(); } }
@Override public void process(Exchange exchange) throws Exception { Object obj = exchange.getIn().getBody(); //xpath expression directly results in a: String String content = (String) XPathBuilder.xpath("//xml/text()").stringResult().evaluate(context, obj, Object.class); exchange.getOut().setBody(content); exchange.getOut().setHeaders(exchange.getIn().getHeaders()); }
@Override public void process(Exchange exchange) throws Exception { Object obj = exchange.getIn().getBody(); //xpath expression results in a: net.sf.saxon.dom.DOMNodeList //after which it is converted to a String String content = XPathBuilder.xpath("//xml/text()").evaluate(context, obj, String.class); exchange.getOut().setBody(content); exchange.getOut().setHeaders(exchange.getIn().getHeaders()); }
@Test public void testXPathUsingSaxon() throws Exception { XPathFactory fac = new XPathFactoryImpl(); XPathBuilder builder = XPathBuilder.xpath("foo/bar").factory(fac); // will evaluate as XPathConstants.NODESET and have Camel convert that to String // this should return the String incl. xml tags String name = builder.evaluate(context, "<foo><bar id=\"1\">cheese</bar></foo>", String.class); assertEquals("<bar id=\"1\">cheese</bar>", name); // will evaluate using XPathConstants.STRING which just return the text content (eg like text()) name = builder.evaluate(context, "<foo><bar id=\"1\">cheese</bar></foo>"); assertEquals("cheese", name); }
@Test public void testXPathFunctionSubstringUsingSaxon() throws Exception { String xml = "<foo><bar>Hello World</bar></foo>"; XPathFactory fac = new XPathFactoryImpl(); XPathBuilder builder = XPathBuilder.xpath("substring(/foo/bar, 7)").factory(fac); String result = builder.resultType(String.class).evaluate(context, xml, String.class); assertEquals("World", result); result = builder.evaluate(context, xml); assertEquals("World", result); }
@Test public void testXPathFunctionTokenizeUsingSaxonXPathFactory() throws Exception { // START SNIPPET: e1 // create a Saxon factory XPathFactory fac = new net.sf.saxon.xpath.XPathFactoryImpl(); // create a builder to evaluate the xpath using the saxon factory XPathBuilder builder = XPathBuilder.xpath("tokenize(/foo/bar, '_')[2]").factory(fac); // evaluate as a String result String result = builder.evaluate(context, "<foo><bar>abc_def_ghi</bar></foo>"); assertEquals("def", result); // END SNIPPET: e1 }
@Test public void testXPathFunctionTokenizeUsingObjectModel() throws Exception { // START SNIPPET: e2 // create a builder to evaluate the xpath using saxon based on its object model uri XPathBuilder builder = XPathBuilder.xpath("tokenize(/foo/bar, '_')[2]").objectModel("http://saxon.sf.net/jaxp/xpath/om"); // evaluate as a String result String result = builder.evaluate(context, "<foo><bar>abc_def_ghi</bar></foo>"); assertEquals("def", result); // END SNIPPET: e2 }
@Test public void testXPathFunctionTokenizeUsingSaxon() throws Exception { // START SNIPPET: e3 // create a builder to evaluate the xpath using saxon XPathBuilder builder = XPathBuilder.xpath("tokenize(/foo/bar, '_')[2]").saxon(); // evaluate as a String result String result = builder.evaluate(context, "<foo><bar>abc_def_ghi</bar></foo>"); assertEquals("def", result); // END SNIPPET: e3 }
@Test public void testXPathFunctionTokenizeUsingSystemProperty() throws Exception { // START SNIPPET: e4 // set system property with the XPath factory to use which is Saxon System.setProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + "http://saxon.sf.net/jaxp/xpath/om", "net.sf.saxon.xpath.XPathFactoryImpl"); // create a builder to evaluate the xpath using saxon XPathBuilder builder = XPathBuilder.xpath("tokenize(/foo/bar, '_')[2]"); // evaluate as a String result String result = builder.evaluate(context, "<foo><bar>abc_def_ghi</bar></foo>"); assertEquals("def", result); // END SNIPPET: e4 }
@Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { XPathBuilder splitter = new XPathBuilder("//records/record"); context.setTracing(true); from("direct:xpath").split(splitter).filter().xquery("//record[type=2]") .to("mock:result"); } }; }
@Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { final String fcrepo_uri = FcrepoTestUtils.getFcrepoEndpointUri(); final Namespaces ns = new Namespaces("rdf", RDF.uri); final XPathBuilder titleXpath = new XPathBuilder("/rdf:RDF/rdf:Description/dc:title/text()"); titleXpath.namespaces(ns); titleXpath.namespace("dc", "http://purl.org/dc/elements/1.1/"); from("direct:setup") .to(fcrepo_uri) .to("mock:created"); from("direct:start") .to(fcrepo_uri) .convertBodyTo(org.w3c.dom.Document.class) .filter().xpath( "/rdf:RDF/rdf:Description/rdf:type" + "[@rdf:resource='" + REPOSITORY + "Resource']", ns) .split(titleXpath) .to("mock:result"); from("direct:teardown") .to(fcrepo_uri) .to("mock:deleted"); } }; }
/** * Returns an XPathBuilder that can be used as a Predicate to evaluate a request or response is as expected * * @param expression An XPath expression that evaluates the incoming exchange body to a boolean value * @param namespaces Namespace definitions used within the XPath expression */ default XPathBuilder xpath(String expression, NS... namespaces) { XPathBuilder builder = new XPathBuilder(expression); for (NS namespace : namespaces) { builder.namespace(namespace.getPrefix(), namespace.getUri()); } return builder; }
public static String xpath(Exchange exchange, String path) { return XPathBuilder.xpath(path).stringResult().evaluate(exchange, String.class); }
public void testExpressionExpectationOfProperty() throws InterruptedException { MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); resultEndpoint.reset(); resultEndpoint.expectedPropertyReceived("number", 123); template.sendBodyAndProperty("direct:a", "<foo><id>123</id></foo>", "number", XPathBuilder.xpath("/foo/id", Integer.class)); resultEndpoint.assertIsSatisfied(); }
@Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(simpleEndpointURI + "&dataFormat=PAYLOAD").to("log:info").process(new Processor() { @SuppressWarnings("unchecked") @Override public void process(final Exchange exchange) throws Exception { Object request = exchange.getIn().getBody(); assertIsInstanceOf(CxfPayload.class, request); //attempt 1) applying XPath to exchange.getIn().getBody() receivedMessageCxfPayloadApplyingXPath = XPathBuilder.xpath("//*[name()='arg0']/text()").evaluate(context, request, String.class); //attempt 2) in stead of XPATH, browse the DOM-tree CxfPayload<SoapHeader> payload = (CxfPayload<SoapHeader>) request; Element el = payload.getBody().get(0); Element el2 = (Element) el.getFirstChild(); Text textnode = (Text) el2.getFirstChild(); receivedMessageByDom = textnode.getNodeValue(); textnode = (Text) textnode.getNextSibling(); while (textnode != null) { //the textnode appears to have siblings! receivedMessageByDom = receivedMessageByDom + textnode.getNodeValue(); textnode = (Text) textnode.getNextSibling(); } //attempt 3) apply XPATH after converting CxfPayload to String request = exchange.getIn().getBody(String.class); assertIsInstanceOf(String.class, request); receivedMessageStringApplyingXPath = XPathBuilder.xpath("//*[name()='arg0']/text()").evaluate(context, request, String.class); //build some dummy response XmlConverter converter = new XmlConverter(); Document outDocument = converter.toDOMDocument(ECHO_RESPONSE, exchange); List<Source> outElements = new ArrayList<Source>(); outElements.add(new DOMSource(outDocument.getDocumentElement())); // set the payload header with null CxfPayload<SoapHeader> responsePayload = new CxfPayload<SoapHeader>(null, outElements, null); exchange.getOut().setBody(responsePayload); } }); } }; }
@Override protected RouteBuilder createRouteBuilder() throws Exception { final Namespaces ns = new Namespaces("sparql", "http://www.w3.org/2005/sparql-results#"); final XPathBuilder xpath = new XPathBuilder( "//sparql:result/sparql:binding[@name='o']"); xpath.namespaces(ns); final XPathBuilder uriResult = new XPathBuilder( "/sparql:binding/sparql:uri"); uriResult.namespaces(ns); final XPathBuilder literalResult = new XPathBuilder( "/sparql:binding/sparql:literal"); literalResult.namespaces(ns); return new RouteBuilder() { public void configure() throws IOException { final String fuseki_url = "http4://localhost:" + Integer.toString(FUSEKI_PORT); from("direct:start") .setHeader(AuditHeaders.EVENT_BASE_URI, constant(EVENT_BASE_URI)) .process(new AuditSparqlProcessor()) .to(fuseki_url + "/fuseki/test/update") .to("mock:sparql.update"); from("direct:query") .to(fuseki_url + "/fuseki/test/query") .split(xpath) .choice() .when().xpath("/sparql:binding/sparql:uri", String.class, ns) .transform().xpath("/sparql:binding/sparql:uri/text()", String.class, ns) .to("mock:sparql.query") .when().xpath("/sparql:binding/sparql:literal", String.class, ns) .transform().xpath("/sparql:binding/sparql:literal/text()", String.class, ns) .to("mock:sparql.query"); from("direct:clear") .transform().constant("update=DELETE WHERE { ?s ?o ?p }") .setHeader(Exchange.CONTENT_TYPE).constant("application/x-www-form-urlencoded") .setHeader(Exchange.HTTP_METHOD).constant("POST") .to(fuseki_url + "/fuseki/test/update") .to("mock:sparql.update"); } }; }
@Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { final String fcrepo_uri = FcrepoTestUtils.getFcrepoEndpointUriWithScheme(); final Namespaces ns = new Namespaces("rdf", RDF.uri); ns.add("ldp", "http://www.w3.org/ns/ldp#"); final XPathBuilder ldpChildren = new XPathBuilder("/rdf:RDF/rdf:Description/ldp:contains"); ldpChildren.namespaces(ns); getContext().getStreamCachingStrategy().setSpoolThreshold(1024); getContext().getStreamCachingStrategy().setBufferSize(128); getContext().setStreamCaching(true); from("direct:create") .to(fcrepo_uri) .to("mock:created"); from("direct:get") .streamCaching() .to(fcrepo_uri) .convertBodyTo(StreamSource.class) .split(ldpChildren).streaming() .transform() .xpath("/ldp:contains/@rdf:resource", String.class, ns) .to("mock:child"); from("direct:delete") .setHeader(Exchange.HTTP_METHOD, constant("DELETE")) .to(fcrepo_uri) .to("mock:deleted") .setHeader(Exchange.HTTP_METHOD, constant("GET")) .to(fcrepo_uri + "?throwExceptionOnFailure=false") .to("mock:verifyGone"); } }; }
/** * Returns a xpath expression value builder * @param value The XPath expression * @return A new XPathBuilder object */ public XPathBuilder xpath(String value) { return XPathBuilder.xpath(value); }
/** * Returns a xpath expression value builder * @param value The XPath expression * @param resultType The result type that the XPath expression will return. * @return A new XPathBuilder object */ public static XPathBuilder xpath(String value, Class<?> resultType) { return XPathBuilder.xpath(value, resultType); }