Example usage for javax.xml.xpath XPathFactory newInstance

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

Introduction

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

Prototype

public static XPathFactory newInstance() 

Source Link

Document

Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.

This method is functionally equivalent to:

 newInstance(DEFAULT_OBJECT_MODEL_URI) 

Since the implementation for the W3C DOM is always available, this method will never fail.

Usage

From source file:com.github.robozonky.app.version.UpdateMonitor.java

/**
 * Parse XML using XPath and retrieve the version string.
 * @param xml XML in question.//  w w  w.  ja  v  a  2 s. c o  m
 * @return The version string.
 * @throws ParserConfigurationException Failed parsing XML.
 * @throws IOException Failed I/O.
 * @throws SAXException Failed reading XML.
 * @throws XPathExpressionException XPath parsing problem.
 */
private static VersionIdentifier parseVersionString(final InputStream xml)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    final DocumentBuilderFactory factory = XmlUtil.getDocumentBuilderFactory();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.parse(xml);
    final XPathFactory xPathfactory = XPathFactory.newInstance();
    final XPath xpath = xPathfactory.newXPath();
    final XPathExpression expr = xpath.compile("/metadata/versioning/versions/version");
    return UpdateMonitor.parseNodeList((NodeList) expr.evaluate(doc, XPathConstants.NODESET));
}

From source file:com.gisgraphy.domain.geoloc.service.fulltextsearch.SolrClient.java

public boolean isServerAlive() {
    try {//  w  ww. jav a2  s.  c o m
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        XPath xpath = XPathFactory.newInstance().newXPath();
        if (xpath == null || builder == null) {
            throw new RuntimeException("Can not determine if fulltext engine is alive");
        }
        SolrPingResponse response = getServer().ping();
        if (response == null) {
            return false;
        }
        return ((String) response.getResponse().get("status")).equals("OK");
    } catch (Exception e) {
        logger.error("can not determine if fulltext engine is alive " + e.getMessage());
        return false;
    }

}

From source file:com.stevpet.sonar.plugins.dotnet.resharper.customseverities.BaseCustomSeverities.java

/**
 * create xpath and assign the namespace resolver for InspectCode namespace
 * @return xpath//from  www  .  java  2s .  co  m
 */
private XPath createXPathForInspectCode() {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    NamespaceContext inspectCodeNamespaceResolver = new InspectCodeNamespaceResolver();
    xpath.setNamespaceContext(inspectCodeNamespaceResolver);
    return xpath;
}

From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java

/**
 * Parses the response received by making call to REST API.
 * It parses and gets the total no. roles and their instances.
 * /*  w w  w  . j  a  v  a 2s .  c  om*/
 * @param roleInfo
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 * @throws ParseException
 */
private void parseRoleInfo(StringBuffer roleInfo) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, ParseException {
    DocumentBuilder docBuilder = null;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    docBuilder = docBuilderFactory.newDocumentBuilder();
    doc = docBuilder.parse(new InputSource(new StringReader(roleInfo.toString())));

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    NodeList roleList = (NodeList) xPath.evaluate("/Deployment/RoleList/Role/RoleName", doc,
            XPathConstants.NODESET);
    //get all the roles
    String roleName = null;
    List<String> listRoleNames = new ArrayList<String>();
    for (int i = 0; i < roleList.getLength(); i++) {
        Element element = (Element) roleList.item(i);
        roleName = element.getTextContent();
        RoleEntity roleEntity = roleDao.findByRoleName(roleName);
        if (roleEntity == null) {
            roleEntity = new RoleEntity();
            roleEntity.setName(roleName);
            roleDao.add(roleEntity);
        }
        listRoleNames.add(roleName);
    }

    xPathFactory = XPathFactory.newInstance();
    xPath = xPathFactory.newXPath();
    RoleInstancesEntity roleInstancesEntity = null;
    RoleInstancesId roleInstancesId = null;
    for (String name : listRoleNames) {
        roleList = (NodeList) xPath.evaluate(
                "/Deployment/RoleInstanceList/RoleInstance[RoleName='" + name + "']", doc,
                XPathConstants.NODESET);
        //get no. of instances for WorkerRole
        int noOfInstances = roleList.getLength();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        String date = dateFormat.format(calendar.getTime());
        roleInstancesId = new RoleInstancesId(dateFormat.parse(date), name);
        roleInstancesEntity = new RoleInstancesEntity(roleInstancesId, noOfInstances, "UPDATE");
        roleInstancesDao.add(roleInstancesEntity);
    }

}

From source file:eu.impact_project.wsclient.HtmlServiceProvider.java

