001/*
002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     matic
016 */
017package org.nuxeo.ecm.platform.ec.notification.email;
018
019import java.security.AccessController;
020import java.security.PrivilegedAction;
021import java.util.Enumeration;
022import java.util.Hashtable;
023import java.util.Properties;
024
025import javax.mail.Session;
026import javax.naming.Context;
027import javax.naming.Name;
028import javax.naming.RefAddr;
029import javax.naming.Reference;
030import javax.naming.spi.ObjectFactory;
031
032/**
033 * @author matic
034 */
035public class EmailResourceFactory implements ObjectFactory {
036
037    @Override
038    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) {
039        final Reference ref = (Reference) obj;
040        if (!ref.getClassName().equals("javax.mail.Session"))
041            return (null);
042        ref.getAll();
043        final Properties properties = toProperties(ref.getAll());
044        return AccessController.doPrivileged(new PrivilegedAction<Session>() {
045            public Session run() {
046                return EmailHelper.newSession(properties);
047            }
048        });
049
050    }
051
052    protected Properties toProperties(Enumeration<RefAddr> attributes) {
053        Properties props = new Properties();
054        while (attributes.hasMoreElements()) {
055            RefAddr attribute = attributes.nextElement();
056            if ("factory".equals(attribute.getType())) {
057                continue;
058            }
059            props.put(attribute.getType(), attribute.getContent());
060        }
061        return props;
062    }
063}