Example usage for org.dom4j DocumentHelper createXPath

List of usage examples for org.dom4j DocumentHelper createXPath

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper createXPath.

Prototype

public static XPath createXPath(String xpathExpression) throws InvalidXPathException 

Source Link

Document

createXPath parses an XPath expression and creates a new XPath XPath instance using the singleton DocumentFactory .

Usage

From source file:org.apache.taverna.activities.xpath.XPathActivity.java

License:Apache License

/**
 * This method executes pre-configured instance of XPath activity.
 *//*from   w  ww. j a va 2  s  .  c  o  m*/
@Override
public void executeAsynch(final Map<String, T2Reference> inputs, final AsynchronousActivityCallback callback) {
    // Don't execute service directly now, request to be run asynchronously
    callback.requestRun(new Runnable() {
        @Override
        @SuppressWarnings("unchecked")
        public void run() {

            InvocationContext context = callback.getContext();
            ReferenceService referenceService = context.getReferenceService();

            // ---- RESOLVE INPUT ----

            String xmlInput = (String) referenceService.renderIdentifier(inputs.get(IN_XML), String.class,
                    context);

            // ---- DO THE ACTUAL SERVICE INVOCATION ----

            List<Node> matchingNodes = new ArrayList<Node>();

            // only attempt to execute XPath expression if there is some input data
            if (xmlInput != null && xmlInput.length() > 0) {
                // XPath configuration is taken from the config bean
                try {
                    XPath expr = DocumentHelper.createXPath(json.get("xpathExpression").textValue());
                    Map<String, String> xpathNamespaceMap = new HashMap<>();
                    for (JsonNode namespaceMapping : json.get("xpathNamespaceMap")) {
                        xpathNamespaceMap.put(namespaceMapping.get("prefix").textValue(),
                                namespaceMapping.get("uri").textValue());
                    }
                    expr.setNamespaceURIs(xpathNamespaceMap);
                    Document doc = DocumentHelper.parseText(xmlInput);
                    matchingNodes = expr.selectNodes(doc);
                } catch (InvalidXPathException e) {
                    callback.fail("Incorrect XPath Expression -- XPath processing library "
                            + "reported the following error: " + e.getMessage(), e);

                    // make sure we don't call callback.receiveResult later
                    return;
                } catch (DocumentException e) {
                    callback.fail("XML document was not valid -- XPath processing library "
                            + "reported the following error: " + e.getMessage(), e);

                    // make sure we don't call callback.receiveResult later
                    return;
                } catch (XPathException e) {
                    callback.fail("Unexpected error has occurred while executing the XPath expression. "
                            + "-- XPath processing library reported the following error:\n" + e.getMessage(),
                            e);

                    // make sure we don't call callback.receiveResult later
                    return;
                }
            }

            // --- PREPARE OUTPUTS ---

            List<String> outNodesText = new ArrayList<String>();
            List<String> outNodesXML = new ArrayList<String>();
            Object textValue = null;
            Object xmlValue = null;

            for (Object o : matchingNodes) {
                if (o instanceof Node) {
                    Node n = (Node) o;
                    if (n.getStringValue() != null && n.getStringValue().length() > 0) {
                        outNodesText.add(n.getStringValue());
                        if (textValue == null)
                            textValue = n.getStringValue();
                    }
                    outNodesXML.add(n.asXML());
                    if (xmlValue == null)
                        xmlValue = n.asXML();
                } else {
                    outNodesText.add(o.toString());
                    if (textValue == null)
                        textValue = o.toString();
                }
            }

            // ---- REGISTER OUTPUTS ----

            Map<String, T2Reference> outputs = new HashMap<String, T2Reference>();
            if (textValue == null) {
                ErrorDocumentService errorDocService = referenceService.getErrorDocumentService();
                textValue = errorDocService.registerError("No value produced", 0, callback.getContext());
            }

            if (xmlValue == null) {
                ErrorDocumentService errorDocService = referenceService.getErrorDocumentService();
                xmlValue = errorDocService.registerError("No value produced", 0, callback.getContext());
            }

            T2Reference firstNodeAsText = referenceService.register(textValue, 0, true, context);
            outputs.put(SINGLE_VALUE_TEXT, firstNodeAsText);

            T2Reference firstNodeAsXml = referenceService.register(xmlValue, 0, true, context);
            outputs.put(SINGLE_VALUE_XML, firstNodeAsXml);

            T2Reference outNodesAsText = referenceService.register(outNodesText, 1, true, context);
            outputs.put(OUT_TEXT, outNodesAsText);

            T2Reference outNodesAsXML = referenceService.register(outNodesXML, 1, true, context);
            outputs.put(OUT_XML, outNodesAsXML);

            // return map of output data, with empty index array as this is
            // the only and final result (this index parameter is used if
            // pipelining output)
            callback.receiveResult(outputs, new int[0]);
        }
    });
}

