JmxMonRESTgetMetrics.java 4.44 KB


import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.remote.JMXServiceURL;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import se.lil.jm.JmxMon;
import se.lil.jm.Registry;

/**
 * Servlet implementation class JmxMonRESTgetMetrics
 */
@WebServlet(description = "Gets JMX Monitors metrics", urlPatterns = { "/JmxMonREST/getMetrics" })
public class JmxMonRESTgetMetrics extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final static Logger LOGGER = Logger.getLogger(JmxMonRESTgetMetrics.class.getName());   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JmxMonRESTgetMetrics() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		try {
			StringBuffer sb = new StringBuffer();
			JmxMon mon = null;
			
			if(request.getParameterMap().containsKey("connectionString")) {
				// Check that we have a valid connection string
				JMXServiceURL url;
				try {
					url = new JMXServiceURL(request.getParameter("connectionString"));
				} catch (Exception e) {
					// Error, we need a correct connection string
					response.setStatus(400);
					response.getWriter().println("{\"error\":true,\"msg\":\"connectionString is not a correct JMX Service URL\"}");
					return;
				}
				
				// Try to find the monitor in our list
				for (JmxMon item : Registry.getList()) {
					if(item.getConString().equals(url.toString())) {
						mon = item;
					}
				}
				
				// If not found return error
				if(mon == null) {
					// Not found, create it
					response.setStatus(HttpServletResponse.SC_NOT_FOUND);
					response.getWriter().println("{\"error\":true,\"msg\":\"Can not find a monitor with connection string "+url.toString()+"\"}");
					return;
				}
			}
			
			// Loop over all monitors and output a Json array with the default set of metrics
			sb.append("{\"name\":\"" + mon.getServerName() + "\",\"error\":false,\"nvarray\":");
			sb.append("[");

			sb.append("{\"name\":\"Process CPU Used %\",\"value\":" + mon.getCPUPercent() + "}");
			sb.append(",{\"name\":\"Process Heap Used %\",\"value\":" + mon.getHeapUsedPercent() + "}");
			sb.append(",{\"name\":\"OldGen Used %\",\"value\":" + mon.getOldGenUsedPercent() + "}");
			sb.append(",{\"name\":\"GC Time (Overhead) %\",\"value\":" + mon.getGCOverhead() + "}");
			sb.append(",{\"name\":\"Process File Descriptors %\",\"value\":" + mon.getSystemFileDescriptorsPercentUsed() + "}");
			sb.append(",{\"name\":\"System Memory %\",\"value\":" + mon.getSystemMemoryPercentUsed() + "}");
			sb.append(",{\"name\":\"System Swap %\",\"value\":" + mon.getSystemSwapPercentUsed() + "}");
			sb.append(",{\"name\":\"Process Threads #\",\"value\":" + mon.getThreads() + "}");
			sb.append(",{\"name\":\"Process Loaded Classes #\",\"value\":" + mon.getLoadedClassCount() + "}");
			
			sb.append(",{\"name\":\"Process Heap Committed MB\",\"value\":" + mon.getHeapCommittedMB() + "}");
			sb.append(",{\"name\":\"Process Heap Used MB\",\"value\":" + mon.getHeapUsedMB() + "}");
			
			sb.append(",{\"name\":\"OldGen Used MB\",\"value\":" + mon.getOldGenUsedMB() + "}");
			
			sb.append(",{\"name\":\"OldGen After Last GC MB\",\"value\":" + mon.getOldGenAfterGCMB() + "}");
			sb.append(",{\"name\":\"PermGen After Last GC MB\",\"value\":" + mon.getPermGenAfterGCMB() + "}");
			
			sb.append(",{\"name\":\"System Load (per cpu)\",\"value\":" + mon.getAverageLoadPerCpu() + "}");
			sb.append(",{\"name\":\"System Load (total)\",\"value\":" + mon.getAverageLoad() + "}");
			sb.append(",{\"name\":\"Number of processors #\",\"value\":" + mon.getNumberOfCPUs() + "}");

			sb.append("]}");
			
			response.getWriter().println(sb.toString());
			
		} catch (Throwable e) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.getWriter().println("{\"error\":true,\"msg\":\""+e.toString().replace("\n"," ").trim()+"\"}");
			LOGGER.log(Level.SEVERE, e.toString());
			e.printStackTrace();
		}
	}

}