Search in sources :

Example 66 with CachedOutputStream

use of org.apache.cxf.io.CachedOutputStream in project cxf by apache.

the class JwsMultipartSignatureInFilter method filter.

@Override
public void filter(List<Attachment> atts) {
    if (atts.size() < 2) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    Attachment sigPart = atts.remove(atts.size() - 1);
    final String jwsSequence;
    try {
        jwsSequence = IOUtils.readStringFromStream(sigPart.getDataHandler().getInputStream());
    } catch (IOException ex) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    final String base64UrlEncodedHeaders;
    final String base64UrlEncodedSignature;
    if (!useJwsJsonSignatureFormat) {
        String[] parts = JoseUtils.getCompactParts(jwsSequence);
        if (parts.length != 3 || !parts[1].isEmpty()) {
            throw ExceptionUtils.toBadRequestException(null, null);
        }
        base64UrlEncodedHeaders = parts[0];
        base64UrlEncodedSignature = parts[2];
    } else {
        Map<String, Object> parts = reader.fromJson(jwsSequence);
        if (parts.size() != 2 || !parts.containsKey("protected") || !parts.containsKey("signature")) {
            throw ExceptionUtils.toBadRequestException(null, null);
        }
        base64UrlEncodedHeaders = (String) parts.get("protected");
        base64UrlEncodedSignature = (String) parts.get("signature");
    }
    JwsHeaders headers = new JwsHeaders(new JsonMapObjectReaderWriter().fromJson(JoseUtils.decodeToString(base64UrlEncodedHeaders)));
    JoseUtils.traceHeaders(headers);
    if (Boolean.FALSE != headers.getPayloadEncodingStatus()) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    final JwsSignatureVerifier theVerifier;
    if (verifier == null) {
        Properties props = KeyManagementUtils.loadStoreProperties(message, true, JoseConstants.RSSEC_SIGNATURE_IN_PROPS, JoseConstants.RSSEC_SIGNATURE_PROPS);
        theVerifier = JwsUtils.loadSignatureVerifier(message, props, headers);
    } else {
        theVerifier = verifier;
    }
    JwsVerificationSignature sig = theVerifier.createJwsVerificationSignature(headers);
    if (sig == null) {
        throw ExceptionUtils.toBadRequestException(null, null);
    }
    byte[] signatureBytes = JoseUtils.decode(base64UrlEncodedSignature);
    byte[] headerBytesWithDot = StringUtils.toBytesASCII(base64UrlEncodedHeaders + '.');
    sig.update(headerBytesWithDot, 0, headerBytesWithDot.length);
    int attSize = atts.size();
    for (int i = 0; i < attSize; i++) {
        Attachment dataPart = atts.get(i);
        final InputStream dataPartStream;
        try {
            dataPartStream = dataPart.getDataHandler().getDataSource().getInputStream();
        } catch (IOException ex) {
            throw ExceptionUtils.toBadRequestException(ex, null);
        }
        boolean verifyOnLastRead = i == attSize - 1 ? true : false;
        JwsInputStream jwsStream = new JwsInputStream(dataPartStream, sig, signatureBytes, verifyOnLastRead);
        final InputStream newStream;
        if (bufferPayload) {
            CachedOutputStream cos = new CachedOutputStream();
            try {
                IOUtils.copy(jwsStream, cos);
                newStream = cos.getInputStream();
            } catch (Exception ex) {
                throw ExceptionUtils.toBadRequestException(ex, null);
            }
        } else {
            newStream = jwsStream;
        }
        Attachment newDataPart = new Attachment(newStream, dataPart.getHeaders());
        atts.set(i, newDataPart);
    }
}
Also used : JwsInputStream(org.apache.cxf.rs.security.jose.jws.JwsInputStream) InputStream(java.io.InputStream) JsonMapObjectReaderWriter(org.apache.cxf.jaxrs.json.basic.JsonMapObjectReaderWriter) Attachment(org.apache.cxf.jaxrs.ext.multipart.Attachment) IOException(java.io.IOException) Properties(java.util.Properties) IOException(java.io.IOException) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) JwsHeaders(org.apache.cxf.rs.security.jose.jws.JwsHeaders) JwsVerificationSignature(org.apache.cxf.rs.security.jose.jws.JwsVerificationSignature) JwsInputStream(org.apache.cxf.rs.security.jose.jws.JwsInputStream)

Example 67 with CachedOutputStream

use of org.apache.cxf.io.CachedOutputStream in project cxf by apache.

the class SamlEnvelopedOutInterceptor method createEnvelopedSamlToken.

