KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > hipermail > DBMimePart


1 /*
2   Copyright (C) 2004 Know Gate S.L. All rights reserved.
3                       C/Oņa, 107 1š2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.hipermail;
34
35 import com.knowgate.debug.DebugFile;
36 import com.knowgate.dataobjs.DB;
37 import com.knowgate.dataobjs.DBBind;
38 import com.knowgate.jdc.JDCConnection;
39 import com.knowgate.misc.Gadgets;
40
41 import java.io.StringBufferInputStream JavaDoc;
42 import java.io.InputStream JavaDoc;
43 import java.io.IOException JavaDoc;
44 import java.io.OutputStream JavaDoc;
45 import java.io.UnsupportedEncodingException JavaDoc;
46 import java.io.FileInputStream JavaDoc;
47 import java.io.File JavaDoc;
48
49 import java.util.LinkedList JavaDoc;
50 import java.util.Properties JavaDoc;
51 import java.util.Enumeration JavaDoc;
52
53 import java.math.BigDecimal JavaDoc;
54
55 import java.net.URL JavaDoc;
56 import java.net.MalformedURLException JavaDoc;
57
58 import java.sql.Blob JavaDoc;
59 import java.sql.ResultSet JavaDoc;
60 import java.sql.Statement JavaDoc;
61 import java.sql.CallableStatement JavaDoc;
62 import java.sql.PreparedStatement JavaDoc;
63 import java.sql.SQLException JavaDoc;
64 import java.sql.Timestamp JavaDoc;
65
66 import javax.activation.DataHandler JavaDoc;
67
68 import javax.mail.Multipart JavaDoc;
69 import javax.mail.BodyPart JavaDoc;
70 import javax.mail.internet.MimeMessage JavaDoc;
71 import javax.mail.internet.MimePart JavaDoc;
72 import javax.mail.internet.MimeMultipart JavaDoc;
73 import javax.mail.internet.MimeBodyPart JavaDoc;
74 import javax.mail.MessagingException JavaDoc;
75
76 import org.apache.oro.text.regex.MalformedPatternException;
77 import org.apache.oro.text.regex.Perl5Compiler;
78
79 import javax.activation.DataHandler JavaDoc;
80 import javax.activation.FileDataSource JavaDoc;
81
82 import com.knowgate.dfs.ByteArrayDataSource;
83 import com.knowgate.dfs.FileSystem;
84
85 /**
86  * @author Sergio Montoro Ten
87  * @version 1.0
88  */

