org.apache.cxf.helpers.DOMUtils Java Examples

The following examples show how to use org.apache.cxf.helpers.DOMUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JAXRSClientServerSpringBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void checkSchemas(String address, String schemaSegment,
                          String includedSchema,
                          String refAttrName) throws Exception {
    WebClient client = WebClient.create(address + schemaSegment);
    WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(10000000L);
    Document doc = StaxUtils.read(new InputStreamReader(client.get(InputStream.class), StandardCharsets.UTF_8));
    Element root = doc.getDocumentElement();
    assertEquals(Constants.URI_2001_SCHEMA_XSD, root.getNamespaceURI());
    assertEquals("schema", root.getLocalName());
    if (includedSchema != null) {
        List<Element> includeEls = DOMUtils.getChildrenWithName(root,
                                                                Constants.URI_2001_SCHEMA_XSD,
                                                                refAttrName);
        assertEquals(1, includeEls.size());
        String href = includeEls.get(0).getAttribute("schemaLocation");
        assertEquals(address + includedSchema, href);
    }

}
 
Example #2
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 6 votes vote down vote up
protected String findMEXLocation(Element ref) {
    Element el = DOMUtils.getFirstElement(ref);
    while (el != null) {
        if (el.getLocalName().equals("Address")
            && VersionTransformer.isSupported(el.getNamespaceURI())
            && "MetadataReference".equals(ref.getLocalName())) {
            return DOMUtils.getContent(el);
        } else {
            String ad = findMEXLocation(el);
            if (ad != null) {
                return ad;
            }
        }
        el = DOMUtils.getNextElement(el);
    }
    return null;
}
 
