1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
package org.mule.transformer.simple; |
8 | |
|
9 | |
import org.mule.api.transformer.TransformerException; |
10 | |
import org.mule.transformer.AbstractTransformer; |
11 | |
import org.mule.transformer.types.DataTypeFactory; |
12 | |
import org.mule.util.IOUtils; |
13 | |
import org.mule.util.StringUtils; |
14 | |
|
15 | |
import java.io.InputStream; |
16 | |
import java.io.UnsupportedEncodingException; |
17 | |
|
18 | |
|
19 | |
|
20 | |
|
21 | |
|
22 | |
|
23 | |
|
24 | |
public class StringToObjectArray extends AbstractTransformer |
25 | |
{ |
26 | 0 | private String delimiter = null; |
27 | |
private static final String DEFAULT_DELIMITER = " "; |
28 | |
|
29 | |
public StringToObjectArray() |
30 | 0 | { |
31 | 0 | registerSourceType(DataTypeFactory.STRING); |
32 | 0 | registerSourceType(DataTypeFactory.BYTE_ARRAY); |
33 | 0 | registerSourceType(DataTypeFactory.INPUT_STREAM); |
34 | 0 | setReturnDataType(DataTypeFactory.create(Object[].class)); |
35 | 0 | } |
36 | |
|
37 | |
@Override |
38 | |
public Object doTransform(Object src, String outputEncoding) throws TransformerException |
39 | |
{ |
40 | |
String in; |
41 | |
|
42 | 0 | if (src instanceof byte[]) |
43 | |
{ |
44 | 0 | in = createStringFromByteArray((byte[]) src, outputEncoding); |
45 | |
} |
46 | 0 | else if (src instanceof InputStream) |
47 | |
{ |
48 | 0 | in = createStringFromInputStream((InputStream) src); |
49 | |
} |
50 | |
else |
51 | |
{ |
52 | 0 | in = (String) src; |
53 | |
} |
54 | |
|
55 | 0 | String[] out = StringUtils.splitAndTrim(in, getDelimiter()); |
56 | 0 | return out; |
57 | |
} |
58 | |
|
59 | |
protected String createStringFromByteArray(byte[] bytes, String outputEncoding) throws TransformerException |
60 | |
{ |
61 | |
try |
62 | |
{ |
63 | 0 | return new String(bytes, outputEncoding); |
64 | |
} |
65 | 0 | catch (UnsupportedEncodingException uee) |
66 | |
{ |
67 | 0 | throw new TransformerException(this, uee); |
68 | |
} |
69 | |
} |
70 | |
|
71 | |
protected String createStringFromInputStream(InputStream input) |
72 | |
{ |
73 | |
try |
74 | |
{ |
75 | 0 | return IOUtils.toString(input); |
76 | |
} |
77 | |
finally |
78 | |
{ |
79 | 0 | IOUtils.closeQuietly(input); |
80 | |
} |
81 | |
} |
82 | |
|
83 | |
|
84 | |
|
85 | |
|
86 | |
public String getDelimiter() |
87 | |
{ |
88 | 0 | if (delimiter == null) |
89 | |
{ |
90 | 0 | return DEFAULT_DELIMITER; |
91 | |
} |
92 | |
else |
93 | |
{ |
94 | 0 | return delimiter; |
95 | |
} |
96 | |
} |
97 | |
|
98 | |
|
99 | |
|
100 | |
|
101 | |
public void setDelimiter(String delimiter) |
102 | |
{ |
103 | 0 | this.delimiter = delimiter; |
104 | 0 | } |
105 | |
|
106 | |
} |