89
90 public class DBMimePart extends BodyPart JavaDoc implements MimePart JavaDoc {
91   private int iPartId, iSize;
92   private String JavaDoc sMD5,sFile;
93   private MimeBodyPart JavaDoc oMimeBody;
94   private Multipart JavaDoc oParent;
95   private Properties JavaDoc oHeaders;
96
97   public DBMimePart(Multipart JavaDoc oMultipart) {
98     oMimeBody = null;
99     oParent = oMultipart;
100     oHeaders = new Properties JavaDoc();
101   }
102
103   public DBMimePart(InputStream JavaDoc oInStrm)
104     throws MessagingException JavaDoc {
105     oMimeBody = new MimeBodyPart JavaDoc(oInStrm);
106
107     iPartId = -1;
108     iSize = oMimeBody.getSize();
109
110     oHeaders = new Properties JavaDoc();
111     oHeaders.setProperty("Content-ID", oMimeBody.getContentID());
112     oHeaders.setProperty("Content-Type", oMimeBody.getContentType());
113     oHeaders.setProperty("Content-Transfer-Encoding", oMimeBody.getEncoding());
114     oHeaders.setProperty("Content-Description", oMimeBody.getDescription());
115     oHeaders.setProperty("Content-Disposition", oMimeBody.getDisposition());
116
117     sMD5 = oMimeBody.getContentMD5();
118     sFile = oMimeBody.getFileName();
119   }
120
121   // ---------------------------------------------------------------------------
122

123   public DBMimePart(Multipart JavaDoc oMultipart, int iIdPart, String JavaDoc sIdContent, String JavaDoc sContentType, String JavaDoc sContentMD5, String JavaDoc sDescription, String JavaDoc sDisposition, String JavaDoc sEncoding, String JavaDoc sFileName, int nBytes)
124     throws MessagingException JavaDoc {
125
126     oMimeBody = null;
127
128     oParent = oMultipart;
129     iPartId = iIdPart;
130     sMD5 = sContentMD5;
131     sFile = sFileName;
132     iSize = nBytes;
133
134     oHeaders = new Properties JavaDoc();
135     if (null!=sIdContent) oHeaders.setProperty("Content-ID", sIdContent);
136     if (null!=sContentType) oHeaders.setProperty("Content-Type", sContentType);
137     if (null!=sDescription) oHeaders.setProperty("Content-Description", sDescription);
138     if (null!=sDisposition) oHeaders.setProperty("Content-Disposition", sDisposition);
139     if (null!=sEncoding) oHeaders.setProperty("Content-Transfer-Encoding", sEncoding);
140   }
141
142   // ---------------------------------------------------------------------------
143

144   private DBMimeMessage getMessage() {
145     return (DBMimeMessage)(oParent.getParent());
146   }
147
148   // ---------------------------------------------------------------------------
149

150   public String JavaDoc[] getHeader(String JavaDoc name) throws MessagingException JavaDoc {
151     return new String JavaDoc[] {oHeaders.getProperty(name)};
152   }
153
154   // ---------------------------------------------------------------------------
155

156   public String JavaDoc getHeader(String JavaDoc name, String JavaDoc delimiter) throws MessagingException JavaDoc {
157     return oHeaders.getProperty(name);
158   }
159
160   // ---------------------------------------------------------------------------
161

162   public java.util.Enumeration JavaDoc getAllHeaders() throws MessagingException JavaDoc {
163     return oHeaders.keys();
164   }
165
166   // ---------------------------------------------------------------------------
167

168   public java.util.Enumeration JavaDoc getMatchingHeaders(java.lang.String JavaDoc[] names) throws MessagingException JavaDoc {
169     return null;
170   }
171
172   // ---------------------------------------------------------------------------
173

174   public java.util.Enumeration JavaDoc getNonMatchingHeaders(java.lang.String JavaDoc[] names) throws MessagingException JavaDoc {
175     return null;
176   }
177
178   // ---------------------------------------------------------------------------
179

180   public void addHeader(String JavaDoc s1, String JavaDoc s2) throws MessagingException JavaDoc {
181     throw new UnsupportedOperationException JavaDoc("Cannot call addHeader() on DBMimePart)");
182   }
183
184   // ---------------------------------------------------------------------------
185

186   public void setHeader(String JavaDoc s1, String JavaDoc s2) throws MessagingException JavaDoc {
187     throw new UnsupportedOperationException JavaDoc("Cannot call setHeader() on DBMimePart)");
188   }
189
190   // ---------------------------------------------------------------------------
191

192   public void removeHeader(String JavaDoc header) throws MessagingException JavaDoc {
193     throw new UnsupportedOperationException JavaDoc("Cannot call removeHeader() on DBMimePart)");
194   }
195
196   // ---------------------------------------------------------------------------
197

198   public void addHeaderLine(java.lang.String JavaDoc line) throws MessagingException JavaDoc {
199     throw new UnsupportedOperationException JavaDoc("Cannot call addHeaderLine() on DBMimePart)");
200   }
201
202   // ---------------------------------------------------------------------------
203

204   public java.util.Enumeration JavaDoc getAllHeaderLines() throws MessagingException JavaDoc {
205     throw new UnsupportedOperationException JavaDoc("Cannot call getAllHeaderLines() on DBMimePart)");
206   }
207
208   // ---------------------------------------------------------------------------
209

210   public java.util.Enumeration JavaDoc getMatchingHeaderLines(java.lang.String JavaDoc[] names) throws MessagingException JavaDoc {
211     throw new UnsupportedOperationException JavaDoc("Cannot call getMatchingHeaderLines() on DBMimePart)");
212   }
213
214   // ---------------------------------------------------------------------------
215

216   public java.util.Enumeration JavaDoc getNonMatchingHeaderLines(java.lang.String JavaDoc[] names) throws MessagingException JavaDoc {
217     throw new UnsupportedOperationException JavaDoc("Cannot call getNonMatchingHeaderLines() on DBMimePart)");
218   }
219
220   // ---------------------------------------------------------------------------
221

222   public Object JavaDoc getContent () throws MessagingException JavaDoc, IOException JavaDoc {
223
224     int iLen;
225     long lPos, lOff;
226     String JavaDoc sFilePath;
227     PreparedStatement JavaDoc oStmt = null;
228     ResultSet JavaDoc oRSet = null;
229     Object JavaDoc oRetVal = null;
230     DBFolder oFldr = (DBFolder) getMessage().getFolder();
231     String JavaDoc sSQL;
232
233     if (DebugFile.trace) {
234       DebugFile.writeln("Begin DBMimePart.getContent()");
235       DebugFile.incIdent();
236       DebugFile.writeln("Message Content-Id is " + getMessage().getContentID() + " and Part Id is " + String.valueOf(iPartId));
237     }
238
239     if (oFldr==null && oMimeBody!=null) {
240       if (DebugFile.trace) DebugFile.decIdent();
241       return oMimeBody.getContent();
242     }
243
244     try {
245       if (null==oFldr) {
246         sSQL = "SELECT m.pg_message,p.id_disposition,m.nu_position,p.file_name,p.len_part,p.nu_offset,p.id_content,m.by_content FROM k_mime_msgs m, k_mime_parts p WHERE (m.gu_mimemsg=? OR m.id_message=?) AND m.gu_mimemsg=p.gu_mimemsg AND p.id_part=?";
247         if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement("+sSQL+")");
248         oStmt = oFldr.getConnection().prepareStatement(sSQL);
249         oStmt.setString(1, getMessage().getMessageGuid());
250         oStmt.setString(2, getMessage().getContentID());
251         oStmt.setInt(3, iPartId);
252       } else {
253         sSQL = "SELECT m.pg_message,p.id_disposition,m.nu_position,p.file_name,p.len_part,p.nu_offset,p.id_content,m.by_content FROM k_mime_msgs m, k_mime_parts p WHERE (m.gu_mimemsg=? OR m.id_message=?) AND m.gu_mimemsg=p.gu_mimemsg AND p.id_part=? AND m.gu_category=?";
254         if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement("+sSQL+")");
255         oStmt = oFldr.getConnection().prepareStatement(sSQL);
256         oStmt.setString(1, getMessage().getMessageGuid());
257         oStmt.setString(2, getMessage().getContentID());
258         oStmt.setInt(3, iPartId);
259         oStmt.setString(4, oFldr.getCategoryGuid());
260       }
261
262       if (DebugFile.trace) DebugFile.writeln("PreparedStatement.executeQuery()");
263       oRSet = oStmt.executeQuery();
264
265       if (oRSet.next()) {
266         String JavaDoc id_disposition = oRSet.getString(2);
267
268         if (oRSet.wasNull()) id_disposition = "inline";
269
270         if (id_disposition.equals("reference")) {
271           if (DebugFile.trace) DebugFile.writeln("content disposition is reference");
272           sFilePath = oRSet.getString(4);
273
274           FileSystem oFS = new FileSystem();
275           byte[] byData = oFS.readfilebin(sFilePath);
276           String JavaDoc sContentType = oRSet.getString(7);
277           if (DebugFile.trace) DebugFile.writeln("new ByteArrayDataSource("+sFilePath+", "+sContentType+")");
278           ByteArrayDataSource baDataSrc = new ByteArrayDataSource(byData, sContentType);
279
280           oMimeBody = new MimeBodyPart JavaDoc();
281           oMimeBody.setDataHandler(new DataHandler JavaDoc(baDataSrc));
282         }
283         else if (id_disposition.equals("pointer")) {
284           if (DebugFile.trace) DebugFile.writeln("content disposition is pointer");
285           lPos = oRSet.getBigDecimal(3).longValue();
286           sFilePath = oRSet.getString(4);
287           iLen = oRSet.getInt(5);
288           lOff = oRSet.getBigDecimal(6).longValue();
289           MboxFile oMbox = new MboxFile(sFilePath, MboxFile.READ_ONLY);
290           InputStream JavaDoc oPartStrm = oMbox.getPartAsStream(lPos, lOff, iLen);
291           oMimeBody = new MimeBodyPart JavaDoc(oPartStrm);
292         }
293         else if ((oFldr.getType()&DBFolder.MODE_BLOB)!=0) {
294           if (DebugFile.trace) DebugFile.writeln("content disposition is " + id_disposition + " mode is BLOB");
295           if (DebugFile.trace) DebugFile.writeln("new MimeBodyPart([InputStream])");
296           oMimeBody = new MimeBodyPart JavaDoc(oRSet.getBinaryStream(8));
297         }
298         else {
299           if (DebugFile.trace) DebugFile.writeln("content disposition is " + id_disposition + " mode is MBOX");
300           BigDecimal JavaDoc oPosition;
301           Object JavaDoc oLenPart, oOffset;
302
303           oPosition = oRSet.getBigDecimal(3);
304           if (!oRSet.wasNull()) lPos = Long.parseLong(oPosition.toString()); else lPos = -1;
305           oLenPart = oRSet.getObject(5);
306           if (!oRSet.wasNull()) iLen = Integer.parseInt(oLenPart.toString()); else iLen = -1;
307           oOffset = oRSet.getObject(6);
308           if (!oRSet.wasNull()) lOff = Long.parseLong(oOffset.toString()); else lOff = -1;
309
310           if (lPos!=-1) {
311             if (iLen==-1) throw new MessagingException JavaDoc("Part " + String.valueOf(iPartId) + " length not set at k_mime_parts table for message "+getMessage().getMessageGuid());
312             if (lOff==-1 ) throw new MessagingException JavaDoc("Part " + String.valueOf(iPartId) + " offset not set at k_mime_parts table for message "+getMessage().getMessageGuid());
313
314             if (DebugFile.trace) DebugFile.writeln("new MboxFile("+((DBFolder)getMessage().getFolder()).getFile()+")");
315
316             MboxFile oMbox = new MboxFile(((DBFolder)getMessage().getFolder()).getFile(), MboxFile.READ_ONLY);
317
318             InputStream JavaDoc oInStrm = oMbox.getPartAsStream(lPos, lOff, iLen);
319             oMimeBody = new MimeBodyPart JavaDoc(oInStrm);
320             oInStrm.close();
321
322             oMbox.close();
323           }
324           else {
325             if (DebugFile.trace) DebugFile.decIdent();
326             throw new MessagingException JavaDoc("Part " + String.valueOf(iPartId) + " not found for message " + getMessage().getContentID());
327           }
328         } // fi (MODE_MBOX)
329
} else {
330         if (DebugFile.trace) {
331           if (null==oFldr)
332             DebugFile.writeln("Part "+String.valueOf(iPartId) + " not found in message ["+getMessage().getMessageGuid()+"] " + getMessage().getContentID());
333           else
334             DebugFile.writeln("Part "+String.valueOf(iPartId) + " not found in message ["+getMessage().getMessageGuid()+"] " + getMessage().getContentID() + " at folder " + oFldr.getCategoryGuid());
335         }
336       } // fi (oRset.next();
337

338       oRSet.close();
339       oRSet = null;
340       oStmt.close();
341       oStmt = null;
342     } catch (SQLException JavaDoc sqle) {
343       try { if (null!=oRSet) oRSet.close(); } catch (Exception JavaDoc ignore) {}
344       try { if (null!=oStmt) oStmt.close(); } catch (Exception JavaDoc ignore) {}
345       throw new MessagingException JavaDoc(sqle.getMessage(), sqle);
346     } catch (com.enterprisedt.net.ftp.FTPException xcpt) {
347       try { if (null!=oRSet) oRSet.close(); } catch (Exception JavaDoc ignore) {}
348       try { if (null!=oStmt) oStmt.close(); } catch (Exception JavaDoc ignore) {}
349       throw new MessagingException JavaDoc(xcpt.getMessage(), xcpt);
350     }
351
352     if (oMimeBody!=null) {
353       if (DebugFile.trace) DebugFile.writeln("MimeBodyPart.getContent()");
354       oRetVal = oMimeBody.getContent();
355     }
356
357     if (DebugFile.trace) {
358       DebugFile.decIdent();
359       if (null==oRetVal)
360         DebugFile.writeln("End DBMimePart.getContent() : null");
361       else
362         DebugFile.writeln("End DBMimePart.getContent() : " + oRetVal.getClass().getName());
363     }
364
365     return oRetVal;
366   } // getContent ()
367

368   // ---------------------------------------------------------------------------
369

370   public DataHandler JavaDoc getDataHandler () throws MessagingException JavaDoc {
371     throw new UnsupportedOperationException JavaDoc("Method getDataHandler() not implemented for DBMimePart");
372   }
373
374   // ---------------------------------------------------------------------------
375

376   public InputStream JavaDoc getInputStream () throws MessagingException JavaDoc, IOException JavaDoc {
377     PreparedStatement JavaDoc oStmt = null;
378     ResultSet JavaDoc oRSet = null;
379     InputStream JavaDoc oRetVal = null;
380     DBFolder oFldr = (DBFolder) getMessage().getFolder();
381
382     if (DebugFile.trace) {
383       DebugFile.writeln("Begin DBMimePart.getInputStream()");
384       DebugFile.incIdent();
385     }
386
387     if (oMimeBody!=null) {
388       if (DebugFile.trace) DebugFile.writeln("BodyPart.getInputStream()");
389       if (DebugFile.trace) DebugFile.decIdent();
390       return oMimeBody.getInputStream();
391     }
392
393     try {
394
395       if (null!=getMessage().getMessageGuid()) {
396         if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT m.pg_message,m.nu_position,p.id_disposition,p.file_name,p.len_part,p.nu_offset,m.by_content FROM k_mime_msgs m, k_mime_parts p WHERE m.gu_mimemsg='"+getMessage().getMessageGuid()+"' AND m.gu_mimemsg=p.gu_mimemsg AND p.id_part="+String.valueOf(iPartId)+")");
397         oStmt = ((DBFolder)getMessage().getFolder()).getConnection().prepareStatement("SELECT m.pg_message,m.nu_position,p.id_disposition,p.file_name,p.len_part,p.nu_offset,m.by_content FROM k_mime_msgs m, k_mime_parts p WHERE m.gu_mimemsg=? AND m.gu_mimemsg=p.gu_mimemsg AND p.id_part=?");
398         oStmt.setString(1, getMessage().getMessageGuid());
399         oStmt.setInt(2, iPartId);
400       }
401       else {
402         if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT m.pg_message,m.nu_position,p.id_disposition,p.file_name,p.len_part,p.nu_offset,m.by_content FROM k_mime_msgs m, k_mime_parts p WHERE m.id_message='"+getMessage().getMessageID()+"' AND m.gu_mimemsg=p.gu_mimemsg AND p.id_part="+String.valueOf(iPartId)+")");
403         oStmt = ((DBFolder)getMessage().getFolder()).getConnection().prepareStatement("SELECT m.pg_message,m.nu_position,p.id_disposition,p.file_name,p.len_part,p.nu_offset,m.by_content FROM k_mime_msgs m, k_mime_parts p WHERE m.id_message=? AND m.gu_mimemsg=p.gu_mimemsg AND p.id_part=?");
404         oStmt.setString(1, getMessage().getMessageID());
405         oStmt.setInt(2, iPartId);
406       }
407
408       oRSet = oStmt.executeQuery();
409
410       if (oRSet.next()) {
411         BigDecimal JavaDoc oMsgPos = oRSet.getBigDecimal(2);
412         if (oRSet.wasNull()) oMsgPos = null;
413         String JavaDoc id_disposition = oRSet.getString(3);
414         if (oRSet.wasNull()) id_disposition = "inline";
415         String JavaDoc sTmpFilePath = oRSet.getString(4);
416
417         if (id_disposition.equals("reference")) {
418           if (DebugFile.trace) DebugFile.writeln("new FileInputStream(" + sTmpFilePath + ")");
419           oRetVal = new FileInputStream JavaDoc(sTmpFilePath);
420         }
421         else if (id_disposition.equals("pointer")) {
422           if (null==oMsgPos) throw new SQLException JavaDoc ("nu_position column may not be null for parts with pointer disposition", "22002", 22002);
423           Object JavaDoc oPartLen = oRSet.getObject(5);
424           if (oRSet.wasNull()) throw new SQLException JavaDoc ("len_part column may not be null for parts with pointer disposition", "22002", 22002);
425           BigDecimal JavaDoc oPartOffset = oRSet.getBigDecimal(6);
426           if (oRSet.wasNull()) throw new SQLException JavaDoc ("nu_offset column may not be null for parts with pointer disposition", "22002", 22002);
427           if (DebugFile.trace) DebugFile.writeln("new File(" + sTmpFilePath + ")");
428           File oFile = new File (sTmpFilePath);
429           MboxFile oMbox = new MboxFile(oFile, MboxFile.READ_ONLY);
430           oRetVal = oMbox.getPartAsStream(oMsgPos.longValue(), oPartOffset.longValue(), Integer.parseInt(oPartLen.toString()));
431           oMimeBody = new MimeBodyPart JavaDoc(oRetVal);
432           oRetVal.close();
433         }
434         else if ((oFldr.getType()&DBFolder.MODE_BLOB)!=0) {
435           if (DebugFile.trace) DebugFile.writeln("new MimeBodyPart(ResultSet.getBinaryStream(...))");
436           oMimeBody = new MimeBodyPart JavaDoc(oRSet.getBinaryStream(7));
437         }
438         else {
439           BigDecimal JavaDoc oPosition;
440           Object JavaDoc oMsgNum, oLenPart, oOffset;
441           long iPosition = -1, iOffset = -1;
442           int iLenPart = -1;
443
444           oMsgNum = oRSet.getObject(1);
445           oPosition = oRSet.getBigDecimal(2);
446           if (!oRSet.wasNull()) iPosition = Long.parseLong(oPosition.toString());
447           oLenPart = oRSet.getObject(5);
448           if (!oRSet.wasNull()) iLenPart = oRSet.getInt(5);
449           oOffset = oRSet.getObject(6);
450           if (!oRSet.wasNull()) iOffset = oRSet.getInt(6);
451
452           if (iPosition!=-1) {
453             if (iLenPart==-1) throw new MessagingException JavaDoc("Part " + String.valueOf(iPartId) + " length not set at k_mime_parts table");
454             if (iOffset==-1 ) throw new MessagingException JavaDoc("Part " + String.valueOf(iPartId) + " offset not set at k_mime_parts table");
455
456             if (DebugFile.trace) DebugFile.writeln("new MboxFile("+((DBFolder)getMessage().getFolder()).getFile()+")");
457
458             MboxFile oMbox = new MboxFile(((DBFolder)getMessage().getFolder()).getFile(), MboxFile.READ_ONLY);
459
460             oMimeBody = new MimeBodyPart JavaDoc(oMbox.getPartAsStream(iPosition, iOffset, iLenPart));
461
462             oMbox.close();
463           }
464           else {
465             if (DebugFile.trace) DebugFile.decIdent();
466             throw new MessagingException JavaDoc("Part " + String.valueOf(iPartId) + " not found for message " + getMessage().getContentID());
467           }
468         } // fi (MODE_MBOX)
469
} // fi (oRset.next();
470

471       oRSet.close();
472       oRSet = null;
473       oStmt.close();
474       oStmt = null;
475     } catch (SQLException JavaDoc sqle) {
476       try { if (null!=oRSet) oRSet.close(); } catch (Exception JavaDoc ignore) {}
477       try { if (null!=oStmt) oStmt.close(); } catch (Exception JavaDoc ignore) {}
478       throw new MessagingException JavaDoc(sqle.getMessage(), sqle);
479     }
480
481     if (oMimeBody!=null) oRetVal = oMimeBody.getInputStream();
482
483     if (DebugFile.trace) {
484       DebugFile.decIdent();
485       if (null==oRetVal)
486         DebugFile.writeln("End DBMimePart.getInputStream() : null");
487       else
488         DebugFile.writeln("End DBMimePart.getInputStream() : " + oRetVal.getClass().getName());
489     }
490
491     return oRetVal;
492   } // getInputStream
493

