/**
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.activemq.transport.http;

import org.activemq.broker.BrokerContainer;
import org.activemq.broker.impl.BrokerContainerImpl;
import org.activemq.transport.TransportChannelListener;
import org.activemq.transport.TransportServerChannelSupport;

import javax.jms.JMSException;
import javax.servlet.ServletException;

/**
 * This servlet embeds an ActiveMQ broker inside a servlet engine which is
 * ideal for deploying ActiveMQ inside a WAR and using this servlet as a HTTP tunnel.
 *
 * @version $Revision$
 */
public class HttpEmbeddedTunnelServlet extends HttpTunnelServlet {

    private BrokerContainer broker;
    private ServletConnector transportConnector;

    public synchronized void init() throws ServletException {
        // lets initialize the ActiveMQ broker
        if (broker == null) {
            broker = createBroker();
        }
        try {
            broker.start();
        }
        catch (JMSException e) {
            throw new ServletException("Failed to start embedded broker: " + e, e);
        }
        // now lets register the listener
        TransportChannelListener listener = transportConnector.getTransportChannelListener();
        getServletContext().setAttribute("transportChannelListener", listener);
        super.init();
    }

    protected static class ServletConnector extends TransportServerChannelSupport {
        public ServletConnector(String url) {
            super(url);
        }
    }

    /**
     * Factory method to create a new broker
     */
    protected BrokerContainer createBroker() {
        BrokerContainer answer = new BrokerContainerImpl();
        String url = getConnectorURL();
        transportConnector = new ServletConnector(url);
        answer.addConnector(transportConnector);

        String brokerURL = getServletContext().getInitParameter("org.activemq.brokerURL");
        if (brokerURL != null) {
            log("Listening for internal communication on: " + brokerURL);
        }
        return answer;
    }

    protected String getConnectorURL() {
        return "http://localhost/" + getServletContext().getServletContextName();
    }
}
