Package com.ericsson.ssa.config

Source Code of com.ericsson.ssa.config.ConvergedContextConfig

/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) Ericsson AB, 2004-2008. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License").  You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.  If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license."  If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above.  However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.ericsson.ssa.config;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;

import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipSessionsUtil;

import com.ericsson.ssa.container.SipBindingResolver;
import com.ericsson.ssa.container.auth.DescriptorProcessor;
import com.ericsson.ssa.container.datacentric.DataCentricUtilHolder;
import com.ericsson.ssa.container.sim.ApplicationDispatcher;
import com.ericsson.ssa.container.sim.ServletDispatcher;
import com.ericsson.ssa.sip.SipFactoryImpl;
import com.ericsson.ssa.sip.SipSessionsUtilImpl;
import com.ericsson.ssa.sip.dns.DnsResolver;
import com.ericsson.ssa.sip.timer.TimerServiceImpl;
import com.ericsson.ssa.utils.InjectionUtil;

import com.sun.enterprise.NamingManager;
import com.sun.enterprise.Switch;
import com.sun.enterprise.deployment.BundleDescriptor;
import com.sun.enterprise.deployment.EjbReferenceDescriptor;
import com.sun.enterprise.deployment.JmsDestinationReferenceDescriptor;
import com.sun.enterprise.deployment.LocaleEncodingMappingDescriptor;
import com.sun.enterprise.deployment.LocaleEncodingMappingListDescriptor;
import com.sun.enterprise.deployment.MessageDestinationDescriptor;
import com.sun.enterprise.deployment.ResourcePrincipal;
import com.sun.enterprise.deployment.ResourceReferenceDescriptor;
import com.sun.enterprise.deployment.runtime.common.DefaultResourcePrincipal;
import com.sun.enterprise.deployment.runtime.common.ResourceRef;
import com.sun.enterprise.deployment.web.ContextParameter;
import com.sun.enterprise.deployment.web.EnvironmentEntry;
import com.sun.enterprise.deployment.web.SecurityRole;
import com.sun.enterprise.util.LocalStringManagerImpl;
import com.sun.enterprise.web.WebModule;
import com.sun.enterprise.web.WebModuleContextConfig;
import com.sun.enterprise.web.deploy.ContextEjbDecorator;
import com.sun.enterprise.web.deploy.ContextLocalEjbDecorator;
import com.sun.enterprise.web.deploy.ContextResourceDecorator;

import com.sun.enterprise.web.deploy.MessageDestinationDecorator;
import com.sun.org.apache.commons.digester.Digester;
import com.sun.org.apache.commons.digester.RuleSet;

import java.util.logging.Logger;
import org.apache.catalina.Container;
import org.apache.catalina.Host;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.ExpandWar;
import org.apache.catalina.startup.NamingRuleSet;

import org.apache.naming.resources.FileDirContext;
import org.apache.naming.resources.WARDirContext;

import org.glassfish.comms.api.datacentric.DataCentricUtil;
import org.glassfish.comms.api.telurl.TelUrlResolver;
import org.glassfish.comms.api.uriutils.UriTools;

import org.jvnet.glassfish.comms.deployment.backend.SipApplication;
import org.jvnet.glassfish.comms.deployment.backend.SipApplicationListeners;
import org.jvnet.glassfish.comms.deployment.backend.SipBundleDescriptor;
import org.jvnet.glassfish.comms.deployment.runtime.sip.SunSipApp;
import org.jvnet.glassfish.comms.security.auth.impl.Authenticator;
import org.jvnet.glassfish.comms.security.auth.impl.SipSecurityManager;
import org.jvnet.glassfish.comms.util.LogUtil;


public final class ConvergedContextConfig extends WebModuleContextConfig {

    private static final Logger _logger = LogUtil.SIP_LOGGER.getLogger();
    private static final String APPLICATION_SIP_XML = "/WEB-INF/sip.xml";
    private static final String SIP = "sip";
    private static final String SIP_FACTORY_NAME = "SipFactory";
    private static final String SIP_TIMERSERVICE_NAME = "TimerService";
    private static final String SIP_SESSIONS_UTIL_NAME = "SipSessionsUtil";
    protected NamingManager namingManager;
    Switch theSwitch;
    protected ConvergedContextImpl convergedContext;
    boolean contextConfigOk = true;

    public static boolean ALLOW_FROM_CHANGE = Boolean.getBoolean("org.glassfish.sip.allowFromChange");
   
    protected static final LocalStringManagerImpl localStrings =
            new LocalStringManagerImpl(ConvergedContextConfig.class);

