Example usage for org.w3c.dom Node getNamespaceURI

List of usage examples for org.w3c.dom Node getNamespaceURI

Introduction

In this page you can find the example usage for org.w3c.dom Node getNamespaceURI.

Prototype

public String getNamespaceURI();

Source Link

Document

The namespace URI of this node, or null if it is unspecified (see ).

Usage

From source file:org.apache.openaz.xacml.pdp.policy.dom.DOMApply.java

/**
 * Creates a new <code>Apply</code> by parsing the given
 * <code>Node</core> representing a XACML Apply element.
 *
 * @param nodeApply the <code>Node</code> representing the XACML Apply element
 * @param policy the <code>Policy</code> encompassing the Apply element
 * @return a new <code>Apply</code> parsed from the given <code>Node</code>
 * @throws DOMStructureException if there is an error parsing the <code>Node</code>
 *///from   w w w . j a  v  a 2s  .  c o m
public static Apply newInstance(Node nodeApply, Policy policy) throws DOMStructureException {
    Element elementApply = DOMUtil.getElement(nodeApply);
    boolean bLenient = DOMProperties.isLenient();

    DOMApply domApply = new DOMApply();

    try {
        NodeList children = nodeApply.getChildNodes();
        if (children != null) {
            int numChildren = children.getLength();
            for (int i = 0; i < numChildren; i++) {
                Node child = children.item(i);
                if (child.getNodeType() == Node.ELEMENT_NODE && XACML3.XMLNS.equals(child.getNamespaceURI())) {
                    String childName = child.getLocalName();
                    if (XACML3.ELEMENT_DESCRIPTION.equals(childName)) {
                        domApply.setDescription(child.getTextContent());
                    } else if (DOMExpression.isExpression(child)) {
                        domApply.addArgument(DOMExpression.newInstance(child, policy));
                    } else if (!bLenient) {
                        throw DOMUtil.newUnexpectedElementException(child, nodeApply);
                    }
                }
            }
        }

        domApply.setFunctionId(
                DOMUtil.getIdentifierAttribute(elementApply, XACML3.ATTRIBUTE_FUNCTIONID, !bLenient));
    } catch (DOMStructureException ex) {
        domApply.setStatus(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, ex.getMessage());
        if (DOMProperties.throwsExceptions()) {
            throw ex;
        }
    }

    return domApply;
}

From source file:org.apache.openaz.xacml.pdp.policy.dom.DOMApply.java

public static boolean repair(Node nodeApply) throws DOMStructureException {
    Element elementApply = DOMUtil.getElement(nodeApply);
    boolean result = false;

    NodeList children = nodeApply.getChildNodes();
    if (children != null) {
        int numChildren = children.getLength();
        for (int i = 0; i < numChildren; i++) {
            Node child = children.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE && XACML3.XMLNS.equals(child.getNamespaceURI())) {
                String childName = child.getLocalName();
                if (XACML3.ELEMENT_DESCRIPTION.equals(childName)) { //NOPMD
                    // TODO
                } else if (DOMExpression.isExpression(child)) {
                    result = DOMExpression.repair(child) || result;
                } else {
                    logger.warn("Unexpected element " + child.getNodeName());
                    elementApply.removeChild(child);
                    result = true;//from ww w.j ava2s .  c o m
                }
            }
        }
    }

    result = DOMUtil.repairIdentifierAttribute(elementApply, XACML3.ATTRIBUTE_FUNCTIONID,
            XACML3.ID_FUNCTION_STRING_EQUAL, logger) || result;

    return result;
}

From source file:org.apache.openaz.xacml.std.dom.DOMUtil.java

/**
 * Determines if the given <code>Node</code> belongs to the namespace with the given <code>String</code>
 * name./*from   ww  w  . j  a  va  2 s  .  c o m*/
 *
 * @param node the <code>Node</code> to check
 * @param namespace the <code>String</code> namespace
 * @return true if the <code>Node</code> namespace matches, else false
 */
public static boolean isInNamespace(Node node, String namespace) {
    return namespace.equals(node.getNamespaceURI());
}

From source file:org.apache.openaz.xacml.std.dom.DOMUtil.java

/**
 * Determines if the given <code>Node</code> is an <code>Element</code> and is in the given
 * <code>String</code> namespace.
 *
 * @param node the <code>Node</code> to check
 * @param namespace the <code>String</code> namespace to check or null if no namespace check is required
 * @return true if the given <code>Node</code> is an <code>Element</code> and the <code>namespace</code>
 *         is null or matches the <code>Node</code> namespace.
 *///from  w  w  w. j a v  a2  s. c  o  m
