javax.xml.xpath.XPath Java Examples

The following examples show how to use javax.xml.xpath.XPath. 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 File: HDFSSecUtils.java    From bdt with 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 #2
Source File: FDFAnnotationPolygon.java    From PdfBox-Android with 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 #3
Source File: Differences.java    From cerberus-source with 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 #4
Source File: Bug4991939.java    From openjdk-jdk9 with 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 #5
Source File: MetsUtils.java    From proarc with 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 #6
Source File: XMLHelpers.java    From SAMLRaider with 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 #7
Source File: StandardGenericXMLRuleAttribute.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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 #8
Source File: XMLPageDataProvider.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #9
Source File: RMQueryContext.java    From archie with 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 #10
Source File: ExtensionUtils.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #11
Source File: PluginConfigXmlIT.java    From ci.maven with 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 #12
Source File: PackagesProvider.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
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 File: SOAPResponseValidator.java    From gatf with Apache License 2.0 5 votes vote down vote up
protected int getResponseMappedCount(String expression, Object nodeLst) throws Exception {
	expression = expression.replaceAll("\\.", "\\/");
	if(expression.length()>1 && expression.charAt(0)!='/')
		expression = "/" + expression;
	
	Node envelope = getNodeByNameCaseInsensitive(((Document)nodeLst).getFirstChild(), "envelope");
	Node body = getNodeByNameCaseInsensitive(envelope, "body");
	Node requestBody = getNextElement(body);
	Node returnBody = getNextElement(requestBody);
	if(expression.equals(""))
		expression = SOAPResponseValidator.createXPathExpression(expression, envelope, body, requestBody) + "*";
	else	
		expression = SOAPResponseValidator.createXPathExpression(expression, envelope, body, requestBody, returnBody);
	
	XPath xPath =  XPathFactory.newInstance().newXPath();
	NodeList xmlNodeList = (NodeList) xPath.compile(expression).evaluate((Document)nodeLst, XPathConstants.NODESET);
	Assert.assertTrue("Workflow soap variable " + expression +" is null",  
			xmlNodeList!=null && xmlNodeList.getLength()>0);

	String xmlValue = XMLResponseValidator.getXMLNodeValue(xmlNodeList.item(0));
	Assert.assertNotNull("Workflow soap variable " + expression +" is null", xmlValue);
	
	int responseCount = -1;
	try {
		responseCount = Integer.valueOf(xmlValue);
	} catch (Exception e) {
		throw new AssertionError("Invalid responseMappedCount variable defined, " +
				"derived value should be number - "+expression);
	}
	return responseCount;
}
 
Example #14
Source File: XmlPlugin.java    From gatf with Apache License 2.0 5 votes vote down vote up
protected static NodeList getNodeByXpath(String xpathStr, Document xmlDocument) throws XPathExpressionException
{
    if(xpathStr.charAt(0)!='/')
        xpathStr = "/" + xpathStr;
    XPath xPath =  XPathFactory.newInstance().newXPath();
    NodeList xmlNodeList = (NodeList) xPath.compile(xpathStr).evaluate(xmlDocument, XPathConstants.NODESET);
    return xmlNodeList;
}
 
Example #15
Source File: AndroidManifest.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the version Code attribute is set in a given manifest.
 * @param manifestFile the manifest to check
 * @return true if the versionCode attribute is present and its value is not empty.
 * @throws XPathExpressionException
 * @throws StreamException If any error happens when reading the manifest.
 */
public static boolean hasVersionCode(IAbstractFile manifestFile)
        throws XPathExpressionException, StreamException {
    XPath xPath = AndroidXPathFactory.newXPath();

    InputStream is = null;
    try {
        is = manifestFile.getContents();
        Object result = xPath.evaluate(
                "/"  + NODE_MANIFEST +
                "/@" + AndroidXPathFactory.DEFAULT_NS_PREFIX +
                ":"  + ATTRIBUTE_VERSIONCODE,
                new InputSource(is),
                XPathConstants.NODE);

        if (result != null) {
            Node node  = (Node)result;
            if (!node.getNodeValue().isEmpty()) {
                return true;
            }
        }
    } finally {
        try {
            Closeables.close(is, true /* swallowIOException */);
        } catch (IOException e) {
            // cannot happen
        }
    }

    return false;
}
 
