package com.ociweb.j2me.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class EchoServlet extends HttpServlet {
    private static final String PLAIN_CONTENT_TYPE = "text/plain";
    private static final String HTML_CONTENT_TYPE = "text/html";
    private static final String USER_AGENT_PROPERTY_NAME = "User-Agent";
    private static final String MIDP_USER_AGENT = "Profile/MIDP-1.0 Configuration/CLDC-1.0";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGetAndPost("GET", request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGetAndPost("POST", request, response);
    }

    private void doGetAndPost(String title, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userAgent = request.getHeader(USER_AGENT_PROPERTY_NAME);

        if (MIDP_USER_AGENT.equals(userAgent)) {
            // send back plain text
            response.setContentType(PLAIN_CONTENT_TYPE);
            PrintWriter out = response.getWriter();
            out.println(title + " Requests");
            Enumeration enum = request.getParameterNames();
            while (enum.hasMoreElements()) {
                String paramName = enum.nextElement().toString();
                String paramValue = request.getParameter(paramName);
                out.println(paramName + ": " + paramValue);
            }
        } else {
            // send back HTML
            response.setContentType(HTML_CONTENT_TYPE);
            PrintWriter out = response.getWriter();
            out.println("<HTML>");
            out.println("<HEAD><TITLE>" + title + " Requests</TITLE></HEAD>");
            out.println("<BODY>");
            out.println("<H3>Params:</H3>");


            Enumeration enum = request.getParameterNames();
            while (enum.hasMoreElements()) {
                String paramName = enum.nextElement().toString();
                String paramValue = request.getParameter(paramName);
                out.println("<BR>" + paramName + ": " + paramValue);
            }

            out.println("</BODY></HTML>");
        }

    }
}