public static boolean isNamespaceElement(Node node, String namespace) {
    if (node == null) {
        return false;
    } else if (node.getNodeType() != Node.ELEMENT_NODE) {
        return false;
    } else if (namespace != null && !namespace.equals(node.getNamespaceURI())) {
        return false;
    } else {
        return true;
    }
}

From source file:org.apache.openaz.xacml.std.dom.DOMUtil.java

public static String getNodeLabel(Node node) {
    String namespaceURI = node.getNamespaceURI();
    return (namespaceURI == null ? node.getLocalName() : namespaceURI + ":" + node.getLocalName());
}

From source file:org.apache.rahas.impl.util.SAML2Utils.java

public static SAML2KeyInfo getSAML2KeyInfo(Assertion assertion, Crypto crypto, CallbackHandler cb)
        throws WSSecurityException {

    //First ask the cb whether it can provide the secret
    WSPasswordCallback pwcb = new WSPasswordCallback(assertion.getID(), WSPasswordCallback.CUSTOM_TOKEN);
    if (cb != null) {
        try {/* ww  w .  j  a  va  2  s.  c  om*/
            cb.handle(new Callback[] { pwcb });
        } catch (Exception e1) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noKey",
                    new Object[] { assertion.getID() }, e1);
        }
    }

    byte[] key = pwcb.getKey();

    if (key != null) {
        return new SAML2KeyInfo(assertion, key);
    } else {
        // if the cb fails to provide the secret.
        try {
            // extract the subject
            Subject samlSubject = assertion.getSubject();
            if (samlSubject == null) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAML2Token",
                        new Object[] { "for Signature (no Subject)" });
            }

            // extract the subject confirmation element from the subject
            SubjectConfirmation subjectConf = (SubjectConfirmation) samlSubject.getSubjectConfirmations()
                    .get(0);
            if (subjectConf == null) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAML2Token",
                        new Object[] { "for Signature (no Subject Confirmation)" });
            }

            // Get the subject confirmation data, KeyInfoConfirmationDataType extends SubjectConfirmationData.
            SubjectConfirmationData scData = subjectConf.getSubjectConfirmationData();

            if (scData == null) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAML2Token",
                        new Object[] { "for Signature (no Subject Confirmation Data)" });
            }

            // Get the SAML specific XML representation of the keyInfo object
            XMLObject KIElem = null;
            List<XMLObject> scDataElements = scData.getOrderedChildren();
            Iterator<XMLObject> iterator = scDataElements.iterator();
            while (iterator.hasNext()) {
                XMLObject xmlObj = iterator.next();
                if (xmlObj instanceof org.opensaml.xml.signature.KeyInfo) {
                    KIElem = xmlObj;
                    break;
                }
            }

            Element keyInfoElement;

            // Generate a DOM element from the XMLObject.
            if (KIElem != null) {

                // Set the "javax.xml.parsers.DocumentBuilderFactory" system property to make sure the endorsed JAXP
                // implementation is picked over the default jaxp impl shipped with the JDK.
                String jaxpProperty = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
                System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                        "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

                MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
                Marshaller marshaller = marshallerFactory.getMarshaller(KIElem);
                keyInfoElement = marshaller.marshall(KIElem);

                // Reset the sys. property to its previous value.
                if (jaxpProperty == null) {
                    System.getProperties().remove("javax.xml.parsers.DocumentBuilderFactory");
                } else {
                    System.setProperty("javax.xml.parsers.DocumentBuilderFactory", jaxpProperty);
                }

            } else {
                throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAML2Token",
                        new Object[] { "for Signature (no key info element)" });
            }

            AttributeStatement attrStmt = assertion.getAttributeStatements().size() != 0
                    ? (AttributeStatement) assertion.getAttributeStatements().get(0)
                    : null;
            AuthnStatement authnStmt = assertion.getAuthnStatements().size() != 0
                    ? (AuthnStatement) assertion.getAuthnStatements().get(0)
                    : null;

            // if an attr stmt is present, then it has a symmetric key.
            if (attrStmt != null) {
                NodeList children = keyInfoElement.getChildNodes();
                int len = children.getLength();

                for (int i = 0; i < len; i++) {
                    Node child = children.item(i);
                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    QName el = new QName(child.getNamespaceURI(), child.getLocalName());
                    if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)) {

                        EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
                        proc.handleEncryptedKey((Element) child, cb, crypto, null);

                        return new SAML2KeyInfo(assertion, proc.getDecryptedBytes());
                    } else if (el.equals(new QName(WSConstants.WST_NS, "BinarySecret"))) {
                        Text txt = (Text) child.getFirstChild();
                        return new SAML2KeyInfo(assertion, Base64.decode(txt.getData()));
                    } else if (el.equals(new QName(WSConstants.SIG_NS, "X509Data"))) {
                        X509Certificate[] certs = null;
                        try {
                            KeyInfo ki = new KeyInfo(keyInfoElement, null);

                            if (ki.containsX509Data()) {
                                X509Data data = ki.itemX509Data(0);
                                XMLX509Certificate certElem = null;
                                if (data != null && data.containsCertificate()) {
                                    certElem = data.itemCertificate(0);
                                }
                                if (certElem != null) {
                                    X509Certificate cert = certElem.getX509Certificate();
                                    certs = new X509Certificate[1];
                                    certs[0] = cert;
                                    return new SAML2KeyInfo(assertion, certs);
                                }
                            }

                        } catch (XMLSecurityException e3) {
                            throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity",
                                    new Object[] { "cannot get certificate (key holder)" }, e3);
                        }

                    }
                }

            }

            // If an authn stmt is present then it has a public key.
            if (authnStmt != null) {

                X509Certificate[] certs = null;
                try {
                    KeyInfo ki = new KeyInfo(keyInfoElement, null);

                    if (ki.containsX509Data()) {
                        X509Data data = ki.itemX509Data(0);
                        XMLX509Certificate certElem = null;
                        if (data != null && data.containsCertificate()) {
                            certElem = data.itemCertificate(0);
                        }
                        if (certElem != null) {
                            X509Certificate cert = certElem.getX509Certificate();
                            certs = new X509Certificate[1];
                            certs[0] = cert;
                            return new SAML2KeyInfo(assertion, certs);
                        }
                    }

                } catch (XMLSecurityException e3) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity",
                            new Object[] { "cannot get certificate (key holder)" }, e3);
                }

            }

            throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity",
                    new Object[] { "cannot get certificate or key " });

        } catch (MarshallingException e) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "Failed marshalling the SAML Assertion",
                    null, e);
        }
    }
}

