1 16 17 package org.apache.commons.codec.net; 18 19 import java.io.UnsupportedEncodingException ; 20 import org.apache.commons.codec.DecoderException; 21 import org.apache.commons.codec.EncoderException; 22 import org.apache.commons.codec.StringDecoder; 23 import org.apache.commons.codec.StringEncoder; 24 import org.apache.commons.codec.binary.Base64; 25 26 45 public class BCodec extends RFC1522Codec implements StringEncoder, StringDecoder { 46 49 private String charset = StringEncodings.UTF8; 50 51 54 public BCodec() { 55 super(); 56 } 57 58 67 public BCodec(final String charset) { 68 super(); 69 this.charset = charset; 70 } 71 72 protected String getEncoding() { 73 return "B"; 74 } 75 76 protected byte[] doEncoding(byte[] bytes) throws EncoderException { 77 if (bytes == null) { 78 return null; 79 } 80 return Base64.encodeBase64(bytes); 81 } 82 83 protected byte[] doDecoding(byte[] bytes) throws DecoderException { 84 if (bytes == null) { 85 return null; 86 } 87 return Base64.decodeBase64(bytes); 88 } 89 90 102 public String encode(final String value, final String charset) throws EncoderException { 103 if (value == null) { 104 return null; 105 } 106 try { 107 return encodeText(value, charset); 108 } catch (UnsupportedEncodingException e) { 109 throw new EncoderException(e.getMessage()); 110 } 111 } 112 113 123 public String encode(String value) throws EncoderException { 124 if (value == null) { 125 return null; 126 } 127 return encode(value, getDefaultCharset()); 128 } 129 130 142 public String decode(String value) throws DecoderException { 143 if (value == null) { 144 return null; 145 } 146 try { 147 return decodeText(value); 148 } catch (UnsupportedEncodingException e) { 149 throw new DecoderException(e.getMessage()); 150 } 151 } 152 153 163 public Object encode(Object value) throws EncoderException { 164 if (value == null) { 165 return null; 166 } else if (value instanceof String ) { 167 return encode((String ) value); 168 } else { 169 throw new EncoderException("Objects of type " 170 + value.getClass().getName() 171 + " cannot be encoded using BCodec"); 172 } 173 } 174 175 187 public Object decode(Object value) throws DecoderException { 188 if (value == null) { 189 return null; 190 } else if (value instanceof String ) { 191 return decode((String ) value); 192 } else { 193 throw new DecoderException("Objects of type " 194 + value.getClass().getName() 195 + " cannot be decoded using BCodec"); 196 } 197 } 198 199 204 public String getDefaultCharset() { 205 return this.charset; 206 } 207 } | Popular Tags |