Example usage for org.w3c.dom Element getLocalName

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

Introduction

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

Prototype

public String getLocalName();

Source Link

Document

Returns the local part of the qualified name of this node.

Usage

From source file:org.apache.cxf.fediz.service.idp.beans.STSClientAction.java

/**
 * @param context//  www.j a v  a  2  s .  c om
 *            the webflow request context
 * @return a serialized RP security token
 * @throws Exception
 */
public String submit(RequestContext context) throws Exception {

    String wtrealm = (String) WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_TREALM);

    SecurityToken idpToken = getSecurityToken(context);

    Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, IDP_CONFIG);

    Bus cxfBus = getBus();

    IdpSTSClient sts = new IdpSTSClient(cxfBus);
    sts.setAddressingNamespace(HTTP_WWW_W3_ORG_2005_08_ADDRESSING);

    Application serviceConfig = idpConfig.findApplication(wtrealm);
    if (serviceConfig == null) {
        LOG.warn("No service config found for " + wtrealm);
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }

    // Parse wreq parameter - we only support parsing TokenType and KeyType for now
    String wreq = (String) WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_REQUEST);
    String stsTokenType = null;
    String stsKeyType = keyType;
    if (wreq != null) {
        try {
            Document wreqDoc = DOMUtils.readXml(new StringReader(wreq));
            Element wreqElement = wreqDoc.getDocumentElement();
            if (wreqElement != null && "RequestSecurityToken".equals(wreqElement.getLocalName())
                    && (STSUtils.WST_NS_05_12.equals(wreqElement.getNamespaceURI())
                            || HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST
                                    .equals(wreqElement.getNamespaceURI()))) {
                Element tokenTypeElement = DOMUtils.getFirstChildWithName(wreqElement,
                        wreqElement.getNamespaceURI(), "TokenType");
                if (tokenTypeElement != null) {
                    stsTokenType = tokenTypeElement.getTextContent();
                }
                Element keyTypeElement = DOMUtils.getFirstChildWithName(wreqElement,
                        wreqElement.getNamespaceURI(), "KeyType");
                if (keyTypeElement != null) {
                    stsKeyType = keyTypeElement.getTextContent();
                }
            }
        } catch (Exception e) {
            LOG.warn("Error parsing 'wreq' parameter: " + e.getMessage());
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }
    }

    if (stsTokenType != null) {
        sts.setTokenType(stsTokenType);
    } else if (serviceConfig.getTokenType() != null && serviceConfig.getTokenType().length() > 0) {
        sts.setTokenType(serviceConfig.getTokenType());
    } else {
        sts.setTokenType(getTokenType());
    }

    if (serviceConfig.getPolicyNamespace() != null && serviceConfig.getPolicyNamespace().length() > 0) {
        sts.setWspNamespace(serviceConfig.getPolicyNamespace());
    }

    LOG.debug("TokenType {} set for realm {}", sts.getTokenType(), wtrealm);

    sts.setKeyType(stsKeyType);
    if (HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_PUBLICKEY.equals(stsKeyType)) {
        HttpServletRequest servletRequest = WebUtils.getHttpServletRequest(context);
        if (servletRequest != null) {
            X509Certificate certs[] = (X509Certificate[]) servletRequest
                    .getAttribute("javax.servlet.request.X509Certificate");
            if (certs != null && certs.length > 0) {
                sts.setUseCertificateForConfirmationKeyInfo(true);
                sts.setUseKeyCertificate(certs[0]);
            } else {
                LOG.info("Can't send a PublicKey KeyType as no client certs are available");
                sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
            }
        }
    }

    processWsdlLocation(context);
    sts.setWsdlLocation(wsdlLocation);
    sts.setServiceQName(new QName(namespace, wsdlService));
    sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
    if (use200502Namespace) {
        sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
    }

    if (serviceConfig.getRequestedClaims() != null && serviceConfig.getRequestedClaims().size() > 0) {
        addClaims(sts, serviceConfig.getRequestedClaims());
        LOG.debug("Requested claims set for {}", wtrealm);
    }

    sts.setEnableLifetime(true);
    if (serviceConfig.getLifeTime() > 0) {
        try {
            int lifetime = serviceConfig.getLifeTime();
            sts.setTtl(lifetime);
            sts.setEnableLifetime(lifetime > 0);
            LOG.debug("Lifetime set to {} seconds for realm {}", serviceConfig.getLifeTime(), wtrealm);
        } catch (NumberFormatException ex) {
            LOG.warn("Invalid lifetime configured for service provider " + wtrealm);
            sts.setTtl(this.ttl);
            sts.setEnableLifetime(this.ttl > 0);
        }
    } else {
        sts.setTtl(this.ttl);
        sts.setEnableLifetime(this.ttl > 0);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Lifetime set to {} seconds for realm {}", this.ttl, wtrealm);
        }
    }

    sts.setOnBehalfOf(idpToken.getToken());
    if (!(serviceConfig.getProtocol() == null
            || FederationConstants.WS_FEDERATION_NS.equals(serviceConfig.getProtocol()))) {
        LOG.error("Protocol {} not supported for realm {} ", serviceConfig.getProtocol(), wtrealm);
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }

    String rpToken = sts.requestSecurityTokenResponse(wtrealm);

    InputStream is = new ByteArrayInputStream(rpToken.getBytes());
    Document doc = StaxUtils.read(is);
    NodeList nd = doc.getElementsByTagName("saml2:Assertion");
    if (nd.getLength() == 0) {
        nd = doc.getElementsByTagName("saml1:Assertion");
    }
    Element e = (Element) nd.item(0);
    SamlAssertionWrapper aw = new SamlAssertionWrapper(e);
    String id = aw.getId();

    LOG.info("[RP_TOKEN={}] successfully created for realm [{}] on behalf of [IDP_TOKEN={}]", id, wtrealm,
            idpToken.getId());
    return StringEscapeUtils.escapeXml(rpToken);
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java

