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:ch.dbs.actions.bestellung.EZBVascoda.java

/**
 * This class uses the EZB API from//w  w  w.  j  av a  2 s .  c o m
 * http://ezb.uni-regensburg.de/ezeit/vascoda/openURL?pid=format%3Dxml. This
 * API differs from the EZB/ZDB API (http://services.dnb.de). It brings back
 * no print information and other information for electronic holdings. It
 * seems to be more stable.
 */
public EZBForm read(final String content) {

    final EZBForm ezbform = new EZBForm();

    try {

        if (content != null) {

            final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            final DocumentBuilder builder = domFactory.newDocumentBuilder();
            final Document doc = builder.parse(new InputSource(new StringReader(content)));

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

            // issns
            final XPathExpression exprRefE = xpath.compile("//OpenURLResponse");
            final NodeList resultListRefE = (NodeList) exprRefE.evaluate(doc, XPathConstants.NODESET);

            String title = null;
            String levelAvailable = null;

            for (int i = 0; i < resultListRefE.getLength(); i++) {
                final Node firstResultNode = resultListRefE.item(i);
                final Element result = (Element) firstResultNode;

                // First ISSN
                //                    final String issn = getValue(result.getElementsByTagName("issn"));
                //                    System.out.println(issn);

                // title
                // unfortunately this will bring back the title sent by OpenURL, unless if not
                // specified in the OpenURL request. It then brings back the title form the EZB...!
                title = getValue(result.getElementsByTagName("title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    title = Jsoup.parse(title).text();
                }

                // this is the overall level of the best match and not the level of each individual result
                final NodeList levelNode = result.getElementsByTagName("available");
                final Element levelElement = (Element) levelNode.item(0);
                if (levelElement != null) {
                    levelAvailable = levelElement.getAttribute("level");
                }

            }

            // electronic data
            final XPathExpression exprE = xpath.compile("//OpenURLResponse/OpenURLResult/Resultlist/Result");
            final NodeList resultListE = (NodeList) exprE.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < resultListE.getLength(); i++) {
                final Node firstResultNode = resultListE.item(i);
                final Element result = (Element) firstResultNode;

                final NodeList state = result.getElementsByTagName("access");
                final Element stateElement = (Element) state.item(0);
                int color = 0;
                if (stateElement != null) {
                    color = Integer.valueOf(stateElement.getAttribute("color"));
                }

                final EZBDataOnline online = new EZBDataOnline();

                // state
                // 1 free accessible
                if (color == EZBState.FREE.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.free");
                    online.setState(JOPState.FREE.getValue()); // translate state to EZB/ZDB-API
                    // 2 licensed ; 3 partially licensed
                } else if (color == EZBState.LICENSED.getValue()
                        || color == EZBState.LICENSED_PARTIALLY.getValue()) {
                    online.setAmpel("yellow");
                    online.setComment("availresult.abonniert");
                    online.setState(JOPState.LICENSED.getValue()); // translate state to EZB/ZDB-API
                    // not licensed
                } else if (color == EZBState.NOT_LICENSED.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                    online.setState(JOPState.NOT_LICENSED.getValue()); // translate state to EZB/ZDB-API
                } else {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                    online.setState(JOPState.NOT_LICENSED.getValue()); // translate state to EZB/ZDB-API
                }

                // LinkToArticle not always present
                String url = getValue(result.getElementsByTagName("LinkToArticle"));
                // LinkToJournal always present
                if (url == null) {
                    url = getValue(result.getElementsByTagName("LinkToJournal"));
                }
                online.setUrl(url);

                // try to get level from link
                String levelLinkToArticle = null;
                final NodeList levelNode = result.getElementsByTagName("LinkToArticle");
                final Element levelElement = (Element) levelNode.item(0);
                if (levelElement != null) {
                    levelLinkToArticle = levelElement.getAttribute("level");
                }

                if (levelLinkToArticle != null) {
                    online.setLevel(levelLinkToArticle); // specific level of each result
                } else {
                    online.setLevel(levelAvailable); // overall level of best match
                }

                if (title != null) {
                    online.setTitle(title);
                } else {
                    online.setTitle(url);
                }
                online.setReadme(getValue(result.getElementsByTagName("LinkToReadme")));

                ezbform.getOnline().add(online);
            }

            // Title not found
            if (resultListE.getLength() == 0) {
                final EZBDataOnline online = new EZBDataOnline();
                online.setAmpel("red");
                online.setComment("availresult.nohits");
                online.setState(JOPState.NO_HITS.getValue()); // translate state to EZB/ZDB-API

                ezbform.getOnline().add(online);
            }

        }

    } catch (final XPathExpressionException e) {
        LOG.error(e.toString());
    } catch (final SAXParseException e) {
        LOG.error(e.toString());
    } catch (final SAXException e) {
        LOG.error(e.toString());
    } catch (final IOException e) {
        LOG.error(e.toString());
    } catch (final ParserConfigurationException e) {
        LOG.error(e.toString());
    } catch (final Exception e) {
        LOG.error(e.toString());
    }

    return ezbform;
}

