Example usage for org.w3c.dom Element getElementsByTagNameNS

List of usage examples for org.w3c.dom Element getElementsByTagNameNS

Introduction

In this page you can find the example usage for org.w3c.dom Element getElementsByTagNameNS.

Prototype

public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Returns a NodeList of all the descendant Elements with a given local name and namespace URI in document order.

Usage

From source file:org.wso2.carbon.humantask.core.scheduler.NotificationScheduler.java

/**
 * Publish Email notifications by extracting the information from the incoming message rendering tags
 * <htd:renderings>//from w  w w.j  av  a  2s. com
 *  <htd:rendering type="wso2:email" xmlns:wso2="http://wso2.org/ht/schema/renderings/">
 *     <wso2:to name="to" type="xsd:string">wso2bpsemail@wso2.com</wso2:to>
 *     <wso2:subject name="subject" type="xsd:string">email subject to user</wso2:subject>
 *     <wso2:body name="body" type="xsd:string">Hi email notifications</wso2:body>
 *  </htd:rendering>
 *  <htd:rendering type="wso2:sms" xmlns:wso2="http://wso2.org/ht/schema/renderings/">
 *      <wso2:receiver name="receiver" type="xsd:string">94777459299</wso2:receiver>
 *      <wso2:body name="body" type="xsd:string">Hi $firstname$</wso2:body>
 *  </htd:rendering>
 *</htd:renderings>
 *
 * @param  task TaskDAO object for this notification task instance
 * @param taskConfiguration task configuration instance for this notification task definition
 */
public void publishEmailNotifications(TaskDAO task, HumanTaskBaseConfiguration taskConfiguration)
        throws IOException, SAXException, ParserConfigurationException {

    String rendering = CommonTaskUtil.getRendering(task, taskConfiguration,
            new QName(HumanTaskConstants.RENDERING_NAMESPACE, HumanTaskConstants.RENDERING_TYPE_EMAIL));

    if (rendering != null) {
        Map<String, String> dynamicPropertiesForEmail = new HashMap<String, String>();

        Element root = DOMUtils.stringToDOM(rendering);
        if (root != null) {
            String emailBody = null;
            String mailSubject = null;
            String mailTo = null;
            String contentType = null;
            NodeList mailToList = root.getElementsByTagNameNS(HumanTaskConstants.RENDERING_NAMESPACE,
                    HumanTaskConstants.EMAIL_TO_TAG);
            if (log.isDebugEnabled()) {
                log.debug(
                        "Parsing Email notification rendering element to for notification id " + task.getId());
            }
            if (mailToList != null && mailToList.getLength() > 0) {
                mailTo = mailToList.item(0).getTextContent();
            } else {
                log.warn("Email to address not specified for email notification with notification id "
                        + task.getId());
            }

            NodeList mailSubjectList = root.getElementsByTagNameNS(HumanTaskConstants.RENDERING_NAMESPACE,
                    HumanTaskConstants.EMAIL_SUBJECT_TAG);
            if (log.isDebugEnabled()) {
                log.debug("Paring Email notification rendering element subject " + task.getId());
            }
            if (mailSubjectList != null && mailSubjectList.getLength() > 0) {
                mailSubject = mailSubjectList.item(0).getTextContent();
            } else {
                log.warn("Email subject not specified for email notification with notification id "
                        + task.getId());
            }

            NodeList mailContentType = root.getElementsByTagNameNS(HumanTaskConstants.RENDERING_NAMESPACE,
                    HumanTaskConstants.EMAIL_CONTENT_TYPE_TAG);
            if (log.isDebugEnabled()) {
                log.debug("Paring Email notification rendering element contentType " + task.getId());
            }
            if (mailContentType != null && mailContentType.getLength() > 0) {
                contentType = mailContentType.item(0).getTextContent();
            } else {
                contentType = HumanTaskConstants.CONTENT_TYPE_TEXT_PLAIN;
                log.warn("Email contentType not specified for email notification with notification id "
                        + task.getId() + ". Using text/plain.");
            }

            if (log.isDebugEnabled()) {
                log.debug("Parsing Email notification rendering element body tag for notification id "
                        + task.getId());
            }
            NodeList emailBodyList = root.getElementsByTagNameNS(HumanTaskConstants.RENDERING_NAMESPACE,
                    HumanTaskConstants.EMAIL_OR_SMS_BODY_TAG);

            if (emailBodyList != null && emailBodyList.getLength() > 0) {
                emailBody = emailBodyList.item(0).getTextContent();
            } else {
                log.warn("Email notification message body not specified for notification with id "
                        + task.getId());
            }
            dynamicPropertiesForEmail.put(HumanTaskConstants.ARRAY_EMAIL_ADDRESS, mailTo);
            dynamicPropertiesForEmail.put(HumanTaskConstants.ARRAY_EMAIL_SUBJECT, mailSubject);
            dynamicPropertiesForEmail.put(HumanTaskConstants.ARRAY_EMAIL_TYPE, contentType);

            String adaptorName = getAdaptorName(task.getName(), HumanTaskConstants.RENDERING_TYPE_EMAIL);
            if (!emailAdapterNames.contains(adaptorName)) {
                OutputEventAdapterConfiguration outputEventAdapterConfiguration = createOutputEventAdapterConfiguration(
                        adaptorName, HumanTaskConstants.RENDERING_TYPE_EMAIL,
                        HumanTaskConstants.EMAIL_MESSAGE_FORMAT);
                try {
                    HumanTaskServiceComponent.getOutputEventAdapterService()
                            .create(outputEventAdapterConfiguration);
                    emailAdapterNames.add(adaptorName);
                } catch (OutputEventAdapterException e) {
                    log.error("Unable to create Output Event Adapter : " + adaptorName, e);
                }
            }
            HumanTaskServiceComponent.getOutputEventAdapterService().publish(adaptorName,
                    dynamicPropertiesForEmail, emailBody);
            //emailAdapter.publish(emailBody, dynamicPropertiesForEmail);
        }
    } else {
        log.warn("Email Rendering type not found for task definition with task id " + task.getId());
    }
}