/*****
 * Adds a new node or replaces an existing node in the Document
 * //ww w.j a  va 2 s.c o m
 * @param doc Target document where the node will added
 * @param xmlEntity contains definition of the xml entity
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static void addNewNode(final Document doc, final XmlEntity xmlEntity)
        throws IOException, XPathExpressionException, SAXException, ParserConfigurationException {
    // Build up map per call to avoid issues with caching wrong version of the map.
    final LinkedHashMap<String, CacheElement> elementOrderMap = CacheElement.buildElementMap(doc);

    final Node newNode = createNode(doc, xmlEntity.getXmlDefinition());
    final Node root = doc.getDocumentElement();
    final int incomingElementOrder = getElementOrder(elementOrderMap, xmlEntity.getNamespace(),
            xmlEntity.getType());

    boolean nodeAdded = false;
    NodeList nodes = root.getChildNodes();
    final int length = nodes.getLength();
    for (int i = 0; i < length; i++) {
        final Node node = nodes.item(i);

        if (node instanceof Element) {
            final Element childElement = (Element) node;
            final String type = childElement.getLocalName();
            final String namespace = childElement.getNamespaceURI();

            if (namespace.equals(xmlEntity.getNamespace()) && type.equals(xmlEntity.getType())) {
                // First check if the element has a name
                String nameOrId = getAttribute(childElement, "name");
                // If not then check if the element has an Id
                if (nameOrId == null) {
                    nameOrId = getAttribute(childElement, "id");
                }

                if (nameOrId != null) {
                    // If there is a match , then replace the existing node with the incoming node
                    if (nameOrId.equals(xmlEntity.getNameOrId())) {
                        root.replaceChild(newNode, node);
                        nodeAdded = true;
                        break;
                    }
                } else {
                    // This element does not have any name or id identifier for e.g PDX and gateway-receiver
                    // If there is only one element of that type then replace it with the incoming node
                    if (!isMultiple(elementOrderMap, namespace, type)) {
                        root.replaceChild(newNode, node);
                        nodeAdded = true;
                        break;
                    }
                }
            } else {
                if (incomingElementOrder < getElementOrder(elementOrderMap, namespace, type)) {
                    root.insertBefore(newNode, node);
                    nodeAdded = true;
                    break;
                }
            }
        }
    }
    if (!nodeAdded) {
        root.appendChild(newNode);
    }
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java

/****
 * Method to modify the root attribute (cache) of the XML
 * //from   ww  w . j  av  a2  s  . c o  m
 * @param doc Target document whose root attributes must be modified
 * @param xmlEntity xml entity for the root , it also contains the attributes
 * @throws IOException
 */
public static void modifyRootAttributes(Document doc, XmlEntity xmlEntity) {
    if (xmlEntity == null || xmlEntity.getAttributes() == null) {
        return;
    }
    String type = xmlEntity.getType();
    Map<String, String> attributes = xmlEntity.getAttributes();

    Element root = doc.getDocumentElement();
    if (root.getLocalName().equals(type)) {

        for (Entry<String, String> entry : attributes.entrySet()) {
            String attributeName = entry.getKey();
            String attributeValue = entry.getValue();

            // Remove the existing attribute
            String rootAttribute = getAttribute(root, attributeName);
            if (null != rootAttribute) {
                root.removeAttribute(rootAttribute);
            }

            // Add the new attribute with new value
            root.setAttribute(attributeName, attributeValue);
        }
    }
}