From source file:org.codehaus.cargo.container.weblogic.WebLogic8xConfigXmlInstalledLocalDeployer.java

License:Apache License

/**
 * {@inheritDoc} deploys files by adding their configuration to the config.xml file of the
 * WebLogic server.//from   www . j a v  a  2s  .c  om
 * 
 * @see org.codehaus.cargo.container.spi.deployer.AbstractDeployer#deploy(org.codehaus.cargo.container.deployable.Deployable)
 */
@Override
public void deploy(Deployable deployable) {
    Document configXml = readConfigXml();
    XPath xpathSelector = DocumentHelper.createXPath("//Domain");
    List<Element> results = xpathSelector.selectNodes(configXml);
    Element domain = results.get(0);

    if (deployable.getType() == DeployableType.WAR) {
        addWarToDomain((WAR) deployable, domain);
    } else if (deployable.getType() == DeployableType.EAR) {
        addEarToDomain((EAR) deployable, domain);
    } else {
        throw new ContainerException("Not supported");
    }

    this.writeConfigXml(configXml);
}

From source file:org.codehaus.cargo.container.weblogic.WebLogic8xConfigXmlInstalledLocalDeployer.java

License:Apache License

/**
 * {@inheritDoc} undeploys files by removing their configuration to the config.xml file of the
 * WebLogic server./*from w  ww.  j a  v  a 2 s  .  c  o  m*/
 * 
 * @see org.codehaus.cargo.container.spi.deployer.AbstractDeployer#undeploy(org.codehaus.cargo.container.deployable.Deployable)
 */
@Override
public void undeploy(Deployable deployable) {
    Document configXml = readConfigXml();
    XPath xpathSelector = DocumentHelper.createXPath(
            "//Application[@Path='" + getFileHandler().getParent(getAbsolutePath(deployable)) + "']");
    List<Element> results = xpathSelector.selectNodes(configXml);
    for (Element element : results) {
        configXml.remove(element);
    }
    this.writeConfigXml(configXml);

}

From source file:org.codehaus.cargo.util.Dom4JUtil.java

License:Apache License

/**
 * The following will search the given element for the specified xpath and return a list of
 * nodes that match./*from  ww  w .j ava2 s  .  c  o  m*/
 * 
 * @param xpath - selection criteria
 * @param toSearch - element to start the search at
 * @return List of matching elements
 */
public List<Element> selectElementsMatchingXPath(String xpath, Element toSearch) {
    XPath xpathSelector = DocumentHelper.createXPath(xpath);
    xpathSelector.setNamespaceURIs(getNamespaces());
    List<Element> results = xpathSelector.selectNodes(toSearch);
    return results;
}

From source file:org.craftercms.core.util.XmlUtils.java

License:Open Source License

/**
 * Executes the specified namespace aware XPath query as a single node query, returning the resulting single node.
 *//*from  ww  w.j  a va  2 s  .  c  o  m*/
public static Node selectSingleNode(Node node, String xpathQuery, Map<String, String> namespaceUris) {
    XPath xpath = DocumentHelper.createXPath(xpathQuery);
    xpath.setNamespaceURIs(namespaceUris);

    return xpath.selectSingleNode(node);
}

