Java Code Examples for javax.xml.xpath.XPath

The following examples show how to use javax.xml.xpath.XPath. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: PdfBox-Android   Source File: FDFAnnotationPolygon.java    License: Apache License 2.0 6 votes vote down vote up
private void initVertices(Element element) throws IOException, NumberFormatException
{
    XPath xpath = XPathFactory.newInstance().newXPath();
    try
    {
        String vertices = xpath.evaluate("vertices", element);
        if (vertices == null || vertices.isEmpty())
        {
            throw new IOException("Error: missing element 'vertices'");
        }
        String[] verticesValues = vertices.split(",");
        float[] values = new float[verticesValues.length];
        for (int i = 0; i < verticesValues.length; i++)
        {
            values[i] = Float.parseFloat(verticesValues[i]);
        }
        setVertices(values);
    }
    catch (XPathExpressionException e)
    {
        Log.d("PdfBox-Android", "Error while evaluating XPath expression for polygon vertices");
    }
}
 
Example 2
Source Project: SAMLRaider   Source File: XMLHelpers.java    License: MIT License 6 votes vote down vote up
/**
 * Removes empty tags, spaces between XML tags
 *
 * @param document
 *            document in which the empty tags should be removed
 */
public void removeEmptyTags(Document document) {
	NodeList nl = null;
	try {
		if(Thread.currentThread().getContextClassLoader() == null){
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); 
		}
		XPath xPath = XPathFactory.newInstance().newXPath();
		nl = (NodeList) xPath.evaluate("//text()[normalize-space(.)='']", document, XPathConstants.NODESET);
		
		for (int i = 0; i < nl.getLength(); ++i) {
			Node node = nl.item(i);
			node.getParentNode().removeChild(node);
		}
		
	} catch (XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
Example 3
public List getRuleExtensionValues() {
    List extensionValues = new ArrayList();

    XPath xpath = XPathHelper.newXPath();
    try {
        NodeList nodes = getFields(xpath, getConfigXML(), new String[] { "ALL", "RULE" });
        for (int i = 0; i < nodes.getLength(); i++) {
            Node field = nodes.item(i);
            NamedNodeMap fieldAttributes = field.getAttributes();
            String fieldName = fieldAttributes.getNamedItem("name").getNodeValue();
            Map map = getParamMap();
            if (map != null && !org.apache.commons.lang.StringUtils.isEmpty((String) map.get(fieldName))) {
                RuleExtensionValue value = new RuleExtensionValue();
                value.setKey(fieldName);
                value.setValue((String) map.get(fieldName));
                extensionValues.add(value);
            }
        }
    } catch (XPathExpressionException e) {
        LOG.error("error in getRuleExtensionValues ", e);
        throw new RuntimeException("Error trying to find xml content with xpath expression", e);
    }
    return extensionValues;
}
 
Example 4
Source Project: proarc   Source File: MetsUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * Returns a node from the xml document defined by the Xpath
 *
 * @param elements
 * @param xPath
 * @return
 */
public static Node xPathEvaluateNode(List<Element> elements, String xPath) throws MetsExportException {
    Document document = null;
    try {
        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new MetsExportException("Error while evaluating xPath " + xPath, false, e1);
    }

    for (Element element : elements) {
        Node newNode = element.cloneNode(true);
        document.adoptNode(newNode);
        document.appendChild(newNode);
    }
    XPath xpathObject = XPathFactory.newInstance().newXPath();

    try {
        return (Node) xpathObject.compile(xPath).evaluate(document, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new MetsExportException("Error while evaluating xPath " + xPath, false, e);
    }
}
 
Example 5
Source Project: archie   Source File: RMQueryContext.java    License: Apache License 2.0 6 votes vote down vote up
public <T> List<T> findList(String query) throws XPathExpressionException {
    List<T> result = new ArrayList<T>();

    if (query.equals("/")) {
        result.add((T) rootNode);
    } else {

        String convertedQuery = APathToXPathConverter.convertQueryToXPath(query, firstXPathNode);
        XPath xpath = xPathFactory.newXPath();


        xpath.setNamespaceContext(new ArchieNamespaceResolver(domForQueries));
        NodeList foundNodes = (NodeList) xpath.evaluate(convertedQuery, domForQueries, XPathConstants.NODESET);

        //Perform decoration
        for (int i = 0; i < foundNodes.getLength(); i++) {
            Node node = foundNodes.item(i);
            result.add(getJAXBNode(node));
        }
    }

    return result;
}
 
Example 6
/**
 * Returns working sets specified in localextensions.xml
 */
public static Set<String> getWorkingSets() {
	Set<String> workingSets = new HashSet<>();
	File localExtensions = new File(PathUtils.getLocalExtensionsPath());
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	try {
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(localExtensions);
		XPath xPath = XPathFactory.newInstance().newXPath();
		String path = "//comment()[following-sibling::*[1][self::extension]]";
		NodeList commentNodes = (NodeList) xPath.compile(path).evaluate(doc, XPathConstants.NODESET);
		for (int i = 0; i < commentNodes.getLength(); i++) {
			Node node = commentNodes.item(i);
			String workingSet = node.getNodeValue().trim();
			workingSets.add(workingSet);
		}
	} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
		Activator.logError("Couldn't parse working sets file", e);
	}
	return workingSets;
}
 
Example 7
Source Project: bdt   Source File: HDFSSecUtils.java    License: Apache License 2.0 6 votes vote down vote up
public void createSecuredHDFSConnection(String coreSite, String hdfsSite, String krb5Conf, String sslClient, String hdfsHost, String keytabPath, String truststorePath, String realm) throws Exception {
    // Check that ssl-config.xml file provided points to truststore path provided
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(sslClient);

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

    XPathExpression expr = xpath.compile("/configuration/property[name='ssl.client.truststore.location']/value/text()");
    String result = expr.evaluate(doc);

    Assertions.assertThat(result).as("Truststore path specified in ssl-client.xml: " + result + " is different from provided one: " + truststorePath).isEqualTo(truststorePath);

    conf.addResource(new Path("file:///" + coreSite));
    conf.addResource(new Path("file:///" + hdfsSite));

    System.setProperty("java.security.krb5.conf", krb5Conf);

    conf.addResource(new Path("file:///" + sslClient));
    conf.set("fs.defaultFS", "hdfs://" + hdfsHost + "/");

    UserGroupInformation.setConfiguration(conf);
    UserGroupInformation.loginUserFromKeytab("hdfs/" + hdfsHost + "@" + realm, keytabPath);
}
 
Example 8
Source Project: ci.maven   Source File: PluginConfigXmlIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testServerEnvElements() throws Exception {
    File in = new File(CONFIG_XML);
    FileInputStream input = new FileInputStream(in);
    
    // get input XML Document
    DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance();
    inputBuilderFactory.setIgnoringComments(true);
    inputBuilderFactory.setCoalescing(true);
    inputBuilderFactory.setIgnoringElementContentWhitespace(true);
    inputBuilderFactory.setValidating(false);
    DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder();
    Document inputDoc = inputBuilder.parse(input);
    
    // parse input XML Document
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/liberty-plugin-config/serverEnv/text()";
    String nodeValue = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING);
    File f1 = new File(SOURCE_SERVER_ENV);
    File f2 = new File(nodeValue);
    assertEquals("serverEnv value", f1.getAbsolutePath(), f2.getAbsolutePath());
    assertEquals("verify target server server.env", FileUtils.fileRead(f2),
            FileUtils.fileRead(TARGET_SERVER_ENV));
}
 
