KickJava   Java API By Example, From Geeks To Geeks.

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


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.dataobjs.DBSubset;
39 import com.knowgate.jdc.JDCConnection;
40 import com.knowgate.misc.Gadgets;
41 import com.knowgate.misc.MD5;
42 import com.knowgate.dfs.StreamPipe;
43 import com.knowgate.dfs.ByteArrayDataSource;
44
45 import java.io.File JavaDoc;
46 import java.io.StringBufferInputStream JavaDoc;
47 import java.io.IOException JavaDoc;
48 import java.io.InputStream JavaDoc;
49 import java.io.OutputStream JavaDoc;
50 import java.io.ByteArrayInputStream JavaDoc;
51 import java.io.ByteArrayOutputStream JavaDoc;
52 import java.io.UnsupportedEncodingException JavaDoc;
53
54 import java.math.BigDecimal JavaDoc;
55
56 import java.sql.Blob JavaDoc;
57 import java.sql.ResultSet JavaDoc;
58 import java.sql.CallableStatement JavaDoc;
59 import java.sql.PreparedStatement JavaDoc;
60 import java.sql.Statement JavaDoc;
61 import java.sql.SQLException JavaDoc;
62 import java.sql.Timestamp JavaDoc;
63 import java.sql.Types JavaDoc;
64
65 import java.util.Date JavaDoc;
66 import java.util.Properties JavaDoc;
67 import java.util.Enumeration JavaDoc;
68 import java.util.LinkedList JavaDoc;
69 import java.util.HashMap JavaDoc;
70 import java.util.Iterator JavaDoc;
71
72 import java.math.BigDecimal JavaDoc;
73
74 import java.text.SimpleDateFormat JavaDoc;
75
76 import java.net.URL JavaDoc;
77
78 import javax.activation.DataHandler JavaDoc;
79 import javax.activation.FileDataSource JavaDoc;
80
81 import javax.mail.BodyPart JavaDoc;
82 import javax.mail.Address JavaDoc;
83 import javax.mail.Part JavaDoc;
84 import javax.mail.Message JavaDoc;
85 import javax.mail.Flags JavaDoc;
86 import javax.mail.Folder JavaDoc;
87 import javax.mail.Multipart JavaDoc;
88 import javax.mail.Session JavaDoc;
89 import javax.mail.internet.AddressException JavaDoc;
90 import javax.mail.internet.InternetAddress JavaDoc;
91 import javax.mail.internet.MimeMessage JavaDoc;
92 import javax.mail.internet.MimeBodyPart JavaDoc;
93 import javax.mail.internet.InternetAddress JavaDoc;
94 import javax.mail.internet.ParseException JavaDoc;
95 import javax.mail.internet.MimePart JavaDoc;
96 import javax.mail.internet.MimeMultipart JavaDoc;
97 import javax.mail.MessagingException JavaDoc;
98 import javax.mail.FolderClosedException JavaDoc;
99
100 import com.sun.mail.smtp.SMTPMessage;
101
102 import org.htmlparser.Parser;
103 import org.htmlparser.util.NodeList;
104 import org.htmlparser.util.NodeIterator;
105 import org.htmlparser.util.ParserException;
106 import org.htmlparser.tags.ImageTag;
107 import org.htmlparser.beans.StringBean;
108 import org.htmlparser.filters.TagNameFilter;
109
110 import org.apache.oro.text.regex.Pattern;
111 import org.apache.oro.text.regex.PatternMatcher;
112 import org.apache.oro.text.regex.PatternCompiler;
113 import org.apache.oro.text.regex.StringSubstitution;
114 import org.apache.oro.text.regex.Perl5Matcher;
115 import org.apache.oro.text.regex.Perl5Compiler;
116 import org.apache.oro.text.regex.MalformedPatternException;
117 import org.apache.oro.text.regex.Util;
118
119 import javax.mail.internet.MimeUtility JavaDoc;
120
121 /**
122  * MIME messages stored at database BLOB columns or MBOX files
123  * @author Sergio Montoro Ten
124  * @version 2.2
125  */