Example #16
Source File: Playlist.java    From MusicPlayer with MIT License 5 votes vote down vote up
public void addSong(Song song) {
	if (!songs.contains(song)) {

		songs.add(song);

		try {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(Resources.JAR + "library.xml");

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

			XPathExpression expr = xpath.compile("/library/playlists/playlist[@id=\"" + this.id + "\"]");
			Node playlist = ((NodeList) expr.evaluate(doc, XPathConstants.NODESET)).item(0);

			Element songId = doc.createElement("songId");
			songId.setTextContent(Integer.toString(song.getId()));
			playlist.appendChild(songId);

			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			DOMSource source = new DOMSource(doc);
			File xmlFile = new File(Resources.JAR + "library.xml");
			StreamResult result = new StreamResult(xmlFile);
			transformer.transform(source, result);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
 
Example #17
Source File: XMLHierarchy.java    From android-uiautomator-server with MIT License 5 votes vote down vote up
private static XPathExpression compileXpath(String xpathExpression) throws UiAutomator2Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression exp = null;
    try {
        exp = xpath.compile(xpathExpression);
    } catch (XPathExpressionException e) {
        throw new UiAutomator2Exception("Invalid XPath expression: ", e);
    }
    return exp;
}
 
Example #18
Source File: Utils.java    From teamengine with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an XPointer to XPath and evaulates the result (JAXP)
 * 
 */
public static String evaluateXPointer(String xpointer, InputStream is) {
    String results = "";
    // Parse the XPointer into usable namespaces and XPath expressions
    int xmlnsStart = xpointer.indexOf("xmlns(") + "xmlns(".length();
    int xmlnsEnd = xpointer.indexOf(")", xmlnsStart);
    int xpathStart = xpointer.indexOf("xpointer(") + "xpointer(".length();
    int xpathEnd = xpointer.indexOf(")", xpathStart);
    String xmlnsStr = xpointer.substring(xmlnsStart, xmlnsEnd);
    String xpathStr = xpointer.substring(xpathStart, xpathEnd);
    // System.out.println("xmlnsStr: "+xmlnsStr+" xpathStr: "+xpathStr);
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        String[] namespaces = xmlnsStr.split(",");
        // Add namespaces to XPath element
        MyNamespaceContext context = new MyNamespaceContext();
        for (int i = 0; i < namespaces.length; i++) {
            String[] xmlnsParts = namespaces[i].split("=");
            context.setNamespace(xmlnsParts[0], xmlnsParts[1]);
            xpath.setNamespaceContext(context);
        }
        InputSource src = new InputSource(is);
        results = (String) xpath.evaluate(xpathStr, src);
        // System.out.println("results: "+results);
    } catch (Exception e) {
        jlogger.log(Level.SEVERE,
                "Error in evaluating XPointer.  " + e.getMessage(), e);

        System.out.println("Error in evaluating XPointer.  "
                + e.getMessage());
    }
    return results;
}
 
Example #19
Source File: DOMSourceEntityProviderTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
private void assertThatXmlDocumentContainsAllExpectedNodes(Node document) throws XPathExpressionException {
    XPath xPath = XPathFactory.newInstance().newXPath();
    for (Map.Entry<String, String> entry : XPATH_EXPR_TO_VALUE.entrySet()) {
        String xpathExpression = entry.getKey();
        String expectedResult = entry.getValue();

        String result = (String)xPath.evaluate(xpathExpression, document, XPathConstants.STRING);
        assertEquals(String.format("Unexpected result in XML Document for expression: %s", xpathExpression),
                     expectedResult, result);
    }
}
 
Example #20
Source File: SubsystemParsingAllowedClockSkewTestCase.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void setSubsystemXml(String value, String unit) throws IOException {
    try {
        String template = readResource("keycloak-saml-1.3.xml");
        if (value != null) {
            // assign the AllowedClockSkew element using DOM
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = db.parse(new InputSource(new StringReader(template)));
            // create the skew element
            Element allowedClockSkew = doc.createElement(Constants.XML.ALLOWED_CLOCK_SKEW);
            if (unit != null) {
                allowedClockSkew.setAttribute(Constants.XML.ALLOWED_CLOCK_SKEW_UNIT, unit);
            }
            allowedClockSkew.setTextContent(value);
            // locate the IDP and insert the node
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodeList = (NodeList) xPath.compile("/subsystem/secure-deployment[1]/SP/IDP").evaluate(doc, XPathConstants.NODESET);
            nodeList.item(0).appendChild(allowedClockSkew);
            // transform again to XML
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            subsystemXml = writer.getBuffer().toString();
        } else {
            subsystemXml = template;
        }
    } catch (DOMException | ParserConfigurationException | SAXException | TransformerException | XPathExpressionException e) {
        throw new IOException(e);
    }
}
 
Example #21
Source File: DefaultStringLib.java    From jdmn with Apache License 2.0 5 votes vote down vote up
private String evaluateXPath(String input, String expression) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    // Read document
    String xml = "<root>" + input + "</root>";
    DocumentBuilderFactory builderFactory = XMLUtil.makeDocumentBuilderFactory();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
    Document document = builder.parse(inputStream);

    // Evaluate xpath
    XPathFactory xPathFactory = new XPathFactoryImpl();
    XPath xPath = xPathFactory.newXPath();
    return xPath.evaluate(expression, document.getDocumentElement());
}
 
