View Javadoc

1   /*
2    * $Id: Base64Encoder.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.codec;
12  
13  import org.mule.config.i18n.CoreMessages;
14  import org.mule.transformers.AbstractTransformer;
15  import org.mule.umo.transformer.TransformerException;
16  import org.mule.util.Base64;
17  
18  /**
19   * <code>Base64Encoder</code> transforms strings or byte arrays into Base64 encoded
20   * string.
21   */
22  public class Base64Encoder extends AbstractTransformer
23  {
24  
25      public Base64Encoder()
26      {
27          registerSourceType(String.class);
28          registerSourceType(byte[].class);
29          setReturnClass(String.class);
30      }
31  
32      public Object doTransform(Object src, String encoding) throws TransformerException
33      {
34          try
35          {
36              byte[] buf;
37  
38              if (src instanceof String)
39              {
40                  buf = ((String) src).getBytes(encoding);
41              }
42              else
43              {
44                  buf = (byte[]) src;
45              }
46  
47              String result = Base64.encodeBytes(buf, Base64.DONT_BREAK_LINES);
48  
49              if (getReturnClass().equals(byte[].class))
50              {
51                  return result.getBytes(encoding);
52              }
53              else
54              {
55                  return result;
56              }
57          }
58          catch (Exception ex)
59          {
60              throw new TransformerException(
61                  CoreMessages.transformFailed(src.getClass().getName(), "base64"), this, ex);
62          }
63      }
64  
65  }