javax.xml.xpath.XPath#setNamespaceContext ( )源码实例Demo

下面列出了javax.xml.xpath.XPath#setNamespaceContext ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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));
}
 
源代码2 项目: google-cloud-eclipse   文件: PomXmlValidator.java
/**
 * Selects all the <groupId> elements with value "com.google.appengine" whose <artifactId>
 * sibling has the value "appengine-maven-plugin" or "gcloud-maven-plugin".
 */
@Override
public ArrayList<ElementProblem> checkForProblems(IResource resource, Document document) {
  ArrayList<ElementProblem> problems = new ArrayList<>();
  try {
    XPath xPath = FACTORY.newXPath();
    NamespaceContext nsContext =
        new MappedNamespaceContext("prefix", "http://maven.apache.org/POM/4.0.0");
    xPath.setNamespaceContext(nsContext);
    String selectGroupId = "//prefix:plugin/prefix:groupId[.='com.google.appengine']"
        + "[../prefix:artifactId[text()='appengine-maven-plugin'"
        + " or text()='gcloud-maven-plugin']]";
    NodeList groupIdElements =
        (NodeList) xPath.compile(selectGroupId).evaluate(document, XPathConstants.NODESET);
    for (int i = 0; i < groupIdElements.getLength(); i++) {
      Node child = groupIdElements.item(i);
      DocumentLocation location = (DocumentLocation) child.getUserData("location");
      ElementProblem element = new MavenPluginElement(location, child.getTextContent().length());
      problems.add(element);
    }
  } catch (XPathExpressionException ex) {
    throw new RuntimeException("Invalid XPath expression");
  }
  return problems;
}
 
private static XPathExpression compileXpathExpression(String expression,
		@Nullable Map<String, String> namespaces) throws XPathExpressionException {

	SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
	namespaceContext.setBindings(namespaces != null ? namespaces : Collections.emptyMap());
	XPath xpath = XPathFactory.newInstance().newXPath();
	xpath.setNamespaceContext(namespaceContext);
	return xpath.compile(expression);
}
 
private String getTicket(String input) {
    try {
        XPath xPath = XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(new MapNamespaceContext(Collections.singletonMap("samlp", "urn:oasis:names:tc:SAML:1.0:protocol")));

        XPathExpression expression = xPath.compile("//samlp:AssertionArtifact/text()");

        return expression.evaluate(new InputSource(new StringReader(input)));
    } catch (XPathExpressionException ex) {
        throw new CASValidationException(CASErrorCode.INVALID_TICKET, ex.getMessage(), Response.Status.BAD_REQUEST);
    }
}
 
源代码5 项目: rice   文件: XmlSchemaTest.java
/**
 * Tests that default attribute value is visible to XPath from a schema-validated W3C Document
 * TODO: finish this test when we figure out how to conveniently use namespaces with
 * XPath
 */
@Test public void testDefaultAttributeValue() throws Exception {
    URL url = getClass().getResource("XmlConfig.xml");
    Document d = validate(url.openStream());
    //d = XmlHelper.trimXml(url.openStream());
    System.out.println(XmlJotter.jotNode(d));
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new WorkflowNamespaceContext());
    Node node = (Node) xpath.evaluate("/data/ruleAttributes/ruleAttribute[name='XMLSearchableAttribute']/searchingConfig/fieldDef[@name='givenname' and @workflowType='ALL']/@title",
            d, XPathConstants.NODE);
    System.out.println("n: " + node);
    //System.out.println("n: " + node.getNodeName());
    //System.out.println("n: " + node.getLocalName());
    //System.out.println("n: " + node.getNamespaceURI());
}
 
源代码6 项目: sierra-ecg-tools   文件: SierraEcgTransformer.java
public static SierraEcgTransformer create(File input) throws IOException, JAXBException, XPathExpressionException, ParserConfigurationException, SAXException {
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(true);
	DocumentBuilder builder = factory.newDocumentBuilder();

	Document xdoc = builder.parse(input);
	xdoc.getDocumentElement().normalize();

	XPath xpath = XPathFactory.newInstance().newXPath();
	xpath.setNamespaceContext(new UniversalNamespaceCache(xdoc, true));

	Node node = (Node)xpath.evaluate("//DEFAULT:documentversion",
		xdoc, XPathConstants.NODE);
	if (node != null) {
		String version = node.getTextContent();
		if (version.equals("1.03")) {
			return new SierraEcgTransformerImpl_1_03(xdoc.getDocumentElement());
		}
		else if (version.equals("1.04")) {
			return new SierraEcgTransformerImpl_1_04(xdoc.getDocumentElement());
		}
		else if (version.equals("1.04.01")) {
			return new SierraEcgTransformerImpl_1_04(xdoc.getDocumentElement());
		}
		else {
			throw new UnsupportedOperationException("Unsupported Sierra ECG XML file " + node.getTextContent());
		}
	}

	throw new UnsupportedOperationException("File does not appear to be a valid Sierra ECG XML file");
}
 
