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

XmlFactory.java 文件源码 项目:openjdk-jdk10 阅读 34 收藏 0 点赞 0 评论 0
/**
 * Returns properly configured (e.g. security features) factory
 * - securityProcessing == is set based on security processing property, default is true
 */
public static XPathFactory createXPathFactory(boolean disableSecureProcessing) throws IllegalStateException {
    try {
        XPathFactory factory = XPathFactory.newInstance();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "XPathFactory instance: {0}", factory);
        }
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
        return factory;
    } catch (XPathFactoryConfigurationException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new IllegalStateException( ex);
    } catch (AbstractMethodError er) {
        LOGGER.log(Level.SEVERE, null, er);
        throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er);
    }
}
JFXProjectUtils.java 文件源码 项目:incubator-netbeans 阅读 27 收藏 0 点赞 0 评论 0
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;
}
ModuleProjectClassPathExtenderTest.java 文件源码 项目:incubator-netbeans 阅读 18 收藏 0 点赞 0 评论 0
public void testAddLibraries() throws Exception {
    SuiteProject suite = TestBase.generateSuite(getWorkDir(), "suite");
    TestBase.generateSuiteComponent(suite, "lib");
    TestBase.generateSuiteComponent(suite, "testlib");
    NbModuleProject clientprj = TestBase.generateSuiteComponent(suite, "client");
    Library lib = LibraryFactory.createLibrary(new LibImpl("lib"));
    FileObject src = clientprj.getSourceDirectory();
    assertTrue(ProjectClassPathModifier.addLibraries(new Library[] {lib}, src, ClassPath.COMPILE));
    assertFalse(ProjectClassPathModifier.addLibraries(new Library[] {lib}, src, ClassPath.COMPILE));
    Library testlib = LibraryFactory.createLibrary(new LibImpl("testlib"));
    FileObject testsrc = clientprj.getTestSourceDirectory("unit");
    assertTrue(ProjectClassPathModifier.addLibraries(new Library[] {testlib}, testsrc, ClassPath.COMPILE));
    assertFalse(ProjectClassPathModifier.addLibraries(new Library[] {testlib}, testsrc, ClassPath.COMPILE));
    InputSource input = new InputSource(clientprj.getProjectDirectory().getFileObject("nbproject/project.xml").toURL().toString());
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(nbmNamespaceContext());
    assertEquals("org.example.client", xpath.evaluate("//nbm:data/nbm:code-name-base", input)); // control
    assertEquals("org.example.lib", xpath.evaluate("//nbm:module-dependencies/*/nbm:code-name-base", input));
    assertEquals("org.example.testlib", xpath.evaluate("//nbm:test-dependencies/*/*/nbm:code-name-base", input));
}
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));
}
Generator.java 文件源码 项目:jpms-module-names 阅读 22 收藏 0 点赞 0 评论 0
/** Extract specific POM-related values from a XML-String into a map. */
Map<String, String> mapPom(String pom) {
  try {
    var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    var document = builder.parse(new InputSource(new StringReader(pom)));
    var xpath = XPathFactory.newInstance().newXPath();
    var name = xpath.evaluate("/project/name", document);
    var url = xpath.evaluate("/project/url", document);
    var group = xpath.evaluate("/project/groupId", document);
    var artifact = xpath.evaluate("/project/artifactId", document);
    var version = xpath.evaluate("/project/version", document);
    if (group.isEmpty()) {
      group = xpath.evaluate("/project/parent/groupId", document);
    }
    if (version.isEmpty()) {
      version = xpath.evaluate("/project/parent/version", document);
    }
    return Map.of(
        "name", name, "url", url, "group", group, "artifact", artifact, "version", version);
  } catch (Exception e) {
    debug("scan({0}) failed: {0}", pom, e);
  }
  return Map.of();
}
Bug7143711Test.java 文件源码 项目:openjdk-jdk10 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void testXPath_DOM_withSM() {
    System.out.println("Evaluate DOM Source;  Security Manager is set:");
    setSystemProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");

    try {
        XPathFactory xPathFactory = XPathFactory.newInstance("http://java.sun.com/jaxp/xpath/dom",
                "com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl", null);
        xPathFactory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, true);
        if ((boolean) xPathFactory.getFeature(ORACLE_FEATURE_SERVICE_MECHANISM)) {
            Assert.fail("should not override in secure mode");
        }

    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        clearSystemProperty(DOM_FACTORY_ID);
    }
}
Bug4991939.java 文件源码 项目:openjdk-jdk10 阅读 16 收藏 0 点赞 0 评论 0
@Test
public void testXPath13() throws Exception {
    QName qname = new QName(XMLConstants.XML_NS_URI, "");

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

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

    try {
        xpath.evaluate("1+1", (Object) null, qname);
        Assert.fail("failed , expected IAE not thrown");
    } catch (IllegalArgumentException e) {
        ; // as expected
    }
}
Pom.java 文件源码 项目:nbreleaseplugin 阅读 18 收藏 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);
    }
}
XPathMetadataExtracter.java 文件源码 项目:alfresco-repository 阅读 18 收藏 0 点赞 0 评论 0
/**
 * Default constructor
 */
