001    /*
002     * This file is part of the Echo Point Project.  This project is a
003     * collection of Components that have extended the Echo Web Application
004     * Framework Version 3.
005     *
006     * Version: MPL 1.1
007     *
008     * The contents of this file are subject to the Mozilla Public License Version
009     * 1.1 (the "License"); you may not use this file except in compliance with
010     * the License. You may obtain a copy of the License at
011     * http://www.mozilla.org/MPL/
012     *
013     * Software distributed under the License is distributed on an "AS IS" basis,
014     * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
015     * for the specific language governing rights and limitations under the
016     * License.
017     */
018    
019    package echopoint.tucana;
020    
021    import org.apache.commons.io.IOUtils;
022    
023    import java.io.IOException;
024    import java.io.InputStream;
025    import java.io.OutputStream;
026    import static java.util.UUID.randomUUID;
027    
028    /**
029     * A download provider implementation that streams the contents of the
030     * specified input stream to the client request output stream on demand.
031     *
032     * @author Rakesh 2009-08-21
033     * @version $Id: InputStreamDownloadProvider.java 255 2009-11-29 12:16:16Z sptrakesh $
034     */
035    public class InputStreamDownloadProvider extends AbstractDownloadProvider
036    {
037      private static final long serialVersionUID = 1L;
038    
039      /**
040       * The input stream to use as the data source to write to the client
041       * output stream.
042       */
043      @SuppressWarnings( { "TransientFieldNotInitialized" } )
044      private final transient InputStream stream;
045    
046      /**
047       * Create a new download provider instance for the specified input
048       * stream.
049       *
050       * @param stream The input stream from which to stream the output.
051       */
052      public InputStreamDownloadProvider( final InputStream stream )
053      {
054        this.stream = stream;
055      }
056    
057      public String getContentType()
058      {
059        return ( contentType == null ) ? "binary/octet-stream" : contentType;
060      }
061    
062      public void writeFile( final OutputStream out ) throws IOException
063      {
064        status = Status.inprogress;
065    
066        try
067        {
068          IOUtils.copy( stream, out );
069          out.flush();
070        }
071        catch ( IOException e )
072        {
073          status = Status.failed;
074          throw e;
075        }
076    
077        status = Status.completed;
078      }
079    
080      @Override
081      public String getFileName()
082      {
083        return ( fileName == null ) ? randomUUID().toString() : fileName;
084      }
085    }