KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > columba > ristretto > imap > MailboxNameUTF7Converter


1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3  *
4  * The contents of this file are subject to the Mozilla Public License Version
5  * 1.1 (the "License"); you may not use this file except in compliance with
6  * the License. You may obtain a copy of the License at
7  * http://www.mozilla.org/MPL/
8  *
9  * Software distributed under the License is distributed on an "AS IS" basis,
10  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11  * for the specific language governing rights and limitations under the
12  * License.
13  *
14  * The Original Code is Ristretto Mail API.
15  *
16  * The Initial Developers of the Original Code are
17  * Timo Stich and Frederik Dietz.
18  * Portions created by the Initial Developers are Copyright (C) 2004
19  * All Rights Reserved.
20  *
21  * Contributor(s):
22  *
23  * Alternatively, the contents of this file may be used under the terms of
24  * either the GNU General Public License Version 2 or later (the "GPL"), or
25  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
26  * in which case the provisions of the GPL or the LGPL are applicable instead
27  * of those above. If you wish to allow use of your version of this file only
28  * under the terms of either the GPL or the LGPL, and not to allow others to
29  * use your version of this file under the terms of the MPL, indicate your
30  * decision by deleting the provisions above and replace them with the notice
31  * and other provisions required by the GPL or the LGPL. If you do not delete
32  * the provisions above, a recipient may use your version of this file under
33  * the terms of any one of the MPL, the GPL or the LGPL.
34  *
35  * ***** END LICENSE BLOCK ***** */

36 package org.columba.ristretto.imap;
37
38 import java.io.UnsupportedEncodingException JavaDoc;
39 import java.nio.ByteBuffer JavaDoc;
40
41 import org.columba.ristretto.coder.Base64;
42
43 /**
44  * @author tstich
45  *
46  * TODO To change the template for this generated type comment go to
47  * Window - Preferences - Java - Code Style - Code Templates
48  */

