Java Code Examples for org.w3c.dom.Document#getElementsByTagNameNS()

The following examples show how to use org.w3c.dom.Document#getElementsByTagNameNS() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Unmarshalls the provided artifact specific content.
 *
 * @param doc to unmarshall.
 * @return DataAssign object.
 */
private DataAssign unmarshall(final Document doc) {

    final NodeList nodeList =
        doc.getElementsByTagNameNS("http://www.siengine.restplugin.org/SpecificContentRestSchema", "DataAssign");

    final Node node = nodeList.item(0);
    try {
        final JAXBContext jc = JAXBContext.newInstance("org.opentosca.bus.management.plugins.rest.service.impl.model");
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        final DataAssign dataAssign = (DataAssign) unmarshaller.unmarshal(node);

        LOG.debug("Artifact specific content successfully unmarshalled.");
        return dataAssign;
    } catch (final JAXBException e) {
        LOG.warn("Couldn't unmarshall provided artifact specific content!");
        e.printStackTrace();
    }
    LOG.debug("No unmarshallable artifact specific content provided. Using default values now.");
    return null;
}
 
Example 2
protected Map<String, DiagramNode> getElementBoundsFromBpmnDi(Document bpmnModel) {
    Map<String, DiagramNode> listOfBounds = new HashMap<>();
    // iterate over all DI shapes
    NodeList shapes = bpmnModel.getElementsByTagNameNS(BpmnParser.BPMN_DI_NS, "BPMNShape");
    for (int i = 0; i < shapes.getLength(); i++) {
        Element shape = (Element) shapes.item(i);
        String bpmnElementId = shape.getAttribute("bpmnElement");
        // get bounds of shape
        NodeList childNodes = shape.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {
            Node childNode = childNodes.item(j);
            if (childNode instanceof Element && BpmnParser.BPMN_DC_NS.equals(childNode.getNamespaceURI()) && "Bounds".equals(childNode.getLocalName())) {
                DiagramNode bounds = parseBounds((Element) childNode);
                bounds.setId(bpmnElementId);
                listOfBounds.put(bpmnElementId, bounds);
                break;
            }
        }
    }
    return listOfBounds;
}
 
Example 3
private static byte[] encrypt(Document doc, Crypto crypto, String detailId, String projectName) throws TechnicalConnectorException, TransformerException, UnsupportedEncodingException {
   NodeList nodes = doc.getElementsByTagNameNS("urn:be:cin:encrypted", "EncryptedKnownContent");
   String content = toStringOmittingXmlDeclaration(nodes);
   SignatureBuilder builder = SignatureBuilderFactory.getSignatureBuilder(AdvancedElectronicSignatureEnumeration.XAdES);
   Map<String, Object> options = new HashMap();
   List<String> tranforms = new ArrayList();
   tranforms.add("http://www.w3.org/2000/09/xmldsig#base64");
   tranforms.add("urn:nippin:xml:sig:transform:optional-deflate");
   options.put("transformerList", tranforms);
   options.put("baseURI", detailId);
   EncryptedKnownContent encryptedKnownContent = (EncryptedKnownContent)ConnectorXmlUtils.toObject(content.getBytes("UTF-8"), EncryptedKnownContent.class);
   encryptedKnownContent.getBusinessContent().setValue(ConnectorIOUtils.compress(encryptedKnownContent.getBusinessContent().getValue(), "deflate"));
   byte[] xades = builder.sign(Session.getInstance().getSession().getEncryptionCredential(), ConnectorXmlUtils.toByteArray((Object)encryptedKnownContent.getBusinessContent()), options);
   encryptedKnownContent.setXades(xades);
   return seal(crypto, ConnectorXmlUtils.toByteArray((Object)encryptedKnownContent), projectName);
}
 
Example 4
public Result validate ( final Document doc ) throws Exception
{
    final NodeList nl = doc.getElementsByTagNameNS ( XMLSignature.XMLNS, "Signature" ); //$NON-NLS-1$

    if ( nl.getLength () == 0 )
    {
        return new Result ( StatusCodes.VALIDATE_NO_SIGNATURE_DATA, "No signature data found" );
    }

    final DOMValidateContext dvc = new DOMValidateContext ( this.keySelector, nl.item ( 0 ) );

    final XMLSignature signature = this.factory.unmarshalXMLSignature ( dvc );

    try
    {
        final boolean result = signature.validate ( dvc );

        return new Result ( result, signature );
    }
    catch ( final XMLSignatureException e )
    {
        logger.debug ( "Failed to perform validation", e );
        return Result.INVALID;
    }
}
 
