View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transformer.codec;
8   
9   import org.mule.api.transformer.TransformerException;
10  import org.mule.config.i18n.CoreMessages;
11  import org.mule.transformer.AbstractTransformer;
12  import org.mule.transformer.types.DataTypeFactory;
13  import org.mule.util.Base64;
14  import org.mule.util.IOUtils;
15  
16  import java.io.InputStream;
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(DataTypeFactory.STRING);
28          registerSourceType(DataTypeFactory.BYTE_ARRAY);
29          registerSourceType(DataTypeFactory.INPUT_STREAM);
30          setReturnDataType(DataTypeFactory.TEXT_STRING);
31      }
32  
33      @Override
34      public Object doTransform(Object src, String encoding) throws TransformerException
35      {
36          try
37          {
38              byte[] buf;
39  
40              if (src instanceof String)
41              {
42                  buf = ((String) src).getBytes(encoding);
43              }
44              else if (src instanceof InputStream)
45              {
46                  InputStream input = (InputStream) src;
47                  try
48                  {
49                      buf = IOUtils.toByteArray(input);
50                  }
51                  finally
52                  {
53                      input.close();
54                  }
55              }
56              else
57              {
58                  buf = (byte[]) src;
59              }
60  
61              String result = Base64.encodeBytes(buf, Base64.DONT_BREAK_LINES);
62  
63              if (getReturnClass().equals(byte[].class))
64              {
65                  return result.getBytes(encoding);
66              }
67              else
68              {
69                  return result;
70              }
71          }
72          catch (Exception ex)
73          {
74              throw new TransformerException(
75                  CoreMessages.transformFailed(src.getClass().getName(), "base64"), this, ex);
76          }
77      }
78  
79  }