01: /*
02: * Copyright 2004-2006 Fouad HAMDI.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.csvbeans.converters;
17:
18: import org.apache.commons.codec.binary.Base64;
19: import org.csvbeans.specs.SpecificationsFile;
20: import org.csvbeans.utils.MessagesBundle;
21:
22: /**
23: * Base64 encoder/decoder. Adapts the Base64 class from Jakarta commons codec
24: * library.
25: *
26: * @author Fouad Hamdi
27: * @since 0.7
28: */
29: public class Base64Converter implements Converter {
30: /** The Jakarta Commons Codec used here. */
31: private Base64 codec;
32:
33: /**
34: * Constructor.
35: */
36: public Base64Converter() {
37: codec = new Base64();
38: }
39:
40: /**
41: * No property is managed by this converter. An exception will be thrown if
42: * this method is called.
43: *
44: * @see org.csvbeans.converters.Converter#addProperty(java.lang.String,
45: * java.lang.String)
46: */
47: final public void addProperty(final String name, final String value) {
48: throw new IllegalArgumentException(MessagesBundle
49: .getMessage("converter.base64.property"));
50: }
51:
52: /**
53: * @see org.csvbeans.converters.Converter#init()
54: */
55: public void init(SpecificationsFile specs) {
56: }
57:
58: /**
59: * Transform the specified object into a Base64 string. The
60: * <code>toString()</code> method of the specified object is called to
61: * convert the object into a string before encoding.
62: *
63: * @see org.csvbeans.converters.Converter#encode(java.lang.Object)
64: */
65: public String encode(final Object object) {
66: if (object == null) {
67: return null;
68: }
69: String value = object.toString();
70: byte[] result = codec.encode(value.getBytes());
71: return new String(result);
72: }
73:
74: /**
75: * Convert a Base64 string into a clear string.
76: *
77: * @see org.csvbeans.converters.Converter#decode(java.lang.String)
78: */
79: public Object decode(final String value) {
80: byte[] result = codec.decode(value.getBytes());
81: return new String(result);
82: }
83: }
|