java类javax.xml.xpath.XPath的实例源码

S3ExceptionUnmarshaller.java 文件源码 项目:aws-sdk-java-v2 阅读 13 收藏 0 点赞 0 评论 0
@Override
public SdkServiceException unmarshall(Node in) throws Exception {

    XPath xpath = xpath();

    String error = asString("Error/Code", in, xpath);
    String requestId = asString("Error/RequestId", in, xpath);
    String message = asString("Error/Message", in, xpath);

    if (!StringUtils.equals(error, this.errorCode)) {
        return null;
    }

    SdkServiceException exception = newException(message);
    exception.errorCode(errorCode);
    exception.requestId(requestId);

    return exception;
}
ModuleProjectClassPathExtenderTest.java 文件源码 项目:incubator-netbeans 阅读 19 收藏 0 点赞 0 评论 0
public void testAddRoots() throws Exception {
    NbModuleProject prj = TestBase.generateStandaloneModule(getWorkDir(), "module");
    FileObject src = prj.getSourceDirectory();
    FileObject jar = TestFileUtils.writeZipFile(FileUtil.toFileObject(getWorkDir()), "a.jar", "entry:contents");
    URL root = FileUtil.getArchiveRoot(jar.toURL());
    assertTrue(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE));
    assertFalse(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE));
    FileObject releaseModulesExt = prj.getProjectDirectory().getFileObject("release/modules/ext");
    assertNotNull(releaseModulesExt);
    assertNotNull(releaseModulesExt.getFileObject("a.jar"));
    jar = TestFileUtils.writeZipFile(releaseModulesExt, "b.jar", "entry2:contents");
    root = FileUtil.getArchiveRoot(jar.toURL());
    assertTrue(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE));
    assertFalse(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE));
    assertEquals(2, releaseModulesExt.getChildren().length);
    String projectXml = prj.getProjectDirectory().getFileObject("nbproject/project.xml").toURL().toString();
    InputSource input = new InputSource(projectXml);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(nbmNamespaceContext());
    assertEquals(projectXml, "ext/a.jar", xpath.evaluate("//nbm:class-path-extension[1]/nbm:runtime-relative-path", input));
    assertEquals(projectXml, "release/modules/ext/a.jar", xpath.evaluate("//nbm:class-path-extension[1]/nbm:binary-origin", input));
    assertEquals(projectXml, "ext/b.jar", xpath.evaluate("//nbm:class-path-extension[2]/nbm:runtime-relative-path", input));
    assertEquals(projectXml, "release/modules/ext/b.jar", xpath.evaluate("//nbm:class-path-extension[2]/nbm:binary-origin", input));
}
LegacyErrorUnmarshaller.java 文件源码 项目:aws-sdk-java-v2 阅读 16 收藏 0 点赞 0 评论 0
@Override
public SdkServiceException unmarshall(Node in) throws Exception {
    XPath xpath = XpathUtils.xpath();
    String errorCode = parseErrorCode(in, xpath);
    String message = XpathUtils.asString("Response/Errors/Error/Message", in, xpath);
    String requestId = XpathUtils.asString("Response/RequestID", in, xpath);
    String errorType = XpathUtils.asString("Response/Errors/Error/Type", in, xpath);

    SdkServiceException exception = newException(message);
    exception.errorCode(errorCode);
    exception.requestId(requestId);

    if ("Client".equalsIgnoreCase(errorType)) {
        exception.errorType(ErrorType.CLIENT);
    } else if ("Server".equalsIgnoreCase(errorType)) {
        exception.errorType(ErrorType.SERVICE);
    } else {
        exception.errorType(ErrorType.fromValue(errorType));
    }

    return exception;
}
AbstractDienstVerzoekParser.java 文件源码 项目:OperatieBRP 阅读 18 收藏 0 点赞 0 评论 0
@Override
public final void vulStuurgegevens(final T verzoek, final Node node, final XPath xPath) throws ParseException {
    verzoek.getStuurgegevens().setCommunicatieId(
            getNodeTextContent(getPrefix() + "/brp:stuurgegevens/@brp:communicatieID", xPath, node));
    verzoek.getStuurgegevens()
            .setZendendePartijCode(getNodeTextContent(getPrefix() + "/brp:stuurgegevens/brp:zendendePartij", xPath, node));
    verzoek.getStuurgegevens().setZendendSysteem(
            getNodeTextContent(getPrefix() + "/brp:stuurgegevens/brp:zendendeSysteem", xPath, node));
    verzoek.getStuurgegevens()
            .setReferentieNummer(getNodeTextContent(getPrefix() + "/brp:stuurgegevens/brp:referentienummer", xPath, node));
    final String tijdstipVerzendingString = getNodeTextContent(getPrefix() + "/brp:stuurgegevens/brp:tijdstipVerzending", xPath, node);
    if (tijdstipVerzendingString != null) {
        final ZonedDateTime tijdstipVerzending = DatumUtil.vanXsdDatumTijdNaarZonedDateTime(tijdstipVerzendingString);
        verzoek.getStuurgegevens().setTijdstipVerzending(tijdstipVerzending);
    }
}
SoapMessageManager.java 文件源码 项目:verify-hub 阅读 19 收藏 0 点赞 0 评论 0
public Element unwrapSoapMessage(Element soapElement) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NamespaceContextImpl context = new NamespaceContextImpl();
    context.startPrefixMapping("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
    context.startPrefixMapping("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
    context.startPrefixMapping("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
    context.startPrefixMapping("ds", "http://www.w3.org/2000/09/xmldsig#");
    xpath.setNamespaceContext(context);
    try {
        final String expression = "/soapenv:Envelope/soapenv:Body/samlp:Response";
        Element element = (Element) xpath.evaluate(expression, soapElement, XPathConstants.NODE);

        if (element == null) {
            String errorMessage = format("Document{0}{1}{0}does not have element {2} inside it.", NEW_LINE,
                    writeToString(soapElement), expression);
            LOG.error(errorMessage);
            throw new IllegalArgumentException(errorMessage);
        }

        return element;
    } catch (XPathExpressionException e) {
        throw propagate(e);
    }
}
Pom.java 文件源码 项目:nbreleaseplugin 阅读 17 收藏 0 点赞 0 评论 0
/**
 * Find the element reference for the selected element. The selected element
 * is an XPATH expression relation to the element reference given as a
 * parameter.
 *
 * @param pev the element reference from which the XPATH expression is
 * evaluated.
 * @param path the XPATH expression
 * @return the resulting element reference
 */
public final ElementValue findElementValue(ElementValue pev, String path) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        Element el = (Element) xpath.evaluate(path, pev.getElement(), XPathConstants.NODE);
        return pev.isInHerited()
                ? (el == null
                        ? new ElementValue(Type.INHERITED_MISSING)
                        : new ElementValue(el, Type.INHERITED))
                : (el == null
                        ? new ElementValue(pev, path)
                        : new ElementValue(el, Type.OK));
    } catch (XPathExpressionException ex) {
        return new ElementValue(pev, path);
    }
}
TableFunctions.java 文件源码 项目:JATS2LaTeX 阅读 16 收藏 0 点赞 0 评论 0
protected static void countColumns(XPath xPath, Table table, Node tableHead)
        throws XPathExpressionException, DOMException, NumberFormatException {
    if (tableHead != null) {
        Node firstRow = (Node) xPath.compile("*[1]").evaluate(tableHead, XPathConstants.NODE);
        NodeList childFirstRows = firstRow.getChildNodes();
        int columnNumber = 0;
        for (int w = 0; w < childFirstRows.getLength(); w++) {
            Node childFirstRow = childFirstRows.item(w);
            if (childFirstRow.getNodeValue() == null && (childFirstRow.getNodeName() == "th" || childFirstRow.getNodeName() == "td")) {
                int number = 1;
                if (childFirstRow.getAttributes().getNamedItem("colspan") != null) {
                    number = Integer.parseInt(childFirstRow.getAttributes().getNamedItem("colspan").getNodeValue());
                } 
                columnNumber = columnNumber + number;
            }
        }
        table.setColumnNumber(columnNumber);
    }
}
XPathCondition.java 文件源码 项目:oscm 阅读 20 收藏 0 点赞 0 评论 0
public boolean eval() throws BuildException {
    if (nullOrEmpty(fileName)) {
        throw new BuildException("No file set");
    }
    File file = new File(fileName);
    if (!file.exists() || file.isDirectory()) {
        throw new BuildException(
                "The specified file does not exist or is a directory");
    }
    if (nullOrEmpty(path)) {
        throw new BuildException("No XPath expression set");
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    InputSource inputSource = new InputSource(fileName);
    Boolean result = Boolean.FALSE;
    try {
        result = (Boolean) xpath.evaluate(path, inputSource,
                XPathConstants.BOOLEAN);
    } catch (XPathExpressionException e) {
        throw new BuildException("XPath expression fails", e);
    }
    return result.booleanValue();
}
DomXmlUtils.java 文件源码 项目:DaUtil 阅读 20 收藏 0 点赞 0 评论 0
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;
        }
    };
}
ValidationService.java 文件源码 项目:ARCLib 阅读 21 收藏 0 点赞 0 评论 0
/**
 * Performs all file existence checks contained in the validation profile. If the validation has failed (some of the files specified
 * in the validation profile do not exist), {@link MissingFile} exception is thrown.
 *
 * @param sipPath path to the SIP
 * @param validationProfileDoc document with the validation profile
 * @param validationProfileId id of the validation profile
 * @throws XPathExpressionException if there is an error in the XPath expression
 */
