/*
 * $RCSfile: ModelBusServlet.java,v $
 * $Date: 2006/01/26 14:48:59 $
 * $Revision: 1.1.2.2 $
 * $Author: andreys $
 */

/*
 * Copyright (c) 2002-2003 IST-2004-2006-511731 ModelWare - ModelBus.
 * All rights reserved.
 *
 * This software is published under the terms of the ModelBus Software License
 * 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.
 * A copy of ModelBus Software License is provided with this distribution in
 * doc/LICENSE.txt file.
 */

/*
 * ModelBusServlet.java 
 * 
 * @author Prawee Sriplakich, Andrey Sadovykh (LIP6)
 * @version $Revision: 1.1.2.2 $ $Date: 2006/01/26 14:48:59 $
 */
package org.eclipse.mddi.modelbus.adapter.infrastructure.transport.server.ws;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;

import org.apache.axis.Message;
import org.apache.log4j.Logger;
import org.eclipse.mddi.modelbus.adapter.infrastructure.LoggerConfigurator;
import org.eclipse.mddi.modelbus.adapter.infrastructure.transport.marshal.ws.SoapUtil;
import org.eclipse.mddi.modelbus.adapter.infrastructure.transport.server.AbstractServer;

public abstract class ModelBusServlet extends HttpServlet implements
        AbstractServer {

    /**
     * 
     */
    private static final long serialVersionUID = 6796675107296804862L;

    private static Logger logger = Logger.getLogger(ModelBusServlet.class);

    private String context;

    EndPointManager endPointManager;

    /**
     * dispatches incoming calls to appropriate end point (e. g. modeling
     * service)
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        logger.debug("Processing request");
        logger.debug(req);
        res.setContentType("text/xml");

        try {
            String urlPath = req.getRequestURI();
            logger.debug("path = " + urlPath);
            String relativePath = "";
            String begin = "/" + context + "/";
            if (urlPath.startsWith(begin)) {
                relativePath = urlPath.replaceFirst(begin, "");
            }
            logger.debug("relative path = " + relativePath);

            Message reqMsg = (Message) SoapUtil.messageFactory.createMessage(
                    null, req.getInputStream());

            Message respMsg;
            respMsg = (Message) SoapUtil.messageFactory.createMessage();

            try {
                // this step can produce an exception if the request message is
                // not well formed.
                SOAPEnvelope reqEnv = reqMsg.getSOAPEnvelope();
                endPointManager.execute(relativePath, reqEnv, respMsg
                        .getSOAPEnvelope());
            } catch (Exception e) {
                DefaultWsInvocationReceiver.createSoapFault(respMsg
                        .getSOAPEnvelope(), e);
            }

            OutputStream out = res.getOutputStream();
            respMsg.writeTo(out);

        } catch (SOAPException e) {
            logger.error("", e);
            throw new ServletException(e);
        }
    }

    /**
     * This is the first time that ModelBus code is executed in Tomcat Server
     * This method is invoked by the tomcat
     * 
     */
    public void init(ServletConfig config) {
        LoggerConfigurator.configure();
        logger.debug("Init ModelBus");

        // deploy every tools
        // every tools must uses the current port in order to receive requests
        // via this servlet.
        // i.e. Property AdapterStub.MODELBUS_PORT must not be set.
        logger.debug("Deploy Evry Tool");
    }

    /**
     * 
     * setDefaultPort - overrides default port settings
     * 
     * @param port
     * 
     */
    public void setDefaultPort(int port) {
        ServerManager.DEFAULT_MB_PORT = port;
        logger.debug("Setting port:" + port);
    }

    /**
     * 
     * setDefaultContext - specifies default context for current servlet
     * installation
     * 
     * @param context
     * 
     */
    public void setDefaultContext(String context) {
        this.context = context;
        logger.debug("Setting cotext:" + context);
    }

    /**
     * 
     * registerServer - registers servlet as ModelBus server in the
     * AtapterContainer by using Server Manager
     * 
     * 
     */
    public void registerServer() {
        ServerManager.getInstance().putServer(this);
    }

    /**
     * implementing AbstractServer
     */
    public void setEndPointManager(EndPointManager endPointManager) {
        this.endPointManager = endPointManager;
    }

    /**
     * @return Returns the context.
     */
    public String getContext() {
        return context;
    }

    /**
     * @return Returns the port.
     */
    public int getPort() {
        return ServerManager.DEFAULT_MB_PORT;
    }

    /**
     * dispatches incoming calls to appropriate end point (e. g. modeling
     * service)
     */
    protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1)
            throws ServletException, IOException {
        doGet(arg0, arg1);
    }

}