Example 5
public static byte[] encrypt(Document doc, Crypto crypto, String detailId) throws TechnicalConnectorException, TransformerException, UnsupportedEncodingException {
   NodeList nodes = doc.getElementsByTagNameNS("urn:be:cin:encrypted", "EncryptedKnownContent");
   String content = toStringOmittingXmlDeclaration(nodes);
   SignatureBuilder builder = SignatureBuilderFactory.getSignatureBuilder(AdvancedElectronicSignatureEnumeration.XAdES);
   Map<String, Object> options = new HashMap();
   List<String> tranforms = new ArrayList();
   tranforms.add("http://www.w3.org/2000/09/xmldsig#base64");
   tranforms.add("http://www.w3.org/2001/10/xml-exc-c14n#");
   options.put("transformerList", tranforms);
   options.put("baseURI", detailId);
   options.put("encapsulate", true);
   options.put("encapsulate-transformer", new EncapsulationTransformer() {
      public Node transform(Node signature) {
         Element result = signature.getOwnerDocument().createElementNS("urn:be:cin:encrypted", "Xades");
         result.setTextContent(Base64.encodeBase64String(ConnectorXmlUtils.toByteArray(signature)));
         return result;
      }
   });
   byte[] encryptedKnowContent = builder.sign(Session.getInstance().getSession().getEncryptionCredential(), content.getBytes("UTF-8"), options);
   return seal(crypto, encryptedKnowContent);
}
 
Example 6
Source Project: io   File: AbstractCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 名前空間を指定してDOMから要素を取得する.
 * @param doc Documentオブジェクト
 * @param name 取得する要素名
 * @param ns 名前空間名
 * @return 取得したNodeオブジェクト
 */
private Node getElementByTagNameNS(final Document doc, final String name, final String ns) {
    NodeList nl = doc.getElementsByTagNameNS(ns, name);
    if (nl.getLength() > 0) {
        return nl.item(0);
    } else {
        return null;
    }
}
 
Example 7
private void receivePermissionsImpl(Document document) {
  DocumentPermissions permissions = getPermissions();
  permissions.clear();

  if (document == null)
    return;

  NodeList permissionsIn = document.getElementsByTagNameNS(REST_API_NS, "permission");
  int permissionsInLength = permissionsIn.getLength();
  for (int i=0; i < permissionsInLength; i++) {
    String roleName = null;
    Set<Capability> caps = new HashSet<>();

    NodeList children = permissionsIn.item(i).getChildNodes();
    for (int j=0; j < children.getLength(); j++) {
      Node node = children.item(j);
      if (node.getNodeType() != Node.ELEMENT_NODE)
        continue;
      Element element = (Element) node;

      if ("role-name".equals(element.getLocalName()))
        roleName = element.getTextContent();
      else if ("capability".equals(element.getLocalName()))
        caps.add(Capability.getValueOf(element.getTextContent()));
      else if (logger.isWarnEnabled())
        logger.warn("Skipping unknown permission element", element.getTagName());
    }

    if (roleName == null || caps.size() == 0) {
      if (logger.isWarnEnabled())
        logger.warn("Could not parse permission");
      continue;
    }

    permissions.put(roleName, caps);
  }
}
 
Example 8
Source Project: google-cloud-eclipse   File: PomTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveUnusedDependencies_keepLibrary1()
    throws CoreException, ParserConfigurationException, IOException, SAXException {
  LibraryFile file1 = new LibraryFile(coordinates("com.example.group1", "artifact1"));
  LibraryFile file2 = new LibraryFile(coordinates("com.example.group2", "artifact2"));
  Library library1 = newLibrary("id1", file1);
  Library library2 = newLibrary("id2", file1, file2);

  pom.addDependencies(Arrays.asList(library1, library2));
  try (InputStream contents = pomFile.getContents()) {
    Document actual = parse(contents);
    NodeList dependenciesList = actual.getElementsByTagNameNS("http://maven.apache.org/POM/4.0.0", "dependencies");
    Assert.assertEquals(2, dependenciesList.getLength());
    Element dependencies = (Element) dependenciesList.item(1);
    Assert.assertEquals(2, dependencies.getElementsByTagNameNS("http://maven.apache.org/POM/4.0.0", "dependency").getLength());

    // dependencies from library2 should be removed
    Pom.removeUnusedDependencies(dependencies, Arrays.asList(library1),
        Arrays.asList(library1, library2));
    Assert.assertEquals(1, dependencies.getElementsByTagNameNS("http://maven.apache.org/POM/4.0.0", "dependency").getLength());
    Element dependency = getOnlyChild((dependencies), "dependency");
    Element groupId = getOnlyChild(dependency, "groupId");
    Assert.assertEquals("com.example.group1", groupId.getTextContent());
    Element artifactId = getOnlyChild(dependency, "artifactId");
    Assert.assertEquals("artifact1", artifactId.getTextContent());
  }
}
 
