View Javadoc

1   /*
2    * $Id: StringToByteArray.java 7976 2007-08-21 14:26:13Z 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.transformers.simple;
12  
13  import org.mule.config.i18n.MessageFactory;
14  import org.mule.transformers.AbstractTransformer;
15  import org.mule.umo.transformer.TransformerException;
16  
17  import java.io.UnsupportedEncodingException;
18  
19  /**
20   * <code>StringToByteArray</code> converts a String into a byte array.
21   */
22  
23  public class StringToByteArray extends AbstractTransformer
24  {
25  
26      public StringToByteArray()
27      {
28          registerSourceType(String.class);
29          registerSourceType(byte[].class);
30          setReturnClass(byte[].class);
31      }
32  
33      public Object doTransform(Object src, String encoding) throws TransformerException
34      {
35          if (src instanceof byte[])
36          {
37              return src;
38          }
39          else
40          {
41              try
42              {
43                  return ((String) src).getBytes(encoding);
44              }
45              catch (UnsupportedEncodingException e)
46              {
47                  throw new TransformerException(MessageFactory
48                      .createStaticMessage("Unable to convert String to byte[]."), e);
49              }
50          }
51      }
52  
53  }