Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:net.adamcin.commons.testing.sling.SlingPostResponse.java

public static SlingPostResponse createFromInputStream(InputStream stream, String encoding) throws IOException {

    InputSource source = new InputSource(new BufferedInputStream(stream));
    source.setEncoding(encoding == null ? "UTF-8" : encoding);

    SlingPostResponse postResponse = new SlingPostResponse();

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();

    try {//from ww w . j a v  a2s .com

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(source);

        postResponse
                .setStatus((String) xpath.compile(XPATH_ID_STATUS).evaluate(document, XPathConstants.STRING));
        postResponse
                .setMessage((String) xpath.compile(XPATH_ID_MESSAGE).evaluate(document, XPathConstants.STRING));
        postResponse.setLocation(
                (String) xpath.compile(XPATH_ID_LOCATION).evaluate(document, XPathConstants.STRING));
        postResponse.setParentLocation(
                (String) xpath.compile(XPATH_ID_PARENT_LOCATION).evaluate(document, XPathConstants.STRING));
        postResponse.setPath((String) xpath.compile(XPATH_ID_PATH).evaluate(document, XPathConstants.STRING));
        postResponse
                .setReferer((String) xpath.compile(XPATH_ID_REFERER).evaluate(document, XPathConstants.STRING));

        List<Change> changes = new ArrayList<Change>();

        NodeList changeLogNodes = (NodeList) xpath.compile(XPATH_ID_CHANGE_LOG).evaluate(document,
                XPathConstants.NODESET);

        if (changeLogNodes != null) {
            for (int i = 0; i < changeLogNodes.getLength(); i++) {
                String rawChange = changeLogNodes.item(i).getTextContent();
                rawChange = rawChange.substring(0, rawChange.length() - 2);
                String[] rawChangeParts = rawChange.split("\\(", 2);
                if (rawChangeParts.length != 2) {
                    continue;
                }
                String changeType = rawChangeParts[0];
                String[] rawArguments = rawChangeParts[1].split(", ");
                List<String> arguments = new ArrayList<String>();
                for (String rawArgument : rawArguments) {
                    arguments.add(rawArgument.substring(1, rawArgument.length() - 1));
                }

                Change change = new Change(changeType, arguments.toArray(new String[arguments.size()]));
                changes.add(change);
            }
        }

        postResponse.setChangeLog(changes);

    } catch (XPathExpressionException e) {
        LOGGER.error("Failed to evaluate xpath statement.", e);
        throw new IOException("Failed to evaluate xpath statement.", e);
    } catch (ParserConfigurationException e) {
        LOGGER.error("Failed to create DocumentBuilder.", e);
        throw new IOException("Failed to create DocumentBuilder.", e);
    } catch (SAXException e) {
        LOGGER.error("Failed to create Document.", e);
        throw new IOException("Failed to create Document.", e);
    }

    LOGGER.info("Returning post response");
    return postResponse;
}

From source file:com.microsoft.windowsazure.exception.ServiceException.java

public static ServiceException createFromXml(final HttpRequest httpRequest, final String requestContent,
        final HttpResponse httpResponse, final HttpEntity entity) {
    String content;/*from  ww  w  .  j  a  v  a  2  s  . c  om*/
    try {
        content = EntityUtils.toString(entity);
    } catch (IOException e) {
        return new ServiceException(e);
    }

    ServiceException serviceException;

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document responseDoc = documentBuilder
                .parse(new BOMInputStream(new ByteArrayInputStream(content.getBytes())));

        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        String code = xpath.compile("/Error/Code/text()").evaluate(responseDoc);
        String message = xpath.compile("/Error/Message/text()").evaluate(responseDoc);

        serviceException = new ServiceException(buildExceptionMessage(code, message, content, httpResponse));

        serviceException.getError().setCode(code);
        serviceException.getError().setMessage(message);
    } catch (XPathExpressionException e) {
        return new ServiceException(content);
    } catch (ParserConfigurationException e) {
        return new ServiceException(content);
    } catch (SAXException e) {
        return new ServiceException(content);
    } catch (IOException e) {
        return new ServiceException(content);
    }

    serviceException.setHttpStatusCode(httpResponse.getStatusLine().getStatusCode());
    serviceException.setHttpReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());

    return serviceException;
}

From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfParser.java