Example 9
Source Project: ttt   File: Documents.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static List<Element> findElementsByName(Document d, QName qn) {
    String ns = qn.getNamespaceURI();
    NodeList nodes;
    if ((ns == null) || (ns.length() == 0))
        nodes = d.getElementsByTagName(qn.getLocalPart());
    else
        nodes = d.getElementsByTagNameNS(ns, qn.getLocalPart());
    List<Element> elts = new java.util.ArrayList<Element>();
    if (nodes != null) {
        for (int i = 0, n = nodes.getLength(); i < n; ++i) {
            elts.add((Element) nodes.item(i));
        }
    }
    return elts;
}
 
Example 10
/**
 * Parses a set of schemas inside a WSDL file.
 *
 * A WSDL file may contain multiple &lt;xsd:schema> elements.
 */
private XSSchemaSet loadWSDL()
    throws SAXException {


    // build DOMForest just like we handle XML Schema
    DOMForest forest = buildDOMForest( new XMLSchemaInternalizationLogic() );

    DOMForestScanner scanner = new DOMForestScanner(forest);

    XSOMParser xsomParser = createXSOMParser( forest );

    // find <xsd:schema>s and parse them individually
    for( InputSource grammar : opt.getGrammars() ) {
        Document wsdlDom = forest.get( grammar.getSystemId() );
        if (wsdlDom == null) {
            String systemId = Options.normalizeSystemId(grammar.getSystemId());
            if (forest.get(systemId) != null) {
                grammar.setSystemId(systemId);
                wsdlDom = forest.get( grammar.getSystemId() );
            }
        }

        NodeList schemas = wsdlDom.getElementsByTagNameNS(XMLConstants.W3C_XML_SCHEMA_NS_URI,"schema");
        for( int i=0; i<schemas.getLength(); i++ )
            scanner.scan( (Element)schemas.item(i), xsomParser.getParserHandler() );
    }
    return xsomParser.getResult();
}
 
Example 11
Source Project: SAMLRaider   File: XMLHelpers.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the issuer of an SAML Message
 *
 * @param document
 *            Document which contains the issuer
 * @return Issuer of message / first Assertion if found, else empty string
 */
public String getIssuer(Document document) {
	NodeList nl = document.getElementsByTagNameNS("*", "Issuer");
	if (nl.getLength() > 0) {
		return nl.item(0).getTextContent();
	}
	return "";
}
 
Example 12
Source Project: java-client-api   File: AlertingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPostDocumentWithoutFormat() throws SAXException, IOException {
  StringHandle stringHandle = new StringHandle("<search xmlns=\"http://marklogic.com/appservices/search\"><qtext>true</qtext></search>");

  DOMHandle answer = ruleManager.match(stringHandle, new DOMHandle());

  Document doc = answer.get();
  NodeList nl = doc.getElementsByTagNameNS(
    "http://marklogic.com/rest-api", "name");
  assertEquals(2, nl.getLength());

}
 
Example 13
/**
 * Parses the parser element to get the schematron file location and type of
 * resource (from ctl file).
 * 
 * @param schema_links
 *            Gets the location of the schema (and type of resource) and
 *            saves to global parameter
 * @return The type of resource (URL, File, Resource)
 */
public String getFileType(Element schema_links) throws Exception {
    Document d = schema_links.getOwnerDocument();
    NodeList nodes = d.getElementsByTagNameNS(
            "http://www.occamlab.com/te/parsers", "schema");
    String localType = null;
    for (int i = 0; i < nodes.getLength(); i++) {
        Element e = (Element) nodes.item(i);
        localType = e.getAttribute("type");
        this.type = e.getAttribute("type");
        this.phase = e.getAttribute("phase");
        this.schemaLocation = e.getTextContent().trim();
    }
    return localType;
}
 
Example 14
private static void validate(String data, boolean pass) throws Exception {
    System.out.println("Validating " + data);
    File file = new File(DIR, data);

    Document doc = dbf.newDocumentBuilder().parse(file);
    NodeList nl =
        doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    XMLSignature signature = new XMLSignature
        (sigElement, file.toURI().toString());
    SecretKey sk = signature.createSecretKey("secret".getBytes("ASCII"));
    try {
        System.out.println
            ("Validation status: " + signature.checkSignatureValue(sk));
        if (!pass) {
            System.out.println("FAILED");
            atLeastOneFailed = true;
        } else {
            System.out.println("PASSED");
        }
    } catch (XMLSignatureException xse) {
        System.out.println(xse.getMessage());
        if (!pass) {
            System.out.println("PASSED");
        } else {
            System.out.println("FAILED");
            atLeastOneFailed = true;
        }
    }
}
 