Example #22
Source File: TranslationStatistics.java    From ToGoZip with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #23
Source File: Bug4992805.java    From openjdk-jdk9 with 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 #24
Source File: AudioPremisUtils.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private Node createNode(JAXBElement jaxb, JAXBContext jc, String expression) throws  Exception{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.newDocument();

    // Marshal the Object to a Document
    Marshaller marshaller = jc.createMarshaller();
    marshaller.marshal(jaxb, document);
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node agentNode = (Node) xpath.compile(expression).evaluate(document, XPathConstants.NODE);
    return agentNode;
}
 
Example #25
Source File: PomTransformerTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static void assertFormat(String xml, String expectedIndent, String expectedEol)
        throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError {
    final XPath xPath = XPathFactory.newInstance().newXPath();
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new StringReader(xml)), result);
    final Node document = result.getNode();
    Assertions.assertEquals(expectedIndent, PomTransformer.detectIndentation(document, xPath));
    Assertions.assertEquals(expectedEol, PomTransformer.detectEol(xml));
}
 
Example #26
Source File: Pom.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
static Pom parse(IFile pomFile) throws SAXException, IOException, CoreException {
  Preconditions.checkState(pomFile.exists(), pomFile.getFullPath() + " does not exist");
  
  try {
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder.parse(pomFile.getContents());
    Pom pom = new Pom(document, pomFile);
    
    XPath xpath = xpathFactory.newXPath();
    xpath.setNamespaceContext(maven4NamespaceContext);

    NodeList bomNodes = (NodeList) xpath.evaluate(
        "//m:dependencyManagement/m:dependencies/m:dependency[m:type='pom'][m:scope='import']",
        document.getDocumentElement(),
        XPathConstants.NODESET);
    
    for (int i = 0; i < bomNodes.getLength(); i++) {
      String artifactId = (String) xpath.evaluate("string(./m:artifactId)",
          bomNodes.item(i),
          XPathConstants.STRING);
      String groupId = (String) xpath.evaluate("string(./m:groupId)",
          bomNodes.item(i),
          XPathConstants.STRING);
      String version = (String) xpath.evaluate("string(./m:version)",
          bomNodes.item(i),
          XPathConstants.STRING);
      Bom bom = Bom.loadBom(groupId, artifactId, version, null);
      pom.boms.add(bom);
    } 
    
    return pom;
  } catch (ParserConfigurationException | XPathExpressionException ex) {
    IStatus status = StatusUtil.error(Pom.class, ex.getMessage(), ex);
    throw new CoreException(status);
  }
}
 
Example #27
Source File: EpubBook.java    From BookyMcBookface with GNU General Public License v3.0 5 votes vote down vote up
private static Map<String,?> processToc(BufferedReader tocReader) {
    Map<String,Object> bookdat = new LinkedHashMap<>();

    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    XPathFactory factory = XPathFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = dfactory.newDocumentBuilder();

        tocReader.mark(4);
        if ('\ufeff' != tocReader.read()) tocReader.reset(); // not the BOM marker

        Document doc = builder.parse(new InputSource(tocReader));

        XPath tocPath = factory.newXPath();
        tocPath.setNamespaceContext(tocnsc);

        Node nav = (Node)tocPath.evaluate("/ncx/navMap", doc, XPathConstants.NODE);

        int total = readNavPoint(nav, tocPath, bookdat, 0);
        bookdat.put(TOCCOUNT, total);

    } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
        Log.e("BMBF", "Error parsing xml " + e.getMessage(), e);
    }
    return bookdat;
}
 
