KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > mail > internet > ParameterList


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the "License"). You may not use this file except
5  * in compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * glassfish/bootstrap/legal/CDDLv1.0.txt or
9  * https://glassfish.dev.java.net/public/CDDLv1.0.html.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * HEADER in each file and include the License file at
15  * glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
16  * add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your
18  * own identifying information: Portions Copyright [yyyy]
19  * [name of copyright owner]
20  */

21
22 /*
23  * @(#)ParameterList.java 1.12 05/08/29
24  *
25  * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
26  */

27
28 package javax.mail.internet;
29
30 import java.util.*;
31 import java.io.*;
32
33 /**
34  * This class holds MIME parameters (attribute-value pairs).
35  * The <code>mail.mime.encodeparameters</code> and
36  * <code>mail.mime.decodeparameters</code> System properties
37  * control whether encoded parameters, as specified by
38  * <a HREF="http://www.ietf.org/rfc/rfc2231.txt">RFC 2231</a>,
39  * are supported. By default, such encoded parameters are not
40  * supported. <p>
41  *
42  * Also, in the current implementation, setting the System property
43  * <code>mail.mime.decodeparameters.strict</code> to <code>"true"</code>
44  * will cause a <code>ParseException</code> to be thrown for errors
45  * detected while decoding encoded parameters. By default, if any
46  * decoding errors occur, the original (undecoded) string is used.
47  *
48  * @version 1.12, 05/08/29
49  * @author John Mani
50  * @author Bill Shannon
51  */

