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 | 0 | super(); |
34 | 0 | registerSourceType(DataTypeFactory.create(File.class)); |
35 | 0 | registerSourceType(DataTypeFactory.BYTE_ARRAY); |
36 | 0 | } |
37 | |
|
38 | |
@Override |
39 | |
public Object doTransform(Object src, String outputEncoding) throws TransformerException |
40 | |
{ |
41 | |
|
42 | |
|
43 | 0 | if (src instanceof byte[]) |
44 | |
{ |
45 | 0 | return src; |
46 | |
} |
47 | |
|
48 | 0 | if (src instanceof InputStream || src instanceof String) |
49 | |
{ |
50 | 0 | return super.doTransform(src, outputEncoding); |
51 | |
} |
52 | |
else |
53 | |
{ |
54 | 0 | File file = (File) src; |
55 | |
|
56 | 0 | if (file == null) |
57 | |
{ |
58 | 0 | throw new TransformerException(this, new IllegalArgumentException("null file")); |
59 | |
} |
60 | |
|
61 | 0 | if (!file.exists()) |
62 | |
{ |
63 | 0 | throw new TransformerException(this, new FileNotFoundException(file.getPath())); |
64 | |
} |
65 | |
|
66 | 0 | if (file.length() == 0) |
67 | |
{ |
68 | 0 | logger.warn("File is empty: " + file.getAbsolutePath()); |
69 | 0 | return ArrayUtils.EMPTY_BYTE_ARRAY; |
70 | |
} |
71 | |
|
72 | 0 | FileInputStream fis = null; |
73 | 0 | byte[] bytes = null; |
74 | |
|
75 | |
try |
76 | |
{ |
77 | 0 | fis = new FileInputStream(file); |
78 | |
|
79 | |
|
80 | 0 | int length = new Long(file.length()).intValue(); |
81 | 0 | bytes = new byte[length]; |
82 | 0 | fis.read(bytes); |
83 | 0 | return bytes; |
84 | |
} |
85 | |
|
86 | 0 | catch (OutOfMemoryError oom) |
87 | |
{ |
88 | 0 | throw new TransformerException(this, oom); |
89 | |
} |
90 | 0 | catch (IOException e) |
91 | |
{ |
92 | 0 | throw new TransformerException(this, e); |
93 | |
} |
94 | |
finally |
95 | |
{ |
96 | 0 | IOUtils.closeQuietly(fis); |
97 | |
} |
98 | |
} |
99 | |
} |
100 | |
} |