Search in sources :

Example 31 with CachedOutputStream

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

the class CreateSignatureInterceptor method addDigest.

private void addDigest(WriterInterceptorContext context) throws IOException {
    // make sure we have all content
    OutputStream originalOutputStream = context.getOutputStream();
    CachedOutputStream cachedOutputStream = new CachedOutputStream();
    context.setOutputStream(cachedOutputStream);
    context.proceed();
    cachedOutputStream.flush();
    // then digest using requested encoding
    String encoding = context.getMediaType().getParameters().getOrDefault(MediaType.CHARSET_PARAMETER, StandardCharsets.UTF_8.toString());
    String digestAlgorithm = digestAlgorithmName;
    if (digestAlgorithm == null) {
        Message m = PhaseInterceptorChain.getCurrentMessage();
        digestAlgorithm = (String) m.getContextualProperty(HTTPSignatureConstants.RSSEC_HTTP_SIGNATURE_DIGEST_ALGORITHM);
        if (digestAlgorithm == null) {
            digestAlgorithm = DefaultSignatureConstants.DIGEST_ALGORITHM;
        }
    }
    // not so nice - would be better to have a stream
    String digest = SignatureHeaderUtils.createDigestHeader(new String(cachedOutputStream.getBytes(), encoding), digestAlgorithm);
    // add header
    context.getHeaders().add(DIGEST_HEADER_NAME, digest);
    sign(context);
    // write the contents
    context.setOutputStream(originalOutputStream);
    IOUtils.copy(cachedOutputStream.getInputStream(), originalOutputStream);
}
Also used : Message(org.apache.cxf.message.Message) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) CachedOutputStream(org.apache.cxf.io.CachedOutputStream)

Example 32 with CachedOutputStream

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

the class JwsJsonWriterInterceptor method aroundWriteTo.

@Override
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException {
    if (ctx.getEntity() == null) {
        ctx.proceed();
        return;
    }
    List<String> propLocs = getPropertyLocations();
    List<JwsHeaders> protectedHeaders = new ArrayList<>(propLocs.size());
    for (int i = 0; i < propLocs.size(); i++) {
        protectedHeaders.add(new JwsHeaders());
    }
    List<JwsSignatureProvider> sigProviders = getInitializedSigProviders(propLocs, protectedHeaders);
    OutputStream actualOs = ctx.getOutputStream();
    if (useJwsOutputStream) {
        List<String> encodedProtectedHeaders = new ArrayList<>(sigProviders.size());
        List<JwsSignature> signatures = new ArrayList<>(sigProviders.size());
        int size = sigProviders.size();
        for (int i = 0; i < size; i++) {
            JwsSignatureProvider signer = sigProviders.get(i);
            JwsHeaders protectedHeader = protectedHeaders.get(i);
            prepareProtectedHeader(protectedHeader, ctx, signer, size == 1);
            String encoded = Base64UrlUtility.encode(writer.toJson(protectedHeader));
            encodedProtectedHeaders.add(encoded);
            JwsSignature signature = signer.createJwsSignature(protectedHeader);
            byte[] start = StringUtils.toBytesUTF8(encoded + ".");
            signature.update(start, 0, start.length);
            signatures.add(signature);
        }
        ctx.setMediaType(JAXRSUtils.toMediaType(JoseConstants.MEDIA_TYPE_JOSE_JSON));
        actualOs.write(StringUtils.toBytesUTF8("{\"payload\":\""));
        JwsJsonOutputStream jwsStream = new JwsJsonOutputStream(actualOs, encodedProtectedHeaders, signatures);
        Base64UrlOutputStream base64Stream = null;
        if (encodePayload) {
            base64Stream = new Base64UrlOutputStream(jwsStream);
            ctx.setOutputStream(base64Stream);
        } else {
            ctx.setOutputStream(jwsStream);
        }
        ctx.proceed();
        if (base64Stream != null) {
            base64Stream.flush();
        }
        jwsStream.flush();
    } else {
        CachedOutputStream cos = new CachedOutputStream();
        ctx.setOutputStream(cos);
        ctx.proceed();
        JwsJsonProducer p = new JwsJsonProducer(new String(cos.getBytes(), StandardCharsets.UTF_8));
        int size = sigProviders.size();
        for (int i = 0; i < size; i++) {
            JwsSignatureProvider signer = sigProviders.get(i);
            JwsHeaders protectedHeader = protectedHeaders.get(i);
            prepareProtectedHeader(protectedHeader, ctx, signer, size == 1);
            p.signWith(signer, protectedHeader, null);
        }
        ctx.setMediaType(JAXRSUtils.toMediaType(JoseConstants.MEDIA_TYPE_JOSE_JSON));
        writeJws(p, actualOs);
    }
}
Also used : JwsSignature(org.apache.cxf.rs.security.jose.jws.JwsSignature) OutputStream(java.io.OutputStream) Base64UrlOutputStream(org.apache.cxf.common.util.Base64UrlOutputStream) JwsJsonOutputStream(org.apache.cxf.rs.security.jose.jws.JwsJsonOutputStream) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) ArrayList(java.util.ArrayList) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) JwsHeaders(org.apache.cxf.rs.security.jose.jws.JwsHeaders) JwsJsonOutputStream(org.apache.cxf.rs.security.jose.jws.JwsJsonOutputStream) Base64UrlOutputStream(org.apache.cxf.common.util.Base64UrlOutputStream) JwsJsonProducer(org.apache.cxf.rs.security.jose.jws.JwsJsonProducer) JwsSignatureProvider(org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider)

