Search in sources :

Example 51 with W3CDOMStreamWriter

use of org.apache.cxf.staxutils.W3CDOMStreamWriter in project cxf by apache.

the class JSONProvider method readFrom.

public T readFrom(Class<T> type, Type genericType, Annotation[] anns, MediaType mt, MultivaluedMap<String, String> headers, InputStream is) throws IOException {
    if (isPayloadEmpty(headers)) {
        if (AnnotationUtils.getAnnotation(anns, Nullable.class) != null) {
            return null;
        }
        reportEmptyContentLength();
    }
    XMLStreamReader reader = null;
    String enc = HttpUtils.getEncoding(mt, StandardCharsets.UTF_8.name());
    Unmarshaller unmarshaller = null;
    try {
        InputStream realStream = getInputStream(type, genericType, is);
        if (Document.class.isAssignableFrom(type)) {
            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
            reader = createReader(type, realStream, false, enc);
            copyReaderToWriter(reader, writer);
            return type.cast(writer.getDocument());
        }
        boolean isCollection = InjectionUtils.isSupportedCollectionOrArray(type);
        Class<?> theGenericType = isCollection ? InjectionUtils.getActualType(genericType) : type;
        Class<?> theType = getActualType(theGenericType, genericType, anns);
        unmarshaller = createUnmarshaller(theType, genericType, isCollection);
        XMLStreamReader xsr = createReader(type, realStream, isCollection, enc);
        Object response;
        if (JAXBElement.class.isAssignableFrom(type) || !isCollection && (unmarshalAsJaxbElement || jaxbElementClassMap != null && jaxbElementClassMap.containsKey(theType.getName()))) {
            response = unmarshaller.unmarshal(xsr, theType);
        } else {
            response = unmarshaller.unmarshal(xsr);
        }
        if (response instanceof JAXBElement && !JAXBElement.class.isAssignableFrom(type)) {
            response = ((JAXBElement<?>) response).getValue();
        }
        if (isCollection) {
            response = ((CollectionWrapper) response).getCollectionOrArray(unmarshaller, theType, type, genericType, org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(theGenericType, anns));
        } else {
            response = checkAdapter(response, type, anns, false);
        }
        return type.cast(response);
    } catch (JAXBException e) {
        handleJAXBException(e, true);
    } catch (XMLStreamException e) {
        if (e.getCause() instanceof JSONSequenceTooLargeException) {
            throw new WebApplicationException(413);
        }
        handleXMLStreamException(e, true);
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw ExceptionUtils.toBadRequestException(e, null);
    } finally {
        try {
            StaxUtils.close(reader);
        } catch (XMLStreamException e) {
            throw ExceptionUtils.toBadRequestException(e, null);
        }
        JAXBUtils.closeUnmarshaller(unmarshaller);
    }
    // unreachable
    return null;
}
Also used : W3CDOMStreamWriter(org.apache.cxf.staxutils.W3CDOMStreamWriter) XMLStreamReader(javax.xml.stream.XMLStreamReader) WebApplicationException(javax.ws.rs.WebApplicationException) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) InputStream(java.io.InputStream) JAXBException(javax.xml.bind.JAXBException) JAXBElement(javax.xml.bind.JAXBElement) XMLStreamException(javax.xml.stream.XMLStreamException) JSONSequenceTooLargeException(org.codehaus.jettison.JSONSequenceTooLargeException) JAXBException(javax.xml.bind.JAXBException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) JSONSequenceTooLargeException(org.codehaus.jettison.JSONSequenceTooLargeException) XMLStreamException(javax.xml.stream.XMLStreamException) Unmarshaller(javax.xml.bind.Unmarshaller) Nullable(org.apache.cxf.jaxrs.ext.Nullable)

Example 52 with W3CDOMStreamWriter

use of org.apache.cxf.staxutils.W3CDOMStreamWriter in project cxf by apache.

the class STSInvoker method invoke.

