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:org.sonar.dotnet.tools.commons.visualstudio.ModelFactory.java

/**
 * Generates a list of projects from the path of the visual studio projects files (.csproj)
 * // w  w  w .  j av a  2 s.c o  m
 * @param projectFile
 *          the project file
 * @param projectName
 *          the name of the project
 * @throws DotNetToolsException
 * @throws FileNotFoundException
 *           if the file was not found
 */
public static VisualStudioProject getProject(File projectFile, String projectName,
        List<String> buildConfigurations) throws FileNotFoundException, DotNetToolsException {

    VisualStudioProject project = new VisualStudioProject();
    project.setProjectFile(projectFile);
    project.setName(projectName);
    File projectDir = projectFile.getParentFile();

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

    // This is a workaround to avoid Xerces class-loading issues
    ClassLoader savedClassloader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(xpath.getClass().getClassLoader());
    try {
        // We define the namespace prefix for Visual Studio
        xpath.setNamespaceContext(new VisualStudioNamespaceContext());

        if (buildConfigurations != null) {
            Map<String, File> buildConfOutputDirMap = new HashMap<String, File>();
            for (String config : buildConfigurations) {
                XPathExpression configOutputExpression = xpath.compile(
                        "/vst:Project/vst:PropertyGroup[contains(@Condition,'" + config + "')]/vst:OutputPath");
                String configOutput = extractProjectProperty(configOutputExpression, projectFile);
                buildConfOutputDirMap.put(config, new File(projectDir, configOutput));
            }
            project.setBuildConfOutputDirMap(buildConfOutputDirMap);
        }

        XPathExpression projectTypeExpression = xpath.compile("/vst:Project/vst:PropertyGroup/vst:OutputType");
        XPathExpression assemblyNameExpression = xpath
                .compile("/vst:Project/vst:PropertyGroup/vst:AssemblyName");
        XPathExpression rootNamespaceExpression = xpath
                .compile("/vst:Project/vst:PropertyGroup/vst:RootNamespace");
        XPathExpression debugOutputExpression = xpath
                .compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'Debug')]/vst:OutputPath");
        XPathExpression releaseOutputExpression = xpath
                .compile("/vst:Project/vst:PropertyGroup[contains(@Condition,'Release')]/vst:OutputPath");
        XPathExpression silverlightExpression = xpath
                .compile("/vst:Project/vst:PropertyGroup/vst:SilverlightApplication");

        // Extracts the properties of a Visual Studio Project
        String typeStr = extractProjectProperty(projectTypeExpression, projectFile);
        String silverlightStr = extractProjectProperty(silverlightExpression, projectFile);
        String assemblyName = extractProjectProperty(assemblyNameExpression, projectFile);
        String rootNamespace = extractProjectProperty(rootNamespaceExpression, projectFile);
        String debugOutput = extractProjectProperty(debugOutputExpression, projectFile);
        String releaseOutput = extractProjectProperty(releaseOutputExpression, projectFile);

        // Assess if the artifact is a library or an executable
        ArtifactType type = ArtifactType.LIBRARY;
        if (StringUtils.containsIgnoreCase(typeStr, "exe")) {
            type = ArtifactType.EXECUTABLE;
        }
        // The project is populated
        project.setProjectFile(projectFile);
        project.setType(type);
        project.setDirectory(projectDir);
        project.setAssemblyName(assemblyName);
        project.setRootNamespace(rootNamespace);
        project.setDebugOutputDir(new File(projectDir, debugOutput));
        project.setReleaseOutputDir(new File(projectDir, releaseOutput));

        if (StringUtils.isNotEmpty(silverlightStr)) {
            project.setSilverlightProject(true);
        }

        project.setBinaryReferences(getBinaryReferences(xpath, projectFile));

        assessTestProject(project, testProjectNamePattern);

        return project;
    } catch (XPathExpressionException xpee) {
        throw new DotNetToolsException("Error while processing the project " + projectFile, xpee);
    } finally {
        // Replaces the class loader after usage
        Thread.currentThread().setContextClassLoader(savedClassloader);
    }
}