private void performFileExistenceChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws
        XPathExpressionException {
    XPath xPath =  XPathFactory.newInstance().newXPath();

    NodeList nodes = (NodeList) xPath.compile("/profile/rule/fileExistenceCheck")
            .evaluate(validationProfileDoc, XPathConstants.NODESET);
    for (int i = 0; i< nodes.getLength(); i++) {

        Element element = (Element) nodes.item(i);
        String relativePath = element.getElementsByTagName("filePath").item(0).getTextContent();
        String absolutePath = sipPath + relativePath;
        if (!ValidationChecker.fileExists(absolutePath)) {
            log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + relativePath + "\" is missing.");
            throw new MissingFile(relativePath, validationProfileId);
        }
    }
}
ValidationService.java 文件源码 项目:ARCLib 阅读 21 收藏 0 点赞 0 评论 0
/**
 * Performs all validation schema checks contained in the validation profile. If the validation has failed (some of the XMLs
 * specified in the validation profile do not match their respective validation schemas) {@link SchemaValidationError} is thrown.
 *
 * @param sipPath path to the SIP
 * @param validationProfileDoc document with the validation profile
 * @param validationProfileId id of the validation profile
 * @throws IOException if some of the XMLs address from the validation profile does not exist
 * @throws XPathExpressionException if there is an error in the XPath expression
 * @throws SAXException if the XSD schema is invalid
 */
