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:eu.fbk.dh.tint.tokenizer.ItalianTokenizer.java

public ItalianTokenizer(@Nullable File settingFile) {
        Trie.TrieBuilder builder = Trie.builder().removeOverlaps();

        InputStream stream = null;
        if (settingFile != null) {
            try {
                stream = new FileInputStream(settingFile);
            } catch (FileNotFoundException e) {
                // continue
            }// www.j a  v a  2  s  .co  m
        }
        if (stream == null) {
            stream = this.getClass().getResourceAsStream("/token-settings.xml");
        }

        logger.trace("Loading model");
        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();

            XPathExpression expr;
            NodeList nl;
            int count;

            Document doc = dBuilder.parse(stream);
            doc.getDocumentElement().normalize();

            // Normalization rules
            expr = xpath.compile("/settings/normalization/char");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String hexCode = element.getAttribute("hexcode");
                String content = element.getTextContent();

                // Bad: need fix
                if (content.equals("`")) {
                    content = "'";
                }

                int num = Integer.parseInt(hexCode, 16);
                if (content.length() == 0) {
                    continue;
                }
                normalizedChars.put(num, content);
            }
            logger.info("Loaded {} normalization rules", normalizedChars.size());

            // end sentence chars
            expr = xpath.compile("/settings/sentenceSplitting/char");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String charID = element.getAttribute("id");
                sentenceChars.add(Integer.parseInt(charID));
            }
            logger.info("Loaded {} sentence splitting rules", sentenceChars.size());

            // splitting rules
            expr = xpath.compile("/settings/tokenSplitting/char");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String charID = element.getAttribute("id");
                splittingChars.add(Integer.parseInt(charID));
            }
            logger.info("Loaded {} token splitting rules", splittingChars.size());

            // expressions
            expr = xpath.compile("/settings/expressions/expression");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            StringBuilder b = new StringBuilder();
            b.append("(");
            boolean first = true;
            count = 0;
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                Element element = (Element) item;
                String regExp = element.getAttribute("find");
                boolean merge = PropertiesUtils.getBoolean(element.getAttribute("merge"), true);
                Integer group = PropertiesUtils.getInteger(element.getAttribute("get"), 1);
                if (merge) {
                    if (!first) {
                        b.append("|");
                    }
                    b.append(regExp);
                    count++;
                    first = false;
                } else {
                    expressions.put(Pattern.compile(regExp), group);
                    count++;
                }
            }
            b.append(")");
            expressions.put(Pattern.compile(b.toString()), 1);
            logger.info("Loaded {} regular expressions", count);

            // abbreviations
            expr = xpath.compile("/settings/abbreviations/abbreviation");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            count = 0;
            for (int i = 0; i < nl.getLength(); i++) {
                Node item = nl.item(i);
                String abbr = item.getTextContent();
                abbr = getString(tokenArray(abbr));
                builder.addKeyword(" " + abbr + " ");
                count++;
            }
            logger.info("Loaded {} abbreviations", count);

        } catch (Exception e) {
            e.printStackTrace();
        }

        trie = builder.build();
    }

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

/**
 * Parses the job instance represented by <code>xml</code> and extracts the job type.
 * /*w w w  . j  a va 2  s  . c o m*/
 * @param xml
 *          the job instance
 * @return the job type
 * @throws Exception
 *           if parsing fails
 */
public static String getJobType(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("type");
}

From source file:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java

public ZencoderClient(String zencoderApiKey, String zencoderReadOnlyApiKey, ZencoderAPIVersion apiVersion) {
    this.zencoderAPIKey = zencoderApiKey;
    this.zencoderReadOnlyAPIKey = zencoderReadOnlyApiKey;
    if (ZencoderAPIVersion.API_DEV.equals(apiVersion)) {
        LOGGER.warn("!!! Using development version of zencoder API !!!");
    }//from www.j a va  2s .com

    this.zencoderAPIVersion = apiVersion;

    httpClient = ApacheHttpClient.create();
    httpClient.setFollowRedirects(true);

    // set a 20 second timeout on the client
    httpClient.setConnectTimeout(20000);
    httpClient.setReadTimeout(20000);

    xPath = XPathFactory.newInstance().newXPath();
    zencoderAPIBaseUrl = zencoderAPIVersion.getBaseUrl();
}

From source file:XMLBody.java

