KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > scheduler > jobs > MimeSender


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.scheduler.jobs;
34
35 import java.io.IOException JavaDoc;
36
37 import java.sql.SQLException JavaDoc;
38 import java.sql.PreparedStatement JavaDoc;
39 import java.sql.ResultSet JavaDoc;
40
41 import java.util.Properties JavaDoc;
42
43 import javax.mail.Message JavaDoc;
44 import javax.mail.URLName JavaDoc;
45 import javax.mail.Address JavaDoc;
46 import javax.mail.Folder JavaDoc;
47 import javax.mail.MessagingException JavaDoc;
48 import javax.mail.SendFailedException JavaDoc;
49 import javax.mail.internet.InternetAddress JavaDoc;
50
51 import com.sun.mail.smtp.SMTPMessage;
52
53 import com.knowgate.debug.DebugFile;
54 import com.knowgate.acl.ACLUser;
55 import com.knowgate.jdc.JDCConnection;
56 import com.knowgate.misc.Gadgets;
57 import com.knowgate.dataobjs.DB;
58 import com.knowgate.dataxslt.FastStreamReplacer;
59 import com.knowgate.hipermail.DBStore;
60 import com.knowgate.hipermail.DBFolder;
61 import com.knowgate.hipermail.DBInetAddr;
62 import com.knowgate.hipermail.DBMimeMessage;
63 import com.knowgate.hipermail.MailAccount;
64 import com.knowgate.hipermail.SessionHandler;
65 import com.knowgate.scheduler.Job;
66 import com.knowgate.scheduler.Atom;
67
68 /**
69  * <p>Send mime mail message to a recipients list</p>
70  * @author Sergio Montoro Ten
71  * @version 3.0
72  */

