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