From source file:org.wso2.carbon.identity.application.authenticator.passive.sts.manager.PassiveSTSManager.java

/**
 * @param samlString/*  w ww  . j a  va 2  s . c o m*/
 * @return
 * @throws PassiveSTSException
 */
private XMLObject unmarshall(String samlString) throws PassiveSTSException {

    String samlStr = decodeHTMLCharacters(samlString);
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);

        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        ByteArrayInputStream is = new ByteArrayInputStream(samlStr.getBytes(Charset.forName("UTF-8")));
        Document document = docBuilder.parse(is);
        Element element = document.getDocumentElement();

        NodeList nodeList = element.getElementsByTagNameNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512",
                "RequestedSecurityToken");
        if (nodeList == null || nodeList.getLength() == 0) {
            throw new PassiveSTSException("Security Token is not found in the Response");
        }

        if (nodeList.getLength() > 1) {
            log.warn("More than one Security Token is found in the Response");
        }

        Element node = (Element) nodeList.item(0).getFirstChild();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(node);
        return unmarshaller.unmarshall(node);
    } catch (ParserConfigurationException e) {
        throw new PassiveSTSException(
                PassiveSTSConstants.ERROR_IN_UNMARSHALLING_SAML_REQUEST_FROM_THE_ENCODED_STRING, e);
    } catch (UnmarshallingException e) {
        throw new PassiveSTSException(
                PassiveSTSConstants.ERROR_IN_UNMARSHALLING_SAML_REQUEST_FROM_THE_ENCODED_STRING, e);
    } catch (SAXException e) {
        throw new PassiveSTSException(
                PassiveSTSConstants.ERROR_IN_UNMARSHALLING_SAML_REQUEST_FROM_THE_ENCODED_STRING, e);
    } catch (IOException e) {
        throw new PassiveSTSException(
                PassiveSTSConstants.ERROR_IN_UNMARSHALLING_SAML_REQUEST_FROM_THE_ENCODED_STRING, e);
    }

}

From source file:org.wso2.carbon.identity.relyingparty.saml.SAMLTokenVerifier.java

