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