Example #3
Source File: WSSUsernameCallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof DelegationCallback) {
            DelegationCallback callback = (DelegationCallback) callbacks[i];
            Message message = callback.getCurrentMessage();
            
            String username = 
                (String)message.getContextualProperty(SecurityConstants.USERNAME);
            if (username != null) {
                Node contentNode = message.getContent(Node.class);
                Document doc = null;
                if (contentNode != null) {
                    doc = contentNode.getOwnerDocument();
                } else {
                    doc = DOMUtils.createDocument();
                }
                UsernameToken usernameToken = createWSSEUsernameToken(username, doc);
                callback.setToken(usernameToken.getElement());
            }
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #4
Source File: SCTValidatorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Test an invalid SecurityContextToken
 */
@org.junit.Test
public void testInvalidSecurityContextToken() throws Exception {
    TokenValidator sctValidator = new SCTValidator();
    TokenValidatorParameters validatorParameters = createValidatorParameters();
    TokenRequirements tokenRequirements = validatorParameters.getTokenRequirements();

    // Create a ValidateTarget consisting of a SecurityContextToken
    Document doc = DOMUtils.createDocument();
    SecurityContextToken sct = new SecurityContextToken(doc);
    ReceivedToken validateTarget = new ReceivedToken(sct.getElement());
    tokenRequirements.setValidateTarget(validateTarget);
    validatorParameters.setToken(validateTarget);

    assertTrue(sctValidator.canHandleToken(validateTarget));

    TokenValidatorResponse validatorResponse =
        sctValidator.validateToken(validatorParameters);
    assertNotNull(validatorResponse);
    assertNotNull(validatorResponse.getToken());
    assertTrue(validatorResponse.getToken().getState() == STATE.INVALID);
}
 
Example #5
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 6 votes vote down vote up
protected String findID(Element rar, Element rur, Element rst) {
    String id = null;
    if (rst != null) {
        QName elName = DOMUtils.getElementQName(rst);
        if (elName.equals(new QName(WSConstants.SAML_NS, "Assertion"))
            && rst.hasAttributeNS(null, "AssertionID")) {
            id = rst.getAttributeNS(null, "AssertionID");
        } else if (elName.equals(new QName(WSConstants.SAML2_NS, "Assertion"))
            && rst.hasAttributeNS(null, "ID")) {
            id = rst.getAttributeNS(null, "ID");
        }
        if (id == null) {
            id = this.getIDFromSTR(rst);
        }
    }
    if (id == null && rar != null) {
        id = this.getIDFromSTR(rar);
    }
    if (id == null && rur != null) {
        id = this.getIDFromSTR(rur);
    }
    if (id == null && rst != null) {
        id = rst.getAttributeNS(WSConstants.WSU_NS, "Id");
    }
    return id;
}
 
Example #6
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 6 votes vote down vote up
protected Element getDelegationSecurityToken(Object delegationObject) throws Exception {
    if (delegationObject != null) {
        final boolean isString = delegationObject instanceof String;
        final boolean isElement = delegationObject instanceof Element; 
        final boolean isCallbackHandler = delegationObject instanceof CallbackHandler;
        if (isString || isElement || isCallbackHandler) {
            if (isString) {
                final Document doc =
                    DOMUtils.readXml(new StringReader((String) delegationObject));
                return doc.getDocumentElement();
            } else if (isElement) {
                return (Element) delegationObject;
            } else {
                DelegationCallback callback = new DelegationCallback(message);
                ((CallbackHandler)delegationObject).handle(new Callback[]{callback});
                return callback.getToken();
            }
        }
    }
    return null;
}
 
Example #7
Source File: MemoryResourceManager.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public ReferenceParametersType create(Representation initRepresentation) {
    // Store xmlResource
    String uuid = UUID.randomUUID().toString();
    Element representationEl = (Element) initRepresentation.getAny();
    if (representationEl == null) {
        storage.put(uuid, "");
    } else {
        storage.put(uuid, StaxUtils.toString(representationEl));
    }

    Element uuidEl = DOMUtils.getEmptyDocument().createElementNS(REF_NAMESPACE, REF_LOCAL_NAME);
    uuidEl.setTextContent(uuid);

    // Create referenceParameter
    ReferenceParametersType refParam = new ReferenceParametersType();
    refParam.getAny().add(uuidEl);
    return refParam;
}
 
Example #8
Source File: W3CDOMStreamWriter.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void setChild(Element element, boolean append) {
    Node appendedChildNode = null;
    if (currentNode != null) {
        stack.push(currentNode);
        if (append) {
            appendedChildNode = currentNode.appendChild(element);
        }
    } else {
        if (append) {
            appendedChildNode = document.appendChild(element);
        }
    }
    if (!(context instanceof W3CNamespaceContext)) {
        // set the outside namespace context
        W3CNamespaceContext childContext = new W3CNamespaceContext();
        childContext.setOutNamespaceContext(context);
        context = childContext;
    }
    ((W3CNamespaceContext)context).setElement(element);
    if (appendedChildNode != null) {
        currentNode = org.apache.cxf.helpers.DOMUtils.getDomElement(appendedChildNode);
    } else {
        currentNode = element;
    }
}
 
Example #9
Source File: HandlerInvocationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSOAPHandlerHandleMessageThrowsSOAPFaultExceptionServerInbound() throws PingException {
    try {
        handlerTest.pingWithArgs("soapHandler3 inbound throw SOAPFaultExceptionWDetail");
        fail("did not get expected SOAPFaultException");
    } catch (SOAPFaultException e) {
        assertEquals("HandleMessage throws exception", e.getMessage());
        SOAPFault fault = e.getFault();
        assertNotNull(fault);
        assertEquals(new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE, "Server"),
                     fault.getFaultCodeAsQName());
        assertEquals("http://gizmos.com/orders", fault.getFaultActor());

        Detail detail = fault.getDetail();
        assertNotNull(detail);

        QName nn = new QName("http://gizmos.com/orders/", "order");
        Element el = DOMUtils.getFirstChildWithName(detail, nn);
        assertNotNull(el);
        el.normalize();
        assertEquals("Quantity element does not have a value", el.getFirstChild().getNodeValue());
        el = DOMUtils.getNextElement(el);
        el.normalize();
        assertEquals("Incomplete address: no zip code", el.getFirstChild().getNodeValue());
    }
}
 
