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 private String delimiter = null;
27 private static final String DEFAULT_DELIMITER = " ";
28
29 public StringToObjectArray()
30 {
31 registerSourceType(DataTypeFactory.STRING);
32 registerSourceType(DataTypeFactory.BYTE_ARRAY);
33 registerSourceType(DataTypeFactory.INPUT_STREAM);
34 setReturnDataType(DataTypeFactory.create(Object[].class));
35 }
36
37 @Override
38 public Object doTransform(Object src, String outputEncoding) throws TransformerException
39 {
40 String in;
41
42 if (src instanceof byte[])
43 {
44 in = createStringFromByteArray((byte[]) src, outputEncoding);
45 }
46 else if (src instanceof InputStream)
47 {
48 in = createStringFromInputStream((InputStream) src);
49 }
50 else
51 {
52 in = (String) src;
53 }
54
55 String[] out = StringUtils.splitAndTrim(in, getDelimiter());
56 return out;
57 }
58
59 protected String createStringFromByteArray(byte[] bytes, String outputEncoding) throws TransformerException
60 {
61 try
62 {
63 return new String(bytes, outputEncoding);
64 }
65 catch (UnsupportedEncodingException uee)
66 {
67 throw new TransformerException(this, uee);
68 }
69 }
70
71 protected String createStringFromInputStream(InputStream input)
72 {
73 try
74 {
75 return IOUtils.toString(input);
76 }
77 finally
78 {
79 IOUtils.closeQuietly(input);
80 }
81 }
82
83
84
85
86 public String getDelimiter()
87 {
88 if (delimiter == null)
89 {
90 return DEFAULT_DELIMITER;
91 }
92 else
93 {
94 return delimiter;
95 }
96 }
97
98
99
100
101 public void setDelimiter(String delimiter)
102 {
103 this.delimiter = delimiter;
104 }
105
106 }