Example usage for javax.xml.xpath XPathFactory newXPath

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

Introduction

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

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Return the list of children of the node selected by the xPath.
 * //from w  w w .  j  a va  2  s. co  m
 * @param node The node.
 * @param xpathExpression The xPath.
 * @return The list of children of the node selected by the xPath.
 * @throws TransformerException If anything fails.
 */
public static NodeList selectNodeList(final Node node, final String xpathExpression)
        throws TransformerException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    try {
        return (NodeList) xPath.evaluate(xpathExpression, node, XPathConstants.NODESET);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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.
 * //from w w w. j  av  a 2 s .  co  m
 * @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 ww  w .  j a  va2s . co 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: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();//from   www.j a v a2s .  c om
            }
        });
        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:it.isti.cnr.hpc.europeana.hackthon.domain.DbpediaMapper.java

private boolean load(String query) throws EntityException, NoResultException {

    boolean success = true;

    label = "";//from ww  w.  ja va  2s . c  om
    description = "";
    String queryUrl = produceQueryUrl(query);

    try {
        Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(queryUrl);

        if (response != null) {

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

            NodeList nodes = (NodeList) xPath.evaluate("/ArrayOfResult/Result", response,
                    XPathConstants.NODESET);

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

                // WE TAKE THE FIRST ENTITY FROM DBPEDIA
                label = ((String) xPath.evaluate("Label", nodes.item(0), XPathConstants.STRING));

                description = ((String) xPath.evaluate("Description", nodes.item(0), XPathConstants.STRING))
                        .toLowerCase();

                NodeList classesList = (NodeList) xPath.evaluate("Classes/Class", nodes.item(0),
                        XPathConstants.NODESET);

                classes = new ArrayList<String>(classesList.getLength());
                for (int i = 0; i < classesList.getLength(); i++) {
                    Node n = classesList.item(i);
                    String clazz = (String) xPath.evaluate("Label", n, XPathConstants.STRING);
                    classes.add(clazz);
                }
            }
            if (label.isEmpty()) {
                success = false;
                label = query;
            }

        }
    } catch (Exception e) {
        logger.error("Error during the mapping of the query " + query + " on dbPedia (" + e.toString() + ")");

        if (e.toString().contains("sorry")) {
            try {
                Thread.sleep(60000 * 5);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        success = false;

    } catch (Error e) {
        logger.error("Error during the mapping of the query " + query + " on dbPedia (" + e.toString() + ")");
        if (e.toString().contains("sorry")) {
            try {
                Thread.sleep(60000 * 5);
            } catch (InterruptedException e1) {
                throw new EntityException("Error during the mapping of the query " + query + " on dbPedia ("
                        + e.toString() + ")");
            }
        }
        success = false;

    }

    if (!success) {
        throw new NoResultException("mapping to dbpedia failed for query " + query);
    }
    return success;
}

From source file:com.oracle.tutorial.jdbc.RSSFeedsTable.java

public void addRSSFeed(String fileName) throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, TransformerConfigurationException, TransformerException, SQLException {
    // Parse the document and retrieve the name of the RSS feed

    String titleString = null;/*w w  w.ja  v a 2 s.co  m*/

    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    Node titleElement = (Node) xPath.evaluate("/rss/channel/title[1]", doc, XPathConstants.NODE);

    if (titleElement == null) {
        System.out.println("Unable to retrieve title element");
        return;
    } else {
        titleString = titleElement.getTextContent().trim().toLowerCase().replaceAll("\\s+", "_");
        System.out.println("title element: [" + titleString + "]");
    }

    System.out.println(JDBCTutorialUtilities.convertDocumentToString(doc));

    PreparedStatement insertRow = null;
    SQLXML rssData = null;

    System.out.println("Current DBMS: " + this.dbms);

    try {
        if (this.dbms.equals("mysql")) {
            // For databases that support the SQLXML data type, this creates a
            // SQLXML object from org.w3c.dom.Document.

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values" + " (?, ?)";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);

            System.out.println("Creating SQLXML object with MySQL");
            rssData = con.createSQLXML();
            System.out.println("Creating DOMResult object");
            DOMResult dom = (DOMResult) rssData.setResult(DOMResult.class);
            dom.setNode(doc);

            insertRow.setSQLXML(2, rssData);
            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

        else if (this.dbms.equals("derby")) {

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values"
                    + " (?, xmlparse(document cast (? as clob) preserve whitespace))";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);
            String convertedDoc = JDBCTutorialUtilities.convertDocumentToString(doc);
            insertRow.setClob(2, new StringReader(convertedDoc));

            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } catch (Exception ex) {
        System.out.println("Another exception caught:");
        ex.printStackTrace();
    }

    finally {
        if (insertRow != null) {
            insertRow.close();
        }
    }
}

From source file:org.ala.harvester.WikipediaImageHarvester.java

private String getSingleXPathValue(Document currentResDom, String xpathAsString) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    return (String) xpath.evaluate(xpathAsString, currentResDom, XPathConstants.STRING);
}

From source file:pl.psnc.synat.wrdz.mdz.format.FileFormatVerifierBean.java

/**
 * Returns the nodes from the given xml document that match the given xpath expression.
 * //w  w  w  . ja  v  a2s. com
 * @param document
 *            xml document to search
 * @param path
 *            xpath expression
 * @return matching nodes
 */
private NodeList xpath(Document document, String path) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new NamespaceContextImpl(NS_PREFIX, NS_URI));

    try {
        return (NodeList) xpath.evaluate(path, document, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Incorrect XPath expression", e);
    }
}

From source file:org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerConnection.java

protected String checkXPath(String xPathQuery) throws ManifoldCFException {
    try {/*from   w  w w  .ja va2s.c o  m*/
        readXmlResponse();
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression xPathExpr = xpath.compile(xPathQuery);
        return xPathExpr.evaluate(xmlResponse);
    } catch (XPathExpressionException e) {
        throw new ManifoldCFException(e);
    }
}

From source file:org.ala.harvester.WikipediaImageHarvester.java

protected List<String> getXPathValues(Document document, String xpathAsString) throws Exception {

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

    List<String> extractedValues = new ArrayList<String>();
    NodeList nodes = (NodeList) xpath.evaluate(xpathAsString, document, XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        String value = (nodes.item(i)).getNodeValue().trim();
        value = StringUtils.trimToNull(value);
        if (value != null) {
            extractedValues.add(value);//from   ww  w  . ja  va2 s .  com
        }
    }
    return extractedValues;
}