1
2
3
4
5
6
7
8
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.util.Base64;
17 import org.mule.util.IOUtils;
18
19 import java.io.InputStream;
20
21
22
23
24
25 public class Base64Encoder extends AbstractTransformer
26 {
27
28 public Base64Encoder()
29 {
30 registerSourceType(String.class);
31 registerSourceType(byte[].class);
32 registerSourceType(InputStream.class);
33 setReturnClass(String.class);
34 }
35
36 public Object doTransform(Object src, String encoding) throws TransformerException
37 {
38 try
39 {
40 byte[] buf;
41
42 if (src instanceof String)
43 {
44 buf = ((String) src).getBytes(encoding);
45 }
46 else if (src instanceof InputStream)
47 {
48 InputStream input = (InputStream) src;
49 try
50 {
51 buf = IOUtils.toByteArray(input);
52 }
53 finally
54 {
55 input.close();
56 }
57 }
58 else
59 {
60 buf = (byte[]) src;
61 }
62
63 String result = Base64.encodeBytes(buf, Base64.DONT_BREAK_LINES);
64
65 if (getReturnClass().equals(byte[].class))
66 {
67 return result.getBytes(encoding);
68 }
69 else
70 {
71 return result;
72 }
73 }
74 catch (Exception ex)
75 {
76 throw new TransformerException(
77 CoreMessages.transformFailed(src.getClass().getName(), "base64"), this, ex);
78 }
79 }
80
81 }