private void performValidationSchemaChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws
        XPathExpressionException, IOException, SAXException {
    XPath xPath =  XPathFactory.newInstance().newXPath();

    NodeList nodes = (NodeList) xPath.compile("/profile/rule/validationSchemaCheck")
            .evaluate(validationProfileDoc,
                    XPathConstants.NODESET);
    for (int i = 0; i< nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        String filePath = element.getElementsByTagName("filePath").item(0).getTextContent();
        String schema = element.getElementsByTagName("schema").item(0).getTextContent();

        String absoluteFilePath = sipPath + filePath;

        try {
            ValidationChecker.validateWithXMLSchema(new FileInputStream(absoluteFilePath), new InputStream[] {
                    new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8.name()))});
        } catch (GeneralException e) {
            log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + filePath + "\" is not " +
                    "valid against its corresponding schema.");
            throw new SchemaValidationError(filePath, schema, e.getMessage());
        }
    }
}
Xml.java 文件源码 项目:SofaTime 阅读 26 收藏 0 点赞 0 评论 0
/**
 * 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);
}
XPathUtils.java 文件源码 项目:ARCLib 阅读 21 收藏 0 点赞 0 评论 0
/**
 * Searches XML element with XPath and returns list of nodes found
 *
 * @param xml        input stream with the XML in which the element is being searched
 * @param expression XPath expression used in search
 * @return {@link NodeList} of elements matching the XPath in the XML
 * @throws XPathExpressionException     if there is an error in the XPath expression
 * @throws IOException                  if the XML at the specified path is missing
 * @throws SAXException                 if the XML cannot be parsed
 * @throws ParserConfigurationException
 */