From source file:com.github.radium226.github.maven.MetaDataDownloader.java

public static String evaluateXPath(InputStream pomInputStream, String expression)
        throws XPathExpressionException {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    xPath.setNamespaceContext(new NamespaceContext() {

        @Override//from w w  w .  j a v a 2 s.  c o  m
        public String getNamespaceURI(String prefix) {
            if (prefix.equals("ns")) {
                return "http://maven.apache.org/POM/4.0.0";
            }

            return null;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            return null;
        }

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            return null;
        }
    });
    XPathExpression xPathExpression = xPath.compile(expression);
    String version = (String) xPathExpression.evaluate(new InputSource(pomInputStream), XPathConstants.STRING);
    return version;
}

From source file:com.rackspace.api.clients.veracode.responses.AbstractXmlResponse.java

public AbstractXmlResponse(HttpResponse response) throws VeracodeApiException {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;

    try {//from www . ja v  a2 s.  com
        builder = domFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Xml Configuration Issue parsing response", e);
    }

    HttpEntity responseEntity = extractResponse(response);

    try {
        if (response.getStatusLine().getStatusCode() == 200) {
            this.doc = builder.parse(responseEntity.getContent());
            EntityUtils.consume(responseEntity);
        } else {
            String errorMessage = EntityUtils.toString(responseEntity);
            int errorCode = response.getStatusLine().getStatusCode();

            throw new VeracodeApiException("Error Code: " + errorCode + " Error Message: " + errorMessage);
        }
    } catch (SAXException e) {
        throw new VeracodeApiException("Could not Parse Response.", e);
    } catch (IOException e) {
        throw new VeracodeApiException("Could not Parse Response.", e);
    }

    XPathFactory factory = XPathFactory.newInstance();
    this.xpath = factory.newXPath();
}

From source file:com.thed.launcher.EggplantZBotScriptLauncher.java

@Override
public void testcaseExecutionResult() {
    String scriptPath = LauncherUtils.getFilePathFromCommand(currentTestcaseExecution.getScriptPath());
    logger.info("Script Path is " + scriptPath);
    File scriptFile = new File(scriptPath);
    String scriptName = scriptFile.getName().split("\\.")[0];
    logger.info("Script Name is " + scriptName);
    File resultsFolder = new File(
            scriptFile.getParentFile().getParentFile().getAbsolutePath() + File.separator + "Results");
    File statisticalFile = resultsFolder.listFiles(new FilenameFilter() {
        @Override/*from ww w. j  av a2  s.c  o m*/
        public boolean accept(File file, String s) {
            return StringUtils.endsWith(s, "Statistics.xml");
        }
    })[0];
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        Document statisticalDoc = getDoc(statisticalFile);
        String result = xpath.compile("/statistics/script[@name='" + scriptName + "']/LastStatus/text()")
                .evaluate(statisticalDoc, XPathConstants.STRING).toString();
        logger.info("Result is " + result);
        String comments;
        if (StringUtils.equalsIgnoreCase(result, "Success")) {
            logger.info("Test success detected");
            status = currentTestcaseExecution.getTcId() + ": " + currentTestcaseExecution.getScriptId()
                    + " STATUS: Script Successfully Executed";
            currentTcExecutionResult = new Integer(1);
            comments = " Successfully executed on " + agent.getAgentHostAndIp();
        } else {
            logger.info("Test failure detected, getting error message");
            status = currentTestcaseExecution.getTcId() + ": " + currentTestcaseExecution.getScriptId()
                    + " STATUS: Script Successfully Executed";
            currentTcExecutionResult = new Integer(2);
            comments = " Error in test: ";
            String lastRunDateString = xpath
                    .compile("/statistics/script[@name='" + scriptName + "']/LastRun/text()")
                    .evaluate(statisticalDoc);
            //Date lastRunDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(lastRunDateString);
            File historyFile = new File(resultsFolder.getAbsolutePath() + File.separator + scriptName
                    + File.separator + "RunHistory.xml");
            Document historyDoc = getDoc(historyFile);
            //xpath = XPathFactory.newInstance().newXPath();
            String xpathExpr = "/runHistory[@script='" + scriptName + "']/run[contains(RunDate, '"
                    + StringUtils.substringBeforeLast(lastRunDateString, " ") + "')]/ErrorMessage/text()";
            logger.info("Using xPath to find errorMessage " + xpathExpr);
            comments += xpath.compile(xpathExpr).evaluate(historyDoc, XPathConstants.STRING);
            logger.info("Sending comments: " + comments);
        }
        if (currentTcExecutionResult != null) {
            ScriptUtil.updateTestcaseExecutionResult(url, currentTestcaseExecution, currentTcExecutionResult,
                    comments);
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error in reading process steams \n", e);
    }
}