public Object invoke(Exchange exchange, Object o) {
    AddressingProperties inProps = (AddressingProperties) exchange.getInMessage().getContextualProperty(JAXWSAConstants.ADDRESSING_PROPERTIES_INBOUND);
    if (inProps != null) {
        AddressingProperties props = inProps.createCompatibleResponseProperties();
        AttributedURIType action = new AttributedURIType();
        action.setValue(inProps.getAction().getValue().replace("/RST/", "/RSTR/"));
        props.setAction(action);
        exchange.getOutMessage().put(JAXWSAConstants.ADDRESSING_PROPERTIES_OUTBOUND, props);
    }
    MessageContentsList lst = (MessageContentsList) o;
    DOMSource src = (DOMSource) lst.get(0);
    Node nd = src.getNode();
    final Element requestEl;
    if (nd instanceof Document) {
        requestEl = ((Document) nd).getDocumentElement();
    } else {
        requestEl = (Element) nd;
    }
    String namespace = requestEl.getNamespaceURI();
    String prefix = requestEl.getPrefix();
    SecurityToken cancelOrRenewToken = null;
    if ("RequestSecurityToken".equals(requestEl.getLocalName())) {
        try {
            String requestType = null;
            Element binaryExchange = null;
            String tokenType = null;
            Element el = DOMUtils.getFirstElement(requestEl);
            while (el != null) {
                String localName = el.getLocalName();
                if (namespace.equals(el.getNamespaceURI())) {
                    if ("RequestType".equals(localName)) {
                        requestType = el.getTextContent();
                    } else if ("CancelTarget".equals(localName) || "RenewTarget".equals(localName)) {
                        cancelOrRenewToken = findCancelOrRenewToken(exchange, el);
                    } else if ("BinaryExchange".equals(localName)) {
                        binaryExchange = el;
                    } else if ("TokenType".equals(localName)) {
                        tokenType = DOMUtils.getContent(el);
                    }
                }
                el = DOMUtils.getNextElement(el);
            }
            if (requestType == null) {
                requestType = "/Issue";
            }
            if (requestType.endsWith("/Issue") && !STSUtils.getTokenTypeSCT(namespace).equals(tokenType)) {
                throw new Exception("Unknown token type: " + tokenType);
            }
            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
            writer.setNsRepairing(true);
            if (requestType.endsWith("/Issue")) {
                doIssue(requestEl, exchange, binaryExchange, writer, prefix, namespace);
            } else if (requestType.endsWith("/Cancel")) {
                doCancel(exchange, cancelOrRenewToken, writer, prefix, namespace);
            } else if (requestType.endsWith("/Renew")) {
                doRenew(requestEl, exchange, cancelOrRenewToken, binaryExchange, writer, prefix, namespace);
            }
            return new MessageContentsList(new DOMSource(writer.getDocument()));
        } catch (RuntimeException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new Fault(ex);
        }
    }
    throw new Fault("Unknown SecureConversation element: " + requestEl.getLocalName(), LOG);
}
Also used : W3CDOMStreamWriter(org.apache.cxf.staxutils.W3CDOMStreamWriter) DOMSource(javax.xml.transform.dom.DOMSource) MessageContentsList(org.apache.cxf.message.MessageContentsList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) AttributedURIType(org.apache.cxf.ws.addressing.AttributedURIType) Fault(org.apache.cxf.interceptor.Fault) Document(org.w3c.dom.Document) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) XMLStreamException(javax.xml.stream.XMLStreamException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) AddressingProperties(org.apache.cxf.ws.addressing.AddressingProperties)

Example 53 with W3CDOMStreamWriter

use of org.apache.cxf.staxutils.W3CDOMStreamWriter in project cxf by apache.

the class SecurityToken method cloneElement.

private static Element cloneElement(Element el) {
    try {
        W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
        writer.setNsRepairing(true);
        StaxUtils.copy(el, writer);
        return writer.getDocument().getDocumentElement();
    } catch (Exception ex) {
    // ignore
    }
    return el;
}
Also used : W3CDOMStreamWriter(org.apache.cxf.staxutils.W3CDOMStreamWriter) IOException(java.io.IOException) DateTimeParseException(java.time.format.DateTimeParseException) XMLStreamException(javax.xml.stream.XMLStreamException)

Example 54 with W3CDOMStreamWriter

use of org.apache.cxf.staxutils.W3CDOMStreamWriter in project cxf by apache.

the class AbstractSTSClient method validate.

/**
 * Make an "Validate" invocation and return the response as a STSResponse Object
 */