public String getContent(String xpath) throws Exception {
    XPath path = XPathFactory.newInstance().newXPath();
    NodeList childNodes;/* w w  w  . j  av  a 2s .co m*/
    try {
        childNodes = (NodeList) path.evaluate(xpath, xmlDocument, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new Exception("Error evaluate xpath", e);
    }
    return serializeNodes(childNodes);
}

From source file:com.cisco.dvbu.ps.common.adapters.config.SoapHttpConfig.java

private void parseCallback(Element eElement) throws AdapterException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {/*from  w  w w.  j a v a 2 s  .  c  o m*/
        SoapHttpConnectorCallback cb = new SoapHttpConnectorCallback();
        cb.setOperation(eElement.getAttribute(AdapterConstants.CONNECTOR_SE_NAME));
        //         log.debug("Operation: " + cb.getOperation());
        cb.setEndpoint(eElement.getAttribute(AdapterConstants.CONNECTOR_SH_ENDPOINT));
        //         log.debug("Endpoint: " + cb.getEndpoint());
        cb.setName(cb.getEndpoint() + AdapterConstants.CONNECTOR_EP_SEPARATOR + cb.getOperation());
        Element e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_CB_SOAPACTION, eElement,
                XPathConstants.NODE);
        cb.setAction(e.getTextContent());
        //         log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_CB_RQ_BODY, eElement, XPathConstants.NODE);
        cb.setRequestBodyXsl(e.getTextContent().trim());
        //         log.debug(e.getNodeName() + ": " + e.getTextContent());
        e = (Element) xpath.evaluate(AdapterConstants.XPATH_CONN_CB_RS_BODY, eElement, XPathConstants.NODE);
        cb.setResponseBodyXsl(e.getTextContent().trim());
        //         log.debug(e.getNodeName() + ": " + e.getTextContent());
        connCallbacks.put(cb.getName(), cb);
    } catch (Exception e) {
        log.error("Configuration File Error! One or more mandatory configuration options are missing");
        throw new AdapterException(401,
                "Configuration File Error! One or more mandatory configuration options are missing.", e);
    }
}

From source file:org.fcrepo.mint.HttpPidMinter.java

/**
 * Create a new HttpPidMinter.//from www. java2s . c o m
 * @param url The URL for the minter service.  This is the only required argument -- all
 *    other parameters can be blank.
 * @param method The HTTP method (POST, PUT or GET) used to generate a new PID (POST will
 *    be used if the method is blank.
 * @param username If not blank, use this username to connect to the minter service.
 * @param password If not blank, use this password used to connect to the minter service.
 * @param regex If not blank, use this regular expression used to remove unwanted text from the
 *    minter service response.  For example, if the response text is "/foo/bar:baz" and the
 *    desired identifier is "baz", then the regex would be ".*:".
 * @param xpath If not blank, use this XPath expression used to extract the desired identifier
 *    from an XML minter response.
**/
public HttpPidMinter(final String url, final String method, final String username, final String password,
        final String regex, final String xpath) {

    if (isBlank(url)) {
        throw new IllegalArgumentException("Minter URL must be specified!");
    }

    this.url = url;
    this.method = (method == null ? "post" : method);
    this.username = username;
    this.password = password;
    this.regex = regex;
    if (!isBlank(xpath)) {
        try {
            this.xpath = XPathFactory.newInstance().newXPath().compile(xpath);
        } catch (final XPathException ex) {
            LOGGER.warn("Error parsing xpath ({}): {}", xpath, ex.getMessage());
            throw new IllegalArgumentException("Error parsing xpath" + xpath, ex);
        }
    }
    this.client = buildClient();
}

From source file:it.jnrpe.plugin.tomcat.TomcatDataProvider.java

private void parseMemoryPools() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(tomcatXML));

    Document doc = builder.parse(is);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();

    NodeList memoryPoolList = (NodeList) xpath.compile("//status/jvm/memorypool")
            .evaluate(doc.getDocumentElement(), XPathConstants.NODESET);

    for (int i = 0; i < memoryPoolList.getLength(); i++) {
        Node poolNode = memoryPoolList.item(i);
        NamedNodeMap atts = poolNode.getAttributes();
        final String poolName = atts.getNamedItem("name").getNodeValue();
        long usageInit = Long.parseLong(atts.getNamedItem("usageInit").getNodeValue());
        long usageCommitted = Long.parseLong(atts.getNamedItem("usageCommitted").getNodeValue());
        long usageMax = Long.parseLong(atts.getNamedItem("usageMax").getNodeValue());
        long usageUsed = Long.parseLong(atts.getNamedItem("usageUsed").getNodeValue());

        memoryPoolData.put(poolName,//w  ww .j av  a  2s . c om
                new MemoryPoolData(poolName, usageInit, usageCommitted, usageMax, usageUsed));
    }
}

From source file:org.opencastproject.remotetest.server.WorkflowAuthorizationTest.java

protected String getXACMLAttachmentId(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//w w w  .j a  v a 2 s . co  m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8"));
    return ((String) XPathFactory.newInstance().newXPath()
            .compile("//*[local-name() = 'attachment'][@type='security/xacml']/@id")
            .evaluate(doc, XPathConstants.STRING));
}

From source file:eu.interedition.collatex.tools.CollationPipe.java

