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 Base64 encoded data into strings or byte
20   * arrays.
21   */
22  public class Base64Decoder extends AbstractTransformer
23  {
24      public Base64Decoder()
25      {
26          registerSourceType(DataTypeFactory.STRING);
27          registerSourceType(DataTypeFactory.BYTE_ARRAY);
28          registerSourceType(DataTypeFactory.INPUT_STREAM);
29          setReturnDataType(DataTypeFactory.BYTE_ARRAY);
30      }
31  
32      @Override
33      public Object doTransform(Object src, String outputEncoding) throws TransformerException
34      {
35          try
36          {
37              String data;
38  
39              if (src instanceof byte[])
40              {
41                  data = new String((byte[]) src, outputEncoding);
42              }
43              else if (src instanceof InputStream)
44              {
45                  InputStream input = (InputStream) src;
46                  try
47                  {
48                      data = IOUtils.toString(input);
49                  }
50                  finally
51                  {
52                      input.close();
53                  }
54              }
55              else
56              {
57                  data = (String) src;
58              }
59  
60              byte[] result = Base64.decode(data);
61  
62              if (DataTypeFactory.STRING.equals(getReturnDataType()))
63              {
64                  return new String(result, outputEncoding);
65              }
66              else
67              {
68                  return result;
69              }
70          }
71          catch (Exception ex)
72          {
73              throw new TransformerException(
74                  CoreMessages.transformFailed("base64", getReturnDataType()), this, ex);
75          }
76      }
77  
78  }