001    package railo.commons.net.http.httpclient4;
002    
003    import java.io.FileNotFoundException;
004    import java.io.IOException;
005    import java.io.OutputStream;
006    
007    import org.apache.http.entity.mime.MIME;
008    import org.apache.http.entity.mime.content.AbstractContentBody;
009    
010    import railo.commons.io.IOUtil;
011    import railo.commons.io.res.Resource;
012    import railo.commons.lang.StringUtil;
013    
014    public class ResourceBody extends AbstractContentBody {
015    
016        public static final String DEFAULT_MIMETYPE = "application/octet-stream";
017        
018            private String fileName = null;
019            private Resource res;
020            private String charset;
021        
022            public ResourceBody(Resource res, String mimetype, String fileName, String charset) throws FileNotFoundException{
023                    super(StringUtil.isEmpty(mimetype,true)?DEFAULT_MIMETYPE:mimetype);
024                    this.res=res;
025            if (!res.isFile()) {
026                throw new FileNotFoundException("File is not a normal file.");
027            }
028            if (!res.isReadable()) {
029                throw new FileNotFoundException("File is not readable.");
030            }
031            this.fileName = StringUtil.isEmpty(fileName,true)?res.getName():fileName;  
032            this.charset = charset;       
033            
034            }
035            
036            public String getFilename() {
037            return (fileName == null) ? "noname" : fileName;
038        }
039    
040            @Override
041            public void writeTo(OutputStream os) throws IOException {
042                    IOUtil.copy(res, os, false);
043            }
044    
045            @Override
046            public String getCharset() {
047                    return charset;
048            }
049    
050            @Override
051            public long getContentLength() {
052                    if (this.res != null) {
053                return this.res.length();
054            } 
055            return 0;
056            }
057    
058            @Override
059            public String getTransferEncoding() {
060                    return MIME.ENC_BINARY;
061            }
062    
063        /**
064             * @return the res
065             */
066            public Resource getResource() {
067                    return res;
068            }
069    }