1 16 17 package org.apache.commons.codec.net; 18 19 import java.io.UnsupportedEncodingException ; 20 21 import org.apache.commons.codec.DecoderException; 22 import org.apache.commons.codec.EncoderException; 23 24 45 abstract class RFC1522Codec { 46 47 65 protected String encodeText(final String text, final String charset) 66 throws EncoderException, UnsupportedEncodingException 67 { 68 if (text == null) { 69 return null; 70 } 71 StringBuffer buffer = new StringBuffer (); 72 buffer.append("=?"); 73 buffer.append(charset); 74 buffer.append('?'); 75 buffer.append(getEncoding()); 76 buffer.append('?'); 77 byte [] rawdata = doEncoding(text.getBytes(charset)); 78 buffer.append(new String (rawdata, StringEncodings.US_ASCII)); 79 buffer.append("?="); 80 return buffer.toString(); 81 } 82 83 95 protected String decodeText(final String text) 96 throws DecoderException, UnsupportedEncodingException 97 { 98 if (text == null) { 99 return null; 100 } 101 if ((!text.startsWith("=?")) || (!text.endsWith("?="))) { 102 throw new DecoderException("RFC 1522 violation: malformed encoded content"); 103 } 104 int termnator = text.length() - 2; 105 int from = 2; 106 int to = text.indexOf("?", from); 107 if ((to == -1) || (to == termnator)) { 108 throw new DecoderException("RFC 1522 violation: charset token not found"); 109 } 110 String charset = text.substring(from, to); 111 if (charset.equals("")) { 112 throw new DecoderException("RFC 1522 violation: charset not specified"); 113 } 114 from = to + 1; 115 to = text.indexOf("?", from); 116 if ((to == -1) || (to == termnator)) { 117 throw new DecoderException("RFC 1522 violation: encoding token not found"); 118 } 119 String encoding = text.substring(from, to); 120 if (!getEncoding().equalsIgnoreCase(encoding)) { 121 throw new DecoderException("This codec cannot decode " + 122 encoding + " encoded content"); 123 } 124 from = to + 1; 125 to = text.indexOf("?", from); 126 byte[] data = text.substring(from, to).getBytes(StringEncodings.US_ASCII); 127 data = doDecoding(data); 128 return new String (data, charset); 129 } 130 131 136 protected abstract String getEncoding(); 137 138 148 protected abstract byte[] doEncoding(byte[] bytes) throws EncoderException; 149 150 160 protected abstract byte[] doDecoding(byte[] bytes) throws DecoderException; 161 } 162 | Popular Tags |