001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.commons.net.http.httpclient4;
020
021import java.io.FileNotFoundException;
022import java.io.IOException;
023import java.io.OutputStream;
024
025import lucee.commons.io.IOUtil;
026import lucee.commons.io.res.Resource;
027import lucee.commons.lang.StringUtil;
028
029import org.apache.http.entity.mime.MIME;
030import org.apache.http.entity.mime.content.AbstractContentBody;
031
032public class ResourceBody extends AbstractContentBody {
033
034    public static final String DEFAULT_MIMETYPE = "application/octet-stream";
035    
036        private String fileName = null;
037        private Resource res;
038        private String charset;
039    
040        public ResourceBody(Resource res, String mimetype, String fileName, String charset) throws FileNotFoundException{
041                super(StringUtil.isEmpty(mimetype,true)?DEFAULT_MIMETYPE:mimetype);
042                this.res=res;
043        if (!res.isFile()) {
044            throw new FileNotFoundException("File is not a normal file.");
045        }
046        if (!res.isReadable()) {
047            throw new FileNotFoundException("File is not readable.");
048        }
049        this.fileName = StringUtil.isEmpty(fileName,true)?res.getName():fileName;  
050        this.charset = charset;       
051        
052        }
053        
054        public String getFilename() {
055        return (fileName == null) ? "noname" : fileName;
056    }
057
058        @Override
059        public void writeTo(OutputStream os) throws IOException {
060                IOUtil.copy(res, os, false);
061        }
062
063        @Override
064        public String getCharset() {
065                return charset;
066        }
067
068        @Override
069        public long getContentLength() {
070                if (this.res != null) {
071            return this.res.length();
072        } 
073        return 0;
074        }
075
076        @Override
077        public String getTransferEncoding() {
078                return MIME.ENC_BINARY;
079        }
080
081    /**
082         * @return the res
083         */
084        public Resource getResource() {
085                return res;
086        }
087}