    public ConvergedContextConfig() {
        theSwitch = Switch.getSwitch();
        namingManager = theSwitch.getNamingManager();
    }

    /**
     * Create (if necessary) and return a Digester configured to process the
     * context configuration descriptor for an application.
     */
    protected static Digester createContextDigester() {
        Digester digester = new Digester();
        digester.setValidating(false);

        RuleSet contextRuleSet = new ConvergedContextRuleSet("", false);
        digester.addRuleSet(contextRuleSet);

        RuleSet namingRuleSet = new NamingRuleSet("Context/");
        digester.addRuleSet(namingRuleSet);

        return digester;
    }

    /**
     * Process events for an associated Context.
     *
     * @param event The lifecycle event that has occurred
     */
    public void lifecycleEvent(LifecycleEvent event) {
        if (event.getType().equals(Lifecycle.INIT_EVENT)) {
            try {
                convergedContext = (ConvergedContextImpl) event.getLifecycle();
                preConfigureServletContextAttributes();
            } catch (ClassCastException e) {
                return;
            }
        } else if (event.getType().equals(Lifecycle.AFTER_START_EVENT)) {
            postConfigureServletContextAttributes();
        }

        super.lifecycleEvent(event);
    }

    /**
     * Process a "before start" event for this Context.
     */
    protected void beforeStart() {
        try {
            getSipApplication();
        } catch (Exception e) {
            //log exception
            System.out.print(e.getMessage());
        }
    }

    /**
     * Process a "start" event for this Context.
     */
    protected synchronized void start() {
        beforeStart();
        super.start();
        ok = true;

        // Set properties based on DefaultContext
        Container container = context.getParent();

        if (!context.getOverride()) {
            if (container instanceof Host) {
                container = container.getParent();
            }
        }

        ServletContext servletContext = context.getServletContext();
        InputStream sipXml = servletContext.getResourceAsStream(APPLICATION_SIP_XML);

        // if (sipXml != null) {
            // Do the SIP servlet specific part.
            try {
                /*
                 * The sequence to start a context 1. Parse the deployment descriptor into a
                 * SipApplication 2. Copy Context Parameters to the Standard Context of
                 * Tomcat 3. bind resources to the context 4. Initialize the servlet
                 * dispatcher
                 */
                configureServletContextAttributes();
                copyContextProperties();

                initializeServletDispatcher();

                Authenticator.initNonceManager();
    org.jvnet.glassfish.comms.security.auth.impl.PAssertedAuthenticatorFactory.getInstance();               
                SipSecurityManager manager = SipSecurityManager.createManager((SipBundleDescriptor)super.getDescriptor(),true);
                String pContextId = manager.getContextID();
                if (!manager.inService()) {
                    new DescriptorProcessor().process(pContextId, convergedContext.getSipApplication());
                }
                convergedContext.getDispatcher().setContextId(pContextId);

                SipApplication application = convergedContext.getSipApplication();
                Map<String, org.jvnet.glassfish.comms.deployment.backend.Servlet> map = application.getServlets();
                Collection<org.jvnet.glassfish.comms.deployment.backend.Servlet> coll = map.values();
                Iterator<org.jvnet.glassfish.comms.deployment.backend.Servlet> itr = coll.iterator();
                HashMap<String, String> runAsMap = new HashMap<String, String>();

                while (itr.hasNext()) {
                    org.jvnet.glassfish.comms.deployment.backend.Servlet servlet = itr.next();
                    String rolename = servlet.getRunAsRoleName();
                    String servletName = servlet.getServletName();
                    runAsMap.put(servletName, rolename);
                }

                if (runAsMap.size() > 0) {
                    convergedContext.getDispatcher().getAuthModule().setRunAs(manager.readRunAs(super.getDescriptor(), runAsMap));
                }
            } catch (Exception e) {
                e.printStackTrace();
                ok = false;
            }
        //}

        // Make our application available if no problems were encountered
        if (ok && contextConfigOk) {
            context.setConfigured(true);
            String msg = localStrings.getLocalString("contextConfig.available",
                convergedContext.getName());
            _logger.log(Level.INFO,msg + convergedContext.getName());
        } else {
            String msg = localStrings.getLocalString("contextConfig.unavailable",
                    convergedContext.getName());
            _logger.log(Level.INFO,msg);
            context.setAvailable(false);
        }
    }

