KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > suberic > pooka > Attachment


1 package net.suberic.pooka;
2 import javax.mail.*;
3 import javax.mail.internet.*;
4 import javax.activation.DataHandler JavaDoc;
5 import java.io.*;
6 import java.util.*;
7 import javax.mail.internet.InternetHeaders JavaDoc;
8
9 public class Attachment {
10   DataHandler JavaDoc handler;
11   String JavaDoc name;
12   ContentType mimeType;
13   int size;
14   String JavaDoc encoding;
15   InternetHeaders JavaDoc headers = null;
16   Vector headerLines = null;
17
18   /**
19    * Creates an Attachment out of a MimeBodyPart.
20    */

21   public Attachment(MimePart mp) throws MessagingException {
22     handler = mp.getDataHandler();
23     name = mp.getFileName();
24     String JavaDoc type = mp.getContentType();
25     try {
26       mimeType = new ContentType(type);
27     } catch (ParseException pe) {
28       if (type.equalsIgnoreCase("text"))
29         mimeType = new ContentType("text/plain");
30       else if (type.length() > 0 && type.indexOf('/') == -1) {
31         try {
32           mimeType = new ContentType(type + "/plain");
33         } catch (ParseException petwo) {
34           // fall back to text/plain.
35
mimeType = new ContentType("text/plain");
36         }
37
38       } else {
39         // fall back to text/plain.
40
mimeType = new ContentType("text/plain");
41       }
42
43     }
44     size = mp.getSize();
45     encoding = mp.getEncoding();
46   }
47
48   /**
49    * Creates an Attachment with the given MimeBodyPart, but with
50    * the attached MimePart as the source for the Headers.
51    */

52   public Attachment(MimePart mp, MimePart headerSource) throws MessagingException {
53     handler = mp.getDataHandler();
54     if (mp instanceof MimeBodyPart)
55       name = mp.getFileName();
56     else
57       name = Pooka.getProperty("message.unknownMessage", "Message Text");
58
59     String JavaDoc type = mp.getContentType();
60     try {
61       mimeType = new ContentType(type);
62     } catch (ParseException pe) {
63       if (type.equalsIgnoreCase("text"))
64         mimeType = new ContentType("text/plain");
65       else if (type.length() > 0 && type.indexOf('/') == -1) {
66         try {
67           mimeType = new ContentType(type + "/plain");
68         } catch (ParseException petwo) {
69           // fall back to text/plain.
70
mimeType = new ContentType("text/plain");
71         }
72       } else {
73         // fall back to text/plain.
74
mimeType = new ContentType("text/plain");
75
76       }
77     }
78     size = mp.getSize();
79     encoding = mp.getEncoding();
80     headers = parseHeaders(headerSource.getAllHeaders());
81     headerLines = parseHeaderLines(headerSource.getAllHeaderLines());
82   }
83
84   /**
85    * Creates an Attachment out of a MimeMessage. This is typically
86    * used when the content of a Message is too large to display, and
87    * therefore it needs to be treated as an attachment rather than
88    * as the text of the Message.
89    */

90   /*
91     public Attachment(MimeMessage msg) throws MessagingException {
92     handler = msg.getDataHandler();
93     name = Pooka.getProperty("message.unknownMessage", "Message Text");
94     String type = msg.getContentType();
95     try {
96     mimeType = new ContentType(type);
97     } catch (ParseException pe) {
98     if (type.equalsIgnoreCase("text"))
99     mimeType = new ContentType("text/plain");
100     else if (type.length() > 0 && type.indexOf('/') == -1) {
101     try {
102     mimeType = new ContentType(type + "/plain");
103     } catch (ParseException petwo) {
104     // fall back to text/plain.
105     mimeType = new ContentType("text/plain");
106     }
107     } else {
108     // fall back to text/plain.
109     mimeType = new ContentType("text/plain");
110     }
111     }
112     size = msg.getSize();
113     encoding = msg.getEncoding();
114     }
115   */

116
117   public void setHeaderSource(MimePart headerSource) throws MessagingException {
118     headers = parseHeaders(headerSource.getAllHeaders());
119     headerLines = parseHeaderLines(headerSource.getAllHeaderLines());
120   }
121
122   public void setHeaderSource(AttachmentBundle bundle) {
123     headers = bundle.headers;
124     headerLines = bundle.headerLines;
125   }
126
127   // accessor methods.
128

129   /**
130    * Returns the decoded InputStream of this Attachment.
131    */

132   public InputStream getInputStream() throws java.io.IOException JavaDoc {
133     return handler.getInputStream();
134   }
135
136   /**
137    * Returns the DataHandler for this Attachment.
138    */

139   public DataHandler JavaDoc getDataHandler() {
140     return handler;
141   }
142
143   /**
144    * Returns the content of this attachment as an Object.
145    */

146   public Object JavaDoc getContent() throws java.io.IOException JavaDoc {
147     try {
148       return getDataHandler().getContent();
149     } catch (UnsupportedEncodingException uee) {
150       if (isText()) {
151         /**
152          * Just read the InputStream directly into a byte array and
153          * hope for the best. :)
154          */

155         InputStream is = getDataHandler().getInputStream();
156         ByteArrayOutputStream bos = new ByteArrayOutputStream();
157         int b;
158         while ((b = is.read()) != -1)
159           bos.write(b);
160         byte[] barray = bos.toByteArray();
161         return new String JavaDoc(barray, Pooka.getProperty("Pooka.defaultCharset", "iso-8859-1"));
162       } else {
163         throw uee;
164       }
165     }
166   }
167
168   public int getSize() {
169     return size;
170   }
171
172   public String JavaDoc getName() {
173     return name;
174   }
175
176   public String JavaDoc getEncoding() {
177     return encoding;
178   }
179
180   public ContentType getMimeType() {
181     return mimeType;
182   }
183
184   public boolean isText() {
185     return getMimeType().match("text/");
186   }
187
188   public boolean isPlainText() {
189     return getMimeType().match("text/plain") ;
190   }
191
192   public boolean isHtml() {
193     return getMimeType().match("text/html");
194   }
195
196   /**
197    * Returns the text of the Attachment, up to maxLength bytes. If
198    * the content is truncated, then append the truncationMessage at the
199    * end of the content displayed.
200    *
201    * If withHeaders is set, then show the Headers to go with this message.
202    * If showFullHeaders is also set, then show all the headers.
203    */

204   public String JavaDoc getText(boolean withHeaders, boolean showFullHeaders, int maxLength, String JavaDoc truncationMessage) throws java.io.IOException JavaDoc {
205     if (isPlainText()) {
206       StringBuffer JavaDoc retVal = new StringBuffer JavaDoc();
207       if (withHeaders)
208         retVal.append(getHeaderInformation(showFullHeaders));
209
210       retVal.append(getText(maxLength, truncationMessage));
211
212       return retVal.toString();
213     } else
214       return null;
215   }
216
217   /**
218    * Returns the String content of this message, up to maxLength
219    * bytes.
220    */

221   String JavaDoc getText(int maxLength, String JavaDoc truncationMessage) throws IOException {
222     if (maxLength > 0 && maxLength >= size) {
223       try {
224         Object JavaDoc o = getDataHandler().getContent();
225         if (o instanceof String JavaDoc)
226           return (String JavaDoc) o;
227         else
228           throw new UnsupportedEncodingException();
229       } catch (UnsupportedEncodingException uee) {
230         /**
231          * Just read the InputStream directly into a byte array and
232          * hope for the best. :)
233          */

234
235         InputStream is = getDataHandler().getInputStream();
236         ByteArrayOutputStream bos = new ByteArrayOutputStream();
237         int b;
238         while ((b = is.read()) != -1)
239           bos.write(b);
240         byte[] barray = bos.toByteArray();
241         return new String JavaDoc(barray, Pooka.getProperty("Pooka.defaultCharset", "iso-8859-1"));
242       }
243     } else {
244       int written = 0;
245       InputStream decodedIS = null;
246       ByteArrayOutputStream outStream = new ByteArrayOutputStream();
247
248       decodedIS = getInputStream();
249
250       int b=0;
251       byte[] buf = new byte[16384];
252
253       b = decodedIS.read(buf);
254       while (b != -1 && written < maxLength) {
255         if (b <= (maxLength - written)) {
256           outStream.write(buf, 0, b);
257           written = written + b;
258         } else {
259           outStream.write(buf, 0, (maxLength - written));
260           written = maxLength;
261         }
262         b = decodedIS.read(buf);
263       }
264
265       byte[] barray = outStream.toByteArray();
266       String JavaDoc content;
267       try {
268         content = new String JavaDoc(barray, Pooka.getProperty("Pooka.defaultCharset", "iso-8859-1"));
269       } catch (UnsupportedEncodingException uee) {
270         content = new String JavaDoc(barray, Pooka.getProperty("Pooka.defaultCharset", "iso-8859-1"));
271       }
272
273       return content + "\n" + truncationMessage + "\n";
274     }
275
276   }
277
278   /**
279    * Returns the html of the Attachment, up to maxLength bytes. If
280    * the content is truncated, then append the truncationMessage at the
281    * end of the content displayed.
282    *
283    * If withHeaders is set, then show the Headers to go with this message.
284    * If showFullHeaders is also set, then show all the headers.
285    */

286   public String JavaDoc getHtml(boolean withHeaders, boolean showFullHeaders, int maxLength, String JavaDoc truncationMessage) throws java.io.IOException JavaDoc {
287     if (isHtml()) {
288       StringBuffer JavaDoc retVal = new StringBuffer JavaDoc();
289       if (withHeaders)
290         retVal.append(getHeaderInformation(showFullHeaders));
291
292       retVal.append(getText(maxLength, truncationMessage));
293
294       return retVal.toString();
295     } else
296       return null;
297   }
298
299   /**
300    * Parses the Enumeration of Header objects into a HashMap.
301    */

302   private InternetHeaders JavaDoc parseHeaders(Enumeration pHeaders) {
303     InternetHeaders JavaDoc retVal = new InternetHeaders JavaDoc();
304     while (pHeaders.hasMoreElements()) {
305       Header hdr = (Header) pHeaders.nextElement();
306       retVal.addHeader(hdr.getName(), hdr.getValue());
307     }
308
309     return retVal;
310   }
311
312   /**
313    * Parses the Enumeration of header lines into a Vector.
314    */

315   private Vector parseHeaderLines(Enumeration pHeaderLines) {
316     Vector retVal = new Vector();
317     while (pHeaderLines.hasMoreElements())
318       retVal.add(pHeaderLines.nextElement());
319     return retVal;
320   }
321
322   /**
323    * This returns the formatted header information for a message.
324    */

325   public StringBuffer JavaDoc getHeaderInformation (boolean showFullHeaders) {
326     if (headers != null) {
327       StringBuffer JavaDoc headerText = new StringBuffer JavaDoc();
328
329       if (showFullHeaders) {
330         Enumeration allHdrs = headers.getAllHeaderLines();
331         while (allHdrs.hasMoreElements()) {
332           headerText.append(MailUtilities.decodeText((String JavaDoc) allHdrs.nextElement()));
333         }
334       } else {
335         StringTokenizer tokens = new StringTokenizer(Pooka.getProperty("MessageWindow.Header.DefaultHeaders", "From:To:CC:Date:Subject"), ":");
336         String JavaDoc hdrLabel,currentHeader = null;
337         String JavaDoc hdrValue = null;
338
339         while (tokens.hasMoreTokens()) {
340           currentHeader=tokens.nextToken();
341           hdrLabel = Pooka.getProperty("MessageWindow.Header." + currentHeader + ".label", currentHeader);
342           hdrValue = MailUtilities.decodeText((String JavaDoc) headers.getHeader(Pooka.getProperty("MessageWindow.Header." + currentHeader + ".MIMEHeader", currentHeader), ":"));
343           if (hdrValue != null) {
344             headerText.append(hdrLabel + ": ");
345             headerText.append(hdrValue);
346
347             headerText.append("\n");
348           }
349         }
350       }
351       String JavaDoc separator = Pooka.getProperty("MessageWindow.separator", "");
352       if (separator.equals(""))
353         headerText.append("\n\n");
354       else
355         headerText.append(separator);
356
357       return headerText;
358     } else {
359       return new StringBuffer JavaDoc();
360     }
361   }
362
363   /**
364    * Returns the Headers for this Attachment.
365    */

366   public InternetHeaders JavaDoc getHeaders() {
367     return headers;
368   }
369 }
370
371
Popular Tags