Example 33 with CachedOutputStream

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

the class RetransmissionQueueImpl method doResend.

private void doResend(SoapMessage message) {
    InputStream is = null;
    try {
        // NOPMD
        // initialize copied interceptor chain for message
        PhaseInterceptorChain retransmitChain = manager.getRetransmitChain(message);
        ProtocolVariation protocol = RMContextUtils.getProtocolVariation(message);
        Endpoint endpoint = manager.getReliableEndpoint(message).getEndpoint(protocol);
        PhaseChainCache cache = new PhaseChainCache();
        boolean after = true;
        if (retransmitChain == null) {
            // no saved retransmit chain, so construct one from scratch (won't work for WS-Security on server, so
            // need to fix)
            retransmitChain = buildRetransmitChain(endpoint, cache);
            after = false;
        }
        message.setInterceptorChain(retransmitChain);
        // clear flag for SOAP out interceptor so envelope will be written
        message.remove(SoapOutInterceptor.WROTE_ENVELOPE_START);
        // discard all saved content
        Set<Class<?>> formats = message.getContentFormats();
        List<CachedOutputStreamCallback> callbacks = null;
        for (Class<?> clas : formats) {
            Object content = message.getContent(clas);
            if (content != null) {
                LOG.info("Removing " + clas.getName() + " content of actual type " + content.getClass().getName());
                message.removeContent(clas);
                if (clas == OutputStream.class && content instanceof WriteOnCloseOutputStream) {
                    callbacks = ((WriteOnCloseOutputStream) content).getCallbacks();
                }
            }
        }
        // read SOAP headers from saved input stream
        CachedOutputStream cos = (CachedOutputStream) message.get(RMMessageConstants.SAVED_CONTENT);
        // CachedOutputStream is hold until delivering was successful
        cos.holdTempFile();
        // instance is needed to close input stream later on
        is = cos.getInputStream();
        XMLStreamReader reader = StaxUtils.createXMLStreamReader(is, StandardCharsets.UTF_8.name());
        message.getHeaders().clear();
        if (reader.getEventType() != XMLStreamConstants.START_ELEMENT && reader.nextTag() != XMLStreamConstants.START_ELEMENT) {
            throw new IllegalStateException("No document found");
        }
        readHeaders(reader, message);
        int event;
        while ((event = reader.nextTag()) != XMLStreamConstants.START_ELEMENT) {
            if (event == XMLStreamConstants.END_ELEMENT) {
                throw new IllegalStateException("No body content present");
            }
        }
        // set message addressing properties
        AddressingProperties maps = MAPCodec.getInstance(message.getExchange().getBus()).unmarshalMAPs(message);
        RMContextUtils.storeMAPs(maps, message, true, MessageUtils.isRequestor(message));
        AttributedURIType to = null;
        if (null != maps) {
            to = maps.getTo();
        }
        if (null == to) {
            LOG.log(Level.SEVERE, "NO_ADDRESS_FOR_RESEND_MSG");
            return;
        }
        if (RMUtils.getAddressingConstants().getAnonymousURI().equals(to.getValue())) {
            LOG.log(Level.FINE, "Cannot resend to anonymous target");
            return;
        }
        // initialize conduit for new message
        Conduit c = message.getExchange().getConduit(message);
        if (c == null) {
            c = buildConduit(message, endpoint, to);
        }
        c.prepare(message);
        // replace standard message marshaling with copy from saved stream
        ListIterator<Interceptor<? extends Message>> iterator = retransmitChain.getIterator();
        while (iterator.hasNext()) {
            Interceptor<? extends Message> incept = iterator.next();
            // remove JAX-WS interceptors which handle message modes and such
            if (incept.getClass().getName().startsWith("org.apache.cxf.jaxws.interceptors")) {
                retransmitChain.remove(incept);
            } else if (incept instanceof PhaseInterceptor && Phase.MARSHAL.equals(((PhaseInterceptor<?>) incept).getPhase())) {
                // remove any interceptors from the marshal phase
                retransmitChain.remove(incept);
            }
        }
        retransmitChain.add(new CopyOutInterceptor(reader));
        // restore callbacks on output stream
        if (callbacks != null) {
            OutputStream os = message.getContent(OutputStream.class);
            if (os != null) {
                WriteOnCloseOutputStream woc;
                if (os instanceof WriteOnCloseOutputStream) {
                    woc = (WriteOnCloseOutputStream) os;
                } else {
                    woc = new WriteOnCloseOutputStream(os);
                    message.setContent(OutputStream.class, woc);
                }
                for (CachedOutputStreamCallback cb : callbacks) {
                    woc.registerCallback(cb);
                }
            }
        }
        // send the message
        message.put(RMMessageConstants.RM_RETRANSMISSION, Boolean.TRUE);
        if (after) {
            retransmitChain.doInterceptStartingAfter(message, RMCaptureOutInterceptor.class.getName());
        } else {
            retransmitChain.doIntercept(message);
        }
        if (LOG.isLoggable(Level.INFO)) {
            RMProperties rmps = RMContextUtils.retrieveRMProperties(message, true);
            SequenceType seq = rmps.getSequence();
            LOG.log(Level.INFO, "Retransmitted message " + seq.getMessageNumber() + " in sequence " + seq.getIdentifier().getValue());
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "RESEND_FAILED_MSG", ex);
    } finally {
        // make sure to always close InputStreams of the CachedOutputStream to avoid leaving temp files undeleted
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
            // Ignore
            }
        }
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) PartialXMLStreamReader(org.apache.cxf.staxutils.PartialXMLStreamReader) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) Message(org.apache.cxf.message.Message) WriteOnCloseOutputStream(org.apache.cxf.io.WriteOnCloseOutputStream) CachedOutputStreamCallback(org.apache.cxf.io.CachedOutputStreamCallback) PhaseInterceptor(org.apache.cxf.phase.PhaseInterceptor) WriteOnCloseOutputStream(org.apache.cxf.io.WriteOnCloseOutputStream) OutputStream(java.io.OutputStream) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) AttributedURIType(org.apache.cxf.ws.addressing.AttributedURIType) SequenceType(org.apache.cxf.ws.rm.v200702.SequenceType) RMCaptureOutInterceptor(org.apache.cxf.ws.rm.RMCaptureOutInterceptor) PhaseChainCache(org.apache.cxf.phase.PhaseChainCache) CachedOutputStream(org.apache.cxf.io.CachedOutputStream) RMEndpoint(org.apache.cxf.ws.rm.RMEndpoint) Endpoint(org.apache.cxf.endpoint.Endpoint) AddressingProperties(org.apache.cxf.ws.addressing.AddressingProperties) RMCaptureOutInterceptor(org.apache.cxf.ws.rm.RMCaptureOutInterceptor) AbstractOutDatabindingInterceptor(org.apache.cxf.interceptor.AbstractOutDatabindingInterceptor) Interceptor(org.apache.cxf.interceptor.Interceptor) PhaseInterceptor(org.apache.cxf.phase.PhaseInterceptor) SoapOutInterceptor(org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor) RMProperties(org.apache.cxf.ws.rm.RMProperties) ProtocolVariation(org.apache.cxf.ws.rm.ProtocolVariation) PhaseInterceptorChain(org.apache.cxf.phase.PhaseInterceptorChain) InputStream(java.io.InputStream) IOException(java.io.IOException) RMEndpoint(org.apache.cxf.ws.rm.RMEndpoint) Endpoint(org.apache.cxf.endpoint.Endpoint) XMLStreamException(javax.xml.stream.XMLStreamException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException) RMException(org.apache.cxf.ws.rm.RMException) Conduit(org.apache.cxf.transport.Conduit)