    /**
     * Upon stop of context, all allocated resources and references are reset
     */
    protected synchronized void stop() {
        super.stop();


        cleanSecurityContext(super.getDescriptor().getApplication().getRegistrationName());
        // Notify ServletContextListener.contextDestroyed here.
        if (convergedContext.getSipApplicationListeners() != null) {
            ServletContextEvent servletContextEvent = new ServletContextEvent(context.getServletContext());
            Iterator<ServletContextListener> contextListenerIterator = convergedContext.getSipApplicationListeners()
                                                                                       .getServletContextListener()
                                                                                       .iterator();
            while (contextListenerIterator.hasNext()) {
                ServletContextListener listener = contextListenerIterator.next();
                listener.contextDestroyed(servletContextEvent);
            }
        }

        // Calling the un-initialize method to call the
        // destroy method on the servlet(s).
        if (convergedContext.getDispatcher() != null) {
            convergedContext.getDispatcher().unInitialize();
        }

        if (convergedContext.getSipApplicationListeners() != null) {
            convergedContext.getSipApplicationListeners().clean();
        }

        convergedContext.setSipApplication(null);
        convergedContext.setDispatcher(null);
        convergedContext.setSipFactory(null);
        convergedContext.setSipSessionsUtil(null);

        unPublishResourceReference(getSipResourceJNDIName(SIP_FACTORY_NAME));
        SipFactoryMap.getInstance().removeSipFactoryFacade(getSipResourceJNDIName(SIP_FACTORY_NAME));

        unPublishResourceReference(getSipResourceJNDIName(SIP_SESSIONS_UTIL_NAME));
        SipSessionsUtilMap.getInstance().removeSipSessionsUtil(getSipResourceJNDIName(SIP_SESSIONS_UTIL_NAME));

        unPublishResourceReference(getSipResourceJNDIName(SIP_TIMERSERVICE_NAME));
    }

    /**
     * Process a "destroy" event for this Context.
     */
    protected synchronized void destroy() {
        String workDir = ((StandardContext) context).getWorkPath();

        if (workDir != null) {
            ExpandWar.delete(new File(workDir));
        }
    }
   
    private void cleanSecurityContext(String appName) {

        ArrayList<SipSecurityManager> managers =
                SipSecurityManager.getManagersForApp(appName, false);

        for (int i = 0; managers != null && i < managers.size(); i++) {

            try {
                managers.get(i).destroy();
            } catch (javax.security.jacc.PolicyContextException pce) {
                logger.log(Level.FINE,"Error occurred while cleaning SIPSecurityManagers ",pce);
            }
        }
    }

    /**
     * configureServletContextAttributes is called upon start of contextconfig.
     *
     */
    private void configureServletContextAttributes() {
        SipApplication sipApplication = convergedContext.getSipApplication();
        ServletContext servletContext = convergedContext.getServletContext();

        SipApplicationListeners sipApplicationListeners = new SipApplicationListeners(((SipApplication) sipApplication).getListeners(), context.getLoader().getClassLoader());

        convergedContext.setSipApplicationListeners(sipApplicationListeners);

        // Notify the ServletContextListener.contextInitialized here.
        ServletContextEvent servletContextEvent = new ServletContextEvent(servletContext);
        Iterator<ServletContextListener> contextListenerIterator = sipApplicationListeners.getServletContextListener().iterator();

        while (contextListenerIterator.hasNext()) {
            ServletContextListener listener = contextListenerIterator.next();
            listener.contextInitialized(servletContextEvent);
        }
    }

    private void postConfigureServletContextAttributes() {
        SipBundleDescriptor sbd = (SipBundleDescriptor) getDescriptor();

        SipApplicationListeners sipApplicationListeners = convergedContext.getSipApplicationListeners();

        InjectionUtil injectionUtil = new InjectionUtil();
       
        if( sipApplicationListeners != null ) {
            Set<Object> instances =
                sipApplicationListeners.getNonServletListenerInstances();

            for (Object instance : instances) {
                injectionUtil.injectResources(instance, context, sbd);
            }
        }
    }
   
