/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008-2011 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$
 * -------------------------------------------------------------------------
 */

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

import org.apache.cxf.Bus;
import org.apache.cxf.message.ExchangeImpl;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageImpl;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.transport.ConduitInitiator;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.cxf.transport.http.DestinationRegistry;
import org.apache.cxf.transport.http.HTTPSession;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.soap.MessageFactory;

import java.io.IOException;
import java.net.URI;
import java.util.logging.Logger;

/**
 * Object that manages the activation/deactivation of the EJB3 endpoint.
 * @author Florent Benoit
 */
public class JOnASDestination extends AbstractHTTPDestination {

    /**
     * Logger (JDK logger used by the super classes).
     */
    private static Logger jdkLogger = Logger.getLogger(JOnASDestination.class.getName());

    /**
     * Build a new Destination.
     * @param bus the associated Bus
     * @param registry the registry of Destinations
     * @param endpointInfo the endpoint info of the destination
     * @throws IOException if super constructor fails
     */
    public JOnASDestination(final Bus bus,
                            final DestinationRegistry registry,
                            final EndpointInfo endpointInfo) throws IOException {
        super(bus, registry, endpointInfo, endpointInfo.getAddress(), false);
        registry.addDestination(this);
    }

    /**
     * @return the JDK logger used by the super class.
     */
    @Override
    protected Logger getLogger() {
        return jdkLogger;
    }

    /**
     * @return the bus used by this Destination.
     */
    public Bus getBus() {
        return this.bus;
    }

    /**
     * Invoke the web service (prepare message + exchange + session)
     * Copied from CXF ServletDestination.
     * @param context HTTP context
     * @param req HTTP request
     * @param resp HTTP response
     * @throws IOException When the Message couldn't be prepared appropriately
     */
    public void invoke(final ServletContext context,
                       final HttpServletRequest req,
                       final HttpServletResponse resp) throws IOException {

        MessageImpl inMessage = new MessageImpl();
        setupMessage(inMessage,
                     context,
                     req,
                     resp);

        ExchangeImpl exchange = new ExchangeImpl();
        exchange.setInMessage(inMessage);
        exchange.setSession(new HTTPSession(req));
        inMessage.setDestination(this);

        String oldAddress = endpointInfo.getAddress();
        ClassLoader oldCCL = Thread.currentThread().getContextClassLoader();
        try {

            endpointInfo.setAddress((String) inMessage.get(Message.REQUEST_URL));
            // Here i use MessageFactory, but any other class located in the
            // javaee-api bundle should works
            // Note This is just for SAAJ implementation class-loading
            Thread.currentThread().setContextClassLoader(MessageFactory.class.getClassLoader());
            incomingObserver.onMessage(inMessage);
        } finally {
            Thread.currentThread().setContextClassLoader(oldCCL);
            endpointInfo.setAddress(oldAddress);
        }

    }

    /**
     * Exposes this Destination's EndpointInfo
     * @return this Destination's EndpointInfo
     */
    public EndpointInfo getEndpointInfo() {
        return endpointInfo;
    }

    protected String getBasePath(String contextPath) throws IOException {

        String address = getAddress().getAddress().getValue();
        if (address == null) {
            return contextPath;
        }
        if (address.startsWith("http")) {
            return URI.create(address).getPath();
        }

        return contextPath + address;
    }

}
