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 | 12 | { |
32 | 16 | registerSourceType(File.class); |
33 | 12 | setReturnClass(byte[].class); |
34 | 12 | } |
35 | |
|
36 | |
public Object doTransform(Object src, String encoding) throws TransformerException |
37 | |
{ |
38 | 28 | File file = (File)src; |
39 | |
|
40 | 28 | if (file == null) |
41 | |
{ |
42 | 0 | throw new TransformerException(this, new IllegalArgumentException("null file")); |
43 | |
} |
44 | |
|
45 | 28 | if (!file.exists()) |
46 | |
{ |
47 | 0 | throw new TransformerException(this, new FileNotFoundException(file.getPath())); |
48 | |
} |
49 | |
|
50 | 28 | if (file.length() == 0) |
51 | |
{ |
52 | 10 | logger.warn("File is empty: " + file.getAbsolutePath()); |
53 | 10 | return ArrayUtils.EMPTY_BYTE_ARRAY; |
54 | |
} |
55 | |
|
56 | 18 | FileInputStream fis = null; |
57 | 18 | byte[] bytes = null; |
58 | |
|
59 | |
try |
60 | |
{ |
61 | 18 | fis = new FileInputStream(file); |
62 | |
|
63 | |
|
64 | 18 | int length = new Long(file.length()).intValue(); |
65 | 18 | bytes = new byte[length]; |
66 | 18 | fis.read(bytes); |
67 | 18 | return bytes; |
68 | |
} |
69 | |
|
70 | 0 | catch (OutOfMemoryError oom) |
71 | |
{ |
72 | 0 | throw new TransformerException(this, oom); |
73 | |
} |
74 | 0 | catch (IOException e) |
75 | |
{ |
76 | 0 | throw new TransformerException(this, e); |
77 | |
} |
78 | |
finally |
79 | |
{ |
80 | 18 | IOUtils.closeQuietly(fis); |
81 | |
} |
82 | |
} |
83 | |
|
84 | |
} |