KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ivata > groupware > business > mail > server > JavaMailServer


1 /*
2  * Copyright (c) 2001 - 2005 ivata limited.
3  * All rights reserved.
4  * -----------------------------------------------------------------------------
5  * ivata groupware may be redistributed under the GNU General Public
6  * License as published by the Free Software Foundation;
7  * version 2 of the License.
8  *
9  * These programs are free software; you can redistribute them and/or
10  * modify them under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; version 2 of the License.
12  *
13  * These programs are distributed in the hope that they will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16  *
17  * See the GNU General Public License in the file LICENSE.txt for more
18  * details.
19  *
20  * If you would like a copy of the GNU General Public License write to
21  *
22  * Free Software Foundation, Inc.
23  * 59 Temple Place - Suite 330
24  * Boston, MA 02111-1307, USA.
25  *
26  *
27  * To arrange commercial support and licensing, contact ivata at
28  * http://www.ivata.com/contact.jsp
29  * -----------------------------------------------------------------------------
30  * $Log: JavaMailServer.java,v $
31  * Revision 1.3 2005/04/10 19:30:11 colinmacleod
32  * Fixed exception message when login fails
33  * (added missing quote).
34  *
35  * Revision 1.2 2005/04/09 17:20:01 colinmacleod
36  * Changed copyright text to GPL v2 explicitly.
37  *
38  * Revision 1.1.1.1 2005/03/10 17:51:22 colinmacleod
39  * Restructured ivata op around Hibernate/PicoContainer.
40  * Renamed ivata groupware.
41  *
42  * -----------------------------------------------------------------------------
43  */

44 package com.ivata.groupware.business.mail.server;
45
46 import java.util.Properties JavaDoc;
47
48 import javax.mail.AuthenticationFailedException JavaDoc;
49 import javax.mail.Folder JavaDoc;
50 import javax.mail.MessagingException JavaDoc;
51 import javax.mail.NoSuchProviderException JavaDoc;
52 import javax.mail.Session JavaDoc;
53 import javax.mail.Store JavaDoc;
54
55 import org.apache.log4j.Logger;
56 import org.picocontainer.MutablePicoContainer;
57 import org.picocontainer.PicoContainer;
58 import org.picocontainer.defaults.DefaultPicoContainer;
59
60 import com.ivata.groupware.admin.security.server.PlainTextSecuritySession;
61 import com.ivata.groupware.admin.security.server.SecuritySession;
62 import com.ivata.groupware.admin.security.user.UserDO;
63 import com.ivata.groupware.admin.setting.Settings;
64 import com.ivata.groupware.business.addressbook.AddressBook;
65 import com.ivata.groupware.business.addressbook.person.PersonDO;
66 import com.ivata.groupware.business.mail.session.MailSession;
67 import com.ivata.groupware.container.PicoContainerFactory;
68 import com.ivata.mask.util.SystemException;
69
70
71 /**
72  * <p>Uses <strong>JavaMail</strong> methods to actually log into the mail server.</p>
73  *
74  * @since ivata groupware 0.10 (2005-02-21)
75  * @author Colin MacLeod
76  * <a HREF='mailto:colin.macleod@ivata.com'>colin.macleod@ivata.com</a>
77  * @version $Revision: 1.3 $
78  */

