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:org.jasig.portlet.proxy.search.GsaSearchStrategy.java

@Override
public List<SearchResult> search(SearchRequest searchQuery, EventRequest request,
        org.jsoup.nodes.Document ignore) {

    List<SearchResult> searchResults = new ArrayList<SearchResult>();

    String searchBaseURL = this.buildGsaUrl(searchQuery, request);
    HttpClient client = new DecompressingHttpClient(new DefaultHttpClient());
    HttpGet get = new HttpGet(searchBaseURL);

    try {/*from   ww  w .  ja  v a2  s  . com*/

        HttpResponse httpResponse = client.execute(get);
        log.debug("STATUS CODE :: " + httpResponse.getStatusLine().getStatusCode());

        InputStream in = httpResponse.getEntity().getContent();

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = docFactory.newDocumentBuilder();

        Document doc = builder.parse(in);

        log.debug(("GOT InputSource"));
        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();

        Integer maxCount = Integer.parseInt(xPath.evaluate("count(/GSP/RES/R)", doc));

        final String[] whitelistRegexes = request.getPreferences().getValues("gsaWhitelistRegex",
                new String[] {});

        log.debug(maxCount + " -- Results");
        for (int count = 1; count <= maxCount; count++) {
            String u = xPath.evaluate("/GSP/RES/R[" + count + "]/U/text()", doc);
            String t = xPath.evaluate("/GSP/RES/R[" + count + "]/T/text()", doc);
            String s = xPath.evaluate("/GSP/RES/R[" + count + "]/S/text()", doc);

            log.debug("title: [" + t + "]");
            SearchResult result = new SearchResult();
            result.setTitle(t);
            result.setSummary(s);

            PortletUrl pUrl = new PortletUrl();
            pUrl.setPortletMode(PortletMode.VIEW.toString());
            pUrl.setType(PortletUrlType.RENDER);
            pUrl.setWindowState(WindowState.MAXIMIZED.toString());
            PortletUrlParameter param = new PortletUrlParameter();
            param.setName("proxy.url");
            param.getValue().add(u);
            pUrl.getParam().add(param);
            result.setPortletUrl(pUrl);

            new SearchUtil().updateUrls(u, request, whitelistRegexes);
            searchResults.add(result);
        }

    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
    } catch (XPathExpressionException ex) {
        log.error(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        log.error(ex.getMessage(), ex);
    } catch (SAXException ex) {
        log.error(ex.getMessage(), ex);
    }

    return searchResults;

}

From source file:com.sqewd.os.maracache.core.Config.java

/**
 * Load the configuration from the path and file specified.
 *
 * @throws ConfigException//from   ww  w .ja  v a2s .  c om
 */
public void load() throws ConfigException {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(filePath);

        //optional, but recommended
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        XPath xp = XPathFactory.newInstance().newXPath();
        Element root = (Element) xp.compile(configPath).evaluate(doc, XPathConstants.NODE);
        if (root == null) {
            throw new ConfigException("Cannot find specified path in document. [path=" + configPath + "]");
        }

        node = new ConfigPath(root.getNodeName(), null);
        load(node, root);

        state = EObjectState.Available;
    } catch (ParserConfigurationException pse) {
        state = EObjectState.Exception;
        state.setException(pse);
        throw new ConfigException("Error building the configuration document.", pse);
    } catch (IOException ioe) {
        state = EObjectState.Exception;
        state.setException(ioe);
        throw new ConfigException("Error reading configuration file [path=" + filePath + "]", ioe);
    } catch (SAXException se) {
        state = EObjectState.Exception;
        state.setException(se);
        throw new ConfigException("Error parsing document [document=" + filePath + "]", se);
    } catch (XPathExpressionException xpe) {
        state = EObjectState.Exception;
        state.setException(xpe);
        throw new ConfigException("Error parsing specified XPath expression.", xpe);
    }
}

From source file:es.sistedes.handle.generator.Conversor.java

/**
 * Converts the XML data available in the <code>input</code>
 * {@link InputStream} and dumps the result in the <code>output</code>
 * {@link OutputStream}//w  w  w.  ja v a2 s.co m
 * 
 * @throws ConversionException
 *             If any error occurs, check
 *             {@link ConversionException#getCause()} to figure out the exact
 *             cause
 */
