Java 类javax.xml.xpath.XPathExpression 实例源码

项目:fluentxml4j    文件:FluentXPathContext.java   
XPathExpression compile(String xPathQuery, NamespaceContext namespaceContext)
{
    try
    {
        XPath xPath = this.xPathConfigurer.getXPath(namespaceContext);
        return xPath.compile(xPathQuery);
    }
    catch (XPathExpressionException ex)
    {
        throw new FluentXmlProcessingException(ex);
    }
}
项目:incubator-netbeans    文件:JFXProjectUtils.java   
public static boolean isMavenFXProject(@NonNull final Project prj) {
    if (isMavenProject(prj)) {
        try {
            FileObject pomXml = prj.getProjectDirectory().getFileObject("pom.xml"); //NOI18N
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(FileUtil.toFile(pomXml));
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression exprJfxrt = xpath.compile("//bootclasspath[contains(text(),'jfxrt')]"); //NOI18N
            XPathExpression exprFxPackager = xpath.compile("//executable[contains(text(),'javafxpackager')]"); //NOI18N
            XPathExpression exprPackager = xpath.compile("//executable[contains(text(),'javapackager')]"); //NOI18N
            boolean jfxrt = (Boolean) exprJfxrt.evaluate(doc, XPathConstants.BOOLEAN);
            boolean packager = (Boolean) exprPackager.evaluate(doc, XPathConstants.BOOLEAN);
            boolean fxPackager = (Boolean) exprFxPackager.evaluate(doc, XPathConstants.BOOLEAN);
            return jfxrt && (packager || fxPackager);
        } catch (XPathExpressionException | ParserConfigurationException | SAXException | IOException ex) {
            LOGGER.log(Level.INFO, "Error while parsing pom.xml.", ex);  //NOI18N
            return false;
        }
    }
    return false;
}
项目:neoscada    文件:XmlHelper.java   
public static List<Node> findNodes ( final Node node, final String expression ) throws XPathExpressionException
{
    final XPath path = xpf.newXPath ();
    final XPathExpression expr = path.compile ( expression );
    final NodeList nodeList = (NodeList)expr.evaluate ( node, XPathConstants.NODESET );

    if ( nodeList == null )
    {
        return Collections.emptyList ();
    }

    final List<Node> result = new LinkedList<Node> ();
    for ( int i = 0; i < nodeList.getLength (); i++ )
    {
        result.add ( nodeList.item ( i ) );
    }

    return result;
}
项目:ats-framework    文件:XmlUtilities.java   
/**
 * Get values matching passed XPath expression
 * @param node
 * @param expression XPath expression
 * @return matching values
 * @throws Exception
 */