Example 9
/**
 * Gets the nodes.
 *
 * @param xmlDocument the xml document
 * @param xPathExpression the x path expression
 * @return the nodes
 */
private NodeList getNodes( Document xmlDocument, String xPathExpression )
{
	try
	{
		if (log.isDebugEnabled())
			log.debug( "Attempting to return Nodes for [" + xPathExpression + "]" );

		XPath xPath = xPathFactory.newXPath();
		return ( NodeList ) xPath.evaluate( xPathExpression, xmlDocument, XPathConstants.NODESET );
	}
	catch (Exception e)
	{
		log.error( "Error parsing xPath Expression [" + xPathExpression + "]" );
		return null;
	}
}
 
Example 10
Source Project: cerberus-source   Source File: Differences.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link Differences} instance from the given {@link Document}
 * 
 * @param documentDiff
 *            the {@link Document} base to create the {@link Differences} instance
 * @return a {@link Differences} instance from the given {@link Document}
 * @throws DifferencesException
 *             if the given {@link Document} does not have a correct {@link Differences} format
 */
public static Differences fromDocument(Document documentDiff) throws DifferencesException {
	NodeList list = null;
	try {
		XPath path = XPathFactory.newInstance().newXPath();
		list = (NodeList) path.compile(DIFFERENCE_COMMON_XPATH).evaluate(documentDiff, XPathConstants.NODESET);
	} catch (XPathExpressionException e) {
		throw new DifferencesException(e);
	}

	Differences diff = new Differences();
	for (int i = 0; i < list.getLength(); i++) {
		diff.addDifference(new Difference(list.item(i).getFirstChild().getNodeValue()));
	}
	return diff;
}
 