From source file:org.sonar.dotnet.tools.commons.visualstudio.ModelFactory.java

/**
 * Gets the relative paths of all the files in a project, as they are defined in the .csproj file.
 * /*from ww  w .j a v a2 s. co m*/
 * @param project
 *          the project file
 * @return a list of the project files
 */
public static List<String> getFilesPath(File project) {
    List<String> result = new ArrayList<String>();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    // We define the namespace prefix for Visual Studio
    xpath.setNamespaceContext(new VisualStudioNamespaceContext());
    try {
        XPathExpression filesExpression = xpath.compile("/vst:Project/vst:ItemGroup/vst:Compile");
        InputSource inputSource = new InputSource(new FileInputStream(project));
        NodeList nodes = (NodeList) filesExpression.evaluate(inputSource, XPathConstants.NODESET);
        int countNodes = nodes.getLength();
        for (int idxNode = 0; idxNode < countNodes; idxNode++) {
            Element compileElement = (Element) nodes.item(idxNode);
            // We filter the files
            String filePath = compileElement.getAttribute("Include");
            if ((filePath != null) && filePath.endsWith(".cs")) {

                // fix tests on unix system
                // but should not be necessary
                // on windows build machines
                filePath = StringUtils.replace(filePath, "\\", File.separatorChar + "");
                result.add(filePath);
            }
        }

    } catch (XPathExpressionException exception) {
        // Should not happen
        LOG.debug("xpath error", exception);
    } catch (FileNotFoundException exception) {
        // Should not happen
        LOG.debug("project file not found", exception);
    }
    return result;
}

From source file:org.sonar.plugins.csharp.stylecop.profiles.utils.StyleCopRuleParser.java

/**
 * @param reader//from   ww w  . jav a2 s.co  m
 * @return
 */
public static List<StyleCopRule> parse(Reader reader) {
    InputSource source = new InputSource(reader);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    List<StyleCopRule> result = new ArrayList<StyleCopRule>();

    try {
        XPathExpression expression = xpath.compile("//Rule");
        NodeList nodes = (NodeList) expression.evaluate(source, XPathConstants.NODESET);
        int count = nodes.getLength();
        for (int idxRule = 0; idxRule < count; idxRule++) {
            Element ruleElement = (Element) nodes.item(idxRule);
            Element analyzerElement = (Element) ruleElement.getParentNode().getParentNode();
            String ruleName = ruleElement.getAttribute("Name");
            String priority = ruleElement.getAttribute("SonarPriority");

            StyleCopRule rule = new StyleCopRule();
            NodeList elements = ruleElement.getElementsByTagName("BooleanProperty");
            boolean active = true;
            int countBoolean = elements.getLength();
            for (int idxElement = 0; idxElement < countBoolean; idxElement++) {
                Element booleanElement = (Element) elements.item(idxElement);
                String booleanName = booleanElement.getAttribute("Name");
                if ("Enabled".equals(booleanName)) {
                    String activeStr = booleanElement.getTextContent();
                    active = !activeStr.toLowerCase().contains("false");
                }
            }
            String analyzerId = analyzerElement.getAttribute("AnalyzerId");
            String category = StringUtils.removeEnd(StringUtils.substringAfterLast(analyzerId, "."), "Rules");
            rule.setAnalyzerId(analyzerId);
            rule.setName(ruleName);
            rule.setPriority(priority);
            rule.setEnabled(active);
            rule.setCategory(category);
            result.add(rule);
        }
    } catch (XPathExpressionException e) {
        LOG.debug("Xpath error un stylecop report", e);
    }

    return result;
}

From source file:org.springframework.boot.gradle.testkit.GradleBuild.java

private static String evaluateExpression(String expression) {
    try {//  ww w . j  a v  a 2s.c  om
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();
        XPathExpression expr = xpath.compile(expression);
        String version = expr.evaluate(new InputSource(new FileReader(".flattened-pom.xml")));
        return version;
    } catch (Exception ex) {
        throw new IllegalStateException("Failed to evaluate expression", ex);
    }
}