From source file:org.craftercms.core.util.XmlUtils.java

License:Open Source License

/**
 * Executes the specified namespace aware XPath query as a multiple node query, returning the resulting list of nodes.
 *//*w w  w.  ja va2  s  .  com*/
@SuppressWarnings("unchecked")
public static List<Node> selectNodes(Node node, String xpathQuery, Map<String, String> namespaceUris) {
    XPath xpath = DocumentHelper.createXPath(xpathQuery);
    xpath.setNamespaceURIs(namespaceUris);

    return xpath.selectNodes(node);
}

From source file:org.dom4j.samples.XPathGrep.java

License:Open Source License

public void setXPath(String xpathExpression) {
    xpath = DocumentHelper.createXPath(xpathExpression);
}

From source file:org.fcrepo.server.messaging.FedoraTypes.java

License:fedora commons license

public String getDatatype(String method, String param) {
    String key = method + "." + param;

    if (!method2datatype.containsKey(key)) {
        String query = String.format("/xsd:schema/xsd:element[@name='%s']" + "/xsd:complexType/xsd:sequence"
                + "/xsd:element[@name='%s']/@type", method, param);
        XPath xpath = DocumentHelper.createXPath(query);
        xpath.setNamespaceURIs(ns2prefix);
        String datatype = xpath.valueOf(getDocument());
        if (datatype.isEmpty()) {
            datatype = null;/*ww w  . j a va  2 s  .  c o m*/
        }
        method2datatype.put(key, datatype);
    }
    return method2datatype.get(key);
}

From source file:org.fcrepo.server.messaging.FedoraTypes.java

License:fedora commons license

public String getResponseParameter(String response) {
    if (!response2parameter.containsKey(response)) {
        String query = String.format(
                "/xsd:schema/xsd:element[@name='%s']" + "/xsd:complexType/xsd:sequence" + "/xsd:element/@name",
                response);/* w w  w  .  j  a  va2  s . co  m*/
        XPath xpath = DocumentHelper.createXPath(query);
        xpath.setNamespaceURIs(ns2prefix);
        String param = xpath.valueOf(getDocument());
        if (param.isEmpty()) {
            param = null;
        }
        response2parameter.put(response, param);
    }
    return response2parameter.get(response);
}

From source file:org.footware.server.gpx.GPXImport.java

License:Apache License

