Example usage for org.w3c.dom Element getAttributeNodeNS

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

Introduction

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

Prototype

public Attr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Retrieves an Attr node by local name and namespace URI.

Usage

From source file:org.wso2.carbon.ndatasource.core.utils.DataSourceUtils.java

private static void secureLoadElement(Element element, boolean checkSecureVault) throws CryptoException {
    if (checkSecureVault) {
        Attr secureAttr = element.getAttributeNodeNS(DataSourceConstants.SECURE_VAULT_NS,
                DataSourceConstants.SECRET_ALIAS_ATTR_NAME);
        if (secureAttr != null) {
            element.setTextContent(loadFromSecureVault(secureAttr.getValue()));
            element.removeAttributeNode(secureAttr);
        }/*from www  . j a v a  2  s.c  o  m*/
    } else {
        String encryptedStr = element.getAttribute(DataSourceConstants.ENCRYPTED_ATTR_NAME);
        if (encryptedStr != null) {
            boolean encrypted = Boolean.parseBoolean(encryptedStr);
            if (encrypted) {
                element.setTextContent(new String(CryptoUtil
                        .getDefaultCryptoUtil(DataSourceServiceComponent.getServerConfigurationService(),
                                DataSourceServiceComponent.getRegistryService())
                        .base64DecodeAndDecrypt(element.getTextContent())));
            }
        }
    }
    NodeList childNodes = element.getChildNodes();
    int count = childNodes.getLength();
    Node tmpNode;
    for (int i = 0; i < count; i++) {
        tmpNode = childNodes.item(i);
        if (tmpNode instanceof Element) {
            secureLoadElement((Element) tmpNode, checkSecureVault);
        }
    }
}

From source file:org.wso2.carbon.rssmanager.core.util.RSSManagerUtil.java

