KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > oyster > util > MimeAssist


1 /**
2  * Title: Oyster Project
3  * Description: Creating S/MIME email transport capabilities.
4  * Copyright: Copyright (c) 2001
5  * @Author Vladimir Radisic
6  * @Version 2.1.5
7  */

8
9 package org.enhydra.oyster.util;
10
11 import org.enhydra.oyster.exception.ErrorStorage;
12 import org.enhydra.oyster.exception.SMIMEException;
13 import java.net.InetAddress;
14 import java.util.Random;
15 import java.io.File;
16 import javax.mail.internet.MimeMessage;
17 import java.io.FileInputStream;
18 import java.io.ByteArrayOutputStream;
19 import javax.mail.Header;
20 import java.util.Enumeration;
21 import javax.activation.MimetypesFileTypeMap;
22 import java.io.*;
23 import org.bouncycastle.util.encoders.Base64;
24
25
26 /**
27  * MimeAssist contains static methods which help in manipulation and work
28  * with mime messages.
29  */

30 public class MimeAssist {
31
32 /**
33  * Unique number for one session;
34  */

35   private static long sesionIncrement = 0L;
36
37 /**
38  * Converts email messages, previously composed in Java MimeMessage object,
39  * to byte array suitable for later processing within CMS object. Input
40  * (MimeMessage) has all the necessary data for sending MIME message
41  * (attachments, text content, Content-Type, Content-Transfer-Encoding etc).
42  * All RFC822 header lines except Content-Type, Content-Transfer-Encoding,
43  * Content-Disposition and Content-Description are removed in proces of
44  * converting.
45  * @param message0 MIME email prepared for sending as MimeMessage
46  * @return Byte array representation of MIME email prepared for later use in
47  * criptographic processing.
48  * @exception SMIMEException if there is no MimeBodyPart in MimeMultipart
49  * message, or in the cases of unrecognisable content of bodypart in MIME
50  * multipart/mixed message or unrecognisable Content-Transfer-Encoding of
51  * message. Also, it can be caused by non SMIMEException which can be one of
52  * the following: MessagingException, IOException or
53  * UnsupportedEncodingException.
54  */

55   public static byte[] messageConvertor(MimeMessage message0) throws SMIMEException{
56     String s = new String(); // Container for message
57
byte[] returnByteArray = null;
58
59     try {
60       MimeMessage message = new MimeMessage(message0);
61
62       Enumeration enum = message0.getAllHeaders();
63
64       while(enum.hasMoreElements()) {
65         Header temp = (Header)enum.nextElement();
66         if( !(temp.getName().equalsIgnoreCase("Content-Type") ||
67               temp.getName().equalsIgnoreCase("Content-Transfer-Encoding") ||
68               temp.getName().equalsIgnoreCase("Content-Disposition") ||
69               temp.getName().equalsIgnoreCase("Content-Description")) ) {
70           message.removeHeader(temp.getName());
71         }
72       }
73
74       ByteArrayOutputStream baos = new ByteArrayOutputStream();
75       String[] excludeHeaders = {"Message-ID", "Mime-Version"};
76       message.writeTo(baos, excludeHeaders);
77       s = baos.toString("ISO-8859-1");
78       returnByteArray = s.getBytes("ISO-8859-1");
79     }
80     catch (Exception e) {
81       throw SMIMEException.getInstance("org.enhydra.oyster.util.MimeAssist",
82                                         e, "MessageConvertor");
83     }
84     return returnByteArray;
85   }
86
87 /**
88  * Converts email messages, previously composed in Java MimeMessage object,
89  * to String suitable for later criptographic processing. Input
90  * (MimeMessage) has all the necessery data for sending MIME message
91  * (attachments, text content, Content-Type, Content-Transfer-Encoding etc).
92  * All RFC822 header lines except Content-Type, Content-Transfer-Encoding,
93  * Content-Disposition and Content-Description are removed in the process of
94  * converting.
95  * @param message0 MIME email prepared for sending as MimeMessage
96  * @return String representation of MIME email prepared for later use in
97  * criptographic processing.
98  * @exception SMIMEException if there is no MimeBodyPart in MimeMultipart
99  * message, or in the cases of unrecognisable content of bodypart in MIME
100  * multipart/mixed message or unrecognisable Content-Transfer-Encoding of
101  * message. Also, it can be caused by non SMIMEException which can be one of
102  * the following: MessagingException or IOException.
103  */

104   public static String messageStringConvertor(MimeMessage message0) throws SMIMEException{
105     String s = new String(); // Container for message
106
try {
107       MimeMessage message = new MimeMessage(message0);
108
109       Enumeration enum = message0.getAllHeaders();
110
111       while(enum.hasMoreElements()) {
112         Header temp = (Header)enum.nextElement();
113         if( !(temp.getName().equalsIgnoreCase("Content-Type") ||
114               temp.getName().equalsIgnoreCase("Content-Transfer-Encoding") ||
115               temp.getName().equalsIgnoreCase("Content-Disposition") ||
116               temp.getName().equalsIgnoreCase("Content-Description")) ) {
117           message.removeHeader(temp.getName());
118         }
119       }
120
121       ByteArrayOutputStream baos = new ByteArrayOutputStream();
122       String[] excludeHeaders = {"Message-ID", "Mime-Version"};
123       message.writeTo(baos, excludeHeaders);
124       s = baos.toString();
125     }
126     catch (Exception e) {
127       throw SMIMEException.getInstance("org.enhydra.oyster.util.MimeAssist",
128                                         e, "messageStringConvertor");
129     }
130     return s;
131   }
132
133 /**
134  * Generates value for Content-ID MIME header line which is used in construction
135  * of multipart/related type of MimeMessage. Generated value is composed from
136  * four parts in order to be unique: random number, unique session number, current
137  * date and time defined in milliseconds and the host name.<BR>
138  * <BR>
139  * &lt;random-number&gt;-&lt;unique_session_number&gt;-&lt;date_&_time_in_ms&gt;@&lt;host-name&gt;
140  * <BR>
141  * @return Content-ID value represented as String.
142  * @exception SMIMEException caused by non SMIMEException which is
143  * UnknownHostException
144  */

145   public static String generateID() throws SMIMEException {
146
147     String contentID = "";
148     String hostName = "";
149     try {
150       hostName = InetAddress.getLocalHost().getHostName();
151     }
152     catch (Exception e) {
153       throw SMIMEException.getInstance("org.enhydra.oyster.util.MimeAssist",
154                                         e, "generateID");
155     }
156
157     Random random = new Random(System.currentTimeMillis());
158     contentID = random.nextLong() + "$" + sesionIncrement + "$" +
159                 System.currentTimeMillis() + "@" + hostName ;
160     sesionIncrement++;
161
162     return contentID;
163   }
164
165
166 /**
167  * Returns object of class MimetypesFileTypeMap generated by using data stored
168  * in the given file. For more information see Java documentation related to class
169  * MimetypesFileTypeMap.
170  * @param path0 path and file name of the file which contains desired mime-type
171  * definitions in appropriate format (usually file name is mime.types).
172  * @return MimetypesFileTypeMap object which can be used for getting appropriate
173  * mime-types from desired file names.
174  * @exception SMIMEException caused with non SMIMEException which is IOException
175  */

176   public static MimetypesFileTypeMap getFileTypeMap(String path0) throws SMIMEException {
177     try {
178       return new MimetypesFileTypeMap(new FileInputStream(path0));
179     }
180     catch (Exception e) {
181       throw SMIMEException.getInstance("org.enhydra.oyster.util.MimeAssist",
182                                         e, "getFileTypeMap");
183     }
184   }
185
186
187 /**
188  * Returns mime-type for given file name and extension.
189  * @param file0 is File type object that represents file which mime-type is
190  * looking for.
191  * @param mimeFile0 path and file name of the file which contains desired mime-type
192  * definitions in appropriate format (usually file name is mime.types).
193  * @return mime-type for given file.
194  * @exception SMIMEException caused with non SMIMEException which is IOException
195  */

196   public static String getMimeTypeFromFileName(File file0, String mimeFile0) throws SMIMEException {
197
198     String contType;
199     try {
200       contType = getFileTypeMap(mimeFile0).getContentType(file0);
201     }
202     catch (Exception e) {
203       throw SMIMEException.getInstance("org.enhydra.oyster.util.MimeAssist",
204                                         e, "getMimeTypeFromFileName");
205     }
206     return contType;
207   }
208
209 /**
210  * Returns mime-type for given file name and extension.
211  * @param file0 path and file name of the file which mime-type is looking for.
212  * @param mimeFile0 path and file name to file which contains desired mime-type
213  * definitions in appropriate format (usually file name is mime.types).
214  * @return mime-type for given file.
215  * @exception SMIMEException caused with non SMIMEException which is IOException
216  */

217   public static String getMimeTypeFromFileName(String file0, String mimeFile0) throws SMIMEException {
218
219     File virtualFile = new File(file0);
220
221     return getMimeTypeFromFileName(virtualFile, mimeFile0);
222   }
223
224
225 /**
226  * Returns BASE64 encoded String with the break at the 76th character. Base64
227  * is necessary for encoding, for transport binary data by email in MIME format. After
228  * encoding, data must be split at the 76th charachter (maximum) by inserting
229  * CRLF characters.
230  * @param b0 input byte array
231  * @return BASE64 encoded String with the break at the 76th character
232  * @exception SMIMEException in case of wrong parameter breakPosition0. Also,
233  * it can be caused by non SMIMEException which can be one of the following:
234  * NoSuchPaddingException, NoSuchProviderException, NoSuchAlgorithmException,
235  * InvalidKeyException, BadPaddingException, IllegalBlockSizeException or
236  * UnsupportedEncodingException.
237  */

238   public static String getStringBASE64WithBreakOn76(byte[] b0) throws SMIMEException {
239     return getStringBASE64WithBreak(b0, 76);
240   }
241
242
243 /**
244  * Returns BASE64 encoded byte array with the break at the 76th character. Base64
245  * is necessary for encoding, for transport binary data by email in MIME format. After
246  * encoding, data must be split at the 76th charachter (maximum) by inserting
247  * CRLF characters.
248  * @param b0 input byte array
249  * @return BASE64 encoded byte array with the break at the 76th character
250  * @exception SMIMEException in case of wrong parameter breakPosition0. Also,
251  * it can be caused by non SMIMEException which can be one of the following:
252  * NoSuchPaddingException, NoSuchProviderException, NoSuchAlgorithmException,
253  * InvalidKeyException, BadPaddingException, IllegalBlockSizeException or
254  * UnsupportedEncodingException.
255  */

256   public static byte[] getBASE64WithBreakOn76(byte[] b0) throws SMIMEException {
257     return getBASE64WithBreak(b0, 76);
258   }
259
260
261 /**
262  * Returns BASE64 encoded String with the break at the 76th character. Base64
263  * is necessary for encoding, for transport binary data by email in MIME format. After
264  * encoding, data must be split at the 76th charachter (maximum) by inserting
265  * CRLF characters.
266  * @param s0 input String
267  * @return BASE64 encoded String with the break at the 76th character
268  * @exception SMIMEException in case of wrong parameter breakPosition0. Also,
269  * it can be caused by non SMIMEException which can be one of the following:
270  * NoSuchPaddingException, NoSuchProviderException, NoSuchAlgorithmException,
271  * InvalidKeyException, BadPaddingException, IllegalBlockSizeException or
272  * UnsupportedEncodingException.
273  */

274   public static String getStringBASE64WithBreakOn76(String s0) throws SMIMEException {
275     return getStringBASE64WithBreak(s0, 76);
276   }
277
278
279 /**
280  * Returns BASE64 encoded byte array with the break at the 76th character. Base64
281  * is necessary for encoding, for transport binary data by email in MIME format. After
282  * encoding, data must be split at the 76th charachter (maximum) by inserting
283  * CRLF characters.
284  * @param s0 input String
285  * @return BASE64 encoded byte array with the break at the 76th character
286  * @exception SMIMEException in case of wrong parameter breakPosition0. Also,
287  * it can be caused by non SMIMEException which can be one of the following:
288  * NoSuchPaddingException, NoSuchProviderException, NoSuchAlgorithmException,
289  * InvalidKeyException, BadPaddingException, IllegalBlockSizeException or
290  * UnsupportedEncodingException.
291  */

292   public static byte[] getBASE64WithBreakOn76(String s0) throws SMIMEException {
293     return getBASE64WithBreak(s0, 76);
294   }
295
296
297 /**
298  * Returns BASE64 encoded String with the break at the defined character. Base64
299  * is necessary for encoding, for transport binary data by email in MIME format. After
300  * encoding, data must be split at the 76th charachter (maximum) by inserting
301  * CRLF characters.
302  * @param b0 input byte array
303  * @param breakPosition0 position for breaking lines in resulted Base64
304  * encoding message content. It should be grather than 0 and less or equal
305  * than 76.
306  * @return BASE64 encoded String with the break at the 76th character
307  * @exception SMIMEException in case of wrong parameter breakPosition0. Also,
308  * it can be caused by non SMIMEException which can be one of the following:
309  * NoSuchPaddingException, NoSuchProviderException, NoSuchAlgorithmException,
310  * InvalidKeyException, BadPaddingException, IllegalBlockSizeException or
311  * UnsupportedEncodingException.
312  */

313   public static String getStringBASE64WithBreak (byte[] b0, int breakPosition0) throws SMIMEException {
314     if(breakPosition0<1 | breakPosition0>76)
315       throw new SMIMEException("org.enhydra.oyster.util.Base64ForMime", 1032);
316     StringBuffer b = new StringBuffer(65536);
317     try {
318       String a = new String(Base64.encode(b0), "ISO-8859-1");
319
320       for (int i = 0; breakPosition0*i < a.length(); i++) {
321         try {
322           b.append(a.substring(i * breakPosition0, (i + 1) * breakPosition0));
323         } catch (IndexOutOfBoundsException e) {
324           b.append(a.substring(i * breakPosition0));
325           break;
326         }
327         b.append("\r\n");
328       }
329     }
330     catch(Exception e) {
331       throw SMIMEException.getInstance("org.enhydra.oyster.util.MimeAssist",
332                                        e, "getStringBASE64WithBreak");
333     }
334     return b.toString();
335   }
336
337 /**
338  * Returns BASE64 encoded byte array with the break at the defined character. Base64
339  * is necessary for encoding, for transport binary data by email in MIME format. After
340  * encoding, data must be split at the 76th charachter (maximum) by inserting
341  * CRLF characters.
342  * @param b0 input byte array
343  * @param breakPosition0 position for breaking lines in resulted Base64
344  * encoding message content. It should be grather than 0 and less or equal
345  * than 76.
346  * @return BASE64 encoded byte array with the break at the 76th character
347  * @exception SMIMEException in case of wrong parameter breakPosition0. Also,
348  * it can be caused by non SMIMEException which can be one of the following:
349  * NoSuchPaddingException, NoSuchProviderException, NoSuchAlgorithmException,
350  * InvalidKeyException, BadPaddingException, IllegalBlockSizeException or
351  * UnsupportedEncodingException.
352  */

353   public static byte[] getBASE64WithBreak (byte[] b0, int breakPosition0) throws SMIMEException {
354     byte[] finalBASE64 = null;
355
356     try {
357       finalBASE64 = getStringBASE64WithBreak(b0, breakPosition0).getBytes("ISO-8859-1");
358     }
359     catch(Exception e) {
360       throw SMIMEException.getInstance("org.enhydra.oyster.util.MimeAssist",
361                                         e, "getBASE64WithBreak");
362     }
363     return finalBASE64;
364   }
365
366
367 /**
368  * Returns BASE64 encoded String with the break at the defined character. Base64
369  * is necessary for encoding, for transport binary data by email in MIME format. After
370  * encoding, data must be split at the 76th charachter (maximum) by inserting
371  * CRLF characters.
372  * @param s0 input String
373  * @param breakPosition0 position for breaking lines in resulted Base64
374  * encoding message content. It should be grather than 0 and less or equal
375  * than 76.
376  * @return BASE64 encoded String with the break at the 76th character
377  * @exception SMIMEException in case of wrong parameter breakPosition0. Also,
378  * it can be caused by non SMIMEException which can be one of the following:
379  * NoSuchPaddingException, NoSuchProviderException, NoSuchAlgorithmException,
380  * InvalidKeyException, BadPaddingException, IllegalBlockSizeException or
381  * UnsupportedEncodingException.
382  */

383   public static String getStringBASE64WithBreak (String s0, int breakPosition0) throws SMIMEException {
384     byte[] bArray;
385
386     try {
387       bArray = s0.getBytes("ISO-8859-1");
388     }
389     catch(Exception e) {
390       throw SMIMEException.getInstance("org.enhydra.oyster.util.MimeAssist",
391                                         e, "getStringBASE64WithBreak");
392     }
393     return getStringBASE64WithBreak(bArray, breakPosition0);
394   }
395
396
397 /**
398  * Returns BASE64 encoded byte array with the break at the defined character.
399  * Base64 is necessary for encoding, for transport binary data by email in MIME
400  * format. After encoding, data must be split at the 76th charachter (maximum)
401  * by inserting CRLF characters.
402  * @param s0 input String
403  * @param breakPosition0 position for breaking lines in resulted Base64
404  * encoding message content. It should be grather than 0 and less or equal
405  * than 76.
406  * @return BASE64 encoded byte array with the break at the 76th character
407  * @exception SMIMEException in case of wrong parameter breakPosition0. Also,
408  * it can be caused by non SMIMEException which can be one of the following:
409  * NoSuchPaddingException, NoSuchProviderException, NoSuchAlgorithmException,
410  * InvalidKeyException, BadPaddingException, IllegalBlockSizeException or
411  * UnsupportedEncodingException.
412  */

413   public static byte[] getBASE64WithBreak (String s0, int breakPosition0) throws SMIMEException {
414     byte[] bArray;
415
416     try {
417       bArray = s0.getBytes("ISO-8859-1");
418     }
419     catch(Exception e) {
420       throw SMIMEException.getInstance("org.enhydra.oyster.util.MimeAssist",
421                                         e, "getBASE64WithBreak");
422     }
423     return getBASE64WithBreak(bArray, breakPosition0);
424   }
425
426
427 }
Popular Tags