Example usage for org.w3c.dom Element getNamespaceURI

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

Introduction

In this page you can find the example usage for org.w3c.dom Element 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.xml.security.utils.XMLUtils.java

/**
 * Returns true if the element is in XML Signature namespace and the local
 * name equals the supplied one./*from  w w w.  ja v  a 2 s . c o  m*/
 *
 * @param element
 * @param localName
 * @return true if the element is in XML Signature namespace and the local name equals 
 * the supplied one
 */
public static boolean elementIsInSignatureSpace(Element element, String localName) {
    if (element == null) {
        return false;
    }

    return Constants.SignatureSpecNS.equals(element.getNamespaceURI())
            && element.getLocalName().equals(localName);
}

From source file:org.apache.xml.security.utils.XMLUtils.java

/**
 * Returns true if the element is in XML Encryption namespace and the local
 * name equals the supplied one.//from w  w w. j ava 2  s . c  om
 *
 * @param element
 * @param localName
 * @return true if the element is in XML Encryption namespace and the local name 
 * equals the supplied one
 */
public static boolean elementIsInEncryptionSpace(Element element, String localName) {
    if (element == null) {
        return false;
    }
    return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI())
            && element.getLocalName().equals(localName);
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * method to set an Id to this element and to all XForms descendants of this element
 */// w  ww  .  ja va2 s.  c o m
private void resetXFormIds(Element newControl) {
    if (newControl.getNamespaceURI() != null && newControl.getNamespaceURI().equals(XFORMS_NS))
        this.setXFormsId(newControl);

    //recursive call
    NodeList children = newControl.getChildNodes();
    int nb = children.getLength();
    for (int i = 0; i < nb; i++) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.ELEMENT_NODE)
            this.resetXFormIds((Element) child);
    }
}

From source file:org.codice.ddf.cxf.paos.PaosInInterceptor.java

