View Javadoc

1   /*
2    * $Id: StringToObjectArray.java 11316 2008-03-11 15:50:38Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
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.util.IOUtils;
16  import org.mule.util.StringUtils;
17  
18  import java.io.InputStream;
19  
20  /**
21   * <code>StringToObjectArray</code> converts a String into an object array. This
22   * is useful in certain situations, as when a string needs to be converted into
23   * an Object[] in order to be passed to a SOAP service. The input String is parsed
24   * into the array based on a configurable delimiter - default is a space.
25   */
26  
27  public class StringToObjectArray extends AbstractTransformer
28  {
29      private String delimiter = null;
30      private static final String DEFAULT_DELIMITER = " ";
31  
32      public StringToObjectArray()
33      {
34          registerSourceType(String.class);
35          registerSourceType(byte[].class);
36          registerSourceType(InputStream.class);
37          setReturnClass(Object[].class);
38      }
39  
40      public Object doTransform(Object src, String encoding) throws TransformerException
41      {
42          String in;
43  
44          if (src instanceof byte[])
45          {
46              in = new String((byte[])src);
47          }
48          else if (src instanceof InputStream)
49          {
50              InputStream input = (InputStream) src;
51              try
52              {
53                  in = IOUtils.toString(input);
54              }
55              finally
56              {
57                  IOUtils.closeQuietly(input);
58              }
59          }
60          else
61          {
62              in = (String)src;
63          }
64  
65          String[] out = StringUtils.splitAndTrim(in, getDelimiter());
66          return out;
67      }
68  
69      /**
70       * @return the delimiter
71       */
72      public String getDelimiter()
73      {
74          if (delimiter == null)
75          {
76              return DEFAULT_DELIMITER;
77          }
78          else
79          {
80              return delimiter;
81          }
82      }
83  
84      /**
85       * @param delimiter the delimiter
86       */
87      public void setDelimiter(String delimiter)
88      {
89          this.delimiter = delimiter;
90      }
91          
92  }