KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2   Copyright (C) 2005 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 java.util.Properties JavaDoc;
36 import java.util.Iterator JavaDoc;
37
38 import java.security.Security JavaDoc;
39
40 import javax.mail.AuthenticationFailedException JavaDoc;
41 import javax.mail.NoSuchProviderException JavaDoc;
42 import javax.mail.MessagingException JavaDoc;
43 import javax.mail.internet.ParseException JavaDoc;
44 import javax.mail.SendFailedException JavaDoc;
45 import javax.mail.URLName JavaDoc;
46 import javax.mail.Session JavaDoc;
47 import javax.mail.Address JavaDoc;
48 import javax.mail.Message JavaDoc;
49 import javax.mail.Store JavaDoc;
50 import javax.mail.Transport JavaDoc;
51 import javax.mail.Folder JavaDoc;
52
53 import com.sun.net.ssl.internal.ssl.Provider;
54
55 import com.knowgate.debug.DebugFile;
56 import com.knowgate.dataobjs.DB;
57
58 /**
59  * <p>A wrapper around javax.mail.Store and javax.mail.Transport</p>
60  * @author Sergio Montoro Ten
61  * @version 1.0
62  */

63 public class SessionHandler {
64
65   private String JavaDoc sInAccountName;
66   private String JavaDoc sInAuthStr;
67   private String JavaDoc sOutAccountName;
68   private String JavaDoc sOutAuthStr;
69   private String JavaDoc sInHostName;
70   private String JavaDoc sOutHostName;
71   private String JavaDoc sMBoxDir;
72   private Properties JavaDoc oProps;
73   private URLName JavaDoc oURLSession;
74   private Session JavaDoc oMailSession;
75   private Session JavaDoc oSmtpSession;
76   private Store JavaDoc oMailStore;
77   private Transport JavaDoc oMailTransport;
78   private boolean bIsStoreConnected;
79   private boolean bIsTransportConnected;
80   private boolean bIncomingSSL;
81   private boolean bOutgoingSSL;
82
83   // ---------------------------------------------------------------------------
84

85   /**
86    * Default constructor
87    */

88   public SessionHandler() {
89     bIsStoreConnected = bIsTransportConnected = false;
90     oMailTransport = null;
91     oMailStore = null;
92     oProps = null;
93     sOutAccountName = sOutAuthStr = sInAccountName = sInAuthStr = sInHostName = sOutHostName = sMBoxDir = null;
94     oMailSession = null;
95     bOutgoingSSL = bIncomingSSL=false;
96   }
97
98   // ---------------------------------------------------------------------------
99

100   /**
101    * <p>Create instance taking data from a MailAccount</p>
102    * The data of MailAccount stored at k_user_mail table is used for initializing
103    * the connection properties
104    * @param oAccount MailAccount
105    */

106   public SessionHandler(MailAccount oAccount) {
107     String JavaDoc sProtocol;
108     oMailStore = null;
109     oMailTransport = null;
110     bIsStoreConnected = bIsTransportConnected = false;
111     sInAccountName=oAccount.getStringNull(DB.incoming_account,null);
112     sInAuthStr=oAccount.getStringNull(DB.incoming_password,null);
113     sOutAccountName=oAccount.getStringNull(DB.outgoing_account,null);
114     sOutAuthStr=oAccount.getStringNull(DB.outgoing_password,null);
115     sInHostName=oAccount.getStringNull(DB.incoming_server,null);
116     sOutHostName=oAccount.getStringNull(DB.outgoing_server,null);
117     if (!oAccount.isNull(DB.incoming_ssl))
118       bIncomingSSL = (oAccount.getShort(DB.incoming_ssl)==(short)1);
119     if (!oAccount.isNull(DB.outgoing_ssl))
120       bOutgoingSSL = (oAccount.getShort(DB.outgoing_ssl)==(short)1);
121
122     oProps = new Properties JavaDoc();
123
124     sProtocol = oAccount.getStringNull(DB.incoming_protocol,"pop3");
125     oProps.put("mail.store.protocol", sProtocol);
126     oProps.put("mail."+sProtocol+".host", oAccount.getStringNull(DB.incoming_server,"localhost"));
127     if (oAccount.isNull(DB.incoming_port))
128       oProps.put("mail."+sProtocol+".port", (bIncomingSSL ? "995" : "110"));
129     else
130       oProps.put("mail."+sProtocol+".port", String.valueOf(oAccount.getShort(DB.incoming_port)));
131     if (bIncomingSSL) {
132       oProps.setProperty( "mail."+sProtocol+".socketFactory.class", "javax.net.ssl.SSLSocketFactory");
133       oProps.setProperty("mail."+sProtocol+".socketFactory.port", oProps.getProperty("mail."+sProtocol+".port"));
134       oProps.setProperty("mail."+sProtocol+".socketFactory.fallback", "false");
135     }
136
137     sProtocol = oAccount.getStringNull(DB.outgoing_protocol,"smtp");
138     oProps.put("mail.transport.protocol", sProtocol);
139     oProps.put("mail."+sProtocol+".host", oAccount.getStringNull(DB.outgoing_server,"localhost"));
140     if (oAccount.isNull(DB.outgoing_port))
141       oProps.put("mail."+sProtocol+".port", (bOutgoingSSL ? "465" : "25"));
142     else
143       oProps.put("mail."+sProtocol+".port", String.valueOf(oAccount.getShort(DB.outgoing_port)));
144     if (bOutgoingSSL) {
145       oProps.setProperty( "mail."+sProtocol+".socketFactory.class", "javax.net.ssl.SSLSocketFactory");
146       oProps.setProperty("mail."+sProtocol+".socketFactory.port", oProps.getProperty("mail."+sProtocol+".port"));
147       oProps.setProperty("mail."+sProtocol+".socketFactory.fallback", "false");
148     }
149
150     if (!oAccount.isNull(DB.outgoing_account) && !oAccount.isNull(DB.outgoing_password)) {
151       oProps.put("mail."+sProtocol+".auth", "true");
152     }
153
154     if (bIncomingSSL || bOutgoingSSL) {
155       Security.addProvider(new Provider());
156       if (bOutgoingSSL)
157         oProps.put("mail."+oAccount.getStringNull(DB.outgoing_protocol,"smtp")+".starttls.enable","true");
158     }
159
160     if (DebugFile.trace) {
161       DebugFile.writeln("new SessionHandler(oAccount="+oAccount.getStringNull(DB.gu_account,"null")+")");
162       DebugFile.incIdent();
163       Iterator JavaDoc oIter = oProps.keySet().iterator();
164       while (oIter.hasNext()) {
165         String JavaDoc sKey = (String JavaDoc) oIter.next();
166         DebugFile.writeln(sKey+"="+oProps.getProperty(sKey));
167       } // wend
168
DebugFile.decIdent();
169     }
170   }
171
172   // ---------------------------------------------------------------------------
173

174   /**
175    * <p>Create instance taking data from a MailAccount and set local directory for MBOX files</p>
176    * @param oAccount MailAccount
177    * @param sMBoxDirectory String
178    */

179   public SessionHandler(MailAccount oAccount, String JavaDoc sMBoxDirectory) {
180     this(oAccount);
181     sMBoxDir = sMBoxDirectory;
182   }
183
184   // ---------------------------------------------------------------------------
185

186   /**
187    * <p>Get column incoming_account of k_user_mail</p>
188    * @return String account name or <b>null</b> if this instance has not been
189    * initialized from a MailAccount object
190    */

191   public String JavaDoc getAccountName() {
192     return sInAccountName;
193   }
194
195   // ---------------------------------------------------------------------------
196

197   public void setAccountName(String JavaDoc aAccName) {
198     sInAccountName=aAccName;
199   }
200
201   // ---------------------------------------------------------------------------
202

203   /**
204    * <p>Get column incoming_password of k_user_mail</p>
205    * @return String password or <b>null</b> if this instance has not been
206    * initialized from a MailAccount object
207    */

208   public String JavaDoc getAuthStr() {
209     return sInAuthStr;
210   }
211
212   // ---------------------------------------------------------------------------
213

214   public void setAuthStr(String JavaDoc aAutStr) {
215     sInAuthStr=aAutStr;
216   }
217
218   // ---------------------------------------------------------------------------
219

220   /**
221    * <p>Get column incoming_server of k_user_mail</p>
222    * @return String
223    */

224   public String JavaDoc getHostName() {
225     return sInHostName;
226   }
227
228   // ---------------------------------------------------------------------------
229

230   public void setHostName(String JavaDoc sName) {
231     sInHostName=sName;
232   }
233
234   // ---------------------------------------------------------------------------
235

236   public String JavaDoc getMBoxDirectory() {
237     return sMBoxDir;
238   }
239
240   // ---------------------------------------------------------------------------
241

242   public void setMBoxDirectory(String JavaDoc sDir) {
243     sMBoxDir=sDir;
244   }
245
246   // ---------------------------------------------------------------------------
247

248   public Properties JavaDoc getProperties() {
249     return oProps;
250   }
251
252   // ---------------------------------------------------------------------------
253

254   public void setProperties(Properties JavaDoc oPropties) {
255     oProps=oPropties;
256   }
257
258   // ---------------------------------------------------------------------------
259

260   /**
261    * <p>Get incoming mail server Session</p>
262    * This method calls JavaMail Session.getInstance() method if neccesary,
263    * using properties currently set at this instance and SilentAuthenticator as
264    * Authenticator subclass
265    * @return javax.mail.Session
266    * @throws IllegalStateException
267    * @throws NullPointerException
268    */

269   public Session JavaDoc getSession() throws IllegalStateException JavaDoc {
270     if (DebugFile.trace) {
271       DebugFile.writeln("Begin SessionHandler.getSession()");
272       DebugFile.incIdent();
273     }
274     if (null==oMailSession) {
275       if (null==oProps) {
276         if (DebugFile.trace) DebugFile.decIdent();
277         throw new IllegalStateException JavaDoc("SessionHandler properties not set");
278       }
279       if (null==sInAccountName) {
280         if (DebugFile.trace) DebugFile.decIdent();
281         throw new NullPointerException JavaDoc("SessionHandler account name not set");
282       }
283       if (DebugFile.trace) DebugFile.writeln("new SilentAuthenticator("+sInAccountName+", ...)");
284       SilentAuthenticator oAuth = new SilentAuthenticator(sInAccountName, sInAuthStr);
285       if (DebugFile.trace) DebugFile.writeln("Session.getInstance([Properties],[SilentAuthenticator])");
286       oMailSession = Session.getInstance(oProps, oAuth);
287     }
288     if (DebugFile.trace) {
289       DebugFile.decIdent();
290       DebugFile.writeln("End SessionHandler.getSession() : " + oMailSession);
291     }
292     return oMailSession;
293   } // getSession
294

295   // ---------------------------------------------------------------------------
296

297   /**
298    * <p>Get outgoing mail server Session</p>
299    * This method calls JavaMail Session.getInstance() method if neccesary,
300    * using properties currently set at this instance and SilentAuthenticator as
301    * Authenticator subclass
302    * @return javax.mail.Session
303    * @throws IllegalStateException
304    * @throws NullPointerException
305    */

306   public Session JavaDoc getSmtpSession() throws IllegalStateException JavaDoc {
307     if (DebugFile.trace) {
308       DebugFile.writeln("Begin SessionHandler.getSmtpSession()");
309       DebugFile.incIdent();
310     }
311     if (null==oSmtpSession) {
312       if (null==oProps) {
313         if (DebugFile.trace) DebugFile.decIdent();
314         throw new IllegalStateException JavaDoc("SessionHandler properties not set");
315       }
316       if (null==sOutAccountName) {
317         if (DebugFile.trace) DebugFile.decIdent();
318         throw new NullPointerException JavaDoc("SessionHandler account name not set");
319       }
320       if (DebugFile.trace) DebugFile.writeln("new SilentAuthenticator("+sOutAccountName+", ...)");
321       SilentAuthenticator oAuth = new SilentAuthenticator(sOutAccountName, sOutAuthStr);
322       if (DebugFile.trace) DebugFile.writeln("Session.getInstance([Properties],[SilentAuthenticator])");
323       oSmtpSession = Session.getInstance(oProps, oAuth);
324     }
325     if (DebugFile.trace) {
326       DebugFile.decIdent();
327       DebugFile.writeln("End SessionHandler.getSmtpSession() : " + oSmtpSession);
328     }
329     return oSmtpSession;
330   } // getSmtpSession
331

332   // ---------------------------------------------------------------------------
333

334   /**
335    * <p>Get Store</p>
336    * This method calls Session.getStore() and Store.connect() if neccesary.
337    * @return javax.mail.Store
338    * @throws NoSuchProviderException
339    * @throws MessagingException
340    */

341   public Store JavaDoc getStore() throws NoSuchProviderException JavaDoc, MessagingException JavaDoc {
342     if (DebugFile.trace) {
343       DebugFile.writeln("Begin SessionHandler.getStore()");
344       DebugFile.incIdent();
345     }
346     if (null==oMailStore) {
347       if (null==sInHostName) {
348         if (DebugFile.trace) DebugFile.decIdent();
349         throw new NullPointerException JavaDoc("SessionHandler host name not set");
350       }
351       if (DebugFile.trace) DebugFile.writeln("Session.getStore()");
352       oMailStore = getSession().getStore();
353       if (DebugFile.trace) DebugFile.writeln("Store.connect("+sInHostName+","+sInAccountName+", ...)");
354       getStore().connect(sInHostName, sInAccountName, sInAuthStr);
355       bIsStoreConnected = true;
356     }
357     if (DebugFile.trace) {
358       DebugFile.decIdent();
359       DebugFile.writeln("End SessionHandler.getStore() : " + oMailStore);
360     }
361     return oMailStore;
362   } // getStore()
363

364   // ---------------------------------------------------------------------------
365

366   /**
367    * <p>Get Transport</p>
368    * This method calls Session.getTransport() and Transport.connect() if neccesary
369    * @return javax.mail.Transport
370    * @throws NoSuchProviderException
371    * @throws MessagingException
372    */

373   public Transport JavaDoc getTransport()
374     throws NoSuchProviderException JavaDoc,MessagingException JavaDoc {
375     if (DebugFile.trace) {
376       DebugFile.writeln("Begin SessionHandler.getTransport()");
377       DebugFile.incIdent();
378     }
379     if (null==oMailTransport) {
380       if (DebugFile.trace) DebugFile.writeln("Session.getTransport()");
381       oMailTransport = getSmtpSession().getTransport();
382       oMailTransport.connect();
383     }
384     if (DebugFile.trace) {
385       DebugFile.decIdent();
386       DebugFile.writeln("End SessionHandler.getTransport() : " + oMailTransport);
387     }
388     return oMailTransport;
389   } // getTransport
390

391   // ---------------------------------------------------------------------------
392

393   public Folder JavaDoc getFolder(String JavaDoc sFolderName)
394       throws NoSuchProviderException JavaDoc,MessagingException JavaDoc {
395     getStore();
396     if (null==oMailStore)
397       return null;
398     else {
399       return oMailStore.getFolder(sFolderName);
400     }
401   } // getFolder
402

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

405   public URLName JavaDoc getURL() {
406     if (null==oURLSession) {
407       if (DebugFile.trace) DebugFile.writeln("new URLName(jdbc://, "+sInHostName+", -1, "+sMBoxDir+", "+sInAccountName+", ...)");
408       oURLSession = new URLName JavaDoc("jdbc://", sInHostName, -1, sMBoxDir, sInAccountName, sInAuthStr);
409     }
410     return oURLSession;
411   }
412
413   // ---------------------------------------------------------------------------
414

415   public boolean isStoreConnected() {
416     return bIsStoreConnected;
417   }
418
419   // ---------------------------------------------------------------------------
420

421   public boolean isTransportConnected() {
422     return bIsTransportConnected;
423   }
424
425   // ---------------------------------------------------------------------------
426

427   public void sendMessage(Message JavaDoc oMsg)
428     throws NoSuchProviderException JavaDoc,SendFailedException JavaDoc,ParseException JavaDoc,
429            MessagingException JavaDoc,NullPointerException JavaDoc {
430     if (DebugFile.trace) {
431       DebugFile.writeln("Begin SessionHandler.sendMessage([Message])");
432       DebugFile.incIdent();
433     }
434     oMsg.setSentDate(new java.util.Date JavaDoc());
435     if (DebugFile.trace) DebugFile.writeln("Transport.send(Message)");
436     Transport.send(oMsg);
437     if (DebugFile.trace) {
438       DebugFile.decIdent();
439       DebugFile.writeln("End SessionHandler.sendMessage()");
440     }
441   } // sendMessage
442

443   // ---------------------------------------------------------------------------
444

445   public void sendMessage(Message JavaDoc oMsg, Address JavaDoc[] aAddrs)
446     throws NoSuchProviderException JavaDoc,SendFailedException JavaDoc,ParseException JavaDoc,
447            MessagingException JavaDoc,NullPointerException JavaDoc {
448     if (DebugFile.trace) {
449       DebugFile.writeln("Begin SessionHandler.sendMessage([Message],Address[])");
450       DebugFile.incIdent();
451     }
452     oMsg.setSentDate(new java.util.Date JavaDoc());
453     if (DebugFile.trace) DebugFile.writeln("Transport.send(Message,Address[])");
454     Transport.send(oMsg,aAddrs);
455     if (DebugFile.trace) {
456       DebugFile.decIdent();
457       DebugFile.writeln("End SessionHandler.sendMessage()");
458     }
459   } // sendMessage
460

461   // ---------------------------------------------------------------------------
462

463   public void sendMessage (Message JavaDoc oMsg,
464                            Address JavaDoc[] aAdrFrom, Address JavaDoc[] aAdrReply,
465                            Address JavaDoc[] aAdrTo, Address JavaDoc[] aAdrCc, Address JavaDoc[] aAdrBcc)
466     throws NoSuchProviderException JavaDoc,SendFailedException JavaDoc,ParseException JavaDoc,
467            MessagingException JavaDoc,NullPointerException JavaDoc {
468     if (DebugFile.trace) {
469       DebugFile.writeln("Begin SessionHandler.sendMessage([Message],Address[],Address[],Address[],Address[],Address[])");
470       DebugFile.incIdent();
471     }
472     oMsg.addFrom(aAdrFrom);
473     if (null==aAdrReply)
474       oMsg.setReplyTo(aAdrReply);
475     else
476       oMsg.setReplyTo(aAdrFrom);
477     if (aAdrTo!=null) oMsg.addRecipients(javax.mail.Message.RecipientType.TO, aAdrTo);
478     if (aAdrCc!=null) oMsg.addRecipients(javax.mail.Message.RecipientType.CC, aAdrCc);
479     if (aAdrBcc!=null) oMsg.addRecipients(javax.mail.Message.RecipientType.BCC, aAdrBcc);
480     oMsg.setSentDate(new java.util.Date JavaDoc());
481     if (DebugFile.trace) DebugFile.writeln("Transport.send(Message)");
482     Transport.send(oMsg);
483     if (DebugFile.trace) {
484       DebugFile.decIdent();
485       DebugFile.writeln("End SessionHandler.sendMessage()");
486     }
487   } // sendMessage
488

489   // ---------------------------------------------------------------------------
490

491   public void close()
492     throws MessagingException JavaDoc {
493     if (DebugFile.trace) {
494       DebugFile.writeln("Begin SessionHandler.close()");
495       DebugFile.incIdent();
496     }
497     if (null!=oMailStore) {
498       if (isStoreConnected()) {
499         if (DebugFile.trace) DebugFile.writeln("Store.close()");
500         oMailStore.close();
501       }
502       oMailStore = null;
503     }
504     if (null!=oMailTransport) {
505       if (isTransportConnected()) {
506         if (DebugFile.trace) DebugFile.writeln("Transport.close()");
507         oMailTransport.close();
508       }
509       oMailTransport=null;
510     }
511     oMailSession=null;
512     oSmtpSession=null;
513     if (DebugFile.trace) {
514       DebugFile.decIdent();
515       DebugFile.writeln("End SessionHandler.close()");
516     }
517   } // close
518

519 }
520
Popular Tags