494   // ---------------------------------------------------------------------------
495

496   public String JavaDoc getContentMD5 () throws MessagingException JavaDoc {
497     throw new UnsupportedOperationException JavaDoc("Method getContentMD5() not implemented for DBMimePart");
498   }
499
500   // ---------------------------------------------------------------------------
501

502   public int getLineCount () throws MessagingException JavaDoc {
503     throw new UnsupportedOperationException JavaDoc("Method getLineCount() not implemented for DBMimePart");
504   }
505
506   // ---------------------------------------------------------------------------
507

508   public boolean isMimeType (String JavaDoc sMimeTp) throws MessagingException JavaDoc {
509     throw new UnsupportedOperationException JavaDoc("Method isMimeType() not implemented for DBMimePart");
510   }
511
512   // ---------------------------------------------------------------------------
513

514   public String JavaDoc getContentID () { return oHeaders.getProperty("Content-ID"); }
515
516   // ---------------------------------------------------------------------------
517

518   public void setDisposition (String JavaDoc sDisposition) {
519     throw new UnsupportedOperationException JavaDoc("Method setDisposition() not implemented for DBMimePart");
520   }
521
522   // ---------------------------------------------------------------------------
523

524   public void setContentLanguage (String JavaDoc[] aLangs) {
525     throw new UnsupportedOperationException JavaDoc("Method setContentLanguage() not implemented for DBMimePart");
526   }
527
528   // ---------------------------------------------------------------------------
529