From source file:org.structr.web.datasource.XPathGraphDataSource.java

@Override
public List<GraphObject> getData(final RenderContext renderContext, final AbstractNode referenceNode)
        throws FrameworkException {

    final String xpathQuery = referenceNode.getProperty(DOMNode.xpathQuery);

    if (StringUtils.isBlank(xpathQuery)) {
        return null;
    }//from  w w  w.  j ava 2 s.com

    final Document document = ((DOMNode) referenceNode).getOwnerDocument();
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();

    try {

        // FIXME: this code works only with absolute xpath queries because
        //        the xpath parser implementation is stupid (comparing object
        //        equality using ==).
        Object result = xpath.evaluate(xpathQuery, document, XPathConstants.NODESET);
        List<GraphObject> results = new LinkedList<>();

        if (result instanceof NodeList) {

            NodeList nodes = (NodeList) result;
            int len = nodes.getLength();

            for (int i = 0; i < len; i++) {

                Node node = nodes.item(i);

                if (node instanceof GraphObject) {

                    results.add((GraphObject) node);
                }
            }

        } else if (result instanceof GraphObject) {

            results.add((GraphObject) result);
        }

        return results;

    } catch (Throwable t) {

        t.printStackTrace();

        logger.log(Level.WARNING, "Unable to execute xpath query: {0}", t.getMessage());
    }

    return Collections.EMPTY_LIST;

}

From source file:org.syncany.connection.plugins.box.BoxTransferManager.java

@Override
public Map<String, RemoteFile> list() throws StorageException {
    connect();/*from ww w . j  av a  2  s . c om*/

    try {
        GetAccountTreeResponse accountTreeResponse = box
                .getAccountTree(BoxRequestFactory.createGetAccountTreeRequest(getConnection().getApiKey(),
                        getConnection().getToken(), getConnection().getFolderId(), new String[] {}));

        if (!"listing_ok".equals(accountTreeResponse.getStatus())) {
            throw new StorageException("List query failed. Status: " + accountTreeResponse.getStatus());
        }

        // Note:
        //   The result is a (1) base 64 encoded, (2) zipped (3) XML file
        //   See http://developers.box.net/w/page/12923929/ApiFunction_get_account_tree

        // (1) Decode Base 64
        String base64Xml = accountTreeResponse.getEncodedTree();
        InputStream decodedBase64 = new ByteArrayInputStream(Base64.decodeBase64(base64Xml));

        // (2) Unzip
        ZipInputStream zip = new ZipInputStream(decodedBase64);

        if (zip.getNextEntry() == null) {
            throw new StorageException("Cannot read folder tree. Invalid ZIP data.");
        }

        // (3) Read XML            
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(zip);

        // Find files via XPath
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();

        Object result = xpath.evaluate("files/file", doc.getDocumentElement(), XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;
        Map<String, RemoteFile> list = new HashMap<String, RemoteFile>();

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

            String name = node.getAttributes().getNamedItem("file_name").getTextContent();
            Integer size = StringUtil.parseInt(node.getAttributes().getNamedItem("size").getTextContent(), -1);

            list.put(name, new RemoteFile(name, size, node));
        }

        return list;
    } catch (Exception ex) {
        Logger.getLogger(BoxTransferManager.class.getName()).log(Level.SEVERE, null, ex);
        throw new StorageException("...");
    }
}

From source file:org.wattdepot.client.http.api.collector.EGaugeCollector.java