private NodeList applyXPath(Document doc, String xpathExpression, String namespace) {

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

    if (!namespace.equals(NO_NAMESPACE))
        xpath.setNamespaceContext(new WSDLNamespaceContext());

    XPathExpression expr;//from  w  ww.  j  a  v a 2  s .c  o  m

    Object result = null;
    try {
        expr = xpath.compile(xpathExpression);
        result = expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return (NodeList) result;

}

From source file:org.dataconservancy.dcs.integration.main.ManualDepositIT.java

/**
 * Ensure that the <code>href</code> attribute values for &lt;collection&gt;s are valid URLs.
 *//* w  w w  .  ja  v a2 s .c o m*/
@Test
public void testServiceDocCollectionUrls() throws IOException, XPathExpressionException {
    final HttpGet req = new HttpGet(serviceDocUrl);
    final HttpResponse resp = client.execute(req);
    assertEquals("Unable to retrieve atompub service document " + serviceDocUrl, 200,
            resp.getStatusLine().getStatusCode());

    final XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            if ("app".equals(prefix) || prefix == null || "".equals(prefix)) {
                return ATOM_NS;
            }
            throw new RuntimeException("Unknown xmlns prefix: '" + prefix + "'");
        }

        @Override
        public String getPrefix(String nsUri) {
            if (ATOM_NS.equals(nsUri)) {
                return "app";
            }
            throw new RuntimeException("Unknown xmlns uri '" + nsUri + "'");
        }

        @Override
        public Iterator<String> getPrefixes(String s) {
            ArrayList<String> prefixes = new ArrayList<String>();
            prefixes.add("app");
            return prefixes.iterator();
        }
    });

    final String xpathExpression = "//app:collection/@href";
    final NodeList collectionHrefs = (NodeList) xpath.evaluate(xpathExpression,
            new InputSource(resp.getEntity().getContent()), XPathConstants.NODESET);

    assertTrue(
            "No atompub collections found in service document " + serviceDocUrl + " (xpath search '"
                    + xpathExpression + "' yielded no results.",
            collectionHrefs != null && collectionHrefs.getLength() > 0);

    for (int i = 0; i < collectionHrefs.getLength(); i++) {
        final String collectionUrl = collectionHrefs.item(i).getNodeValue();
        assertNotNull("atompub collection url was null.", collectionUrl);
        assertTrue("atompub collection url was the empty string.", collectionUrl.trim().length() > 0);
        new URL(collectionUrl);
        assertTrue("Expected atompub collection url to start with " + serviceDocUrl + " (collection url was: "
                + collectionUrl, collectionUrl.startsWith(serviceDocUrl));
    }
}

From source file:io.selendroid.nativetests.GetWindowSourceTest.java

private Element findElementByXpath(String expr, String source) throws Exception {
    String xml = JsonXmlUtil.toXml(new JSONObject(source));
    InputSource is = new InputSource(new StringReader(xml));
    XPath xPath = XPathFactory.newInstance().newXPath();

    XPathExpression xpathExpr = xPath.compile(expr);
    return (Element) xpathExpr.evaluate(is, XPathConstants.NODE);
}

From source file:org.opencastproject.remotetest.util.WorkflowUtils.java

/**
 * Parses the workflow instance represented by <code>xml</code> and extracts the workflow identifier.
 * // w  w w . j  a v  a 2s  . c om
 * @param xml
 *          the workflow instance
 * @return the workflow instance
 * @throws Exception
 *           if parsing fails
 */
public static String getWorkflowInstanceId(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8"));
    return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE))
            .getAttribute("id");
}

From source file:eu.smartfp7.terrier.sensor.ParserUtility.java

public static EdgeNodeSnapShot parseShort(InputStream is) throws Exception {

    DocumentBuilderFactory xmlfact = DocumentBuilderFactory.newInstance();
    xmlfact.setNamespaceAware(true);// w w  w. j ava 2s.c o  m
    Document document = xmlfact.newDocumentBuilder().parse(is);

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

    String time = (String) xpath.compile("//crowd/time/text()").evaluate(document, XPathConstants.STRING);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar c = Calendar.getInstance();
    ;
    c.setTime(df.parse(time));

    String density = (String) xpath.compile("//crowd/density/text()").evaluate(document, XPathConstants.STRING);

    NodeList list = (NodeList) xpath.compile("//crowd/colour").evaluate(document, XPathConstants.NODESET);
    double[] colors = new double[list.getLength()];
    for (int i = 0; i < list.getLength(); i++) {
        org.w3c.dom.Node colorNode = list.item(i);
        String v = colorNode.getFirstChild().getTextContent();
        colors[i] = new Double(v);
    }

    String activity = (String) xpath.compile("//activity/name/text()").evaluate(document,
            XPathConstants.STRING);

    CrowdReport crowdReport = new CrowdReport(null, new Double(density), 0.0, colors);

    EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(null, null, c, crowdReport);
    snapShot.setText((activity != null ? activity : StringUtils.EMPTY));

    return snapShot;

}

From source file:com.seajas.search.utilities.web.WebPages.java

private XPath getXPathEngine() {
    XPath engine = xPathEngine;/*from  w w w.  ja  va  2  s.  c o m*/
    if (engine == null) {
        XPathFactory factory = XPathFactory.newInstance();
        engine = factory.newXPath();
        SimpleNamespaceContext namespaces = new SimpleNamespaceContext();
        namespaces.bindNamespaceUri("ht", "http://www.w3.org/1999/xhtml");
        engine.setNamespaceContext(namespaces);
        xPathEngine = engine;
    }
    return engine;
}