源代码7 项目: rice   文件: XPathTest.java
@Test
public void testXPathWithValidatedDOMDocNamespace() throws Exception {
    LOG.debug("TEST");
    Document doc = getDocument(true, true);
    LOG.info("Default namespace: " + doc.lookupNamespaceURI(null));
    LOG.info("default prefix: " + doc.lookupPrefix(doc.lookupNamespaceURI(null)));
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(Util.getNotificationNamespaceContext(doc));
    String channelName = (String) xpath.evaluate("/nreq:notification/nreq:channel", doc.getDocumentElement(), XPathConstants.STRING);
    assertEquals("Test Channel #1", channelName);
}
 
源代码8 项目: rice   文件: WorkflowUtils.java
/**
 *
 * This method sets up the XPath with the correct workflow namespace and resolver initialized. This ensures that the XPath
 * statements can use required workflow functions as part of the XPath statements.
 *
 * @param document - document
 * @return a fully initialized XPath instance that has access to the workflow resolver and namespace.
 *
 */
public final static XPath getXPath(Document document) {
    XPath xpath = getXPath(RouteContext.getCurrentRouteContext());
    xpath.setNamespaceContext(new WorkflowNamespaceContext());
    WorkflowFunctionResolver resolver = new WorkflowFunctionResolver();
    resolver.setXpath(xpath);
    resolver.setRootNode(document);
    xpath.setXPathFunctionResolver(resolver);
    return xpath;
}
 
