1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
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 {
38  
39      public Class<?> getObjectType() {
40          return Session.class;
41      }
42  
43      public void setPropertyPrefix(String propertyPrefix) {
44          _propertyPrefix = propertyPrefix;
45      }
46  
47      protected Object 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 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  }