public synchronized void generate() throws ConversionException {

    PrintWriter outputWriter = new PrintWriter(output);

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(input);

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

        NodeList list = (NodeList) xpath.evaluate(
                "//channel/item[link and guid and postmeta[meta_key/text()='handle']]", doc,
                XPathConstants.NODESET);

        Boolean useGuid = useGuid();
        Boolean addDelete = addDelete();

        Map<String, String> vars = new HashMap<String, String>();
        vars.put(HandleVariables.prefix.toString(), prefix);

        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            String handle = xpath.evaluate("postmeta[meta_key/text()='handle']/meta_value/text()", node);
            if (filter() != null) {
                // We use a regex in the Node instead of a XPath filter in
                // the NodeList because Java only supports XPath 1 and the
                // "matches" function has been introduced in XPath 2
                Pattern pattern = Pattern.compile(filter());
                if (!pattern.matcher(handle).matches()) {
                    continue;
                }
            }
            vars.put(HandleVariables.handle.toString(), handle);
            vars.put(HandleVariables.url.toString(),
                    useGuid ? xpath.evaluate("guid/text()", node) : xpath.evaluate("link/text()", node));

            if (addDelete) {
                outputWriter.println(StrSubstitutor.replace(commands.get("command.delete"), vars));
            }
            outputWriter.println(StrSubstitutor.replace(commands.get("command.create"), vars));
            outputWriter.println(StrSubstitutor.replace(commands.get("command.admin"), vars));
            outputWriter.println(StrSubstitutor.replace(commands.get("command.url"), vars));
            outputWriter.println();
        }
    } catch (Exception e) {
        throw new ConversionException(e);
    } finally {
        outputWriter.flush();
    }
}

From source file:eu.interedition.collatex.cli.Engine.java

Engine configure(CommandLine commandLine)
        throws XPathExpressionException, ParseException, ScriptException, IOException {
    this.inputCharset = Charset.forName(commandLine.getOptionValue("ie", "UTF-8"));
    this.xmlMode = commandLine.hasOption("xml");
    this.tokenXPath = XPathFactory.newInstance().newXPath()
            .compile(commandLine.getOptionValue("xp", "//text()"));

    final String script = commandLine.getOptionValue("s");
    try {// w  ww . j av a2s .  co  m
        final PluginScript pluginScript = (script == null
                ? PluginScript.read("<internal>", new StringReader(""))
                : PluginScript.read(argumentToResource(script)));

        this.tokenizer = Objects.firstNonNull(pluginScript.tokenizer(), SimplePatternTokenizer.BY_WS_OR_PUNCT);
        this.normalizer = Objects.firstNonNull(pluginScript.normalizer(), SimpleTokenNormalizers.LC_TRIM_WS);
        this.comparator = Objects.firstNonNull(pluginScript.comparator(), new EqualityTokenComparator());
    } catch (IOException e) {
        throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage());
    }

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

    this.variantGraph = new JungVariantGraph();

    this.joined = !commandLine.hasOption("t");

    this.outputFormat = commandLine.getOptionValue("f", "json").toLowerCase();

    outputCharset = Charset.forName(commandLine.getOptionValue("oe", "UTF-8"));
    final String output = commandLine.getOptionValue("o", "-");
    if (!"-".equals(output)) {
        try {
            this.outFile = new File(output);
            this.out = new PrintWriter(Files.newWriter(this.outFile, outputCharset));
        } catch (FileNotFoundException e) {
            throw new ParseException("Output file '" + outFile + "' not found");
        }
    } else {
        this.out = new PrintWriter(new OutputStreamWriter(System.out, outputCharset));
    }

    final String[] witnessSpecs = commandLine.getArgs();
    this.inputResources = Lists.newArrayListWithExpectedSize(witnessSpecs.length);
    for (String witnessSpec : witnessSpecs) {
        inputResources.add(argumentToResource(witnessSpec));
    }
    if (inputResources.size() < 1) {
        throw new ParseException("No input resource(s) given");
    }

    return this;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.validation.BcrExperimentFieldValidator.java