protected STSResponse validate(SecurityToken tok, String tokentype) throws Exception {
    createClient();
    if (tokentype == null) {
        tokentype = tokenType;
    }
    if (tokentype == null) {
        tokentype = namespace + "/RSTR/Status";
    }
    Policy validatePolicy = new Policy();
    ExactlyOne one = new ExactlyOne();
    validatePolicy.addPolicyComponent(one);
    All all = new All();
    one.addPolicyComponent(all);
    all.addAssertion(getAddressingAssertion());
    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    BindingOperationInfo boi = findOperation("/RST/Validate");
    if (boi == null) {
        boi = findOperation("/RST/Issue");
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, validatePolicy);
    }
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/Validate");
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "TokenType", namespace);
    writer.writeCharacters(tokentype);
    writer.writeEndElement();
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Validate");
    writer.writeEndElement();
    if (tokentype.endsWith("/RSTR/Status")) {
        addClaims(writer);
        writer.writeStartElement("wst", "ValidateTarget", namespace);
        Element el = tok.getToken();
        if (el != null) {
            StaxUtils.copy(el, writer);
        }
        writer.writeEndElement();
        writer.writeEndElement();
        Object[] o = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
        @SuppressWarnings("unchecked") Collection<Attachment> attachments = (Collection<Attachment>) client.getResponseContext().get(Message.ATTACHMENTS);
        return new STSResponse((DOMSource) o[0], null, null, null, attachments);
    }
    if (enableLifetime) {
        addLifetime(writer);
    }
    // Default to Bearer KeyType
    String keyTypeTemplate = keyType;
    if (keyTypeTemplate == null) {
        keyTypeTemplate = namespace + "/Bearer";
    }
    keyTypeTemplate = writeKeyType(writer, keyTypeTemplate);
    byte[] requestorEntropy = null;
    X509Certificate cert = null;
    Crypto crypto = null;
    if (keySize <= 0) {
        keySize = 256;
    }
    if (keyTypeTemplate != null && keyTypeTemplate.endsWith("SymmetricKey")) {
        requestorEntropy = writeElementsForRSTSymmetricKey(writer, false);
    } else if (keyTypeTemplate != null && keyTypeTemplate.endsWith("PublicKey")) {
        // Use the given cert, or else get it from a Crypto instance
        if (useKeyCertificate != null) {
            cert = useKeyCertificate;
        } else {
            crypto = createCrypto(false);
            cert = getCert(crypto);
        }
        writeElementsForRSTPublicKey(writer, cert);
    }
    writeRenewalSemantics(writer);
    addClaims(writer);
    writer.writeStartElement("wst", "ValidateTarget", namespace);
    Element el = tok.getToken();
    StaxUtils.copy(el, writer);
    writer.writeEndElement();
    writer.writeEndElement();
    Object[] o = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    @SuppressWarnings("unchecked") Collection<Attachment> attachments = (Collection<Attachment>) client.getResponseContext().get(Message.ATTACHMENTS);
    return new STSResponse((DOMSource) o[0], requestorEntropy, cert, crypto, attachments);
}
Also used : Policy(org.apache.neethi.Policy) EffectivePolicy(org.apache.cxf.ws.policy.EffectivePolicy) All(org.apache.neethi.All) W3CDOMStreamWriter(org.apache.cxf.staxutils.W3CDOMStreamWriter) BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) DOMSource(javax.xml.transform.dom.DOMSource) ExtensibilityElement(javax.wsdl.extensions.ExtensibilityElement) Element(org.w3c.dom.Element) Attachment(org.apache.cxf.message.Attachment) ExactlyOne(org.apache.neethi.ExactlyOne) X509Certificate(java.security.cert.X509Certificate) Crypto(org.apache.wss4j.common.crypto.Crypto) Collection(java.util.Collection) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection)

Example 55 with W3CDOMStreamWriter

use of org.apache.cxf.staxutils.W3CDOMStreamWriter in project cxf by apache.

the class SAAJOutInterceptorTest method testHandleHeader.

@Test
public void testHandleHeader() throws Exception {
    soapMessage = TestUtil.createEmptySoapMessage(Soap11.getInstance(), chain);
    soapMessage.setContent(OutputStream.class, new ByteArrayOutputStream());
    SOAPMessage m = SAAJFactoryResolver.createMessageFactory(soapMessage.getVersion()).createMessage();
    InputStream ins = getClass().getResourceAsStream("../test-soap-header.xml");
    m.getSOAPPart().setContent(new StreamSource(ins));
    Element el = DOMUtils.getFirstElement(m.getSOAPPart().getEnvelope().getHeader());
    el = (Element) DOMUtils.getDomElement(el);
    List<Header> h = soapMessage.getHeaders();
    while (el != null) {
        h.add(new SoapHeader(DOMUtils.getElementQName(el), el));
        el = DOMUtils.getNextElement(el);
    }
    soapMessage.setContent(SOAPMessage.class, m);
    W3CDOMStreamWriter writer = new SAAJStreamWriter(m.getSOAPPart());
    soapMessage.setContent(XMLStreamWriter.class, writer);
    soi.handleMessage(soapMessage);
}
Also used : W3CDOMStreamWriter(org.apache.cxf.staxutils.W3CDOMStreamWriter) SoapHeader(org.apache.cxf.binding.soap.SoapHeader) Header(org.apache.cxf.headers.Header) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) Element(org.w3c.dom.Element) SoapHeader(org.apache.cxf.binding.soap.SoapHeader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SOAPMessage(javax.xml.soap.SOAPMessage) Test(org.junit.Test)

Aggregations

W3CDOMStreamWriter (org.apache.cxf.staxutils.W3CDOMStreamWriter)60 Element (org.w3c.dom.Element)29 DOMSource (javax.xml.transform.dom.DOMSource)24 XMLStreamException (javax.xml.stream.XMLStreamException)15 Document (org.w3c.dom.Document)14 WebClient (org.apache.cxf.jaxrs.client.WebClient)9 Node (org.w3c.dom.Node)9 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)8 Fault (org.apache.cxf.interceptor.Fault)8 XMLStreamReader (javax.xml.stream.XMLStreamReader)7 BindingOperationInfo (org.apache.cxf.service.model.BindingOperationInfo)7 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)7 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)7 JAXBElement (javax.xml.bind.JAXBElement)6 JAXBException (javax.xml.bind.JAXBException)5 SOAPMessage (javax.xml.soap.SOAPMessage)5 SoapFault (org.apache.cxf.binding.soap.SoapFault)5 SoapMessage (org.apache.cxf.binding.soap.SoapMessage)5 InputStream (java.io.InputStream)4 HashMap (java.util.HashMap)4