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.streak.logging.utils.AnalysisUtility.java

public static void fetchCloudStorageUris(String bucketName, String startKey, String endKey,
        HttpRequestFactory requestFactory, List<String> urisToProcess, boolean readSchemas) throws IOException {
    String bucketUri = "http://commondatastorage.googleapis.com/" + bucketName;
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(bucketUri + "?marker=" + startKey));
    HttpResponse response = request.execute();

    try {/*from w ww  . jav a  2 s  . c o  m*/
        Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(response.getContent());
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xPath.evaluate("//Contents/Key/text()", responseDoc,
                XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            String key = nodes.item(i).getNodeValue();
            if (key.compareTo(endKey) >= 0) {
                break;
            }
            if (key.endsWith(".schema") ^ readSchemas) {
                continue;
            }
            if (readSchemas) {
                key = key.substring(0, key.length() - ".schema".length());
            }
            urisToProcess.add("gs://" + bucketName + "/" + key);
        }
    } catch (SAXException e) {
        throw new IOException("Error parsing cloud storage response", e);
    } catch (ParserConfigurationException e) {
        throw new IOException("Error configuring cloud storage parser", e);
    } catch (XPathExpressionException e) {
        throw new IOException("Error finding keys", e);
    }
}

From source file:com.orion.utility.XmlConfiguration.java

/**
 * Object constructor/* w w  w .ja v a2  s  .  co  m*/
 * 
 * @author Mathias Van Malderen
 * @param  config The configuration <tt>File</tt>
 * @throws ParserException If there is an error while initializing the parser
 **/
public XmlConfiguration(File config) throws ParserException {

    try {

        this.builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        this.xpath = XPathFactory.newInstance().newXPath();
        this.document = this.builder.parse(config);

    } catch (IOException | SAXException | ParserConfigurationException e) {
        // Rethrowing our custom exception
        throw new ParserException(
                "Unable to initialize XML configuration parser [ path : " + config.getAbsolutePath() + " ]", e);
    }

}

From source file:XPathTest.java

public XPathFrame() {
        setTitle("XPathTest");

        JMenu fileMenu = new JMenu("File");
        JMenuItem openItem = new JMenuItem("Open");
        openItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                openFile();//w  w  w  .  jav a  2  s  .  co  m
            }
        });
        fileMenu.add(openItem);

        JMenuItem exitItem = new JMenuItem("Exit");
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }
        });
        fileMenu.add(exitItem);

        JMenuBar menuBar = new JMenuBar();
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);

        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                evaluate();
            }
        };
        expression = new JTextField(20);
        expression.addActionListener(listener);
        JButton evaluateButton = new JButton("Evaluate");
        evaluateButton.addActionListener(listener);

        typeCombo = new JComboBox(new Object[] { "STRING", "NODE", "NODESET", "NUMBER", "BOOLEAN" });
        typeCombo.setSelectedItem("STRING");

        JPanel panel = new JPanel();
        panel.add(expression);
        panel.add(typeCombo);
        panel.add(evaluateButton);
        docText = new JTextArea(10, 40);
        result = new JTextField();
        result.setBorder(new TitledBorder("Result"));

        add(panel, BorderLayout.NORTH);
        add(new JScrollPane(docText), BorderLayout.CENTER);
        add(result, BorderLayout.SOUTH);

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            JOptionPane.showMessageDialog(this, e);
        }

        XPathFactory xpfactory = XPathFactory.newInstance();
        path = xpfactory.newXPath();
        pack();
    }

From source file:org.jasig.springframework.security.portlet.authentication.PortletXmlMappableAttributesRetriever.java

/**
 * Loads the portlet.xml file using the configured <tt>ResourceLoader</tt> and
 * parses the role-name elements from it, using these as the set of <tt>mappableAttributes</tt>.
 *///from   w w  w  . j  a v a  2 s.c  o m
