Package org.cafesip.jiplet

Source Code of org.cafesip.jiplet.JipletContext

/*
* Created on Nov 8, 2004
*
* Copyright 2005 CafeSip.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.cafesip.jiplet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.LinkRef;
import javax.naming.NamingException;
import javax.naming.OperationNotSupportedException;
import javax.sip.RequestEvent;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.cafesip.jiplet.cma.SecurityConstraintManager;
import org.cafesip.jiplet.config.jip.ContextMapping;
import org.cafesip.jiplet.config.jip.EJBLocalRef;
import org.cafesip.jiplet.config.jip.EJBRef;
import org.cafesip.jiplet.config.jip.EnvEntry;
import org.cafesip.jiplet.config.jip.InitParam;
import org.cafesip.jiplet.config.jip.InitParams;
import org.cafesip.jiplet.config.jip.JipApplication;
import org.cafesip.jiplet.config.jip.JipletConfig;
import org.cafesip.jiplet.config.jip.JipletMapping;
import org.cafesip.jiplet.config.jip.Mapping;
import org.cafesip.jiplet.config.jip.ResourceEnvRef;
import org.cafesip.jiplet.config.jip.ResourceRef;
import org.cafesip.jiplet.jmxbeans.JipletElement;
import org.cafesip.jiplet.mapping.CriteriaMatch;
import org.cafesip.jiplet.mapping.MappingCompiler;
import org.cafesip.jiplet.naming.EnvEntryMetaData;
import org.cafesip.jiplet.naming.NamingUtil;

/**
* This class encapsulates the functions of a jiplet context. A context is a SIP
* application consisting of one or more jiplets, supporting classes and a
* descriptor (jip.xml). The jiplet container can host multiple contexts. Each
* context runs in its own "object space" and is completely isolated from other
* contexts. It is analogous to the web context in the servlet world. A context
* can be deployed as a single spr file or in exploded format. For more details,
*
* @see JipletContainer description.
*      <p>
*
*      The jiplet context also provides support for application-scope
*      variables. Application scope variables remain active during the
*      life-time of the context. Using the methods provided by the
*      ScopedVariable class (that this class extends), jiplets can create,
*      remove and retrieve application-scope variables.
*
* @author Becky McElroy & Amit Chatterjee
*
*/
public class JipletContext extends ScopedVariables implements
        JipletContextMBean
{
    public static final int CONTEXT_UNKNOWN = 0;

    private static final String CONTEXT_UNKNOWN_DESCR = "Unknown";

    public static final int CONTEXT_DEPLOYED = 1;

    private static final String CONTEXT_DEPLOYED_DESCR = "Deployed";

    public static final int CONTEXT_J2EE = 2;

    private static final String CONTEXT_J2EE_DESCR = "J2EE";

    private String context;

    private ClassLoader classLoader;

    private File contextRoot;

    private JipApplication config;

    private HashMap jiplets = new HashMap();

    private HashMap sessions = new HashMap();

    private int contextType = CONTEXT_UNKNOWN;

    public ObjectName MBEAN_NAME = null;

    private ArrayList criteriaConnectorsList = new ArrayList();

    private ArrayList jipletSelectionCriteria = new ArrayList();

    private ArrayList contextSelectionCriteria = new ArrayList();

    private ArrayList criteria = new ArrayList();

    private SecurityConstraintManager securityManager = new SecurityConstraintManager(
            this);

    private ClassLoader parentLoader;

    /**
     * Constructor for this class. The jiplet container instantiates this class
     * when a new context is deployed.
     *
     * @param context
     *            name of the context
     * @param contextRoot
     *            root directory for the context
     * @param type
     *            whether it is a J2EE context (deployed by JBOSS) or a context
     *            deployed using the JMX interface. The deployment of J2EE
     *            context is managed by the J2EE server (JBOSS) whereas the
     *            contexts deployed by the JMX interface is fully managed by the
     *            container
     * @param loader
     *            classloader for this context.
     * @throws Exception
     */
    public JipletContext(String context, File contextRoot, int type,
            ClassLoader loader) throws Exception
    {
        super();

        setContextType(type);
        setContext(context);
        setContextRoot(contextRoot);

        MBEAN_NAME = new ObjectName(
                "org.cafesip.jiplet:type=JipletContext,name=" + context);

        parentLoader = loader;
    }

    public String getRealPath(String path)
    {
        File f = new File(contextRoot, path);
        return f.getAbsolutePath();
    }

    /**
     * @return Returns the contextRoot.
     */
    public File getContextRoot()
    {
        return contextRoot;
    }

    /**
     * @param contextRoot
     *            The contextRoot to set.
     */
    private void setContextRoot(File contextRoot)
    {
        this.contextRoot = contextRoot;
    }

    /**
     * @return Returns the context name.
     */
    public String getContext()
    {
        return context;
    }

    /**
     * @param context
     *            The context to set.
     */
    private void setContext(String context)
    {
        this.context = context;
    }

    /**
     * @return the display name of the context.
     */
    public String getDisplayName()
    {
        if (config != null)
        {
            return config.getDisplayName();
        }

        return "";
    }

    protected void init() throws Exception
    {
        if (JipletLogger.isDebugEnabled() == true)
        {
            JipletLogger.debug("Context " + context
                    + " being initialized from " + contextRoot);
        }

        initJipletLoader();

        File f = new File(contextRoot, "JIP-INF/jip.xml");
        if (f.exists() == false)
        {
            throw new JipletException("File " + f.getAbsolutePath()
                    + " not found");
        }

        // unmarshall the config file
        readConfigFile(f);

        initContextCriteria();

        // create the naming context
        initNamingContext();

        initJiplets();

        initJipletCriteria();

        if (JipletContainer.getInstance().getAuthCachePeriod() > 0L)
        {
            securityManager.setCachePeriod(JipletContainer.getInstance()
                    .getAuthCachePeriod());
        }

        securityManager.setAuthOnLogout(JipletContainer.getInstance()
                .isAuthOnLogout());
        securityManager.init(config);

        initJmxServices();
    }

    private void initNamingContext() throws Exception
    {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try
        {
            InitialContext ini_ctx = new InitialContext();

            Thread.currentThread().setContextClassLoader(classLoader);

            Context env_ctx = null;

            try
            {
                env_ctx = (Context) ini_ctx.lookup("java:comp");
            }
            catch (NamingException e)
            {
                JipletLogger
                        .info("Naming exception while initializing naming context. "
                                + "We are going to ignore any naming-context related operations.");
                return;
            }

            Context sub = null;
            try
            {
                sub = (Context) ini_ctx.lookup("java:comp/env");
            }
            catch (NamingException e)
            {
                JipletLogger
                        .info("The context java:comp/env has not been created. Going to create the sub-context");
                sub = env_ctx.createSubcontext("env");
            }

            VendorDescriptorFactory fac = JipletContainer
                    .getVendorDeploymentFactory();
            VendorDescriptor vdh = null;
            if (fac != null)
            {
                vdh = fac.createVendorDescriptor();
                vdh.init(context, config, contextRoot);
            }

            Iterator i = config.getEnvEntry().iterator();
            while (i.hasNext() == true)
            {
                EnvEntry env = (EnvEntry) i.next();
                initEnvEntry(sub, env, vdh);
            }

            i = config.getResourceRef().iterator();
            while (i.hasNext() == true)
            {
                ResourceRef rsrc = (ResourceRef) i.next();
                initResourceEntry(sub, rsrc, vdh);
            }

            i = config.getResourceEnvRef().iterator();
            while (i.hasNext() == true)
            {
                ResourceEnvRef rsrc = (ResourceEnvRef) i.next();
                initResourceEnvEntry(sub, rsrc, vdh);
            }

            i = config.getEjbRef().iterator();
            while (i.hasNext() == true)
            {
                EJBRef ejb = (EJBRef) i.next();
                String jndi_name = ejb.getEjbRefName();
                if (vdh != null)
                {
                    jndi_name = vdh.getEjbRefJndiName(jndi_name);
                }

                NamingUtil.rebind(sub, ejb.getEjbRefName(), new LinkRef(
                        jndi_name));
            }

            i = config.getEjbLocalRef().iterator();
            while (i.hasNext() == true)
            {
                EJBLocalRef ejb = (EJBLocalRef) i.next();
                String jndi_name = ejb.getEjbRefName();
                if (vdh != null)
                {
                    jndi_name = vdh.getEjbLocalRefJndiName(jndi_name);
                }
                NamingUtil.rebind(sub, ejb.getEjbRefName(), new LinkRef(
                        jndi_name));
            }
        }
        finally
        {
            Thread.currentThread().setContextClassLoader(cl);
        }
    }

    private void removeNamingContext() throws Exception
    {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try
        {
            InitialContext ini_ctx = new InitialContext();

            Thread.currentThread().setContextClassLoader(classLoader);

            Context env_ctx = null;

            try
            {
                env_ctx = (Context) ini_ctx.lookup("java:comp");
            }
            catch (NamingException e)
            {
                JipletLogger
                        .info("Naming exception while removing naming context. "
                                + "We are going to ignore any naming-context related operations.");
                return;
            }

            Context sub = null;
            try
            {
                sub = (Context) ini_ctx.lookup("java:comp/env");
            }
            catch (NamingException e)
            {
                JipletLogger
                        .info("Could not locate  java:comp/env while removing naming context. "
                                + "We are going to ignore any naming-context related operations.");
                return;
            }

            Iterator i = config.getEnvEntry().iterator();
            while (i.hasNext() == true)
            {
                EnvEntry env = (EnvEntry) i.next();
                NamingUtil.unbind(sub, env.getEnvEntryName());
            }

            i = config.getResourceRef().iterator();
            while (i.hasNext() == true)
            {
                ResourceRef rsrc = (ResourceRef) i.next();
                NamingUtil.unbind(sub, rsrc.getResRefName());
            }

            i = config.getResourceEnvRef().iterator();
            while (i.hasNext() == true)
            {
                ResourceEnvRef rsrc = (ResourceEnvRef) i.next();
                NamingUtil.unbind(sub, rsrc.getResourceEnvRefName());
            }

            i = config.getEjbRef().iterator();
            while (i.hasNext() == true)
            {
                EJBRef ejb = (EJBRef) i.next();
                NamingUtil.unbind(sub, ejb.getEjbRefName());
            }

            i = config.getEjbLocalRef().iterator();
            while (i.hasNext() == true)
            {
                EJBLocalRef ejb = (EJBLocalRef) i.next();
                NamingUtil.unbind(sub, ejb.getEjbRefName());
            }

            try
            {
                env_ctx.destroySubcontext("env");
            }
            catch (OperationNotSupportedException e)
            {
                // ignore
            }
        }
        finally
        {
            Thread.currentThread().setContextClassLoader(cl);
        }
    }

    private void initResourceEntry(Context sub, ResourceRef rsrc,
            VendorDescriptor vdh) throws MalformedURLException, NamingException
    {
        String jndi_name = rsrc.getResRefName();
        if (vdh != null)
        {
            jndi_name = vdh.getResourceJndiName(jndi_name);
        }

        if (rsrc.getResType().equals("java.net.URL") == true)
        {
            URL url = new URL(jndi_name);
            NamingUtil.rebind(sub, rsrc.getResRefName(), url);
        }
        else
        {
            if (JipletLogger.isDebugEnabled() == true)
            {
                JipletLogger.debug("Binding resource-ref"
                        + rsrc.getResRefName() + " to " + jndi_name
                        + " for the context " + context);
            }
            NamingUtil
                    .rebind(sub, rsrc.getResRefName(), new LinkRef(jndi_name));
        }
    }

    private void initResourceEnvEntry(Context sub, ResourceEnvRef rsrc,
            VendorDescriptor vdh) throws MalformedURLException, NamingException
    {
        String jndi_name = rsrc.getResourceEnvRefName();
        if (vdh != null)
        {
            jndi_name = vdh.getResourceEnvJndiName(jndi_name);
        }

        if (rsrc.getResourceEnvRefType().equals("java.net.URL") == true)
        {
            URL url = new URL(jndi_name);
            NamingUtil.rebind(sub, rsrc.getResourceEnvRefName(), url);
        }
        else
        {
            if (JipletLogger.isDebugEnabled() == true)
            {
                JipletLogger.debug("Binding env-resource-ref"
                        + rsrc.getResourceEnvRefName() + " to " + jndi_name
                        + " for the context " + context);
            }
            NamingUtil.rebind(sub, rsrc.getResourceEnvRefName(), new LinkRef(
                    jndi_name));
        }
    }

    private void initEnvEntry(Context sub, EnvEntry env, VendorDescriptor vdh)
            throws NamingException
    {
        String jndi_name = env.getEnvEntryName();
        if (vdh != null)
        {
            jndi_name = vdh.getEnvJndiName(jndi_name);
        }

        EnvEntryMetaData meta = new EnvEntryMetaData(jndi_name, env
                .getEnvEntryValue(), env.getEnvEntryValue());
        meta.bind(sub);
    }

    private void initJipletCriteria() throws Exception
    {
        Iterator iter = config.getJipletMapping().iterator();
        while (iter.hasNext() == true)
        {
            JipletMapping mapping = (JipletMapping) iter.next();
            String jiplet_name = mapping.getJiplet();
            Jiplet j = null;
            synchronized (jiplets)
            {
                j = (Jiplet) jiplets.get(jiplet_name);
            }

            if (j == null)
            {
                throw new JipletException("Jiplet " + jiplet_name
                        + " specified in the context mapping is not found");
            }

            String exp = addMapping(mapping.getMapping(), j);
            jipletSelectionCriteria.add(new Pair(jiplet_name, exp));
        }
    }

    private void initContextCriteria() throws Exception
    {
        Iterator iter = null;
        ArrayList cmaps = JipletContainer.getInstance().getContextMapping(
                context);
        if (cmaps.size() > 0)
        {
            if (JipletLogger.isDebugEnabled() == true)
            {
                JipletLogger.debug("For context " + context
                        + ", the context mapping has been overridden ");
            }

            iter = cmaps.iterator();
        }
        else
        {
            iter = config.getContextMappings().getContextMapping().iterator();
        }

        while (iter.hasNext() == true)
        {
            ContextMapping mapping = (ContextMapping) iter.next();
            String connector_name = mapping.getConnector();
            if (connector_name == null)
            {
                connector_name = JipletContainer.getInstance()
                        .getDefaultConnectorName();
            }

            SipConnector c = JipletContainer.getInstance().findConnector(
                    connector_name);

            if (c == null)
            {
                throw new JipletException("Connector " + connector_name
                        + " specified in the context mapping is not found");
            }

            String ret = c.addMapping(mapping.getMapping(), this);
            if (ret == null)
            {
                return;
            }

            contextSelectionCriteria.add(new Pair(connector_name, ret));
            criteriaConnectorsList.add(c);
        }
    }

    private void initJmxServices() throws InstanceAlreadyExistsException,
            MBeanRegistrationException, NotCompliantMBeanException
    {
        MBeanServer agent = getJmxAgent();

        if (agent != null)
        {
            JipletLogger.info("Registering MBEAN JipletContext-" + context);
            agent.registerMBean(this, MBEAN_NAME);
        }
        else
        {
            JipletLogger
                    .info("No JMX agent found. JMX services for JipletContext will not be initialized");
        }
    }

    /**
     * @return the MBeanServer object.
     */
    public MBeanServer getJmxAgent()
    {
        return JipletContainer.getJmxAgent();
    }

    private void initJipletLoader() throws JipletException,
            MalformedURLException
    {
        // add the classes directory
        File c = new File(contextRoot, "JIP-INF/classes");
        if (c.isDirectory() == false)
        {
            // does not exist or is not a directory
            c = null;
        }

        // next, add all the jars under the lib directory
        File j = new File(contextRoot, "JIP-INF/lib");
        if (j.isDirectory() == false)
        {
            j = null;
        }

        ClassLoader parent = getClass().getClassLoader();
        if (parentLoader != null)
        {
            parent = parentLoader;
        }
        classLoader = JipletClassLoader.getClassLoader(parent, c, j);
    }

    private void initJiplets() throws Exception
    {
        List list = config.getJiplet();
        Collections.sort(list, new Comparator()
        {
            public int compare(Object obj1, Object obj2)
            {
                JipletConfig o1 = (JipletConfig) obj1;
                JipletConfig o2 = (JipletConfig) obj2;

                return o1.getStartupOrder() - o2.getStartupOrder();
            }
        });
        Iterator iter = list.iterator();
        while (iter.hasNext() == true)
        {
            JipletConfig jiplet = (JipletConfig) iter.next();
            try
            {
                initJiplet(jiplet);
            }
            catch (Exception e)
            {
                JipletLogger.fatal("Error starting context "
                        + jiplet.getJipletName() + "\n" + "Exception: "
                        + e.getClass().getName() + ": " + e.getMessage() + "\n"
                        + JipletLogger.getStackTrace(e));
            }
        }
    }

    private void initJiplet(JipletConfig jipletConfig) throws Exception
    {
        ClassLoader tcl = Thread.currentThread().getContextClassLoader();

        JipletLogger.info("Starting jiplet " + jipletConfig.getJipletName());

        Class cl = classLoader.loadClass(jipletConfig.getJipletClass());
        if (Jiplet.class.isAssignableFrom(cl) == false)
        {
            throw new JipletException(
                    "The jiplet class does not extend org.cafesip.jiplet.Jiplet");
        }

        Jiplet jiplet = null;
        try
        {
            Thread.currentThread().setContextClassLoader(classLoader);
            jiplet = (Jiplet) cl.newInstance();
        }
        finally
        {
            Thread.currentThread().setContextClassLoader(tcl);
        }

        jiplet.setName(jipletConfig.getJipletName());

        String descr = jipletConfig.getJipletDescription();
        if (descr != null)
        {
            jiplet.setDescription(descr);
        }

        InitParams plist = jipletConfig.getInitParams();
        if (plist != null)
        {
            HashMap params = new HashMap();
            List paramlist = plist.getInitParam();
            Iterator i = paramlist.iterator();
            while (i.hasNext())
            {
                InitParam parm = (InitParam) i.next();
                params.put(parm.getParamName(), parm.getParamValue());
            }
            jiplet.setInitParams(params);
        }

        jiplet.setJipletContext(this);

        try
        {
            // next, assign a SIP listener
            initSip(jipletConfig, jiplet);

            Thread.currentThread().setContextClassLoader(
                    jiplet.getClass().getClassLoader());

            // call the Jiplet's init() method
            jiplet.init(jipletConfig);
        }
        catch (Exception e)
        {
            Thread.currentThread().setContextClassLoader(
                    jiplet.getClass().getClassLoader());
            jiplet.destroy();
            throw e;
        }
        finally
        {
            Thread.currentThread().setContextClassLoader(tcl);
        }

        synchronized (jiplets)
        {
            jiplets.put(jiplet.getName(), jiplet);
        }
    }

    private void initSip(JipletConfig jipletConfig, Jiplet jiplet)
            throws Exception
    {
        String connector = jipletConfig.getJipletConnector();
        if (connector == null)
        {
            connector = JipletContainer.getInstance().getDefaultConnectorName();
        }

        SipConnector c = JipletContainer.getInstance().findConnector(connector);
        if (c == null)
        {
            throw new JipletException("The connector " + connector
                    + " is not defined");
        }

        jiplet.setConnector(c);
        jiplet.setAddressFactory(c.getAddressFactory());
        jiplet.setMessageFactory(c.getMessageFactory());
        jiplet.setHeaderFactory(c.getHeaderFactory());

        if (JipletLogger.isDebugEnabled() == true)
        {
            JipletLogger.debug("Registering jiplet: " + jiplet.getName()
                    + " with connector: " + c.getName());
        }
    }

    private void readConfigFile(File file) throws JAXBException, IOException
    {
        FileInputStream istream = new FileInputStream(file);
        config = (JipApplication) JAXBContext.newInstance(
                "org.cafesip.jiplet.config.jip",
                this.getClass().getClassLoader()).createUnmarshaller()
                .unmarshal(istream);
        istream.close();
    }

    /**
     * @return Returns the context configuration in the form of a JipApplication
     *         object.
     */
    public JipApplication getConfig()
    {
        return config;
    }

    /**
     * @param config
     *            The config to set.
     */
    private void setConfig(JipApplication config)
    {
        this.config = config;
    }

    protected JipletSession findSession(SessionInfo session)
    {
        synchronized (sessions)
        {
            String sname = session.toString();
            if (JipletLogger.isDebugEnabled() == true)
            {
                JipletLogger.debug("Looking for  session " + sname
                        + ".from the sessions list of size " + sessions.size());
            }

            return (JipletSession) sessions.get(session.toString());
        }
    }

    protected JipletSession addSession(SessionInfo session)
    {
        synchronized (sessions)
        {
            String sname = session.toString();
            JipletSession s = new JipletSession(this, session);
            sessions.put(sname, s);

            if (JipletLogger.isDebugEnabled() == true)
            {
                JipletLogger
                        .debug("Adding session "
                                + sname
                                + ". The number of sessions in the sessions table is now "
                                + sessions.size());
            }

            return s;
        }
    }

    protected void removeSession(SessionInfo session)
    {
        synchronized (sessions)
        {
            String sname = session.toString();
            sessions.remove(sname);

            if (JipletLogger.isDebugEnabled() == true)
            {
                JipletLogger
                        .debug("Removing session "
                                + sname
                                + ". The number of sessions in the sessions table is now "
                                + sessions.size());
            }
        }
    }

    /**
     * Find a jiplet belonging to this context given its name.
     *
     * @param name
     *            name of the context
     * @return The jiplet object, null if the jiplet with the given name was not
     *         found.
     */
    public Jiplet findJiplet(String name)
    {
        synchronized (jiplets)
        {
            return (Jiplet) jiplets.get(name);
        }
    }

    /**
     * This method is called by the container when the context is being removed.
     */
    public void destroy()
    {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();

        // unregister from MBeanServer
        MBeanServer agent = getJmxAgent();
        if (agent != null)
        {
            try
            {
                agent.unregisterMBean(MBEAN_NAME);
            }
            catch (Exception e)
            {
                JipletLogger.error("Error occured while unregistering "
                        + MBEAN_NAME.getCanonicalName() + " MBEAN: "
                        + e.getClass().getName() + ": " + e.getMessage() + "\n"
                        + JipletLogger.getStackTrace(e));
            }
        }

        Iterator iter = criteriaConnectorsList.iterator();
        while (iter.hasNext() == true)
        {
            SipConnector c = (SipConnector) iter.next();
            c.removeMapping(this);
        }

        synchronized (jiplets)
        {
            iter = jiplets.entrySet().iterator();
            while (iter.hasNext() == true)
            {
                Map.Entry entry = (Map.Entry) iter.next();
                JipletLogger
                        .info("Deleting jiplet: " + (String) entry.getKey());
                Jiplet jiplet = (Jiplet) entry.getValue();

                try
                {
                    Thread.currentThread().setContextClassLoader(
                            jiplet.getClass().getClassLoader());
                    jiplet.destroy();
                }
                finally
                {
                    Thread.currentThread().setContextClassLoader(cl);
                }
                iter.remove();
            }
        }

        // next, remove all the sessions
        sessions.clear();

        // remove the naming context
        try
        {
            removeNamingContext();
        }
        catch (Exception e)
        {
            JipletLogger.error("Error removing naming context for context "
                    + context + "\n" + JipletLogger.getStackTrace(e));
        }

        // remove the security stuff
        securityManager.destroy();
    }

    /**
     * @return Returns the contextType.
     */
    public int getContextType()
    {
        return contextType;
    }

    /**
     * @param contextType
     *            The contextType to set.
     */
    private void setContextType(int contextType)
    {
        this.contextType = contextType;
    }

    protected String getContextTypeDescription()
    {
        switch (contextType)
        {
        case CONTEXT_UNKNOWN:
            return CONTEXT_UNKNOWN_DESCR;
        case CONTEXT_DEPLOYED:
            return CONTEXT_DEPLOYED_DESCR;
        case CONTEXT_J2EE:
            return CONTEXT_J2EE_DESCR;
        }

        JipletLogger
                .error("getContextTypeDescription(): encountered invalid contextType = "
                        + contextType);
        return "Invalid";
    }

    /**
     *
     * @see org.cafesip.jiplet.JipletContextMBean#listJiplets()
     */
    public String[] listJiplets()
    {
        if (JipletLogger.isDebugEnabled() == true)
        {
            JipletLogger
                    .debug("Received a request from JMX agent to list jiplets for context: "
                            + this.getContext());
        }

        synchronized (jiplets)
        {
            String[] ret = new String[jiplets.size()];
            jiplets.keySet().toArray(ret);
            return ret;
        }
    }

    /**
     *
     * @see org.cafesip.jiplet.JipletContextMBean#getJipletProperty(java.lang.String)
     */
    public JipletElement getJipletProperty(String name)
    {
        if (JipletLogger.isDebugEnabled() == true)
        {
            JipletLogger
                    .debug("Received a request from JMX agent to view the jiplet: "
                            + name + " (context " + this.getContext() + ')');
        }

        Jiplet jiplet = findJiplet(name);

        if (jiplet == null)
        {
            if (JipletLogger.isDebugEnabled() == true)
            {
                JipletLogger.debug("Jiplet: " + name
                        + " was not found (context " + this.getContext() + ')');
            }
            return null;
        }

        JipletElement element = new JipletElement();

        Iterator iter = jipletSelectionCriteria.iterator();
        ArrayList criteria = new ArrayList();
        while (iter.hasNext() == true)
        {
            Pair p = (Pair) iter.next();
            String jip_name = (String) p.getFirst();
            String exp = (String) p.getSecond();

            if (jip_name.equals(name) == true)
            {
                criteria.add(exp);
            }
        }
        element.setSelectionCriteria(criteria);

        Pair p = securityManager.findSecurityConstraint(jiplet);
        if (p != null)
        {
            StringBuffer buffer = new StringBuffer();
            String realm = ((Realm) p.getFirst()).getRealmName();
            String[] roles = (String[]) p.getSecond();

            buffer.append("realm = " + realm + "; role(s) = ");

            for (int i = 0; i < roles.length; i++)
            {
                if (i > 0)
                {
                    buffer.append("," + roles[i]);
                }
                else
                {
                    buffer.append(roles[i]);
                }
            }
            element.setSecurityConstraint(buffer.toString());
        }

        element.setConnectorName(jiplet.getConnectorName());
        element.setDescription(jiplet.getDescription());
        element.setInitParams(jiplet.getInitParams());
        element.setName(name);
        element.setParentContext(context);

        return element;
    }

    protected Jiplet[] criteriaMatch(RequestEvent event)
    {
        ArrayList list = new ArrayList();
        synchronized (criteria)
        {
            Iterator iter = criteria.iterator();
            while (iter.hasNext() == true)
            {
                Pair p = (Pair) iter.next();
                CriteriaMatch cr = (CriteriaMatch) p.getFirst();

                if (cr.matches(event) == true)
                {
                    list.add(p.getSecond());
                }
            }
        }

        Jiplet[] jiplets = new Jiplet[list.size()];
        list.toArray(jiplets);
        return jiplets;
    }

    private String addMapping(Mapping mapping, Jiplet jiplet)
            throws JipletException
    {
        MappingCompiler compiler = new MappingCompiler();
        compiler.setCompiledList(criteria);
        compiler.setMappedObject(jiplet);
        compiler.setMapping(mapping);
        synchronized (criteria)
        {
            String ret = compiler.compile();
            if (ret == null)
            {
                throw new JipletException("Failed to compile mapping");
            }

            return ret;
        }
    }

    /**
     * @return Returns the contextSelectionCriteria.
     */
    public ArrayList getContextSelectionCriteria()
    {
        return contextSelectionCriteria;
    }

    /*
     * @see java.lang.Object#toString()
     */
    public String toString()
    {
        return "JipletContext: " + context;
    }

    /**
     * @return Returns the securityManager.
     */
    protected SecurityConstraintManager getSecurityManager()
    {
        return securityManager;
    }

    /**
     * This method returns the class loader for this context
     *
     * @return
     */
    public ClassLoader getClassLoader()
    {
        return classLoader;
    }

    /**
     * This method is used to send a signal to a jiplet. A signal is sent by an
     * external entity to notify a jiplet of an external event. For more
     * details, see the documentation for the class
     * org.cafesip.jiplet.JipletSignal
     *
     *
     * @param jiplet
     *            name of the jiplet
     * @param signal
     *            event information
     * @return true if the signal was delivered successfully, false otherwise.
     * @see org.cafesip.jiplet.JipletSignal
     */
    public boolean sendSignal(String jiplet, JipletSignal signal)
    {
        try
        {
            Jiplet j = findJiplet(jiplet);
            if (j == null)
            {
                return false;
            }

            SipConnector c = JipletContainer.getInstance().findConnector(
                    j.getConnectorName());
            if (c == null)
            {
                return false;
            }

            return c.processSignal(j, signal);
        }
        catch (Exception e)
        {
            JipletLogger.fatal(e.getClass().getName()
                    + " occured while getting connector information: "
                    + e.getMessage() + "\n" + JipletLogger.getStackTrace(e));
            return false;
        }
    }
}
TOP

Related Classes of org.cafesip.jiplet.JipletContext

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.