From source file:org.apache.rampart.PolicyBasedResultsValidator.java

protected void validateSignedPartsHeaders(ValidatorData data, Vector signatureParts, Vector results)
        throws RampartException {

    RampartMessageData rmd = data.getRampartMessageData();

    Node envelope = rmd.getDocument().getFirstChild();

    WSSecurityEngineResult[] actionResults = fetchActionResults(results, WSConstants.SIGN);

    // Find elements that are signed
    Vector actuallySigned = new Vector();
    if (actionResults != null) {
        for (int j = 0; j < actionResults.length; j++) {

            WSSecurityEngineResult actionResult = actionResults[j];
            List wsDataRefs = (List) actionResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS);

            // if header was encrypted before it was signed, protected
            // element is 'EncryptedHeader.' the actual element is
            // first child element

            for (Iterator k = wsDataRefs.iterator(); k.hasNext();) {
                WSDataRef wsDataRef = (WSDataRef) k.next();
                Element protectedElement = wsDataRef.getProtectedElement();
                if (protectedElement.getLocalName().equals("EncryptedHeader")) {
                    NodeList nodeList = protectedElement.getChildNodes();
                    for (int x = 0; x < nodeList.getLength(); x++) {
                        if (nodeList.item(x).getNodeType() == Node.ELEMENT_NODE) {
                            String ns = ((Element) nodeList.item(x)).getNamespaceURI();
                            String ln = ((Element) nodeList.item(x)).getLocalName();
                            actuallySigned.add(new QName(ns, ln));
                            break;
                        }//from w ww .j  a  va2 s .  c  o m
                    }
                } else {
                    String ns = protectedElement.getNamespaceURI();
                    String ln = protectedElement.getLocalName();
                    actuallySigned.add(new QName(ns, ln));
                }
            }

        }
    }

    for (int i = 0; i < signatureParts.size(); i++) {
        WSEncryptionPart wsep = (WSEncryptionPart) signatureParts.get(i);

        if (wsep.getType() == WSConstants.PART_TYPE_BODY) {

            QName bodyQName;

            if (WSConstants.URI_SOAP11_ENV.equals(envelope.getNamespaceURI())) {
                bodyQName = new SOAP11Constants().getBodyQName();
            } else {
                bodyQName = new SOAP12Constants().getBodyQName();
            }

            if (!actuallySigned.contains(bodyQName) && !rmd.getPolicyData().isSignBodyOptional()) {
                // soap body is not signed
                throw new RampartException("bodyNotSigned");
            }

        } else if (wsep.getType() == WSConstants.PART_TYPE_HEADER
                || wsep.getType() == WSConstants.PART_TYPE_ELEMENT) {

            Element element = (Element) WSSecurityUtil.findElement(envelope, wsep.getName(),
                    wsep.getNamespace());

            if (element == null) {
                // The signedpart header or element we are checking is not present in
                // soap envelope - this is allowed
                continue;
            }

            // header or the element present in soap envelope - verify that it is part of
            // signature
            if (actuallySigned.contains(new QName(element.getNamespaceURI(), element.getLocalName()))) {
                continue;
            }

            String msg = wsep.getType() == WSConstants.PART_TYPE_HEADER ? "signedPartHeaderNotSigned"
                    : "signedElementNotSigned";

            // header or the element defined in policy is present but not signed
            throw new RampartException(msg, new String[] { wsep.getNamespace() + ":" + wsep.getName() });

        }
    }
}

