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