@Override
public void handleMessage(Message message) throws Fault {
    List authHeader = (List) ((Map) message.getExchange().getOutMessage().get(Message.PROTOCOL_HEADERS))
            .get("Authorization");
    String authorization = null;/*from   www .  j a v  a 2 s .c om*/
    if (authHeader != null && authHeader.size() > 0) {
        authorization = (String) authHeader.get(0);
    }
    InputStream content = message.getContent(InputStream.class);
    String contentType = (String) message.get(Message.CONTENT_TYPE);
    if (contentType == null || !contentType.contains(APPLICATION_VND_PAOS_XML)) {
        return;
    }
    try {
        SOAPPart soapMessage = SamlProtocol
                .parseSoapMessage(IOUtils.toString(content, Charset.forName("UTF-8")));
        Iterator iterator = soapMessage.getEnvelope().getHeader().examineAllHeaderElements();
        IDPEntry idpEntry = null;
        String relayState = "";
        String responseConsumerURL = "";
        String messageId = "";
        while (iterator.hasNext()) {
            Element soapHeaderElement = (SOAPHeaderElement) iterator.next();
            if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) {
                relayState = DOM2Writer.nodeToString(soapHeaderElement);
            } else if (REQUEST.equals(soapHeaderElement.getLocalName()) && soapHeaderElement.getNamespaceURI()
                    .equals(URN_OASIS_NAMES_TC_SAML_2_0_PROFILES_SSO_ECP)) {
                try {
                    soapHeaderElement = SamlProtocol.convertDomImplementation(soapHeaderElement);
                    Request ecpRequest = (Request) OpenSAMLUtil.fromDom(soapHeaderElement);
                    IDPList idpList = ecpRequest.getIDPList();
                    if (idpList == null) {
                        throw new Fault(new AccessDeniedException(
                                "Unable to complete SAML ECP connection. Unable to determine IdP server."));
                    }
                    List<IDPEntry> idpEntrys = idpList.getIDPEntrys();
                    if (idpEntrys == null || idpEntrys.size() == 0) {
                        throw new Fault(new AccessDeniedException(
                                "Unable to complete SAML ECP connection. Unable to determine IdP server."));
                    }
                    // choose the right entry, probably need to do something better than select the first
                    // one
                    // but the spec doesn't specify how this is supposed to be done
                    idpEntry = idpEntrys.get(0);
                } catch (WSSecurityException e) {
                    // TODO figure out IdP alternatively
                    LOGGER.info(
                            "Unable to determine IdP appropriately. ECP connection will fail. SP may be incorrectly configured. Contact the administrator for the remote system.");
                }
            } else if (REQUEST.equals(soapHeaderElement.getLocalName())
                    && soapHeaderElement.getNamespaceURI().equals(URN_LIBERTY_PAOS_2003_08)) {
                responseConsumerURL = soapHeaderElement.getAttribute(RESPONSE_CONSUMER_URL);
                messageId = soapHeaderElement.getAttribute(MESSAGE_ID);
            }
        }
        if (idpEntry == null) {
            throw new Fault(new AccessDeniedException(
                    "Unable to complete SAML ECP connection. Unable to determine IdP server."));
        }
        String token = createToken(authorization);
        checkAuthnRequest(soapMessage);
        Element authnRequestElement = SamlProtocol
                .getDomElement(soapMessage.getEnvelope().getBody().getFirstChild());
        String loc = idpEntry.getLoc();
        String soapRequest = buildSoapMessage(token, relayState, authnRequestElement, null);
        HttpResponseWrapper httpResponse = getHttpResponse(loc, soapRequest, null);
        InputStream httpResponseContent = httpResponse.content;
        SOAPPart idpSoapResponse = SamlProtocol
                .parseSoapMessage(IOUtils.toString(httpResponseContent, Charset.forName("UTF-8")));
        Iterator responseHeaderElements = idpSoapResponse.getEnvelope().getHeader().examineAllHeaderElements();
        String newRelayState = "";
        while (responseHeaderElements.hasNext()) {
            SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) responseHeaderElements.next();
            if (RESPONSE.equals(soapHeaderElement.getLocalName())) {
                String assertionConsumerServiceURL = soapHeaderElement
                        .getAttribute(ASSERTION_CONSUMER_SERVICE_URL);
                if (!responseConsumerURL.equals(assertionConsumerServiceURL)) {
                    String soapFault = buildSoapFault(ECP_RESPONSE,
                            "The responseConsumerURL does not match the assertionConsumerServiceURL.");
                    httpResponse = getHttpResponse(responseConsumerURL, soapFault, null);
                    message.setContent(InputStream.class, httpResponse.content);
                    return;
                }
            } else if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) {
                newRelayState = DOM2Writer.nodeToString(soapHeaderElement);
                if (StringUtils.isNotEmpty(relayState) && !relayState.equals(newRelayState)) {
                    LOGGER.debug("RelayState does not match between ECP request and response");
                }
                if (StringUtils.isNotEmpty(relayState)) {
                    newRelayState = relayState;
                }
            }
        }
        checkSamlpResponse(idpSoapResponse);
        Element samlpResponseElement = SamlProtocol
                .getDomElement(idpSoapResponse.getEnvelope().getBody().getFirstChild());
        Response paosResponse = null;
        if (StringUtils.isNotEmpty(messageId)) {
            paosResponse = getPaosResponse(messageId);
        }
        String soapResponse = buildSoapMessage(null, newRelayState, samlpResponseElement, paosResponse);
        httpResponse = getHttpResponse(responseConsumerURL, soapResponse,
                message.getExchange().getOutMessage());
        if (httpResponse.statusCode < 400) {
            httpResponseContent = httpResponse.content;
            message.setContent(InputStream.class, httpResponseContent);
            Map<String, List<String>> headers = new HashMap<>();
            message.put(Message.PROTOCOL_HEADERS, headers);
            httpResponse.headers.forEach((entry) -> headers.put(entry.getKey(),
                    // CXF Expects pairs of <String, List<String>>
                    entry.getValue() instanceof List
                            ? ((List<Object>) entry.getValue()).stream().map(String::valueOf)
                                    .collect(Collectors.toList())
                            : Lists.newArrayList(String.valueOf(entry.getValue()))));

        } else {
            throw new Fault(
                    new AccessDeniedException("Unable to complete SAML ECP connection due to an error."));
        }

    } catch (IOException e) {
        LOGGER.debug("Error encountered while performing ECP handshake.", e);
    } catch (XMLStreamException | SOAPException e) {
        throw new Fault(new AccessDeniedException(
                "Unable to complete SAML ECP connection. The server's response was not in the correct format."));
    } catch (WSSecurityException e) {
        throw new Fault(new AccessDeniedException(
                "Unable to complete SAML ECP connection. Unable to send SOAP request messages."));
    }
}

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