private List<GPXTrack> parseXML(File file) {
    LinkedList<GPXTrack> tracks = new LinkedList<GPXTrack>();
    try {/*from   www . j ava2 s.  c om*/
        long startTime = System.currentTimeMillis();
        logger.info("Start parsing @" + startTime);

        // Determine GPX Version
        SAXReader xmlReader = new SAXReader();
        Document document = xmlReader.read(file);
        String version = document.getRootElement().attributeValue("version");

        File xsd = null;

        if (version.equals("1.1")) {
            logger.info("Detected gpx version " + version + "  +" + (System.currentTimeMillis() - startTime));
            xsd = new File("gpx_1_1.xsd");
            GPX_NAMESPACE_URI = GPX_NAMESPACE_URI_1_1;
        } else if (version.equals("1.0")) {
            logger.info("Detected gpx version '" + version + "'  +" + (System.currentTimeMillis() - startTime));
            xsd = new File("gpx_1_0.xsd");
            GPX_NAMESPACE_URI = GPX_NAMESPACE_URI_1_0;
        } else {
            logger.info("No supported version detected: " + version + "  +"
                    + (System.currentTimeMillis() - startTime));
            // As default we try version 1.1
            xsd = new File("gpx_1_1.xsd");
            GPX_NAMESPACE_URI = GPX_NAMESPACE_URI_1_1;
        }

        // Parse GPX
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        factory.setSchema(schemaFactory.newSchema(xsd));

        SAXParser parser = factory.newSAXParser();
        SAXReader reader = new SAXReader(parser.getXMLReader());
        reader.setValidation(true);
        reader.setErrorHandler(new SimpleErrorHandler());

        document = reader.read(file);
        logger.info("End parsing +" + (System.currentTimeMillis() - startTime));

        // Define namespaces
        HashMap<String, String> namespacesMap = new HashMap<String, String>();
        namespacesMap.put(GPX_NS, GPX_NAMESPACE_URI);

        // Find tracks
        logger.info("Search tracks +" + (System.currentTimeMillis() - startTime));
        XPath xpathTrk = DocumentHelper.createXPath("//" + GPX_NS + ":trk");
        xpathTrk.setNamespaceURIs(namespacesMap);

        List<Element> xmlTracks = xpathTrk.selectNodes(document);
        logger.info("Found " + xmlTracks.size() + " tracks +" + (System.currentTimeMillis() - startTime));

        GPXTrack track;

        // for (Element xmlTrack : xmlTracks) {
        // Iterate about all tracks of the gpx file
        for (int currentTrackNummer = 1; currentTrackNummer <= xmlTracks.size(); currentTrackNummer++) {
            logger.info("Start track " + currentTrackNummer + " +" + (System.currentTimeMillis() - startTime));

            track = new GPXTrack();

            // Find track segments
            XPath xpathTrkseg = DocumentHelper
                    .createXPath("//" + GPX_NS + ":trk[" + currentTrackNummer + "]/" + GPX_NS + ":trkseg");
            xpathTrkseg.setNamespaceURIs(namespacesMap);

            List<Element> xmlTrackSegs = xpathTrkseg.selectNodes(document);
            logger.info("Found " + xmlTrackSegs.size() + " segments for track " + currentTrackNummer + " +"
                    + (System.currentTimeMillis() - startTime));

            // List<Element> xmlTrackSegs =
            // xmlTrack.selectNodes("//trkseg");

            GPXTrackSegment trackSegment;

            // for (Element xmlTrackSeq : xmlTrackSegs) {
            // Iterate above all segments of a track
            for (int currentTrackSegmentNummer = 1; currentTrackSegmentNummer <= xmlTrackSegs
                    .size(); currentTrackSegmentNummer++) {
                trackSegment = new GPXTrackSegment();

                // Find track points
                XPath xpathTrkPt = DocumentHelper.createXPath("//" + GPX_NS + ":trk[" + currentTrackNummer
                        + "]/" + GPX_NS + ":trkseg[" + currentTrackSegmentNummer + "]/" + GPX_NS + ":trkpt");
                xpathTrkPt.setNamespaceURIs(namespacesMap);
                List<Element> xmlTrackPts = xpathTrkPt.selectNodes(document);

                logger.info("Found " + xmlTrackPts.size() + " points for segment " + currentTrackSegmentNummer
                        + " for track " + currentTrackNummer + " +" + (System.currentTimeMillis() - startTime));

                GPXTrackPoint trackPoint;
                BigDecimal latitude;
                BigDecimal longitude;
                BigDecimal elevation;
                DateTime time;

                // Iterate above all points of a segment of a track
                for (Element xmlTrackPt : xmlTrackPts) {

                    latitude = new BigDecimal(xmlTrackPt.attributeValue(LATITUDE));
                    longitude = new BigDecimal(xmlTrackPt.attributeValue(LONGITUDE));
                    elevation = new BigDecimal(xmlTrackPt.element(ELEVATION).getText());
                    time = ISODateTimeFormat.dateTimeNoMillis()
                            .parseDateTime(xmlTrackPt.element(TIME).getText());

                    trackPoint = new GPXTrackPoint(latitude, longitude, elevation, time);
                    trackSegment.addPoint(trackPoint);
                }
                track.addTrackSegment(trackSegment);
            }
            tracks.add(track);

        }
        logger.info("Done parsing +" + (System.currentTimeMillis() - startTime));

    } catch (ParserConfigurationException e) {
        logger.error("ParserConfigurationException", e);
        e.printStackTrace();
    } catch (SAXException e) {
        logger.error("SAXException", e);
        e.printStackTrace();
    } catch (DocumentException e) {
        logger.error("DocumentException", e);
        e.printStackTrace();
    }

    return tracks;
}