源代码9 项目: proarc   文件: CejshBuilderTest.java
@Test
    public void testCreateCejshXml_TitleVolumeIssue() throws Exception {
        CejshConfig conf = new CejshConfig();
        CejshBuilder cb = new CejshBuilder(conf, appConfig.getExportOptions());
        Document articleDoc = cb.getDocumentBuilder().parse(CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
        // issn must match some cejsh_journals.xml/cejsh/journal[@issn=$issn]
        final String pkgIssn = "0231-5955";
        Issue issue = new Issue();
        issue.setIssn(pkgIssn);
        issue.setIssueId("uuid-issue");
        issue.setIssueNumber("issue1");
        Volume volume = new Volume();
        volume.setVolumeId("uuid-volume");
        volume.setVolumeNumber("volume1");
        volume.setYear("1985");
        Article article = new Article(null, articleDoc.getDocumentElement(), null);
        cb.setIssue(issue);
        cb.setVolume(volume);

        Document articleCollectionDoc = cb.mergeElements(Collections.singletonList(article));
        DOMSource cejshSource = new DOMSource(articleCollectionDoc);
        DOMResult cejshResult = new DOMResult();
//        dump(cejshSource);

        TransformErrorListener xslError = cb.createCejshXml(cejshSource, cejshResult);
        assertEquals(Collections.emptyList(), xslError.getErrors());
        final Node cejshRootNode = cejshResult.getNode();
//        dump(new DOMSource(cejshRootNode));

        List<String> errors = cb.validateCejshXml(new DOMSource(cejshRootNode));
        assertEquals(Collections.emptyList(), errors);

        XPath xpath = ProarcXmlUtils.defaultXPathFactory().newXPath();
        xpath.setNamespaceContext(new SimpleNamespaceContext().add("b", CejshBuilder.NS_BWMETA105));
        assertNotNull(xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.ebfd7bf2-169d-476e-a230-0cc39f01764c']", cejshRootNode, XPathConstants.NODE));
        assertEquals("volume1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-volume']/b:name", cejshRootNode, XPathConstants.STRING));
        assertEquals("issue1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-issue']/b:name", cejshRootNode, XPathConstants.STRING));
        assertEquals("1985", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.9358223b-b135-388f-a71e-24ac2c8422c7-1985']/b:name", cejshRootNode, XPathConstants.STRING));
    }
 
源代码10 项目: jdk8u60   文件: XPathExFuncTest.java
void evaluate(boolean enableExt) throws XPathFactoryConfigurationException, XPathExpressionException {
    Document document = getDocument();

    XPathFactory xPathFactory = XPathFactory.newInstance();
    /**
     * Use of the extension function 'http://exslt.org/strings:tokenize' is
     * not allowed when the secure processing feature is set to true.
     * Attempt to use the new property to enable extension function
     */
    if (enableExt) {
        boolean isExtensionSupported = enableExtensionFunction(xPathFactory);
    }

    xPathFactory.setXPathFunctionResolver(new MyXPathFunctionResolver());
    if (System.getSecurityManager() == null) {
        xPathFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
    }

    XPath xPath = xPathFactory.newXPath();
    xPath.setNamespaceContext(new MyNamespaceContext());

    String xPathResult = xPath.evaluate(XPATH_EXPRESSION, document);
    System.out.println(
            "XPath result (enableExtensionFunction == " + enableExt + ") = \""
            + xPathResult
            + "\"");
}
 
源代码11 项目: dss   文件: DomUtils.java
/**
 * This method creates a new instance of XPathExpression with the given xpath
 * expression
 * 
 * @param xpathString
 *                    XPath query string
 * @return an instance of {@code XPathExpression} for the given xpathString @ if
 */
public static XPathExpression createXPathExpression(final String xpathString) {
	final XPath xpath = factory.newXPath();
	xpath.setNamespaceContext(namespacePrefixMapper);
	try {
		return xpath.compile(xpathString);
	} catch (XPathExpressionException ex) {
		throw new DSSException(ex);
	}
}
 
源代码12 项目: excel-streaming-reader   文件: XmlUtils.java
public static NodeList searchForNodeList(Document document, String xpath) {
  try {
    XPath xp = XPathFactory.newInstance().newXPath();
    NamespaceContextImpl nc = new NamespaceContextImpl();
    nc.addNamespace("ss", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
    xp.setNamespaceContext(nc);
    return (NodeList)xp.compile(xpath)
            .evaluate(document, XPathConstants.NODESET);
  } catch(XPathExpressionException e) {
    throw new ParseException(e);
  }
}
 
protected Map<String, DiagramNode> fixFlowNodePositionsIfModelFromAdonis(Document bpmnModel, Map<String, DiagramNode> elementBoundsFromBpmnDi) {
  if (isExportedFromAdonis50(bpmnModel)) {
    Map<String, DiagramNode> mapOfFixedBounds = new HashMap<String, DiagramNode>();
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    xPath.setNamespaceContext(new Bpmn20NamespaceContext());
    for (Entry<String, DiagramNode> entry : elementBoundsFromBpmnDi.entrySet()) {
      String elementId = entry.getKey();
      DiagramNode elementBounds = entry.getValue();
      String expression = "local-name(//bpmn:*[@id = '" + elementId + "'])";
      try {
        XPathExpression xPathExpression = xPath.compile(expression);
        String elementLocalName = xPathExpression.evaluate(bpmnModel);
        if (!"participant".equals(elementLocalName) && !"lane".equals(elementLocalName) && !"textAnnotation".equals(elementLocalName) && !"group".equals(elementLocalName)) {
          elementBounds.setX(elementBounds.getX() - elementBounds.getWidth() / 2);
          elementBounds.setY(elementBounds.getY() - elementBounds.getHeight() / 2);
        }
      } catch (XPathExpressionException e) {
        throw new ActivitiException("Error while evaluating the following XPath expression on a BPMN XML document: '" + expression + "'.", e);
      }
      mapOfFixedBounds.put(elementId, elementBounds);
    }
    return mapOfFixedBounds;
  } else {
    return elementBoundsFromBpmnDi;
  }
}
 
源代码14 项目: netbeans   文件: Utilities.java
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;
}
 
源代码15 项目: buck   文件: AndroidXPathFactory.java
/**
 * Creates a new XPath object using the default prefix for the android namespace.
 * @see #DEFAULT_NS_PREFIX
 */
public static XPath newXPath() {
    XPath xpath = sFactory.newXPath();
    xpath.setNamespaceContext(AndroidNamespaceContext.getDefault());
    return xpath;
}
 
源代码16 项目: cs-actions   文件: XmlUtils.java
public static XPathExpression createXPathExpression(NamespaceContext context, String xPathQuery) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(context);
    return xpath.compile(xPathQuery);
}
 
