//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   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 de.ugoe.cs.autoquest.httpmonitor;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import de.ugoe.cs.autoquest.plugin.http.logdata.HttpExchange;
import de.ugoe.cs.util.console.Console;

/**
 * <p>
 * the servlet deployed in the web server that receives all recorded exchanges from the proxy. The
 * exchanges are parsed and forwarded to the provided exchange handler. If an exchange can not
 * be parsed it is discarded. Exchanges are only received via the POST HTTP method. Via the GET
 * method, the servlet provides unique ordering ids as a header parameter in the response. The
 * header parameter is named "X-AutoQUEST-OrderingId". For creating the ids it uses a provided id
 * generator.
 * </p>
 * 
 * @author Patrick Harms
 */
class HttpMonitorServlet extends HttpServlet {

    /**  */
    private static final long serialVersionUID = 1L;
    
    /**
     * the exchange handler to forward received exchanges to.
     */
    private transient HttpMonitorExchangeHandler exchangeHandler;
    
    /**
     * the id generator used to return new unique ids.
     */
    private transient IdGenerator idGenerator;

    /**
     * <p>
     * initializes the servlet with the exchange handler to which all exchanges shall be forwarded
     * and the id generator to be used for returning new ids
     * </p>
     *
     * @param exchangeHandler the exchange handler that shall receive all exchanges
     * @param idGenerator     the id generator used to generate new ids
     */
    HttpMonitorServlet(HttpMonitorExchangeHandler exchangeHandler, IdGenerator idGenerator) {
        this.exchangeHandler = exchangeHandler;
        this.idGenerator = idGenerator;
    }

    /**
     * this implements handling of doPost. For this servlet this means that
     * the data from the post request will be parsed and the contained exchanges forwarded to the
     * exchange handler.
     * 
     * (non-Javadoc)
     * @see org.mortbay.jetty.servlet.DefaultServlet#doPost(HttpServletRequest, HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        try {
            JAXBContext jaxbContext =
                JAXBContext.newInstance(HttpExchange.class.getPackage().getName());
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            
            @SuppressWarnings("unchecked")
            JAXBElement<HttpExchange> jaxObject =
                (JAXBElement<HttpExchange>) unmarshaller.unmarshal(request.getReader());
            
            exchangeHandler.handleHttpExchange(jaxObject.getValue());
        }
        catch (JAXBException e) {
            Console.printerrln
                ("could not parse incoming data --> discarding it (" + e.toString() + ")");
        }
    }

    /**
     * this implements handling of doGet. For this servlet this means that we return a unique
     * ordering id which can be used by proxies as ordering ids for requests and responses.
     * 
     * (non-Javadoc) (non-Javadoc)
     * @see HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        response.setHeader("X-AutoQUEST-OrderingId", Long.toString(idGenerator.getNextId()));
    }
    
}
