001
014
015 package com.liferay.mail.util;
016
017 import com.liferay.portal.kernel.jndi.JNDIUtil;
018 import com.liferay.portal.kernel.log.Log;
019 import com.liferay.portal.kernel.log.LogFactoryUtil;
020 import com.liferay.portal.kernel.util.PropsKeys;
021 import com.liferay.portal.kernel.util.SortedProperties;
022 import com.liferay.portal.kernel.util.Validator;
023 import com.liferay.portal.util.PropsUtil;
024
025 import java.util.Properties;
026
027 import javax.mail.Session;
028
029 import javax.naming.Context;
030 import javax.naming.InitialContext;
031
032 import org.springframework.beans.factory.config.AbstractFactoryBean;
033
034
037 public class MailSessionFactoryBean extends AbstractFactoryBean<Session> {
038
039 @Override
040 public Class<Session> getObjectType() {
041 return Session.class;
042 }
043
044 public void setPropertyPrefix(String propertyPrefix) {
045 _propertyPrefix = propertyPrefix;
046 }
047
048 @Override
049 protected Session createInstance() throws Exception {
050 Properties properties = PropsUtil.getProperties(_propertyPrefix, true);
051
052 String jndiName = properties.getProperty("jndi.name");
053
054 if (Validator.isNotNull(jndiName)) {
055 try {
056 Properties jndiEnvironmentProperties = PropsUtil.getProperties(
057 PropsKeys.JNDI_ENVIRONMENT, true);
058
059 Context context = new InitialContext(jndiEnvironmentProperties);
060
061 return (Session)JNDIUtil.lookup(context, jndiName);
062 }
063 catch (Exception e) {
064 _log.error("Unable to lookup " + jndiName, e);
065 }
066 }
067
068 Session session = Session.getInstance(properties);
069
070 if (_log.isDebugEnabled()) {
071 session.setDebug(true);
072
073 SortedProperties sortedProperties = new SortedProperties(
074 session.getProperties());
075
076 _log.debug("Properties for prefix " + _propertyPrefix);
077
078 sortedProperties.list(System.out);
079 }
080
081 return session;
082 }
083
084 private static Log _log = LogFactoryUtil.getLog(
085 MailSessionFactoryBean.class);
086
087 private String _propertyPrefix;
088
089 }