From source file:org.jasig.portlet.calendar.service.RoleService.java

/**
 * Do the real work of reading the role list.
 *
 * @return the set of role names./*  ww  w  .jav a  2s .  co  m*/
 */
private Set<String> readRolesFromPortletXml() {
    try {
        URL portletXmlUrl = context.getResource(PORTLET_XML_PATH);
        InputSource is = new InputSource(portletXmlUrl.openStream());

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = builder.parse(is);

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression xPathExpression = xpath.compile(ROLES_XPATH);

        NodeList nodeList = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET);

        Set<String> roles = new LinkedHashSet<String>();
        for (int i = 0; i < nodeList.getLength(); i++) {
            String role = nodeList.item(i).getNodeValue();
            roles.add(role);
        }

        return roles;

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException("Error reading roles from portlet.xml", e);
    }
}

From source file:com.netscape.cms.tomcat.PKIListener.java

@Override
public void lifecycleEvent(LifecycleEvent event) {

    String type = event.getType();
    logger.info("PKIListener: " + event.getLifecycle().getClass().getName() + " [" + type + "]");

    if (type.equals(Lifecycle.BEFORE_INIT_EVENT)) {

        String wdPipeName = System.getenv("WD_PIPE_NAME");
        if (StringUtils.isNotEmpty(wdPipeName)) {
            startedByWD = true;/*from www.j  ava  2 s.c om*/
            logger.info("PKIListener: Initializing the watchdog");
            WatchdogClient.init();
        }

        logger.info("PKIListener: Initializing TomcatJSS");

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            String catalinaBase = System.getProperty("catalina.base");
            File file = new File(catalinaBase + "/conf/server.xml");
            Document doc = builder.parse(file);

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

            Element connector = (Element) xpath.evaluate(
                    "/Server/Service[@name='Catalina']/Connector[@name='Secure']", doc, XPathConstants.NODE);

            TomcatJSS tomcatjss = TomcatJSS.getInstance();

            String certDb = connector.getAttribute("certdbDir");
            if (certDb != null)
                tomcatjss.setCertdbDir(certDb);

            String passwordClass = connector.getAttribute("passwordClass");
            if (passwordClass != null)
                tomcatjss.setPasswordClass(passwordClass);

            String passwordFile = connector.getAttribute("passwordFile");
            if (passwordFile != null)
                tomcatjss.setPasswordFile(passwordFile);

            String serverCertNickFile = connector.getAttribute("serverCertNickFile");
            if (serverCertNickFile != null)
                tomcatjss.setServerCertNickFile(serverCertNickFile);

            String enableOCSP = connector.getAttribute("enableOCSP");
            if (enableOCSP != null)
                tomcatjss.setEnableOCSP(Boolean.parseBoolean(enableOCSP));

            String ocspResponderURL = connector.getAttribute("ocspResponderURL");
            if (ocspResponderURL != null)
                tomcatjss.setOcspResponderURL(ocspResponderURL);

            String ocspResponderCertNickname = connector.getAttribute("ocspResponderCertNickname");
            if (ocspResponderCertNickname != null)
                tomcatjss.setOcspResponderCertNickname(ocspResponderCertNickname);

            String ocspCacheSize = connector.getAttribute("ocspCacheSize");
            if (ocspCacheSize != null)
                tomcatjss.setOcspCacheSize(Integer.parseInt(ocspCacheSize));

            String ocspMinCacheEntryDuration = connector.getAttribute("ocspMinCacheEntryDuration");
            if (ocspMinCacheEntryDuration != null)
                tomcatjss.setOcspMinCacheEntryDuration(Integer.parseInt(ocspMinCacheEntryDuration));

            String ocspMaxCacheEntryDuration = connector.getAttribute("ocspMaxCacheEntryDuration");
            if (ocspMaxCacheEntryDuration != null)
                tomcatjss.setOcspMaxCacheEntryDuration(Integer.parseInt(ocspMaxCacheEntryDuration));

            String ocspTimeout = connector.getAttribute("ocspTimeout");
            if (ocspTimeout != null)
                tomcatjss.setOcspTimeout(Integer.parseInt(ocspTimeout));

            String strictCiphers = connector.getAttribute("strictCiphers");
            if (strictCiphers != null)
                tomcatjss.setStrictCiphers(strictCiphers);

            String sslVersionRangeStream = connector.getAttribute("sslVersionRangeStream");
            if (sslVersionRangeStream != null)
                tomcatjss.setSslVersionRangeStream(sslVersionRangeStream);

            String sslVersionRangeDatagram = connector.getAttribute("sslVersionRangeDatagram");
            if (sslVersionRangeDatagram != null)
                tomcatjss.setSslVersionRangeDatagram(sslVersionRangeDatagram);

            String sslRangeCiphers = connector.getAttribute("sslRangeCiphers");
            if (sslRangeCiphers != null)
                tomcatjss.setSslRangeCiphers(sslRangeCiphers);

            String sslOptions = connector.getAttribute("sslOptions");
            if (sslOptions != null)
                tomcatjss.setSslOptions(sslOptions);

            String ssl2Ciphers = connector.getAttribute("ssl2Ciphers");
            if (ssl2Ciphers != null)
                tomcatjss.setSsl2Ciphers(ssl2Ciphers);

            String ssl3Ciphers = connector.getAttribute("ssl3Ciphers");
            if (ssl3Ciphers != null)
                tomcatjss.setSsl3Ciphers(ssl3Ciphers);

            String tlsCiphers = connector.getAttribute("tlsCiphers");
            if (tlsCiphers != null)
                tomcatjss.setTlsCiphers(tlsCiphers);

            tomcatjss.init();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    } else if (type.equals(Lifecycle.AFTER_START_EVENT)) {

        if (startedByWD) {
            logger.info("PKIListener: Sending endInit to the watchdog");
            WatchdogClient.sendEndInit(0);
        }

        verifySubsystems((Server) event.getLifecycle());
    }
}

