List of usage examples for javax.xml.xpath XPathFactory newInstance
public static XPathFactory newInstance()
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.
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
@Override public void OutputJaxpImplementationInfo() { logger.debug(getJaxpImplementationInfo("DocumentBuilderFactory", DocumentBuilderFactory.newInstance().getClass())); logger.debug(getJaxpImplementationInfo("XPathFactory", XPathFactory.newInstance().getClass())); logger.debug(getJaxpImplementationInfo("TransformerFactory", TransformerFactory.newInstance().getClass())); logger.debug(getJaxpImplementationInfo("SAXParserFactory", SAXParserFactory.newInstance().getClass())); }
From source file:de.dplatz.padersprinter.control.TripService.java
Optional<List<Leg>> parseLegs(Node node) { XPath xpath = XPathFactory.newInstance().newXPath(); try {/* w ww . j av a 2s . c o m*/ NodeList legNodes = (NodeList) xpath.evaluate(".//table[contains(@class, 'legTable')]", node, XPathConstants.NODESET); final List<Leg> legs = new LinkedList<>(); logger.debug("Number of legs indentified: " + legNodes.getLength()); for (int i = 0; i < legNodes.getLength(); i++) { Optional<Leg> leg = parseLeg(legNodes.item(i), xpath); if (!leg.isPresent()) { logger.info("At least one leg could not be parsed. Ignoring trip."); return Optional.empty(); } legs.add(leg.get()); } return Optional.of(legs); } catch (Exception ex) { logger.log(Level.ERROR, null, ex); return Optional.empty(); } }
From source file:com.orion.utility.XmlConfiguration.java
/** * Object constructor// w w w .j a va 2 s .com * * @author Mathias Van Malderen * @param config The configuration <tt>File</tt> * @param log Main logger reference * @throws ParserException If there is an error while initializing the parser **/ public XmlConfiguration(File config, Log log) throws ParserException { try { this.log = log; 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:de.ingrid.iplug.dscmapclient.index.producer.PlugDescriptionConfiguredWmsRecordSetProducer.java
/** * this private method does all the dirty work, read the file, parse it into * a document and find the desired ids, through the xpath expression * //from w w w .ja v a 2s. c o m * @param filePath * @param expression * @return NodeList */ private NodeList readXmlFile(String filePath, String expression) { XPath xPath = XPathFactory.newInstance().newXPath(); File fXmlFile = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); return (NodeList) xPath.evaluate(expression, doc, XPathConstants.NODESET); } catch (ParserConfigurationException e) { log.error("Error creating record ids.", e); e.printStackTrace(); } catch (SAXException e) { log.error("Error creating record ids.", e); e.printStackTrace(); } catch (IOException e) { log.error("Error creating record ids.", e); e.printStackTrace(); } catch (XPathExpressionException e) { log.error("Error creating record ids.", e); e.printStackTrace(); } return null; }
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;/*from ww 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:de.fzi.ALERT.actor.MessageObserver.ComplexEventObserver.JMSMessageParser.java
public Message XMLFileParse(String msgString) { Message message = new Message(); try {/* w ww . jav a 2s. co m*/ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.setErrorHandler(new MyErrorHandler()); InputStream in = new ByteArrayInputStream(msgString.getBytes("UTF-8")); org.w3c.dom.Document doc = builder.parse(in); XPath xpath = XPathFactory.newInstance().newXPath(); // XPath Query for showing all nodes value javax.xml.xpath.XPathExpression expr = xpath.compile("//patternID/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; Pattern pattern = new Pattern(); if (nodes.getLength() > 0) { pattern = patternDAO.findById(nodes.item(0).getNodeValue()); } if (pattern != null) { message.setPatternId(pattern); for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } javax.xml.xpath.XPathExpression expr1 = xpath.compile("//alertcomplex/*/text()"); Object result1 = expr1.evaluate(doc, XPathConstants.NODESET); NodeList nodes1 = (NodeList) result1; String content = ""; if (nodes.getLength() > 0) { for (int i = 0; i < nodes1.getLength(); i++) { System.out.println("modes " + nodes1.item(i).getParentNode().getNodeName()); System.out.println(nodes1.item(i).getNodeValue()); content += nodes1.item(i).getNodeValue(); } } message.setSubject("complex event"); message.setSummary("default summary"); message.setContent(content); message.setMsgDate(new Date()); message.setMsgID(1); } else { message.setContent("ERROR!"); } } catch (ParserConfigurationException e) { // TODO Auto-generated catch block message.setContent("ERROR!"); System.out.println(e.getMessage()); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block message.setContent("ERROR!"); System.out.println(e.getMessage()); } catch (SAXException e) { // TODO Auto-generated catch block message.setContent("ERROR!"); System.out.println(e.getMessage()); } catch (IOException e) { // TODO Auto-generated catch block message.setContent("ERROR!"); System.out.println(e.getMessage()); } catch (XPathExpressionException e) { // TODO Auto-generated catch block message.setContent("ERROR!"); System.out.println(e.getMessage()); } return message; }
From source file:com.mnxfst.testing.client.TSClientPlanResultCollectCallable.java
/** * TODO TEST!!!//from w w w . j a v a 2 s .c o m * @see java.util.concurrent.Callable#call() */ public TSClientPlanExecutionResult call() throws Exception { InputStream ptestServerInputStream = null; try { HttpResponse response = httpClient.execute(httpHost, getMethod); ptestServerInputStream = response.getEntity().getContent(); XPath xpath = XPathFactory.newInstance().newXPath(); Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(ptestServerInputStream); if (response == null) throw new TSClientExecutionException( "No response document received from " + httpHost.getHostName()); // fetch root node Node rootNode = responseDoc.getFirstChild(); if (rootNode == null) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); if (rootNode.getNodeName() == null || !rootNode.getNodeName().equalsIgnoreCase(TEST_EXEC_RESPONSE_ROOT)) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); int responseCode = parseIntValue(rootNode, TEST_EXEC_RESPONSE_CODE, xpath); String resultIdentifier = parseStringValue(rootNode, TEST_EXEC_RESULT_IDENTIFIER, xpath); switch (responseCode) { case RESPONSE_CODE_EXECUTION_RESULTS_PENDING: { TSClientPlanExecutionResult planExecutionResult = new TSClientPlanExecutionResult(); planExecutionResult.setResponseCode(RESPONSE_CODE_EXECUTION_RESULTS_PENDING); planExecutionResult.setResultIdentifier(resultIdentifier); planExecutionResult.setHostName(httpHost.getHostName()); planExecutionResult.setPort(httpHost.getPort()); return planExecutionResult; } case RESPONSE_CODE_EXECUTION_RESULTS_CONTAINED: { long averageDuration = parseLongValue(rootNode, TEST_EXEC_AVERAGE_DURATION, xpath); double averageDurationMedian = parseDoubleValue(rootNode, TEST_EXEC_AVERAGE_MEDIAN, xpath); long endTimestamp = parseLongValue(rootNode, TEST_EXEC_END, xpath); long startTimestamp = parseLongValue(rootNode, TEST_EXEC_START, xpath); int errors = parseIntValue(rootNode, TEST_EXEC_ERRORS, xpath); String executionEnvironmentId = parseStringValue(rootNode, TEST_EXEC_ENVIRONMENT, xpath); long singleAverageDuration = parseLongValue(rootNode, TEST_EXEC_SINGLE_AVERAGE_DURATION, xpath); long singleMaxDuration = parseLongValue(rootNode, TEST_EXEC_SINGLE_MAX_DURATION, xpath); long singleMinDuration = parseLongValue(rootNode, TEST_EXEC_SINGLE_MIN_DURATION, xpath); String testPlan = parseStringValue(rootNode, TEST_EXEC_TEST_PLAN, xpath); TSClientPlanExecutionResult planExecutionResult = new TSClientPlanExecutionResult(); planExecutionResult.setResponseCode(RESPONSE_CODE_EXECUTION_RESULTS_PENDING); planExecutionResult.setResultIdentifier(resultIdentifier); planExecutionResult.setHostName(httpHost.getHostName()); planExecutionResult.setPort(httpHost.getPort()); planExecutionResult.setAverageDuration(averageDuration); planExecutionResult.setAverageDurationMedian(averageDurationMedian); planExecutionResult.setEndTimestamp(endTimestamp); planExecutionResult.setErrors(errors); planExecutionResult.setExecutionEnvironmentId(executionEnvironmentId); planExecutionResult.setSingleAverageDuration(singleAverageDuration); planExecutionResult.setSingleMaxDuration(singleMaxDuration); planExecutionResult.setSingleMinDuration(singleMinDuration); planExecutionResult.setStartTimestamp(startTimestamp); planExecutionResult.setTestPlan(testPlan); return planExecutionResult; } default: { throw new TSClientExecutionException("Unexpected response code '" + responseCode + "' received from " + httpHost.getHostName() + ":" + httpHost.getPort()); } } } catch (ClientProtocolException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + getMethod.getURI() + ". Error: " + e.getMessage()); } catch (IOException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + getMethod.getURI() + ". Error: " + e.getMessage()); } finally { if (ptestServerInputStream != null) { try { ptestServerInputStream.close(); httpClient.getConnectionManager().shutdown(); } catch (Exception e) { System.out.println("Failed to close ptest-server connection"); } } } }
From source file:com.microsoft.windowsazure.exception.ServiceException.java
public static ServiceException createFromXml(final HttpRequest httpRequest, final String requestContent, final HttpResponse httpResponse, final HttpEntity entity) { String content;// w w w . ja v a2 s . c om try { content = EntityUtils.toString(entity); } catch (IOException e) { return new ServiceException(e); } ServiceException serviceException; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder .parse(new BOMInputStream(new ByteArrayInputStream(content.getBytes()))); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); String code = xpath.compile("/Error/Code/text()").evaluate(responseDoc); String message = xpath.compile("/Error/Message/text()").evaluate(responseDoc); serviceException = new ServiceException(buildExceptionMessage(code, message, content, httpResponse)); serviceException.getError().setCode(code); serviceException.getError().setMessage(message); } catch (XPathExpressionException e) { return new ServiceException(content); } catch (ParserConfigurationException e) { return new ServiceException(content); } catch (SAXException e) { return new ServiceException(content); } catch (IOException e) { return new ServiceException(content); } serviceException.setHttpStatusCode(httpResponse.getStatusLine().getStatusCode()); serviceException.setHttpReasonPhrase(httpResponse.getStatusLine().getReasonPhrase()); return serviceException; }
From source file:org.opencastproject.remotetest.server.perf.ConcurrentWorkflowTest.java
protected String getWorkflowInstanceId(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);/*ww w .j a v a 2 s.c o m*/ DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8")); return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE)) .getAttribute("id"); }
From source file:ch.entwine.weblounge.common.impl.util.xml.XPathHelper.java
/** * Returns the query result as a <code>Node</code> or <code>null</code> if the * xpath expression doesn't yield a resulting node. * <p>/* w w w. j av a 2 s . c o m*/ * <b>Note:</b> This signature creates a new <code>XPath</code> processor on * every call, which is probably fine for testing but not favorable when it * comes to production use, since creating an <code>XPath</code> processor is * resource intensive. * * @param node * the context node * @param xpathExpression * the xpath expression * @return the selected node */ public static Node select(Node node, String xpathExpression) { XPath xpath = XPathFactory.newInstance().newXPath(); return select(node, xpathExpression, xpath); }