
package qms.io.http;
import qms.messages.*;
import qms.queue.*;
import qms.util.*;
import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Interfaccia verso gli altri nodi del gruppo. Prevede solo di ricevere dei messaggi, non restituisce mai un risultato se non in caso di errore interno al server
 * @author  Enrico

 */
public class CoordinationInterface extends HttpServlet {
    
    /** Initializes the servlet.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
    
    /** Destroys the servlet.
     */
    public void destroy() {
        
    }
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        
        PrintWriter out = response.getWriter();
        
        InputStream input = request.getInputStream();
        try {
            Message msg = MessageFactory.decodeMessage(input);
            Logger.log("Received msg:"+msg);
            if (msg != null) {
                Controller controller = Controller.getLocalInstance();
                controller.messageReceived(msg);
            }
        } catch (Throwable t) {
            Logger.log("Error Receiving msg:"+t.getClass()+" "+t.getMessage()+" cause:"+t.getCause());
            Logger.log(t);
        }
    }
    
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "QMSNodesCoordinationInterface";
    }
    
}
