1 10 11 package org.mule.providers.file.transformers; 12 13 import java.io.File ; 14 import java.io.FileInputStream ; 15 import java.io.FileNotFoundException ; 16 import java.io.IOException ; 17 18 import org.apache.commons.io.IOUtils; 19 import org.apache.commons.lang.ArrayUtils; 20 import org.mule.transformers.AbstractTransformer; 21 import org.mule.umo.transformer.TransformerException; 22 23 26 public class FileToByteArray extends AbstractTransformer 27 { 28 31 private static final long serialVersionUID = -2836878450595052607L; 32 33 public FileToByteArray() 34 { 35 registerSourceType(File .class); 36 setReturnClass(byte[].class); 37 } 38 39 public Object doTransform(Object src, String encoding) throws TransformerException 40 { 41 File file = (File )src; 42 43 if (file == null) 44 { 45 throw new TransformerException(this, new IllegalArgumentException ("null file")); 46 } 47 48 if (!file.exists()) 49 { 50 throw new TransformerException(this, new FileNotFoundException (file.getPath())); 51 } 52 53 if (file.length() == 0) 54 { 55 logger.warn("File is empty: " + file.getAbsolutePath()); 56 return ArrayUtils.EMPTY_BYTE_ARRAY; 57 } 58 59 FileInputStream fis = null; 60 byte[] bytes = null; 61 62 try 63 { 64 fis = new FileInputStream (file); 65 int length = new Long (file.length()).intValue(); 68 bytes = new byte[length]; 69 fis.read(bytes); 70 return bytes; 71 } 72 catch (OutOfMemoryError oom) 74 { 75 throw new TransformerException(this, oom); 76 } 77 catch (IOException e) 78 { 79 throw new TransformerException(this, e); 80 } 81 finally 82 { 83 IOUtils.closeQuietly(fis); 84 } 85 } 86 87 } 88 | Popular Tags |