public static void start(CommandLine commandLine) throws Exception {
    List<SimpleWitness> witnesses = null;
    Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT;
    Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS;
    Comparator<Token> comparator = new EqualityTokenComparator();
    CollationAlgorithm collationAlgorithm = null;
    boolean joined = true;

    final String[] witnessSpecs = commandLine.getArgs();
    final InputStream[] inputStreams = new InputStream[witnessSpecs.length];
    for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) {
        try {//from w w w .j a v a  2s .c  o m
            inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]);
        } catch (MalformedURLException urlEx) {
            throw new ParseException("Invalid resource: " + witnessSpecs[wc]);
        }
    }

    if (inputStreams.length < 1) {
        throw new ParseException("No input resource(s) given");
    } else if (inputStreams.length < 2) {
        try (InputStream inputStream = inputStreams[0]) {
            final SimpleCollation collation = JsonProcessor.read(inputStream);
            witnesses = collation.getWitnesses();
            collationAlgorithm = collation.getAlgorithm();
            joined = collation.isJoined();
        }
    }

    final String script = commandLine.getOptionValue("s");
    try {
        final PluginScript pluginScript = (script == null
                ? PluginScript.read("<internal>", new StringReader(""))
                : PluginScript.read(argumentToInput(script)));

        tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer);
        normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer);
        comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator);
    } catch (IOException e) {
        throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage());
    }

    switch (commandLine.getOptionValue("a", "").toLowerCase()) {
    case "needleman-wunsch":
        collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator);
        break;
    case "medite":
        collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR);
        break;
    case "gst":
        collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2);
        break;
    default:
        collationAlgorithm = Optional.ofNullable(collationAlgorithm)
                .orElse(CollationAlgorithmFactory.dekker(comparator));
        break;
    }

    if (witnesses == null) {
        final Charset inputCharset = Charset
                .forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name()));
        final boolean xmlMode = commandLine.hasOption("xml");
        final XPathExpression tokenXPath = XPathFactory.newInstance().newXPath()
                .compile(commandLine.getOptionValue("xp", "//text()"));

        witnesses = new ArrayList<>(inputStreams.length);
        for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) {
            try (InputStream stream = inputStreams[wc]) {
                final String sigil = "w" + (wc + 1);
                if (!xmlMode) {
                    final BufferedReader reader = new BufferedReader(
                            new InputStreamReader(stream, inputCharset));
                    final StringWriter writer = new StringWriter();
                    final char[] buf = new char[1024];
                    while (reader.read(buf) != -1) {
                        writer.write(buf);
                    }
                    witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer));
                } else {
                    final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
                            .newDocumentBuilder();
                    final Document document = documentBuilder.parse(stream);
                    document.normalizeDocument();

                    final SimpleWitness witness = new SimpleWitness(sigil);
                    final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document,
                            XPathConstants.NODESET);
                    final List<Token> tokens = new ArrayList<>(tokenNodes.getLength());
                    for (int nc = 0; nc < tokenNodes.getLength(); nc++) {
                        final String tokenText = tokenNodes.item(nc).getTextContent();
                        tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText)));
                    }
                    witness.setTokens(tokens);
                    witnesses.add(witness);
                }
            }
        }
    }

    final VariantGraph variantGraph = new VariantGraph();
    collationAlgorithm.collate(variantGraph, witnesses);

    if (joined && !commandLine.hasOption("t")) {
        VariantGraph.JOIN.apply(variantGraph);
    }

    final String output = commandLine.getOptionValue("o", "-");
    final Charset outputCharset = Charset
            .forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name()));
    final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase();

    try (PrintWriter out = argumentToOutput(output, outputCharset)) {
        final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph);
        if ("csv".equals(outputFormat)) {
            serializer.toCsv(out);
        } else if ("dot".equals(outputFormat)) {
            serializer.toDot(out);
        } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) {
            XMLStreamWriter xml = null;
            try {
                xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
                xml.writeStartDocument(outputCharset.name(), "1.0");
                if ("graphml".equals(outputFormat)) {
                    serializer.toGraphML(xml);
                } else {
                    serializer.toTEI(xml);
                }
                xml.writeEndDocument();
            } catch (XMLStreamException e) {
                throw new IOException(e);
            } finally {
                if (xml != null) {
                    try {
                        xml.close();
                    } catch (XMLStreamException e) {
                        // ignored
                    }
                }
            }
        } else {
            JsonProcessor.write(variantGraph, out);
        }
    }
}

From source file:com.github.koraktor.steamcondenser.community.XMLData.java

/**
 * Returns the XML data for the element specified by the given XPath
 *
 * @param path The XPath to get the XML data for
 * @return The element with the given XPath
 *//*from w  w  w. j a v a2s . c om*/
public XMLData getXPath(String path) {
    if (xpath == null) {
        xpath = XPathFactory.newInstance().newXPath();
    }

    try {
        return new XMLData((Element) xpath.evaluate(path, this.root, XPathConstants.NODE));
    } catch (XPathExpressionException e) {
        return null;
    }
}