Java tutorial
/* * Copyright (c) 2012, Codice Foundation. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package org.codice.ddf.status; import java.io.IOException; import java.io.PrintWriter; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hyperic.sigar.Mem; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.json.simple.JSONValue; public class MemoryService extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger("org.codice.ddf.MemoryService"); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); writer.append(toJSON()); } static Map<String, Object> getMemoryStatus() { Map<String, Object> obj = new LinkedHashMap<String, Object>(); Sigar sigar = null; try { sigar = new Sigar(); // call it to make sure the library was loaded sigar.getPid(); Mem mem = null; try { mem = sigar.getMem(); } catch (SigarException se) { se.printStackTrace(); } obj.put("data", mem.toMap()); obj.put("type", "mem"); obj.put("time", new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()).toString()); sigar.close(); } catch (Throwable t) { logger.log(Level.SEVERE, "Failed to load sigar", t); if (sigar != null) { try { sigar.close(); } catch (Throwable t1) { // ignore } finally { sigar = null; } } } return obj; } static String toJSON() { return JSONValue.toJSONString(getMemoryStatus()); } }