private static XPath newXpath() {
    XPathFactory xf = XPathFactory.newInstance();
    XPath xpath = xf.newXPath();

    NamespaceContextImpl ctx = new NamespaceContextImpl();

    ctx.addNamespace("ovf", "http://schemas.dmtf.org/ovf/envelope/1");
    ctx.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    ctx.addNamespace("rasd",
            "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
    ctx.addNamespace("vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
    ctx.addNamespace("vmw", "http://www.vmware.com/schema/ovf");

    xpath.setNamespaceContext(ctx);// ww  w. java 2  s.  c om
    return xpath;
}

From source file:org.eclipse.lyo.testsuite.server.util.OSLCUtils.java

public static XPath getXPath() {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new OSLCNamespaceContext());
    return xpath;
}

From source file:com.bloomreach.bstore.highavailability.utils.SolrInteractionUtils.java

/**
 * Parse Status of given XPath Patterns//  w  w  w  .j  ava2s.c o m
 *
 * @param result
 * @param xpathPatterns
 * @return {@link java.util.List<String>} of the xpath data.
 * @throws SAXException
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 */
public static List<String> parseStatusResponse(InputStream result, String[] xpathPatterns)
        throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(result);
    List<String> data = new ArrayList<String>();
    if (doc == null) {
        return data;
    }
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    for (String pattern : xpathPatterns) {
        data.add(xpath.compile(pattern).evaluate(doc));
    }
    return data;
}

From source file:org.hyperic.plugin.vrealize.automation.DiscoveryVRAIaasWeb.java

private static String getVCO(ConfigResponse config) {
    String vcoFNQ = null;/*from   w w w.ja  v  a2s.co m*/
    String xml = null;

    String user = config.getValue("iaas.http.user", "");
    String pass = config.getValue("iaas.http.pass", "");
    String domain = config.getValue("iaas.http.domain", "");

    try {
        AgentKeystoreConfig ksCFG = new AgentKeystoreConfig();
        HQHttpClient client = new HQHttpClient(ksCFG, new HttpConfig(5000, 5000, null, 0),
                ksCFG.isAcceptUnverifiedCert());

        List<String> authpref = new ArrayList<String>();
        authpref.add(AuthPolicy.NTLM);
        authpref.add(AuthPolicy.BASIC);
        client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

        client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthPolicy.NTLM),
                new NTCredentials(user, pass, "localhost", domain));

        HttpGet get = new HttpGet(
                "https://localhost/Repository/Data/ManagementModelEntities.svc/ManagementEndpoints");
        HttpResponse response = client.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            xml = readInputString(response.getEntity().getContent());
        } else {
            log.debug("[getVCOx] GET failed: " + response.getStatusLine().getReasonPhrase());
        }
    } catch (IOException ex) {
        log.debug("[getVCOx] " + ex, ex);
    }

    if (xml != null) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = (Document) builder.parse(new ByteArrayInputStream(xml.getBytes()));

            log.debug("[getVCOx] xml:" + xml);

            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xpath = xFactory.newXPath();

            String xPath = "//properties[InterfaceType[text()='vCO']]/ManagementEndpointName/text()";

            log.debug("[getVCOx] evaluating XPath:" + xPath);

            vcoFNQ = xpath.evaluate(xPath, doc);

            log.debug("[getVCOx] vcoFNQ:" + vcoFNQ);

        } catch (Exception ex) {
            log.debug("[getVCOx] " + ex, ex);
        }
    }

    return VRAUtils.getFqdn(vcoFNQ);
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @param documentDom//ww w. ja  v  a 2 s  .c  o  m
 * @param xpath
 * @return
 * @throws XPathExpressionException
 */
static Node getWordParaForXPath(Document documentDom, String xpath) throws XPathExpressionException {
    XPathFactory xpathFactory = DomUtil.getXPathFactory();
    XPath xpathObj = xpathFactory.newXPath();
    xpathObj.setNamespaceContext(DocxConstants.docxNamespaceContext);
    Object result = xpathObj.evaluate(xpath, documentDom, XPathConstants.NODE);
    Node node = null;
    if (result != null) {
        node = (Node) result;

    }
    return node;
}

From source file:be.fedict.eid.applet.service.signer.odf.ODFUtil.java

/**
 * Check if an ODF package is self-contained, i.e. content files don't have
 * OLE objects linked to external files//from w w w . jav  a 2s . co  m
 * 
 * @param odfUrl
 * @return
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static boolean isSelfContained(URL odfUrl)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    InputStream odfInputStream = odfUrl.openStream();
    List zipEntries = getZipEntriesAsList(odfInputStream);

    odfInputStream = odfUrl.openStream();
    ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream);
    ZipEntry zipEntry;

    XPathFactory factory = XPathFactory.newInstance();
    /* Maybe a bit overkill, but implementations can use other prefixes */
    ODFNamespaceContext namespaceContext = new ODFNamespaceContext();

    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(namespaceContext);
    XPathExpression expression = xpath.compile("//draw:object/@xlink:href|" + "//draw:object-ole/@xlink:href|"
            + "//draw:image/@xlink:href|" + "//draw:floating-frame/@xlink:href");

    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (isContentFile(zipEntry)) {
            /* TODO: pure SAX is probably more memory-efficient */
            Document content = ODFUtil.loadDocument(odfZipInputStream);
            NodeList nodes = (NodeList) expression.evaluate(content, XPathConstants.NODESET);
            return checkNodes(nodes, zipEntries);
        }
    }
    return true;
}

