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