private static String[] getByXpath( Node node, String expression ) throws Exception {

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression xPathExpression = xPath.compile(expression);

    NodeList nlist = (NodeList) xPathExpression.evaluate(node, XPathConstants.NODESET);

    int nodeListSize = nlist.getLength();
    List<String> values = new ArrayList<String>(nodeListSize);
    for (int index = 0; index < nlist.getLength(); index++) {
        Node aNode = nlist.item(index);
        values.add(aNode.getTextContent());
    }
    return values.toArray(new String[values.size()]);
}
项目:DAFramework    文件:XPathEvaluator.java   
public XPathExpression getExpr(String exp) {
    XPathExpression expr = expCache.get(exp);
    if (expr == null) {
        try {
            expr = xpath.compile(exp);
            if (expr != null) {
                expCache.put(exp, expr);
            }
            return expr;
        } catch (XPathExpressionException e) {
            LOG.error(e.getMessage(), e);
            return null;
        }
    }
    return expr;
}
项目:DAFramework    文件:DomXmlUtils.java   
public static Iterator<Node> getNodeList(String exp, Element dom) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expUserTask = xpath.compile(exp);
    final NodeList nodeList = (NodeList) expUserTask.evaluate(dom, XPathConstants.NODESET);

    return new Iterator<Node>() {
        private int index = 0;

        @Override
        public Node next() {
            return nodeList.item(index++);
        }

        @Override
        public boolean hasNext() {
            return (nodeList.getLength() - index) > 0;
        }
    };
}
项目:xtf    文件:MavenProject.java   
private XPathExpression buildXpath(String... path) {
    StringBuilder builder = new StringBuilder();
    for (String pathSegment : path) {
        if (builder.length() > 0) {
            builder.append("/");
        }
        builder.append(pathSegment);
    }

    try {
        return XPATH.newXPath().compile(builder.toString());
    } catch (XPathExpressionException e) {
        LOGGER.error("Unable to compile xpath '{}'", builder);
        throw new RuntimeException("Unable to compile xpath");
    }
}
项目:NBANDROID-V2    文件:ManifestParser.java   
private static Iterable<String> getAttrNames(InputStream is, XPathExpression expr) {
    Set<String> names = Sets.newHashSet();
    if (expr != null) {
        try {
            Document doc = parseStream(is);
            if (doc != null) {
                NodeList nodelist = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                for (int i = 0; i < nodelist.getLength(); i++) {
                    String name = nodelist.item(i).getNodeValue();
                    names.add(name);
                }
            }
        } catch (XPathExpressionException ex) {
            LOG.log(Level.WARNING, null, ex);
        }
    }
    return names;
}
项目:OpenJSharp    文件:XPathImpl.java   
/**
 * <p>Compile an XPath expression for later evaluation.</p>
 *
 * <p>If <code>expression</code> contains any {@link XPathFunction}s,
 * they must be available via the {@link XPathFunctionResolver}.
 * An {@link XPathExpressionException} will be thrown if the <code>XPathFunction</code>
 * cannot be resovled with the <code>XPathFunctionResolver</code>.</p>
 *
 * <p>If <code>expression</code> is <code>null</code>, a <code>NullPointerException</code> is thrown.</p>
 *
 * @param expression The XPath expression.
 *
 * @return Compiled XPath expression.

 * @throws XPathExpressionException If <code>expression</code> cannot be compiled.
 * @throws NullPointerException If <code>expression</code> is <code>null</code>.
 */
public XPathExpression compile(String expression)
    throws XPathExpressionException {
    if ( expression == null ) {
        String fmsg = XSLMessages.createXPATHMessage(
                XPATHErrorResources.ER_ARG_CANNOT_BE_NULL,
                new Object[] {"XPath expression"} );
        throw new NullPointerException ( fmsg );
    }
    try {
        com.sun.org.apache.xpath.internal.XPath xpath = new XPath (expression, null,
                prefixResolver, com.sun.org.apache.xpath.internal.XPath.SELECT );
        // Can have errorListener
        XPathExpressionImpl ximpl = new XPathExpressionImpl (xpath,
                prefixResolver, functionResolver, variableResolver,
                featureSecureProcessing, useServiceMechanism, featureManager );
        return ximpl;
    } catch ( javax.xml.transform.TransformerException te ) {
        throw new XPathExpressionException ( te ) ;
    }
}
项目:DaUtil    文件:XPathEvaluator.java   
public XPathExpression getExpr(String exp) {
    XPathExpression expr = expCache.get(exp);
    if (expr == null) {
        try {
            expr = xpath.compile(exp);
            if (expr != null) {
                expCache.put(exp, expr);
            }
            return expr;
        } catch (XPathExpressionException e) {
            LOG.error(e.getMessage(), e);
            return null;
        }
    }
    return expr;
}
项目:DaUtil    文件:DomXmlUtils.java   
public static Iterator<Node> getNodeList(String exp, Element dom) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expUserTask = xpath.compile(exp);
    final NodeList nodeList = (NodeList) expUserTask.evaluate(dom, XPathConstants.NODESET);

    return new Iterator<Node>() {
        private int index = 0;

        @Override
        public Node next() {
            return nodeList.item(index++);
        }

        @Override
        public boolean hasNext() {
            return (nodeList.getLength() - index) > 0;
        }
    };
}
项目:jaffa-framework    文件:TransformationHelper.java   
/**
 * @param xmlString
 * @return
 * @throws Exception
 */
public static String findFunction(String xmlString) throws Exception {

    DocumentBuilder document = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Element node = document.parse(new ByteArrayInputStream(xmlString.getBytes())).getDocumentElement();

    //Xpath
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//*[local-name()='Envelope']/*[local-name()='Body']/*");

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

    if (log.isDebugEnabled()) {
        log.debug("nodes.item(0).getNodeName():" + nodes.item(0).getNodeName());
    }

    if (nodes.item(0).getNodeName().contains("query")) {
        return "query";
    } else if (nodes.item(0).getNodeName().contains("update")) {
        return "update";
    } else {
        return null;
    }
}
项目:SofaTime    文件:Xml.java   
/**
 * Get value from status XML doc.
 *
 * @param doc         Doc to get value from
 * @param elementName Element name to search
 * @param attribute   Attribute to search
 * @return The value found
 * @throws XPathExpressionException Error in XPath expression
 */