73
74 public class MimeSender extends Job {
75
76   private SessionHandler oHndlr;
77   private DBStore oStor;
78   private DBFolder oOutBox;
79   private String JavaDoc sBody;
80   private boolean bPersonalized;
81   private DBMimeMessage oDraft;
82   private Properties JavaDoc oHeaders;
83   private InternetAddress JavaDoc[] aFrom;
84   private InternetAddress JavaDoc[] aReply;
85
86   public MimeSender() {
87     sBody = null;
88     oHndlr = null;
89     oStor = null;
90     oOutBox = null;
91   }
92
93   // ---------------------------------------------------------------------------
94

95   private String JavaDoc personalizeBody(Atom oAtm) throws NullPointerException JavaDoc {
96     JDCConnection oConn = null;
97     PreparedStatement JavaDoc oStmt = null;
98     ResultSet JavaDoc oRSet = null;
99     String JavaDoc sPersonalizedBody;
100     String JavaDoc sNm, sSn, sSl, sCo, sEm;
101
102     if (DebugFile.trace) {
103       DebugFile.writeln("Begin MimeSender.personalizeBody([Atom])");
104       DebugFile.incIdent();
105       DebugFile.writeln("gu_job="+oAtm.getStringNull(DB.gu_job,"null"));
106       if (oAtm.isNull(DB.pg_atom)) {
107         DebugFile.decIdent();
108         throw new NullPointerException JavaDoc("MimeSender.personalizeBody() no Atom set");
109       } else {
110         DebugFile.writeln("pg_atom="+String.valueOf(oAtm.getInt(DB.pg_atom)));
111       }
112     }
113
114     sEm = oAtm.getString(DB.tx_email);
115
116     try {
117       oConn = getDataBaseBind().getConnection("MimeSender");
118       if (DebugFile.trace) {
119         DebugFile.writeln("Connection.prepareStatement(SELECT "+DB.tx_name+","+DB.tx_surname+","+DB.tx_salutation+","+DB.nm_commercial+" FROM "+DB.k_member_address+" WHERE "+DB.gu_workarea+"='"+getStringNull(DB.gu_workarea,"null")+"' AND "+DB.tx_email+"='"+sEm+"')");
120       }
121       oStmt = oConn.prepareStatement("SELECT "+DB.tx_name+","+DB.tx_surname+","+DB.tx_salutation+","+DB.nm_commercial+" FROM "+DB.k_member_address+" WHERE "+DB.gu_workarea+"='"+getString(DB.gu_workarea)+"' AND "+DB.tx_email+"=?",
122                                      ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
123       oStmt.setString(1, sEm);
124       oRSet = oStmt.executeQuery();
125       if (oRSet.next()) {
126         sNm = oRSet.getString(1); if (oRSet.wasNull()) sNm = "";
127         sSn = oRSet.getString(2); if (oRSet.wasNull()) sSn = "";
128         sSl = oRSet.getString(3); if (oRSet.wasNull()) sSl = "";
129         sCo = oRSet.getString(4); if (oRSet.wasNull()) sCo = "";
130       } else {
131         sNm=sSn=sSl=sCo="";
132       }
133       oRSet.close();
134       oRSet=null;
135       oStmt.close();
136       oStmt=null;
137       FastStreamReplacer oRplcr = new FastStreamReplacer(sBody.length()+256);
138       try {
139         sPersonalizedBody = oRplcr.replace(sBody, FastStreamReplacer.createMap(
140                              new String JavaDoc[]{"Data.Name","Data.Surname","Data.Salutation","Data.Legal_Name,Address.EMail",
141                                           "Datos.Nombre","Datos.Apellidos","Datos.Saludo","Datos.Razon_Social","Direccion.EMail"},
142                              new String JavaDoc[]{sNm,sSn,sSl,sCo,sEm,sNm,sSn,sSl,sCo,sEm}));
143       } catch (IOException JavaDoc ioe) {
144         if (DebugFile.trace) DebugFile.writeln("IOException " + ioe.getMessage() + " sending message "+getParameter("message") + " to " + sEm);
145         log("IOException " + ioe.getMessage() + " sending message "+getParameter("message") + " to " + sEm);
146         sPersonalizedBody = sBody;
147       }
148       oConn.close("MimeSender");
149       oConn=null;
150     } catch (SQLException JavaDoc sqle) {
151       if (oRSet!=null) { try { oRSet.close(); } catch (Exception JavaDoc ignore) {} }
152       if (oStmt!=null) { try { oStmt.close(); } catch (Exception JavaDoc ignore) {} }
153       if (oConn!=null) { try { oConn.close(); } catch (Exception JavaDoc ignore) {} }
154       if (DebugFile.trace) DebugFile.writeln("SQLException " + sqle.getMessage() + " sending message "+getParameter("message") + " to " + sEm);
155       log("SQLException " + sqle.getMessage() + " sending message "+getParameter("message") + " to " + sEm);
156       sPersonalizedBody = sBody;
157     }
158
159     if (DebugFile.trace) {
160       DebugFile.decIdent();
161       DebugFile.writeln("End MimeSender.personalizeBody()");
162     }
163     return sPersonalizedBody;
164   } // personalizeBody
165

166   // ---------------------------------------------------------------------------
167

168   private static int getDomainForWorkArea(JDCConnection oConn, String JavaDoc sWrkA)
169     throws SQLException JavaDoc {
170     int iDomainId = -1;
171
172     if (DebugFile.trace) {
173       DebugFile.writeln("Begin MimeSender.getDomainForWorkArea([JDCConnection],"+sWrkA+")");
174       DebugFile.incIdent();
175       DebugFile.writeln("Connection.prepareStatement(SELECT "+DB.id_domain+" FROM "+DB.k_workareas+" WHERE "+DB.gu_workarea+"='"+sWrkA+"')");
176     }
177
178     PreparedStatement JavaDoc oStmt = oConn.prepareStatement("SELECT "+DB.id_domain+" FROM "+DB.k_workareas+" WHERE "+DB.gu_workarea+"=?",
179                               ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
180     oStmt.setString(1, sWrkA);
181     ResultSet JavaDoc oRSet = oStmt.executeQuery();
182     if (oRSet.next()) iDomainId = oRSet.getInt(1);
183     oRSet.close();
184     oStmt.close();
185
186     if (DebugFile.trace) {
187       DebugFile.decIdent();
188       DebugFile.writeln("End MimeSender.getDomainForWorkArea() : " +String.valueOf(iDomainId));
189     }
190     return iDomainId;
191   } // getDomainForWorkArea
192

193   // ---------------------------------------------------------------------------
194

195   public void init(Atom oAtm)
196     throws SQLException JavaDoc,MessagingException JavaDoc,NullPointerException JavaDoc {
197       if (DebugFile.trace) {
198         DebugFile.writeln("Begin MimeSender.init()");
199         DebugFile.incIdent();
200       }
201       // If mail is personalized (contains {#...} tags) a special parameter must has been previously set
202
bPersonalized = Boolean.getBoolean(getParameter("personalized"));
203       if (DebugFile.trace) DebugFile.writeln("personalized="+getParameter("personalized"));
204       JDCConnection oConn = null;
205       PreparedStatement JavaDoc oStmt = null;
206       PreparedStatement JavaDoc oUpdt = null;
207       ResultSet JavaDoc oRSet = null;
208       ACLUser oUser = new ACLUser();
209       MailAccount oMacc = new MailAccount();
210       if (DebugFile.trace) DebugFile.writeln("workarea="+getStringNull(DB.gu_workarea,"null"));
211       String JavaDoc sWrkA = getString(DB.gu_workarea);
212       int iDomainId=-1;
213       try {
214         if (DebugFile.trace) DebugFile.writeln("DBBind="+getDataBaseBind());
215         // Get User, Account and Domain objects
216
oConn = getDataBaseBind().getConnection("MimeSender");
217         iDomainId = getDomainForWorkArea(oConn, sWrkA);
218         if (!oUser.load(oConn, new Object JavaDoc[]{getStringNull(DB.gu_writer,null)})) oUser=null;
219         if (!oMacc.load(oConn, new Object JavaDoc[]{getParameter("account")})) oMacc=null;
220         // If message is personalized then fill data for each mail address
221
if (bPersonalized) resolveAtomsEMails(oConn);
222         oConn.close("MimeSender");
223         oConn=null;
224       } catch (SQLException JavaDoc sqle) {
225         if (DebugFile.trace) DebugFile.writeln("MimeSender.process("+getStringNull(DB.gu_job,"null")+") " + sqle.getClass().getName() + " " + sqle.getMessage());
226         if (oConn!=null) { try { oConn.close(); } catch (Exception JavaDoc ignore) {} }
227         throw sqle;
228       } catch (NullPointerException JavaDoc npe) {
229         if (DebugFile.trace) DebugFile.writeln("MimeSender.process("+getStringNull(DB.gu_job,"null")+") " + npe.getClass().getName());
230         if (oConn!=null) { try { oConn.close(); } catch (Exception JavaDoc ignore) {} }
231         throw npe;
232       }
233       if (null==oUser) {
234         if (DebugFile.trace) {
235           DebugFile.decIdent();
236           DebugFile.writeln("End MimeSender.init("+oAtm.getString(DB.gu_job)+":"+String.valueOf(oAtm.getInt(DB.pg_atom))+") : abnormal process termination");
237         }
238         throw new NullPointerException JavaDoc("User "+getStringNull(DB.gu_writer,"null")+" not found");
239       }
240       if (null==oMacc) {
241         if (DebugFile.trace) {
242           DebugFile.decIdent();
243           DebugFile.writeln("End MimeSender.init("+oAtm.getString(DB.gu_job)+":"+String.valueOf(oAtm.getInt(DB.pg_atom))+") : abnormal process termination");
244         }
245         throw new NullPointerException JavaDoc("Mail Account "+getParameter("account")+" not found");
246       }
247       try {
248         // Create mail session
249
if (DebugFile.trace) DebugFile.writeln("new SessionHandler("+oMacc.getStringNull(DB.gu_account,"null")+")");
250         oHndlr = new SessionHandler(oMacc);
251         // Retrieve profile name to be used from a Job parameter
252
// Profile is needed because it contains the path to /storage directory
253
// which is used for composing the path to outbox mbox file containing
254
// source of message to be sent
255
String JavaDoc sProfile = getParameter("profile");
256         String JavaDoc sMBoxDir = DBStore.MBoxDirectory(sProfile,iDomainId,sWrkA);
257         oStor = new DBStore(oHndlr.getSession(), new URLName JavaDoc("jdbc://", sProfile, -1, sMBoxDir, oUser.getString(DB.gu_user), oUser.getString(DB.tx_pwd)));
258         oStor.connect(sProfile, oUser.getString(DB.gu_user), oUser.getString(DB.tx_pwd));
259         oOutBox = (DBFolder) oStor.getFolder("outbox");
260         oOutBox.open(Folder.READ_WRITE);
261         String JavaDoc sMsgId = getParameter("message");
262         oDraft = oOutBox.getMessageByGuid(sMsgId);
263         if (null==oDraft) throw new MessagingException JavaDoc("DBFolder.getMessageByGuid() Message "+sMsgId+" not found");
264         oHeaders = oOutBox.getMessageHeaders(sMsgId);
265         if (null==oHeaders) throw new MessagingException JavaDoc("DBFolder.getMessageHeaders() Message "+sMsgId+" not found");
266         if (null==oHeaders.get(DB.nm_from))
267           aFrom = new InternetAddress JavaDoc[]{new InternetAddress JavaDoc(oHeaders.getProperty(DB.tx_email_from))};
268         else
269           aFrom = new InternetAddress JavaDoc[]{new InternetAddress JavaDoc(oHeaders.getProperty(DB.tx_email_from),
270                                                             oHeaders.getProperty(DB.nm_from))};
271         if (null==oHeaders.get(DB.tx_reply_email))
272           aReply = aFrom;
273         else
274           aReply = new InternetAddress JavaDoc[]{new InternetAddress JavaDoc(oHeaders.getProperty(DB.tx_reply_email))};
275         sBody = oDraft.getText();
276         if (DebugFile.trace) {
277           if (null==sBody)
278             DebugFile.writeln("Message body: null");
279           else
280             DebugFile.writeln("Message body: " + Gadgets.left(sBody.replace('\n',' '), 100));
281         }
282       } catch (Exception JavaDoc e) {
283         if (DebugFile.trace) {
284           DebugFile.decIdent();
285           DebugFile.writeln("End MimeSender.init(" + oAtm.getString(DB.gu_job) + ":" + String.valueOf(oAtm.getInt(DB.pg_atom)) + ") : abnormal process termination");
286         }
287         if (null!=oOutBox) { try { oOutBox.close(false); oOutBox=null; } catch (Exception JavaDoc ignore) {} }
288         if (null!=oStor) { try { oStor.close(); oStor=null; } catch (Exception JavaDoc ignore) {} }
289         if (null!=oHndlr) { try { oHndlr.close(); oHndlr=null; } catch (Exception JavaDoc ignore) {} }
290         throw new MessagingException JavaDoc(e.getMessage(),e);
291       }
292       if (DebugFile.trace) {
293         DebugFile.decIdent();
294         DebugFile.writeln("End MimeSender.init()");
295       }
296   } // init
297

298   // ---------------------------------------------------------------------------
299

300   public void free() {
301     if (DebugFile.trace) {
302       DebugFile.writeln("Begin MimeSender.free()");
303       DebugFile.incIdent();
304       DebugFile.writeln("gu_job="+getStringNull(DB.gu_job,"null"));
305     }
306     oDraft=null;
307     if (null!=oOutBox) { try { oOutBox.close(false); oOutBox=null; } catch (Exception JavaDoc ignore) {} }
308     if (null!=oStor) { try { oStor.close(); oStor=null; } catch (Exception JavaDoc ignore) {} }
309     if (null!=oHndlr) { try { oHndlr.close(); oHndlr=null; } catch (Exception JavaDoc ignore) {} }
310     if (DebugFile.trace) {
311       DebugFile.decIdent();
312       DebugFile.writeln("End MimeSender.free()");
313     }
314   } // free
315

316   // ---------------------------------------------------------------------------
317

318   public Object JavaDoc process(Atom oAtm) throws SQLException JavaDoc, MessagingException JavaDoc, NullPointerException JavaDoc {
319
320     if (DebugFile.trace) {
321       DebugFile.writeln("Begin MimeSender.process("+oAtm.getString(DB.gu_job)+":"+String.valueOf(oAtm.getInt(DB.pg_atom))+")");
322       DebugFile.incIdent();
323     }
324
325     // ***************************************************
326
// Create mail session if it does not previously exist
327

328     if (oHndlr==null && iPendingAtoms>0) {
329       init(oAtm);
330     }
331
332     if (null==oDraft) {
333       if (DebugFile.trace) {
334         DebugFile.decIdent();
335         DebugFile.writeln("End MimeSender.process(" + oAtm.getString(DB.gu_job) + ":" + String.valueOf(oAtm.getInt(DB.pg_atom)) + ") : abnormal process termination");
336       }
337       throw new NullPointerException JavaDoc("Draft message "+getParameter("message")+" not found");
338     }
339
340     // ***********************************
341
// Once session is created set message
342

343     SMTPMessage oSentMsg;
344
345     try {
346       // Personalize mail if needed by replacing {#...} tags by values taken from Atom fields
347
if (bPersonalized)
348         oSentMsg = oDraft.composeFinalMessage(oHndlr.getSession(), oDraft.getSubject(),
349                                               personalizeBody(oAtm), getParameter("id"),
350                                               oAtm.getStringNull(DB.id_format,"text"));
351       else
352         oSentMsg = oDraft.composeFinalMessage(oHndlr.getSession(), oDraft.getSubject(),
353                                               sBody, getParameter("id"),
354                                               oAtm.getStringNull(DB.id_format,"text"));
355
356       // If there is no mail address at the atom then send message to recipients
357
// that are already set into message object itself.
358
// If there is a mail address at the atom then send message to that recipient
359
if (!oAtm.isNull(DB.tx_email)) {
360         if (DebugFile.trace) DebugFile.writeln("tx_email="+oAtm.getString(DB.tx_email));
361         InternetAddress JavaDoc oRec = DBInetAddr.parseAddress(oAtm.getString(DB.tx_email));
362         String JavaDoc sRecType = oAtm.getStringNull(DB.tp_recipient,"to");
363         if (sRecType.equalsIgnoreCase("to"))
364           oSentMsg.setRecipient(Message.RecipientType.TO, oRec);
365         else if (sRecType.equalsIgnoreCase("cc"))
366           oSentMsg.setRecipient(Message.RecipientType.CC, oRec);
367         else
368           oSentMsg.setRecipient(Message.RecipientType.BCC, oRec);
369       } else {
370         if (DebugFile.trace) DebugFile.writeln("tx_email is null");
371       }
372
373       // Set From and Reply-To addresses
374
oSentMsg.addFrom(aFrom);
375       oSentMsg.setReplyTo(aReply);
376
377       // Send message here
378
oHndlr.sendMessage(oSentMsg);
379
380     } catch (Exception JavaDoc e) {
381       if (DebugFile.trace) {
382         DebugFile.writeStackTrace(e);
383         DebugFile.write("\n");
384         DebugFile.decIdent();
385         DebugFile.writeln("End MimeSender.process("+oAtm.getString(DB.gu_job)+":"+String.valueOf(oAtm.getInt(DB.pg_atom))+") : abnormal process termination");
386       }
387       throw new MessagingException JavaDoc(e.getMessage(),e);
388     } finally {
389       // Decrement de count of atoms pending of processing at this job
390
if (0==--iPendingAtoms) {
391         free();
392       } // fi (iPendingAtoms==0)
393
}
394
395     if (DebugFile.trace) {
396       DebugFile.writeln("End MimeSender.process("+oAtm.getString(DB.gu_job)+":"+String.valueOf(oAtm.getInt(DB.pg_atom))+")");
397       DebugFile.decIdent();
398     }
399
400     return null;
401  } // process
402

403  // ----------------------------------------------------------------------------
404

405  public static MimeSender newInstance(JDCConnection oConn, String JavaDoc sProfile, String JavaDoc sIdWrkA,
406                                       String JavaDoc sGuMsg, String JavaDoc sIdMsg,
407                                       String JavaDoc sGuUser, String JavaDoc sGuAccount,
408                                       boolean bIsPersonalizedMail,
409                                       String JavaDoc sTxTitle)
410    throws SQLException JavaDoc {
411    MimeSender oJob = new MimeSender();
412
413    if (DebugFile.trace) {
414      DebugFile.writeln("Begin MimeSender.newInstance(JDCConnection, "+sProfile+", "+sIdWrkA+", "+sGuMsg+", "+sIdMsg+", "+sGuUser+", "+sGuAccount+", "+String.valueOf(bIsPersonalizedMail)+", "+sTxTitle+")");
415      DebugFile.incIdent();
416    }
417
418    oJob.put(DB.gu_workarea, sIdWrkA);
419    oJob.put(DB.gu_writer, sGuUser);
420    oJob.put(DB.id_command, "SEND");
421    oJob.put(DB.tl_job, Gadgets.left(sTxTitle,100));
422    oJob.put(DB.tx_parameters, "profile:"+sProfile+
423                               ",id:"+sIdMsg+
424                               ",message:"+sGuMsg+
425                               ",account:"+sGuAccount+
426                               ",personalized:"+String.valueOf(bIsPersonalizedMail));
427    oJob.store(oConn);
428
429    if (DebugFile.trace) {
430      DebugFile.writeln("End MimeSender.newInstance() " + oJob.getStringNull(DB.gu_job,"null"));
431      DebugFile.decIdent();
432    }
433
434    return oJob;
435  }
436
437 } // MimeSender
438
Popular Tags