/**
 * checks all tags in a file//from   www. j av  a 2 s.c o  m
 *  @param xmlFile to check for XSDElements
 */

private boolean checkXmlFile(final File xmlFile, final QcContext context, List<String> clinicalElementList)
        throws ProcessorException {
    NodeList nodes = null;
    try {
        final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
        final XPath xpath = XPathFactory.newInstance().newXPath();
        nodes = (NodeList) xpath.evaluate(PATIENT_XPATH, document, XPathConstants.NODESET);
    } catch (XPathException e) {
        throw new ProcessorException("Unable to evaluate " + PATIENT_XPATH + " expression ", e);
    } catch (Exception e) {
        // same handling no matter what is thrown by parser
        throw new ProcessorException("Unable to parse file: " + xmlFile.getName(), e);
    }

    if (nodes.getLength() == 0) {
        throw new ProcessorException("No patient node found in file " + xmlFile.getName());
    }
    if (nodes.getLength() > 1) {
        throw new ProcessorException("More than one patient node found in file " + xmlFile.getName());
    }

    return parse(nodes.item(0), context, clinicalElementList, xmlFile.getName());

}

From source file:com.dianping.zebra.shard.jdbc.base.MultiDBBaseTestCase.java

private List<DBDataEntry> parseDataFile() throws Exception {
    List<DBDataEntry> datas = new ArrayList<DBDataEntry>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document configDoc = builder/*  ww  w.  j  a v a 2  s .c  o  m*/
            .parse(MultiDBBaseTestCase.class.getClassLoader().getResourceAsStream(getDataFile()));
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    NodeList databaseList = (NodeList) xpath.compile("/dataset/database").evaluate(configDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < databaseList.getLength(); i++) {
        DBDataEntry entry = new DBDataEntry();
        Element ele = (Element) databaseList.item(i);
        entry.setDbName(ele.getAttribute("name"));
        NodeList scriptNodeList = ele.getChildNodes();
        List<String> scripts = new ArrayList<String>();
        for (int j = 0; j < scriptNodeList.getLength(); j++) {
            scripts.add(scriptNodeList.item(j).getTextContent());
        }
        entry.setScripts(scripts);
        datas.add(entry);
    }

    return datas;

}

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

public static Object xpath(Document document, String path, QName returnType)
        throws XPathExpressionException, TransformerException {
    XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new UniversalNamespaceResolver(document));
    return xPath.compile(path).evaluate(document, returnType);
}

From source file:br.gov.lexml.parser.documentoarticulado.LexMLParserFromText.java