49 public class MailboxNameUTF7Converter {
50
51     private final static int PRINTABLE = 0;
52     private final static int BASE64 = 1;
53     
54     /**
55      * Encode the mailbox name in the IMAP UTF-7 style charset.
56      *
57      * @param mailboxName
58      * @return the IMAP UTF-7 representation
59      */

60     public static String JavaDoc encode(String JavaDoc mailboxName) {
61         int dataBits = 0;
62         int mode = PRINTABLE;
63         // Allocate a bytebuffer that must be at max
64
// twice the length of characters in the string
65
// because of utf-16 encoding and add 2 more
66
// bytes in order to have a length that can be
67
// devided by 3. This is necessary to avoid the
68
// padding in base64 which is forbidden in
69
// modified UTF-7 encoding.
70
ByteBuffer JavaDoc buffer = ByteBuffer.allocate(mailboxName.length() * 4 + 4);
71         
72         
73         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
74         char c;
75         
76         for( int i=0; i<mailboxName.length(); i++) {
77             c = mailboxName.charAt(i);
78             
79             if( isPrintable(c) ) {
80                 if( mode != PRINTABLE && buffer.position()> 0) {
81                     // pad buffer with zeros
82
if(buffer.position() % 3 != 0 ) {
83                         buffer.put(new byte[3 - (buffer.position() % 3)]);
84                     }
85                     buffer.limit(buffer.position());
86                     
87                     // encode in base64
88
StringBuffer JavaDoc encoded = Base64.encode(buffer, false);
89                     buffer.rewind();
90                     
91                     // do the modifications
92
String JavaDoc rawEncoded = encoded.toString().replace('/',',');
93                     
94                     // cut the end to a valid base64 character
95
// base64: 6 bits per character
96

97                     int encodedBits = rawEncoded.length() * 6;
98                     int superfluentChars = (encodedBits - dataBits) / 6;
99                     
100                     if( superfluentChars > 0) {
101                         rawEncoded = rawEncoded.substring(0, rawEncoded.length()-superfluentChars);
102                     }
103                     
104                     result.append(rawEncoded);
105                     
106                     //switch back to PRINTABLE mode
107
mode = PRINTABLE;
108                     result.append('-');
109                 }
110                 
111                 // write the character
112
if( c == '&') {
113                     result.append("&-");
114                 } else {
115                     result.append(c);
116                 }
117             } else {
118                 if( mode != BASE64) {
119                     result.append('&');
120                     mode = BASE64;
121                 }
122                 
123                 try {
124                     byte[] utfBytes = mailboxName.substring(i,i+1).getBytes("UTF-16");
125                     if( utfBytes[0] != -2 ) {
126                         buffer.put(utfBytes[0]);
127                         buffer.put(utfBytes[1]);
128                         dataBits += 16;
129                     }
130                     buffer.put(utfBytes[2]);
131                     buffer.put(utfBytes[3]);
132                     
133                     dataBits += 16;
134                 } catch (UnsupportedEncodingException JavaDoc e) {
135                     //will never happen
136
}
137             }
138         }
139         
140         if( mode != PRINTABLE) {
141             // pad buffer with zeros
142
if(buffer.position() % 3 != 0 ) {
143                 buffer.put(new byte[3 - (buffer.position() % 3)]);
144             }
145             buffer.limit(buffer.position());
146             
147             // encode in base64
148
StringBuffer JavaDoc encoded = Base64.encode(buffer, false);
149             buffer.rewind();
150             
151             // do the modifications
152
String JavaDoc rawEncoded = encoded.toString().replace('/',',');
153             
154             // cut the end to a valid base64 character
155
// base64: 6 bits per character
156

157             int encodedBits = rawEncoded.length() * 6;
158             int superfluentChars = (encodedBits - dataBits) / 6;
159             
160             if( superfluentChars > 0) {
161                 rawEncoded = rawEncoded.substring(0, rawEncoded.length()-superfluentChars);
162             }
163
164             result.append(rawEncoded);
165             
166             //switch back to PRINTABLE mode
167
mode = PRINTABLE;
168             result.append('-');
169         }
170         
171         return result.toString();
172     }
173     
174     /**
175      * Decode the IMAP UTF-7 mailbox name to a Java String.
176      *
177      * @param mailboxName
178      * @return the Java representation of the mailbox names
179      */

180     public static String JavaDoc decode(String JavaDoc mailboxName) {
181         int lastEnd = 0;
182         int nextAnd = mailboxName.indexOf('&');
183         
184         // if no & is in the name no decoding must be done
185
if( nextAnd == -1 ) return mailboxName;
186         
187         StringBuffer JavaDoc result = new StringBuffer JavaDoc(mailboxName.length());
188         
189         while( nextAnd != -1 ) {
190             // add all the printable characters until this position
191
result.append(mailboxName.substring(lastEnd,nextAnd));
192             
193             //can be either a switch to utf-7 or &-
194
if( mailboxName.charAt(nextAnd+1) == '-') {
195                 result.append('&');
196                 lastEnd = nextAnd+2;
197             } else {
198                 // find end of base64 code
199
lastEnd = mailboxName.indexOf('-',nextAnd);
200                 int expanded = 0;
201                 
202                 // pad with A's for modified base64
203
StringBuffer JavaDoc rawEncoded = new StringBuffer JavaDoc(mailboxName.substring(nextAnd+1, lastEnd).replace(',','/'));
204                 while( rawEncoded.length() % 4 != 0) {
205                     rawEncoded.append('A');
206                     expanded++;
207                 }
208                 
209                 // decode the transformed modified-base64
210
ByteBuffer JavaDoc decoded = Base64.decode(rawEncoded);
211                 decoded.limit( decoded.limit() - expanded );
212                 if( decoded.limit() % 2 != 0) {
213                     // delete the end zeros
214
decoded.limit( decoded.limit() - (decoded.limit() % 2));
215                 }
216                 
217                 result.append(decoded.asCharBuffer());
218                 
219                 lastEnd++;
220             }
221             
222             nextAnd = mailboxName.indexOf('&', lastEnd );
223         }
224         
225         result.append(mailboxName.substring(lastEnd));
226         
227         return result.toString();
228     }
229     
230     private static boolean isPrintable(char c) {
231         return ( c >= 0x020 && c <= 0x7e);
232     }
233     
234 }
235
Popular Tags