public static String getValueFromStatus(final Document doc,
                                        final String elementName,
                                        final String attribute)
        throws XPathExpressionException {

    // Create XPath
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    StringBuilder expression = new StringBuilder();

    // Build XPath from element name and attribute value (if exists)
    expression.append("//").append(elementName);
    if (attribute != null) {
        expression.append("[@name=\'").append(attribute).append("\']");
    }
    expression.append("/text()");
    XPathExpression xPathExpression = xPath.compile(expression.toString());

    // Return result from XPath expression
    return xPathExpression.evaluate(doc);
}
项目:doctemplate    文件:DOCXMergeEngine.java   
private int getMaxRId(ByteArrayOutputStream xmlStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(xmlStream.toByteArray()));
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("Relationships/*");
        NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            String id = nodeList.item(i).getAttributes().getNamedItem("Id").getTextContent();
            int idNum = Integer.parseInt(id.substring("rId".length()));
            this.maxRId = idNum > this.maxRId ? idNum : this.maxRId;
        }
        return this.maxRId;
    }
项目:mnp    文件:CustomMasksParser.java   
@Override
public void parse(Consumer<MnoInfo> consumer) throws Exception {
    File fXmlFile = config.toFile();

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
    XPathExpression xpathMno = XPathFactory.newInstance().newXPath().compile("//*[local-name()='mno']");
    XPathExpression xpathMasksMno = XPathFactory.newInstance().newXPath().compile("//*[local-name()='mask']");
    NodeList mnoNodes = (NodeList) xpathMno.evaluate(doc, XPathConstants.NODESET);
    for (int i=0; i<mnoNodes.getLength(); i++) {
        Node node = mnoNodes.item(i);
        NamedNodeMap attributes = node.getAttributes();
        String country = getValue(attributes.getNamedItem("country"));
        String title = getValue(attributes.getNamedItem("title"));
        String area = getValue(attributes.getNamedItem("area"));
        Set<Mask> masks = new HashSet<>();
        NodeList maskNodes = (NodeList) xpathMasksMno.evaluate(doc, XPathConstants.NODESET);
        for (int j=0; j<maskNodes.getLength(); j++) {
            masks.add(Mask.parse(getValue(maskNodes.item(j))));
        }
        consumer.accept(new MnoInfo(title, area, country, masks));
    }
}
项目:komplexni-validator    文件:VfCheckBibliographicMetadataMatchProfile.java   
private List<String> detectEntityIds(Document metsDoc, EntityType entityType) throws InvalidXPathExpressionException, XPathExpressionException {
    XPathExpression xPathExpression = engine.buildXpath("/mets:mets/mets:dmdSec[contains(@ID, \"" + entityType.getDmdSecCode() + "\")]/@ID");
    NodeList idAttrs = (NodeList) xPathExpression.evaluate(metsDoc, XPathConstants.NODESET);
    Set<String> set = new HashSet<>(idAttrs.getLength());
    for (int i = 0; i < idAttrs.getLength(); i++) {
        Attr attr = (Attr) idAttrs.item(i);
        String id = attr.getValue();
        if (id.startsWith("MODSMD_")) {
            id = id.substring("MODSMD_".length());
        } else if (id.startsWith("DCMD_")) {
            id = id.substring("DCMD_".length());
        }
        String typePrefix = entityType.getDmdSecCode() + '_';
        id = id.substring(typePrefix.length());
        set.add(id);
    }
    return new ArrayList<>(set);
}
项目:bdd-test-automation-for-mobile    文件:IosApplication.java   
public String getExpectedAnalytics(String analyticsParams) throws Exception{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true); 
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("vertical");
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();

    String paramsToPath = "//"+(analyticsParams.replaceAll(":", "/"))+"/node()";
    XPathExpression expr = xpath.compile(paramsToPath);
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < nodes.getLength(); i++) {
        sb.append((nodes.item(i).getNodeName()+"="+nodes.item(i).getTextContent()).trim());           
    }  
    String expectedParams = sb.toString().replaceAll("#text=", ";");

    return expectedParams;
}
项目:Ads-Attacher    文件:XMLFileManipulation.java   
public boolean deleteNode(String node){

    //TODO Make deleteNode for all 

    XPathFactory xpf = XPathFactory.newInstance();
       XPath xpath = xpf.newXPath();
       XPathExpression expression;
       Node b13Node;
    try {
        expression = xpath.compile("//UserList/user[username/text()='"+node+"']");
        b13Node = (Node) expression.evaluate(doc, XPathConstants.NODE);
        b13Node.getParentNode().removeChild(b13Node);
        saveXML("Users");
        return true; 
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    return false;
}
项目:wES    文件:XPathEvaluator.java   
public XPathExpression getExpr(String exp) {
    XPathExpression expr = expCache.get(exp);
    if (expr == null) {
        try {
            expr = xpath.compile(exp);
            if (expr != null) {
                expCache.put(exp, expr);
            }
            return expr;
        } catch (XPathExpressionException e) {
            LOG.error(e.getMessage(), e);
            return null;
        }
    }
    return expr;
}
项目:wES    文件:DomXmlUtils.java   
public static Iterator<Node> getNodeList(String exp, Element dom) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expUserTask = xpath.compile(exp);
    final NodeList nodeList = (NodeList) expUserTask.evaluate(dom, XPathConstants.NODESET);

    return new Iterator<Node>() {
        private int index = 0;

        @Override
        public Node next() {
            return nodeList.item(index++);
        }

        @Override
        public boolean hasNext() {
            return (nodeList.getLength() - index) > 0;
        }
    };
}
项目:subrelease-maven-plugin    文件:XpathPomReader.java   
/**
 * Retrieves a scm connection from pom, by looking specifically at scm/developerConnection.
 *
 * @return a scm connection indicates scm type, and connection information; {@code null}
 * otherwise
 */
