1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.mail.util;
16  
17  import com.liferay.portal.kernel.jndi.JNDIUtil;
18  import com.liferay.portal.kernel.log.Log;
19  import com.liferay.portal.kernel.log.LogFactoryUtil;
20  import com.liferay.portal.kernel.util.SortedProperties;
21  import com.liferay.portal.kernel.util.Validator;
22  import com.liferay.portal.util.PropsUtil;
23  
24  import java.util.Properties;
25  
26  import javax.mail.Session;
27  
28  import javax.naming.InitialContext;
29  
30  import org.springframework.beans.factory.config.AbstractFactoryBean;
31  
32  /**
33   * <a href="MailSessionFactoryBean.java.html"><b><i>View Source</i></b></a>
34   *
35   * @author Brian Wing Shun Chan
36   */
37  public class MailSessionFactoryBean extends AbstractFactoryBean<Session> {
38  
39      public Class<Session> getObjectType() {
40          return Session.class;
41      }
42  
43      public void setPropertyPrefix(String propertyPrefix) {
44          _propertyPrefix = propertyPrefix;
45      }
46  
47      protected Session createInstance() throws Exception {
48          Properties properties = PropsUtil.getProperties(
49              _propertyPrefix, true);
50  
51          String jndiName = properties.getProperty("jndi.name");
52  
53          if (Validator.isNotNull(jndiName)) {
54              try {
55                  return (Session)JNDIUtil.lookup(new InitialContext(), jndiName);
56              }
57              catch (Exception e) {
58                  _log.error("Unable to lookup " + jndiName, e);
59              }
60          }
61  
62          Session session = Session.getInstance(properties);
63  
64          if (_log.isDebugEnabled()) {
65              session.setDebug(true);
66  
67              SortedProperties sortedProperties = new SortedProperties(
68                  session.getProperties());
69  
70              _log.debug("Properties for prefix " + _propertyPrefix);
71  
72              sortedProperties.list(System.out);
73          }
74  
75          return session;
76      }
77  
78      private static Log _log = LogFactoryUtil.getLog(
79          MailSessionFactoryBean.class);
80  
81      private String _propertyPrefix;
82  
83  }