Example 15
private boolean containsUnencryptedSignature(SAMLDocumentHolder documentHolder, boolean postBinding) {
    if (postBinding) {
        Document signedDoc = documentHolder.getSamlDocument();
        NodeList nl = signedDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        return nl != null && nl.getLength() > 0;
    } else {
        String algorithm = facade.getRequest().getQueryParamValue(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY);
        return algorithm != null;
    }
}
 
Example 16
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}
 
Example 17
Source Project: openid4java   File: XrdsParserImpl.java    License: Apache License 2.0 4 votes vote down vote up
public List parseXrds(String input, Set targetTypes) throws DiscoveryException
{
    if (DEBUG)
        _log.debug("Parsing XRDS input for service types: " + targetTypes.toString());

    Document document = parseXmlInput(input);

    NodeList XRDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_XRD);
    Node lastXRD;
    if (XRDs.getLength() < 1 || (lastXRD = XRDs.item(XRDs.getLength() - 1)) == null)
        throw new DiscoveryException("No XRD elements found.");

    // get the canonical ID, if any (needed for XRIs)
    String canonicalId = null;
    Node canonicalIdNode;
    NodeList canonicalIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_CANONICALID);
    for (int i = 0; i < canonicalIDs.getLength(); i++) {
        canonicalIdNode = canonicalIDs.item(i);
        if (canonicalIdNode.getParentNode() != lastXRD) continue;
        if (canonicalId != null)
            throw new DiscoveryException("More than one Canonical ID found.");
        canonicalId = canonicalIdNode.getFirstChild() != null && canonicalIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
            canonicalIdNode.getFirstChild().getNodeValue() : null;
    }

    // extract the services that match the specified target types
    NodeList types = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_TYPE);
    Map serviceTypes = new HashMap();
    Set selectedServices = new HashSet();
    Node typeNode, serviceNode;
    for (int i = 0; i < types.getLength(); i++) {
        typeNode = types.item(i);
        String type = typeNode != null && typeNode.getFirstChild() != null && typeNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
            typeNode.getFirstChild().getNodeValue() : null;
        if (type == null) continue;

        serviceNode = typeNode.getParentNode();
        if (serviceNode.getParentNode() != lastXRD) continue;

        if (targetTypes.contains(type))
            selectedServices.add(serviceNode);
        addServiceType(serviceTypes, serviceNode, type);
    }

    if (DEBUG)
        _log.debug("Found " + serviceTypes.size() + " services for the requested types.");

    // extract local IDs
    Map serviceLocalIDs = extractElementsByParent(XRD_NS, XRD_ELEM_LOCALID, selectedServices, document);
    Map serviceDelegates = extractElementsByParent(OPENID_NS, OPENID_ELEM_DELEGATE, selectedServices, document);

    // build XrdsServiceEndpoints for all URIs in the found services
    List result = new ArrayList();
    NodeList uris = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_URI);
    Node uriNode;
    for (int i = 0; i < uris.getLength(); i++) {
        uriNode = uris.item(i);
        if (uriNode == null || !selectedServices.contains(uriNode.getParentNode())) continue;

        String uri = uriNode.getFirstChild() != null && uriNode.getFirstChild().getNodeType() == Node.TEXT_NODE ?
            uriNode.getFirstChild().getNodeValue() : null;

        serviceNode = uriNode.getParentNode();
        Set typeSet = (Set) serviceTypes.get(serviceNode);

        String localId = (String) serviceLocalIDs.get(serviceNode);
        String delegate = (String) serviceDelegates.get(serviceNode);

        XrdsServiceEndpoint endpoint = new XrdsServiceEndpoint(uri, typeSet, getPriority(serviceNode), getPriority(uriNode), localId, delegate, canonicalId);
        if (DEBUG)
            _log.debug("Discovered endpoint: \n" + endpoint);
        result.add(endpoint);
    }

    Collections.sort(result);
    return result;
}
 
Example 18
public static Element getElement(Document parent, QName qname){
  NodeList children = parent.getElementsByTagNameNS(qname.getNamespaceURI(), qname.getLocalPart());
  if(children.getLength() >= 1)
    return (Element)children.item(0);
  return null;
}
 
Example 19
@Test(dataProvider = "elementName")
public void testGetElementsByTagNameNS(String localName, int number) throws Exception {
    Document document = createDOMWithNS("DocumentTest01.xml");
    NodeList nodeList = document.getElementsByTagNameNS("urn:BooksAreUs.org:BookInfo", localName);
    assertEquals(nodeList.getLength(), number);
}
 
Example 20
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}