Example #28
Source File: IndexSchema.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the copy fields
 */
protected synchronized void loadCopyFields(Document document, XPath xpath) throws XPathExpressionException {
  String expression = "//" + COPY_FIELD;
  NodeList nodes = (NodeList)xpath.evaluate(expression, document, XPathConstants.NODESET);

  for (int i=0; i<nodes.getLength(); i++) {
    Node node = nodes.item(i);
    NamedNodeMap attrs = node.getAttributes();

    String source = DOMUtil.getAttr(attrs, SOURCE, COPY_FIELD + " definition");
    String dest   = DOMUtil.getAttr(attrs, DESTINATION,  COPY_FIELD + " definition");
    String maxChars = DOMUtil.getAttr(attrs, MAX_CHARS);

    int maxCharsInt = CopyField.UNLIMITED;
    if (maxChars != null) {
      try {
        maxCharsInt = Integer.parseInt(maxChars);
      } catch (NumberFormatException e) {
        log.warn("Couldn't parse {} attribute for '{}' from '{}' to '{}' as integer. The whole field will be copied."
            , MAX_CHARS, COPY_FIELD, source, dest);
      }
    }

    if (dest.equals(uniqueKeyFieldName)) {
      String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
        ") can not be the " + DESTINATION + " of a " + COPY_FIELD + "(" + SOURCE + "=" +source+")";
      log.error(msg);
      throw new SolrException(ErrorCode.SERVER_ERROR, msg);
    }
    
    registerCopyField(source, dest, maxCharsInt);
  }
    
  for (Map.Entry<SchemaField, Integer> entry : copyFieldTargetCounts.entrySet()) {
    if (entry.getValue() > 1 && !entry.getKey().multiValued())  {
      log.warn("Field {} is not multivalued and destination for multiople {} ({})"
          , entry.getKey().name, COPY_FIELDS, entry.getValue());
    }
  }
}
 
Example #29
Source File: FeatureXMLGetVersionVisitor.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes arg1) throws IOException {
	FileSystem fileSystem = FileSystems.getDefault();
	PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:" + filePattern);

	if (pathMatcher.matches(path.getFileName())) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(path.toFile());

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

			XPathExpression expr = xpath.compile("string(//feature[1]/@version)");
			Object result = expr.evaluate(doc, XPathConstants.STRING);
			if (result instanceof String) {
				this.version = result.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return FileVisitResult.TERMINATE;
	}
	return FileVisitResult.CONTINUE;
}
 
Example #30
Source File: MockDriverHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public MockDriverHandler(Class<? extends AbstractDriverLoader> loaderClass, String behaviorSpec,
        DeviceId mockDeviceId, CoreService mockCoreService, DeviceService mockDeviceService) {

    // Had to split into declaration and initialization to make stylecheck happy
    // else line was considered too long
    // and auto format couldn't be tweak to make it correct
    Map<Class<? extends Behaviour>, Class<? extends Behaviour>> behaviours;
    behaviours = new HashMap<Class<? extends Behaviour>, Class<? extends Behaviour>>();

    try {
        String data = Resources.toString(Resources.getResource(loaderClass, behaviorSpec), StandardCharsets.UTF_8);
        InputStream resp = IOUtils.toInputStream(data, StandardCharsets.UTF_8);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(resp);

        XPath xp = XPathFactory.newInstance().newXPath();
        NodeList list = (NodeList) xp.evaluate("//behaviour", document, XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i += 1) {
            Node node = list.item(i);
            NamedNodeMap attrs = node.getAttributes();
            Class<? extends Behaviour> api = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("api").getNodeValue());
            Class<? extends Behaviour> impl = (Class<? extends Behaviour>) Class
                    .forName(attrs.getNamedItem("impl").getNodeValue());
            behaviours.put(api, impl);
        }
        init(behaviours, mockDeviceId, mockCoreService, mockDeviceService);
    } catch (Exception e) {
        fail(e.toString());
    }
}