From source file:org.apache.solr.kelvin.responseanalyzers.LegacyResponseAnalyzer.java

public void configure(JsonNode config) throws Exception {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    expr = xpath.compile("/response/federator/result/doc");
}

From source file:net.firejack.platform.core.config.meta.parse.XMLStreamDescriptorParser.java

private void uidValidation(String xml)
        throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);// w w w  .j  a  va  2  s  .  c  om
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//*/@uid");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    Map<String, Integer> uids = new HashMap<String, Integer>();
    for (int i = 0; i < nodes.getLength(); i++) {
        String uid = nodes.item(i).getNodeValue();
        Integer count = uids.get(uid);
        if (count == null) {
            count = 0;
        }
        count++;
        uids.put(uid, count);
    }
    StringBuilder errorMessage = new StringBuilder();
    for (Map.Entry<String, Integer> entry : uids.entrySet()) {
        if (entry.getValue() > 1) {
            errorMessage.append(" [").append(entry.getKey()).append("]");
        }
    }
    if (errorMessage.length() > 0) {
        throw new BusinessFunctionException(
                "UIDs are not unique in package.xml. Check UIDs:" + errorMessage.toString());
    }
}

From source file:Main.java

/**
 * Gets the node list from the given xml file and the given xpath expression.
 * // w ww .j  a va 2 s  . c o m
 * @param xml
 *            the xml file as string.
 * @param xpathExpression
 *            the xpath expression as string.
 * @return the node list
 * @throws XPathExpressionException
 *             the x path expression exception
 * @throws ParserConfigurationException
 *             the parser configuration exception
 * @throws SAXException
 *             the sAX exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static NodeList getNodeList(final String xml, final String xpathExpression)
        throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
    final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    final DocumentBuilder builder = domFactory.newDocumentBuilder();
    final Document doc = builder.parse(xml);
    final XPath xpath = XPathFactory.newInstance().newXPath();
    final XPathExpression expr = xpath.compile(xpathExpression);

    final Object result = expr.evaluate(doc, XPathConstants.NODESET);
    final NodeList nodes = (NodeList) result;
    return nodes;
}

From source file:cz.incad.kramerius.security.impl.criteria.MovingWall.java

public MovingWall() {
    this.xpfactory = XPathFactory.newInstance();
}