public String getScmConnection() {
    XPath xPath = XPathFactory.newInstance().newXPath();
    try {
        XPathExpression xPathExpression = xPath.compile("//scm/developerConnection");
        NodeList nl = (NodeList) xPathExpression.evaluate(pomDoc, XPathConstants.NODESET);

        if (nl == null || nl.getLength() == 0) {
            return null;
        }

        return nl.item(0).getTextContent().trim();

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return null;
}
项目:essence    文件:ValueOutOfBoundDetector.java   
public String parseXML4XpathValue(Document doc, String xpathString) {
    if (doc == null || xpathString == null)
        return null;

    try {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression msgPath = xpath.compile(xpathString);
        Node msg = (Node) msgPath.evaluate(doc, XPathConstants.NODE);
        //NodeList msgs = (NodeList) msgPath.evaluate(doc, XPathConstants.NODESET);
        //System.out.println("Two ways for xpath: " + xpathString);
        System.out.println("One node content = " + msg.getTextContent() + "\tOne node value = " + msg.getNodeValue());
        /* TODO - will support array in the future
        for (int i=0; i<msgs.getLength(); i++) {
            System.out.println(i + "-text=" + msgs.item(i).getTextContent() + "\t" + i + "-value=" + msgs.item(i).getNodeValue());
        }
        */
        return msg.getTextContent();
        //return msg.getNodeValue();
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return null;
}
项目:essence    文件:XpathPlay.java   
public static String parseXML4XpathValue(Document doc, String xpathString) {
    if (doc == null || xpathString == null)
        return null;

    try {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression msgPath = xpath.compile(xpathString);
        Node msg = (Node) msgPath.evaluate(doc, XPathConstants.NODE);
        NodeList msgs = (NodeList) msgPath.evaluate(doc, XPathConstants.NODESET);
        System.out.println("Two ways for xpath: " + xpathString);
        System.out.println("one node content = " + msg.getTextContent() + "\tone node value = " + msg.getNodeValue());
        for (int i=0; i<msgs.getLength(); i++) {
            System.out.println(i + "-text=" + msgs.item(i).getTextContent() + "\t" + i + "-value=" + msgs.item(i).getNodeValue());
        }
        return msg.getTextContent();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:komplexni-validator    文件:VfCheckBibliographicMetadataMatchProfile.java   
private CatalogingConventions detectCatalogingConventions(String entityId, EntityType entityType, Document metsDoc, ValidationResult result)
        throws InvalidXPathExpressionException, XPathExpressionException {
    String entityGlobalId = entityType.getDmdSecCode() + '_' + entityId;
    String dmdSecId = "MODSMD_" + entityGlobalId;
    XPathExpression xPathExpression = engine.buildXpath("/mets:mets/mets:dmdSec[@ID=\"" + dmdSecId + "\"]/mets:mdWrap/mets:xmlData/mods:mods/mods:recordInfo/mods:descriptionStandard");

    String specStr = (String) xPathExpression.evaluate(metsDoc, XPathConstants.STRING);
    if (specStr == null || specStr.isEmpty()) {
        result.addError(invalid(Level.INFO, "záznam %s neobsahuje informaci o použitých katalogizačních pravidlech; validuji %s oproti AACR2", dmdSecId, entityGlobalId));
        return CatalogingConventions.AACR2;
    } else {
        if (specStr.toLowerCase().equals("aacr") || specStr.toLowerCase().equals("aacr2")) {
            return CatalogingConventions.AACR2;
        } else if (specStr.equals("rda")) {
            return CatalogingConventions.RDA;
        } else {
            result.addError(invalid(Level.WARNING, "záznam %s obsahuje neplatnou informaci o použitých katalogizačních pravidlech (%s); validuji %s oproti AACR2", dmdSecId, specStr, entityGlobalId));
            return CatalogingConventions.AACR2;
        }
    }
}
项目:auto-dex    文件:AutoDexUtil.java   
/**
 * parse package name
 * 
 * @param androidManifestFullFilename
 * @return String
 */
public static String parsePackageName(String androidManifestFullFilename) {
    String packageName = null;
    if (FileUtil.isExist(androidManifestFullFilename)) {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        Document document = JavaXmlUtil.parse(androidManifestFullFilename);
        try {
            XPathExpression expression = xpath.compile("/manifest[@package]");
            NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
            if (nodeList != null && nodeList.getLength() > 0) {
                Node node = nodeList.item(0);
                packageName = node.getAttributes().getNamedItem("package").getTextContent();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return packageName;
}
项目:gvnix1    文件:XmlUtils.java   
/**
 * Checks in under a given root element whether it can find a child node
 * which matches the XPath expression supplied. Returns {@link Node} if
 * exists. Please note that the XPath parser used is NOT namespace aware. So
 * if you want to find a element <code>&lt;beans&gt;&lt;sec:http&gt;</code>,
 * you need to use the XPath expression '<code>/beans/http</code>'.
 * 
 * @param xPathExpression the XPath expression (required)
 * @param root the parent DOM element (required)
 * @return the Node if discovered (null if not found)
 */
public static Node findNode(final String xPathExpression, final Node root) {
    Validate.notBlank(xPathExpression, "XPath expression required");
    Validate.notNull(root, "Root element required");
    Node node = null;
    try {
        XPathExpression expr = COMPILED_EXPRESSION_CACHE
                .get(xPathExpression);
        if (expr == null) {
            expr = XPATH.compile(xPathExpression);
            COMPILED_EXPRESSION_CACHE.put(xPathExpression, expr);
        }
        node = (Node) expr.evaluate(root, XPathConstants.NODE);
    }
    catch (final XPathExpressionException e) {
        throw new IllegalArgumentException(
                "Unable evaluate XPath expression '" + xPathExpression
                        + "'", e);
    }
    return node;
}
项目:test-analyzer    文件:JaCoCoXmlParser.java   
private void parseMethodNode(String className, Node methodNode, IResultReceiver resultReceiver)
        throws XPathExpressionException {
    XPathExpression methodNameAttributeXPath = compileXPath("@name");
    XPathExpression methodDescAttributeXPath = compileXPath("@desc");

    String methodName = evaluateStringValue(methodNode, methodNameAttributeXPath);
    String methodDesc = evaluateStringValue(methodNode, methodDescAttributeXPath);

    if (BytecodeUtility.isConstructor(methodName)) {
        return;
    }

    MethodIdentifier methodIdentifier = MethodIdentifier.create(className, methodName, methodDesc);
    parseMethodNode(methodIdentifier, methodNode, resultReceiver, COUNTER_TYPE_LINE);
    parseMethodNode(methodIdentifier, methodNode, resultReceiver, COUNTER_TYPE_INSTRUCTION);
    parseMethodNode(methodIdentifier, methodNode, resultReceiver, COUNTER_TYPE_BRANCH);
}
项目:test-analyzer    文件:JaCoCoXmlParser.java   
private void parseMethodNode(MethodIdentifier methodIdentifier, Node methodNode, IResultReceiver resultReceiver,
        String counterTypeName) throws XPathExpressionException {
    XPathExpression counterNodeXPath = compileXPath(String.format("./counter[@type='%s']", counterTypeName));
    XPathExpression folderCountCoveredAttributeXPath = compileXPath("@covered");
    XPathExpression folderCountMissedAttributeXPath = compileXPath("@missed");

    ECoverageLevel coverageLevel = convertCounterTypeToCoverageLevel(counterTypeName);

    Node counterNode = (Node) counterNodeXPath.evaluate(methodNode, XPathConstants.NODE);
    int countCovered = 0;
    int countNotCovered = 0;

    if (counterNode != null) {
        // counterNode is null if a method does not contain any branches
        countCovered = Integer.parseInt(evaluateStringValue(counterNode, folderCountCoveredAttributeXPath));
        countNotCovered = Integer.parseInt(evaluateStringValue(counterNode, folderCountMissedAttributeXPath));
    }

    resultReceiver.append(getResultPresentation().formatCoveragePerMethod(methodIdentifier, coverageLevel,
            countCovered, ECoverageValueType.COVERED_COUNT));
    resultReceiver.append(getResultPresentation().formatCoveragePerMethod(methodIdentifier, coverageLevel,
            countCovered + countNotCovered, ECoverageValueType.ALL_COUNT));
}
项目:github-pr-coverage-status    文件:XmlUtils.java   
public static String findInXml(String xml, String xpath) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver(new EntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
//                    if (systemId.contains("foo.dtd")) {
                    return new InputSource(new StringReader(""));
//                    } else {
//                        return null;
//                    }
                }
            });
            Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPathExpression expr = xPathfactory.newXPath().compile(xpath);
            return (String) expr.evaluate(doc, XPathConstants.STRING);
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }
项目:mdw    文件:DomHelper.java   
public static Object peek(Document doc, String xpathExpr) throws XPathExpressionException
{
  XPathFactory xPathfactory = XPathFactory.newInstance();
  XPath xpath = xPathfactory.newXPath();
  XPathExpression expr = xpath.compile(xpathExpr);
  NodeList nodeList = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
  if (nodeList == null || nodeList.getLength() == 0)
  {
    return null;
  }
  else if (nodeList.getLength() == 1)
  {
    Node node = nodeList.item(0);
    if (node instanceof Attr)
      return ((Attr)node).getValue();
    else
      return node.getChildNodes().item(0).getNodeValue();
  }
  else
  {
    return nodeList;
  }
}
项目:komplexni-validator    文件:FirstNonemptyByXpathDataExctraction.java   
@Override
public Object extract(Object processedOutput) throws ExtractionException {
    String pathForError = null;
    try {
        for (String path : paths) {
            pathForError = path;
            XPathExpression xPath = buildXpath(path);
            Object extractedData = extractData(xPath, processedOutput);
            if (extractedData != null && !extractedData.toString().isEmpty()) {
                return extractedData;
            }
        }
        return null;
    } catch (XPathExpressionException e) {
        throw new ExtractionException(String.format("chyba v zápisu Xpath '%s': %s", pathForError, e.getMessage()));
    }
}
项目:C4SG-Obsolete    文件:CoordinatesUtil.java   
/**@param{Object} Address- The physical address of a location
  * This method returns Geocode coordinates of the Address object.Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway,
  * Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739).Please give all the physical Address values 
  * for a precise coordinate. setting none of the values will give a null value for the Latitude and Longitude. 
  */ 
public static GeoCode getCoordinates(Address address) throws Exception
 {
  GeoCode geo= new GeoCode();
  String physicalAddress = (address.getAddress1() == null ? "" : address.getAddress1() + ",")
          + (address.getAddress2() == null ? "" : address.getAddress2() + ",")
          + (address.getCityName() == null ? "" : address.getCityName() + ",")
          + (address.getState()    == null ? "" : address.getState() + "-")
          + (address.getZip()      == null ? "" : address.getZip() + ",")
          + (address.getCountry()  == null ? "" :  address.getCountry());
  String api = GMAPADDRESS + URLEncoder.encode(physicalAddress, "UTF-8") + SENSOR;
  URL url = new URL(api);
  HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
  httpConnection.connect();
  int responseCode = httpConnection.getResponseCode();
  if(responseCode == 200)
   {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(httpConnection.getInputStream());
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(STATUS);
    String status = (String)expr.evaluate(document, XPathConstants.STRING);
    if(status.equals("OK"))
     {
       expr = xpath.compile(LATITUDE);
       String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
          expr = xpath.compile(LONGITUDE);
       String longitude = (String)expr.evaluate(document, XPathConstants.STRING);
       geo.setLatitude(latitude);
       geo.setLongitude(longitude);
     }
    }
    else
    {
        throw new Exception("Fail to Convert to Geocode");
    }
    return geo;
  }
项目:qpp-conversion-tool    文件:MarkupManipulator.java   
public InputStream upsetTheNorm(String xPath, boolean remove) {
    try {
        document = dbf.newDocumentBuilder().parse(new File(pathname));
        XPath xpath = xpf.newXPath();
        XPathExpression expression = xpath.compile(xPath);

        NodeList searchedNodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
        if (searchedNodes == null) {
            System.out.println("bad path: " + xPath);
        } else {
            for (int i = 0; i < searchedNodes.getLength(); i++) {
                Node searched = searchedNodes.item(i);

                Node owningElement = (searched instanceof ElementImpl)
                        ? searched
                        : ((AttrImpl) searched).getOwnerElement();

                Node containingParent = owningElement.getParentNode();

                if (remove) {
                    containingParent.removeChild(owningElement);
                } else {
                    containingParent.appendChild(owningElement.cloneNode(true));
                }

            }
        }

        Transformer t = tf.newTransformer();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Result result = new StreamResult(os);
        t.transform(new DOMSource(document), result);
        return new ByteArrayInputStream(os.toByteArray());
    } catch (ParserConfigurationException | IOException | SAXException |
            XPathExpressionException | TransformerException ex) {
        throw new RuntimeException(ex);
    }
}
项目:smaph    文件:Stands4AbbreviationExpansion.java   
/**Query the API and returns the list of expansions. Update the cache.
 * @param abbrev lowercase abbreviation.
 * @throws Exception
 */
private synchronized String[] queryApi(String abbrev, int retryLeft)
        throws Exception {
    if (retryLeft < MAX_RETRY)
        Thread.sleep(1000);
    URL url = new URL(String.format("%s?uid=%s&tokenid=%s&term=%s",
            API_URL, uid, tokenId, URLEncoder.encode(abbrev, "utf8")));

    boolean cached = abbrToExpansion.containsKey(abbrev);
    LOG.info("{} {}", cached ? "<cached>" : "Querying", url);
    if (cached) return abbrToExpansion.get(abbrev);


    HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
    connection.setConnectTimeout(0);
    connection.setRequestProperty("Accept", "*/*");
    connection
    .setRequestProperty("Content-Type", "multipart/form-data");

    connection.setUseCaches(false);

    if (connection.getResponseCode() != 200) {
        Scanner s = new Scanner(connection.getErrorStream())
                .useDelimiter("\\A");
        LOG.error("Got HTTP error {}. Message is: {}",
                connection.getResponseCode(), s.next());
        s.close();
        throw new RuntimeException("Got response code:"
                + connection.getResponseCode());
    }

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc;
    try {
        doc = builder.parse(connection.getInputStream());
    } catch (IOException e) {
        LOG.error("Got error while querying: {}", url);
        throw e;
    }

    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression resourceExpr = xpath.compile("//definition/text()");

    NodeList resources = (NodeList) resourceExpr.evaluate(doc,
            XPathConstants.NODESET);

    Vector<String> resVect = new Vector<>();
    for (int i=0; i<resources.getLength(); i++){
        String expansion = resources.item(i).getTextContent().replace(String.valueOf((char) 160), " ").trim();
        if (!resVect.contains(expansion))
            resVect.add(expansion);
    }

    String[] res = resVect.toArray(new String[]{});
    abbrToExpansion.put(abbrev, res);
    increaseFlushCounter();
    return res;
}
项目:fluentxml4j    文件:FluentXPathContextTest.java   
@Test
public void compile() throws XPathExpressionException
{
    when(this.xPathConfigurer.getXPath(this.immutableNamespaceContext)).thenReturn(this.xpath);
    when(this.xpath.compile("aQuery")).thenReturn(this.xpathExpr);

    XPathExpression xpathExprReturned = this.fluentXPathContext.compile("aQuery", this.immutableNamespaceContext);

    assertThat(xpathExprReturned, is(xpathExpr));
}
项目:alfresco-repository    文件:XPathMetadataExtracter.java   
/**
 * Executes all the necessary XPath statements to extract values.
 */
protected Map<String, Serializable> processDocument(Document document) throws Throwable
{
    Map<String, Serializable> rawProperties = super.newRawMap();

    // Execute all the XPaths that we saved
    for (Map.Entry<String, XPathExpression> element : xpathExpressionMapping.entrySet())
    {
        String documentProperty = element.getKey();
        XPathExpression xpathExpression = element.getValue();
        // Get the value, assuming it is a nodeset
        Serializable value = null;
        try
        {
            value = getNodeSetValue(document, xpathExpression);
        }
        catch (XPathExpressionException e)
        {
            // That didn't work, so give it a try as a STRING
            value = getStringValue(document, xpathExpression);
        }
        // Put the value
        super.putRawValue(documentProperty, value, rawProperties);
    }
    // Done
    return rawProperties;
}
项目:AndroidApktool    文件:ResXmlPatcher.java   
/**
 * Any @string reference in a <provider> value in AndroidManifest.xml will break on
 * build, thus preventing the application from installing. This is from a bug/error
 * in AOSP where public resources cannot be part of an authorities attribute within
 * a <provider> tag.
 *
 * This finds any reference and replaces it with the literal value found in the
 * res/values/strings.xml file.
 *
 * @param file File for AndroidManifest.xml
 * @throws AndrolibException
 */
public static void fixingPublicAttrsInProviderAttributes(File file) throws AndrolibException {
    if (file.exists()) {
        try {
            Document doc = loadDocument(file);
            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression expression = xPath.compile("/manifest/application/provider");

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

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

                if (attrs != null) {
                    Node provider = attrs.getNamedItem("android:authorities");

                    if (provider != null) {
                        String reference = provider.getNodeValue();
                        String replacement = pullValueFromStrings(file.getParentFile(), reference);

                        if (replacement != null) {
                            provider.setNodeValue(replacement);
                            saveDocument(file, doc);
                        }
                    }
                }
            }

        }  catch (SAXException | ParserConfigurationException | IOException |
                XPathExpressionException | TransformerException ignored) {
        }
    }
}
项目:AndroidApktool    文件:ResXmlPatcher.java   
/**
 * Finds key in strings.xml file and returns text value
 *
 * @param directory Root directory of apk
 * @param key String reference (ie @string/foo)
 * @return String|null
 * @throws AndrolibException
 */
public static String pullValueFromStrings(File directory, String key) throws AndrolibException {
    if (! key.contains("@")) {
        return null;
    }

    File file = new File(directory, "/res/values/strings.xml");
    key = key.replace("@string/", "");

    if (file.exists()) {
        try {
            Document doc = loadDocument(file);
            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression expression = xPath.compile("/resources/string[@name=" + '"' + key + "\"]/text()");

            Object result = expression.evaluate(doc, XPathConstants.STRING);

            if (result != null) {
                return (String) result;
            }

        }  catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException ignored) {
        }
    }

    return null;
}
项目:oscm    文件:XMLConverter.java   
/**
 * 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);
}
项目:oscm    文件:XMLConverter.java   
/**
 * Returns the number value of an XPath evaluation.
 * 
 * @param doc
 *            The document to be checked.
 * @param xpathString
 *            The XPath to search at.
 * @return The number according to the XPath.
 * @throws XPathExpressionException
 */
public static Number getNumberByXPath(Document doc, String xpathString)
        throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    XPathExpression expr = xpath.compile(xpathString);

    Number result = (Number) expr.evaluate(doc, XPathConstants.NUMBER);
    return result;
}