public void afterPropertiesSet() throws Exception {
    Resource portletXml = resourceLoader.getResource("/WEB-INF/portlet.xml");
    Document doc = getDocument(portletXml.getInputStream());

    final XPathExpression roleNamesExpression;
    if (portletConfig == null) {
        final XPathFactory xPathFactory = XPathFactory.newInstance();

        final XPath xPath = xPathFactory.newXPath();
        roleNamesExpression = xPath.compile("/portlet-app/portlet/security-role-ref/role-name");
    } else {
        final XPathFactory xPathFactory = XPathFactory.newInstance();
        xPathFactory.setXPathVariableResolver(new XPathVariableResolver() {
            @Override
            public Object resolveVariable(QName variableName) {
                if ("portletName".equals(variableName.getLocalPart())) {
                    return portletConfig.getPortletName();
                }

                return null;
            }
        });
        final XPath xPath = xPathFactory.newXPath();
        roleNamesExpression = xPath
                .compile("/portlet-app/portlet[portlet-name=$portletName]/security-role-ref/role-name");
    }

    final NodeList securityRoles = (NodeList) roleNamesExpression.evaluate(doc, XPathConstants.NODESET);
    final Set<String> roleNames = new HashSet<String>();

    for (int i = 0; i < securityRoles.getLength(); i++) {
        Element secRoleElt = (Element) securityRoles.item(i);
        String roleName = secRoleElt.getTextContent().trim();
        roleNames.add(roleName);
        logger.info("Retrieved role-name '" + roleName + "' from portlet.xml");
    }

    if (roleNames.isEmpty()) {
        logger.info("No security-role-ref elements found in " + portletXml
                + (portletConfig == null ? "" : " for portlet " + portletConfig.getPortletName()));
    }

    mappableAttributes = Collections.unmodifiableSet(roleNames);
}

From source file:com.esri.geoportal.harvester.migration.MigrationDataBuilder.java

private URI createBrokerUri(MigrationData data) throws URISyntaxException {
    MigrationHarvestSite site = data.siteuuid != null ? sites.get(data.siteuuid) : null;
    if (site != null) {
        String type = StringUtils.trimToEmpty(site.type).toUpperCase();
        switch (type) {
        case "WAF":
            return new URI("WAF", escapeUri(site.host), null);
        case "CKAN":
            return new URI("CKAN", escapeUri(site.host), null);
        case "ARCGIS": {
            int rsIdx = site.host.toLowerCase().indexOf("/rest/services");
            String host = rsIdx >= 0 ? site.host.substring(0, rsIdx) : site.host;
            return new URI("AGS", escapeUri(host), null);
        }//from www.j a  va  2 s  .c  o m
        case "CSW":
            try {
                Document doc = strToDom(site.protocol);
                XPath xPath = XPathFactory.newInstance().newXPath();
                String protocolId = (String) xPath.evaluate("/protocol[@type='CSW']/profile", doc,
                        XPathConstants.STRING);
                URL host = new URL(site.host);
                host = new URL(host.getProtocol(), host.getHost(), host.getPort(), host.getPath());
                return new URI("CSW", host.toExternalForm(), protocolId);
            } catch (Exception ex) {
            }
        }
    }
    return brokerUri;
}

From source file:com.greglturnquist.springagram.fileservice.s3.FileService.java

/**
 * Parse the {@link AmazonS3Exception} error result to capture the endpoint for
 * redirection./* w  w w .  j  av  a 2 s. c o  m*/
 *
 * @param e
 */
private void updateEndpoint(AmazonS3Exception e) {

    try {
        Document errorResponseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new StringInputStream(e.getErrorResponseXml()));

        XPathExpression endpointXpathExtr = XPathFactory.newInstance().newXPath().compile("/Error/Endpoint");

        this.s3Client.setEndpoint(endpointXpathExtr.evaluate(errorResponseDoc));
    } catch (Exception ex) {
        throw new RuntimeException(e);
    }
}

From source file:com.tranek.chivalryserverbrowser.XMLData2.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
 *///w  ww  . j  a va2  s. c  o  m
public XMLData2 getXPath(String path) {
    if (xpath == null) {
        xpath = XPathFactory.newInstance().newXPath();
    }

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

From source file:org.ambraproject.search.service.DummySOLRMessageSender.java

private Node XPathSingleNodeQuery(Document dom, String statement) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile(statement);

    return (Node) expr.evaluate(dom, XPathConstants.NODE);
}

From source file:org.openmrs.module.dhisreport.api.dxf2.DataValueSetTest.java

protected String xpathTest(String xpathString, String xml) throws XPathExpressionException {
    InputSource source = new InputSource(new StringReader(xml));
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new Dxf2NamespaceResolver());

    return (String) xpath.evaluate(xpathString, source);
}

From source file:edu.lternet.pasta.common.EmlUtility.java

/**
 * Returns the packageId of the provided EML document without parsing it
 * (the packageId). If the document does not contain the attribute
 * {@code //@packageId}, or if it does not have a value, an empty string
 * is returned./*  w ww  .  j av  a  2  s .  c  om*/
 *
 * @param emlDocument
 *            an EML document.
 *
 * @return the packageId contained in the provided EML document.
 */
public static String getRawEmlPackageId(Document emlDocument) {

    try {

        XPath xpath = XPathFactory.newInstance().newXPath();
        return xpath.evaluate("//@packageId", emlDocument);

    } catch (XPathExpressionException e) {
        throw new IllegalStateException(e); // Should never be reached
    }

}