public Element createElement(final Node in, final String relativePath, final Map<String, String> leafElements) {
    final Document doc;
    final Element below;
    if (in instanceof Document) {
        doc = (Document) in;//w w  w  .j  av  a2  s.  c  o m
        below = doc.getDocumentElement();
    } else if (in instanceof Element) {
        below = (Element) in;
        doc = below.getOwnerDocument();
    } else {
        throw new IllegalArgumentException("Cannot create nodes/content under a node of type: " + in);
    }

    Element insertionPoint = below;
    if (relativePath != null && relativePath.length() > 0 && !"/".equals(relativePath)) {
        final String[] intermediates = relativePath.split("/");

        // DO NOT traverse last "intermediate"...this will be the new element!
        for (int i = 0; i < intermediates.length - 1; i++) {
            final NodeList nl = insertionPoint.getElementsByTagNameNS(below.getNamespaceURI(),
                    intermediates[i]);
            if (nl != null && nl.getLength() > 0) {
                insertionPoint = (Element) nl.item(0);
            } else {
                final Element e = doc.createElementNS(below.getNamespaceURI(), intermediates[i]);
                insertionPoint.appendChild(e);
                insertionPoint = e;
            }
        }

        final Element e = doc.createElementNS(below.getNamespaceURI(), intermediates[intermediates.length - 1]);
        insertionPoint.appendChild(e);
        insertionPoint = e;
    }

    for (final Entry<String, String> entry : leafElements.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        final Element e = doc.createElementNS(below.getNamespaceURI(), key);
        insertionPoint.appendChild(e);
        e.setTextContent(value);
    }

    return insertionPoint;
}

From source file:org.cruxframework.crux.core.declarativeui.template.Templates.java

/**
 * @param template//from w w  w .  ja va 2s .  c om
 * @return
 */
static boolean isWidgetTemplate(Document template) {
    boolean isWidget = false;
    if (template != null) {
        Element templateElement = template.getDocumentElement();

        List<Element> children = extractChildrenElements(templateElement);

        if (children != null && children.size() == 1) {
            Element element = children.get(0);
            String namespaceURI = element.getNamespaceURI();
            if (namespaceURI != null) {
                if (namespaceURI.startsWith("http://www.cruxframework.org/crux/")) {
                    isWidget = true;
                } else if (namespaceURI.startsWith("http://www.cruxframework.org/templates/")) {
                    String library = namespaceURI.substring("http://www.cruxframework.org/templates/".length());
                    Document refTemplate = getTemplate(library, element.getLocalName());
                    isWidget = isWidgetTemplate(refTemplate);
                }
            }
        }
    }

    return isWidget;
}

From source file:org.cruxframework.crux.core.declarativeui.ViewParser.java

/**
 * // www . ja v a2s. co m
 * @param node
 * @return
 */
private boolean isCruxModuleImportTag(Node node) {
    if (node instanceof Element) {
        Element elem = (Element) node;
        String tagName = elem.getTagName();
        String namespaceURI = elem.getNamespaceURI();
        String src = elem.getAttribute("src");
        return (namespaceURI == null || namespaceURI.equals(XHTML_NAMESPACE))
                && tagName.equalsIgnoreCase("script") && (src != null && src.endsWith(".nocache.js"));
    }
    return false;
}

From source file:org.dhatim.cdr.SmooksResourceConfiguration.java

/**
 * Is this configuration targeted at the supplied DOM element.
 * <p/>//  w w w .  jav  a2 s  .  c  o  m
 * Checks that the element is in the correct namespace and is a contextual
 * match for the configuration.
 *
 * @param element The element to be checked.
 * @param executionContext
 * @return True if this configuration is targeted at the supplied element, otherwise false.
 */
public boolean isTargetedAtElement(Element element, ExecutionContext executionContext) {
    if (!assertConditionTrue()) {
        return false;
    }

    if (namespaceURI != null) {
        if (!isTargetedAtNamespace(element.getNamespaceURI())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Not applying resource [" + this + "] to element [" + DomUtils.getXPath(element)
                        + "].  Element not in namespace [" + getSelectorNamespaceURI() + "].");
            }
            return false;
        }
    } else {
        // We don't test the SelectorStep namespace if a namespace is configured on the
        // resource configuration.  This is why we have this code inside the else block.
        if (!selectorStep.isTargetedAtNamespace(element.getNamespaceURI())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Not applying resource [" + this + "] to element [" + DomUtils.getXPath(element)
                        + "].  Element not in namespace [" + selectorStep.getTargetElement().getNamespaceURI()
                        + "].");
            }
            return false;
        }
    }

    XPathExpressionEvaluator evaluator = selectorStep.getPredicatesEvaluator();
    if (evaluator == null) {
        logger.debug("Predicate Evaluators for resource [" + this
                + "] is null.  XPath step predicates will not be evaluated.");
    } else if (!evaluator.evaluate(element, executionContext)) {
        return false;
    }

    if (isContextualSelector && !isTargetedAtElementContext(element, executionContext)) {
        // Note: If the selector is not contextual, there's no need to perform the
        // isTargetedAtElementContext check because we already know the unit is targeted at the
        // element by name - because we looked it up by name in the 1st place (at least that's the assumption).
        if (logger.isDebugEnabled()) {
            logger.debug("Not applying resource [" + this + "] to element [" + DomUtils.getXPath(element)
                    + "].  This resource is only targeted at '" + DomUtils.getName(element)
                    + "' when in the following context '" + getSelector() + "'.");
        }
        return false;
    }

    return true;
}