126
127 public class DBMimeMessage extends MimeMessage JavaDoc implements MimePart JavaDoc,Part JavaDoc {
128
129   private String JavaDoc sGuid;
130   private Folder JavaDoc oFolder;
131   private Address JavaDoc[] aAddrs;
132   private HashMap JavaDoc oHeaders;
133
134   private static PatternMatcher oMatcher = new Perl5Matcher();
135   private static PatternCompiler oCompiler = new Perl5Compiler();
136
137   /**
138    * Create an empty message
139    * @param oMailSession
140    */

141
142   public DBMimeMessage(Session JavaDoc oMailSession) {
143     super(oMailSession);
144     sGuid = null;
145     oFolder = null;
146     oHeaders = null;
147   }
148
149   /**
150    * Create DBMimeMessage from a MimeMessage and assign a new GUID
151    * @param oMsg MimeMessage
152    * @throws MessagingException
153    */

154   public DBMimeMessage(MimeMessage JavaDoc oMsg)
155     throws MessagingException JavaDoc {
156     super(oMsg);
157     sGuid = Gadgets.generateUUID();
158     oHeaders = null;
159   }
160
161   /**
162    * Create DBMimeMessage from an InputStream and assign a new GUID
163    * @param oMailSession Session
164    * @param oInStrm InputStream
165    * @throws MessagingException
166    */

167   public DBMimeMessage(Session JavaDoc oMailSession, InputStream JavaDoc oInStrm)
168     throws MessagingException JavaDoc {
169     super(oMailSession, oInStrm);
170     sGuid = Gadgets.generateUUID();
171     oHeaders = null;
172   }
173
174   /**
175    * Create DBMimeMessage from an InputStream, set folder and assign a new GUID
176    * @param Folder oFldr
177    * @param oInStrm InputStream
178    * @throws MessagingException
179    */

180   public DBMimeMessage(Folder JavaDoc oFldr, InputStream JavaDoc oInStrm)
181     throws MessagingException JavaDoc,ClassCastException JavaDoc {
182     super(((DBStore)oFldr.getStore()).getSession(), oInStrm);
183     setFolder(oFldr);
184     sGuid = Gadgets.generateUUID();
185     oHeaders = null;
186   }
187
188   /**
189    * Create DBMimeMessage from a MimeMessage, set folder and assign a new GUID
190    * @param oFldr Folder
191    * @param MimeMessage oMsg
192    * @throws MessagingException
193    */

194   public DBMimeMessage(Folder JavaDoc oFldr, MimeMessage JavaDoc oMsg)
195     throws MessagingException JavaDoc {
196     super(oMsg);
197     setFolder(oFldr);
198     sGuid = Gadgets.generateUUID();
199     oHeaders = null;
200   }
201
202   /**
203    * <p>Create DBMimeMessage from another DBMimeMessage</p>
204    * GUID of this message is set to be the same as that of oMsg
205    * @param oFldr Folder
206    * @param MimeMessage oMsg
207    * @throws MessagingException
208    */

209   public DBMimeMessage(Folder JavaDoc oFldr, DBMimeMessage oMsg)
210     throws MessagingException JavaDoc {
211     super(oMsg);
212     setFolder(oFldr);
213     sGuid = oMsg.getMessageGuid();
214     oHeaders = null;
215   }
216
217   /**
218    * Create empty message at the given folder
219    * @param oFldr Folder
220    * @param sMsgGuid String Message GUID
221    * @throws MessagingException
222    */

223   public DBMimeMessage (Folder JavaDoc oFldr, String JavaDoc sMsgGuid)
224     throws MessagingException JavaDoc {
225     super(((DBStore)oFldr.getStore()).getSession());
226     sGuid = sMsgGuid;
227     setFolder(oFldr);
228     oHeaders = null;
229   }
230
231   // ---------------------------------------------------------------------------
232

233   /**
234    * Get message folder
235    * @return Folder
236    */

237   public Folder JavaDoc getFolder() {
238     if (oFolder==null)
239       return super.getFolder();
240     else
241       return oFolder;
242   }
243
244   // ---------------------------------------------------------------------------
245

246   /**
247    * Set message folder
248    * @param oFldr Folder
249    */

250   public void setFolder(Folder JavaDoc oFldr) {
251     oFolder = oFldr;
252   }
253
254   // ---------------------------------------------------------------------------
255

256   /**
257    * <p>Get message GUID</p>
258    * If message had no previous GUID then a new one is assigned
259    * @return String
260    */

261   public String JavaDoc getMessageGuid() {
262     if (DebugFile.trace) {
263       DebugFile.writeln("Begin DBMimeMessage.getMessageGuid()");
264       DebugFile.incIdent();
265     }
266
267     if (null==sGuid) {
268       if (DebugFile.trace) DebugFile.writeln("previous message GUID is null, assigning a new one");
269       sGuid = Gadgets.generateUUID();
270     }
271
272     if (DebugFile.trace) {
273       DebugFile.decIdent();
274       DebugFile.writeln("End DBMimeMessage.getMessageGuid() : "+sGuid);
275     }
276     return sGuid;
277   }
278
279   // ---------------------------------------------------------------------------
280

281   /**
282    * Set message GUID
283    * @param sId String
284    */

285   public void setMessageGuid(String JavaDoc sId) {
286     sGuid = sId;
287   }
288   // ---------------------------------------------------------------------------
289

290   /**
291    * <p>Get message flags</p>
292    * Message flags are readed from k_mime_msgs table at the database
293    * @return Flags
294    * @throws MessagingException
295    */

296   public Flags JavaDoc getFlags() throws MessagingException JavaDoc {
297     Object JavaDoc oFlag;
298
299     if (oFolder==null)
300       return super.getFlags();
301     else {
302       Flags JavaDoc oRetVal = null;
303       Statement JavaDoc oStmt = null;
304       ResultSet JavaDoc oRSet = null;
305       try {
306         Flags.Flag JavaDoc[] aFlags = new Flags.Flag JavaDoc[]{Flags.Flag.RECENT, Flags.Flag.ANSWERED, Flags.Flag.DELETED, Flags.Flag.DRAFT, Flags.Flag.FLAGGED, Flags.Flag.SEEN};
307         oStmt = ( (DBFolder) oFolder).getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
308         oRSet = oStmt.executeQuery("SELECT "+DB.bo_recent+","+DB.bo_answered+","+DB.bo_deleted+","+DB.bo_draft+","+DB.bo_flagged+","+DB.bo_recent+","+DB.bo_seen+" FROM "+DB.k_mime_msgs+" WHERE "+DB.gu_mimemsg+"='"+getMessageGuid()+"'");
309         if (oRSet.next()) {
310           oRetVal = new Flags JavaDoc();
311           for (int f=1; f<=6; f++) {
312             oFlag = oRSet.getObject(f);
313             if (!oRSet.wasNull()) {
314               if (oFlag.getClass().equals(Short.TYPE)) {
315                 if (((Short JavaDoc) oFlag).shortValue()==(short)1)
316                   oRetVal.add(aFlags[f-1]);
317               }
318               else {
319                 if (Integer.parseInt(oFlag.toString())!=0)
320                   oRetVal.add(aFlags[f-1]);
321               }
322             }
323           } // next (f)
324
}
325         oRSet.close();
326         oRSet = null;
327         oStmt.close();
328         oStmt = null;
329         return oRetVal;
330       }
331       catch (SQLException JavaDoc sqle) {
332         if (oStmt!=null) { try { oStmt.close(); } catch (Exception JavaDoc ignore) {} }
333         if (oRSet!=null) { try { oRSet.close(); } catch (Exception JavaDoc ignore) {} }
334       }
335     }
336     return null;
337   } // getFlags
338

339   // ---------------------------------------------------------------------------
340

341   /**
342    * <p>Get message recipients</p>
343    * This method read recipients from a message stored at k_inet_addrs table
344    * or if message is not already stored at k_inet_addrs then it delegates
345    * behaviour to parent class MimMessage.getAllRecipients()
346    * @return If this message is stored at the database then this method returns
347    * an array of DBInetAddr objects. If this message has not been stored yet then
348    * this method returns an array of javax.mail.internet.InternetAddress objects
349    * @throws MessagingException
350    * @throws NullPointerException
351    * @throws IllegalArgumentException
352    */

353   public Address JavaDoc[] getAllRecipients()
354     throws MessagingException JavaDoc, NullPointerException JavaDoc, IllegalArgumentException JavaDoc {
355     DBSubset oAddrs;
356     int iAddrs;
357
358     if (DebugFile.trace) {
359       DebugFile.writeln("Begin DBMimeMessage.getAllRecipients()");
360       DebugFile.incIdent();
361     }
362
363     if (oFolder==null) {
364       if (DebugFile.trace) {
365         DebugFile.writeln("Message is not stored at any Folder or Folder is closed");
366         DebugFile.decIdent();
367       }
368       return super.getAllRecipients();
369     }
370     else {
371       if (oFolder.getClass().getName().equals("com.knowgate.hipermail.DBFolder")) {
372
373         if (((DBFolder)oFolder).getConnection()==null) {
374           if (DebugFile.trace) DebugFile.decIdent();
375           throw new MessagingException JavaDoc("DBMimeMessage.getAllRecipients() not connected to the database");
376         }
377
378         oAddrs = new DBSubset(DB.k_inet_addrs,
379                               DB.gu_mimemsg + "," + DB.id_message + "," +
380                               DB.tx_email + "," + DB.tx_personal + "," +
381                               DB.tp_recipient + "," + DB.gu_user + "," +
382                               DB.gu_contact + "," + DB.gu_company,
383                               DB.gu_mimemsg + "=?", 10);
384         try {
385           iAddrs = oAddrs.load(((DBFolder)oFolder).getConnection(), new Object JavaDoc[]{sGuid});
386         } catch (SQLException JavaDoc sqle) {
387           if (DebugFile.trace) DebugFile.decIdent();
388           throw new MessagingException JavaDoc(sqle.getMessage(), sqle);
389         }
390
391         if (iAddrs>0) {
392           aAddrs = new DBInetAddr[iAddrs];
393           for (int a = 0; a < iAddrs; a++) {
394             aAddrs[a] = new DBInetAddr(oAddrs.getString(0,a), // gu_mimemsg
395
oAddrs.getString(1,a), // id_message
396
oAddrs.getString(2,a), // tx_email
397
oAddrs.getStringNull(3,a,null), // tx_personal
398
oAddrs.getString(4,a), // tp_recipient
399
oAddrs.getStringNull(5,a,null), // gu_user
400
oAddrs.getStringNull(6,a,null), // gu_contact
401
oAddrs.getStringNull(7,a,null)); // gu_company
402
} // next
403
} // fi (iAddrs)
404
else {
405           aAddrs = null;
406         }
407       } // fi (oFolder.getClass() == com.knowgate.hipergate.DBFolder)
408
else {
409         DebugFile.writeln("message Folder type is " + oFolder.getClass().getName());
410         if (DebugFile.trace) DebugFile.decIdent();
411         aAddrs = super.getAllRecipients();
412       } // fi(oFolder instanceof DBFolder)
413
} // fi (oFolder)
414

415     if (DebugFile.trace) {
416       DebugFile.decIdent();
417       DebugFile.writeln("End DBMimeMessage.getAllRecipients()");
418     }
419
420     return aAddrs;
421   } // getAllRecipients
422

423   // ---------------------------------------------------------------------------
424

425   /**
426    * <p>Get recipients of a particular type</p>
427    * This method first calls getAllRecipients() and then filters retrieved recipients by their type.
428    * @param cTpRecipient javax.mail.Message.RecipientType
429    * @return Address[]
430    * @throws MessagingException
431    */

432   public Address JavaDoc[] getRecipients(Message.RecipientType JavaDoc cTpRecipient)
433     throws MessagingException JavaDoc {
434     int a;
435     int iRecipients = 0;
436     DBInetAddr[] aRecipients = null;
437     DBInetAddr oAdr;
438
439     if (oFolder==null) {
440       return super.getRecipients(cTpRecipient);
441     }
442
443     if (aAddrs==null) getAllRecipients();
444
445     if (aAddrs!=null) {
446         for (a=0; a<aAddrs.length; a++) {
447           oAdr = ((DBInetAddr) aAddrs[a]);
448           if ((oAdr.getStringNull(DB.tp_recipient, "").equalsIgnoreCase("to") && Message.RecipientType.TO.equals(cTpRecipient))
449             ||(oAdr.getStringNull(DB.tp_recipient, "").equalsIgnoreCase("cc") && Message.RecipientType.CC.equals(cTpRecipient))
450             ||(oAdr.getStringNull(DB.tp_recipient, "").equalsIgnoreCase("bcc") && Message.RecipientType.BCC.equals(cTpRecipient)))
451
452             iRecipients++;
453         } // next
454

455         aRecipients = new DBInetAddr[iRecipients];
456
457         int iRecipient = 0;
458
459         for (a=0; a<aAddrs.length; a++) {
460           oAdr = ((DBInetAddr)aAddrs[a]);
461           if ((oAdr.getStringNull(DB.tp_recipient, "").equalsIgnoreCase("to") && Message.RecipientType.TO.equals(cTpRecipient))
462             ||(oAdr.getStringNull(DB.tp_recipient, "").equalsIgnoreCase("cc") && Message.RecipientType.CC.equals(cTpRecipient))
463             ||(oAdr.getStringNull(DB.tp_recipient, "").equalsIgnoreCase("bcc") && Message.RecipientType.BCC.equals(cTpRecipient)))
464
465             aRecipients[iRecipient++] = (DBInetAddr) aAddrs[a];
466         } // next
467
}
468
469     return aRecipients;
470   } // getRecipients
471

472   // ---------------------------------------------------------------------------
473

474   public DBInetAddr getFromRecipient()
475     throws MessagingException JavaDoc {
476
477     DBInetAddr oFrom = null;
478
479     if (aAddrs==null) getAllRecipients();
480
481     if (aAddrs!=null) {
482       for (int a=0; a<aAddrs.length && oFrom==null; a++) {
483
484         if (((DBInetAddr)(aAddrs[a])).getStringNull(DB.tp_recipient, "").equals("from"))
485           oFrom = (DBInetAddr) (aAddrs[a]);
486       } // next
487

488     } // fi
489

490     return oFrom;
491   } // getFrom
492

493   // ---------------------------------------------------------------------------
494

495   private void cacheHeaders()
496     throws SQLException JavaDoc {
497
498     if (DebugFile.trace) {
499       DebugFile.writeln("Begin DBMimeMessage.cacheHeaders()");
500       DebugFile.incIdent();
501     }
502
503     PreparedStatement JavaDoc oStmt = null;
504     ResultSet JavaDoc oRSet = null;
505
506         oStmt = ((DBFolder) oFolder).getConnection().prepareStatement( "SELECT "+
507           DB.id_type+","+DB.tx_subject+","+DB.id_message+","+
508           DB.len_mimemsg+","+DB.tx_md5+","+DB.de_mimemsg+","+DB.tx_encoding+","+
509           DB.dt_sent+","+DB.dt_received+","+DB.dt_readed+","+
510           DB.bo_spam+","+DB.id_compression+","+DB.id_priority+
511           " FROM "+DB.k_mime_msgs+" WHERE "+DB.gu_mimemsg+"=?",
512           ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
513         oStmt.setString(1, getMessageGuid());
514         oRSet = oStmt.executeQuery();
515
516         if (oRSet.next()) {
517           oHeaders = new HashMap JavaDoc (23);
518           oHeaders.put("Content-Type", oRSet.getString(1));
519           oHeaders.put("Subject", oRSet.getString(2));
520           oHeaders.put("Message-ID", oRSet.getString(3));
521           oHeaders.put("Date", oRSet.getDate(8));
522           oHeaders.put("Date-Received", oRSet.getDate(9));
523           oHeaders.put("Date-Readed", oRSet.getDate(10));
524           oHeaders.put("X-Spam-Flag", oRSet.getObject(11));
525           oHeaders.put("Compression", oRSet.getString(12));
526           oHeaders.put("X-Priority", oRSet.getString(13));
527         }
528         oRSet.close();
529         oStmt.close();
530
531     if (DebugFile.trace) {
532       DebugFile.decIdent();
533       DebugFile.writeln("End DBMimeMessage.cacheHeaders()");
534     }
535   }
536
537   // ---------------------------------------------------------------------------
538

539   public String JavaDoc getContentType()
540     throws MessagingException JavaDoc {
541
542     if (DebugFile.trace) {
543       DebugFile.writeln("Begin DBMimeMessage.getContentType()");
544       DebugFile.incIdent();
545     }
546
547     String JavaDoc sRetVal;
548
549     if (oFolder==null) {
550       if (DebugFile.trace) {
551         DebugFile.writeln("Message is not stored at any Folder or Folder is closed");
552       }
553       sRetVal = super.getContentType();
554     }
555     else {
556       try {
557         if (null==oHeaders) cacheHeaders();
558         if (null==oHeaders)
559           sRetVal = super.getContentType();
560         else
561           sRetVal = (String JavaDoc) oHeaders.get("Content-Type");
562       }
563       catch (SQLException JavaDoc sqle) {
564         throw new MessagingException JavaDoc (sqle.getMessage(), sqle);
565       }
566     }
567
568     if (DebugFile.trace) {
569       DebugFile.decIdent();
570       DebugFile.writeln("End DBMimeMessage.getContentType() : " + sRetVal);
571     }
572     return sRetVal;
573   }
574
575   // ---------------------------------------------------------------------------
576

577   public Date JavaDoc getSentDate()
578     throws MessagingException JavaDoc {
579
580     if (DebugFile.trace) {
581       DebugFile.writeln("Begin DBMimeMessage.getSentDate()");
582       DebugFile.incIdent();
583     }
584
585     Date JavaDoc dtRetVal;
586
587     if (oFolder==null) {
588       if (DebugFile.trace) {
589         DebugFile.writeln("Message is not stored at any Folder or Folder is closed");
590       }
591       dtRetVal = super.getSentDate();
592     }
593     else {
594       try {
595         if (null==oHeaders) cacheHeaders();
596         if (null==oHeaders)
597           dtRetVal = super.getSentDate();
598         else
599           dtRetVal = (java.util.Date JavaDoc) oHeaders.get("Date");
600       }
601       catch (SQLException JavaDoc sqle) {
602         throw new MessagingException JavaDoc (sqle.getMessage(), sqle);
603       }
604     }
605
606     if (DebugFile.trace) {
607       DebugFile.decIdent();
608       if (dtRetVal==null)
609         DebugFile.writeln("End DBMimeMessage.getSentDate() : null");
610       else
611         DebugFile.writeln("End DBMimeMessage.getSentDate() : " + dtRetVal.toString());
612     }
613     return dtRetVal;
614   }
615
616   // ---------------------------------------------------------------------------
617

618   public String JavaDoc getSubject()
619     throws MessagingException JavaDoc {
620
621     if (DebugFile.trace) {
622       DebugFile.writeln("Begin DBMimeMessage.getSubject()");
623       DebugFile.incIdent();
624     }
625
626     String JavaDoc sRetVal;
627
628     if (oFolder==null) {
629       if (DebugFile.trace) {
630         DebugFile.writeln("Message is not stored at any Folder or Folder is closed");
631       }
632       sRetVal = super.getSubject();
633     }
634     else {
635       try {
636         if (null==oHeaders) cacheHeaders();
637         if (null==oHeaders)
638           sRetVal = super.getSubject();
639         else
640           sRetVal = (String JavaDoc) oHeaders.get("Subject");
641       }
642       catch (SQLException JavaDoc sqle) {
643         throw new MessagingException JavaDoc (sqle.getMessage(), sqle);
644       }
645     }
646
647     if (DebugFile.trace) {
648       DebugFile.decIdent();
649       DebugFile.writeln("End DBMimeMessage.getSubject() : " + sRetVal);
650     }
651     return sRetVal;
652   }
653
654   // ---------------------------------------------------------------------------
655

656   public MimePart JavaDoc getMessageBody ()
657     throws ParseException JavaDoc, MessagingException JavaDoc, IOException JavaDoc {
658
659     MimePart JavaDoc oRetVal = null;
660
661     if (DebugFile.trace) {
662       DebugFile.writeln("Begin DBMimeMessage.getMessageBody([MimeMessage])");
663       DebugFile.incIdent();
664     }
665
666      Object JavaDoc oContent = getContent();
667
668      if (DebugFile.trace) {
669        if (null==oContent)
670          DebugFile.writeln("message content is null");
671        else
672          DebugFile.writeln("message content class is " + oContent.getClass().getName());
673      }
674
675      String JavaDoc sContentClass = oContent.getClass().getName();
676
677      if (sContentClass.equals("javax.mail.internet.MimeMultipart")) {
678
679        MimeMultipart JavaDoc oParts = (MimeMultipart JavaDoc) oContent;
680        int iParts = oParts.getCount();
681        MimePart JavaDoc oPart;
682        String JavaDoc sType, sPrevType, sNextType;
683
684        for (int p=0; p<iParts; p++) {
685
686          oPart = (MimeBodyPart JavaDoc) oParts.getBodyPart(0);
687
688          sType = oPart.getContentType().toUpperCase();
689
690          if (p<iParts-1)
691            sNextType = ((MimeBodyPart JavaDoc) oParts.getBodyPart(p+1)).getContentType().toUpperCase();
692          else
693            sNextType = "";
694
695          if (p>0 && iParts>1)
696            sPrevType = ((MimeBodyPart JavaDoc) oParts.getBodyPart(p-1)).getContentType().toUpperCase();
697          else
698            sPrevType = "";
699
700          // If a message has a dual content both text and html ignore the text and show only HTML
701
if ((iParts<=1) && (sType.startsWith("TEXT/PLAIN") || sType.startsWith("TEXT/HTML"))) {
702            if (DebugFile.trace) DebugFile.writeln("parts=" + String.valueOf(iParts) + ", content-type=" + oPart.getContentType());
703            oRetVal = oPart;
704            break;
705          }
706          else if (((p==0) && (iParts>1) && sType.startsWith("TEXT/PLAIN") && sNextType.startsWith("TEXT/HTML"))) {
707            if (DebugFile.trace) DebugFile.writeln("parts=" + String.valueOf(iParts) + ", part=0, content-type=" + oPart.getContentType() + ", next-type=" + sNextType);
708            oRetVal = ((MimeBodyPart JavaDoc) oParts.getBodyPart(p+1));
709            break;
710          }
711          else if ((p==1) && sType.startsWith("TEXT/PLAIN") && sPrevType.startsWith("TEXT/HTML")) {
712            if (DebugFile.trace) DebugFile.writeln("parts=" + String.valueOf(iParts) + ", part=1, content-type=" + oPart.getContentType() + ", prev-type=" + sPrevType);
713            oRetVal = ((MimeBodyPart JavaDoc) oParts.getBodyPart(p-1));
714            break;
715          }
716          else {
717            oRetVal = DBMimePart.getMessagePart (oPart, p);
718          }
719        } // next (p)
720
}
721      else if (sContentClass.equals("java.lang.String")) {
722        oRetVal = new MimeBodyPart JavaDoc();
723        oRetVal.setText((String JavaDoc) oContent);
724      }
725      else {
726        throw new MessagingException JavaDoc("Unparsed Mime Content " + oContent.getClass().getName());
727      }
728
729      if (null==oRetVal) {
730        oRetVal = new MimeBodyPart JavaDoc();
731        oRetVal.setText("");
732      }
733
734      if (DebugFile.trace) {
735        DebugFile.decIdent();
736        DebugFile.writeln("End DBMimeMessage.getMessageBody() : " + oRetVal.getContentType());
737      }
738
739      return oRetVal;
740   } // getMessageBody
741

742   // ---------------------------------------------------------------------------
743

744   public void setFlag (Flags.Flag JavaDoc oFlg, boolean bFlg) throws MessagingException JavaDoc {
745     String JavaDoc sColunm;
746
747     super.setFlag(oFlg, bFlg);
748
749     if (oFlg.equals(Flags.Flag.ANSWERED))
750       sColunm = DB.bo_answered;
751     else if (oFlg.equals(Flags.Flag.DELETED))
752       sColunm = DB.bo_deleted;
753     else if (oFlg.equals(Flags.Flag.DRAFT))
754       sColunm = DB.bo_draft;
755     else if (oFlg.equals(Flags.Flag.FLAGGED))
756       sColunm = DB.bo_flagged;
757     else if (oFlg.equals(Flags.Flag.RECENT))
758       sColunm = DB.bo_recent;
759     else if (oFlg.equals(Flags.Flag.SEEN))
760       sColunm = DB.bo_seen;
761     else
762       sColunm = null;
763
764     if (null!=sColunm && oFolder instanceof DBFolder) {
765       JDCConnection oConn = null;
766       PreparedStatement JavaDoc oUpdt = null;
767       try {
768         oConn = ((DBFolder)oFolder).getConnection();
769         String JavaDoc sSQL = "UPDATE " + DB.k_mime_msgs + " SET " + sColunm + "=" + (bFlg ? "1" : "0") + " WHERE " + DB.gu_mimemsg + "='" + getMessageGuid() + "'";
770         if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement("+sSQL+")");
771         oUpdt = oConn.prepareStatement(sSQL);
772         oUpdt.executeUpdate();
773         oUpdt.close();
774         oUpdt=null;
775         oConn.commit();
776         oConn=null;
777       }
778       catch (SQLException JavaDoc e) {
779         if (null!=oConn) { try { oConn.rollback(); } catch (Exception JavaDoc ignore) {} }
780         if (null!=oUpdt) { try { oUpdt.close(); } catch (Exception JavaDoc ignore) {} }
781         if (DebugFile.trace) DebugFile.decIdent();
782         throw new MessagingException JavaDoc(e.getMessage(), e);
783       }
784     }
785   } // setFlag
786

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

789   public void saveChanges() throws MessagingException JavaDoc {
790
791     if (DebugFile.trace) {
792       DebugFile.writeln("Begin DBMimeMessage.saveChanges()");
793       DebugFile.incIdent();
794     }
795
796     Flags JavaDoc oFlgs = getFlags();
797
798     if (oFolder instanceof DBFolder) {
799       JDCConnection oConn = null;
800       try {
801         oConn.commit();
802         oConn=null;
803       }
804       catch (SQLException JavaDoc e) {
805         if (null!=oConn) { try { oConn.rollback(); } catch (Exception JavaDoc ignore) {} }
806         if (DebugFile.trace) DebugFile.decIdent();
807         throw new MessagingException JavaDoc(e.getMessage(), e);
808       }
809     }
810     else {
811       super.saveChanges();
812     }
813
814     if (DebugFile.trace) {
815       DebugFile.decIdent();
816       DebugFile.writeln("End DBMimeMessage.saveChanges()");
817     }
818   }
819
820   // ---------------------------------------------------------------------------
821

822   /**
823    * Get message parts as an array of DBMimePart objects
824    * @return DBMimeMultiPart if this message folder is of type DBFolder
825    * or another type of Object if this message folder is another subclass of javax.mail.Folder
826    * such as POP3Folder.
827    * @throws MessagingException
828    * @throws IOException
829    * @throws NullPointerException If this message Folder is <b>null</b>
830    */

831   public Multipart JavaDoc getParts () throws MessagingException JavaDoc, IOException JavaDoc, NullPointerException JavaDoc {
832
833     if (DebugFile.trace) {
834       DebugFile.writeln("Begin DBMimeMessage.getParts()");
835       DebugFile.incIdent();
836     }
837
838     if (oFolder==null) {
839       if (DebugFile.trace) DebugFile.decIdent();
840       throw new NullPointerException JavaDoc("DBMimeMessage.getContent() : Folder for message cannot be null");
841     }
842
843     if (DebugFile.trace) DebugFile.writeln("Folder type " + oFolder.getClass().getName());
844
845     Multipart JavaDoc oRetVal;
846
847     if (oFolder.getClass().getName().equals("com.knowgate.hipermail.DBFolder")) {
848
849       if (sGuid==null) {
850         if (DebugFile.trace) DebugFile.decIdent();
851         throw new NullPointerException JavaDoc("DBMimeMessage.getContent() : message GUID cannot be null");
852       }
853
854       PreparedStatement JavaDoc oStmt = null;
855       ResultSet JavaDoc oRSet = null;
856       DBMimeMultipart oMultiPart = new DBMimeMultipart((Part JavaDoc) this);
857
858       try {
859         if (DebugFile.trace) {
860           DebugFile.writeln("Connection.prepareStatement(SELECT id_part,id_content,id_disposition,len_part,de_part,tx_md5,id_encoding,file_name,id_type FROM "+ DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='"+sGuid+"')");
861         }
862
863         oStmt = ((DBFolder)oFolder).getConnection().prepareStatement("SELECT id_part,id_content,id_disposition,len_part,de_part,tx_md5,id_encoding,file_name,id_type FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "=?",
864                                                                      ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
865         oStmt.setString(1, sGuid);
866
867         oRSet = oStmt.executeQuery();
868
869         while (oRSet.next()) {
870           if (DebugFile.trace) DebugFile.writeln("DBMimeMultipart.addBodyPart("+sGuid+","+String.valueOf(oRSet.getInt(1))+","+oRSet.getString(2)+","+oRSet.getString(9)+","+oRSet.getString(6)+","+oRSet.getString(5)+","+oRSet.getString(3)+","+oRSet.getString(7)+","+oRSet.getString(8)+","+String.valueOf(oRSet.getInt(4)));
871
872           MimePart JavaDoc oPart = new DBMimePart(oMultiPart, oRSet.getInt(1),oRSet.getString(2),oRSet.getString(9),oRSet.getString(6),oRSet.getString(5),oRSet.getString(3), oRSet.getString(7), oRSet.getString(8),oRSet.getInt(4));
873
874           oMultiPart.addBodyPart(oPart );
875         }
876
877         oRSet.close();
878         oRSet = null;
879         oStmt.close();
880         oStmt = null;
881
882       } catch (SQLException JavaDoc sqle) {
883         try { if (oRSet!=null) oRSet.close(); } catch (Exception JavaDoc e) {}
884         try { if (oStmt!=null) oStmt.close(); } catch (Exception JavaDoc e) {}
885         throw new MessagingException JavaDoc(sqle.getMessage(), sqle);
886       }
887       oRetVal = oMultiPart;
888     }
889     else {
890       oRetVal = (MimeMultipart JavaDoc) super.getContent();
891     }
892
893     if (DebugFile.trace) {
894       DebugFile.decIdent();
895         DebugFile.writeln("End DBMimeMessage.getParts() : " + (oRetVal==null ? "null" : oRetVal.getClass().getName()));
896     }
897
898     return oRetVal;
899   } // getParts
900

901   // ---------------------------------------------------------------------------
902

903    public MimePart JavaDoc getBody ()
904     throws ParseException JavaDoc, MessagingException JavaDoc, IOException JavaDoc {
905
906     MimePart JavaDoc oRetVal = null;
907
908     if (DebugFile.trace) {
909       DebugFile.writeln("Begin DBMimeMessage.getBody([MimeMessage])");
910       DebugFile.incIdent();
911     }
912
913      Object JavaDoc oContent = null;
914
915      try {
916        oContent = super.getContent();
917      }
918      catch (Exception JavaDoc xcpt) {
919        DebugFile.decIdent();
920        throw new ParseException JavaDoc("MimeMessage.getContent() ParseException cause " + xcpt.getClass().getName() + " " + (xcpt.getMessage()==null ? "" : xcpt.getMessage()));
921      }
922
923      if (DebugFile.trace) {
924        if (null==oContent)
925          DebugFile.writeln("message content is null");
926        else
927          DebugFile.writeln("message content class is " + oContent.getClass().getName());
928      }
929
930      String JavaDoc sContentClass = oContent.getClass().getName();
931
932      if (sContentClass.equals("javax.mail.internet.MimeMultipart")) {
933
934        MimeMultipart JavaDoc oParts = (MimeMultipart JavaDoc) oContent;
935        int iParts = oParts.getCount();
936        MimePart JavaDoc oPart;
937        String JavaDoc sType, sPrevType, sNextType;
938
939        for (int p=0; p<iParts; p++) {
940
941          oPart = (MimePart JavaDoc) oParts.getBodyPart(0);
942
943          sType = oPart.getContentType().toUpperCase();
944
945          if (p<iParts-1)
946            sNextType = ((MimeBodyPart JavaDoc) oParts.getBodyPart(p+1)).getContentType().toUpperCase();
947          else
948            sNextType = "";
949
950          if (p>0 && iParts>1)
951            sPrevType = ((MimeBodyPart JavaDoc) oParts.getBodyPart(p-1)).getContentType().toUpperCase();
952          else
953            sPrevType = "";
954
955          // If a message has a dual content both text and html ignore the text and show only HTML
956
if ((iParts<=1) && (sType.startsWith("TEXT/PLAIN") || sType.startsWith("TEXT/HTML"))) {
957            if (DebugFile.trace) DebugFile.writeln("parts=" + String.valueOf(iParts) + ", content-type=" + oPart.getContentType());
958            oRetVal = oPart;
959            break;
960          }
961          else if (((p==0) && (iParts>1) && sType.startsWith("TEXT/PLAIN") && sNextType.startsWith("TEXT/HTML"))) {
962            if (DebugFile.trace) DebugFile.writeln("parts=" + String.valueOf(iParts) + ", part=0, content-type=" + oPart.getContentType() + ", next-type=" + sNextType);
963            oRetVal = ((MimeBodyPart JavaDoc) oParts.getBodyPart(p+1));
964            break;
965          }
966          else if ((p==1) && sType.startsWith("TEXT/PLAIN") && sPrevType.startsWith("TEXT/HTML")) {
967            if (DebugFile.trace) DebugFile.writeln("parts=" + String.valueOf(iParts) + ", part=1, content-type=" + oPart.getContentType() + ", prev-type=" + sPrevType);
968            oRetVal = ((MimeBodyPart JavaDoc) oParts.getBodyPart(p-1));
969            break;
970          }
971          else {
972            oRetVal = DBMimePart.getMessagePart (oPart, p);
973          }
974        } // next (p)
975
}
976      else if (sContentClass.equals("java.lang.String")) {
977        oRetVal = new MimeBodyPart JavaDoc();
978        oRetVal.setText((String JavaDoc) oContent);
979      }
980      else if (oContent instanceof InputStream JavaDoc) {
981        // This branch is reached when the content-type is not recognized
982
// (usually with a com.sun.mail.util.SharedByteArrayInputStream)
983
// Decode content as an ISO-8859-1 string
984
if (DebugFile.trace) DebugFile.writeln("No data handler found for Content-Type, decoding as ISO-8859-1 string");
985        InputStream JavaDoc oInStrm = (InputStream JavaDoc) oContent;
986        ByteArrayOutputStream JavaDoc oBaStrm = new ByteArrayOutputStream JavaDoc();
987        StreamPipe oPipe = new StreamPipe();
988        oPipe.between(oInStrm, oBaStrm);
989        oRetVal = new MimeBodyPart JavaDoc();
990        oRetVal.setText(oBaStrm.toString("ISO8859_1"));
991      }
992      else {
993        throw new MessagingException JavaDoc("Unparsed Mime Content " + oContent.getClass().getName());
994      }
995
996      if (null==oRetVal) {
997        oRetVal = new MimeBodyPart JavaDoc();
998        oRetVal.setText("");
999      }
1000
1001     if (DebugFile.trace) {
1002       DebugFile.decIdent();
1003       DebugFile.writeln("End DBMimeMessage.getBody() : " + oRetVal.getContentType());
1004     }
1005
1006     return oRetVal;
1007  } // getBody
1008

1009  // ---------------------------------------------------------------------------
1010

1011  /**
1012   * Get message body text into a StringBuffer
1013   * @param oBuffer StringBuffer
1014   * @throws MessagingException
1015   * @throws IOException
1016   * @throws ClassCastException
1017   */

1018  public void getText (StringBuffer JavaDoc oBuffer)
1019    throws MessagingException JavaDoc,IOException JavaDoc,ClassCastException JavaDoc {
1020
1021    if (DebugFile.trace) {
1022      DebugFile.writeln("Begin DBMimeMessage.getText()");
1023      DebugFile.incIdent();
1024    }
1025
1026    if (null==oFolder) {
1027      Multipart JavaDoc oParts = (Multipart JavaDoc) super.getContent();
1028
1029      if (DebugFile.trace) DebugFile.writeln("MimeBodyPart = MimeMultipart.getBodyPart(0)");
1030
1031      BodyPart JavaDoc oPart0 = oParts.getBodyPart(0);
1032
1033      if (DebugFile.trace) {
1034        if (null==oPart0)
1035          DebugFile.writeln("part 0 is null");
1036        else
1037          DebugFile.writeln("part 0 is " + oPart0.getClass().getName());
1038      }
1039      DBMimePart.parseMimePart (oBuffer, null, null, getMessageID()!=null ? getMessageID() : getContentID(), (MimePart JavaDoc) oPart0, 0);
1040    }
1041    else {
1042      InputStream JavaDoc oInStrm;
1043      PreparedStatement JavaDoc oStmt = null;
1044      ResultSet JavaDoc oRSet = null;
1045      MimeBodyPart JavaDoc oBody = null;
1046      String JavaDoc sFolderNm = null;
1047      String JavaDoc sType = "multipart/";
1048
1049      try {
1050        sFolderNm = ((DBFolder)oFolder).getCategory().getStringNull(DB.nm_category, null);
1051        if (getMessageGuid()!=null) {
1052          oStmt = ((DBFolder)oFolder).getConnection().prepareStatement("SELECT "+DB.id_type+","+DB.by_content+" FROM "+DB.k_mime_msgs+" WHERE "+DB.gu_mimemsg+"=?");
1053          oStmt.setString(1, getMessageGuid());
1054        }
1055        else {
1056          oStmt = ((DBFolder)oFolder).getConnection().prepareStatement("SELECT "+DB.id_type+","+DB.by_content+" FROM "+DB.k_mime_msgs+" WHERE "+DB.id_message+"=? AND "+DB.gu_category+"=?");
1057          oStmt.setString(1, getMessageID());
1058          oStmt.setString(2, ((DBFolder)oFolder).getCategory().getString(DB.gu_category));
1059        }
1060        oRSet = oStmt.executeQuery();
1061        if (oRSet.next()) {
1062          sType = oRSet.getString(1);
1063          oInStrm = oRSet.getBinaryStream(2);
1064          if (!oRSet.wasNull()) {
1065            oBody = new MimeBodyPart JavaDoc(oInStrm);
1066            oInStrm.close();
1067          }
1068        }
1069        oRSet.close();
1070        oRSet=null;
1071        oStmt.close();
1072        oStmt=null;
1073      }
1074      catch (SQLException JavaDoc sqle) {
1075        if (oRSet!=null) { try {oRSet.close();} catch (Exception JavaDoc ignore) {} }
1076        if (oStmt!=null) { try {oStmt.close();} catch (Exception JavaDoc ignore) {} }
1077        throw new MessagingException JavaDoc(sqle.getMessage(), sqle);
1078      }
1079      if (oBody!=null) {
1080        if (sType.startsWith("text/"))
1081          oBuffer.append(oBody.getContent());
1082        else
1083          DBMimePart.parseMimePart (oBuffer, null, sFolderNm, getMessageID()!=null ? getMessageID() : getContentID(), oBody, 0);
1084      }
1085    }
1086
1087    if (DebugFile.trace) {
1088      DebugFile.decIdent();
1089      DebugFile.writeln("End DBMimeMessage.getText() : " + String.valueOf(oBuffer.length()));
1090    }
1091  } // getText
1092

1093  // ---------------------------------------------------------------------------
1094

1095  public String JavaDoc getText ()
1096    throws MessagingException JavaDoc,IOException JavaDoc {
1097    StringBuffer JavaDoc oStrBuff = new StringBuffer JavaDoc(16000);
1098    getText(oStrBuff);
1099    return oStrBuff.toString();
1100  }
1101
1102  // ---------------------------------------------------------------------------
1103

1104  public void getTextPlain (StringBuffer JavaDoc oBuffer)
1105    throws MessagingException JavaDoc,IOException JavaDoc {
1106
1107    if (DebugFile.trace) {
1108      DebugFile.writeln("Begin DBMimeMessage.getTextPlain()");
1109      DebugFile.incIdent();
1110    }
1111    boolean bHasPlainTextVersion = false;
1112
1113    if (getContentType().startsWith("text/plain")) {
1114      getText(oBuffer);
1115    }
1116    else if (getContentType().startsWith("text/html")) {
1117      StringBuffer JavaDoc oHtmlBuff = new StringBuffer JavaDoc();
1118      getText(oHtmlBuff);
1119      Parser oPrsr = Parser.createParser(oHtmlBuff.toString(), getEncoding());
1120      StringBean oStrBn = new StringBean();
1121      try {
1122        oPrsr.visitAllNodesWith (oStrBn);
1123      } catch (ParserException pe) {
1124        throw new MessagingException JavaDoc(pe.getMessage(), pe);
1125      }
1126      // Code for HTML parser 1.4
1127
// oStrBn.setInputHTML(oHtmlBuff.toString());
1128
oBuffer.append(oStrBn.getStrings());
1129    }
1130    else {
1131      if (DebugFile.trace) DebugFile.writeln("Multipart = DBMimeMessage.getParts()");
1132
1133      Multipart JavaDoc oParts = getParts();
1134
1135      final int iParts = oParts.getCount();
1136
1137      MimePart JavaDoc oPart;
1138
1139      int p;
1140      for (p=0; p<iParts && !bHasPlainTextVersion; p++) {
1141        oPart = (MimePart JavaDoc) oParts.getBodyPart(p);
1142
1143        String JavaDoc sType = oPart.getContentType();
1144        if (null!=sType) sType=sType.toLowerCase();
1145        String JavaDoc sDisp = oPart.getDisposition();
1146        if (null==sDisp) sDisp="inline"; else if (sDisp.length()==0) sDisp="inline";
1147
1148        if (DebugFile.trace) DebugFile.writeln("scanning part " + String.valueOf(p) + sDisp + " " + sType.replace('\r',' ').replace('\n', ' '));
1149
1150        if (sType.startsWith("text/plain") && sDisp.equalsIgnoreCase("inline")) {
1151          bHasPlainTextVersion = true;
1152          DBMimePart.parseMimePart (oBuffer, null,
1153                                    getFolder().getName(),
1154                                    getMessageID()!=null ? getMessageID() : getContentID(),
1155                                    oPart, p);
1156        }
1157      }
1158
1159      if (DebugFile.trace) {
1160        if (bHasPlainTextVersion)
1161          DebugFile.writeln("MimeMultipart has plain text version at part " + String.valueOf(p));
1162        else
1163          DebugFile.writeln("MimeMultipart has no plain text version, converting part 0 from HTML");
1164      }
1165
1166      if (!bHasPlainTextVersion) {
1167        oPart = (MimeBodyPart JavaDoc) oParts.getBodyPart(0);
1168        StringBuffer JavaDoc oHtml = new StringBuffer JavaDoc();
1169        DBMimePart.parseMimePart (oHtml, null, getFolder().getName(), getMessageID()!=null ? getMessageID() : getContentID(), oPart, 0);
1170
1171        Parser oPrsr = Parser.createParser(oHtml.toString(), getEncoding());
1172        StringBean oStrBn = new StringBean();
1173
1174        try {
1175          oPrsr.visitAllNodesWith (oStrBn);
1176        } catch (ParserException pe) {
1177          throw new MessagingException JavaDoc(pe.getMessage(), pe);
1178        }
1179
1180        // Code for HTML parser 1.4
1181
// oSB.setInputHTML(oHtml.toString());
1182

1183        String JavaDoc sStrs = oStrBn.getStrings();
1184
1185        if (DebugFile.trace) {
1186          DebugFile.writeln("StringBean.getStrings(");
1187          if (null!=sStrs) DebugFile.write(sStrs); else DebugFile.write("null");
1188          DebugFile.writeln(")");
1189        }
1190        oBuffer.append(sStrs);
1191      } // fi (!bHasPlainTextVersion)
1192
}
1193
1194    if (DebugFile.trace) {
1195      DebugFile.decIdent();
1196      DebugFile.writeln("End DBMimeMessage.getTextPlain() : " + String.valueOf(oBuffer.length()));
1197    }
1198  }
1199
1200  // ---------------------------------------------------------------------------
1201

1202  public void writeTo (OutputStream JavaDoc oOutStrm)
1203    throws IOException JavaDoc, FolderClosedException JavaDoc, MessagingException JavaDoc {
1204
1205    if (DebugFile.trace) {
1206      DebugFile.writeln("Begin DBMimeMessage.writeTo([OutputStream])");
1207      DebugFile.incIdent();
1208    }
1209
1210    if (getFolder()==null) {
1211      DebugFile.decIdent();
1212      throw new MessagingException JavaDoc("No folder for message");
1213    }
1214
1215    DBFolder oDBF = (DBFolder) getFolder();
1216
1217    if ((oDBF.getType()&DBFolder.MODE_MBOX)!=0) {
1218      if (oDBF.getConnection()==null) {
1219        if (DebugFile.trace) DebugFile.decIdent();
1220        throw new FolderClosedException JavaDoc(oDBF, "Folder is closed");
1221      }
1222
1223      PreparedStatement JavaDoc oStmt = null;
1224      ResultSet JavaDoc oRSet = null;
1225      BigDecimal JavaDoc oPos = null;
1226      int iLen = 0;
1227
1228      try {
1229          oStmt = oDBF.getConnection().prepareStatement("SELECT " + DB.nu_position + "," + DB .len_mimemsg + " FROM " + DB.k_mime_msgs + " WHERE " + DB.gu_mimemsg + "=?", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
1230          oStmt.setString(1, getMessageGuid());
1231          oRSet = oStmt.executeQuery();
1232          boolean bFound = oRSet.next();
1233          if (bFound) {
1234            oPos = oRSet.getBigDecimal(1);
1235            iLen = oRSet.getInt(2);
1236          }
1237          oRSet.close();
1238          oRSet=null;
1239          oStmt.close();
1240          oStmt=null;
1241
1242          if (!bFound) {
1243            if (DebugFile.trace) DebugFile.writeln("MimeMessage.writeTo(" + oOutStrm.getClass().getName() + ")");
1244            super.writeTo(oOutStrm);
1245            if (DebugFile.trace) {
1246              DebugFile.decIdent();
1247              DebugFile.writeln("End DBMimeMessage.writeTo()");
1248            }
1249            return;
1250          } // fi (!bFound)
1251
}
1252      catch (SQLException JavaDoc sqle) {
1253        if (oRSet!=null) { try {oRSet.close();} catch (Exception JavaDoc ignore) {} }
1254        if (oStmt!=null) { try {oStmt.close();} catch (Exception JavaDoc ignore) {} }
1255      }
1256
1257      File oFile = oDBF.getFile();
1258      MboxFile oMBox = new MboxFile(oFile, MboxFile.READ_ONLY);
1259
1260      InputStream JavaDoc oInStrm = oMBox.getMessageAsStream(oPos.longValue(), iLen);
1261      StreamPipe oPipe = new StreamPipe();
1262      oPipe.between(oInStrm, oOutStrm);
1263      oInStrm.close();
1264      oMBox.close();
1265    }
1266    else {
1267      Multipart JavaDoc oDBParts = getParts();
1268      MimeMultipart JavaDoc oMimeParts = new MimeMultipart JavaDoc();
1269
1270      for (int p=0;p<oDBParts.getCount(); p++) {
1271        oMimeParts.addBodyPart(oDBParts.getBodyPart(p));
1272        super.setContent(oMimeParts);
1273      }
1274      super.writeTo(oOutStrm);
1275    }
1276    if (DebugFile.trace) {
1277      DebugFile.decIdent();
1278      DebugFile.writeln("End DBMimeMessage.writeTo()");
1279    }
1280  }
1281
1282  // ----------------------------------------------------------------------------------------
1283

1284  public String JavaDoc tagBodyHtml()
1285    throws java.io.IOException JavaDoc, javax.mail.MessagingException JavaDoc {
1286
1287    if (com.knowgate.debug.DebugFile.trace) {
1288      com.knowgate.debug.DebugFile.writeln("Begin DBMimeMessage.tagBodyHtml()");
1289      com.knowgate.debug.DebugFile.incIdent();
1290    }
1291
1292    StringBuffer JavaDoc oText = new StringBuffer JavaDoc();
1293
1294    oText.append("<P><BR>------------------------------------------------------------<BR>");
1295
1296    com.knowgate.hipermail.DBInetAddr oAddr;
1297
1298    oAddr = (DBInetAddr) this.getFromRecipient();
1299    oText.append("<B>From:</B>&nbsp;<A HREF=\"mailto:"+oAddr.getAddress()+"\">&lt;");
1300    if (oAddr.getPersonal()!=null)
1301      oText.append(oAddr.getPersonal());
1302    else
1303      oText.append(oAddr.getAddress());
1304    oText.append("&gt;</A><BR>");
1305
1306    aAddrs = this.getRecipients(Message.RecipientType.TO);
1307    if (aAddrs!=null) {
1308      if (aAddrs.length>0) {
1309        oText.append("<B>To:</B>&nbsp;");
1310        for (int a=0; a<aAddrs.length; a++) {
1311          oAddr = (DBInetAddr) aAddrs[a];
1312            oText.append("&lt;<A HREF=\"mailto:"+oAddr.getAddress()+"\">");
1313            if (oAddr.getPersonal()!=null)
1314              oText.append(oAddr.getPersonal());
1315            else
1316              oText.append(oAddr.getAddress());
1317            oText.append("</A>&gt;; ");
1318        } // next
1319
oText.append("<BR>");
1320      }
1321    } // fi (aAddrs.TO)
1322

1323    aAddrs = this.getRecipients(Message.RecipientType.CC);
1324    if (aAddrs!=null) {
1325      if (aAddrs.length>0) {
1326        oText.append("<B>CC:</B>&nbsp;");
1327        for (int a=0; a<aAddrs.length; a++) {
1328          oAddr = (DBInetAddr) aAddrs[a];
1329            oText.append("&lt;<A HREF=\"mailto:"+oAddr.getAddress()+"\">");
1330            if (oAddr.getPersonal()!=null)
1331              oText.append(oAddr.getPersonal());
1332            else
1333              oText.append(oAddr.getAddress());
1334            oText.append("</A>&gt;; ");
1335        } // next
1336
oText.append("<BR>");
1337      }
1338    } // fi (aAddrs.CC)
1339

1340    aAddrs = this.getRecipients(Message.RecipientType.BCC);
1341    if (aAddrs!=null) {
1342      if (aAddrs.length>0) {
1343        oText.append("<B>BCC:</B>&nbsp;");
1344        for (int a=0; a<aAddrs.length; a++) {
1345          oAddr = (DBInetAddr) aAddrs[a];
1346            oText.append("&lt;<A HREF=\"mailto:"+oAddr.getAddress()+"\">");
1347            if (oAddr.getPersonal()!=null)
1348              oText.append(oAddr.getPersonal());
1349            else
1350              oText.append(oAddr.getAddress());
1351            oText.append("</A>&gt;; ");
1352        } // next
1353
oText.append("<BR>");
1354      }
1355    } // fi (aAddrs.CCO)
1356

1357   aAddrs = null;
1358
1359    Date JavaDoc dtSent = this.getSentDate();
1360    if (dtSent!=null) {
1361      SimpleDateFormat JavaDoc dtFmt = new SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss");
1362
1363      oText.append("<B>Sent:</B>&nbsp;"+dtFmt.format(dtSent)+"<BR>");
1364    }
1365
1366    oText.append("</P><BR>");
1367
1368    this.getTextPlain(oText);
1369
1370    if (DebugFile.trace) {
1371      DebugFile.decIdent();
1372      DebugFile.writeln("End DBMimeMessage.tagBodyHtml()");
1373    }
1374
1375    return oText.toString();
1376  } // tagBodyHtml
1377

1378  // ----------------------------------------------------------------------------------------
1379

1380  public String JavaDoc tagBodyPlain()
1381    throws java.io.IOException JavaDoc, javax.mail.MessagingException JavaDoc {
1382
1383    if (com.knowgate.debug.DebugFile.trace) {
1384      com.knowgate.debug.DebugFile.writeln("Begin DBMimeMessage.tagBodyPlain()");
1385      com.knowgate.debug.DebugFile.incIdent();
1386    }
1387
1388    StringBuffer JavaDoc oText = new StringBuffer JavaDoc();
1389
1390    oText.append("\n------------------------------------------------------------\n");
1391
1392    com.knowgate.hipermail.DBInetAddr oAddr;
1393
1394    oAddr = (DBInetAddr) this.getFromRecipient();
1395    oText.append("From: "+oAddr.getAddress());
1396
1397    javax.mail.Address JavaDoc[] aAddrs;
1398
1399    aAddrs = this.getRecipients(MimeMessage.RecipientType.TO);
1400    if (aAddrs!=null) {
1401      if (aAddrs.length>0) {
1402        oText.append("To: ");
1403        for (int a=0; a<aAddrs.length; a++) {
1404          oAddr = (DBInetAddr) aAddrs[a];
1405          oText.append(oAddr.getAddress());
1406        } // next
1407
oText.append("\n");
1408      }
1409    } // fi (aAddrs.TO)
1410

1411    aAddrs = this.getRecipients(MimeMessage.RecipientType.CC);
1412    if (aAddrs!=null) {
1413      if (aAddrs.length>0) {
1414        oText.append("CC: ");
1415        for (int a=0; a<aAddrs.length; a++) {
1416          oAddr = (DBInetAddr) aAddrs[a];
1417          oText.append(oAddr.getAddress());
1418        } // next
1419
oText.append("\n");
1420      }
1421    } // fi (aAddrs.CC)
1422

1423    aAddrs = this.getRecipients(MimeMessage.RecipientType.BCC);
1424    if (aAddrs!=null) {
1425      if (aAddrs.length>0) {
1426        oText.append("BCC: ");
1427        for (int a=0; a<aAddrs.length; a++) {
1428          oAddr = (DBInetAddr) aAddrs[a];
1429          oText.append(oAddr.getAddress());
1430        } // next
1431
oText.append("\n");
1432      }
1433    } // fi (aAddrs.CCO)
1434

1435    java.util.Date JavaDoc dtSent = this.getSentDate();
1436    if (dtSent!=null) {
1437      java.text.SimpleDateFormat JavaDoc dtFmt = new java.text.SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss");
1438
1439      oText.append("Sent: "+dtFmt.format(dtSent)+"\n");
1440    }
1441
1442    oText.append("\n\n");
1443
1444    this.getTextPlain(oText);
1445
1446    if (com.knowgate.debug.DebugFile.trace) {
1447      com.knowgate.debug.DebugFile.decIdent();
1448      com.knowgate.debug.DebugFile.writeln("End DBMimeMessage.tagBodyPlain()");
1449    }
1450
1451    return oText.toString();
1452  } // tagBodyPlain
1453

1454  // ---------------------------------------------------------------------------
1455

1456  /**
1457   * <p>Create an SMTPMessage object from given components</p>
1458   * Depending on what is inside, message structure is as follows :<br>
1459   * <table>
1460   * <tr><td><b>Format/Attachments</b></td><td><b>No</b></td><td><b>Yes</b></td></tr>
1461   * <tr><td><b>plain</b></td><td><b>text/plain</b></td><td><b>multipart/mixed [text/plain, {attachment}]</b></td></tr>
1462   * <tr><td><b>html without images</b></td><td><b>multipart/alternative [text/plain, text/html]</b></td><td><b>multipart/mixed [multipart/alternative [text/plain, text/html], {attachment}]</b></td></tr>
1463   * <tr><td><b>html with images</b></td><td><b>multipart/alternative [text/plain, multipart/related[text/html, {image}]]</b></td><td><b>multipart/mixed [multipart/alternative [text/plain, multipart/related[text/html, {image}]], {attachment}]</b></td></tr>
1464   * </table>
1465   * @param oMailSession Session
1466   * @param sSubject String Message subject or <b>null</b>
1467   * @param sBody String Message text body or <b>null</b>
1468   * @param sId String Contend-ID for message or <b>null</b>
1469   * @param sContentType String should be either "plain" or "html"
1470   * @return SMTPMessage
1471   * @throws IOException
1472   * @throws MessagingException
1473   * @throws SecurityException
1474   * @throws IllegalArgumentException if sContentType is not "plain" or "html"
1475   */

1476  public SMTPMessage composeFinalMessage(Session JavaDoc oMailSession, String JavaDoc sSubject, String JavaDoc sBody, String JavaDoc sId, String JavaDoc sContentType)
1477    throws IOException JavaDoc,MessagingException JavaDoc,IllegalArgumentException JavaDoc,SecurityException JavaDoc {
1478
1479    if (DebugFile.trace) {
1480      DebugFile.writeln("Begin DBMimeMessage.composeFinalMessage([Session],"+sSubject+",...,"+sId+","+sContentType+")");
1481    }
1482
1483    if (!"html".equalsIgnoreCase(sContentType) && !"plain".equalsIgnoreCase(sContentType))
1484      throw new IllegalArgumentException JavaDoc("Content Type must be either plain or html but it is "+sContentType);
1485
1486    if (DebugFile.trace) DebugFile.incIdent();
1487
1488    // If message has no body then send it always as plain text even if marked as HTML
1489
if (null==sBody) {
1490      sBody = "";
1491      sContentType = "plain";
1492    } else if (sBody.length()==0) {
1493      sContentType = "plain";
1494    }
1495
1496    SMTPMessage oSentMessage = new SMTPMessage(oMailSession);
1497
1498    Multipart JavaDoc oDraftParts = getParts();
1499    final int iDraftParts = oDraftParts.getCount();
1500
1501    if (DebugFile.trace) DebugFile.writeln("Multipart.getCount() = " + String.valueOf(iDraftParts));
1502
1503    MimeBodyPart JavaDoc oMsgPlainText = new MimeBodyPart JavaDoc();
1504    MimeMultipart JavaDoc oSentMsgParts = new MimeMultipart JavaDoc("mixed");
1505
1506    if (sContentType.equalsIgnoreCase("html")) {
1507
1508      MimeMultipart JavaDoc oHtmlRelated = new MimeMultipart JavaDoc("related");
1509      MimeMultipart JavaDoc oTextHtmlAlt = new MimeMultipart JavaDoc("alternative");
1510
1511      // ************************************************************************
1512
// Replace image CIDs
1513

1514      HashMap JavaDoc oDocumentImages = new HashMap JavaDoc(23);
1515
1516      StringSubstitution oSrcSubs = new StringSubstitution();
1517
1518      String JavaDoc sText = "";
1519
1520      Parser oPrsr = Parser.createParser(sBody, getEncoding());
1521
1522      String JavaDoc sCid, sSrc;
1523
1524      try {
1525
1526        // ****************************
1527
// Extract plain text from HTML
1528
if (DebugFile.trace) DebugFile.writeln("new StringBean()");
1529
1530        StringBean oStrBn = new StringBean();
1531
1532        try {
1533          oPrsr.visitAllNodesWith (oStrBn);
1534        } catch (ParserException pe) {
1535          throw new MessagingException JavaDoc(pe.getMessage(), pe);
1536        }
1537
1538        sText = oStrBn.getStrings();
1539
1540        oStrBn = null;
1541
1542        // *******************************
1543
// Set plain text alternative part
1544

1545        oMsgPlainText.setDisposition("inline");
1546        oMsgPlainText.setContent(sText, "text/plain; charset=utf-8");
1547        if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/alternative).addBodyPart(text/plain)");
1548        oTextHtmlAlt.addBodyPart(oMsgPlainText);
1549
1550        // ****************************************
1551
// Iterate images from HTML ad replace CIDs
1552

1553        NodeList oCollectionList = new NodeList();
1554        TagNameFilter oImgFilter = new TagNameFilter ("IMG");
1555        for (NodeIterator e = oPrsr.elements(); e.hasMoreNodes();)
1556          e.nextNode().collectInto(oCollectionList, oImgFilter);
1557
1558        final int nImgs = oCollectionList.size();
1559
1560        if (DebugFile.trace) DebugFile.writeln("NodeList.size() = " + String.valueOf(nImgs));
1561
1562        for (int i=0; i<nImgs; i++) {
1563
1564          sSrc = ((ImageTag) oCollectionList.elementAt(i)).extractImageLocn();
1565
1566          // Keep a reference to every related image name so that the same image is not included twice in the message
1567
if (!oDocumentImages.containsKey(sSrc)) {
1568
1569            // Find last slash from image url
1570
int iSlash = sSrc.lastIndexOf('/');
1571
1572            // Take image name
1573
if (iSlash>=0) {
1574              while (sSrc.charAt(iSlash)=='/') { if (++iSlash==sSrc.length()) break; }
1575              sCid = sSrc.substring(iSlash);
1576            }
1577            else {
1578              sCid = sSrc;
1579            }
1580
1581            //String sUid = Gadgets.generateUUID();
1582
//sCid = sUid.substring(0,12)+"$"+sUid.substring(12,20)+"$"+sUid.substring(20,28)+"@hipergate.org";
1583

1584            if (DebugFile.trace) DebugFile.writeln("HashMap.put("+sSrc+","+sCid+")");
1585
1586            oDocumentImages.put(sSrc, sCid);
1587          } // fi (!oDocumentImages.containsKey(sSrc))
1588

1589          try {
1590            Pattern oPattern = oCompiler.compile(sSrc, Perl5Compiler.SINGLELINE_MASK);
1591            oSrcSubs.setSubstitution("cid:"+oDocumentImages.get(sSrc));
1592            if (DebugFile.trace) DebugFile.writeln("Util.substitute([PatternMatcher],"+ sSrc + ",cid:"+oDocumentImages.get(sSrc)+",...)");
1593            sBody = Util.substitute(oMatcher, oPattern, oSrcSubs, sBody);
1594          } catch (MalformedPatternException neverthrown) { }
1595
1596        } // next
1597
}
1598      catch (ParserException pe) {
1599        if (DebugFile.trace) {
1600          DebugFile.writeln("org.htmlparser.util.ParserException " + pe.getMessage());
1601        }
1602      }
1603      // End replace image CIDs
1604
// ************************************************************************
1605

1606      // ************************************************************************
1607
// Add HTML related images
1608

1609      if (oDocumentImages.isEmpty()) {
1610          // Set HTML part
1611
MimeBodyPart JavaDoc oMsgHtml = new MimeBodyPart JavaDoc();
1612          oMsgHtml.setDisposition("inline");
1613          oMsgHtml.setContent(sBody, "text/html; charset=utf-8");
1614          oTextHtmlAlt.addBodyPart(oMsgHtml);
1615      } else {
1616
1617        // Set HTML text related part
1618

1619        MimeBodyPart JavaDoc oMsgHtmlText = new MimeBodyPart JavaDoc();
1620        oMsgHtmlText.setDisposition("inline");
1621        oMsgHtmlText.setContent(sBody, "text/html; charset=utf-8");
1622        if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/related).addBodyPart(text/html)");
1623        oHtmlRelated.addBodyPart(oMsgHtmlText);
1624
1625        // Set HTML text related inline images
1626

1627        Iterator JavaDoc oImgs = oDocumentImages.keySet().iterator();
1628
1629        while (oImgs.hasNext()) {
1630          BodyPart JavaDoc oImgBodyPart = new MimeBodyPart JavaDoc();
1631
1632          sSrc = (String JavaDoc) oImgs.next();
1633          sCid = (String JavaDoc) oDocumentImages.get(sSrc);
1634
1635          if (sSrc.startsWith("www."))
1636            sSrc = "http://" + sSrc;
1637
1638          if (sSrc.startsWith("http://") || sSrc.startsWith("https://")) {
1639            oImgBodyPart.setDataHandler(new DataHandler JavaDoc(new URL JavaDoc(sSrc)));
1640          }
1641          else {
1642            oImgBodyPart.setDataHandler(new DataHandler JavaDoc(new FileDataSource JavaDoc(sSrc)));
1643          }
1644
1645          oImgBodyPart.setDisposition("inline");
1646          oImgBodyPart.setHeader("Content-ID", sCid);
1647          oImgBodyPart.setFileName(sCid);
1648
1649          // Add image to multi-part
1650
if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/related).addBodyPart("+sCid+")");
1651          oHtmlRelated.addBodyPart(oImgBodyPart);
1652        } // wend
1653

1654        // Set html text alternative part (html text + inline images)
1655
MimeBodyPart JavaDoc oTextHtmlRelated = new MimeBodyPart JavaDoc();
1656        oTextHtmlRelated.setContent(oHtmlRelated);
1657        if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/alternative).addBodyPart(multipart/related)");
1658        oTextHtmlAlt.addBodyPart(oTextHtmlRelated);
1659      }
1660
1661      // ************************************************************************
1662
// Create message to be sent and add main text body to it
1663

1664      if (0==iDraftParts) {
1665        oSentMessage.setContent(oTextHtmlAlt);
1666      } else {
1667        MimeBodyPart JavaDoc oMixedPart = new MimeBodyPart JavaDoc();
1668        oMixedPart.setContent(oTextHtmlAlt);
1669        oSentMsgParts.addBodyPart(oMixedPart);
1670      }
1671
1672    } else { // (sContentType=="plain")
1673

1674      // *************************************************
1675
// If this is a plain text message just add the text
1676

1677      if (0==iDraftParts) {
1678        oSentMessage.setText(sBody, "utf-8");
1679      } else {
1680        oMsgPlainText.setDisposition("inline");
1681        oMsgPlainText.setContent(sBody, "text/plain; charset=utf-8");
1682        if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/mixed).addBodyPart(text/plain)");
1683        oSentMsgParts.addBodyPart(oMsgPlainText);
1684      }
1685    }
1686    // fi (sContentType=="html")
1687