// enveloping & detached sigs will be supported too
private Document createEnvelopedSamlToken(Message message, Document payloadDoc) throws Exception {
    Element docEl = payloadDoc.getDocumentElement();
    SamlAssertionWrapper assertion = SAMLUtils.createAssertion(message);
    QName rootName = DOMUtils.getElementQName(payloadDoc.getDocumentElement());
    if (rootName.equals(envelopeQName)) {
        docEl.appendChild(assertion.toDOM(payloadDoc));
        return payloadDoc;
    }
    Document newDoc = DOMUtils.createDocument();
    Element root = newDoc.createElementNS(envelopeQName.getNamespaceURI(), envelopeQName.getPrefix() + ":" + envelopeQName.getLocalPart());
    newDoc.appendChild(root);
    Element assertionEl = assertion.toDOM(newDoc);
    root.appendChild(assertionEl);
    payloadDoc.removeChild(docEl);
    newDoc.adoptNode(docEl);
    root.appendChild(docEl);
    if (signLater) {
        // It appears adopting and removing nodes
        // leaves some stale refs/state with adopted nodes and thus the digest ends up
        // being wrong on the server side if XML sig is applied later in the enveloped mode
        // TODO: this is not critical now - but figure out if we can avoid copying
        // DOMs
        CachedOutputStream bos = new CachedOutputStream();
        StaxUtils.writeTo(newDoc, bos);
        return StaxUtils.read(bos.getInputStream());
    }
    return newDoc;
}
Also used : QName(javax.xml.namespace.QName) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Document(org.w3c.dom.Document) CachedOutputStream(org.apache.cxf.io.CachedOutputStream)

Example 68 with CachedOutputStream

use of org.apache.cxf.io.CachedOutputStream in project cxf by apache.

the class JAXRSOutInterceptor method serializeMessage.

private void serializeMessage(ServerProviderFactory providerFactory, Message message, Response theResponse, OperationResourceInfo ori, boolean firstTry) {
    ResponseImpl response = (ResponseImpl) JAXRSUtils.copyResponseIfNeeded(theResponse);
    final Exchange exchange = message.getExchange();
    boolean headResponse = response.getStatus() == 200 && firstTry && ori != null && HttpMethod.HEAD.equals(ori.getHttpMethod());
    Object entity = response.getActualEntity();
    if (headResponse && entity != null) {
        LOG.info(new org.apache.cxf.common.i18n.Message("HEAD_WITHOUT_ENTITY", BUNDLE).toString());
        entity = null;
    }
    Method invoked = ori == null ? null : ori.getAnnotatedMethod() != null ? ori.getAnnotatedMethod() : ori.getMethodToInvoke();
    Annotation[] annotations;
    Annotation[] staticAnns = ori != null ? ori.getOutAnnotations() : new Annotation[] {};
    Annotation[] responseAnns = response.getEntityAnnotations();
    if (responseAnns != null) {
        annotations = new Annotation[staticAnns.length + responseAnns.length];
        System.arraycopy(staticAnns, 0, annotations, 0, staticAnns.length);
        System.arraycopy(responseAnns, 0, annotations, staticAnns.length, responseAnns.length);
    } else {
        annotations = staticAnns;
    }
    response.setStatus(getActualStatus(response.getStatus(), entity));
    response.setEntity(entity, annotations);
    // Prepare the headers
    MultivaluedMap<String, Object> responseHeaders = prepareResponseHeaders(message, response, entity, firstTry);
    // Run the filters
    try {
        JAXRSUtils.runContainerResponseFilters(providerFactory, response, message, ori, invoked);
    } catch (Throwable ex) {
        handleWriteException(providerFactory, message, ex, firstTry);
        return;
    }
    // Write the entity
    entity = InjectionUtils.getEntity(response.getActualEntity());
    setResponseStatus(message, getActualStatus(response.getStatus(), entity));
    if (entity == null) {
        if (!headResponse) {
            responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, "0");
            if (MessageUtils.getContextualBoolean(message, "remove.content.type.for.empty.response", false)) {
                responseHeaders.remove(HttpHeaders.CONTENT_TYPE);
                message.remove(Message.CONTENT_TYPE);
            }
        }
        HttpUtils.convertHeaderValuesToString(responseHeaders, true);
        return;
    }
    Object ignoreWritersProp = exchange.get(JAXRSUtils.IGNORE_MESSAGE_WRITERS);
    boolean ignoreWriters = ignoreWritersProp != null && Boolean.valueOf(ignoreWritersProp.toString());
    if (ignoreWriters) {
        writeResponseToStream(message.getContent(OutputStream.class), entity);
        return;
    }
    MediaType responseMediaType = getResponseMediaType(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE));
    Class<?> serviceCls = invoked != null ? ori.getClassResourceInfo().getServiceClass() : null;
    Class<?> targetType = InjectionUtils.getRawResponseClass(entity);
    Type genericType = InjectionUtils.getGenericResponseType(invoked, serviceCls, response.getActualEntity(), targetType, exchange);
    targetType = InjectionUtils.updateParamClassToTypeIfNeeded(targetType, genericType);
    annotations = response.getEntityAnnotations();
    List<WriterInterceptor> writers = providerFactory.createMessageBodyWriterInterceptor(targetType, genericType, annotations, responseMediaType, message, ori == null ? null : ori.getNameBindings());
    OutputStream outOriginal = message.getContent(OutputStream.class);
    if (writers == null || writers.isEmpty()) {
        writeResponseErrorMessage(message, outOriginal, "NO_MSG_WRITER", targetType, responseMediaType);
        return;
    }
    try {
        boolean checkWriters = false;
        if (responseMediaType.isWildcardSubtype()) {
            Produces pM = AnnotationUtils.getMethodAnnotation(ori == null ? null : ori.getAnnotatedMethod(), Produces.class);
            Produces pC = AnnotationUtils.getClassAnnotation(serviceCls, Produces.class);
            checkWriters = pM == null && pC == null;
        }
        responseMediaType = checkFinalContentType(responseMediaType, writers, checkWriters);
    } catch (Throwable ex) {
        if (LOG.isLoggable(Level.FINE)) {
            LOG.log(Level.FINE, ex.getMessage(), ex);
        }
        handleWriteException(providerFactory, message, ex, firstTry);
        return;
    }
    String finalResponseContentType = JAXRSUtils.mediaTypeToString(responseMediaType);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Response content type is: " + finalResponseContentType);
    }
    responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, finalResponseContentType);
    message.put(Message.CONTENT_TYPE, finalResponseContentType);
    boolean enabled = checkBufferingMode(message, writers, firstTry);
    try {
        try {
            // NOPMD
            JAXRSUtils.writeMessageBody(writers, entity, targetType, genericType, annotations, responseMediaType, responseHeaders, message);
            if (isResponseRedirected(message)) {
                return;
            }
            checkCachedStream(message, outOriginal, enabled);
        } finally {
            if (enabled) {
                OutputStream os = message.getContent(OutputStream.class);
                if (os != outOriginal && os instanceof CachedOutputStream) {
                    os.close();
                }
                message.setContent(OutputStream.class, outOriginal);
                message.put(XMLStreamWriter.class.getName(), null);
            }
        }
    } catch (Throwable ex) {
        logWriteError(firstTry, targetType, responseMediaType);
        handleWriteException(providerFactory, message, ex, firstTry);
    }
}
Also used : WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) Message(org.apache.cxf.message.Message) OutputStream(java.io.OutputStream) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) HttpMethod(javax.ws.rs.HttpMethod) Method(java.lang.reflect.Method) ResponseImpl(org.apache.cxf.jaxrs.impl.ResponseImpl) Annotation(java.lang.annotation.Annotation) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) Exchange(org.apache.cxf.message.Exchange) MediaType(javax.ws.rs.core.MediaType) Type(java.lang.reflect.Type) Produces(javax.ws.rs.Produces) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) MediaType(javax.ws.rs.core.MediaType)

