/*
 * UserInterface.java
 *
 * Created on 25 marzo 2004, 15.09
 */

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

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

/**
 * Interfacia per i client, prevede di estrarre dal payload nel request http di un messaggio e della restituzione di un altro messaggio xml in risposta
 * @author  Enrico

 */
public class UserInterface 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/xml");
        
        PrintWriter out = response.getWriter();
        
        InputStream input = request.getInputStream();
        try {
            Message msg = MessageFactory.decodeMessage(input);
            Logger.log("Received from client msg:"+msg);
            if (msg != null) {                
                Controller controller = Controller.getLocalInstance();
                Message result = controller.userMessageReceived(msg);                                
                result.update();                
                out.write(result.asXML());
            }
        } catch (Throwable t) {
            Logger.log("Error Receiving msg:"+t.getClass()+" "+t.getMessage()+" cause:"+t.getCause());
            Logger.log(t);
        }
        out.close();
    }
    
    /** 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 "Short description";
    }
    
}