Example #10
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Test
public void validateIdpInitiatedLoginResponse() throws Exception {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    SAML2SPService saml2Service = anonymous.getService(SAML2SPService.class);

    // Create a SAML Response using WSS4J
    SAML2ReceivedResponseTO response = new SAML2ReceivedResponseTO();
    response.setSpEntityID("http://recipient.apache.org/");
    response.setUrlContext("saml2sp");

    org.opensaml.saml.saml2.core.Response samlResponse =
            createResponse(null, true, SAML2Constants.CONF_BEARER, "urn:org:apache:cxf:fediz:idp:realm-B");

    Document doc = DOMUtils.newDocument();
    Element responseElement = OpenSAMLUtil.toDom(samlResponse, doc);
    String responseStr = DOM2Writer.nodeToString(responseElement);

    // Validate the SAML Response
    response.setSamlResponse(Base64.getEncoder().encodeToString(responseStr.getBytes()));
    response.setRelayState("idpInitiated");
    SAML2LoginResponseTO loginResponse = saml2Service.validateLoginResponse(response);
    assertNotNull(loginResponse.getAccessToken());
    assertEquals("puccini", loginResponse.getNameID());
}
 
Example #11
Source File: SCTCancellerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Try to cancel an invalid SecurityContextToken
 */
@org.junit.Test
public void testCancelInvalidToken() throws Exception {
    TokenCanceller sctCanceller = new SCTCanceller();
    sctCanceller.setVerifyProofOfPossession(false);
    TokenCancellerParameters cancellerParameters = createCancellerParameters();
    TokenRequirements tokenRequirements = cancellerParameters.getTokenRequirements();

    // Create a CancelTarget consisting of a SecurityContextToken
    Document doc = DOMUtils.getEmptyDocument();
    SecurityContextToken sct = new SecurityContextToken(doc);
    ReceivedToken cancelTarget = new ReceivedToken(sct.getElement());
    tokenRequirements.setCancelTarget(cancelTarget);
    cancellerParameters.setToken(cancelTarget);

    assertTrue(sctCanceller.canHandleToken(cancelTarget));

    TokenCancellerResponse cancellerResponse = sctCanceller.cancelToken(cancellerParameters);
    assertNotNull(cancellerResponse);
    assertFalse(cancellerResponse.getToken().getState() == STATE.CANCELLED);
}
 