79 public abstract class JavaMailServer implements MailServer {
80     private static Logger log = Logger.getLogger(JavaMailServer.class);
81     private AddressBook addressBook;
82     private Settings settings;
83     public JavaMailServer(final AddressBook addressBookParam,
84             final Settings settingsParam) {
85         this.addressBook = addressBookParam;
86         this.settings = settingsParam;
87     }
88     /**
89      * <p>Check the password for a user. Throws {@link GroupwareException
90      * GroupwareException} if the password is incorrect.</p>
91      *
92      * @param userName the user for whom to set/change the password.
93      * @param password the password to check. If this password is
94      * incorrect, an
95      * <code>AuthenticationException</code> is thrown.
96      */

97     public void checkPassword(final SecuritySession securitySession,
98             final String JavaDoc userName, final String JavaDoc password) throws SystemException {
99         PicoContainer globalContainer = PicoContainerFactory.getInstance()
100             .getGlobalContainer();
101         MutablePicoContainer sessionContainer = new DefaultPicoContainer(globalContainer);
102         SecuritySession guestSession = loginGuest();
103         PersonDO person = addressBook.findPersonByUserName(guestSession, userName);
104         UserDO user = person.getUser();
105         MailSession mailSession = new MailSession(sessionContainer, user);
106         user.setName(user.getName().toLowerCase());
107
108         Properties JavaDoc mailProperties = new Properties JavaDoc();
109         String JavaDoc hostName;
110
111         try {
112             mailProperties.setProperty("mail.host",
113                 (hostName = settings.getStringSetting(mailSession,
114                     "emailHost", null)));
115             mailProperties.setProperty("mail.smtp.host",
116                 settings.getStringSetting(mailSession,
117                     "emailHostSmtp", null));
118         } catch (Exception JavaDoc e) {
119             throw new SystemException("ERROR: Exception in ScriptMailServer",
120                 e);
121         }
122         mailProperties.setProperty("mail.user",
123                 getSystemUserName(securitySession, user.getName()));
124
125         if (user.getName().equals("emergency")) {
126             mailProperties.setProperty("mail.from", "emergency@ivata.com");
127         } else {
128             mailProperties.setProperty("mail.from", person.getEmailAddress());
129         }
130
131
132         boolean isConnected = false;
133         try {
134             mailSession.login(password, mailProperties);
135             isConnected = true;
136         } catch (AuthenticationFailedException JavaDoc e) {
137             throw new SystemException(e);
138         } catch (NoSuchProviderException JavaDoc e) {
139             throw new SystemException(
140                 "ERROR: "
141                 + e.getClass().getName()
142                 + " connecting using imap to "
143                 + mailProperties.getProperty("mail.host"),
144                 e);
145         } catch (MessagingException JavaDoc e) {
146             throw new SystemException(
147                 "ERROR: "
148                 + e.getClass().getName()
149                 + " connecting using imap to "
150                 + mailProperties.getProperty("mail.host"),
151                 e);
152         } catch (Exception JavaDoc e) {
153             throw new SystemException(
154                 "ERROR: "
155                 + e.getClass().getName()
156                 + " connecting using imap to "
157                 + mailProperties.getProperty("mail.host"),
158                 e);
159         }
160     }
161
162     /**
163      * <p>Helper. Get the store from the mail session and connect it.</p>
164      */

165     public Store JavaDoc connectStore(final MailSession mailSession)
166             throws SystemException {
167         try {
168             Session JavaDoc javaMailSession;
169             try {
170                 javaMailSession = mailSession.getJavaMailSession();
171             } catch (java.security.NoSuchProviderException JavaDoc e1) {
172                 throw new SystemException(e1);
173             }
174             Store JavaDoc store = javaMailSession.getStore("imap");
175             if (store == null) {
176                 throw new SystemException(
177                     "ERROR in MailBean: could not access the mail store");
178             }
179             if (!store.isConnected()) {
180                 store.connect();
181             }
182             return store;
183         } catch (MessagingException JavaDoc e) {
184             throw new SystemException(e);
185         }
186     }
187     /**
188      * Wrapper for <code>Store.getFolder</code> to get around the fact that
189      * courier/cyrus imap prefixes all "personal namespace" folder names with
190      * "INBOX".
191      *
192      * @param securitySession used to access the settings.
193      * @param store valid, connected store.
194      * @param name name of the folder you want to open.
195      * @return folder for the name you passed.
196      * @throws SystemException if the settings cannot be accessed, or there is
197      * any exception accessing the store.
198      */

199     public Folder JavaDoc getFolder(final SecuritySession securitySession,
200             final Store JavaDoc store, final String JavaDoc name)
201             throws SystemException {
202         assert (securitySession != null);
203         assert (store != null);
204         assert (store.isConnected());
205         assert (name != null);
206         String JavaDoc prefix;
207         if ("inbox".equalsIgnoreCase(name)) {
208             prefix = "";
209         } else {
210             prefix = settings.getStringSetting(securitySession,
211                     "emailFolderNamespace", securitySession.getUser());
212         }
213         String JavaDoc fullFolderName = prefix + name;
214         try {
215             return store.getFolder(fullFolderName);
216         } catch (MessagingException JavaDoc e) {
217             throw new SystemException(e);
218         }
219     }
220     /**
221      * <p>Get the time the specified mail folder was last modified as a
222      * <code>long</code>. This can then be saved and compared to
223      * subsequent
224      * calls of this method to see if the folder has changed.</p>
225      *
226      * @param userName the name of the user for whom to locate the folder.
227      * @param folderName the name of the folder to locate.
228      * @return operating system specific timestamp indicating when the
229      * folder was last changed.
230      * @throws SystemException if the folder doesn't exists or there
231      * is an application problem retrieving the modified time.
232      */

233     public boolean hasNewMessages(final SecuritySession securitySession,
234             final String JavaDoc userName,
235             final String JavaDoc folderName)
236             throws SystemException {
237         assert (securitySession instanceof MailSession);
238         MailSession mailSession = (MailSession) securitySession;
239
240         Store JavaDoc store = connectStore(mailSession);
241         try {
242             String JavaDoc sentFolderName = settings.getStringSetting(
243                     mailSession,
244                     "emailFolderSent",
245                     mailSession.getUser());
246             Folder JavaDoc folder = getFolder(mailSession, store, folderName);
247             return folder.hasNewMessages();
248         } catch(MessagingException JavaDoc e) {
249             throw new SystemException(e);
250         } finally {
251             try {
252                 store.close();
253             } catch(MessagingException JavaDoc e) {
254                 log.error("Closing store.", e);
255             }
256         }
257     }
258
259     /**
260      * <p>Login to the mail server.</p>
261      *
262      * @see com.ivata.groupware.admin.security.session.SessionServer#login(String, String)
263      */

264     public SecuritySession login(final UserDO user,
265             final String JavaDoc password)
266             throws SystemException {
267         PicoContainer globalContainer = PicoContainerFactory.getInstance()
268             .getGlobalContainer();
269         MutablePicoContainer sessionContainer = new DefaultPicoContainer(globalContainer);
270         MailSession mailSession = new MailSession(sessionContainer, user);
271         sessionContainer.registerComponentInstance(SecuritySession.class, mailSession);
272
273         // all user names are lower case
274
if (user == null) {
275             throw new SystemException("ERROR in ScriptMailServer: user is null");
276         }
277         if (user.getName() == null) {
278             throw new SystemException("ERROR in ScriptMailServer: user name is null");
279         }
280         user.setName(user.getName().toLowerCase());
281
282         Properties JavaDoc mailProperties = new Properties JavaDoc();
283         String JavaDoc hostName;
284
285         try {
286             mailProperties.setProperty("mail.host",
287                 (hostName = settings.getStringSetting(mailSession,
288                     "emailHost", null)));
289             mailProperties.setProperty("mail.smtp.host",
290                 settings.getStringSetting(mailSession,
291                     "emailHostSmtp", null));
292         } catch (Exception JavaDoc e) {
293             throw new SystemException("ERROR: Exception in ScriptMailServer",
294                 e);
295         }
296         mailProperties.setProperty("mail.user",
297                 getSystemUserName(mailSession, user.getName()));
298
299         if (user.getName().equals("emergency")) {
300             mailProperties.setProperty("mail.from", "emergency@ivata.com");
301         } else {
302             // now check out this user's name and email address
303
PersonDO person = addressBook.findPersonByUserName(mailSession,
304                     user.getName());
305             mailProperties.setProperty("mail.from", person.getEmailAddress());
306         }
307
308
309         boolean isConnected = false;
310         try {
311             try {
312                 mailSession.login(password, mailProperties);
313                 isConnected = true;
314             } catch (AuthenticationFailedException JavaDoc e) {
315                 String JavaDoc logPassword = "**********";
316                 Boolean JavaDoc showPassword = settings.getBooleanSetting(mailSession,
317                         "siteLoginDebugPassword", null);
318                 if ((showPassword != null)
319                         && showPassword.booleanValue()) {
320                     logPassword = password;
321                 }
322                 throw new SystemException("Warning: could not connect user '"
323                     + mailProperties.getProperty("mail.user")
324                     + ", password '"
325                     + logPassword
326                     + "' to server '"
327                     + hostName
328                     + "'",
329                     e);
330             }
331         } catch (NoSuchProviderException JavaDoc e) {
332             throw new SystemException(
333                 "ERROR: "
334                 + e.getClass().getName()
335                 + " connecting using imap to "
336                 + mailProperties.getProperty("mail.host"),
337                 e);
338         } catch (MessagingException JavaDoc e) {
339             throw new SystemException(
340                 "ERROR: "
341                 + e.getClass().getName()
342                 + " connecting using imap to "
343                 + mailProperties.getProperty("mail.host"),
344                 e);
345         } catch (Exception JavaDoc e) {
346             throw new SystemException(
347                 "ERROR: "
348                 + e.getClass().getName()
349                 + " connecting using imap to "
350                 + mailProperties.getProperty("mail.host"),
351                 e);
352         }
353         mailSession.setPassword(password);
354         return mailSession;
355     }
356
357     /**
358      * @see com.ivata.groupware.admin.security.server.SecurityServer#loginGuest()
359      */

360     public SecuritySession loginGuest() throws SystemException {
361         PicoContainer globalContainer = PicoContainerFactory.getInstance()
362             .getGlobalContainer();
363         UserDO guestUser = new UserDO();
364         guestUser.setDeleted(false);
365         guestUser.setEnabled(true);
366         guestUser.setName("guest");
367         MutablePicoContainer sessionContainer = new DefaultPicoContainer(globalContainer);
368         SecuritySession session = new PlainTextSecuritySession(sessionContainer, guestUser);
369         sessionContainer.registerComponentInstance(SecuritySession.class, session);
370
371         return session;
372     }
373 }
374
Popular Tags