@Override
public void run() {
    Measurement meas = null;// w  ww.  ja  v a  2s  .co  m
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        // Have to make HTTP connection manually so we can set proper timeouts
        URL url = new URL(eGaugeUri);
        URLConnection httpConnection;
        httpConnection = url.openConnection();
        // Set both connect and read timeouts to 15 seconds. No point in long
        // timeouts since the
        // sensor will retry before too long anyway.
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(15 * 1000);
        httpConnection.connect();

        // Record current time as close approximation to time for reading we are
        // about to make
        Date timestamp = new Date();

        Document doc = builder.parse(httpConnection.getInputStream());

        XPathFactory factory = XPathFactory.newInstance();
        XPath powerXpath = factory.newXPath();
        XPath energyXpath = factory.newXPath();
        // Path to get the current power consumed measured by the meter in watts
        String exprPowerString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/i/text()";
        XPathExpression exprPower = powerXpath.compile(exprPowerString);
        // Path to get the energy consumed month to date in watt seconds
        String exprEnergyString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/v/text()";
        XPathExpression exprEnergy = energyXpath.compile(exprEnergyString);
        Object powerResult = exprPower.evaluate(doc, XPathConstants.NUMBER);
        Object energyResult = exprEnergy.evaluate(doc, XPathConstants.NUMBER);

        Double value = null;
        // power is given in W
        Amount<?> power = Amount.valueOf((Double) powerResult, SI.WATT);
        // energy given in Ws
        Amount<?> energy = Amount.valueOf((Double) energyResult, SI.WATT.times(SI.SECOND));
        if (isPower()) {
            value = power.to(measUnit).getEstimatedValue();
        } else {
            value = energy.to(measUnit).getEstimatedValue();
        }
        meas = new Measurement(definition.getSensorId(), timestamp, value, measUnit);
    } catch (MalformedURLException e) {
        System.err.format("URI %s was invalid leading to malformed URL%n", eGaugeUri);
    } catch (XPathExpressionException e) {
        System.err.println("Bad XPath expression, this should never happen.");
    } catch (ParserConfigurationException e) {
        System.err.println("Unable to configure XML parser, this is weird.");
    } catch (SAXException e) {
        System.err.format("%s: Got bad XML from eGauge sensor %s (%s), hopefully this is temporary.%n",
                Tstamp.makeTimestamp(), sensor.getName(), e);
    } catch (IOException e) {
        System.err.format(
                "%s: Unable to retrieve data from eGauge sensor %s (%s), hopefully this is temporary.%n",
                Tstamp.makeTimestamp(), sensor.getName(), e);
    }

    if (meas != null) {
        try {
            this.client.putMeasurement(depository, meas);
        } catch (MeasurementTypeException e) {
            System.err.format("%s does not store %s measurements%n", depository.getName(),
                    meas.getMeasurementType());
        }
        if (debug) {
            System.out.println(meas);
        }
    }
}

From source file:org.wattdepot.client.http.api.collector.NOAAWeatherCollector.java