private Element decryptElement(PrivateKey privKey, Element encryptedToken) throws Exception {

    Element kiElem = null;/*from   w  w  w  . ja va 2 s .co  m*/
    Element encrKeyElem = null;
    EncryptedKeyProcessor encrKeyProcessor = null;
    SecretKey secretKey = null;
    XMLCipher cipher = null;
    Document doc = null;

    if (log.isDebugEnabled()) {
        log.debug("decryptingToken");
    }

    kiElem = (Element) encryptedToken.getElementsByTagNameNS(WSConstants.SIG_NS, "KeyInfo").item(0);
    encrKeyElem = (Element) kiElem
            .getElementsByTagNameNS(WSConstants.ENC_NS, EncryptionConstants._TAG_ENCRYPTEDKEY).item(0);

    encrKeyProcessor = new EncryptedKeyProcessor();
    encrKeyProcessor.handleEncryptedKey(encrKeyElem, privKey);

    secretKey = WSSecurityUtil.prepareSecretKey(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128,
            encrKeyProcessor.getDecryptedBytes());

    cipher = XMLCipher.getInstance();
    cipher.init(XMLCipher.DECRYPT_MODE, secretKey);

    doc = cipher.doFinal(encryptedToken.getOwnerDocument(), encryptedToken);

    if (log.isDebugEnabled()) {
        log.debug("decryptingTokenDone");
    }

    return doc.getDocumentElement();
}

From source file:org.wso2.carbon.identity.user.registration.ui.util.TokenDecrypter.java

private static Element decryptElement(Element encryptedToken) throws Exception {

    ServerConfiguration serverConfig = ServerConfiguration.getInstance();
    PrivateKey key = null;/*w  w  w.  ja v  a2s . c o m*/
    String keyStoreFile = null;
    String privateKeyPass = null;
    String privateKeyAlias = null;
    String keyStorePass = null;
    String type = null;
    byte[] content = null;

    try {

        keyStoreFile = serverConfig.getFirstProperty("Security.KeyStore.Location");
        keyStorePass = serverConfig.getFirstProperty("Security.KeyStore.Password");
        type = serverConfig.getFirstProperty("Security.KeyStore.Type");
        privateKeyAlias = serverConfig.getFirstProperty("Security.KeyStore.KeyAlias");
        privateKeyPass = serverConfig.getFirstProperty("Security.KeyStore.KeyPassword");
        CryptoUtil.getDefaultCryptoUtil();

        content = readBytesFromFile(keyStoreFile);

        KeyStore keyStore = KeyStore.getInstance(type);
        keyStore.load(new ByteArrayInputStream(content), keyStorePass.toCharArray());

        key = (PrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPass.toCharArray());

        Element kiElem = (Element) encryptedToken.getElementsByTagNameNS(WSConstants.SIG_NS, "KeyInfo").item(0);
        Element encrKeyElem = (Element) kiElem
                .getElementsByTagNameNS(WSConstants.ENC_NS, EncryptionConstants._TAG_ENCRYPTEDKEY).item(0);

        EncryptedKeyProcessor encrKeyProcessor = new EncryptedKeyProcessor();
        encrKeyProcessor.handleEncryptedKey(encrKeyElem, key);

        SecretKey secretKey = WSSecurityUtil.prepareSecretKey(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128,
                encrKeyProcessor.getDecryptedBytes());

        XMLCipher cipher = XMLCipher.getInstance();
        cipher.init(XMLCipher.DECRYPT_MODE, secretKey);

        Document doc = cipher.doFinal(encryptedToken.getOwnerDocument(), encryptedToken);

        return doc.getDocumentElement();
    } catch (Exception e) {
        log.error("error occured while decryptng the token", e);
        throw e;
    }
}

From source file:pl.psnc.ep.rt.web.servlets.CollXMLServlet.java

