001    // Copyright 2007, 2008, 2009, 2010 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    // http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.tapestry5.internal.services;
016    
017    import java.io.BufferedInputStream;
018    import java.io.IOException;
019    import java.io.InputStream;
020    import java.io.OutputStream;
021    
022    import org.apache.tapestry5.StreamResponse;
023    import org.apache.tapestry5.internal.TapestryInternalUtils;
024    import org.apache.tapestry5.ioc.internal.util.InternalUtils;
025    import org.apache.tapestry5.services.ComponentEventResultProcessor;
026    import org.apache.tapestry5.services.Response;
027    
028    public class StreamResponseResultProcessor implements ComponentEventResultProcessor<StreamResponse>
029    {
030        private final Response response;
031    
032        public StreamResponseResultProcessor(Response response)
033        {
034            this.response = response;
035        }
036    
037        public void processResultValue(StreamResponse streamResponse) throws IOException
038        {
039            OutputStream os = null;
040            InputStream is = null;
041    
042            // The whole point is that the response is in the hands of the StreamResponse;
043            // if they want to compress the result, they can add their own GZIPOutputStream to
044            // their pipeline.
045    
046            response.disableCompression();
047    
048            streamResponse.prepareResponse(response);
049    
050            try
051            {
052                is = new BufferedInputStream(streamResponse.getStream());
053    
054                os = response.getOutputStream(streamResponse.getContentType());
055    
056                TapestryInternalUtils.copy(is, os);
057    
058                os.close();
059                os = null;
060    
061                is.close();
062                is = null;
063            }
064            finally
065            {
066                InternalUtils.close(is);
067                InternalUtils.close(os);
068            }
069        }
070    }