Example #12
Source File: WSAActionAssertingHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleMessage(SOAPMessageContext context) {
    // only inbound messages are of use
    if ((Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) {
        return true;
    }
    try {
        Element elm = DOMUtils.getFirstElement(context.getMessage().getSOAPHeader());
        while (elm != null) {
            if ("Action".equals(elm.getLocalName()) && elm.getNamespaceURI().contains("addressing")) {
                if (!elm.getTextContent().equals(action)) {
                    throw new RuntimeException("The event sink should have received "
                            + "WSA-Action: " + action + " but received: "
                            + elm.getTextContent());
                }
                return true;
            }
            elm = DOMUtils.getNextElement(elm);
        }
    } catch (SOAPException e) {
        throw new RuntimeException(e);
    }
    throw new RuntimeException("The event sink should have received a WSA-Action associated with"
            + "the notification");
}
 
Example #13
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void checkParameter(Element paramEl, Param p) {
    assertEquals(p.getName(), paramEl.getAttribute("name"));
    assertEquals(p.getType(), paramEl.getAttribute("style"));
    assertEquals(p.getSchemaType(), paramEl.getAttribute("type"));
    assertEquals(p.isRepeating(), Boolean.valueOf(paramEl.getAttribute("repeating")));
    assertEquals(p.getDefaultValue(), paramEl.getAttribute("default"));
    Set<String> options = p.getOptions();
    if (options != null) {
        Set<String> actualOptions = new HashSet<>();
        List<Element> els = DOMUtils.getChildrenWithNamespace(paramEl, WadlGenerator.WADL_NS);
        assertFalse(els.isEmpty());
        assertEquals(options.size(), els.size());
        for (Element op : els) {
            actualOptions.add(op.getAttribute("value"));
        }
        assertEquals(options, actualOptions);
    }
    String docs = p.getDocs();
    if (docs != null) {
        checkDocs(paramEl, "", docs, "");
    }
}
 
Example #14
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 6 votes vote down vote up
protected String findMEXLocation(Element ref) {
    Element el = DOMUtils.getFirstElement(ref);
    while (el != null) {
        if (el.getLocalName().equals("Address")
            && VersionTransformer.isSupported(el.getNamespaceURI())
            && "MetadataReference".equals(ref.getLocalName())) {
            return DOMUtils.getContent(el);
        } else {
            String ad = findMEXLocation(el);
            if (ad != null) {
                return ad;
            }
        }
        el = DOMUtils.getNextElement(el);
    }
    return null;
}
 
Example #15
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCreateLogoutRequest() throws Exception {
    Document doc = DOMUtils.createDocument();

    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer("http://localhost:9001/app");

    NameIDBean nameIdBean = new NameIDBean();
    nameIdBean.setNameValue("uid=joe,ou=people,ou=saml-demo,o=example.com");
    nameIdBean.setNameQualifier("www.example.com");
    NameID nameID = SAML2ComponentBuilder.createNameID(nameIdBean);

    Date notOnOrAfter = new Date();
    notOnOrAfter.setTime(notOnOrAfter.getTime() + 60L * 1000L);
    LogoutRequest logoutRequest =
        SamlpRequestComponentBuilder.createLogoutRequest(SAMLVersion.VERSION_20, issuer, null, null,
                                                         notOnOrAfter, null, nameID);

    Element policyElement = OpenSAMLUtil.toDom(logoutRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example #16
Source File: VersionTransformer.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Parse an EndpointReferenceType from a DOM element.  Handles all of
 * the WS-Addressing namespaces currently supported.
 * @param ref
 * @throws JAXBException
 */
public static EndpointReferenceType parseEndpointReference(Element ref) throws JAXBException {
    Element child = DOMUtils.getFirstElement(ref);
    String tns = null;
    while (child != null && tns == null) {
        if (isSupported(child.getNamespaceURI())) {
            tns = child.getNamespaceURI();
        }
        child = DOMUtils.getNextElement(child);
    }
    if (tns == null) {
        return null;
    }
    JAXBContext ctx = getExposedJAXBContext(tns);
    Unmarshaller um = ctx.createUnmarshaller();
    um.setEventHandler(null);
    try {
        JAXBElement<?> o = um.unmarshal(ref, getExposedReferenceType(tns));
        if (o != null) {
            return convertToNative(o.getValue());
        }
        return convertToNative(null);
    } finally {
        JAXBUtils.closeUnmarshaller(um);
    }
}
 
Example #17
Source File: UsernameTokenInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
private Header findSecurityHeader(SoapMessage message, boolean create) {
    for (Header h : message.getHeaders()) {
        QName n = h.getName();
        if (n.getLocalPart().equals("Security")
            && (n.getNamespaceURI().equals(WSConstants.WSSE_NS) 
                || n.getNamespaceURI().equals(WSConstants.WSSE11_NS))) {
            return h;
        }
    }
    if (!create) {
        return null;
    }
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Security");
    el.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
    SoapHeader sh = new SoapHeader(new QName(WSConstants.WSSE_NS, "Security"), el);
    sh.setMustUnderstand(true);
    message.getHeaders().add(sh);
    return sh;
}
 
Example #18
Source File: SubscriptionReferenceParsingHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleMessage(SOAPMessageContext context) {
    // we are interested only in inbound messages here
    if ((Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) {
        return true;
    }
    try {
        // read headers
        LOG.finer("Examining header elements");
        Element el = DOMUtils.getFirstElement(context.getMessage().getSOAPHeader());
        while (el != null) {
            if (el.getNamespaceURI().equals(namespace)
                && el.getLocalName().equals(elementName)) {
                LOG.log(Level.FINE, "found UUID parameter in header, uuid={0}", el.getTextContent());
                context.put("uuid", el.getTextContent());
            }
            el = DOMUtils.getNextElement(el);
        }
    } catch (SOAPException e) {
        throw new RuntimeException(e);
    }
    return true;
}
 
Example #19
Source File: RecipientSignatureTokenBuilder.java    From steady with Apache License 2.0 6 votes vote down vote up
public Assertion build(Element element, AssertionBuilderFactory factory)
    throws IllegalArgumentException {
    
    SPConstants consts = SP11Constants.SP_NS.equals(element.getNamespaceURI())
        ? SP11Constants.INSTANCE : SP12Constants.INSTANCE;

    RecipientSignatureToken recipientSignatureToken = new RecipientSignatureToken(consts, builder);
    recipientSignatureToken.setOptional(PolicyConstants.isOptional(element));
    recipientSignatureToken.setIgnorable(PolicyConstants.isIgnorable(element));

    Policy policy = builder.getPolicy(DOMUtils.getFirstElement(element));
    policy = policy.normalize(builder.getPolicyRegistry(), false);

    for (Iterator<List<Assertion>> iterator = policy.getAlternatives(); iterator.hasNext();) {
        processAlternative(iterator.next(), recipientSignatureToken);
        break; // TODO process all the token that must be set ..
    }

    return recipientSignatureToken;
}
 
Example #20
Source File: SamlTokenInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
private Header findSecurityHeader(SoapMessage message, boolean create) {
    for (Header h : message.getHeaders()) {
        QName n = h.getName();
        if (n.getLocalPart().equals("Security")
            && (n.getNamespaceURI().equals(WSConstants.WSSE_NS) 
                || n.getNamespaceURI().equals(WSConstants.WSSE11_NS))) {
            return h;
        }
    }
    if (!create) {
        return null;
    }
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Security");
    el.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
    SoapHeader sh = new SoapHeader(new QName(WSConstants.WSSE_NS, "Security"), el);
    sh.setMustUnderstand(true);
    message.getHeaders().add(sh);
    return sh;
}
 
Example #21
Source File: WadlGeneratorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void checkGrammarsWithLinks(Element appElement, List<String> links) {
    assertFalse(links.isEmpty());
    List<Element> grammarEls = DOMUtils.getChildrenWithName(appElement, WadlGenerator.WADL_NS,
                                                            "grammars");
    assertEquals(1, grammarEls.size());
    List<Element> schemasEls = DOMUtils.getChildrenWithName(grammarEls.get(0),
                                                            Constants.URI_2001_SCHEMA_XSD,
                                                            "schema");
    assertEquals(0, schemasEls.size());

    List<Element> includeEls = DOMUtils.getChildrenWithName(grammarEls.get(0), WadlGenerator.WADL_NS,
                                                            "include");
    assertEquals(links.size(), includeEls.size());
    for (Element el : includeEls) {
        assertTrue(links.contains(el.getAttribute("href")));
    }
}
 
Example #22
Source File: CorbaStreamFaultInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void createFaultDetail(Document faultData, FaultInfo faultInfo, Fault faultEx) {
    MessagePartInfo partInfo = faultInfo.getMessageParts().get(0);
    QName partInfoName = partInfo.getElementQName();
    Document faultDoc = DOMUtils.getEmptyDocument();
    Element faultElement = faultDoc.createElement("detail");
    Element partElement =
        faultDoc.createElementNS(partInfoName.getNamespaceURI(), partInfoName.getLocalPart());

    Element faultDataElement = (Element) faultData.getFirstChild();
    Node node = faultDataElement.getFirstChild();
    while (node != null) {
        Node importedFaultData = faultDoc.importNode(node, true);
        partElement.appendChild(importedFaultData);
        node = node.getNextSibling();
    }
    faultElement.appendChild(partElement);
    faultEx.setDetail(faultElement);
}
 
Example #23
Source File: SamlHeaderOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    try {
        SamlAssertionWrapper assertionWrapper = createAssertion(message);

        Document doc = DOMUtils.newDocument();
        Element assertionElement = assertionWrapper.toDOM(doc);
        String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));

        Map<String, List<String>> headers = getHeaders(message);

        StringBuilder builder = new StringBuilder();
        builder.append("SAML").append(' ').append(encodedToken);
        headers.put("Authorization",
            CastUtils.cast(Collections.singletonList(builder.toString()), String.class));

    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example #24
Source File: SecurityTokenServiceProvider.java    From steady with Apache License 2.0 5 votes vote down vote up
private void walkDom(String pfx, Element element, Binder<Node> binder, Object parent) {
    try {
        Object o = binder.getJAXBNode(element);
        if (o instanceof JAXBElement) {
            o = ((JAXBElement<?>)o).getValue();
        }
        //System.out.println(pfx + DOMUtils.getElementQName(element) + " ->  " 
        //    + (o == null ? "null" : o.getClass()));
        if (o == null && parent != null) {
            // if it's not able to bind to an object, it's possibly an xsd:any
            // we'll check the parent for the standard "any" and replace with 
            // the original element.
            Field f = parent.getClass().getDeclaredField("any");
            if (f.getAnnotation(XmlAnyElement.class) != null) {
                Object old = ReflectionUtil.setAccessible(f).get(parent);
                if (old instanceof Element
                    && DOMUtils.getElementQName(element).equals(DOMUtils.getElementQName((Element)old))) {
                    ReflectionUtil.setAccessible(f).set(parent, element);
                }
            }
        }
        if (o == null) {
            return;
        }
        Node nd = element.getFirstChild();
        while (nd != null) {
            if (nd instanceof Element) {
                walkDom(pfx + "  ", (Element)nd, binder, o);
            }
            nd = nd.getNextSibling();
        }
    } catch (Throwable t) {
        //ignore -this is a complete hack anyway
    }
}
 
Example #25
Source File: AbstractDataBinding.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Document doEmptyNamespaceHack(Document d, boolean alreadyWritable) {
    boolean hasStuffToRemove = false;
    Element el = DOMUtils.getFirstElement(d.getDocumentElement());
    while (el != null) {
        if ("import".equals(el.getLocalName())
            && StringUtils.isEmpty(el.getAttribute("targetNamespace"))) {
            hasStuffToRemove = true;
            break;
        }
        el = DOMUtils.getNextElement(el);
    }
    if (hasStuffToRemove) {
        // create a copy of the dom so we
        // can modify it.
        if (!alreadyWritable) {
            d = copy(d);
        }
        el = DOMUtils.getFirstElement(d.getDocumentElement());
        while (el != null) {
            if ("import".equals(el.getLocalName())
                && StringUtils.isEmpty(el.getAttribute("targetNamespace"))) {
                d.getDocumentElement().removeChild(el);
                el = DOMUtils.getFirstElement(d.getDocumentElement());
            } else {
                el = DOMUtils.getNextElement(el);
            }
        }
    }

    return d;
}
 
Example #26
Source File: SamlTokenInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private void processSamlToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
        return;
    }
    Element el = (Element)h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
        if ("Assertion".equals(child.getLocalName())) {
            try {
                List<WSSecurityEngineResult> samlResults = processToken(child, message);
                if (samlResults != null) {
                    List<WSHandlerResult> results = CastUtils.cast((List<?>)message
                            .get(WSHandlerConstants.RECV_RESULTS));
                    if (results == null) {
                        results = new ArrayList<WSHandlerResult>();
                        message.put(WSHandlerConstants.RECV_RESULTS, results);
                    }
                    WSHandlerResult rResult = new WSHandlerResult(null, samlResults);
                    results.add(0, rResult);

                    assertSamlTokens(message);
                    
                    Principal principal = 
                        (Principal)samlResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
                    message.put(WSS4JInInterceptor.PRINCIPAL_RESULT, principal);                   
                    
                    SecurityContext sc = message.get(SecurityContext.class);
                    if (sc == null || sc.getUserPrincipal() == null) {
                        message.put(SecurityContext.class, new DefaultSecurityContext(principal, null));
                    }

                }
            } catch (WSSecurityException ex) {
                throw new Fault(ex);
            }
        }
        child = DOMUtils.getNextElement(child);
    }
}
 