From source file:org.apache.syncope.core.logic.SAML2IdPLogic.java

private List<SAML2IdPTO> importIdPs(final InputStream input) throws Exception {
    List<EntityDescriptor> idpEntityDescriptors = new ArrayList<>();

    Element root = OpenSAMLUtil.getParserPool().parse(new InputStreamReader(input)).getDocumentElement();
    if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom(root));
    } else if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntitiesDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        NodeList children = root.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (SAMLConstants.SAML20MD_NS.equals(child.getNamespaceURI())
                    && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(child.getLocalName())) {

                NodeList descendants = child.getChildNodes();
                for (int j = 0; j < descendants.getLength(); j++) {
                    Node descendant = descendants.item(j);
                    if (SAMLConstants.SAML20MD_NS.equals(descendant.getNamespaceURI())
                            && IDPSSODescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(descendant.getLocalName())) {

                        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom((Element) child));
                    }//from w  ww .ja  v a2  s .  co m
                }
            }
        }
    }

    List<SAML2IdPTO> result = new ArrayList<>(idpEntityDescriptors.size());
    for (EntityDescriptor idpEntityDescriptor : idpEntityDescriptors) {
        SAML2IdPTO idpTO = new SAML2IdPTO();
        idpTO.setEntityID(idpEntityDescriptor.getEntityID());
        idpTO.setName(idpEntityDescriptor.getEntityID());
        idpTO.setUseDeflateEncoding(false);

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            saml2rw.write(new OutputStreamWriter(baos), idpEntityDescriptor, false);
            idpTO.setMetadata(Base64.getEncoder().encodeToString(baos.toByteArray()));
        }

        ItemTO connObjectKeyItem = new ItemTO();
        connObjectKeyItem.setIntAttrName("username");
        connObjectKeyItem.setExtAttrName("NameID");
        idpTO.setConnObjectKeyItem(connObjectKeyItem);

        SAML2IdPEntity idp = cache.put(idpEntityDescriptor, idpTO);
        if (idp.getSSOLocation(SAML2BindingType.POST) != null) {
            idpTO.setBindingType(SAML2BindingType.POST);
        } else if (idp.getSSOLocation(SAML2BindingType.REDIRECT) != null) {
            idpTO.setBindingType(SAML2BindingType.REDIRECT);
        } else {
            throw new IllegalArgumentException(
                    "Neither POST nor REDIRECT artifacts supported by " + idp.getId());
        }

        result.add(idpTO);
    }

    return result;
}

From source file:org.apache.ws.security.message.token.SecurityTokenReference.java

/**
 * Method length./*from  www  . j  av  a  2  s  .c o m*/
 * 
 * @param namespace
 * @param localname
 * @return number of elements with matching localname and namespace
 */
public int length(String namespace, String localname) {
    NodeList childNodes = this.element.getChildNodes();
    int result = 0;
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node n = childNodes.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            String ns = n.getNamespaceURI();
            String name = n.getLocalName();
            if ((((namespace != null) && namespace.equals(ns)) || ((namespace == null) && (ns == null)))
                    && (localname.equals(name))) {
                result++;
            }
        }
    }
    return result;
}

From source file:org.apache.ws.security.message.WSSecDKSign.java

protected Set getInclusivePrefixes(Element target, boolean excludeVisible) {
    Set result = new HashSet();
    Node parent = target;//from  w  w  w  .j ava 2s. co  m
    NamedNodeMap attributes;
    Node attribute;
    while (!(parent.getParentNode() instanceof Document)) {
        parent = parent.getParentNode();
        attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }
            }
        }
    }

    if (excludeVisible == true) {
        attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.remove("#default");
                } else {
                    result.remove(attribute.getLocalName());
                }
            }
            if (attribute.getPrefix() != null) {
                result.remove(attribute.getPrefix());
            }
        }

        if (target.getPrefix() == null) {
            result.remove("#default");
        } else {
            result.remove(target.getPrefix());
        }
    }

    return result;
}