@Override
public void run() {
    Measurement meas = null;//from w  w  w  . j  ava2 s  . c om
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    try {
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        // Have to make HTTP connection manually so we can set proper timeouts
        URL url = new URL(noaaWeatherUri);
        URLConnection httpConnection;
        httpConnection = url.openConnection();
        // Set both connect and read timeouts to 15 seconds. No point in long
        // timeouts since the
        // sensor will retry before too long anyway.
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(15 * 1000);
        httpConnection.connect();

        // Record current time as close approximation to time for reading we are
        // about to make
        Date timestamp = new Date();

        Document doc = builder.parse(httpConnection.getInputStream());

        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();
        // path to the data
        String valString = "/current_observation/" + this.registerName + "/text()";
        XPathExpression exprValue = xPath.compile(valString);
        Object result = new Double(0);
        if (this.registerName.equals("weather")) {
            Object cloudCoverage = exprValue.evaluate(doc, XPathConstants.STRING);
            String cloudStr = cloudCoverage.toString();
            if (cloudStr.equalsIgnoreCase("sunny") || cloudStr.equalsIgnoreCase("clear")) {
                // 0 to 1/8 cloud coverage
                result = new Double(6.25);
            } else if (cloudStr.equalsIgnoreCase("mostly sunny") || cloudStr.equalsIgnoreCase("mostly clear")) {
                // 1/8 to 2/8 cloud coverage
                result = new Double(18.75);
            } else if (cloudStr.equalsIgnoreCase("partly sunny")
                    || cloudStr.equalsIgnoreCase("partly cloudy")) {
                // 3/8 to 5/8 cloud coverage
                result = new Double(50.0);
            } else if (cloudStr.equalsIgnoreCase("mostly cloudy")) {
                // 6/8 to 7/8 cloud coverage
                result = new Double(81.25);
            } else if (cloudStr.equalsIgnoreCase("cloudy")) {
                // 7/8 to 100% cloud coverage
                result = new Double(93.75);
            }
        } else {
            result = exprValue.evaluate(doc, XPathConstants.NUMBER);
        }

        Double value = (Double) result;
        meas = new Measurement(definition.getSensorId(), timestamp, value, measUnit);
    } catch (MalformedURLException e) {
        System.err.format("URI %s was invalid leading to malformed URL%n", noaaWeatherUri);
    } catch (XPathExpressionException e) {
        System.err.println("Bad XPath expression, this should never happen.");
    } catch (ParserConfigurationException e) {
        System.err.println("Unable to configure XML parser, this is weird.");
    } catch (SAXException e) {
        System.err.format("%s: Got bad XML from eGauge sensor %s (%s), hopefully this is temporary.%n",
                Tstamp.makeTimestamp(), sensor.getName(), e);
    } catch (IOException e) {
        System.err.format(
                "%s: Unable to retrieve data from eGauge sensor %s (%s), hopefully this is temporary.%n",
                Tstamp.makeTimestamp(), sensor.getName(), e);
    }

    if (meas != null) {
        try {
            this.client.putMeasurement(depository, meas);
        } catch (MeasurementTypeException e) {
            System.err.format("%s does not store %s measurements%n", depository.getName(),
                    meas.getMeasurementType());
        }
        if (debug) {
            System.out.println(meas);
        }
    }
}

From source file:org.wso2.carbon.automation.engine.configurations.AutomationConfigurationReader.java

private static void removeText(Node doc) throws XPathExpressionException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    // XPath to find empty text nodes.
    XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
    NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET);

    // Remove each empty text node from document.
    for (int i = 0; i < emptyTextNodes.getLength(); i++) {
        Node emptyTextNode = emptyTextNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
    }//from w  w w  .java2  s .  co  m
}

From source file:org.wso2.carbon.humantask.core.engine.runtime.xpath.XPathExpressionRuntime.java

private Object evaluate(String exp, EvaluationContext evalCtx, QName type) {
    try {//from  w  w  w  .ja v a 2s  .  c  o m
        XPathFactory xpf = new XPathFactoryImpl();
        JaxpFunctionResolver funcResolve = new JaxpFunctionResolver(evalCtx);
        xpf.setXPathFunctionResolver(funcResolve);
        XPathEvaluator xpe = (XPathEvaluator) xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolve);
        xpe.setBackwardsCompatible(true);
        xpe.setNamespaceContext(evalCtx.getNameSpaceContextOfTask());
        XPathExpression xpathExpression = xpe.compile(exp);
        Node contextNode = evalCtx.getRootNode() == null ? DOMUtils.newDocument() : evalCtx.getRootNode();

        Object evalResult = xpathExpression.evaluate(contextNode, type);

        if (evalResult != null && log.isDebugEnabled()) {
            log.debug("Expression " + exp + " generate result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (evalCtx.getRootNode() != null) {
                log.debug("Was using context node " + DOMUtils.domToString(evalCtx.getRootNode()));
            }
        }

        return evalResult;
    } catch (XPathFactoryConfigurationException e) {
        log.error("Exception occurred while creating XPathFactory.", e);
        throw new XPathProcessingException("Exception occurred while creating XPathFactory.", e);
    } catch (XPathExpressionException e) {
        String msg = "Error evaluating XPath expression: " + exp;
        log.error(msg, e);
        throw new XPathProcessingException(msg, e);
    } catch (ParserConfigurationException e) {
        String msg = "XML Parsing error.";
        log.error(msg, e);
        throw new XPathProcessingException(msg, e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new XPathProcessingException(e.getMessage(), e);
    }
}