From source file:com.bloomreach.bstore.highavailability.utils.SolrInteractionUtils.java

/**
 * Returns the replication status of a core on a given host
 *
 * @param host Solr Host to query//  w ww  .j a  va 2s.  c o m
 * @param core name of the core to check replication
 * @return {@link com.bloomreach.bstore.highavailability.models.ReplicationDiagnostics} information about replication
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static ReplicationDiagnostics checkReplicationStatus(String host, String core)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    ReplicationDiagnostics diagnostics = new ReplicationDiagnostics();
    diagnostics.setEntity(core);
    String statusUrl = String.format("http://%s:%s/solr/%s/replication?command=details", host,
            SolrInteractionUtils.DEFAULT_SOLR_PORT, core);
    InputStream result = null;
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = null;
    try {
        result = SolrInteractionUtils.executeSolrCommandAndGetInputStream(statusUrl);
        doc = dBuilder.parse(result);
    } finally {
        if (result != null) {
            result.close();
        }
    }
    if (doc == null) {
        logger.info("Replicationstatus: " + host + " Not results");
        return diagnostics;
    }
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    String curDate = xpath
            .compile("/response/lst[@name='details']/lst[@name = 'slave']/str[@name = 'currentDate']/text()")
            .evaluate(doc);
    String isReplicating = xpath
            .compile("/response/lst[@name='details']/lst[@name = 'slave']/str[@name = 'isReplicating']/text()")
            .evaluate(doc);
    //For some collections, when we query replication details, the replication hasn't started yet and the <slave> tag has not been generated yet.
    //That means the replication has not started yet.
    //Once the tag is generated, there will always be a field called currentDate, we use this tag to check if the replication started
    //Solr some times return something under the filed isReplicating, some times not and the replication normally already finished, so if
    //the currentDate field is populated and no info for isReplicating, that means the replication finished
    boolean replicating = !StringUtils.equalsIgnoreCase(isReplicating, "false");
    if (StringUtils.isBlank(curDate)) {
        replicating = true;
    } else {
        if (StringUtils.isBlank(isReplicating)) {
            replicating = false;
        }
    }
    String downloadSpeed = xpath
            .compile("/response/lst[@name='details']/lst[@name = 'slave']/str[@name = 'downloadSpeed']/text()")
            .evaluate(doc);
    String totalPercent = xpath
            .compile("/response/lst[@name='details']/lst[@name = 'slave']/str[@name = 'totalPercent']/text()")
            .evaluate(doc);
    String timeElapsed = xpath
            .compile("/response/lst[@name='details']/lst[@name = 'slave']/str[@name = 'timeElapsed']/text()")
            .evaluate(doc);
    String timeRemaining = xpath
            .compile("/response/lst[@name='details']/lst[@name = 'slave']/str[@name = 'timeRemaining']/text()")
            .evaluate(doc);
    String bytesDownloaded = xpath
            .compile(
                    "/response/lst[@name='details']/lst[@name = 'slave']/str[@name = 'bytesDownloaded']/text()")
            .evaluate(doc);
    String bytesToDownload = xpath
            .compile(
                    "/response/lst[@name='details']/lst[@name = 'slave']/str[@name = 'bytesToDownload']/text()")
            .evaluate(doc);
    diagnostics.setPercentageComplete(totalPercent);
    diagnostics.setTimeElapsed(timeElapsed);
    logger.info(core + ": " + totalPercent + "% Bytes:" + bytesDownloaded + "/" + bytesToDownload + " @ "
            + downloadSpeed + " Time:" + timeElapsed + "/" + timeRemaining);
    logger.info("This is the return value " + replicating + "  isReplicating:  " + isReplicating);

    if (!replicating) {
        logger.info("REPLICATION COMPLETE: " + host + " : " + core);
    }

    diagnostics.setReplicating(replicating);
    return diagnostics;
}

From source file:com.opentok.OpenTok.java

private static String readXml(String xpathQuery, String xml) throws XPathExpressionException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    InputSource source = new InputSource(new StringReader(xml));
    return xpath.evaluate(xpathQuery, source);
}