private static void addAuthors(Element metadata, Element content, MetadataServer ms)
        throws RemoteException, DLibraException {
    AttributeId authorAttrId = Util.getAttributeId("Autor", ms);

    AttributeValueSet avs = (AttributeValueSet) metadata.getUserData(KEY_AVS);
    List<AbstractAttributeValue> authorValues = getValues(avs, authorAttrId);
    if (authorValues != null && !authorValues.isEmpty()) {
        String authorsValue = authorValues.get(0).getValue();
        NodeList authorsNodes = manualAuthorsHelper.parseAuthorsValue(authorsValue);
        if (authorsNodes != null) {
            for (int i = 0; i < authorsNodes.getLength(); i++) {
                Node imported = metadata.getOwnerDocument().importNode(authorsNodes.item(i), true);
                metadata.appendChild(imported);
            }/*from  w  w  w .j  a  v  a  2  s  .  co m*/
            return;
        }
    }

    LinkedHashSet<String> authors = new LinkedHashSet<String>();
    NodeList modules = content.getElementsByTagNameNS(Namespace.COL.URI, "module");
    for (int i = 0; i < modules.getLength(); i++) {
        avs = (AttributeValueSet) modules.item(i).getUserData(KEY_AVS);
        List<AbstractAttributeValue> values = getValues(avs, authorAttrId);
        for (AbstractAttributeValue av : values)
            authors.add(av.getValue());
    }

    Document doc = metadata.getOwnerDocument();
    Element actors = element(doc, Namespace.MD, "actors", null);
    metadata.appendChild(actors);
    Element roles = element(doc, Namespace.MD, "roles", null);
    metadata.appendChild(roles);

    Pattern authorPattern = Pattern.compile("^([^<]+)<([^>]*)>$");
    int id = 1;
    for (String author : authors) {
        String fullName = author;
        String email = "";
        Matcher matcher = authorPattern.matcher(author);
        if (matcher.matches()) {
            fullName = matcher.group(1).trim();
            email = matcher.group(2).trim();
        }
        Element person = element(doc, Namespace.MD, "person", null);
        person.setAttribute("userid", "" + id);
        person.appendChild(element(doc, Namespace.MD, "fullname", fullName));
        person.appendChild(element(doc, Namespace.MD, "firstname",
                fullName.lastIndexOf(' ') > -1 ? fullName.substring(0, fullName.lastIndexOf(' ')) : fullName));
        person.appendChild(element(doc, Namespace.MD, "surname",
                fullName.lastIndexOf(' ') > -1
                        ? fullName.substring(fullName.lastIndexOf(' ') + 1, fullName.length())
                        : ""));
        person.appendChild(element(doc, Namespace.MD, "email", email));
        actors.appendChild(person);

        Element role = element(doc, Namespace.MD, "role", "" + id);
        role.setAttribute("type", "author");
        roles.appendChild(role);

        id++;
    }
}

From source file:pl.psnc.ep.rt.web.servlets.CollXMLServlet.java

private static void addDateTimes(Element metadata, Element content)
        throws RemoteException, DLibraException, InterruptedException, ExecutionException {
    final ContentServer cs = ServicesManager.getInstance().getContetServer();

    final ThreadLocal<DocumentBuilder> documentBuilderTL = new ThreadLocal<DocumentBuilder>() {

        @Override//from w  ww .  java 2s  .co m
        protected DocumentBuilder initialValue() {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                return factory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                throw new RuntimeException("Default parser configuration failed?", e);
            }
        }
    };

    Date created = null, revised = null;
    NodeList modules = content.getElementsByTagNameNS(Namespace.COL.URI, "module");
    List<Future<Document>> parsedModules = new ArrayList<Future<Document>>();

    for (int i = 0; i < modules.getLength(); i++) {
        final File file = (File) modules.item(i).getUserData(KEY_FILE);
        final VersionId versionId = file.getVersionIds().get(0);
        parsedModules.add(threadPool.submit(new Callable<Document>() {

            @SuppressWarnings("resource")
            @Override
            public Document call() throws Exception {
                InputStream inputStream = cs.getVersionInputStream(versionId);
                Document module = null;
                try {
                    try {
                        module = documentBuilderTL.get().parse(inputStream);
                    } finally {
                        inputStream.close();
                    }
                } catch (Exception e) {
                    logger.warn("Could not parse file version " + versionId, e);
                } finally {
                    cs.releaseElement(versionId);
                }
                return module;
            }
        }));
    }

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm z");
    for (Future<Document> futureModule : parsedModules) {
        Document module = futureModule.get();
        created = findDate(created, df, module, TAG_CREATED, false);
        revised = findDate(revised, df, module, TAG_REVISED, true);
    }

    if (created != null) {
        NodeList nodeList = metadata.getElementsByTagNameNS(Namespace.MD.URI, TAG_CREATED);
        nodeList.item(0).setTextContent(df.format(created));
    }
    if (revised != null) {
        NodeList nodeList = metadata.getElementsByTagNameNS(Namespace.MD.URI, TAG_REVISED);
        nodeList.item(0).setTextContent(df.format(revised));
    }
}

