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 static eu.medsea.util.MimeUtil.getMimeType;
022 import org.apache.commons.io.IOUtils;
023
024 import java.io.BufferedInputStream;
025 import java.io.File;
026 import java.io.FileInputStream;
027 import java.io.IOException;
028 import java.io.OutputStream;
029
030 /**
031 * A download provider for sending files to the client.
032 *
033 * @author Rakesh 2008-11-10
034 * @version $Id: FileDownloadProvider.java 255 2009-11-29 12:16:16Z sptrakesh $
035 */
036 public class FileDownloadProvider extends AbstractDownloadProvider
037 {
038 private static final long serialVersionUID = 1l;
039
040 /** The file that is to be enqueued for download to the client. */
041 private final File file;
042
043 public FileDownloadProvider( final File file )
044 {
045 this.file = file;
046 this.fileName = file.getName();
047 this.size = file.length();
048 }
049
050 /**
051 * Returns the content type, for example "text/plain".
052 *
053 * @return the content type.
054 */
055 public String getContentType()
056 {
057 return ( contentType != null ) ? contentType : getMimeType( file );
058 }
059
060 /**
061 * Writes the file data to the output stream.
062 *
063 * @param out the output stream to which the file data must be written.
064 * @throws IOException If errors are encountered while writing the contents
065 * to the output stream.
066 */
067 @SuppressWarnings( { "IOResourceOpenedButNotSafelyClosed" } )
068 public void writeFile( final OutputStream out ) throws IOException
069 {
070 status = Status.inprogress;
071
072 try
073 {
074 final BufferedInputStream bis =
075 new BufferedInputStream( new FileInputStream( file ) );
076 IOUtils.copy( bis, out );
077 out.flush();
078 bis.close();
079 }
080 catch ( IOException e )
081 {
082 status = Status.failed;
083 throw e;
084 }
085
086 status = Status.completed;
087 }
088 }