public XPathMetadataExtracter()
{
    super(new HashSet<String>(Arrays.asList(SUPPORTED_MIMETYPES)));
    try
    {
        DocumentBuilderFactory normalFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = normalFactory.newDocumentBuilder();

        DocumentBuilderFactory dtdIgnoringFactory = DocumentBuilderFactory.newInstance();
        dtdIgnoringFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        dtdIgnoringFactory.setFeature("http://xml.org/sax/features/validation", false);
        dtdIgnoringDocumentBuilder = dtdIgnoringFactory.newDocumentBuilder();

        xpathFactory = XPathFactory.newInstance();
    }
    catch (Throwable e)
    {
        throw new AlfrescoRuntimeException("Failed to initialize XML metadata extractor", e);
    }
}
XPathCondition.java 文件源码 项目:oscm 阅读 23 收藏 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();
}
WebserviceSAMLSPTestSetup.java 文件源码 项目:oscm 阅读 17 收藏 0 点赞 0 评论 0
private void setJKSLocation(String domainPath) {
    URL fileUrl = Thread.currentThread().getContextClassLoader()
            .getResource(STSConfigTemplateFileName);

    File file = new File(fileUrl.getFile());
    if (!file.exists()) {
        System.out.println("MockSTSServiceTemplate.xml not exists");
        return;
    }
    try {
        Document doc = parse(file);
        XPathFactory xpfactory = XPathFactory.newInstance();
        XPath path = xpfactory.newXPath();
        updateElementValue(path, doc,
                "/definitions/Policy/ExactlyOne/All/KeyStore", "location",
                domainPath + "/config/keystore.jks");
        updateElementValue(path, doc,
                "/definitions/Policy/ExactlyOne/All/TrustStore",
                "location", domainPath + "/config/cacerts.jks");
        doc2Xml(doc);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
SoapMessageManager.java 文件源码 项目:verify-matching-service-adapter 阅读 17 收藏 0 点赞 0 评论 0
private Element unwrapSoapMessage(Element soapElement, SamlElementType samlElementType) {
    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 {
        String expression = "//samlp:" + samlElementType.getElementName();
        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,
                    XmlUtils.writeToString(soapElement), expression);
            LOG.error(errorMessage);
            throw new SoapUnwrappingException(errorMessage);
        }

        return element;
    } catch (XPathExpressionException e) {
        throw propagate(e);
    }
}
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);
        }
    }
}
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);
    }
}
EvaluationUtils.java 文件源码 项目:trust-java 阅读 23 收藏 0 点赞 0 评论 0
/**
 * Evaluates provided XPath expression into the {@link String}
 *
 * @param evalExpression Expression to evaluate
 * @param xmlSource XML source
 * @return Evaluation result
 */
public static String evaluateXPathToString(String evalExpression,
                                           String xmlSource) {
    try {
        return XPathFactory.
                newInstance().
                newXPath().
                evaluate(
                        evalExpression,
                        DocumentBuilderFactory.
                                newInstance().
                                newDocumentBuilder().
                                parse(new InputSource(
                                        new StringReader(
                                                xmlSource))));
    } catch (Exception e) {
        LOG.warning(COMMON_EVAL_ERROR_MESSAGE);
    }

    return EMPTY;
}
DomXmlUtils.java 文件源码 项目:DAFramework 阅读 23 收藏 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;
        }
    };
}
XmlFactory.java 文件源码 项目:OpenJSharp 阅读 22 收藏 0 点赞 0 评论 0
/**
 * Returns properly configured (e.g. security features) factory
 * - securityProcessing == is set based on security processing property, default is true
 */