private static void secureLoadElement(Element element) throws RSSManagerException {
    Attr secureAttr = element.getAttributeNodeNS(RSSManagerConstants.SecureValueProperties.SECURE_VAULT_NS,
            RSSManagerConstants.SecureValueProperties.SECRET_ALIAS_ATTRIBUTE_NAME_WITH_NAMESPACE);
    if (secureAttr != null) {
        element.setTextContent(RSSManagerUtil.loadFromSecureVault(secureAttr.getValue()));
        element.removeAttributeNode(secureAttr);
    }/*from   w  w w  . ja  v  a2  s  .c om*/
    NodeList childNodes = element.getChildNodes();
    int count = childNodes.getLength();
    Node tmpNode;
    for (int i = 0; i < count; i++) {
        tmpNode = childNodes.item(i);
        if (tmpNode instanceof Element) {
            secureLoadElement((Element) tmpNode);
        }
    }
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

@Override
public AppData normalize(List<QName> namespaces, String appData) {
    try {/*  ww w . j  a  v  a  2s  .co m*/
        final Document doc = createDocumentFromFragment(namespaces, appData);
        NodeList childNodes = doc.getDocumentElement().getChildNodes();
        Element body = (Element) childNodes.item(0);
        String _id;
        Attr id = body.getAttributeNodeNS(WSU, "Id");
        if (id == null) {
            _id = "AppData";
            body.setAttributeNS(WSU, "Id", _id);
        } else {
            _id = id.getValue();
        }
        final Transforms transforms = new Transforms(doc);
        //   ? ds:Signature, ?   
        // Element signature = doc.createElementNS(Constants.SignatureSpecNS, Constants._TAG_SIGNATURE);
        // signature = (Element) body.insertBefore(signature, body.getFirstChild());
        // transforms.setElement(signature, _id);
        // transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
        ByteArrayOutputStream c14nStream = new ByteArrayOutputStream();
        MessageDigestAlgorithm mda = MessageDigestAlgorithm.getInstance(doc,
                MessageDigestAlgorithm.ALGO_ID_DIGEST_GOST3411);
        mda.reset();
        XMLSignatureInput output = transforms.performTransforms(new XMLSignatureInput(body), c14nStream);
        DigesterOutputStream digesterStream = new DigesterOutputStream(mda);
        output.updateOutputStream(digesterStream);
        return new AppData(c14nStream.toByteArray(), digesterStream.getDigestValue());
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (CanonicalizationException e) {
        throw new RuntimeException(e);
    } catch (XMLSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

@Override
public String inject(final List<QName> namespaces, final AppData normalized, final X509Certificate certificate,
        final byte[] sig) {
    try {/*  w ww.j ava 2 s  . c om*/
        final String normalizedAppData = new String(normalized.content, "UTF8");
        final Document doc = createDocumentFromFragment(namespaces, normalizedAppData);
        NodeList childNodes = doc.getDocumentElement().getChildNodes();
        Element body = (Element) childNodes.item(0);
        Attr idAttr = body.getAttributeNodeNS(WSU, "Id");
        if (idAttr == null) {
            throw new IllegalStateException("?  ");
        }
        final String id = idAttr.getValue();
        final Transforms transforms = new Transforms(doc);
        Element signature = doc.createElementNS(Constants.SignatureSpecNS, Constants._TAG_SIGNATURE);
        signature = (Element) body.insertBefore(signature, body.getFirstChild());
        transforms.setElement(signature, id);
        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
        ByteArrayOutputStream c14nStream = new ByteArrayOutputStream();
        MessageDigestAlgorithm mda = MessageDigestAlgorithm.getInstance(doc,
                MessageDigestAlgorithm.ALGO_ID_DIGEST_GOST3411);
        mda.reset();
        XMLSignatureInput output = transforms.performTransforms(new XMLSignatureInput(body), c14nStream);
        DigesterOutputStream digesterStream = new DigesterOutputStream(mda);
        output.updateOutputStream(digesterStream);
        AppData check = new AppData(c14nStream.toByteArray(), digesterStream.getDigestValue());
        if (!Arrays.equals(check.digest, normalized.digest)) {
            final StringBuilder sb = new StringBuilder(" ?  ?:\n");
            sb.append(": ").append(new String(normalized.digest, "UTF8")).append('\n');
            sb.append(" : ").append(new String(check.digest, "UTF8"));
            throw new IllegalStateException(sb.toString());
        }

        Element keyInfo = doc.createElementNS(Constants.SignatureSpecNS, "KeyInfo");
        Element securityTokenReference = doc.createElementNS(WSSE, "SecurityTokenReference");
        Element reference = doc.createElementNS(WSSE, "Reference");
        reference.setAttribute("URI", "#CertId");
        reference.setAttribute("ValueType", WSS_X509V3);
        securityTokenReference.appendChild(reference);
        keyInfo.appendChild(securityTokenReference);
        signature.appendChild(keyInfo);
        Element signatureValueElement = XMLUtils.createElementInSignatureSpace(doc,
                Constants._TAG_SIGNATUREVALUE);
        signature.appendChild(signatureValueElement);
        String base64codedValue = Base64.encode(sig);
        if (base64codedValue.length() > 76 && !XMLUtils.ignoreLineBreaks()) {
            base64codedValue = "\n" + base64codedValue + "\n";
        }
        signatureValueElement.appendChild(doc.createTextNode(base64codedValue));
        return saxFilter(doc);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (CanonicalizationException e) {
        throw new RuntimeException(e);
    } catch (XMLSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java

private Element addTimestamp(Element wsSecurityHeaderElement)
        throws SOAPException, DatatypeConfigurationException {
    if (false == this.addTimestamp) {
        return null;
    }//w  ww .  j a v a 2s  . c  o m
    Document document = wsSecurityHeaderElement.getOwnerDocument();
    Element timestampElement = document.createElementNS(WSU_NAMESPACE, "wsu:Timestamp");
    timestampElement.setAttributeNS(WSU_NAMESPACE, "wsu:Id", "TS");
    Attr idAttr = timestampElement.getAttributeNodeNS(WSU_NAMESPACE, "Id");
    timestampElement.setIdAttributeNode(idAttr, true);

    Element createdElement = document.createElementNS(WSU_NAMESPACE, "wsu:Created");
    DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    Date now = new Date();
    gregorianCalendar.setTime(now);
    gregorianCalendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
    createdElement.setTextContent(xmlGregorianCalendar.toXMLFormat());
    timestampElement.appendChild(createdElement);

    Element expiresElement = document.createElementNS(WSU_NAMESPACE, "wsu:Expires");
    Date expiresDate = new Date(now.getTime() + 1000 * 60 * 5);
    gregorianCalendar.setTime(expiresDate);
    xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
    expiresElement.setTextContent(xmlGregorianCalendar.toXMLFormat());
    timestampElement.appendChild(expiresElement);
    wsSecurityHeaderElement.appendChild(timestampElement);
    return timestampElement;
}

From source file:test.unit.be.agiv.security.client.TestUtils.java

/**
 * XMLSEC 1.5 requires us to explicitly mark the Id's within a DOM document.
 * /*from   ww w .ja  v a2s .  com*/
 * @param document
 */
public static void markAllIdAttributesAsId(Document document) {
    Element nsElement = document.createElement("nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsu", WSConstants.WS_SECURITY_UTILITY_NAMESPACE);

    NodeList elementsWithIdNodeList;
    try {
        elementsWithIdNodeList = XPathAPI.selectNodeList(document, "//*[@Id or @wsu:Id]", nsElement);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }

    for (int nodeIdx = 0; nodeIdx < elementsWithIdNodeList.getLength(); nodeIdx++) {
        Element elementWithId = (Element) elementsWithIdNodeList.item(nodeIdx);
        LOG.debug("element with Id: " + elementWithId.getLocalName());
        Attr attributeNode = elementWithId.getAttributeNode("Id");
        if (null == attributeNode) {
            attributeNode = elementWithId.getAttributeNodeNS(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id");
        }
        elementWithId.setIdAttributeNode(attributeNode, true);
    }
}

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.
 *//*from www  .j av  a2s  . c o  m*/
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;
}