源代码17 项目: steady   文件: AbstractPolicySecurityTest.java
protected void verifySignatureAlgorithms(Document signedDoc, AssertionInfoMap aim) throws Exception { 
    final AssertionInfo assertInfo = aim.get(SP12Constants.ASYMMETRIC_BINDING).iterator().next();
    assertNotNull(assertInfo);
    
    final AsymmetricBinding binding = (AsymmetricBinding) assertInfo.getAssertion();
    final String expectedSignatureMethod = binding.getAlgorithmSuite().getAsymmetricSignature();
    final String expectedDigestAlgorithm = binding.getAlgorithmSuite().getDigest();
    final String expectedCanonAlgorithm  = binding.getAlgorithmSuite().getInclusiveC14n();
        
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    final NamespaceContext nsContext = this.getNamespaceContext();
    xpath.setNamespaceContext(nsContext);
    
    // Signature Algorithm
    final XPathExpression sigAlgoExpr = 
        xpath.compile("/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo" 
                          + "/ds:SignatureMethod/@Algorithm");
    
    final String sigMethod =  (String) sigAlgoExpr.evaluate(signedDoc, XPathConstants.STRING);
    assertEquals(expectedSignatureMethod, sigMethod);
    
    // Digest Method Algorithm
    final XPathExpression digestAlgoExpr = xpath.compile(
        "/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestMethod");
    
    final NodeList digestMethodNodes = 
        (NodeList) digestAlgoExpr.evaluate(signedDoc, XPathConstants.NODESET);
    
    for (int i = 0; i < digestMethodNodes.getLength(); i++) {
        Node node = (Node)digestMethodNodes.item(i);
        String digestAlgorithm = node.getAttributes().getNamedItem("Algorithm").getNodeValue();
        assertEquals(expectedDigestAlgorithm, digestAlgorithm);
    }
    
    // Canonicalization Algorithm
    final XPathExpression canonAlgoExpr =
        xpath.compile("/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo" 
                          + "/ds:CanonicalizationMethod/@Algorithm");
    final String canonMethod =  (String) canonAlgoExpr.evaluate(signedDoc, XPathConstants.STRING);
    assertEquals(expectedCanonAlgorithm, canonMethod);
}
 
源代码18 项目: javaide   文件: AndroidXPathFactory.java
/**
 * Creates a new XPath object using the default prefix for the android namespace.
 * @see #DEFAULT_NS_PREFIX
 */
public static XPath newXPath() {
    XPath xpath = sFactory.newXPath();
    xpath.setNamespaceContext(AndroidNamespaceContext.getDefault());
    return xpath;
}
 
源代码19 项目: steady   文件: CryptoCoverageUtil.java
/**
 * Checks that the references provided refer to the required
 * signed/encrypted elements as defined by the XPath expressions in {@code
 * xPaths}.
 * 
 * @param soapEnvelope
 *            the SOAP Envelope element
 * @param refs
 *            the refs to the data extracted from the signature/encryption
 * @param namespaces
 *            the prefix to namespace mapping, may be {@code null}
 * @param xPaths
 *            the collection of XPath expressions
 * @param type
 *            the type of cryptographic coverage to check for
 * @param scope
 *            the scope of the cryptographic coverage to check for, defaults
 *            to element
 * 
 * @throws WSSecurityException
 *             if there is an error evaluating an XPath or an element is not
 *             covered by the signature/encryption.
 */
public static void checkCoverage(
        Element soapEnvelope,
        final Collection<WSDataRef> refs,
        Map<String, String> namespaces,
        Collection<String> xPaths,
        CoverageType type,
        CoverageScope scope) throws WSSecurityException {
    
    // XPathFactory and XPath are not thread-safe so we must recreate them
    // each request.
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    
    if (namespaces != null) {
        xpath.setNamespaceContext(new MapNamespaceContext(namespaces));
    }
    
    checkCoverage(soapEnvelope, refs, xpath, xPaths, type, scope);
}
 
/**
 * Check a particular XPath result
 */
private boolean checkXPathResult(
    Element soapEnvelope,
    String xPath,
    Map<String, String> namespaces,
    List<WSSecurityEngineResult> protResults,
    List<WSSecurityEngineResult> tokenResults
) {
    // XPathFactory and XPath are not thread-safe so we must recreate them
    // each request.
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    
    if (namespaces != null) {
        xpath.setNamespaceContext(new MapNamespaceContext(namespaces));
    }
    
    // For each XPath
    for (String xpathString : Arrays.asList(xPath)) {
        // Get the matching nodes
        NodeList list;
        try {
            list = (NodeList)xpath.evaluate(
                    xpathString, 
                    soapEnvelope,
                    XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            LOG.log(Level.FINE, e.getMessage(), e);
            return false;
        }
        
        // If we found nodes then we need to do the check.
        if (list.getLength() != 0) {
            // For each matching element, check for a ref that
            // covers it.
            for (int x = 0; x < list.getLength(); x++) {
                final Element el = (Element)list.item(x);
                
                if (!checkProtectionResult(el, false, protResults, tokenResults)) {
                    return false;
                }
            }
        }
    }
    return true;
}