View Javadoc

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