    private void setContextApplicationName() {
       
        SipApplication sipApplication = convergedContext.getSipApplication();
        String appName = sipApplication.getAppName();
       
        String sipModuleName = null;       
        //Mostly an 1.0 application.
        String tmp = sipApplication.getModuleID().toLowerCase();
        if (tmp.endsWith("war") || tmp.endsWith(".sar")) {
            sipModuleName = sipApplication.getModuleID().substring(0, tmp.length() - 4);
        } else {
             sipModuleName = sipApplication.getModuleID();
        }               
       
        SipBundleDescriptor sbd = (SipBundleDescriptor) getDescriptor();
       
        /**
         * If there is no app-name specified in the sip.xml, then an app-name is
         *  generated. The logic is as follows :
         *  For an app within an .ear the app-name is <ear-name>/<war-name>
         *  For a standalone app the app-name is <war-name>
         */
        if(appName == null ) {
            if (sbd.getApplication() != null && !sbd.getApplication().isVirtual()) {           
                appName = sbd.getApplication().getRegistrationName() + "/" + sipModuleName ;
            } else {
                appName = sipModuleName;
            }
        }

        //Ideally we should replace dots with underscore. But TCK fails.
        //Will need to ask TCK folks.
        //appName = appName.replace('.', '_');
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Registering the Application Name : " + appName);
        }
        convergedContext.setAppName(appName);
    }

    /*
    * PreConfigure must be called upon "init" LifeCycleEvent and before super class
    * has processed the "init event" The method publishes the SipFactory, SipSessionsUtil
    * and TimerService Reference in JNDI
    */
    private void preConfigureServletContextAttributes() {
        contextConfigOk = true;

        try {
            getSipApplication();
        } catch (Exception e) {
            contextConfigOk = false;
            logger.log(Level.WARNING, "contextConfig.unavailable");
        }

        setContextApplicationName();
        SipApplication sipApplication = convergedContext.getSipApplication();               
        ServletContext servletContext = convergedContext.getServletContext();

        // SSA 1.0, section 4.2, here we can add new extensions.
        // The only extensions we support right now is 100rel and path.
        List<String> supportedExt = new ArrayList<String>();
        supportedExt.add("100rel");
        supportedExt.add("path");
        if (ALLOW_FROM_CHANGE) {
           supportedExt.add("from-change");
        }
        supportedExt.add("join");
        supportedExt.add("replaces");
        servletContext.setAttribute(SipServlet.SUPPORTED, Collections.unmodifiableList(supportedExt));

        servletContext.setAttribute(SipServlet.SUPPORTED_RFCs, getSupportedRfcs());

        SipFactoryImpl.getInstance().setServiceHandler(ApplicationDispatcher.getInstance());

        /*
         * SipFactory
         */
        SipFactoryFacade sipFactory = new SipFactoryFacade(convergedContext, SipFactoryImpl.getInstance(), (SipApplication) sipApplication);
        convergedContext.setSipFactory(sipFactory);
        servletContext.setAttribute(SipServlet.SIP_FACTORY, sipFactory);

        SipFactoryMap.getInstance().addSipFactoryFacade(getSipResourceJNDIName(SIP_FACTORY_NAME), sipFactory);

        /*
         * SipSessionsUtil
         */
        SipSessionsUtilImpl sipSessionsUtil = new SipSessionsUtilImpl(convergedContext);
        convergedContext.setSipSessionsUtil(sipSessionsUtil);
        servletContext.setAttribute("javax.servlet.sip.SipSessionsUtil", sipSessionsUtil);

        (SipSessionsUtilMap.getInstance()).addSipSessionsUtil(getSipResourceJNDIName(SIP_SESSIONS_UTIL_NAME), (SipSessionsUtil) sipSessionsUtil);

        // Bind the timer service
        servletContext.setAttribute(SipServlet.TIMER_SERVICE, TimerServiceImpl.getInstance());

        // put outbound interface in context
        servletContext.setAttribute(SipServlet.OUTBOUND_INTERFACES, Collections.unmodifiableList(Arrays.asList(SipBindingResolver.getInterfaces())));

        //Needed by applications which needs direct TelUrl lookup support
        servletContext.setAttribute(TelUrlResolver.CONTEXT_ATTRIBUTE_NAME, DnsResolver.getInstance());

        //Make UriTools available for applications
        servletContext.setAttribute(UriTools.CONTEXT_ATTRIBUTE_NAME, DnsResolver.getInstance());

        //Make DataCentricUtil available for applications
        servletContext.setAttribute(DataCentricUtil.CONTEXT_ATTRIBUTE_NAME, DataCentricUtilHolder.getInstance());

        SipBundleDescriptor sbd = (SipBundleDescriptor) getDescriptor();

        for (Iterator itr = sbd.getJmsDestinationReferenceDescriptors().iterator();
                itr.hasNext();) {
            JmsDestinationReferenceDescriptor next = (JmsDestinationReferenceDescriptor) itr.next();

            String resourceType = next.getRefType();

            if (javax.servlet.sip.SipFactory.class.getName().equals(resourceType)) {
                updateDescriptor(next, SIP_FACTORY_NAME);
            } else if (javax.servlet.sip.TimerService.class.getName().equals(resourceType)) {
                updateDescriptor(next, SIP_TIMERSERVICE_NAME);
            } else if (javax.servlet.sip.SipSessionsUtil.class.getName().equals(resourceType)) {
                updateDescriptor(next, SIP_SESSIONS_UTIL_NAME);
            }
        }

        try {
            String jndiName = getSipResourceJNDIName(SIP_FACTORY_NAME);
            namingManager.publishObject(jndiName, SerializableSipFactoryProxy.newInstance(jndiName), true);
        } catch (NamingException ne) {
            ne.printStackTrace();
        }

        try {
            String jndiName = getSipResourceJNDIName(SIP_TIMERSERVICE_NAME);
            namingManager.publishObject(jndiName, SerializableTimerServiceProxy.newInstance(), true);
        } catch (NamingException ne) {
            ne.printStackTrace();
        }

        try {
            String jndiName = getSipResourceJNDIName(SIP_SESSIONS_UTIL_NAME);
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "Publishing the object" + jndiName);
            }
            namingManager.publishObject(jndiName, SerializableSipSessionsUtilProxy.newInstance(jndiName), true);
        } catch (NamingException ne) {
            ne.printStackTrace();
        }
    }

    private void updateDescriptor(JmsDestinationReferenceDescriptor desc, String ResourceName) {
        desc.setJndiName(getSipResourceJNDIName(ResourceName));
        desc.setMappedName(getSipResourceJNDIName(ResourceName));
    }

    private String getSipResourceJNDIName(String resourceName) {
        //System.out.println("ConvergedContext Application Name for JNDI is " + convergedContext.getAppName());
        return SIP + "/" + convergedContext.getAppName() + "/" + resourceName;
    }

    private void publishResourceReference(String resourceInterface, String objectFactory, String mappedName) {
        try {
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "mappedName = " + mappedName);
            }

            Reference ref = new Reference(resourceInterface, new StringRefAddr("url", mappedName), objectFactory, null);

            namingManager.publishObject(mappedName, ref, true);
        } catch (NamingException ne) {
            ne.printStackTrace();
        }
    }

    private void unPublishResourceReference(String mappedName) {
        try {
            namingManager.unpublishObject(mappedName);
        } catch (NamingException ne) {
            ne.printStackTrace();
        }
    }

    /**
     * Attaches a <code>SipServletInvokerValve</code> to a <code>Context</code>
     * pipeline and registers the valve with the SIM. The initialization steps
     * of the valve are also executed.
     */
    private void initializeServletDispatcher() {
        ServletDispatcher dispatcher = new ServletDispatcher(convergedContext.getSipSessionManager());
        dispatcher.setSipApplicationModel(convergedContext.getSipApplication());
        context.getPipeline().addValve(dispatcher);

        // Initialize all the servlet wrappers upon initialization of the context.
        // Must do this after adding the valve to the pipeline, so that the parent
        // container of the valve and it's Loader are initialized.
        dispatcher.setSipFactory(convergedContext.getSipFactory());
        dispatcher.initialize();
        convergedContext.setDispatcher(dispatcher);
    }

    /**
     * Adjust docBase.
     */
    protected void fixDocBase() throws IOException {
        Host host = (Host) context.getParent();
        String appBase = host.getAppBase();
        boolean unpackWARs = true;

        if (host instanceof StandardHost) {
            unpackWARs = ((StandardHost) host).isUnpackWARs() && ((StandardContext) context).getUnpackWAR();
        }

        File canonicalAppBase = new File(appBase);

        if (canonicalAppBase.isAbsolute()) {
            canonicalAppBase = canonicalAppBase.getCanonicalFile();
        } else {
            canonicalAppBase = new File(System.getProperty("catalina.base"), appBase).getCanonicalFile();
        }

        String docBase = context.getDocBase();

        if (docBase == null) {
            // Trying to guess the docBase according to the path
            String path = context.getPath();

            if (path == null) {
                return;
            }

            if (path.equals("")) {
                docBase = "ROOT";
            } else {
                if (path.startsWith("/")) {
                    docBase = path.substring(1);
                } else {
                    docBase = path;
                }
            }
        }

        File file = new File(docBase);

        if (!file.isAbsolute()) {
            docBase = (new File(canonicalAppBase, docBase)).getPath();
        } else {
            docBase = file.getCanonicalPath();
        }

        file = new File(docBase);

        if ((docBase.toLowerCase().endsWith(".sar") || docBase.toLowerCase().endsWith(".war")) && !file.isDirectory() && unpackWARs) {
            URL war = new URL("jar:" + (new File(docBase)).toURL() + "!/");
            String contextPath = context.getPath();

            if (contextPath.equals("")) {
                contextPath = "ROOT";
            }

            docBase = ExpandWar.expand(host, war, contextPath);
            file = new File(docBase);
            docBase = file.getCanonicalPath();
        } else {
            File docDir = new File(docBase);

            if (!docDir.exists()) {
                String[] extensions = new String[] { ".sar", ".war" };

                for (String extension : extensions) {
                    File archiveFile = new File(docBase + extension);

                    if (archiveFile.exists()) {
                        if (unpackWARs) {
                            URL war = new URL("jar:" + archiveFile.toURL() + "!/");
                            docBase = ExpandWar.expand(host, war, context.getPath());
                            file = new File(docBase);
                            docBase = file.getCanonicalPath();
                        } else {
                            docBase = archiveFile.getCanonicalPath();
                        }

                        break;
                    }
                }
            }
        }

        if (docBase.startsWith(canonicalAppBase.getPath())) {
            docBase = docBase.substring(canonicalAppBase.getPath().length());
            docBase = docBase.replace(File.separatorChar, '/');

            if (docBase.startsWith("/")) {
                docBase = docBase.substring(1);
            }
        } else {
            docBase = docBase.replace(File.separatorChar, '/');
        }

        context.setDocBase(docBase);
    }

    // =================================================================
    // Copy parameters from the SipApplication Model to the Context
    //
    //
    private void copyContextProperties() {
        SipApplication sipApplication = convergedContext.getSipApplication();

        if (sipApplication.getDisplayName() != null) {
            convergedContext.setDisplayName(sipApplication.getDisplayName());
        }
        context.setDistributable(sipApplication.isDistributable());
        copyContextParameters();
        copySecurityRoles();
        configureContextResource(convergedContext, sipApplication);
        configureResourceRefs(convergedContext, sipApplication);
        configureEjbReferences(convergedContext, sipApplication);
        configureMessageDestination(convergedContext, sipApplication);
        configureLocaleEncodingMappings(convergedContext, sipApplication);       

        //copyResourceEnvRefs();
        //copyResourceRefs();

        //copyEnvironmentEntries();
        //copyEjbReferences();
        //copyEjbLocalReferences();
    }

    private void copySecurityRoles() {
        Enumeration<SecurityRole> roles = convergedContext.getSipApplication().getSecurityRoles();

        if (roles != null) {
            for (Enumeration e = roles; roles.hasMoreElements();) {
                context.addSecurityRole((roles.nextElement()).getName());
            }
        }
    }

    private void copyContextParameters() {
        Enumeration<ContextParameter> parameters = convergedContext.getSipApplication().getContextParameters();

        if (parameters != null) {
            for (Enumeration e = parameters; e.hasMoreElements();) {
                ContextParameter param = (ContextParameter) e.nextElement();
                // Check if this is an internal session case
                context.addParameter(param.getName(), param.getValue());
            }
        }
    }

    /**
     * Get base path.
     */
    private String getBasePath(StandardContext context) {
        String docBase = null;
        Container container = context;

        while (container != null) {
            if (container instanceof Host) {
                break;
            }

            container = container.getParent();
        }

        File file = new File(context.getDocBase());

        if (!file.isAbsolute()) {
            if (container == null) {
                docBase = (new File(engineBase(context), context.getDocBase())).getPath();
            } else {
                // Use the "appBase" property of this container
                String appBase = ((Host) container).getAppBase();
                file = new File(appBase);

                if (!file.isAbsolute()) {
                    file = new File(engineBase(context), appBase);
                }

                docBase = (new File(file, context.getDocBase())).getPath();
            }
        } else {
            docBase = file.getPath();
        }

        return docBase;
    }

    /**
     * Return a File object representing the base directory for the
     * entire servlet container (i.e. the Engine container if present).
     *
     * @param context The StandardContext
     */
    protected File engineBase(StandardContext context) {
        String base = System.getProperty("catalina.base");

        if (base == null) {
            StandardEngine engine = (StandardEngine) context.getParent().getParent();

            base = engine.getBaseDir();
        }

        return new File(base);
    }

    /**
     * Set the resources DirContext object with which this
     * context is associated.
     */
    private void setContextResources() {
        try {
            if ((context.getDocBase() != null) && (context.getDocBase().endsWith(".war")) && (!(new File(getBasePath((StandardContext) context))).isDirectory())) {
                context.setResources(new WARDirContext());
            } else if ((context.getDocBase() != null) && (context.getDocBase().endsWith(".sar")) && (!(new File(getBasePath((StandardContext) context))).isDirectory())) {
                context.setResources(new SARDirContext());
            } else {
                context.setResources(new FileDirContext());
            }
        } catch (IllegalArgumentException e) {
            logger.log(Level.SEVERE, "Error initializing resources: " + e.getMessage());
        }
    }

    private void getSipApplication() throws Exception {
        SipApplication sipApplication = null;

        try {
            if ((super.getDescriptor() != null) && super.getDescriptor() instanceof SipBundleDescriptor) {
                sipApplication = ((SipBundleDescriptor) super.getDescriptor()).getSipApplication();
                convergedContext.setSipApplication((SipApplication) sipApplication);
            }
        } catch (Exception e) {
            throw e; // Just rethrow.
        }
    }

    private void publishSipSessionsUtil(SipSessionsUtil ssu) {
        try {
            String ssuMappedName = "ssu" + convergedContext.getAppName();

            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "ssuMappedName = " + ssuMappedName);
            }

            //Create a Reference object to hold the SipFactory here
            Reference ssuRef = new Reference("javax.servlet.sip.SipSessionsUtil", new StringRefAddr("url", ssuMappedName), "org.jvnet.glassfish.comms.deployment.backend.SSUObjectFactory", null);

            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "sSURef" + ssuRef);
            }

            namingManager.publishObject(ssuMappedName, ssuRef, false);

            // adding the SipSessionsUtil to the map
            (SipSessionsUtilMap.getInstance()).addSipSessionsUtil(ssuMappedName, (SipSessionsUtil) ssu);
        } catch (NamingException ne) {
            ne.printStackTrace();
        }
    }

    private void unpublishSipSessionsUtil() {
        // Unpublish the SipSessionsUtil from the JNDI namespace
        try {
            namingManager.unpublishObject("ssu" + convergedContext.getName());

            //remove the SipFactory from the Map
            SipSessionsUtil ssu = SipSessionsUtilMap.getInstance().removeSipSessionsUtil(convergedContext.getAppName());

            if (ssu != null) {
                logger.log(Level.FINE, "SipSessionsUtil object corresponding to" + convergedContext.getAppName() + "removed");
            }
        } catch (NamingException ne) {
            ne.printStackTrace();
        }
    }

    private List<String> getSupportedRfcs() {
        ArrayList<String> list = new ArrayList<String>();
        list.add("2976"); // SIP INFO
        list.add("3261"); // Session Initiation Protocol
        list.add("3262"); // Reliable Provisional Responses
        list.add("3263"); // SIP: Locating SIP Servers
        list.add("3265"); // SIP: Specific Event Notification
        list.add("3311"); // SIP: UPDATE
        list.add("3323"); // Privacy Mechanism for the SIP
        list.add("3325"); // Extensions to SIP for Asserted Identity with in
                          // trusted networks

        list.add("3327"); // Path Extension header
        list.add("3428"); // Extension for instant messaging
        list.add("3515"); // Refer method
        list.add("3581"); // Symmetric Response Routing
        list.add("3761"); // E.164 to URI, DDDS, ENUM
        list.add("3764"); // enumservice registration
        list.add("3824"); // Using E.164 numbers with in SIP

        list.add("3841"); // Caller Preferences for the SIP
        list.add("3891"); // Replaces
        list.add("3903"); // Extension for Event State Publication
        list.add("3911"); // Join
        list.add("3966"); // Tel URI
        list.add("4028"); // Session Timers
        list.add("4474"); // authenticated identity management
        list.add("4488"); // Suppression of SIP REFER -
                          //Method Implicit Subscription
        list.add("4916"); // Connected Identity
                          // list.add("draft-ietf-sip-outbound-15");
                          // Managing Clinet initiated Connections in the SIP

        return Collections.unmodifiableList(list);
    }

    protected void configureEjbReferences(ConvergedContextImpl convergedContext, SipApplication sipApplication) {
        Set set = sipApplication.getEjbReferenceDescriptors();
        Iterator iterator = set.iterator();

        EjbReferenceDescriptor ejbDescriptor;

        while (iterator.hasNext()) {
            ejbDescriptor = (EjbReferenceDescriptor) iterator.next();

            if (ejbDescriptor.isLocal()) {
                configureContextLocalEjb(convergedContext, ejbDescriptor);
            } else {
                configureContextEjb(convergedContext, ejbDescriptor);
            }
        }
    }

    protected void configureContextLocalEjb(WebModule webModule, EjbReferenceDescriptor ejbDescriptor) {
        ContextLocalEjbDecorator decorator = new ContextLocalEjbDecorator(ejbDescriptor);
        webModule.addLocalEjb(decorator);
    }

    /**
     * Configures EJB resource reference for a web application, as
     * represented in a <code>&lt;ejb-local-ref&gt;</code>element in the
     * deployment descriptor.
     */
    protected void configureContextEjb(WebModule webModule, EjbReferenceDescriptor ejbDescriptor) {
        ContextEjbDecorator decorator = new ContextEjbDecorator(ejbDescriptor);
        webModule.addEjb(decorator);
    }

    /**
     * Configure resource-reference defined in the deployment descriptor.
     */
    protected static void configureResourceRefs(WebModule webModule, SipApplication sipApp) {
        Set set = sipApp.getEnvironmentProperties();

        if (set.isEmpty()) {
            return;
        }

        Iterator iterator = set.iterator();

        EnvironmentEntry envEntry;

        while (iterator.hasNext()) {
            envEntry = (EnvironmentEntry) iterator.next();

            webModule.addResourceEnvRef(envEntry.getName(), envEntry.getType());
        }
    }

    /**
     * Configure a resource reference for a web application, as
     * represented in a <code>&lt;resource-ref&gt;</code> element in the
     * deployment descriptor.
     */
    protected void configureContextResource(WebModule webModule, SipApplication sipApp) {
        Set set = sipApp.getResourceReferenceDescriptors();

        if (set.isEmpty()) {
            return;
        }

        Iterator iterator = set.iterator();

        ResourceReferenceDescriptor resRefDesc;
        ContextResourceDecorator decorator;

        while (iterator.hasNext()) {
            resRefDesc = (ResourceReferenceDescriptor) iterator.next();
            decorator = new ContextResourceDecorator(resRefDesc);

            webModule.addResource(decorator);
        }
    }

    public void configureResources() {
        SipApplication sipApp = convergedContext.getSipApplication();
        SunSipApp sunSipApp = convergedContext.getSipApplication().getSunSipDescriptor();
        ResourceRef[] rr = sunSipApp.getResourceRef();
        DefaultResourcePrincipal drp;
        ResourcePrincipal rp;
        ResourceReferenceDescriptor resRefDesc;
        ContextResourceDecorator decorator;

        if (rr != null) {
            for (int j = 0; j < rr.length; j++) {
                if (sipApp.getResourceReferenceByName(rr[j].getResRefName()) != null) {
                    sipApp.getResourceReferenceByName(rr[j].getResRefName()).setJndiName(rr[j].getJndiName());
                    drp = rr[j].getDefaultResourcePrincipal();

                    if (drp != null) {
                        rp = new ResourcePrincipal(drp.getName(), drp.getPassword());
                        sipApp.getResourceReferenceByName(rr[j].getResRefName()).setResourcePrincipal(rp);
                    }
                }
            }
        }
    }
   
        /**
     * Configure of a message destination for a web application, as
     * represented in a <code>&lt;message-destination&gt;</code> element
     * in the deployment descriptor.
     */   
    protected static void configureMessageDestination(WebModule convergedModule,
                                                      BundleDescriptor wmd) {
                                                       
        Set set = wmd.getMessageDestinations();
        if ( set.isEmpty() ){
            return;
        }
        Iterator iterator = set.iterator();
       
        MessageDestinationDescriptor msgDrd = null;
        MessageDestinationDecorator decorator;
        while(iterator.hasNext()){
            msgDrd = (MessageDestinationDescriptor)iterator.next();
            decorator = new MessageDestinationDecorator(msgDrd);
           
            convergedModule.addMessageDestination(decorator);
        }      
                                                      
    }
   
    public void configureLocaleEncodingMappings(WebModule convergedModule,
                   BundleDescriptor sipApplication) {
      
        LocaleEncodingMappingListDescriptor lemds =
                   ((SipApplication) sipApplication).getLocaleEncodingMappingListDescriptor();
        if (lemds != null) {
            Set set2 = lemds.getLocaleEncodingMappingSet();
            Iterator iterator2 = set2.iterator();
            LocaleEncodingMappingDescriptor lemd;
            while (iterator2.hasNext()){
                lemd = (LocaleEncodingMappingDescriptor) iterator2.next();
                convergedModule.addLocaleEncodingMappingParameter(lemd.getLocale(),
                                                      lemd.getEncoding());
            }
        }
    }
}
TOP

Related Classes of com.ericsson.ssa.config.ConvergedContextConfig

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.