Example 11
Source Project: openjdk-jdk9   Source File: Bug4991939.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testXPath13() throws Exception {
    QName qname = new QName(XMLConstants.XML_NS_URI, "");

    XPathFactory xpathFactory = XPathFactory.newInstance();
    Assert.assertNotNull(xpathFactory);

    XPath xpath = xpathFactory.newXPath();
    Assert.assertNotNull(xpath);

    try {
        xpath.evaluate("1+1", (Object) null, qname);
        Assert.fail("failed , expected IAE not thrown");
    } catch (IllegalArgumentException e) {
        ; // as expected
    }
}
 
Example 12
public List<MagicEdition> listEditions() {

		if (!list.isEmpty())
			return list;

		try {
			XPath xPath = XPathFactory.newInstance().newXPath();
			String expression = "//edition/@id";
			NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
			for (int i = 0; i < nodeList.getLength(); i++)
			{
				list.add(MTGControler.getInstance().getEnabled(MTGCardsProvider.class).getSetById(nodeList.item(i).getNodeValue()));
			}
			
			Collections.sort(list);
		} catch (Exception e) {
			logger.error("Error retrieving IDs ", e);
		}
		return list;
	}
 
Example 13
Source Project: openjdk-jdk9   Source File: Bug4992805.java    License: GNU General Public License v2.0 5 votes vote down vote up
private XPath createXPath() throws XPathFactoryConfigurationException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    Assert.assertNotNull(xpathFactory);
    XPath xpath = xpathFactory.newXPath();
    Assert.assertNotNull(xpath);
    return xpath;
}
 
Example 14
Source Project: mycore   Source File: MCRXMLFunctions.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * The method return a org.w3c.dom.NodeList as subpath of the doc input
 * NodeList selected by a path as String.
 *
 * @param doc
 *            the input org.w3c.dom.Nodelist
 * @param path
 *            the path of doc as String
 * @return a subpath of doc selected by path as org.w3c.dom.NodeList
 */
public static NodeList getTreeByPath(NodeList doc, String path) {
    NodeList n = null;
    DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked();
    try {
        // build path selection
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(path);
        // select part
        Document document = documentBuilder.newDocument();
        if (doc.item(0).getNodeName().equals("#document")) {
            // LOGGER.debug("NodeList is a document.");
            Node child = doc.item(0).getFirstChild();
            if (child != null) {
                Node node = doc.item(0).getFirstChild();
                Node imp = document.importNode(node, true);
                document.appendChild(imp);
            } else {
                document.appendChild(doc.item(0));
            }
        }
        n = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
    } catch (Exception e) {
        LOGGER.error("Error while getting tree by path {}", path, e);
    } finally {
        MCRDOMUtils.releaseDocumentBuilder(documentBuilder);
    }
    return n;
}
 