public static XPathFactory createXPathFactory(boolean disableSecureProcessing) throws IllegalStateException {
    try {
        XPathFactory factory = XPathFactory.newInstance();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "XPathFactory instance: {0}", factory);
        }
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
        return factory;
    } catch (XPathFactoryConfigurationException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new IllegalStateException( ex);
    } catch (AbstractMethodError er) {
        LOGGER.log(Level.SEVERE, null, er);
        throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er);
    }
}
DOCXMergeEngine.java 文件源码 项目:doctemplate 阅读 18 收藏 0 点赞 0 评论 0
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;
    }
TransformationHelper.java 文件源码 项目:jaffa-framework 阅读 19 收藏 0 点赞 0 评论 0
/**
 * @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;
    }
}
SoapMessageManagerTest.java 文件源码 项目:verify-matching-service-adapter 阅读 20 收藏 0 点赞 0 评论 0
private Element getAttributeQuery(Document document) throws XPathExpressionException {
    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");
    xpath.setNamespaceContext(context);

    return (Element) xpath.evaluate("//samlp:Response", document, XPathConstants.NODE);
}
XPathTestBase.java 文件源码 项目:openjdk-jdk10 阅读 20 收藏 0 点赞 0 评论 0
@DataProvider(name = "document")
public Object[][] getDocument() throws Exception {
    DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
    dBF.setValidating(false);
    dBF.setNamespaceAware(true);
    Document doc = dBF.newDocumentBuilder().parse(
            new ByteArrayInputStream(rawXML.getBytes("UTF-8")));

    return new Object[][]{{XPathFactory.newInstance().newXPath(), doc}};
}
XmlUtil.java 文件源码 项目:openjdk-jdk10 阅读 26 收藏 0 点赞 0 评论 0
public static XPathFactory newXPathFactory(boolean disableSecurity) {
    XPathFactory factory = XPathFactory.newInstance();
    try {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !xmlSecurityDisabled(disableSecurity));
    } catch (XPathFactoryConfigurationException e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } );
    }
    return factory;
}
Util.java 文件源码 项目:incubator-netbeans 阅读 19 收藏 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;
}
Bug4992805.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
private XPath createXPath() throws XPathFactoryConfigurationException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    Assert.assertNotNull(xpathFactory);
    XPath xpath = xpathFactory.newXPath();
    Assert.assertNotNull(xpath);
    return xpath;
}
XPathExFuncTest.java 文件源码 项目:openjdk-jdk10 阅读 24 收藏 0 点赞 0 评论 0
boolean enableExtensionFunction(XPathFactory factory) {
    boolean isSupported = true;
    try {
        factory.setFeature(ENABLE_EXTENSION_FUNCTIONS, true);
    } catch (XPathFactoryConfigurationException ex) {
        isSupported = false;
    }
    return isSupported;
}
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;
}
Pom.java 文件源码 项目:nbreleaseplugin 阅读 22 收藏 0 点赞 0 评论 0
private Element findElement(ElementValue pev, String path) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        return (Element) xpath.evaluate(path, pev.getElement(), XPathConstants.NODE);
    } catch (XPathExpressionException ex) {
        return null;
    }
}
EasyTravelScenarioService.java 文件源码 项目:playground-scenario-generator 阅读 19 收藏 0 点赞 0 评论 0
public EasyTravelScenarioService(RestTemplate restTemplate, EasyTravelConfigurationProperties conf) {
    this.restTemplate = restTemplate;
    this.xPathFactory = XPathFactory.newInstance();
    this.documentBuilderFactory = DocumentBuilderFactory.newInstance();

    this.apiUrl = conf.getApiUrl();
    this.availableScenarioConfigsMap = conf.getAvailableScenarios().stream().collect(Collectors.toMap(ScenarioConfigProperty::getId, sc -> sc));
    this.availableScenarioNames = conf.getAvailableScenarioNames();
}
SoapMessageManagerTest.java 文件源码 项目:verify-hub 阅读 20 收藏 0 点赞 0 评论 0
private Element getAttributeQuery(Document document) throws XPathExpressionException {
    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");
    xpath.setNamespaceContext(context);

    return (Element) xpath.evaluate("//samlp:Response", document, XPathConstants.NODE);
}
XPathConfigurerAdapter.java 文件源码 项目:fluentxml4j 阅读 23 收藏 0 点赞 0 评论 0
public XPath getXPath(NamespaceContext namespaceContext)
{
    XPathFactory xPathFactory = buildXPathFactory();
    configure(xPathFactory);
    XPath xPath = buildXPath(xPathFactory);
    configure(xPath, namespaceContext);
    return xPath;
}


问题


面经


文章

微信
公众号

扫码关注公众号