/*
 * Copyright 2009 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openehealth.ipf.commons.ihe.ws.cxf.payload;

import java.io.OutputStream;

import org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor.SoapOutEndingInterceptor;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.openehealth.ipf.commons.ihe.ws.utils.SoapUtils;

/**
 * CXF interceptor that reads outgoing payload collected by the output 
 * stream proxy installed in {@link OutStreamSubstituteInterceptor} 
 * and stores it in the message as String content type.
 * 
 * @author Dmytro Rud
 */
public class OutPayloadExtractorInterceptor extends AbstractPhaseInterceptor<Message> {

    public OutPayloadExtractorInterceptor() {
        super(Phase.WRITE_ENDING);
        addAfter(SoapOutEndingInterceptor.class.getName());
    }
    
    @Override
    public void handleMessage(Message message) {
        WrappedOutputStream wrapper = (WrappedOutputStream) message.getContent(OutputStream.class);
        String soapEnvelope = wrapper.getCollectedPayloadAndDeactivate();
        String payload = SoapUtils.extractSoapBody(soapEnvelope);
        message.setContent(String.class, payload);
    }
}

@@ -805,32 +805,85 @@
 ngInterceptor;%0D%0A
+import org.apache.cxf.io.CacheAndWriteOutputStream;%0D%0A
 import org.apach
@@ -1649,72 +1649,617 @@
 pper
- = (WrappedOutputStream) message.getContent(OutputStream.class);
+;%0D%0A        OutputStream outputStream =  message.getContent(OutputStream.class);%0D%0A        if (outputStream instanceof CacheAndWriteOutputStream) %7B%0D%0A            // Extract what we need from the wrapper added by CXF. CXF sometimes adds the wrapper for diagnostics.%0D%0A            outputStream = ((CacheAndWriteOutputStream)outputStream).getFlowThroughStream();%0D%0A        %7D%0D%0A        if (outputStream instanceof WrappedOutputStream) %7B%0D%0A            wrapper = (WrappedOutputStream) outputStream;%0D%0A        %7D else %7B%0D%0A            throw new IllegalStateException(%22Message output stream is not of expected type%22);%0D%0A        %7D
 %0D%0A  

Add logic to tolerate the diagnostic wrapper that CXF can sometimes place around the stream. There could still be some improvement here some day in the future. The casting to a concrete class is problematic because wrapping InputStreams is a common thing to do.