52
53 public class ParameterList {
54
55     /**
56      * The map of name, value pairs.
57      * The value object is either a String, for unencoded
58      * values, or a Value object, for encoded values.
59      */

60     private Map list = new LinkedHashMap(); // keep parameters in order
61

62     private static boolean encodeParameters = false;
63     private static boolean decodeParameters = false;
64     private static boolean decodeParametersStrict = false;
65
66     static {
67     try {
68         String JavaDoc s = System.getProperty("mail.mime.encodeparameters");
69         // default to false
70
encodeParameters = s != null && s.equalsIgnoreCase("true");
71         s = System.getProperty("mail.mime.decodeparameters");
72         // default to false
73
decodeParameters = s != null && s.equalsIgnoreCase("true");
74         s = System.getProperty("mail.mime.decodeparameters.strict");
75         // default to false
76
decodeParametersStrict = s != null && s.equalsIgnoreCase("true");
77     } catch (SecurityException JavaDoc sex) {
78         // ignore it
79
}
80     }
81
82     /**
83      * A struct to hold an encoded value.
84      * A parsed encoded value is stored as both the
85      * decoded value and the original encoded value
86      * (so that toString will produce the same result).
87      * An encoded value that is set explicitly is stored
88      * as the original value and the encoded value, to
89      * ensure that get will return the same value that
90      * was set.
91      */

92     private static class Value {
93     String JavaDoc value;
94     String JavaDoc encodedValue;
95     }
96
97     /**
98      * Map the LinkedHashMap's keySet iterator to an Enumeration.
99      */

100     private static class ParamEnum implements Enumeration {
101     private Iterator it;
102
103     ParamEnum(Iterator it) {
104         this.it = it;
105     }
106
107     public boolean hasMoreElements() {
108         return it.hasNext();
109     }
110
111     public Object JavaDoc nextElement() {
112         return it.next();
113     }
114     }
115
116     /**
117      * No-arg Constructor.
118      */

119     public ParameterList() {
120     }
121
122     /**
123      * Constructor that takes a parameter-list string. The String
124      * is parsed and the parameters are collected and stored internally.
125      * A ParseException is thrown if the parse fails.
126      * Note that an empty parameter-list string is valid and will be
127      * parsed into an empty ParameterList.
128      *
129      * @param s the parameter-list string.
130      * @exception ParseException if the parse fails.
131      */

132     public ParameterList(String JavaDoc s) throws ParseException JavaDoc {
133     HeaderTokenizer JavaDoc h = new HeaderTokenizer JavaDoc(s, HeaderTokenizer.MIME);
134     HeaderTokenizer.Token JavaDoc tk;
135     int type;
136     String JavaDoc name;
137
138     for (;;) {
139         tk = h.next();
140         type = tk.getType();
141
142         if (type == HeaderTokenizer.Token.EOF) // done
143
return;
144
145         if ((char)type == ';') {
146         // expect parameter name
147
tk = h.next();
148         // tolerate trailing semicolon, even though it violates the spec
149
if (tk.getType() == HeaderTokenizer.Token.EOF)
150             return;
151         // parameter name must be a MIME Atom
152
if (tk.getType() != HeaderTokenizer.Token.ATOM)
153             throw new ParseException JavaDoc("Expected parameter name, " +
154                         "got \"" + tk.getValue() + "\"");
155         name = tk.getValue().toLowerCase();
156
157         // expect '='
158
tk = h.next();
159         if ((char)tk.getType() != '=')
160             throw new ParseException JavaDoc("Expected '=', " +
161                         "got \"" + tk.getValue() + "\"");
162
163         // expect parameter value
164
tk = h.next();
165         type = tk.getType();
166         // parameter value must be a MIME Atom or Quoted String
167
if (type != HeaderTokenizer.Token.ATOM &&
168             type != HeaderTokenizer.Token.QUOTEDSTRING)
169             throw new ParseException JavaDoc("Expected parameter value, " +
170                         "got \"" + tk.getValue() + "\"");
171
172         String JavaDoc value = tk.getValue();
173         if (decodeParameters && name.endsWith("*")) {
174             name = name.substring(0, name.length() - 1);
175             list.put(name, decodeValue(value));
176         } else
177             list.put(name, value);
178         } else
179         throw new ParseException JavaDoc("Expected ';', " +
180                         "got \"" + tk.getValue() + "\"");
181     }
182     }
183
184     /**
185      * Return the number of parameters in this list.
186      *
187      * @return number of parameters.
188      */

189     public int size() {
190     return list.size();
191     }
192
193     /**
194      * Returns the value of the specified parameter. Note that
195      * parameter names are case-insensitive.
196      *
197      * @param name parameter name.
198      * @return Value of the parameter. Returns
199      * <code>null</code> if the parameter is not
200      * present.
201      */

202     public String JavaDoc get(String JavaDoc name) {
203     String JavaDoc value;
204     Object JavaDoc v = list.get(name.trim().toLowerCase());
205     if (v instanceof Value)
206         value = ((Value)v).value;
207     else
208         value = (String JavaDoc)v;
209     return value;
210     }
211
212     /**
213      * Set a parameter. If this parameter already exists, it is
214      * replaced by this new value.
215      *
216      * @param name name of the parameter.
217      * @param value value of the parameter.
218      */

219     public void set(String JavaDoc name, String JavaDoc value) {
220     list.put(name.trim().toLowerCase(), value);
221     }
222
223     /**
224      * Set a parameter. If this parameter already exists, it is
225      * replaced by this new value. If the
226      * <code>mail.mime.encodeparameters</code> System property
227      * is true, and the parameter value is non-ASCII, it will be
228      * encoded with the specified charset, as specified by RFC 2231.
229      *
230      * @param name name of the parameter.
231      * @param value value of the parameter.
232      * @param charset charset of the parameter value.
233      * @since JavaMail 1.4
234      */

235     public void set(String JavaDoc name, String JavaDoc value, String JavaDoc charset) {
236     if (encodeParameters) {
237         Value ev = encodeValue(value, charset);
238         // was it actually encoded?
239
if (ev != null)
240         list.put(name.trim().toLowerCase(), ev);
241         else
242         set(name, value);
243     } else
244         set(name, value);
245     }
246
247     /**
248      * Removes the specified parameter from this ParameterList.
249      * This method does nothing if the parameter is not present.
250      *
251      * @param name name of the parameter.
252      */

253     public void remove(String JavaDoc name) {
254     list.remove(name.trim().toLowerCase());
255     }
256
257     /**
258      * Return an enumeration of the names of all parameters in this
259      * list.
260      *
261      * @return Enumeration of all parameter names in this list.
262      */

263     public Enumeration getNames() {
264     return new ParamEnum(list.keySet().iterator());
265     }
266
267     /**
268      * Convert this ParameterList into a MIME String. If this is
269      * an empty list, an empty string is returned.
270      *
271      * @return String
272      */

273     public String JavaDoc toString() {
274     return toString(0);
275     }
276
277     /**
278      * Convert this ParameterList into a MIME String. If this is
279      * an empty list, an empty string is returned.
280      *
281      * The 'used' parameter specifies the number of character positions
282      * already taken up in the field into which the resulting parameter
283      * list is to be inserted. It's used to determine where to fold the
284      * resulting parameter list.
285      *
286      * @param used number of character positions already used, in
287      * the field into which the parameter list is to
288      * be inserted.
289      * @return String
290      */

291     public String JavaDoc toString(int used) {
292         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
293         Iterator e = list.keySet().iterator();
294  
295         while (e.hasNext()) {
296             String JavaDoc name = (String JavaDoc)e.next();
297             String JavaDoc value;
298         Object JavaDoc v = list.get(name);
299         if (v instanceof Value) {
300         value = ((Value)v).encodedValue;
301         name += '*';
302         } else
303         value = (String JavaDoc)v;
304             value = quote(value);
305             sb.append("; ");
306             used += 2;
307             int len = name.length() + value.length() + 1;
308             if (used + len > 76) { // overflows ...
309
sb.append("\r\n\t"); // .. start new continuation line
310
used = 8; // account for the starting <tab> char
311
}
312         sb.append(name).append('=');
313         used += name.length() + 1;
314         if (used + value.length() > 76) { // still overflows ...
315
// have to fold value
316
String JavaDoc s = MimeUtility.fold(used, value);
317         sb.append(s);
318         int lastlf = s.lastIndexOf('\n');
319         if (lastlf >= 0) // always true
320
used += s.length() - lastlf - 1;
321         else
322             used += s.length();
323         } else {
324         sb.append(value);
325         used += value.length();
326         }
327         }
328  
329         return sb.toString();
330     }
331  
332     // Quote a parameter value token if required.
333
private String JavaDoc quote(String JavaDoc value) {
334     return MimeUtility.quote(value, HeaderTokenizer.MIME);
335     }
336
337     private static final char hex[] = {
338     '0','1', '2', '3', '4', '5', '6', '7',
339     '8','9', 'A', 'B', 'C', 'D', 'E', 'F'
340     };
341
342     /**
343      * Encode a parameter value, if necessary.
344      * If the value is encoded, a Value object is returned.
345      * Otherwise, null is returned.
346      */

347     private Value encodeValue(String JavaDoc value, String JavaDoc charset) {
348     if (MimeUtility.checkAscii(value) == MimeUtility.ALL_ASCII)
349         return null; // no need to encode it
350

351     byte[] b; // charset encoded bytes from the strong
352
try {
353         b = value.getBytes(MimeUtility.javaCharset(charset));
354     } catch (UnsupportedEncodingException ex) {
355         return null;
356     }
357     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(b.length + charset.length() + 2);
358     sb.append(charset).append("''");
359     for (int i = 0; i < b.length; i++) {
360         char c = (char)(b[i] & 0xff);
361         // do we need to encode this character?
362
if (c <= ' ' || c >= 0x7f || c == '*' || c == '\'' || c == '%' ||
363             HeaderTokenizer.MIME.indexOf(c) >= 0) {
364         sb.append('%').append(hex[c>>4]).append(hex[c&0xf]);
365         } else
366         sb.append(c);
367     }
368     Value v = new Value();
369     v.value = value;
370     v.encodedValue = sb.toString();
371     return v;
372     }
373
374     /**
375      * Decode a parameter value.
376      */

377     private Value decodeValue(String JavaDoc value) throws ParseException JavaDoc {
378     Value v = new Value();
379     v.encodedValue = value;
380     v.value = value; // in case we fail to decode it
381
try {
382         int i = value.indexOf('\'');
383         if (i <= 0) {
384         if (decodeParametersStrict)
385             throw new ParseException JavaDoc(
386             "Missing charset in encoded value: " + value);
387         return v; // not encoded correctly? return as is.
388
}
389         String JavaDoc charset = value.substring(0, i);
390         int li = value.indexOf('\'', i + 1);
391         if (li < 0) {
392         if (decodeParametersStrict)
393             throw new ParseException JavaDoc(
394             "Missing language in encoded value: " + value);
395         return v; // not encoded correctly? return as is.
396
}
397         String JavaDoc lang = value.substring(i + 1, li);
398         value = value.substring(li + 1);
399
400         /*
401          * Decode the ASCII characters in value
402          * into an array of bytes, and then convert
403          * the bytes to a String using the specified
404          * charset. We'll never need more bytes than
405          * encoded characters, so use that to size the
406          * array.
407          */

408         byte[] b = new byte[value.length()];
409         int bi;
410         for (i = 0, bi = 0; i < value.length(); i++) {
411         char c = value.charAt(i);
412         if (c == '%') {
413             String JavaDoc hex = value.substring(i + 1, i + 3);
414             c = (char)Integer.parseInt(hex, 16);
415             i += 2;
416         }
417         b[bi++] = (byte)c;
418         }
419         v.value = new String JavaDoc(b, 0, bi, MimeUtility.javaCharset(charset));
420     } catch (NumberFormatException JavaDoc nex) {
421         if (decodeParametersStrict)
422         throw new ParseException JavaDoc(nex.toString());
423     } catch (UnsupportedEncodingException uex) {
424         if (decodeParametersStrict)
425         throw new ParseException JavaDoc(uex.toString());
426     } catch (StringIndexOutOfBoundsException JavaDoc ex) {
427         if (decodeParametersStrict)
428         throw new ParseException JavaDoc(ex.toString());
429     }
430     return v;
431     }
432 }
433
Popular Tags