Example #27
Source File: SourceGenerator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Element getActualRepElement(List<Element> repElements, Element xmlElement) {
    if (xmlElement != null) {
        return xmlElement;
    }
    for (Element el : repElements) {
        Element param = DOMUtils.getFirstChildWithName(el, getWadlNamespace(), "param");
        if (param != null) {
            return el;
        }
    }
    return repElements.isEmpty() ? null : repElements.get(0);
}
 
Example #28
Source File: XMLTypeCreator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Type getValueType(Element mapping, Element parameter) {
    String spec = DOMUtils.getAttributeValueEmptyNull(parameter, "valueType");
    if (spec == null) {
        return null;
    }
    return getGenericParameterFromSpec(mapping, spec);
}
 
Example #29
Source File: WSS11Builder.java    From steady with Apache License 2.0 5 votes vote down vote up
private void processAlternative(Element element, Wss11 parent, SPConstants consts) {
    Element polEl = PolicyConstants.findPolicyElement(element);
    if (polEl != null) {
        Element child = DOMUtils.getFirstElement(polEl);
        while (child != null) {
            String name = child.getLocalName();

            if (SPConstants.MUST_SUPPORT_REF_KEY_IDENTIFIER.equals(name)) {
                parent.setMustSupportRefKeyIdentifier(true);
            } else if (SPConstants.MUST_SUPPORT_REF_ISSUER_SERIAL.equals(name)) {
                parent.setMustSupportRefIssuerSerial(true);
            } else if (SPConstants.MUST_SUPPORT_REF_EXTERNAL_URI.equals(name)) {
                parent.setMustSupportRefExternalURI(true);
            } else if (SPConstants.MUST_SUPPORT_REF_EMBEDDED_TOKEN.equals(name)) {
                parent.setMustSupportRefEmbeddedToken(true);

            } else if (SPConstants.MUST_SUPPORT_REF_THUMBPRINT.equals(name)) {
                parent.setMustSupportRefThumbprint(true);

            } else if (SPConstants.MUST_SUPPORT_REF_ENCRYPTED_KEY.equals(name)) {
                parent.setMustSupportRefEncryptedKey(true);

            } else if (SPConstants.REQUIRE_SIGNATURE_CONFIRMATION.equals(name)) {
                parent.setRequireSignatureConfirmation(true);
            } 
            child = DOMUtils.getNextElement(child);
        }
    }
}
 
Example #30
Source File: TransformUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected static void convertToQNamesMap(Map<String, String> map,
                                         QNamesMap elementsMap,
                                         Map<String, String> nsMap) {
    if (map != null) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            QName lname = DOMUtils.convertStringToQName(entry.getKey());
            QName rname = DOMUtils.convertStringToQName(entry.getValue());
            elementsMap.put(lname, rname);
            if (nsMap != null && !isEmptyQName(rname)
                && ("*".equals(lname.getLocalPart()) && "*".equals(rname.getLocalPart()))) {
                nsMap.put(lname.getNamespaceURI(), rname.getNamespaceURI());
            }
        }
    }
}