Example 34 with CachedOutputStream

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

the class PersistenceUtils method encodeRMContent.

public static void encodeRMContent(RMMessage rmmsg, Message msg, InputStream msgContent) throws IOException {
    CachedOutputStream cos = new CachedOutputStream();
    if (msg.getAttachments() == null) {
        rmmsg.setContentType((String) msg.get(Message.CONTENT_TYPE));
        IOUtils.copyAndCloseInput(msgContent, cos);
        cos.flush();
        rmmsg.setContent(cos);
    } else {
        MessageImpl msgImpl1 = new MessageImpl();
        msgImpl1.setContent(OutputStream.class, cos);
        msgImpl1.setAttachments(msg.getAttachments());
        msgImpl1.put(Message.CONTENT_TYPE, msg.get(Message.CONTENT_TYPE));
        msgImpl1.setContent(InputStream.class, msgContent);
        AttachmentSerializer serializer = new AttachmentSerializer(msgImpl1);
        serializer.setXop(false);
        serializer.writeProlog();
        // write soap root message into cached output stream
        IOUtils.copyAndCloseInput(msgContent, cos);
        cos.flush();
        serializer.writeAttachments();
        rmmsg.setContentType((String) msgImpl1.get(Message.CONTENT_TYPE));
        rmmsg.setContent(cos);
    }
}
Also used : AttachmentSerializer(org.apache.cxf.attachment.AttachmentSerializer) MessageImpl(org.apache.cxf.message.MessageImpl) CachedOutputStream(org.apache.cxf.io.CachedOutputStream)

Example 35 with CachedOutputStream

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

the class LocalConduit method prepare.

public void prepare(final Message message) throws IOException {
    if (!MessageUtils.getContextualBoolean(message, DIRECT_DISPATCH)) {
        dispatchViaPipe(message);
    } else {
        // prepare the stream here
        CachedOutputStream stream = new CachedOutputStream();
        message.setContent(OutputStream.class, stream);
        // save the original stream
        message.put(CachedOutputStream.class, stream);
        stream.holdTempFile();
    }
}
Also used : 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