Example 69 with CachedOutputStream

use of org.apache.cxf.io.CachedOutputStream in project cxf by apache.

the class XSLTJaxbProvider method unmarshalFromReader.

@Override
protected Object unmarshalFromReader(Unmarshaller unmarshaller, XMLStreamReader reader, Annotation[] anns, MediaType mt) throws JAXBException {
    CachedOutputStream out = new CachedOutputStream();
    try {
        XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out);
        StaxUtils.copy(new StaxSource(reader), writer);
        writer.writeEndDocument();
        writer.flush();
        writer.close();
        return unmarshalFromInputStream(unmarshaller, out.getInputStream(), anns, mt);
    } catch (Exception ex) {
        throw ExceptionUtils.toBadRequestException(ex, null);
    }
}
Also used : XMLStreamWriter(javax.xml.stream.XMLStreamWriter) StaxSource(org.apache.cxf.staxutils.StaxSource) JAXBException(javax.xml.bind.JAXBException) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) CachedOutputStream(org.apache.cxf.io.CachedOutputStream)

Example 70 with CachedOutputStream

use of org.apache.cxf.io.CachedOutputStream in project cxf by apache.

the class XSLTJaxbProvider method marshalToWriter.

@Override
protected void marshalToWriter(Marshaller ms, Object obj, XMLStreamWriter writer, Annotation[] anns, MediaType mt) throws Exception {
    CachedOutputStream out = new CachedOutputStream();
    marshalToOutputStream(ms, obj, out, anns, mt);
    StaxUtils.copy(new StreamSource(out.getInputStream()), writer);
}
Also used : StreamSource(javax.xml.transform.stream.StreamSource) CachedOutputStream(org.apache.cxf.io.CachedOutputStream)

Aggregations

CachedOutputStream (org.apache.cxf.io.CachedOutputStream)105 InputStream (java.io.InputStream)38 IOException (java.io.IOException)35 Test (org.junit.Test)24 Message (org.apache.cxf.message.Message)22 OutputStream (java.io.OutputStream)18 Fault (org.apache.cxf.interceptor.Fault)18 MessageImpl (org.apache.cxf.message.MessageImpl)11 ByteArrayInputStream (java.io.ByteArrayInputStream)10 XMLStreamException (javax.xml.stream.XMLStreamException)10 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)10 PrintWriter (java.io.PrintWriter)8 XMLStreamReader (javax.xml.stream.XMLStreamReader)6 StreamSource (javax.xml.transform.stream.StreamSource)6 Endpoint (org.apache.cxf.endpoint.Endpoint)6 ExchangeImpl (org.apache.cxf.message.ExchangeImpl)6 RMMessage (org.apache.cxf.ws.rm.persistence.RMMessage)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 Source (javax.xml.transform.Source)5 ArrayList (java.util.ArrayList)4