/*
 * 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.logging.Level;
import java.lang.reflect.Method;
import java.rmi.UnmarshalException;

import com.sun.enterprise.webservice.monitoring.EndpointImpl;

import com.sun.xml.ws.spi.runtime.SystemHandlerDelegate;
import com.sun.xml.ws.spi.runtime.MessageContext;
import com.sun.enterprise.webservice.monitoring.JAXWSEndpointImpl;

import com.sun.enterprise.Switch;
import com.sun.ejb.Container;
import com.sun.ejb.Invocation;
import com.sun.enterprise.InvocationManager;

/**
 *
 * @author dochez
 */
public class Ejb3SystemHandlerDelegate implements SystemHandlerDelegate {
    
    private JAXWSEndpointImpl endpoint;
    private WsUtil wsUtil = new WsUtil();
    
    /** Creates a new instance of Ejb3SystemHandlerDelegate */
    public Ejb3SystemHandlerDelegate(JAXWSEndpointImpl endpoint) {
        this.endpoint = endpoint;
    }
    

   /**
    * The processRequest method is invoked with an object that
    * implements com.sun.xml.rpc.spi.runtime.SOAPMessageContext.
    * <p>
    * When this method is called by the WSServletDelegate
    * (on the server side of jaxws servlet container invocation processing)
    * it must be called just before the call to implementor.getTie().handle(),
    * and at the time of the request message and the following properties
    * must have been set on the SOAPMessageContext.
    * <p>
    * com.sun.xml.rpc.server.http.MessageContextProperties.IMPLEMENTOR
    * <br>
    * This property must be set to the com.sun.xml.rpc.spi.runtime.Implementor
    * object corresponding to the target endpoint.
    *
    * NOTE: I'd like us to be able to hang the ServletAuthContext off the Implementor.
    *
    * <p>
    * com.sun.xml.rpc.server.http.MessageContextProperties.HTTP_SERVLET_REQUEST
    * <br>
    * This property must be
    * set to the javax.servlet.http.HttpServletRequest object containing the
    * JAXWS invocation.
    * <p>
    * com.sun.xml.rpc.server.http.MessageContextProperties.HTTP_SERVLET_RESPONSE
    * <br>
    * This property must be
    * set to the javax.servlet.http.HttpServletResponse object corresponding to
    * the JAXWS invocation.
    * <p>
    * com.sun.xml.rpc.server.MessageContextProperties.HTTP_SERVLET_CONTEXT
    * <br>
    * This property must be
    * set to the javax.servlet.ServletContext object corresponding to web application
    * in which the JAXWS servlet is running.
    * @param messageContext the SOAPMessageContext object containing the request
    * message and the properties described above.
    * @return true if processing by the delegate was such that the caller
    * should continue with its normal message processing. Returns false if the
    * processing by the delegate resulted in the messageContext containing a response
    * message that should be returned without the caller proceding to its normal
    * message processing.
    * @throws java.lang.RuntimeException when the processing by the delegate failed,
    * without yielding a response message. In this case, the expectation is that
    * the caller will return a HTTP layer response code reporting that an internal
    * error occured.
    */
    public boolean processRequest(MessageContext messageContext)throws Exception {
        String messageID = (String) messageContext.get(EndpointImpl.MESSAGE_ID);
        System.out.println("process request : Message ID " + messageID);
        
        // Trace if necessary
        if (messageID!=null || (endpoint!=null && endpoint.hasListeners())) {
            endpoint.processRequest(messageContext);
        }      
    
        if (endpoint.getDescriptor().hasHandlerChain()) {
            
            // some handlers are defined. 
            Switch theSwitch = Switch.getSwitch();
            InvocationManager invManager = theSwitch.getInvocationManager();
            Invocation inv = (Invocation) invManager.getCurrentInvocation();
            Container container = (Container) inv.container;
            
            Method m = messageContext.getMethod();
            if (m!=null) {                
                try {
                    inv.method = m;

                    inv.setWebServiceMethod(inv.method);
               
                    if ( !container.authorize(inv) ) {
                        inv.exception = new Exception
                            ("Client not authorized for invocation of " 
                             + inv.method);
                    }
                } catch(Exception e) {
                    String errorMsg = "Error unmarshalling method for ejb " 
                            + endpoint.getDescriptor().getEjbComponentImpl().getName();
                    inv.exception = new UnmarshalException(errorMsg); 
                    inv.exception.initCause(e);
                }
            } else {
                inv.setWebServiceMethod(null);
            }
        
            if( inv.exception != null ) {
                WsUtil.getDefaultLogger().log(Level.WARNING, "preRequestHandlerHook", inv.exception);
                // TODO : I need access to the SAAJ 1.3 to write the soap fault,
                // commenting for now
                wsUtil.throwSOAPFaultException(inv.exception.getMessage(),
                        messageContext);
            }
        }        
        return true;
    }

             
    /**
     * Called after request handlers are invoked
     */
    public void preInvokeEndpointHook(MessageContext messageContext) {
       
        
        if (endpoint.getDescriptor().hasHandlerChain()) {
            // some handlers are defined. 
            Switch theSwitch = Switch.getSwitch();
            InvocationManager invManager = theSwitch.getInvocationManager();
            Invocation inv = (Invocation) invManager.getCurrentInvocation();
            Container container = (Container) inv.container;
            
            Method m = messageContext.getMethod();
            if (m!=null) {
                try {                    
                    Method webServiceMethodInPreHandler = inv.getWebServiceMethod();
                    
                    if( webServiceMethodInPreHandler != null ) {
                        // Now that application handlers have run, do another method
                        // lookup and compare the results with the original one.  This
                        // ensures that the application handlers have not changed
                        // the message context in any way that would impact which
                        // method is invoked.
                        if( !webServiceMethodInPreHandler.equals(m) ) {
                            inv.exception = new UnmarshalException
                                    ("Original method " + webServiceMethodInPreHandler +
                                    " does not match post-handler method " + m);
                        }
                    }
                } catch(Exception e) {
                    String errorMsg = "Exception while getting method for " +
                            ((inv != null ) ?
                                ((Container) inv.container).getEjbDescriptor().getName() : "");
                    inv.exception = new UnmarshalException(errorMsg);
                    inv.exception.initCause(e);
                }
                
                if( inv.exception != null ) {
                    WsUtil.getDefaultLogger().log(Level.WARNING, "postEjbHandlerError", inv.exception);

                    wsUtil.throwSOAPFaultException(inv.exception.getMessage(),
                          messageContext);
                }
            }
        }
    }
    
   /**
    * The processResponse method is invoked with an object that
    * implements com.sun.xml.rpc.spi2.runtime.SOAPMessageContext.
    * <p>
    * When this method is called by the WSServletDelegate
    * (on the server side of jaxws servlet container invocation processing)
    * it must be called just just after the call to implementor.getTie().handle().
    * In the special case where the handle method throws an exception, the
    * processResponse message must not be called.
    * <p>
    * The SOAPMessageContext passed to the processRequest and handle messages is
    * passed to the processResponse method.
    * @throws java.lang.RuntimeException when the processing by the delegate failed,
    * in which case the caller is expected to return an HTTP layer
    * response code reporting that an internal error occured.
    */
    public void processResponse(MessageContext messageContext) throws Exception {
        String messageID = (String) messageContext.get(EndpointImpl.MESSAGE_ID);
        System.out.println("process response : Message ID " + messageID);
        
        // Trace if necessary
        if (messageID!=null || (endpoint!=null && endpoint.hasListeners())) {
            endpoint.processResponse(messageContext);
        }      
    }    
}
