List of usage examples for javax.xml.xpath XPathConstants NODE
QName NODE
To view the source code for javax.xml.xpath XPathConstants NODE.
Click Source Link
The XPath 1.0 NodeSet data type.
From source file:org.openengsb.openengsbplugin.Eclipse.java
private File writeCheckstyleEclipseConfigAndSetCheckerConfigPath() throws MojoExecutionException { try {//from w w w. j av a2 s . com String checkstyleEclipseConfigContent = IOUtils.toString( LicenseMojo.class.getClassLoader().getResourceAsStream(CHECKSTYLE_ECLIPSE_CONFIG_PATH)); Document configDocument = Tools.parseXMLFromString(checkstyleEclipseConfigContent, false); tryExtractLicenseHeader(configDocument); Node node = Tools.evaluateXPath("/fileset-config/local-check-config", configDocument, null, XPathConstants.NODE, Node.class); LOG.trace(String.format("Found node: %s, # of attributes: %d", node, node.getAttributes().getLength())); node.getAttributes().getNamedItem("location").setTextContent(checkstyleCheckerConfig.getAbsolutePath()); checkstyleEclipseConfigContent = Tools.serializeXML(configDocument); checkstyleEclipseConfigContent = addHeader(checkstyleEclipseConfigContent); return Tools.generateTmpFile(checkstyleEclipseConfigContent, ".xml"); } catch (Exception e) { throw new MojoExecutionException("Couldn't create checkstyle checker config file!", e); } }
From source file:org.openengsb.openengsbplugin.tools.Tools.java
/** * Insert dom node into {@code parentDoc} at the given {@code xpath} (if this path doesnt exist, the elements are * created). Note: text content of nodes and attributes aren't considered. *///from www .j a va2 s. c om public static void insertDomNode(Document parentDoc, Node nodeToInsert, String xpath, NamespaceContext nsContext) throws XPathExpressionException { LOG.trace("insertDomNode() - start"); String[] tokens = xpath.split("/"); String currPath = ""; Node parent = null; for (int i = 0; i < tokens.length; i++) { if (tokens[i].matches("[\\s]*")) { continue; } LOG.trace(String.format("parent = %s", parent == null ? "null" : parent.getLocalName())); currPath += "/" + tokens[i]; Node result = Tools.evaluateXPath(currPath, parentDoc, nsContext, XPathConstants.NODE, Node.class); LOG.trace(String.format("result empty: %s", result == null)); if (result == null) { String elemName = null; // attribute filter elemName = tokens[i].replaceAll("\\[.*\\]", ""); Element element = null; if (elemName.contains(":")) { String[] elemenNameTokens = elemName.split(":"); String prefix = elemenNameTokens[0]; elemName = elemenNameTokens[1]; element = parentDoc.createElementNS(nsContext.getNamespaceURI(prefix), elemName); } else { element = parentDoc.createElement(elemName); } LOG.trace(String.format("elementName: %s", elemName)); parent.appendChild(element); result = element; } parent = result; } LOG.trace("finally inserting the node.."); LOG.trace(String.format("parent node: %s", parent == null ? "null" : parent.getLocalName())); LOG.trace( String.format("node to insert = %s", nodeToInsert == null ? "null" : nodeToInsert.getLocalName())); parent.appendChild(nodeToInsert); LOG.trace("insertDomNode() - end"); }
From source file:org.openengsb.openengsbplugin.tools.Tools.java
/** * Remove node with given {@code xpath} from {@code targetDocument}. When {@code removeParent} is set to * {@code true} the parent node will also be removed if the removed node was the only child. The method returns * {@code true} if the node specified by {@code xpath} has been found and successfully removed from its parent node. *///from ww w. j a v a2s . c o m public static boolean removeNode(String xpath, Document targetDocument, NamespaceContext nsContext, boolean removeParent) throws XPathExpressionException { Node nodeToRemove = evaluateXPath(xpath, targetDocument, nsContext, XPathConstants.NODE, Node.class); if (nodeToRemove == null) { return false; } Node parent = nodeToRemove.getParentNode(); if (parent == null) { return false; } parent.removeChild(nodeToRemove); if (removeParent && parent.getChildNodes().getLength() == 0) { Node parentParent = parent.getParentNode(); if (parentParent != null) { parentParent.removeChild(parent); } } return true; }
From source file:org.openengsb.openengsbplugin.tools.ToolsTest.java
@Test public void testXPath() throws Exception { Document doc = Tools.parseXMLFromString( IOUtils.toString(ClassLoader.getSystemResourceAsStream(LICENSECHECK_CONFIG_PATH))); Node n = Tools.evaluateXPath("//c:config", doc, NS_CONTEXT, XPathConstants.NODE, Node.class); assertEquals("config", n.getLocalName()); }
From source file:org.openengsb.openengsbplugin.tools.ToolsTest.java
@Test public void testInsertDomNode() throws Exception { Document thePom = Tools.parseXMLFromString( IOUtils.toString(ClassLoader.getSystemResourceAsStream("licenseCheck/pass/pom.xml"))); Document d = Tools.newDOM();//from ww w . ja v a 2 s .c o m Node nodeB = d.createElementNS(POM_NS_URI, "b"); Node importedNode = thePom.importNode(nodeB, true); Tools.insertDomNode(thePom, importedNode, "/pom:project/pom:a", NS_CONTEXT); String serializedXml = Tools.serializeXML(thePom); File generatedFile = Tools.generateTmpFile(serializedXml, ".xml"); Document generatedPom = Tools.parseXMLFromString(FileUtils.readFileToString(generatedFile)); Node foundNode = Tools.evaluateXPath("/pom:project/pom:a/pom:b", generatedPom, NS_CONTEXT, XPathConstants.NODE, Node.class); assertNotNull(foundNode); assertTrue(generatedFile.delete()); }
From source file:org.openengsb.openengsbplugin.tools.ToolsTest.java
@Test public void testRemoveNode() throws Exception { Document doc = Tools/* w ww . ja v a 2 s. c om*/ .parseXMLFromString(IOUtils.toString(ClassLoader.getSystemResourceAsStream("removeNode/pom.xml"))); String xpath = "/pom:project/pom:properties"; assertNotNull(Tools.evaluateXPath(xpath, doc, NS_CONTEXT, XPathConstants.NODE, Node.class)); Tools.removeNode("/pom:project/pom:properties", doc, NS_CONTEXT, false); assertNull(Tools.evaluateXPath(xpath, doc, NS_CONTEXT, XPathConstants.NODE, Node.class)); }
From source file:org.opennms.protocols.xml.collector.AbstractXmlCollectionHandler.java
/** * Gets the resource name.//from ww w .ja va 2 s. c o m * * @param xpath the Xpath * @param group the group * @param resource the resource * @return the resource name * @throws XPathExpressionException the x path expression exception */ private String getResourceName(XPath xpath, XmlGroup group, Node resource) throws XPathExpressionException { // Processing multiple-key resource name. if (group.hasMultipleResourceKey()) { List<String> keys = new ArrayList<String>(); for (String key : group.getXmlResourceKey().getKeyXpathList()) { LOG.debug("getResourceName: getting key for resource's name using {}", key); Node keyNode = (Node) xpath.evaluate(key, resource, XPathConstants.NODE); keys.add(keyNode.getNodeValue() == null ? keyNode.getTextContent() : keyNode.getNodeValue()); } return StringUtils.join(keys, "_"); } // If key-xpath doesn't exist or not found, a node resource will be assumed. if (group.getKeyXpath() == null) { LOG.debug("getResourceName: assuming node level resource"); return "node"; // CollectionResource.RESOURCE_TYPE_NODE } // Processing single-key resource name. LOG.debug("getResourceName: getting key for resource's name using {}", group.getKeyXpath()); Node keyNode = (Node) xpath.evaluate(group.getKeyXpath(), resource, XPathConstants.NODE); return keyNode.getNodeValue() == null ? keyNode.getTextContent() : keyNode.getNodeValue(); }
From source file:org.opennms.protocols.xml.collector.AbstractXmlCollectionHandler.java
/** * Gets the time stamp./*from w w w . j a v a 2s. c o m*/ * * @param doc the doc * @param xpath the xpath * @param group the group * @return the time stamp * @throws XPathExpressionException the x path expression exception */ protected Date getTimeStamp(Document doc, XPath xpath, XmlGroup group) throws XPathExpressionException { if (group.getTimestampXpath() == null) { return null; } String pattern = group.getTimestampFormat() == null ? "yyyy-MM-dd HH:mm:ss" : group.getTimestampFormat(); LOG.debug( "getTimeStamp: retrieving custom timestamp to be used when updating RRDs using XPATH {} and pattern {}", group.getTimestampXpath(), pattern); Node tsNode = (Node) xpath.evaluate(group.getTimestampXpath(), doc, XPathConstants.NODE); if (tsNode == null) { LOG.warn("getTimeStamp: can't find the custom timestamp using XPATH {}", group.getTimestampXpath()); return null; } Date date = null; String value = tsNode.getNodeValue() == null ? tsNode.getTextContent() : tsNode.getNodeValue(); LOG.debug("getTimeStamp: time stamp value is {}", value); try { DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern); DateTime dateTime = dtf.parseDateTime(value); date = dateTime.toDate(); } catch (Exception e) { LOG.warn("getTimeStamp: can't convert custom timetime {} using pattern {}", value, pattern); } return date; }
From source file:org.opennms.upgrade.implementations.JettyConfigMigratorOfflineTest.java
/** * Verify./*from w w w . j a va 2 s . c o m*/ * * @param sslStatus the SSL status * @param ajpStatus the AJP status * @throws Exception the exception */ private void verify(boolean sslStatus, boolean ajpStatus) throws Exception { factory.setIgnoringComments(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File("target/home/etc/jetty.xml")); Node sslNode = (Node) xpath.evaluate( "/Configure/Call/Arg/New[@class='org.eclipse.jetty.server.ssl.SslSelectChannelConnector']", doc, XPathConstants.NODE); if (sslStatus) { Assert.assertNotNull(sslNode); } else { Assert.assertNull(sslNode); } Node ajpNode = (Node) xpath.evaluate( "/Configure/Call/Arg/New[@class='org.eclipse.jetty.ajp.Ajp13SocketConnector']", doc, XPathConstants.NODE); if (ajpStatus) { Assert.assertNotNull(ajpNode); } else { Assert.assertNull(ajpNode); } }
From source file:org.opentox.jaqpot3.qsar.util.PMMLProcess.java
private static String getNodeFromXML(String xml) throws JaqpotException { String res = ""; try {//from w w w . ja v a 2s . c om DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes()); Document doc = docBuilder.parse(bis); // XPath to retrieve the content of the <FamilyAnnualDeductibleAmount> tag XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/PMML/TransformationDictionary"; Node node = (Node) xpath.compile(expression).evaluate(doc, XPathConstants.NODE); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), xmlOutput); res = xmlOutput.getWriter().toString(); } catch (Exception ex) { String message = "Unexpected exception was caught while generating" + " the PMML representaition of a trained model."; logger.error(message, ex); throw new JaqpotException(message, ex); } return res; }