/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008-2009 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: CXFWSEndpoint.java 22114 2012-02-16 13:26:15Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.ws.cxf.jaxws;

import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.jaxws.EndpointImpl;
import org.ow2.jonas.ws.cxf.http.JOnASDestination;
import org.ow2.jonas.ws.jaxws.IWSRequest;
import org.ow2.jonas.ws.jaxws.IWSResponse;
import org.ow2.jonas.ws.jaxws.IWebServiceEndpoint;
import org.ow2.jonas.ws.jaxws.PortMetaData;
import org.ow2.jonas.ws.jaxws.WSException;
import org.ow2.jonas.ws.jaxws.PortIdentifier;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * This class represents the JOnAS' view on a web service endpoint (server side).
 * @author Guillaume Sauthier
 */
public class CXFWSEndpoint implements IWebServiceEndpoint {

    /**
     * Logger.
     */
    private static Log logger = LogFactory.getLog(CXFWSEndpoint.class);

    /**
     * Wrapped CXF Endpoint.
     */
    private EndpointImpl endpoint = null;

    /**
     * The destination to execute.
     */
    private JOnASDestination destination = null;

    /**
     * Web service port description info.
     */
    private PortMetaData portMetaData;

    /**
     * Describe the WS type (EJB/POJO).
     */
    private IWebServiceEndpoint.EndpointType type;

    /**
     * The "parent" container.
     */
    private WebservicesContainer container;

    /**
     * Identifier.
     */
    private PortIdentifier identifier;

    /**
     * Construct a new WSEndpoint using CXF as JAX-WS implementation.
     * @param endpoint the wrapped CXF endpoint.
     * @param type is this endpoint a POJO or an EJB ?
     * @param pmd Metadata related to the port being exposed
     */
    public CXFWSEndpoint(final EndpointImpl endpoint,
                         final EndpointType type,
                         final PortMetaData pmd,
                         final WebservicesContainer container) {
        this.endpoint = endpoint;
        this.type = type;
        this.portMetaData = pmd;
        this.destination = (JOnASDestination) endpoint.getServer(pmd.getUrlPattern()).getDestination();
        this.container = container;

        // Create the identifier
        this.identifier = new PortIdentifier(endpoint.getServiceName(),
                                             endpoint.getEndpointName().getLocalPart());
    }

    /* (non-Javadoc)
     * @see org.ow2.jonas.ws.jaxws.IWebServiceEndpoint#getType()
     */
    public EndpointType getType() {
        return type;
    }

    /**
     * @return the port identifier of this endpoint.
     */
    public PortIdentifier getIdentifier() {
        return this.identifier;
    }

    /* (non-Javadoc)
     * @see org.ow2.jonas.ws.jaxws.IWebServiceEndpoint#invoke(org.ow2.jonas.ws.jaxws.IWSRequest, org.ow2.jonas.ws.jaxws.IWSResponse)
     */
    public void invoke(final IWSRequest request, final IWSResponse response) throws WSException {

        // Invoke the Destination !
        logger.debug("Receiving request on the thread ''{0}''", Thread.currentThread());

        Bus old = BusFactory.getThreadDefaultBus();
        try {

            Bus bus = destination.getBus();
            BusFactory.setThreadDefaultBus(bus);

            HttpServletRequest httpRequest = request.getAttribute(HttpServletRequest.class);
            HttpServletResponse httpResponse = request.getAttribute(HttpServletResponse.class);
            ServletContext servletContext = request.getAttribute(ServletContext.class);

            // Handle POST & GET messages (?WSDL is now handled through interceptors)
            destination.invoke(servletContext, httpRequest, httpResponse);

        } catch (IOException ioe) {
            throw new WSException(ioe);
        } finally {
            BusFactory.setThreadDefaultBus(old);
        }
    }

    /* (non-Javadoc)
    * @see org.ow2.jonas.ws.jaxws.IWebServiceEndpoint#start()
    */
    public void start() {
        logger.debug("Start CXFWSEndpoint[{0}]", endpoint.getEndpointName());
        endpoint.publish();
    }

    /* (non-Javadoc)
     * @see org.ow2.jonas.ws.jaxws.IWebServiceEndpoint#stop()
     */
    public void stop() {
        logger.debug("Stop CXFWSEndpoint[{0}]", endpoint.getEndpointName());
        endpoint.stop();
    }


    /**
     * Return the port info.
     * @see org.ow2.jonas.ws.jaxws.IWebServiceEndpoint#getPortMetaData()
     */
    public PortMetaData getPortMetaData() {
        return portMetaData;
    }

    /**
     * @return the destination associated to this endpoint
     */
    public JOnASDestination getDestination() {
        return this.destination;
    }

    /**
     * Prints info about the endPoint.
     */
    public void displayInfos() {
        String endpointURL = "not yet available";
        String name = endpoint.getImplementorClass().getName();
        if (portMetaData != null && portMetaData.getEndpointURL() != null) {
            endpointURL = portMetaData.getEndpointURL();
        }
        logger.info("{0} endpoint ''{1}'' available at ''{2}''", type, name, endpointURL);

        // TODO: add debug informations too
    }

}
