/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.mail;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.mail.Session;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.spi.ObjectFactory;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class MailSessionObjectFactory implements ObjectFactory {

    /**
     * jndi-name => session
     */
    private static Map sessions = new HashMap();

    public static void addMailSession(String name, Session session) {
        sessions.put(getAbsoluteName(name), session);
    }

    public static void removeMailSession(String name) {
        sessions.remove(getAbsoluteName(name));
    }

    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {
        String _name = getAbsoluteName(name.toString());
        if(!sessions.containsKey(_name)) {
            throw new Exception("mail service with jndi name " + name.toString() + " not started.");
        }
        return sessions.get(_name);
    }

    private static String getAbsoluteName(String name) {
        if(!name.startsWith("/")) {
            return "/" + name;
        }
        return name;
    }

    public static void main(String[] args) {

    }
}