Example 15
public void removePersonObjects( Document doc ) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression personProperties = null;
    try {
        personProperties = xpath.compile("//*[@class='org.kuali.rice.kim.impl.identity.PersonImpl']");
        NodeList matchingNodes = (NodeList)personProperties.evaluate( doc, XPathConstants.NODESET );
        for(int i = 0; i < matchingNodes.getLength(); i++) {
            Node tempNode = matchingNodes.item(i);
            tempNode.getParentNode().removeChild(tempNode);
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
}
 
Example 16
Source Project: BotLibre   Source File: Test.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static void testXPath() throws Exception {
	//String html = Utils.httpGET("http://www.google.ru/search?q=site::http://endurancerobots.com/+робот");
	//System.out.println(html);
		
	Bot bot = Bot.createInstance();
	Http http = bot.awareness().getSense(Http.class);
	
	Element element = http.parseURL(new URL("http://ab-w.net/HTML5/html5_em.php"));
	System.out.println(element.getTextContent());
	XPathFactory factory = XPathFactory.newInstance();
	XPath path = factory.newXPath();
	Object node = path.evaluate("//*/p[5]/em/text()", element, XPathConstants.NODE);
	System.out.println(((Text)node).getTextContent());
	System.out.println("курсивный");
}
 
Example 17
Source Project: hawkular-apm   Source File: XML.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method evaluates the xpath expression on the supplied
 * node. The result can either be a document fragment, a
 * text node value or null if the expression references a
 * missing part of the document.
 *
 * @param xpath The xpath expression
 * @param node The node
 * @return The result, or null if not found (which may be due to an expression error)
 */
public static String evaluate(String xpath, Object node) {
    Node domNode = getNode(node);

    if (domNode == null) {
        log.severe("Unable to evaluate non DOM Node object");
        return null;
    }

    // If no xpath expression, then serialize
    if (xpath == null || xpath.trim().isEmpty()) {
        return serialize(node);
    }

    // TODO: HWKBTM-104 Investigate caching compiled xpath expressions
    try {
        xpath = getExpression(xpath);
        XPath xp = XPathFactory.newInstance().newXPath();
        Node result = (Node) xp.evaluate(xpath, domNode, XPathConstants.NODE);

        if (result != null) {
            if (result.getNodeType() == Node.TEXT_NODE) {
                return result.getNodeValue();
            } else if (result.getNodeType() == Node.ATTRIBUTE_NODE) {
                return result.getNodeValue();
            }
            return serialize(result);
        }
    } catch (DOMException|XPathExpressionException e) {
        log.log(Level.SEVERE, "Failed to evaluate xpath '" + xpath + "'", e);
    }

    return null;
}
 
Example 18
Source Project: development   Source File: XMLConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Count nodes which are given via xpath expression
 */
public static Double countNodes(Node node, String nodePath)
        throws XPathExpressionException {
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    final XPathExpression expr = xpath.compile("count(" + nodePath + ')');
    return (Double) expr.evaluate(node, XPathConstants.NUMBER);
}
 
Example 19
Source Project: development   Source File: XMLConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the node in the given document at the specified XPath.
 * 
 * @param node
 *            The document to be checked.
 * @param xpathString
 *            The xpath to look at.
 * @return The node at the given xpath.
 * @throws XPathExpressionException
 */
public static Node getNodeByXPath(Node node, String xpathString)
        throws XPathExpressionException {

    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new XmlNamespaceResolver(
            getOwningDocument(node)));
    final XPathExpression expr = xpath.compile(xpathString);
    return (Node) expr.evaluate(node, XPathConstants.NODE);
}
 
Example 20
Source Project: BotLibre   Source File: Http.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Post the XML document object and return the XML data from the URL.
 */
