import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;

public class SystemMonitor extends HttpServlet
{
    
    private String adjust(long val)
    {
        int mils = 0;
        int thou = 0;
        
        if(val > 1000000) //million
        {
            mils = (int) (val / 1000000);
            val = val % 1000000;
        }
        if(val > 1000) //thousands
        {
            thou = (int) (val / 1000);
        }
        
        if(mils > 0)
        {
            String result = "" + thou;
            while(result.length() < 3)
            {
                result = "0" + result;
            }
            return(mils + "." + result + "M");
        }
        else
        {
            return(thou + "k");
        }
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<head>");
        out.println("<title>Hello World!</title>");
        out.println("</head>");
        out.println("<body>");
               
        Runtime runtime = Runtime.getRuntime();
        
        int procs = runtime.availableProcessors();
        String max = adjust(runtime.maxMemory());
        String total = adjust(runtime.totalMemory());
        String used = adjust(runtime.totalMemory() - runtime.freeMemory());
        String free = adjust(runtime.freeMemory());
        
        String hostName = request.getServerName();
        String date = (new Date()).toString();
        out.println("<h1>Current Performance Statistics</h1>");
        out.println("<h2>For " + hostName + "</h2>");
        out.println("<h3>As of " + date + "</h3>");
        
        out.println("<BR><BR>Available processors: " + procs);
        out.println("<BR>Maximum memory available (total expandable to): " + max);
        out.println("<BR>Total memory allocated to JVM (used and unused): " + total);
        out.println("<BR>Used memory (memory in use): " + used);
        out.println("<BR>Free memory (memory unused): " + free);

        out.println("<BR><BR><BR>Active Thread Count: " + Thread.activeCount());
        
        
        out.println("</body>");
        out.println("</html>");
    }
    
    public String getRequestURL(HttpServletRequest request)
    {
        return(request.getScheme() + "://" +
            request.getServerName() + ":" +
            request.getServerPort() +
            request.getRequestURI());
    }
}