1688    // ************************************************************************
1689
// Add attachments to message to be sent
1690

1691    if (iDraftParts>0) {
1692
1693      for (int p=0; p<iDraftParts; p++) {
1694        DBMimePart oPart = (DBMimePart) oDraftParts.getBodyPart(p);
1695
1696        String JavaDoc sDisposition = oPart.getDisposition();
1697        if (sDisposition==null)
1698          sDisposition = "inline";
1699        else if (sDisposition.equals("reference") || sDisposition.equals("pointer"))
1700          sDisposition = "attachment";
1701
1702        int iSize = oPart.getSize();
1703        if (iSize<=0) iSize = 4000;
1704        InputStream JavaDoc oInStrm = oPart.getInputStream();
1705        ByteArrayOutputStream JavaDoc oByStrm = new java.io.ByteArrayOutputStream JavaDoc(iSize);
1706        new StreamPipe().between(oInStrm, oByStrm);
1707        oInStrm.close();
1708
1709        if (DebugFile.trace) DebugFile.writeln("part " + String.valueOf(p) + " size is " + String.valueOf(oByStrm.size()));
1710
1711        ByteArrayDataSource oDataSrc = new ByteArrayDataSource(oByStrm.toByteArray(), oPart.getContentType());
1712        MimeBodyPart JavaDoc oAttachment = new MimeBodyPart JavaDoc();
1713        oAttachment.setDisposition(sDisposition);
1714        if (sDisposition.equals("attachment"))
1715        if (null==oPart.getDescription())
1716          oAttachment.setFileName(oPart.getFileName());
1717        else
1718          oAttachment.setFileName(oPart.getDescription());
1719        oAttachment.setHeader("Content-Transfer-Encoding", "base64");
1720        oAttachment.setDataHandler(new DataHandler JavaDoc(oDataSrc));
1721        oSentMsgParts.addBodyPart(oAttachment);
1722      } // next
1723
oSentMessage.setContent(oSentMsgParts);
1724    } // fi (iDraftParts>0)
1725

