Coverage Report - org.mule.transformer.codec.Base64Encoder
 
Classes in this File Line Coverage Branch Coverage Complexity
Base64Encoder
0%
0/21
0%
0/6
0
 
 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  0
     {
 27  0
         registerSourceType(DataTypeFactory.STRING);
 28  0
         registerSourceType(DataTypeFactory.BYTE_ARRAY);
 29  0
         registerSourceType(DataTypeFactory.INPUT_STREAM);
 30  0
         setReturnDataType(DataTypeFactory.TEXT_STRING);
 31  0
     }
 32  
 
 33  
     @Override
 34  
     public Object doTransform(Object src, String encoding) throws TransformerException
 35  
     {
 36  
         try
 37  
         {
 38  
             byte[] buf;
 39  
 
 40  0
             if (src instanceof String)
 41  
             {
 42  0
                 buf = ((String) src).getBytes(encoding);
 43  
             }
 44  0
             else if (src instanceof InputStream)
 45  
             {
 46  0
                 InputStream input = (InputStream) src;
 47  
                 try
 48  
                 {
 49  0
                     buf = IOUtils.toByteArray(input);
 50  
                 }
 51  
                 finally
 52  
                 {
 53  0
                     input.close();
 54  0
                 }
 55  0
             }
 56  
             else
 57  
             {
 58  0
                 buf = (byte[]) src;
 59  
             }
 60  
 
 61  0
             String result = Base64.encodeBytes(buf, Base64.DONT_BREAK_LINES);
 62  
 
 63  0
             if (getReturnClass().equals(byte[].class))
 64  
             {
 65  0
                 return result.getBytes(encoding);
 66  
             }
 67  
             else
 68  
             {
 69  0
                 return result;
 70  
             }
 71  
         }
 72  0
         catch (Exception ex)
 73  
         {
 74  0
             throw new TransformerException(
 75  
                 CoreMessages.transformFailed(src.getClass().getName(), "base64"), this, ex);
 76  
         }
 77  
     }
 78  
 
 79  
 }