View Javadoc

1   /*
2    * $Id: Base64Encoder.java 19250 2010-08-30 16:53:14Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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.codec;
12  
13  import org.mule.api.transformer.TransformerException;
14  import org.mule.config.i18n.CoreMessages;
15  import org.mule.transformer.AbstractTransformer;
16  import org.mule.transformer.types.DataTypeFactory;
17  import org.mule.util.Base64;
18  import org.mule.util.IOUtils;
19  
20  import java.io.InputStream;
21  
22  /**
23   * <code>Base64Encoder</code> transforms strings or byte arrays into Base64 encoded
24   * string.
25   */
26  public class Base64Encoder extends AbstractTransformer
27  {
28  
29      public Base64Encoder()
30      {
31          registerSourceType(DataTypeFactory.STRING);
32          registerSourceType(DataTypeFactory.BYTE_ARRAY);
33          registerSourceType(DataTypeFactory.INPUT_STREAM);
34          setReturnDataType(DataTypeFactory.TEXT_STRING);
35      }
36  
37      @Override
38      public Object doTransform(Object src, String encoding) throws TransformerException
39      {
40          try
41          {
42              byte[] buf;
43  
44              if (src instanceof String)
45              {
46                  buf = ((String) src).getBytes(encoding);
47              }
48              else if (src instanceof InputStream)
49              {
50                  InputStream input = (InputStream) src;
51                  try
52                  {
53                      buf = IOUtils.toByteArray(input);
54                  }
55                  finally
56                  {
57                      input.close();
58                  }
59              }
60              else
61              {
62                  buf = (byte[]) src;
63              }
64  
65              String result = Base64.encodeBytes(buf, Base64.DONT_BREAK_LINES);
66  
67              if (getReturnClass().equals(byte[].class))
68              {
69                  return result.getBytes(encoding);
70              }
71              else
72              {
73                  return result;
74              }
75          }
76          catch (Exception ex)
77          {
78              throw new TransformerException(
79                  CoreMessages.transformFailed(src.getClass().getName(), "base64"), this, ex);
80          }
81      }
82  
83  }