From source file:org.apache.hise.utils.DOMUtils.java

public static Element findElement(QName elementName, List<Object> content) {
    for (Object o : content) {
        if (o instanceof Element) {
            Element u = (Element) o;
            QName n = new QName(u.getNamespaceURI(), u.getLocalName());
            if (n.equals(elementName)) {
                return u;
            }/*w  w  w  .j a  va  2s  .c o  m*/
        }
    }
    return null;
}

From source file:org.apache.jackrabbit.webdav.server.BindTest.java

private URI getResourceId(String uri) throws IOException, DavException, URISyntaxException {
    DavPropertyNameSet names = new DavPropertyNameSet();
    names.add(BindConstants.RESOURCEID);
    PropFindMethod propfind = new PropFindMethod(uri, names, 0);
    int status = this.client.executeMethod(propfind);
    assertEquals(207, status);//w  w  w  .j  a v a2s  .co  m
    MultiStatus multistatus = propfind.getResponseBodyAsMultiStatus();
    MultiStatusResponse[] responses = multistatus.getResponses();
    assertEquals(1, responses.length);
    DavProperty resourceId = responses[0].getProperties(200).get(BindConstants.RESOURCEID);
    assertNotNull(resourceId);
    assertTrue(resourceId.getValue() instanceof Element);
    Element href = (Element) resourceId.getValue();
    assertEquals("href", href.getLocalName());
    String text = getUri(href);
    URI resid = new URI(text);
    return resid;
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMReference.java

/**
 * Creates a <code>DOMReference</code> from an element.
 *
 * @param refElem a Reference element//from   w  w  w .  j a va  2  s . c o  m
 */
public DOMReference(Element refElem, XMLCryptoContext context, Provider provider) throws MarshalException {
    Boolean secureValidation = (Boolean) context.getProperty("org.apache.jcp.xml.dsig.secureValidation");
    boolean secVal = false;
    if (secureValidation != null && secureValidation.booleanValue()) {
        secVal = true;
    }

    // unmarshal Transforms, if specified
    Element nextSibling = DOMUtils.getFirstChildElement(refElem);
    List<Transform> transforms = new ArrayList<Transform>(5);
    if (nextSibling.getLocalName().equals("Transforms")) {
        Element transformElem = DOMUtils.getFirstChildElement(nextSibling);

        int transformCount = 0;
        while (transformElem != null) {
            transforms.add(new DOMTransform(transformElem, context, provider));
            transformElem = DOMUtils.getNextSiblingElement(transformElem);

            transformCount++;
            if (secVal && (transformCount > MAXIMUM_TRANSFORM_COUNT)) {
                String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + " "
                        + "transforms per Reference are allowed with secure validation";
                throw new MarshalException(error);
            }
        }
        nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
    }

    // unmarshal DigestMethod
    Element dmElem = nextSibling;
    this.digestMethod = DOMDigestMethod.unmarshal(dmElem);
    String digestMethodAlgorithm = this.digestMethod.getAlgorithm();
    if (secVal && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) {
        throw new MarshalException(
                "It is forbidden to use algorithm " + digestMethod + " when secure validation is enabled");
    }

    // unmarshal DigestValue
    try {
        Element dvElem = DOMUtils.getNextSiblingElement(dmElem);
        this.digestValue = Base64.decode(dvElem);
    } catch (Base64DecodingException bde) {
        throw new MarshalException(bde);
    }

    // unmarshal attributes
    this.uri = DOMUtils.getAttributeValue(refElem, "URI");

    Attr attr = refElem.getAttributeNodeNS(null, "Id");
    if (attr != null) {
        this.id = attr.getValue();
        refElem.setIdAttributeNode(attr, true);
    } else {
        this.id = null;
    }

    this.type = DOMUtils.getAttributeValue(refElem, "Type");
    this.here = refElem.getAttributeNodeNS(null, "URI");
    this.refElem = refElem;
    this.transforms = transforms;
    this.allTransforms = transforms;
    this.appliedTransformData = null;
    this.provider = provider;
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMXMLSignature.java

/**
 * Creates a <code>DOMXMLSignature</code> from XML.
 *
 * @param sigElem Signature element/*from   w w w .ja v a 2s .  com*/
 * @throws MarshalException if XMLSignature cannot be unmarshalled
 */
public DOMXMLSignature(Element sigElem, XMLCryptoContext context, Provider provider) throws MarshalException {
    localSigElem = sigElem;
    ownerDoc = localSigElem.getOwnerDocument();

    // get Id attribute, if specified
    id = DOMUtils.getAttributeValue(localSigElem, "Id");

    // unmarshal SignedInfo
    Element siElem = DOMUtils.getFirstChildElement(localSigElem);
    si = new DOMSignedInfo(siElem, context, provider);

    // unmarshal SignatureValue
    Element sigValElem = DOMUtils.getNextSiblingElement(siElem);
    sv = new DOMSignatureValue(sigValElem, context);

    // unmarshal KeyInfo, if specified
    Element nextSibling = DOMUtils.getNextSiblingElement(sigValElem);
    if (nextSibling != null && nextSibling.getLocalName().equals("KeyInfo")) {
        ki = new DOMKeyInfo(nextSibling, context, provider);
        nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
    }

    // unmarshal Objects, if specified
    if (nextSibling == null) {
        objects = Collections.emptyList();
    } else {
        List<XMLObject> tempObjects = new ArrayList<XMLObject>();
        while (nextSibling != null) {
            tempObjects.add(new DOMXMLObject(nextSibling, context, provider));
            nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
        }
        objects = Collections.unmodifiableList(tempObjects);
    }
}

From source file:org.apache.ode.axis2.AuthenticationHelper.java

public static void setHttpAuthentication(PartnerRoleMessageExchange odeMex, Options options) {
    Element msg = odeMex.getRequest().getMessage();
    if (msg != null) {
        Element part = DOMUtils.getFirstChildElement(msg);
        while (part != null) {
            Element content = DOMUtils.getFirstChildElement(part);
            if (content != null) {
                if (AUTHENTICATION_NS.equals(content.getNamespaceURI())
                        && AUTHENTICATE_ELEMENT.equals(content.getLocalName())) {
                    setOptions(options, content);
                    msg.removeChild(part);
                    break;
                }/* w  w w .j  av  a2 s .com*/
            }
            part = DOMUtils.getNextSiblingElement(part);
        }
    }
}

From source file:org.apache.ode.axis2.AuthenticationHelper.java

protected static void setOptions(Options options, Element auth) {
    String username = null;/*from   w w w  . j a  va 2  s .  c  o m*/
    String password = null;
    String domain = null;
    String realm = null;
    Element e = DOMUtils.getFirstChildElement(auth);
    while (e != null) {
        if (USERNAME_ELEMENT.equals(e.getLocalName())) {
            username = DOMUtils.getTextContent(e);
        }
        if (PASSWORD_ELEMENT.equals(e.getLocalName())) {
            password = DOMUtils.getTextContent(e);
        }
        if (DOMAIN_ELEMENT.equals(e.getLocalName())) {
            domain = DOMUtils.getTextContent(e);
        }
        if (REALM_ELEMENT.equals(e.getLocalName())) {
            realm = DOMUtils.getTextContent(e);
        }
        e = DOMUtils.getNextSiblingElement(e);
    }

    HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator();
    authenticator.setUsername(username);
    authenticator.setPassword(password);
    authenticator.setDomain(domain);
    authenticator.setRealm(realm);
    options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
}

From source file:org.apache.ode.axis2.ODEService.java

/**
 * Create-and-copy a service-ref element.
 *
 * @param elmt/*from w  ww.j a v a  2s. c  o m*/
 * @return wrapped element
 */
public static MutableEndpoint createServiceRef(Element elmt) {
    Document doc = DOMUtils.newDocument();
    QName elQName = new QName(elmt.getNamespaceURI(), elmt.getLocalName());
    // If we get a service-ref, just copy it, otherwise make a service-ref
    // wrapper
    if (!EndpointReference.SERVICE_REF_QNAME.equals(elQName)) {
        Element serviceref = doc.createElementNS(EndpointReference.SERVICE_REF_QNAME.getNamespaceURI(),
                EndpointReference.SERVICE_REF_QNAME.getLocalPart());
        serviceref.appendChild(doc.importNode(elmt, true));
        doc.appendChild(serviceref);
    } else {
        doc.appendChild(doc.importNode(elmt, true));
    }

    return EndpointFactory.createEndpoint(doc.getDocumentElement());
}