530   public String JavaDoc[] getContentLanguage () {
531     throw new UnsupportedOperationException JavaDoc("Method getContentLanguage() not implemented for DBMimePart");
532   }
533
534   // ---------------------------------------------------------------------------
535

536   public String JavaDoc getDescription () throws MessagingException JavaDoc {
537     return oHeaders.getProperty("Content-Description");
538   }
539
540   // ---------------------------------------------------------------------------
541

542   public String JavaDoc getDisposition () throws MessagingException JavaDoc {
543     return oHeaders.getProperty("Content-Disposition");
544   }
545
546   // ---------------------------------------------------------------------------
547

548   public String JavaDoc getFileName () throws MessagingException JavaDoc {
549
550     DBFolder oFldr = (DBFolder) getMessage().getFolder();
551     PreparedStatement JavaDoc oStmt = null;
552     String JavaDoc sFileName;
553
554     if (DebugFile.trace) {
555        DebugFile.writeln("Begin DBMimePart.getFileName()");
556        DebugFile.incIdent();
557        if (oFldr==null) DebugFile.writeln("Folder is null");
558        if (oMimeBody==null) DebugFile.writeln("MimeBody is null");
559     }
560
561     if (sFile!=null)
562       sFileName = sFile;
563     else if (oFldr==null && oMimeBody!=null) {
564       sFileName = oMimeBody.getFileName();
565     }
566     else if (oFldr==null) {
567       try {
568         if (getMessage().getMessageGuid()!=null) {
569           if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT " + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='"+getMessage().getMessageGuid()+"' AND " + DB.id_part + "="+String.valueOf(iPartId)+")");
570           oStmt = oFldr.getConnection().prepareStatement("SELECT " + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "=? AND " + DB.id_part + "=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
571           oStmt.setString(1, getMessage().getMessageGuid());
572         }
573         else {
574           if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(SELECT " + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.id_message + "='"+getMessage().getContentID()+"' AND " + DB.id_part + "="+String.valueOf(iPartId)+")");
575           oStmt = oFldr.getConnection().prepareStatement("SELECT " + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.id_message + "=? AND " + DB.id_part + "=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
576           oStmt.setString(1, getMessage().getContentID());
577         }
578
579         oStmt.setInt(2, iPartId);
580
581         ResultSet JavaDoc oRSet = oStmt.executeQuery();
582
583         if (oRSet.next())
584           sFileName = oRSet.getString(1);
585         else
586           sFileName = null;
587
588         oRSet.close();
589         oRSet = null;
590         oStmt.close();
591         oStmt = null;
592       }
593       catch (SQLException JavaDoc sqle) {
594         sFileName = null;
595         if (oStmt!=null) { try { oStmt.close(); } catch (Exception JavaDoc ignore) {} }
596         if (DebugFile.trace) DebugFile.decIdent();
597         throw new MessagingException JavaDoc(sqle.getMessage(), sqle);
598       }
599     }
600     else {
601       sFileName = null;
602     }
603
604     if (DebugFile.trace) {
605       DebugFile.decIdent();
606       DebugFile.writeln("End DBMimePart.getFileName() : " + sFileName);
607     }
608
609     return sFileName;
610   } // getFileName
611

612   // ---------------------------------------------------------------------------
613

614   public String JavaDoc getContentType () { return oHeaders.getProperty("Content-Type"); }
615
616   // ---------------------------------------------------------------------------
617

618   public String JavaDoc getEncoding () { return oHeaders.getProperty("Content-Transfer-Encoding"); }
619
620   // ---------------------------------------------------------------------------
621

622   public int getPartId () { return iPartId; }
623
624   // ---------------------------------------------------------------------------
625

626   public int getSize () { return iSize; }
627
628   // ---------------------------------------------------------------------------
629

630   public String JavaDoc getText ()
631     throws SQLException JavaDoc,UnsupportedEncodingException JavaDoc,MessagingException JavaDoc,IOException JavaDoc {
632
633     String JavaDoc sMsgGuid = getMessage().getMessageGuid();
634     JDCConnection oConn = ((DBFolder)getMessage().getFolder()).getConnection();
635     String JavaDoc sText = null;
636
637     if (DebugFile.trace) {
638       DebugFile.writeln("Begin DBMimePart.getText()");
639       DebugFile.incIdent();
640       DebugFile.writeln("Connection.prepareStatement(SELECT "+DB.id_message+","+DBBind.Functions.ISNULL+"(len_part,0),id_encoding,by_content FROM "+ DB.k_mime_parts + " WHERE (" + DB.gu_mimemsg + "='"+sMsgGuid+"') AND id_part='"+String.valueOf(iPartId)+")");
641     }
642
643     PreparedStatement JavaDoc oStmt = oConn.prepareStatement("SELECT "+DB.id_message+","+DBBind.Functions.ISNULL+"(len_part,0),id_encoding,by_content FROM "+ DB.k_mime_parts + " WHERE (" + DB.gu_mimemsg + "=?) AND id_part=?",
644                                                      ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
645
646     oStmt.setString(1, sMsgGuid);
647     oStmt.setInt(2, iPartId);
648
649     ResultSet JavaDoc oRSet = oStmt.executeQuery();
650
651     if (oRSet.next()) {
652
653       oMimeBody = new MimeBodyPart JavaDoc (oRSet.getBinaryStream(4));
654
655       oRSet.close();
656       oStmt.close();
657
658       StringBuffer JavaDoc oText = new StringBuffer JavaDoc();
659
660       parseMimePart (oText, null, getMessage().getFolder().getName(),
661                      getMessage().getMessageID()!=null ? getMessage().getMessageID() : getMessage().getContentID(),
662                      oMimeBody, iPartId);
663
664       sText = oText.toString();
665     }
666     else {
667       oRSet.close();
668       oStmt.close();
669     }
670
671     if (DebugFile.trace) {
672       DebugFile.decIdent();
673       DebugFile.writeln("End DBMimePart.getText()");
674     }
675
676     return sText;
677   }
678
679   // ---------------------------------------------------------------------------
680

681   public void setDataHandler (DataHandler JavaDoc oDataHndlr) {
682     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setDataHandler() for them");
683   }
684
685   // ---------------------------------------------------------------------------
686

687   public void setText (String JavaDoc sTxt) {
688     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setText() for them");
689   }
690
691   // ---------------------------------------------------------------------------
692

693   public void setText (String JavaDoc sTxt, String JavaDoc sEncoding) {
694     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setText() for them");
695   }
696
697   // ---------------------------------------------------------------------------
698

699   public void setText (String JavaDoc sTxt, String JavaDoc sEncoding, String JavaDoc sStr) {
700     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setText() for them");
701   }
702
703   // ---------------------------------------------------------------------------
704

705   public void setContentMD5 (String JavaDoc sMD5) {
706     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setContentMD5() for them");
707   }
708
709   // ---------------------------------------------------------------------------
710

711   public void setContent (Object JavaDoc oObj) {
712     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setContent() for them");
713   }
714
715   // ---------------------------------------------------------------------------
716

717   public void setContent (Object JavaDoc oObj, String JavaDoc s) {
718     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setContent() for them");
719   }
720
721   // ---------------------------------------------------------------------------
722

723   public void setContent (Multipart JavaDoc oPart) {
724     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setContent() for them");
725   }
726
727   // ---------------------------------------------------------------------------
728

729   public void setFileName (String JavaDoc sName) {
730     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setFileName() for them");
731   }
732
733   // ---------------------------------------------------------------------------
734

735   public void setDescription (String JavaDoc sDesc) {
736     throw new UnsupportedOperationException JavaDoc("DBMimePart objects are read-only. Cannot setDescription() for them");
737   }
738
739   // ---------------------------------------------------------------------------
740

741   public void setContentId (String JavaDoc sId) { oHeaders.setProperty("Content-ID", sId); }
742
743   // --------------------------------------------------------------------------
744

745   public void setEncoding (String JavaDoc sEncoding) { oHeaders.setProperty("Content-Transfer-Encoding", sEncoding); }
746
747   // --------------------------------------------------------------------------
748

749   public void setPartId (int iId) { iPartId = iId; }
750
751   // --------------------------------------------------------------------------
752

753   public void setSize (int nBytes) { iSize = nBytes; }
754
755   // --------------------------------------------------------------------------
756

757   public static String JavaDoc textToHtml(String JavaDoc sText) {
758
759     try {
760       sText = Gadgets.replace(sText, "(http|https):\\/\\/(\\S*)",
761                               "<a HREF=\"$1://$2\" target=\"_blank\">$1://$2</a>",
762                                Perl5Compiler.CASE_INSENSITIVE_MASK);
763     }
764     catch (Exception JavaDoc ignore) { }
765
766     final int iLen = sText.length();
767     StringBuffer JavaDoc oHtml = new StringBuffer JavaDoc(iLen+1000);
768     char cAt;
769
770     for (int i=0; i<iLen; i++) {
771       cAt = sText.charAt(i);
772
773       switch (cAt) {
774         case 10:
775           oHtml.append("<BR>");
776           break;
777         case 13:
778           break;
779         default:
780           oHtml.append(cAt);
781       }
782     }
783
784     return oHtml.toString();
785   } // textToHtml
786

787   // ---------------------------------------------------------------------------
788

789   public static MimePart JavaDoc getMessagePart (MimePart JavaDoc oPart, int nPart)
790     throws MessagingException JavaDoc, IOException JavaDoc, UnsupportedEncodingException JavaDoc {
791
792     MimeBodyPart JavaDoc oNext = null;
793     MimeMultipart JavaDoc oAlt;
794     String JavaDoc sType;
795     MimePart JavaDoc oRetVal;
796
797     sType = oPart.getContentType().toUpperCase();
798
799     if (DebugFile.trace) DebugFile.writeln("Begin DBMimePart.getMessagePart("+String.valueOf(nPart)+", "+sType.replace('\n',' ').replace('\r',' ')+")");
800
801     if (sType.startsWith("MESSAGE/RFC822")) {
802       DBMimeMessage oAttachment = new DBMimeMessage((MimeMessage JavaDoc) oPart.getContent());
803       oRetVal = oAttachment.getBody ();
804     }
805     else if (sType.startsWith("MULTIPART/ALTERNATIVE") || sType.startsWith("MULTIPART/RELATED") || sType.startsWith("MULTIPART/SIGNED")) {
806       oAlt = (MimeMultipart JavaDoc) oPart.getContent();
807
808       int iAlt = 0;
809       String JavaDoc[] aPreferred = {"TEXT/HTML","TEXT"};
810       boolean bFound = false;
811
812       while (iAlt<aPreferred.length && !bFound) {
813         for (int q=0; q<oAlt.getCount(); q++) {
814           oNext = (MimeBodyPart JavaDoc) oAlt.getBodyPart(q);
815           if (DebugFile.trace && (iAlt==0)) DebugFile.writeln(" " + oNext.getContentType().toUpperCase().replace('\n',' ').replace('\r',' ') + " ID=" + oNext.getContentID());
816           bFound = oNext.getContentType().toUpperCase().startsWith(aPreferred[iAlt]);
817           if (bFound) break;
818         } // next
819
iAlt++;
820       } // wend
821

822       if (bFound)
823         oRetVal = getMessagePart (oNext, -1);
824       else
825         oRetVal = getMessagePart ((MimeBodyPart JavaDoc) oAlt.getBodyPart(0), -1);
826     }
827     else {
828       oRetVal = oPart;
829     }
830
831     if (DebugFile.trace) DebugFile.writeln("End DBMimePart.getMessagePart() : " + oRetVal.getContentType().replace('\n',' ').replace('\r',' '));
832
833     return oRetVal;
834   } // getMessagePart
835

836   // --------------------------------------------------------------------------
837

838   public static int parseMimePart (StringBuffer JavaDoc oStrBuff, LinkedList JavaDoc oAttachments,
839                                    String JavaDoc sFolder, String JavaDoc sMsgId,
840                                    MimePart JavaDoc oPart, int nPart)
841     throws MessagingException JavaDoc, IOException JavaDoc, UnsupportedEncodingException JavaDoc {
842
843     MimeBodyPart JavaDoc oNext = null;
844     MimeMultipart JavaDoc oAlt;
845     String JavaDoc sType;
846     int iRetVal;
847     String JavaDoc sContent;
848
849     sType = oPart.getContentType().toUpperCase();
850
851     if (DebugFile.trace) {
852       DebugFile.writeln("Begin DBMimePart.parseMimePart(" + sMsgId + "," +String.valueOf(nPart) + "," + sType.replace('\n',' ').replace('\r',' ') + ")");
853       DebugFile.incIdent();
854     }
855
856     oPart = getMessagePart(oPart, nPart);
857     sType = oPart.getContentType().toUpperCase();
858
859     if (DebugFile.trace) DebugFile.writeln("body type = " + sType);
860
861     if (sType.startsWith("TEXT/PLAIN")) {
862       sContent = (String JavaDoc) oPart.getContent(); if (null==sContent) sContent="";
863
864       boolean bHtml = false;
865       int iLT = 0, iLen = sContent.length();
866       for (int p=0; p<iLen; p++) {
867         char cAt = sContent.charAt(p);
868         if (cAt=='<') {
869           if (cAt<iLen-6) {
870             bHtml = sContent.substring(p+1, p+5).equalsIgnoreCase("HTML");
871           }
872           break;
873         } // fi (<)
874
} // next (p)
875

876       if (bHtml)
877         oStrBuff.append (sContent);
878       else
879         oStrBuff.append (textToHtml(sContent));
880
881       iRetVal = nPart;
882     }
883     else if (sType.startsWith("TEXT/HTML")) {
884
885       sContent = (String JavaDoc) oPart.getContent(); if (null==sContent) sContent="";
886
887       try {
888         StringBuffer JavaDoc sMsgIdEsc = new StringBuffer JavaDoc(sMsgId.length()+10);
889         final int iMsgLen = sMsgId.length();
890         for (int i=0; i<iMsgLen; i++) {
891           char c = sMsgId.charAt(i);
892           if (c=='$')
893             sMsgIdEsc.append("\\");
894           sMsgIdEsc.append(c);
895         }
896
897         if (sFolder!=null) {
898         // Replace image cid: with relative references to msg_part.jsp
899
sContent = Gadgets.replace(sContent, "src\\s*=\\s*(\"|')cid:(.*?)(\"|')",
900                                    "src=\"msg_part.jsp\\?folder="+sFolder+"&msgid="+sMsgIdEsc+
901                                    "&cid=$2\"",
902                                    Perl5Compiler.CASE_INSENSITIVE_MASK);
903
904         // Set all anchor targets to _blank
905
sContent = Gadgets.replace(sContent, "<a\\s*href=(.*?)\\s*target\\s*=\\s*(\"|')?(\\w*)(\"|')?",
906                                    "<a HREF=$1 target=\"_blank\"",
907                                    Perl5Compiler.CASE_INSENSITIVE_MASK);
908         }
909       }
910       catch (MalformedPatternException neverthrown) { }
911
912       oStrBuff.append (sContent);
913
914       iRetVal = nPart;
915     }
916     else if (sType.startsWith("APPLICATION/")) {
917
918       if ((nPart!=-1) && (null!=oAttachments)) {
919         Properties JavaDoc oAttachment = new Properties JavaDoc();
920         String JavaDoc sFile_Name = oPart.getFileName();
921         if (null!=oPart.getContentID()) oAttachment.setProperty("Content-Id", oPart.getContentID());
922         oAttachment.setProperty("Part-Number", String.valueOf(nPart));
923         oAttachment.setProperty("Part-Number", String.valueOf(nPart));
924         oAttachment.setProperty("File-Name", sFile_Name==null ? "file"+String.valueOf(nPart) : sFile_Name);
925
926         if (DebugFile.trace) DebugFile.writeln("size = " + String.valueOf(oPart.getSize()));
927
928         if (oPart.getSize()>1048576) {
929           oAttachment.setProperty("File-Length", String.valueOf(oPart.getSize()/1048576) + "Mb");
930         } else if (oPart.getSize()>1024) {
931           oAttachment.setProperty("File-Length", String.valueOf(oPart.getSize()/1024) + "Kb");
932         } else {
933           oAttachment.setProperty("File-Length", String.valueOf(oPart.getSize())+"bytes");
934         }
935
936         oAttachments.addLast(oAttachment);
937       } // fi (nPart!=-1 && null!=oAttachments)
938
iRetVal = -1;
939     }
940     else {
941       oStrBuff.append ("Type: " + sType);
942       oStrBuff.append ("&nbsp;&nbsp;");
943       oStrBuff.append ("Id:" + oPart.getContentID());
944       oStrBuff.append ("&nbsp;&nbsp;");
945       oStrBuff.append ("File:" + oPart.getFileName());
946       oStrBuff.append ("&nbsp;&nbsp;");
947       oStrBuff.append ("Desc:" + oPart.getDescription());
948       oStrBuff.append ("<BR/>");
949       iRetVal = -1;
950     }
951
952     if (DebugFile.trace) {
953       DebugFile.decIdent();
954       DebugFile.writeln("End MimePartDB.parseMimePart() : " + String.valueOf(iRetVal));
955     }
956
957     return iRetVal;
958   } // parseMimePart
959

960   // ---------------------------------------------------------------------------
961

962   public static String JavaDoc getMimeType(JDCConnection oConn, String JavaDoc sFileName) throws SQLException JavaDoc {
963     String JavaDoc sMimeType;
964
965     if (null==sFileName) return null;
966
967     int iDot = sFileName.lastIndexOf('.');
968
969     if (iDot<0 || iDot==sFileName.length()-1) return "application/octec-stream";
970
971     String JavaDoc sFileExtension = sFileName.substring(++iDot).toUpperCase();
972
973     PreparedStatement JavaDoc oStmt = oConn.prepareStatement("SELECT "+DB.mime_type+" FROM "+DB.k_lu_prod_types+" WHERE "+DB.id_prod_type+"=?",
974                                                      ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
975     oStmt.setString(1, sFileExtension);
976
977     ResultSet JavaDoc oRSet = oStmt.executeQuery();
978
979     if (oRSet.next())
980       sMimeType = oRSet.getString(1);
981     else
982       sMimeType = null;
983
984     oRSet.close();
985     oStmt.close();
986
987     return (sMimeType==null ? "application/octec-stream" : sMimeType);
988   } // getMimeType
989

990   // ---------------------------------------------------------------------------
991

992   public void writeTo (OutputStream JavaDoc oOutStrm)
993       throws IOException JavaDoc, MessagingException JavaDoc {
994   }
995 }
996
Popular Tags