From source file:org.dhatim.cdr.XMLConfigDigester.java

private void digestV11XSDValidatedConfig(String baseURI, Document configDoc)
        throws SAXException, URISyntaxException, SmooksConfigurationException {
    Element currentElement = configDoc.getDocumentElement();

    String defaultSelector = DomUtils.getAttributeValue(currentElement, "default-selector");
    String defaultNamespace = DomUtils.getAttributeValue(currentElement, "default-selector-namespace");
    String defaultProfile = DomUtils.getAttributeValue(currentElement, "default-target-profile");
    String defaultConditionRef = DomUtils.getAttributeValue(currentElement, "default-condition-ref");

    NodeList configNodes = currentElement.getChildNodes();

    for (int i = 0; i < configNodes.getLength(); i++) {
        if (configNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element configElement = (Element) configNodes.item(i);

            // Make sure the element is permitted...
            assertElementPermitted(configElement);

            String elementName = DomUtils.getName(configElement);
            String namespaceURI = configElement.getNamespaceURI();
            if (namespaceURI == null || namespaceURI.equals(XSD_V11)) {
                if (elementName.equals("params")) {
                    digestParams(configElement);
                } else if (elementName.equals("conditions")) {
                    digestConditions(configElement);
                } else if (elementName.equals("profiles")) {
                    digestProfiles(configElement);
                } else if (elementName.equals("import")) {
                    digestImport(configElement, new URI(baseURI));
                } else if (elementName.equals("reader")) {
                    digestReaderConfig(configElement, defaultProfile);
                } else if (elementName.equals("resource-config")) {
                    digestResourceConfig(configElement, defaultSelector, defaultNamespace, defaultProfile,
                            defaultConditionRef);
                }/*w  w w .j  a  v a  2 s .c o  m*/
            } else {
                // It's an extended reousource configuration element
                digestExtendedResourceConfig(configElement, defaultSelector, defaultNamespace, defaultProfile,
                        defaultConditionRef);
            }
        }
    }
}

From source file:org.dhatim.cdr.XMLConfigDigester.java

private void digestExtendedResourceConfig(Element configElement, String defaultSelector,
        String defaultNamespace, String defaultProfile, String defaultConditionRef) {
    String configNamespace = configElement.getNamespaceURI();
    Smooks configDigester = getExtenededConfigDigester(configNamespace);
    ExecutionContext executionContext = configDigester.createExecutionContext();
    ExtensionContext extentionContext;/* ww w  . j  av a  2s. co  m*/
    Element conditionElement = DomUtils.getElement(configElement, "condition", 1);

    // Create the ExtenstionContext and set it on the ExecutionContext...
    if (conditionElement != null && (conditionElement.getNamespaceURI().equals(XSD_V10)
            || conditionElement.getNamespaceURI().equals(XSD_V11))) {
        extentionContext = new ExtensionContext(this, defaultSelector, defaultNamespace, defaultProfile,
                digestCondition(conditionElement));
    } else if (defaultConditionRef != null) {
        extentionContext = new ExtensionContext(this, defaultSelector, defaultNamespace, defaultProfile,
                getConditionEvaluator(defaultConditionRef));
    } else {
        extentionContext = new ExtensionContext(this, defaultSelector, defaultNamespace, defaultProfile, null);
    }
    ExtensionContext.setExtensionContext(extentionContext, executionContext);

    // Filter the extension element through Smooks...
    configDigester.filterSource(executionContext, new DOMSource(configElement), null);

    // Copy the created resources from the ExtensionContext and onto the SmooksResourceConfigurationList...
    List<SmooksResourceConfiguration> resources = extentionContext.getResources();
    for (SmooksResourceConfiguration resource : resources) {
        resourcelist.add(resource);
    }
}