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