KickJava   Java API By Example, From Geeks To Geeks.

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


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  * @(#)InternetHeaders.java 1.21 06/02/15
24  *
25  * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
26  */

27
28 package javax.mail.internet;
29
30 import java.io.*;
31 import java.util.*;
32 import javax.mail.*;
33 import com.sun.mail.util.LineInputStream;
34
35 /**
36  * InternetHeaders is a utility class that manages RFC822 style
37  * headers. Given an RFC822 format message stream, it reads lines
38  * until the blank line that indicates end of header. The input stream
39  * is positioned at the start of the body. The lines are stored
40  * within the object and can be extracted as either Strings or
41  * {@link javax.mail.Header} objects. <p>
42  *
43  * This class is mostly intended for service providers. MimeMessage
44  * and MimeBody use this class for holding their headers. <p>
45  *
46  * <hr> <strong>A note on RFC822 and MIME headers</strong><p>
47  *
48  * RFC822 and MIME header fields <strong>must</strong> contain only
49  * US-ASCII characters. If a header contains non US-ASCII characters,
50  * it must be encoded as per the rules in RFC 2047. The MimeUtility
51  * class provided in this package can be used to to achieve this.
52  * Callers of the <code>setHeader</code>, <code>addHeader</code>, and
53  * <code>addHeaderLine</code> methods are responsible for enforcing
54  * the MIME requirements for the specified headers. In addition, these
55  * header fields must be folded (wrapped) before being sent if they
56  * exceed the line length limitation for the transport (1000 bytes for
57  * SMTP). Received headers may have been folded. The application is
58  * responsible for folding and unfolding headers as appropriate. <p>
59  *
60  * @see javax.mail.internet.MimeUtility
61  * @author John Mani
62  * @author Bill Shannon
63  */

64
65 public class InternetHeaders {
66     /**
67      * An individual internet header. This class is only used by
68      * subclasses of InternetHeaders. <p>
69      *
70      * An InternetHeader object with a null value is used as a placeholder
71      * for headers of that name, to preserve the order of headers.
72      * A placeholder InternetHeader object with a name of ":" marks
73      * the location in the list of headers where new headers are
74      * added by default.
75      *
76      * @since JavaMail 1.4
77      */

78     protected static final class InternetHeader extends Header {
79     /*
80      * Note that the value field from the superclass
81      * isn't used in this class. We extract the value
82      * from the line field as needed. We store the line
83      * rather than just the value to ensure that we can
84      * get back the exact original line, with the original
85      * whitespace, etc.
86      */

87     String JavaDoc line; // the entire RFC822 header "line",
88
// or null if placeholder
89

90     /**
91      * Constructor that takes a line and splits out
92      * the header name.
93      */

94     public InternetHeader(String JavaDoc l) {
95         super("", ""); // XXX - we'll change it later
96
int i = l.indexOf(':');
97         if (i < 0) {
98         // should never happen
99
name = l.trim();
100         } else {
101         name = l.substring(0, i).trim();
102         }
103         line = l;
104     }
105
106     /**
107      * Constructor that takes a header name and value.
108      */

109     public InternetHeader(String JavaDoc n, String JavaDoc v) {
110         super(n, "");
111         if (v != null)
112         line = n + ": " + v;
113         else
114         line = null;
115     }
116
117     /**
118      * Return the "value" part of the header line.
119      */

120     public String JavaDoc getValue() {
121         int i = line.indexOf(':');
122         if (i < 0)
123         return line;
124         // skip whitespace after ':'
125
int j;
126         for (j = i + 1; j < line.length(); j++) {
127         char c = line.charAt(j);
128         if (!(c == ' ' || c == '\t' || c == '\r' || c == '\n'))
129             break;
130         }
131         return line.substring(j);
132     }
133     }
134
135     /*
136      * The enumeration object used to enumerate an
137      * InternetHeaders object. Can return
138      * either a String or a Header object.
139      */

140     static class matchEnum implements Enumeration {
141     private Iterator e; // enum object of headers List
142
// XXX - is this overkill? should we step through in index
143
// order instead?
144
private String JavaDoc names[]; // names to match, or not
145
private boolean match; // return matching headers?
146
private boolean want_line; // return header lines?
147
private InternetHeader next_header; // the next header to be returned
148

149     /*
150      * Constructor. Initialize the enumeration for the entire
151      * List of headers, the set of headers, whether to return
152      * matching or non-matching headers, and whether to return
153      * header lines or Header objects.
154      */

155     matchEnum(List v, String JavaDoc n[], boolean m, boolean l) {
156         e = v.iterator();
157         names = n;
158         match = m;
159         want_line = l;
160         next_header = null;
161     }
162
163     /*
164      * Any more elements in this enumeration?
165      */

166     public boolean hasMoreElements() {
167         // if necessary, prefetch the next matching header,
168
// and remember it.
169
if (next_header == null)
170         next_header = nextMatch();
171         return next_header != null;
172     }
173
174     /*
175      * Return the next element.
176      */

177     public Object JavaDoc nextElement() {
178         if (next_header == null)
179         next_header = nextMatch();
180
181         if (next_header == null)
182         throw new NoSuchElementException("No more headers");
183
184         InternetHeader h = next_header;
185         next_header = null;
186         if (want_line)
187         return h.line;
188         else
189         return new Header(h.getName(), h.getValue());
190     }
191
192     /*
193      * Return the next Header object according to the match
194      * criteria, or null if none left.
195      */

196     private InternetHeader nextMatch() {
197         next:
198         while (e.hasNext()) {
199         InternetHeader h = (InternetHeader)e.next();
200
201         // skip "place holder" headers
202
if (h.line == null)
203             continue;
204
205         // if no names to match against, return appropriately
206
if (names == null)
207             return match ? null : h;
208
209         // check whether this header matches any of the names
210
for (int i = 0; i < names.length; i++) {
211             if (names[i].equalsIgnoreCase(h.getName())) {
212             if (match)
213                 return h;
214             else
215                 // found a match, but we're
216
// looking for non-matches.
217
// try next header.
218
continue next;
219             }
220         }
221         // found no matches. if that's what we wanted, return it.
222
if (!match)
223             return h;
224         }
225         return null;
226     }
227     }
228
229
230     /**
231      * The actual list of Headers, including placeholder entries.
232      * Placeholder entries are Headers with a null value and
233      * are never seen by clients of the InternetHeaders class.
234      * Placeholder entries are used to keep track of the preferred
235      * order of headers. Headers are never actually removed from
236      * the list, they're converted into placeholder entries.
237      * New headers are added after existing headers of the same name
238      * (or before in the case of <code>Received</code> and
239      * <code>Return-Path</code> headers). If no existing header
240      * or placeholder for the header is found, new headers are
241      * added after the special placeholder with the name ":".
242      *
243      * @since JavaMail 1.4
244      */

245     protected List headers;
246
247     /**
248      * Create an empty InternetHeaders object. Placeholder entries
249      * are inserted to indicate the preferred order of headers.
250      */

251     public InternetHeaders() {
252     headers = new ArrayList(40);
253     headers.add(new InternetHeader("Return-Path", null));
254     headers.add(new InternetHeader("Received", null));
255     headers.add(new InternetHeader("Resent-Date", null));
256     headers.add(new InternetHeader("Resent-From", null));
257     headers.add(new InternetHeader("Resent-Sender", null));
258     headers.add(new InternetHeader("Resent-To", null));
259     headers.add(new InternetHeader("Resent-Cc", null));
260     headers.add(new InternetHeader("Resent-Bcc", null));
261     headers.add(new InternetHeader("Resent-Message-Id", null));
262     headers.add(new InternetHeader("Date", null));
263     headers.add(new InternetHeader("From", null));
264     headers.add(new InternetHeader("Sender", null));
265     headers.add(new InternetHeader("Reply-To", null));
266     headers.add(new InternetHeader("To", null));
267     headers.add(new InternetHeader("Cc", null));
268     headers.add(new InternetHeader("Bcc", null));
269     headers.add(new InternetHeader("Message-Id", null));
270     headers.add(new InternetHeader("In-Reply-To", null));
271     headers.add(new InternetHeader("References", null));
272     headers.add(new InternetHeader("Subject", null));
273     headers.add(new InternetHeader("Comments", null));
274     headers.add(new InternetHeader("Keywords", null));
275     headers.add(new InternetHeader("Errors-To", null));
276     headers.add(new InternetHeader("MIME-Version", null));
277     headers.add(new InternetHeader("Content-Type", null));
278     headers.add(new InternetHeader("Content-Transfer-Encoding", null));
279     headers.add(new InternetHeader("Content-MD5", null));
280     headers.add(new InternetHeader(":", null));
281     headers.add(new InternetHeader("Content-Length", null));
282     headers.add(new InternetHeader("Status", null));
283     }
284
285     /**
286      * Read and parse the given RFC822 message stream till the
287      * blank line separating the header from the body. The input
288      * stream is left positioned at the start of the body. The
289      * header lines are stored internally. <p>
290      *
291      * For efficiency, wrap a BufferedInputStream around the actual
292      * input stream and pass it as the parameter. <p>
293      *
294      * No placeholder entries are inserted; the original order of
295      * the headers is preserved.
296      *
297      * @param is RFC822 input stream
298      */

299     public InternetHeaders(InputStream is) throws MessagingException {
300     headers = new ArrayList(40);
301     load(is);
302     }
303
304     /**
305      * Read and parse the given RFC822 message stream till the
306      * blank line separating the header from the body. Store the
307      * header lines inside this InternetHeaders object. The order
308      * of header lines is preserved. <p>
309      *
310      * Note that the header lines are added into this InternetHeaders
311      * object, so any existing headers in this object will not be
312      * affected. Headers are added to the end of the existing list
313      * of headers, in order.
314      *
315      * @param is RFC822 input stream
316      */

317     public void load(InputStream is) throws MessagingException {
318     // Read header lines until a blank line. It is valid
319
// to have BodyParts with no header lines.
320
String JavaDoc line;
321     LineInputStream lis = new LineInputStream(is);
322     String JavaDoc prevline = null; // the previous header line, as a string
323
// a buffer to accumulate the header in, when we know it's needed
324
StringBuffer JavaDoc lineBuffer = new StringBuffer JavaDoc();
325
326     try {
327         //while ((line = lis.readLine()) != null) {
328
do {
329         line = lis.readLine();
330         if (line != null &&
331             (line.startsWith(" ") || line.startsWith("\t"))) {
332             // continuation of header
333
if (prevline != null) {
334             lineBuffer.append(prevline);
335             prevline = null;
336             }
337             lineBuffer.append("\r\n");
338             lineBuffer.append(line);
339         } else {
340             // new header
341
if (prevline != null)
342             addHeaderLine(prevline);
343             else if (lineBuffer.length() > 0) {
344             // store previous header first
345
addHeaderLine(lineBuffer.toString());
346             lineBuffer.setLength(0);
347             }
348             prevline = line;
349         }
350         } while (line != null && line.length() > 0);
351     } catch (IOException ioex) {
352         throw new MessagingException("Error in input stream", ioex);
353     }
354     }
355
356     /**
357      * Return all the values for the specified header. The
358      * values are String objects. Returns <code>null</code>
359      * if no headers with the specified name exist.
360      *
361      * @param name header name
362      * @return array of header values, or null if none
363      */

364     public String JavaDoc[] getHeader(String JavaDoc name) {
365     Iterator e = headers.iterator();
366     // XXX - should we just step through in index order?
367
List v = new ArrayList(); // accumulate return values
368

369     while (e.hasNext()) {
370         InternetHeader h = (InternetHeader)e.next();
371         if (name.equalsIgnoreCase(h.getName()) && h.line != null) {
372         v.add(h.getValue());
373         }
374     }
375     if (v.size() == 0)
376         return (null);
377     // convert List to an array for return
378
String JavaDoc r[] = new String JavaDoc[v.size()];
379     r = (String JavaDoc[])v.toArray(r);
380     return (r);
381     }
382
383     /**
384      * Get all the headers for this header name, returned as a single
385      * String, with headers separated by the delimiter. If the
386      * delimiter is <code>null</code>, only the first header is
387      * returned. Returns <code>null</code>
388      * if no headers with the specified name exist.
389      *
390      * @param name header name
391      * @param delimiter delimiter
392      * @return the value fields for all headers with
393      * this name, or null if none
394      */

395     public String JavaDoc getHeader(String JavaDoc name, String JavaDoc delimiter) {
396     String JavaDoc s[] = getHeader(name);
397
398     if (s == null)
399         return null;
400     
401     if ((s.length == 1) || delimiter == null)
402         return s[0];
403     
404     StringBuffer JavaDoc r = new StringBuffer JavaDoc(s[0]);
405     for (int i = 1; i < s.length; i++) {
406         r.append(delimiter);
407         r.append(s[i]);
408     }
409     return r.toString();
410     }
411
412     /**
413      * Change the first header line that matches name
414      * to have value, adding a new header if no existing header
415      * matches. Remove all matching headers but the first. <p>
416      *
417      * Note that RFC822 headers can only contain US-ASCII characters
418      *
419      * @param name header name
420      * @param value header value
421      */

422     public void setHeader(String JavaDoc name, String JavaDoc value) {
423     boolean found = false;
424
425     for (int i = 0; i < headers.size(); i++) {
426         InternetHeader h = (InternetHeader)headers.get(i);
427         if (name.equalsIgnoreCase(h.getName())) {
428         if (!found) {
429             int j;
430             if (h.line != null && (j = h.line.indexOf(':')) >= 0) {
431             h.line = h.line.substring(0, j + 1) + " " + value;
432             // preserves capitalization, spacing
433
} else {
434             h.line = name + ": " + value;
435             }
436             found = true;
437         } else {
438             headers.remove(i);
439             i--; // have to look at i again
440
}
441         }
442     }
443     
444     if (!found) {
445         addHeader(name, value);
446     }
447     }
448
449     /**
450      * Add a header with the specified name and value to the header list. <p>
451      *
452      * The current implementation knows about the preferred order of most
453      * well-known headers and will insert headers in that order. In
454      * addition, it knows that <code>Received</code> headers should be
455      * inserted in reverse order (newest before oldest), and that they
456      * should appear at the beginning of the headers, preceeded only by
457      * a possible <code>Return-Path</code> header. <p>
458      *
459      * Note that RFC822 headers can only contain US-ASCII characters.
460      *
461      * @param name header name
462      * @param value header value
463      */

464     public void addHeader(String JavaDoc name, String JavaDoc value) {
465     int pos = headers.size();
466     boolean addReverse =
467         name.equalsIgnoreCase("Received") ||
468         name.equalsIgnoreCase("Return-Path");
469     if (addReverse)
470         pos = 0;
471     for (int i = headers.size() - 1; i >= 0; i--) {
472         InternetHeader h = (InternetHeader)headers.get(i);
473         if (name.equalsIgnoreCase(h.getName())) {
474         if (addReverse) {
475             pos = i;
476         } else {
477             headers.add(i + 1, new InternetHeader(name, value));
478             return;
479         }
480         }
481         // marker for default place to add new headers
482
if (h.getName().equals(":"))
483         pos = i;
484     }
485     headers.add(pos, new InternetHeader(name, value));
486     }
487
488     /**
489      * Remove all header entries that match the given name
490      * @param name header name
491      */

492     public void removeHeader(String JavaDoc name) {
493     for (int i = 0; i < headers.size(); i++) {
494         InternetHeader h = (InternetHeader)headers.get(i);
495         if (name.equalsIgnoreCase(h.getName())) {
496         h.line = null;
497         //headers.remove(i);
498
//i--; // have to look at i again
499
}
500     }
501     }
502
503     /**
504      * Return all the headers as an Enumeration of
505      * {@link javax.mail.Header} objects.
506      *
507      * @return Header objects
508      */

509     public Enumeration getAllHeaders() {
510     return (new matchEnum(headers, null, false, false));
511     }
512
513     /**
514      * Return all matching {@link javax.mail.Header} objects.
515      *
516      * @return matching Header objects
517      */

518     public Enumeration getMatchingHeaders(String JavaDoc[] names) {
519     return (new matchEnum(headers, names, true, false));
520     }
521
522     /**
523      * Return all non-matching {@link javax.mail.Header} objects.
524      *
525      * @return non-matching Header objects
526      */

527     public Enumeration getNonMatchingHeaders(String JavaDoc[] names) {
528     return (new matchEnum(headers, names, false, false));
529     }
530
531     /**
532      * Add an RFC822 header line to the header store.
533      * If the line starts with a space or tab (a continuation line),
534      * add it to the last header line in the list. Otherwise,
535      * append the new header line to the list. <p>
536      *
537      * Note that RFC822 headers can only contain US-ASCII characters
538      *
539      * @param line raw RFC822 header line
540      */

541     public void addHeaderLine(String JavaDoc line) {
542     try {
543         char c = line.charAt(0);
544         if (c == ' ' || c == '\t') {
545         InternetHeader h =
546             (InternetHeader)headers.get(headers.size() - 1);
547         h.line += "\r\n" + line;
548         } else
549         headers.add(new InternetHeader(line));
550     } catch (StringIndexOutOfBoundsException JavaDoc e) {
551         // line is empty, ignore it
552
return;
553     } catch (NoSuchElementException e) {
554         // XXX - vector is empty?
555
}
556     }
557
558     /**
559      * Return all the header lines as an Enumeration of Strings.
560      */

561     public Enumeration getAllHeaderLines() {
562     return (getNonMatchingHeaderLines(null));
563     }
564
565     /**
566      * Return all matching header lines as an Enumeration of Strings.
567      */

568     public Enumeration getMatchingHeaderLines(String JavaDoc[] names) {
569     return (new matchEnum(headers, names, true, true));
570     }
571
572     /**
573      * Return all non-matching header lines
574      */

575     public Enumeration getNonMatchingHeaderLines(String JavaDoc[] names) {
576     return (new matchEnum(headers, names, false, true));
577     }
578 }
579
Popular Tags