public Vertex postXMLAuth(String url, String user, String password, String agent, Vertex xmlObject, String xpath, Network network) {
	log("POST XML Auth", Level.INFO, url);
	try {
		String data = convertToXML(xmlObject);
		log("POST XML", Level.FINE, data);
		String xml = Utils.httpAuthPOST(url, user, password, agent, "application/xml", data);
		log("XML", Level.FINE, xml);
		InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8"));
		Element element = parseXML(stream);
		if (element == null) {
			return null;
		}
		XPathFactory factory = XPathFactory.newInstance();
		XPath path = factory.newXPath();
		Object node = path.evaluate(xpath, element, XPathConstants.NODE);
		if (node instanceof Element) {
			return convertElement((Element)node, network);
		} else if (node instanceof Attr) {
			return network.createVertex(((Attr)node).getValue());
		} else if (node instanceof org.w3c.dom.Text) {
			return network.createVertex(((org.w3c.dom.Text)node).getTextContent());
		}
		return null;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
Example 21
private NodeList readXMLNodes(Document doc, String xpathExpression) throws Exception {
	XPath xpath = XPathFactory.newInstance().newXPath();
	XPathExpression expr = xpath.compile(xpathExpression);

	Object result = expr.evaluate(doc, XPathConstants.NODESET);
	NodeList nodes = (NodeList) result;

	return nodes;
}
 
Example 22
Source Project: milkman   Source File: XmlContentType.java    License: MIT License 5 votes vote down vote up
public static String toPrettyString(String xml, int indent) {
    try {
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        document.normalize();
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
                                                      document,
                                                      XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        log.warn("Failed to format xml", e);
    }
    return xml;
}
 
Example 23
Source Project: SB_Elsinore_Server   Source File: BeerXMLReader.java    License: MIT License 5 votes vote down vote up
/**
 * Add a mash Profile to a recipe.
 * @param recipe The @{Recipe} object to add the mash profile to.
 * @param mashProfile The node containing the beerXML Mash element.
 * @param xp an XPath object to use to run XPath expressions.
 * @throws XPathException If an XPath expression could not be run.
 */
private void parseMashProfile(Recipe recipe, Node mashProfile, XPath xp) throws XPathException {
    String name = getString(mashProfile, "NAME", xp);
    double grainTemp = getDouble(mashProfile, "GRAIN_TEMP", xp);
    Node mashSteps = (Node) xp.evaluate("MASH_STEPS", mashProfile, XPathConstants.NODE);
    String notes = getString(mashProfile, "NOTES", xp);
    double tunTemp = getDouble(mashProfile, "TUN_TEMP", xp);
    double spargeTemp = getDouble(mashProfile, "SPARGE_TEMP", xp);
    double ph = getDouble(mashProfile, "PH", xp);
    double tunWeight = getDouble(mashProfile, "TUN_WEIGHT", xp);
    double tunSpecificHeat = getDouble(mashProfile, "TUN_SPECIFIC_HEAT", xp);
    boolean tunAdjust = getBoolean(mashProfile, "TUN_ADJUST", xp, false);

    Mash mash = recipe.getMash();
    if (mash == null) {
        mash = new Mash(name, recipe);
        recipe.setMash(mash);
    } else {
        mash.setName(name);
    }

    mash.setGrainTemp(grainTemp);
    mash.setNotes(notes);
    mash.setTunTemp(tunTemp);
    mash.setSpargeTemp(spargeTemp);
    mash.setPh(ph);
    mash.setTunWeight(tunWeight);
    mash.setTunSpecificHeat(tunSpecificHeat);
    mash.setTunAdjust(tunAdjust);
    mash.setTunWeight(getString(mashProfile, "DISPLAY_TUN_WEIGHT", xp));
    mash.setMashTempUnits(getString(mashProfile, "DISPLAY_GRAIN_TEMP", xp));

    parseMashSteps(mash, mashSteps, xp);
}
 
Example 24
Source Project: rice   Source File: XPathTest.java    License: Educational Community License v2.0 5 votes vote down vote up
@Test
public void testXPathWithNamespaceAwareDOM() throws Exception {
    Document doc = getDocument(true, false);
    XPath xpath = getXPath(null);
    String channelName = (String) xpath.evaluate("/nreq:notification/nreq:channel", doc.getDocumentElement(), XPathConstants.STRING);
    assertEquals("Test Channel #1", channelName);
}
 
Example 25
Source Project: SAMLRaider   Source File: XMLHelpers.java    License: MIT License 5 votes vote down vote up
/**
 * Sign whole SAML Message
 *
 * @param document
 *            Document with the response to sign
 * @param signAlgorithm
 *            Signature algorithm in uri form, default if an unknown
 *            algorithm is provided:
 *            http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
 * @param digestAlgorithm
 *            Digest algorithm in uri form, default if an unknown algorithm
 *            is provided: http://www.w3.org/2001/04/xmlenc#sha256
 */
public void signMessage(Document document, String signAlgorithm, String digestAlgorithm, X509Certificate cert, PrivateKey key)
		throws CertificateException, FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException,
		MarshalException, XMLSignatureException, IOException {
	try {
		if(Thread.currentThread().getContextClassLoader() == null){
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); 
		}
		setIDAttribute(document);
		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression expr = xpath.compile("//*[local-name()='Response']/@ID");
		NodeList nlURIs = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

		String[] sigIDs = new String[nlURIs.getLength()];

		for (int i = 0; i < nlURIs.getLength(); i++) {
			sigIDs[i] = nlURIs.item(i).getNodeValue();
		}

		Init.init();
		for (String id : sigIDs) {
			signElement(document, id, cert, key, signAlgorithm, digestAlgorithm);
		}
	} catch (XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
Example 26
Source Project: AuTe-Framework   Source File: XMLUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Parse XML document and get value using XPath expression.
 *
 * @param source          original document
 * @param xpathExpression valid XPath expression for getting required value
 * @return string value by xpath expression
 */
@SuppressWarnings("WeakerAccess")
public static String getValueByXPath(String source, String xpathExpression) throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(new InputSource(new StringReader(source)));
    XPath xPath = XPathFactory.newInstance().newXPath();
    return xPath.compile(xpathExpression).evaluate(xmlDocument);
}
 
Example 27
Source Project: buck   Source File: WorkspaceUpdater.java    License: Apache License 2.0 5 votes vote down vote up
private static Node findChangeListManagerNode(XPath xpath, Document workspaceDocument)
    throws XPathExpressionException {
  return (Node)
      xpath
          .compile("/project/component[@name = 'ChangeListManager']")
          .evaluate(workspaceDocument, XPathConstants.NODE);
}
 
Example 28
Source Project: ph-commons   Source File: XPathHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link XPath} with the passed namespace context using the
 * default {@link XPathFactory}.
 *
 * @param aNamespaceContext
 *        Namespace context to be used. May be <code>null</code>.
 * @return The created non-<code>null</code> {@link XPath} object
 */
@Nonnull
public static XPath createNewXPath (@Nullable final NamespaceContext aNamespaceContext)
{
  return createNewXPath (s_aXPathFactory,
                         (XPathVariableResolver) null,
                         (XPathFunctionResolver) null,
                         aNamespaceContext);
}
 
Example 29
@Override
public List<DocumentAttribute> extractDocumentAttributes(@WebParam(name = "extensionDefinition") ExtensionDefinition extensionDefinition,
                                                         @WebParam(name = "documentWithContent") DocumentWithContent documentWithContent) {
    List<DocumentAttribute> attribs = new ArrayList<DocumentAttribute>(1);
    String appContent = documentWithContent.getDocumentContent().getApplicationContent();
    XPath xpath = XPathHelper.newXPath();
    try {
        //InputSource source = new StringReader(appContent);
        Element source = DocumentBuilderFactory
                .newInstance().newDocumentBuilder().parse(new InputSource(new BufferedReader(new StringReader(appContent)))).getDocumentElement();
        String result = (String) xpath.evaluate(xpathExpression, source, XPathConstants.STRING);
        // xpath has no concept of null node, missing text values are the empty string
        if (StringUtils.isNotEmpty(result)) {
            try {
                attribs.add(createAttribute(this.key, result, this.dataType));
            } catch (ParseException pe) {
                log.error("Error converting value '" + result + "' to type '" + this.dataType + "'");
            }
        }
    } catch (XPathExpressionException xep) {
        log.error("Error evaluating searchable attribute expression: '" + this.xpathExpression + "'", xep);
    } catch (SAXException se) {
        log.error("Error parsing application content: '" + appContent + "'", se);
    } catch (ParserConfigurationException pce) {
        log.error("Error parsing application content: '" + appContent + "'", pce);
    } catch (IOException ioe) {
        log.error("Error parsing application content: '" + appContent + "'", ioe);
    }
    return attribs;
}
 
Example 30
private static XPathExpression getStringsXPathExpression(String expression) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    XPathExpression stringNodesExpression = null;
    try {
        stringNodesExpression = xpath.compile(expression);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    return stringNodesExpression;
}