@Override
public List<Element> getArtigos() {
    try {//from  ww  w.  j a  va2s  .c  om
        NodeList nodelist = (NodeList) XPathFactory.newInstance().newXPath().compile(XPATH_1ST_LEVEL_ARTIGOS)
                .evaluate(LexMLUtil.toDocument(getArticulacao()), XPathConstants.NODESET);
        List<Element> elementslist = new ArrayList<Element>();
        for (int i = 0; i < nodelist.getLength(); i++)
            if (!isAlteracao(nodelist.item(i)))
                elementslist.add((Element) nodelist.item(i));
        return elementslist;
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.jboss.seam.forge.shell.util.PluginUtil.java

public static File downloadPlugin(final PluginRef ref, final PipeOut out, final String targetPath)
        throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();

    String[] artifactParts = ref.getArtifact().split(":");

    if (artifactParts.length != 3) {
        throw new RuntimeException("malformed artifact identifier "
                + "(format should be: <maven.group>:<maven.artifact>:<maven.version>) encountered: "
                + ref.getArtifact());//from  ww w . j a  va2s.co m
    }

    String packageLocation = artifactParts[0].replaceAll("\\.", "/");
    String baseUrl;
    if (ref.getHomeRepo().endsWith("/")) {
        baseUrl = ref.getHomeRepo() + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    } else {
        baseUrl = ref.getHomeRepo() + "/" + packageLocation + "/" + artifactParts[1] + "/" + artifactParts[2];
    }

    HttpGet httpGetManifest = new HttpGet(baseUrl + "/maven-metadata.xml");
    out.print("Retrieving artifact manifest ... ");

    HttpResponse response = client.execute(httpGetManifest);
    switch (response.getStatusLine().getStatusCode()) {
    case 200:
        out.println("done.");

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getEntity().getContent());

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression checkSnapshotExpr = xpath.compile("//versioning/snapshot");
        XPathExpression findJar = xpath.compile("//snapshotVersion[extension='jar']/value");

        NodeList list = (NodeList) checkSnapshotExpr.evaluate(document, XPathConstants.NODESET);

        out.print("Reading manifest ... ");

        if (list.getLength() != 0) {

            Node n = (Node) findJar.evaluate(document, XPathConstants.NODE);

            if (n == null) {
                out.println("failed: could not determine where to find jar file.");
                return null;
            }

            String version = n.getFirstChild().getTextContent();

            // plugin definition points to a snapshot.
            out.println("good! (maven snapshot found): " + version);

            String fileName = artifactParts[1] + "-" + version + ".jar";

            HttpGet jarGet = new HttpGet(baseUrl + "/" + fileName);

            out.print("Downloading: " + baseUrl + "/" + fileName + " ... ");
            response = client.execute(jarGet);

            try {
                File file = saveFile(targetPath + "/" + fileName, response.getEntity().getContent());
                out.println("done.");
                return file;
            } catch (IOException e) {
                out.println("failed to download: " + e.getMessage());
                return null;
            }

            // do download of snapshot.
        } else {
            out.println("error! (maven snapshot not found)");
            return null;
        }

    case 404:
        String requestUrl = baseUrl + "/" + artifactParts[2] + ".pom";
        httpGetManifest = new HttpGet(requestUrl);
        response = client.execute(httpGetManifest);

        if (response.getStatusLine().getStatusCode() != 200) {
            printError(response.getStatusLine().getStatusCode(), requestUrl, out);
            return null;
        } else {

            // download regular POM here.

        }
        break;
    default:
        out.println("failed! (server returned status code: " + response.getStatusLine().getStatusCode());
        return null;
    }

    return null;

}

From source file:com.esri.gpt.catalog.search.SearchFilterSpatial.java

/**
 * Instantiates a new search filter spatial.
 *//*from w  ww  .j a v a 2s  .com*/
public SearchFilterSpatial() {
    super();
    reset();

    // Load a fioel with predefined extents (bookmarks)
    Document domFe;
    XPath xpathFe;
    try {
        String sPredefinedExtents = PREDEFINED_EXTENTS_FILE;
        LogUtil.getLogger().log(Level.FINE, "Loading Predefined extents file: {0}", sPredefinedExtents);
        domFe = DomUtil.makeDomFromResourcePath(sPredefinedExtents, false);
        xpathFe = XPathFactory.newInstance().newXPath();
    } catch (Exception e) {
        LogUtil.getLogger().log(Level.FINE, "No predefined extents file");
        domFe = null;
        xpathFe = null;
    }
    // predefined extent file root
    Node rootFe = null;
    try {
        if (domFe != null)
            rootFe = (Node) xpathFe.evaluate("/extents", domFe, XPathConstants.NODE);
    } catch (Exception e) {
        rootFe = null;
        LogUtil.getLogger().log(Level.FINE, "Xpath problem for predefined extents file");
    }
    /**
     * Reads Bookmarks and load an array
     */
    NodeList extents;
    ArrayList extentsList = new ArrayList();
    if (rootFe != null) {
        try {
            extents = (NodeList) xpathFe.evaluate("extent", rootFe, XPathConstants.NODESET);
            for (Node extent : new NodeListAdapter(extents)) {
                String extPlace = (String) xpathFe.evaluate("@place", extent, XPathConstants.STRING);
                String extValue = (String) xpathFe.evaluate("@ext", extent, XPathConstants.STRING);
                LogUtil.getLogger().log(Level.FINE, "Element added:" + extPlace + "," + extValue);
                SelectItem extElement = new SelectItem(extValue, extPlace);
                extentsList.add(extElement);
            }
        } catch (Exception e) {
            extentsList = null;
            LogUtil.getLogger().log(Level.FINE, "Xpath problem for predefined extents file");
        }
    } else
        extentsList = null;

    this._predefinedExtents = extentsList;
}