/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (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/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.webservice;

import java.util.*;

// jaxrpc spi
import com.sun.xml.rpc.spi.runtime.SystemHandlerDelegate;

import com.sun.enterprise.deployment.WebServiceEndpoint;
import com.sun.enterprise.webservice.monitoring.WebServiceEngineImpl;
import com.sun.enterprise.webservice.monitoring.WebServiceEngineFactory;
import com.sun.ejb.containers.StatelessSessionContainer;        

/**
 * This class acts as a registry of all the webservice EJB end points
 * enabled in this application server. This a singleton class, use 
 * getRegistry() to obtain the registry instance
 *
 * @author  Jerome Dochez
 */
public class WebServiceEjbEndpointRegistry {
    
    private static WebServiceEjbEndpointRegistry registry = null;
    
    // Ejb service endpoint info.  
    private Hashtable webServiceEjbEndpoints = new Hashtable();

    // Derived set of all ejb web service related context roots.  Used
    // to optimize the check that determines whether an HTTP request is 
    // for an ejb.  NOTE that ejb endpoints may share the same context
    // root, but that context root must not be used by any web application.  
    // So if the context root portion of the request is in this set, we know
    // the call is for an ejb.
    private Set ejbContextRoots = new HashSet();
    
    
    /** Creates a new instance of WebServiceEjbEndpointRegistry */
    private WebServiceEjbEndpointRegistry() {
    }
    
    /**
     * @return the registry instance
     */
    public static WebServiceEjbEndpointRegistry getRegistry() {
        if (registry==null) {
            synchronized(WebServiceEjbEndpointRegistry.class) {
                if (registry==null) {
                    registry = new WebServiceEjbEndpointRegistry();
                }
            }
        }
        return registry;        
    }
    
    public void registerEjbWebServiceEndpoint(EjbRuntimeEndpointInfo endpoint) throws Exception {
        synchronized(webServiceEjbEndpoints) {
            String uriRaw = endpoint.getEndpointAddressUri();
            String uri = (uriRaw.charAt(0)=='/') ? uriRaw.substring(1) : uriRaw;
            webServiceEjbEndpoints.put(uri, endpoint);
            regenerateEjbContextRoots();
        }
        
        // notify monitoring layers that a new endpoint is being created.
        WebServiceEngineImpl engine = (WebServiceEngineImpl) WebServiceEngineFactory.getInstance().getEngine();
        if (endpoint.getEndpoint().getWebService().getMappingFileUri()!=null) {
            engine.createHandler((com.sun.xml.rpc.spi.runtime.SystemHandlerDelegate)null, endpoint.getEndpoint());
        } else {
            engine.createHandler((com.sun.xml.ws.spi.runtime.SystemHandlerDelegate)null, endpoint.getEndpoint());            
            // Safe to assume that it's a JAXWS endpoint
            endpoint.initRuntimeInfo();
        }
    }

    public void unregisterEjbWebServiceEndpoint(String endpointAddressUri) {
        
        EjbRuntimeEndpointInfo endpoint = null;
        
        synchronized(webServiceEjbEndpoints) {
            String uriRaw = endpointAddressUri;
            String uri = (uriRaw.charAt(0)=='/') ? uriRaw.substring(1) : uriRaw;
            endpoint = (EjbRuntimeEndpointInfo) webServiceEjbEndpoints.remove(uri);
            regenerateEjbContextRoots();
        }
        
        if (endpoint==null) {
            return;
        }
        
        // notify the monitoring layers that an endpoint is destroyed
        WebServiceEngineImpl engine = (WebServiceEngineImpl) WebServiceEngineFactory.getInstance().getEngine();
        engine.removeHandler(endpoint.getEndpoint());
    }
    
    /**
     * Creates a new EjbRuntimeEndpointInfo instance depending on the type
     * and version of the web service implementation.
     * @param   
     */
    public EjbRuntimeEndpointInfo createEjbEndpointInfo(WebServiceEndpoint webServiceEndpoint,
                                  StatelessSessionContainer ejbContainer, 
                                  Object servant, Class tieClass) {
        EjbRuntimeEndpointInfo info;
        if ("1.1".compareTo(webServiceEndpoint.getWebService().getWebServicesDescriptor().getSpecVersion())>=0) {
            info = new Ejb2RuntimeEndpointInfo(webServiceEndpoint, ejbContainer, servant, tieClass);
        } else {
            info = new EjbRuntimeEndpointInfo(webServiceEndpoint, ejbContainer, servant);
        }
        return info;
    }

    public EjbRuntimeEndpointInfo getEjbWebServiceEndpoint
        (String uriRaw, String method, String query) {
        EjbRuntimeEndpointInfo endpoint = null;
        
        if (uriRaw==null || uriRaw.length()==0) {
            return null;
        }
        
        // Strip off any leading slash.
        String uri = (uriRaw.charAt(0) == '/') ? uriRaw.substring(1) : uriRaw;

        synchronized(webServiceEjbEndpoints) {

            if( method.equals("GET") ) {
                // First check for a context root match so we avoid iterating  
                // through all ejb endpoints.  This logic will be used for
                // all HTTP GETs, so it's important to reduce the overhead in
                // the likely most common case that the request is for a web 
                // component.
                String contextRoot = getContextRootForUri(uri);
                if( ejbContextRoots.contains(contextRoot) ) {
                    // Now check for a match with a specific ejb endpoint.
                    Collection values = webServiceEjbEndpoints.values();
                    for(Iterator iter = values.iterator(); iter.hasNext();) {
                        EjbRuntimeEndpointInfo next = (EjbRuntimeEndpointInfo)
                            iter.next();
                        if( next.getEndpoint().matchesEjbPublishRequest
                            (uri, query)) {
                            endpoint = next;
                            break;
                        }
                    }
                }
            } else {
                // In this case the uri must match exactly to be an ejb web
                // service invocation, so do a direct table lookup.
                endpoint = (EjbRuntimeEndpointInfo) 
                    webServiceEjbEndpoints.get(uri);
            }
        }
        return endpoint;
    }

    public Collection getEjbWebServiceEndpoints() {
        return webServiceEjbEndpoints.entrySet();
    }

    private String getContextRootForUri(String uri) {
        StringTokenizer tokenizer = new StringTokenizer(uri, "/");
        if (tokenizer.hasMoreTokens()) {
            return tokenizer.nextToken();
        } else {
            return null;
        }
        
    }

    private void regenerateEjbContextRoots() {
        synchronized(webServiceEjbEndpoints) {
            Set contextRoots = new HashSet();
            for(Iterator iter = webServiceEjbEndpoints.keySet().iterator(); 
                iter.hasNext();) {
                String uri = (String) iter.next();
                String contextRoot = getContextRootForUri(uri);
                if( (contextRoot != null) && !contextRoot.equals("") ) {
                    contextRoots.add(contextRoot);
                }
            }
            ejbContextRoots = contextRoots;
        }
    }
    
}