From source file:pl.touk.ode.scopeEvaluator.MockExtVarManager.java

private MultiKey elementToKey(String name, Element key) {
    HashMap<String, String> ret = new HashMap<String, String>();
    for (String k : extVarKeyConfig.get(name)) {
        ret.put(k, key.getElementsByTagNameNS(extVarNSConfig.get(name), k).item(0).getTextContent());
    }//from   www .  j  a va 2  s  .  c o  m
    return new MultiKey(name, ret);
}

From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java

private boolean isDigested(Element dataElement, Element signatureElement)
        throws XMLSignatureException, XMLSecurityException {
    NodeList referenceNodeList = signatureElement.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
            "Reference");
    Manifest manifest = new Manifest(dataElement.getOwnerDocument());
    VerifyReference[] references = new VerifyReference[referenceNodeList.getLength()];
    for (int referenceIdx = 0; referenceIdx < referenceNodeList.getLength(); referenceIdx++) {
        Element referenceElement = (Element) referenceNodeList.item(referenceIdx);
        VerifyReference reference = new VerifyReference(referenceElement, manifest);
        reference.init();// www. j  a v  a 2 s . co m
        references[referenceIdx] = reference;
    }

    NodeList nodeList = new SingletonNodeList(dataElement);
    return isDigested(nodeList, references);
}

From source file:test.unit.org.owasp.webscarab.plugin.saml.SamlTest.java

@Test
public void testEncryptedXML() throws Exception {
    // setup/*from  w w w  .j a  v  a  2s  . c  o m*/
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder
            .parse(SamlTest.class.getResourceAsStream("/test-saml-response-encrypted-attribute.xml"));

    NodeList nodeList = document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion",
            "EncryptedAttribute");
    assertEquals(1, nodeList.getLength());
    Element encryptedAttributeElement = (Element) nodeList.item(0);
    NodeList encryptedDataNodeList = encryptedAttributeElement
            .getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData");
    assertEquals(1, encryptedDataNodeList.getLength());
    Element encryptedDataElement = (Element) encryptedDataNodeList.item(0);
    Init.init();
    XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.AES_128);
    String aes128HexStr = "2a1e3d83f475ec3c007f487c5150a5f2";
    byte[] aes128Bytes = Hex.decode(aes128HexStr);
    SecretKeySpec secretKeySpec = new SecretKeySpec(aes128Bytes, "AES");
    xmlCipher.init(XMLCipher.DECRYPT_MODE, secretKeySpec);
    xmlCipher.doFinal(document, encryptedDataElement);
    LOG.debug("decrypted attribute: " + toString(encryptedAttributeElement));
    NodeList attributeNodeList = encryptedAttributeElement
            .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute");
    assertEquals(1, attributeNodeList.getLength());
}

From source file:xsul.dsig.globus.security.authentication.wssec.WSSecurityUtil.java

/**
 * Returns the first WS-Security header element for a given actor
 * Only one WS-Security header is allowed for an actor.
 *//*w w  w  . j av  a  2  s .com*/
public static Element getSecurityHeader(Document doc, String actor) {
    Element soapHeaderElement = (Element) getDirectChild(doc.getFirstChild(), XmlConstants.S_HEADER,
            WSConstants.SOAP_NS);

    // TODO: this can also be slightly optimized
    NodeList list = soapHeaderElement.getElementsByTagNameNS(WSConstants.WSSE_NS, WSConstants.WS_SEC_LN);
    int len = list.getLength();
    Element elem;
    Attr attr;
    String hActor;

    for (int i = 0; i < len; i++) {
        elem = (Element) list.item(i);
        attr = elem.getAttributeNodeNS(WSConstants.SOAP_NS, "actor");
        hActor = (attr != null) ? attr.getValue() : null;

        if ((((hActor == null) || (hActor.length() == 0)) && ((actor == null) || (actor.length() == 0)))
                || ((hActor != null) && (actor != null) && hActor.equalsIgnoreCase(actor))) {
            return elem;
        }
    }

    return null;
}