public static NodeList findWithXPath(InputStream xml, String expression)
        throws IOException, SAXException, ParserConfigurationException {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;

    dBuilder = dbFactory.newDocumentBuilder();

    Document doc = dBuilder.parse(xml);
    doc.getDocumentElement().normalize();

    XPath xPath = XPathFactory.newInstance().newXPath();

    try {
        return (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new InvalidXPathException(expression, e);
    }
}
AndroidManifest.java 文件源码 项目:javaide 阅读 16 收藏 0 点赞 0 评论 0
private static String getStringValue(@NonNull IAbstractFile file, @NonNull String xPath)
        throws StreamException, XPathExpressionException {
    XPath xpath = AndroidXPathFactory.newXPath();

    InputStream is = null;
    try {
        is = file.getContents();
        return xpath.evaluate(xPath, new InputSource(is));
    } finally {
        try {
            Closeables.close(is, true /* swallowIOException */);
        } catch (IOException e) {
            // cannot happen
        }
    }
}
AbstractAfnemerindicatieVerzoekParser.java 文件源码 项目:OperatieBRP 阅读 16 收藏 0 点赞 0 评论 0
private Afnemerindicatie getAfnemerIndicatie(final XPath xPath, final Node node) {
    final Afnemerindicatie afnemerindicatie = new Afnemerindicatie();
    afnemerindicatie
            .setBsn(getNodeTextContent(getActieSpecifiekePrefix() + "/brp:persoon/brp:identificatienummers/brp:burgerservicenummer", xPath, node));
    afnemerindicatie.setPartijCode(
            getNodeTextContent(getActieSpecifiekePrefix() + "/brp:persoon/brp:afnemerindicaties/brp:afnemerindicatie/brp:partijCode", xPath, node));
    final String datumAanvangMaterielePeriode =
            getNodeTextContent(
                    getActieSpecifiekePrefix() + "/brp:persoon/brp:afnemerindicaties/brp:afnemerindicatie/brp:datumAanvangMaterielePeriode", xPath, node);
    if (datumAanvangMaterielePeriode != null) {
        afnemerindicatie
                .setDatumAanvangMaterielePeriode(datumAanvangMaterielePeriode);
    }
    final String datumEindeVolgen = getNodeTextContent(
            getActieSpecifiekePrefix() + "/brp:persoon/brp:afnemerindicaties/brp:afnemerindicatie/brp:datumEindeVolgen", xPath, node);
    if (datumEindeVolgen != null) {
        afnemerindicatie.setDatumEindeVolgen(datumEindeVolgen);
    }
    return afnemerindicatie;
}
AbstractDienstVerzoekParser.java 文件源码 项目:OperatieBRP 阅读 39 收藏 0 点赞 0 评论 0
/**
 * Hulpmethode om een xml fragment uit een node te halen middels xpath.
 * @param locatie de locatie van de node als xpath.
 * @param xPath een XPath instantie
 * @param node de basis node
 * @return de text
 */
protected static String getXmlFragment(final String locatie, final XPath xPath, final Node node) {
    try {
        final Node xPathNode = (Node) xPath.evaluate(locatie, node, XPathConstants.NODE);
        if (xPathNode != null) {
            final StringWriter buf = new StringWriter();
            final Transformer xform = TransformerFactory.newInstance().newTransformer();
            xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            xform.transform(new DOMSource(xPathNode), new StreamResult(buf));
            return buf.toString();
        }
    } catch (final XPathExpressionException | TransformerException e) {
        LOGGER.error("XPath voor text content kon niet worden geëvalueerd voor locatie {}.", locatie);
        throw new UnsupportedOperationException(e);
    }
    return null;
}
FetchDetailsToIndex.java 文件源码 项目:openmrs-contrib-addonindex 阅读 20 收藏 0 点赞 0 评论 0
private void handleRequireModules(AddOnVersion addOnVersion, XPath xpath, Document config)
        throws XPathExpressionException {
    NodeList nodeList = (NodeList) xpath.evaluate("/module/require_modules/require_module", config,
            XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node item = nodeList.item(i);
        Node version = item.getAttributes().getNamedItem("version");
        String requiredModule = item.getTextContent().trim();
        String requiredVersion = version == null ? null : version.getTextContent().trim();
        // sometimes modules are inadvertently uploaded without substituting maven variables in config.xml and we end
        // up with a required module version like ${reportingVersion}
        if (requiredVersion != null && requiredVersion.startsWith("${")) {
            requiredVersion = null;
        }
        addOnVersion.addRequiredModule(requiredModule, requiredVersion);
    }
}
SoapZephyrUtil.java 文件源码 项目:Cognizant-Intelligent-Test-Scripter 阅读 21 收藏 0 点赞 0 评论 0
public static String parseSOAPResponse(SOAPMessage soapResponse, String expression) {
    String retStr = null;
    try {
        final StringWriter writer = new StringWriter();
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(soapResponse.getSOAPPart()),
                new StreamResult(writer));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        ByteArrayInputStream stream = new ByteArrayInputStream(writer.toString().getBytes("UTF-8"));
        Document doc = builder.parse(stream);
        XPath xPath = XPathFactory.newInstance().newXPath();
        //String expression = "//return";
        NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
        for (int index = 0; index < nodeList.getLength(); index++) {
            org.w3c.dom.Node node = nodeList.item(index);
            retStr = node.getTextContent();
        }
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(SoapZephyrUtil.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        Logger.getLogger(SoapZephyrUtil.class.getName()).log(Level.SEVERE, null, e);
    }
    return retStr;
}
XpathUtils.java 文件源码 项目:ibm-cos-sdk-java 阅读 20 收藏 0 点赞 0 评论 0
/**
 * Evaluates the specified expression on the specified node and returns the
 * result as a String.
 *
 * @param expression
 *            The Xpath expression to evaluate.
 * @param node
 *            The node on which to evaluate the expression.
 *
 * @return The result of evaluating the specified expression, or null if the
 *         evaluation didn't return any result.
 *
 * @throws XPathExpressionException
 *             If there are any problems evaluating the Xpath expression.
 */
private static String evaluateAsString(String expression, Node node,
        XPath xpath) throws XPathExpressionException {
    if (isEmpty(node)) return null;

    if (!expression.equals(".")) {
        /*
         * If the expression being evaluated doesn't select a node, we want
         * to return null to distinguish between cases where a node isn't
         * present (which should be represented as null) and when a node is
         * present, but empty (which should be represented as the empty
         * string).
         *
         * We skip this test if the expression is "." since we've already
         * checked that the node exists.
         */
        if (asNode(expression, node, xpath) == null) return null;
    }

    String s = xpath.evaluate(expression, node);

    return s.trim();
}
CoordinatesUtil.java 文件源码 项目:C4SG-Obsolete 阅读 22 收藏 0 点赞 0 评论 0
/**@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;
  }
AbstractDienstVerzoekParser.java 文件源码 项目:OperatieBRP 阅读 18 收藏 0 点赞 0 评论 0
/**
 * Hulpmethode om de nodes uit een node te halen middels xpath.
 * @param locatie de locatie van de node als xpath.
 * @param xPath een XPath instantie
 * @param node de basis node
 * @return de text
 */
protected static NodeList getNodeList(final String locatie, final XPath xPath, final Node node) {
    try {
        return (NodeList) xPath.evaluate(locatie, node, XPathConstants.NODESET);
    } catch (final XPathExpressionException e) {
        LOGGER.error("XPath voor node list kon niet worden geëvalueerd voor locatie {}.", locatie);
        throw new UnsupportedOperationException(e);
    }
}
XpathUtilsTest.java 文件源码 项目:aws-sdk-java-v2 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void testIsEmpty() throws Exception {
    Document document = XpathUtils.documentFrom(DOCUMENT);
    XPath xpath = xpath();
    Node emptyNode = asNode("Foo/Fake", document, xpath);
    Node realNode = asNode("Foo/Count", document, xpath);

    assertTrue(isEmpty(emptyNode));
    assertFalse(isEmpty(realNode));
}
XpathUtilsTest.java 文件源码 项目:aws-sdk-java-v2 阅读 20 收藏 0 点赞 0 评论 0
@Test
public void testXmlDocumentWithNamespace() throws Exception {
    Document document = documentFrom(DOCUMENT_WITH_NAMESPACE);
    XPath xpath = xpath();
    Node root = asNode("/", document, xpath);
    assertNotNull(root);

    Node node = asNode("//AllocateAddressResponse", document, xpath);
    assertNotNull(node);
}
XpathUtilsTest.java 文件源码 项目:aws-sdk-java-v2 阅读 19 收藏 0 点赞 0 评论 0
/**
 * Tests that we can correctly pull a Byte out of an XML document.
 */
@Test
public void testAsByte() throws Exception {
    Document document = XpathUtils.documentFrom(DOCUMENT);
    XPath xpath = xpath();
    assertEquals(new Byte((byte) 123), asByte("Foo/PositiveByte", document, xpath));
    assertEquals(new Byte((byte) -99), asByte("Foo/NegativeByte", document, xpath));
    assertEquals(null, XpathUtils.asByte("Foo/Empty", document));
}
RatReportTask.java 文件源码 项目:incubator-netbeans 阅读 16 收藏 0 点赞 0 评论 0
private void doPopulateUnapproved(Map<String, ModuleInfo> moduleRATInfo, Element rootElement, XPath path) throws XPathExpressionException {
    NodeList evaluate = (NodeList) path.evaluate("descendant::resource[license-approval/@name=\"false\"]", rootElement, XPathConstants.NODESET);
    for (int i = 0; i < evaluate.getLength(); i++) {
        String resources = relativize(evaluate.item(i).getAttributes().getNamedItem("name").getTextContent());
        String moduleName = getModuleName(resources);
        if (!moduleRATInfo.containsKey(moduleName)) {
            moduleRATInfo.get(NOT_CLUSTER).addUnapproved(resources);
        } else {
            moduleRATInfo.get(moduleName).addUnapproved(resources);
        }
    }
}
Utilities.java 文件源码 项目:incubator-netbeans 阅读 17 收藏 0 点赞 0 评论 0
public static List<String> runXPathQuery(File parsedFile, String xpathExpr) throws Exception{
    List<String> result = new ArrayList<String>();
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(getNamespaceContext());

    InputSource inputSource = new InputSource(new FileInputStream(parsedFile));
    NodeList nodes = (NodeList) xpath.evaluate(xpathExpr, inputSource, XPathConstants.NODESET);
    if((nodes != null) && (nodes.getLength() > 0)){
        for(int i=0; i<nodes.getLength();i++){
            Node node = nodes.item(i);
            result.add(node.getNodeValue());
        }
    }
    return result;
}
Util.java 文件源码 项目:incubator-netbeans 阅读 22 收藏 0 点赞 0 评论 0
public static List runXPathQuery(File parsedFile, String xpathExpr) throws Exception{
    List result = new ArrayList();
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(getNamespaceContext());

    InputSource inputSource = new InputSource(new FileInputStream(parsedFile));
    NodeList nodes = (NodeList) xpath.evaluate(xpathExpr, inputSource, XPathConstants.NODESET);
    if((nodes != null) && (nodes.getLength() > 0)){
        for(int i=0; i<nodes.getLength();i++){
            org.w3c.dom.Node node = nodes.item(i);
            result.add(node.getNodeValue());
        }
    }
    return result;
}
Bug4991857.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void testXPath10() throws Exception {
    try {
        XPath xpath = xpathFactory.newXPath();
        Assert.assertNotNull(xpath);

        xpath.evaluate(".", d, XPathConstants.STRING);
        Assert.fail("XPathExpressionException not thrown");
    } catch (XPathExpressionException e) {
        // Expected exception as context node is null
    }
}
XpathUtilsTest.java 文件源码 项目:ibm-cos-sdk-java 阅读 20 收藏 0 点赞 0 评论 0
@Test
public void testXmlDocumentWithNamespace() throws Exception {
    Document document = documentFrom(DOCUMENT_WITH_NAMESPACE);
    XPath xpath = xpath();
    Node root = asNode("/", document, xpath);
    assertNotNull(root);

    Node node = asNode("//AllocateAddressResponse", document, xpath);
    assertNotNull(node);
}
Stands4AbbreviationExpansion.java 文件源码 项目:smaph 阅读 17 收藏 0 点赞 0 评论 0
/**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;
}


问题


面经


文章

微信
公众号

扫码关注公众号