1726    if (null!=sSubject) oSentMessage.setSubject(sSubject);
1727
1728    if (sId!=null)
1729      if (sId.trim().length()>0)
1730        oSentMessage.setContentID(sId);
1731
1732    if (DebugFile.trace) {
1733      DebugFile.decIdent();
1734      DebugFile.writeln("End DBMimeMessage.composeFinalMessage()");
1735    }
1736
1737    return oSentMessage;
1738  } // composeFinalMessage
1739

1740  // ---------------------------------------------------------------------------
1741

1742  /**
1743     * <p>Delete message from database</p>
1744     * This method calls stored procedure k_sp_del_mime_msg<br>
1745     * @param oConn JDBC database connection
1746     * @param sFolderId Folder GUID (k_mime_msgs.gu_category)
1747     * @param sMimeMsgId Message GUID (k_mime_msgs.gu_mimemsg)
1748     * @throws SQLException
1749  */

1750
1751  public static void delete (JDCConnection oConn, String JavaDoc sFolderId, String JavaDoc sMimeMsgId)
1752      throws SQLException JavaDoc,IOException JavaDoc {
1753      Statement JavaDoc oStmt;
1754      CallableStatement JavaDoc oCall;
1755
1756      if (DebugFile.trace) {
1757        DebugFile.writeln("Begin DBMimeMessage.delete([Connection], "+sMimeMsgId+")");
1758        DebugFile.incIdent();
1759      }
1760
1761      oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
1762      ResultSet JavaDoc oRSet = oStmt.executeQuery("SELECT " + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='"+sMimeMsgId+"' AND " + DB.id_disposition + "='reference'");
1763
1764      while (oRSet.next()) {
1765        String JavaDoc sFileName = oRSet.getString(1);
1766        if (!oRSet.wasNull()) {
1767          try {
1768            File oRef = new File(sFileName);
1769            oRef.delete();
1770          }
1771          catch (SecurityException JavaDoc se) {
1772            if (DebugFile.trace) DebugFile.writeln("SecurityException " + sFileName + " " + se.getMessage());
1773          }
1774        }
1775      } // wend
1776

1777      oRSet.close();
1778      oRSet = null;
1779      oStmt.close();
1780      oStmt = null;
1781
1782      if (oConn.getDataBaseProduct()==JDCConnection.DBMS_POSTGRESQL) {
1783        oStmt = oConn.createStatement();
1784        oStmt.executeQuery("SELECT k_sp_del_mime_msg('" + sMimeMsgId + "')");
1785        oStmt.close();
1786      }
1787      else {
1788        oCall = oConn.prepareCall("{ call k_sp_del_mime_msg(?) }");
1789        oCall.setString(1, sMimeMsgId);
1790        oCall.execute();
1791        oCall.close();
1792      }
1793
1794      if (DebugFile.trace) {
1795        DebugFile.decIdent();
1796        DebugFile.writeln("End DBMimeMessage.delete()");
1797      }
1798  } // delete
1799

1800  // ---------------------------------------------------------------------------
1801

1802  public static String JavaDoc source (MimeMessage JavaDoc oMsg, String JavaDoc sEncoding)
1803   throws MessagingException JavaDoc, UnsupportedEncodingException JavaDoc, IOException JavaDoc {
1804
1805   if (DebugFile.trace) {
1806     DebugFile.writeln("Begin DBMimeMessage.source([MimeMessage], "+sEncoding+")");
1807     DebugFile.incIdent();
1808   }
1809
1810   final int iSize = oMsg.getSize();
1811   if (DebugFile.trace) DebugFile.writeln("size="+String.valueOf(iSize));
1812   ByteArrayOutputStream JavaDoc byOutStrm = new ByteArrayOutputStream JavaDoc(iSize>0 ? iSize : 16000);
1813   oMsg.writeTo(byOutStrm);
1814   String JavaDoc sSrc = byOutStrm.toString(sEncoding);
1815   byOutStrm.close();
1816
1817   if (DebugFile.trace) {
1818     DebugFile.decIdent();
1819     if (null==sSrc)
1820       DebugFile.writeln("End DBMimeMessage.source() : null");
1821     else
1822       DebugFile.writeln("End DBMimeMessage.source() : " + String.valueOf(sSrc.length()));
1823   }
1824   return sSrc;
1825  } // source
1826

1827  // ---------------------------------------------------------------------------
1828

1829  public static String JavaDoc getGuidFromId (JDCConnection oConn, String JavaDoc sMsgId)
1830    throws SQLException JavaDoc {
1831      String JavaDoc sMsgGuid;
1832
1833      switch (oConn.getDataBaseProduct()) {
1834        case JDCConnection.DBMS_POSTGRESQL:
1835          PreparedStatement JavaDoc oStmt = oConn.prepareStatement("SELECT k_sp_get_mime_msg(?)");
1836          oStmt.setString(1, sMsgId);
1837          ResultSet JavaDoc oRSet = oStmt.executeQuery();
1838          oRSet.next();
1839          sMsgGuid = oRSet.getString(1);
1840          oRSet.close();
1841          oRSet = null;
1842          oStmt.close();
1843          oStmt = null;
1844          break;
1845        default:
1846          CallableStatement JavaDoc oCall = oConn.prepareCall("{ call k_sp_get_mime_msg(?,?) }");
1847          oCall.setString(1, sMsgId);
1848          oCall.registerOutParameter(2, Types.CHAR);
1849          oCall.execute();
1850          sMsgGuid = oCall.getString(2);
1851          if (sMsgGuid!=null) sMsgGuid = sMsgGuid.trim();
1852          oCall.close();
1853          oCall = null;
1854      }
1855      return sMsgGuid;
1856    }
1857
1858  // ===========================================================================
1859
public static final short ClassId = 822;
1860}
1861
Popular Tags