Example usage for java.lang.management ManagementFactory getMemoryMXBean

List of usage examples for java.lang.management ManagementFactory getMemoryMXBean

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getMemoryMXBean.

Prototype

public static MemoryMXBean getMemoryMXBean() 

Source Link

Document

Returns the managed bean for the memory system of the Java virtual machine.

Usage

From source file:org.cloudfoundry.identity.statsd.UaaMetricsEmitter.java

@Scheduled(fixedRate = 5000, initialDelay = 3000)
public void emitJvmVitals() {
    OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    String prefix = "vitals.jvm.";
    invokeIfPresent(prefix + "cpu.load", osBean, "getProcessCpuLoad", d -> (long) (d.doubleValue() * 100));
    statsDClient.gauge(prefix + "thread.count", threadBean.getThreadCount());
    Map<String, MemoryUsage> memory = new HashMap<>();
    memory.put("heap", memoryBean.getHeapMemoryUsage());
    memory.put("non-heap", memoryBean.getNonHeapMemoryUsage());
    memory.entrySet().stream().forEach(m -> {
        statsDClient.gauge(prefix + m.getKey() + ".init", m.getValue().getInit());
        statsDClient.gauge(prefix + m.getKey() + ".committed", m.getValue().getCommitted());
        statsDClient.gauge(prefix + m.getKey() + ".used", m.getValue().getUsed());
        statsDClient.gauge(prefix + m.getKey() + ".max", m.getValue().getMax());
    });// ww  w .j  a v  a2s. co  m

}

From source file:org.commoncrawl.util.JVMStats.java

public static void dumpMemoryStats() {

    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage();

    List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();

    long gcTime = 0;
    for (GarbageCollectorMXBean gcBean : gcBeans) {
        gcTime += gcBean.getCollectionTime();
    }//from  w w  w.java2 s  .  c  o  m

    float utilizationRatio = ((float) memHeap.getUsed()) / ((float) memHeap.getMax());

    LOG.info("Heap Size:" + memHeap.getUsed() / MBytes + " (MB) CommitSize:" + memHeap.getCommitted() / MBytes
            + " (MB) Max:" + memHeap.getMax() + " Ratio:" + utilizationRatio + " GCTime:"
            + (gcTime - lastGCTime) + "PendingFinalCnt:" + memoryMXBean.getObjectPendingFinalizationCount());

    lastGCTime = gcTime;
}

From source file:org.commoncrawl.util.JVMStats.java

public static float getHeapUtilizationRatio() {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage();

    return ((float) memHeap.getUsed()) / ((float) memHeap.getMax());
}

From source file:org.craftercms.commons.monitoring.MemoryMonitor.java

/**
 * Query all register MemoryPools to get information and create a {@link MemoryMonitor} Pojo
 * @return List with all the memory usage stats.
 */// w  w  w. ja va  2  s. c o  m
public static List<MemoryMonitor> getMemoryStats() {
    ArrayList<MemoryMonitor> memoryPoolInformation = new ArrayList<>();
    MemoryUsage heapMem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    memoryPoolInformation.add(new MemoryMonitor(HEAP_MEMORY, heapMem));
    MemoryUsage nonHeapMen = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
    memoryPoolInformation.add(new MemoryMonitor(NON_HEAP_MEMORY, nonHeapMen));

    for (MemoryPoolMXBean memMXBean : ManagementFactory.getMemoryPoolMXBeans()) {
        memoryPoolInformation.add(new MemoryMonitor(memMXBean.getName(), memMXBean.getUsage()));
    }
    return Collections.unmodifiableList(memoryPoolInformation);
}

From source file:org.easyrec.controller.dev.InfoController.java

public ModelAndView home(HttpServletRequest request, HttpServletResponse httpServletResponse) {
    String tenantId = ServletUtils.getSafeParameter(request, "tenantId", "");
    String operatorId = ServletUtils.getSafeParameter(request, "operatorId", "");

    ModelAndView mav = new ModelAndView("page");

    mav.addObject("title", "??::?");

    mav.addObject("operatorId", operatorId);
    mav.addObject("tenantId", tenantId);

    if (Security.isDeveloper(request)) {
        mav.setViewName("dev/page");
        mav.addObject("page", "home");
        mav.addObject("operatorCount", operatorDAO.count());
        mav.addObject("tenantCount", remoteTenantDAO.count());
        mav.addObject("dbName", operatorDAO.getDbName());
        mav.addObject("dbUserName", operatorDAO.getDbUserName());
        mav.addObject("signedinOperatorId", Security.signedInOperatorId(request));

        mav.addObject("heapsize",
                ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax() / (1000000));
        mav.addObject("usedmemory",
                ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / (1000000));

        int computationTimeInMilliseconds = logEntryDAO.getComputationDurationForDate() * 1000;
        String computationTime = HumanTime.approximately(computationTimeInMilliseconds);
        computationTime = computationTime.replaceAll("ms", "@1");
        computationTime = computationTime.replaceAll("s", "@2");
        computationTime = computationTime.replaceAll("m", "@3");
        computationTime = computationTime.replaceAll("h", "@4");
        computationTime = computationTime.replaceAll("d", "@5");
        computationTime = computationTime.replaceAll("@1", "milliseconds");
        computationTime = computationTime.replaceAll("@2", "seconds");
        computationTime = computationTime.replaceAll("@3", "minutes");
        computationTime = computationTime.replaceAll("@4", "hours");
        computationTime = computationTime.replaceAll("@5", "days");
        mav.addObject("dailyComputationTime", computationTime);

        long freeSpace = 0L;

        try {//from w  w w  . j av  a2s  .com
            freeSpace = FileSystemUtils.freeSpaceKb(System.getProperties().getProperty("user.dir"));
        } catch (IOException e) {
            logger.error("Could not check free Free Disc Space :" + e.getMessage());
        }

        mav.addObject("freespace", freeSpace / 1048576);

        return mav;
    } else {
        return MessageBlock.createSingle(mav, MSG.NOT_SIGNED_IN, HOME, MSG.ERROR);
    }
}

From source file:org.easyrec.controller.dev.InfoController.java

public ModelAndView pullusedmem(HttpServletRequest request, HttpServletResponse httpServletResponse) {
    String tenantId = ServletUtils.getSafeParameter(request, "tenantId", "");
    String operatorId = ServletUtils.getSafeParameter(request, "operatorId", "");

    ModelAndView mav = new ModelAndView("page");

    mav.addObject("title", "??::?");

    mav.addObject("operatorId", operatorId);
    mav.addObject("tenantId", tenantId);

    if (Security.isDeveloper(request)) {
        return MessageBlock.createSingle(mav, MSG.OPERATION_SUCCESSFUL,
                Long.toString(ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / (1000000)),
                MSG.SUCCESS);/*  w  w  w. j ava2 s . c  o m*/
    } else {
        return MessageBlock.createSingle(mav, MSG.NOT_SIGNED_IN, PULL_USED_MEM, MSG.ERROR);
    }
}

From source file:org.eclipse.gyrex.cloud.internal.NodeMetricsReporter.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }//ww  w. j  a  va2  s. c o m

    try {
        final Properties metrics = new Properties() {
            private static final long serialVersionUID = 1L;

            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(keySet());
            }

            @Override
            public Set<Object> keySet() {
                return new TreeSet<Object>(super.keySet());
            }
        };
        final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        metrics.setProperty("os.availableProcessors",
                String.valueOf(operatingSystemMXBean.getAvailableProcessors()));
        metrics.setProperty("os.systemLoadAverage",
                String.valueOf(operatingSystemMXBean.getSystemLoadAverage()));
        metrics.setProperty("os.committedVirtualMemorySize",
                getUsingReflection(operatingSystemMXBean, "getCommittedVirtualMemorySize"));
        metrics.setProperty("os.totalSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getTotalSwapSpaceSize"));
        metrics.setProperty("os.freeSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getFreeSwapSpaceSize"));
        metrics.setProperty("os.processCpuTime",
                getUsingReflection(operatingSystemMXBean, "getProcessCpuTime"));
        metrics.setProperty("os.freePhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getFreePhysicalMemorySize"));
        metrics.setProperty("os.totalPhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getTotalPhysicalMemorySize"));
        metrics.setProperty("os.openFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getOpenFileDescriptorCount"));
        metrics.setProperty("os.maxFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getMaxFileDescriptorCount"));

        final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        metrics.setProperty("heap.used", String.valueOf(heapMemoryUsage.getUsed()));
        metrics.setProperty("heap.committed", String.valueOf(heapMemoryUsage.getCommitted()));
        metrics.setProperty("heap.max", String.valueOf(heapMemoryUsage.getMax()));
        metrics.setProperty("heap.init", String.valueOf(heapMemoryUsage.getInit()));
        final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        metrics.setProperty("nonHeap.used", String.valueOf(nonHeapMemoryUsage.getUsed()));
        metrics.setProperty("nonHeap.committed", String.valueOf(nonHeapMemoryUsage.getCommitted()));
        metrics.setProperty("nonHeap.max", String.valueOf(nonHeapMemoryUsage.getMax()));
        metrics.setProperty("nonHeap.init", String.valueOf(nonHeapMemoryUsage.getInit()));

        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        metrics.setProperty("thread.count", String.valueOf(threadMXBean.getThreadCount()));
        metrics.setProperty("thread.peak", String.valueOf(threadMXBean.getPeakThreadCount()));
        metrics.setProperty("thread.totalStarted", String.valueOf(threadMXBean.getTotalStartedThreadCount()));

        final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        metrics.setProperty("uptime", String.valueOf(runtimeMXBean.getUptime()));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final NodeInfo nodeInfo = CloudState.getNodeInfo();
        metrics.store(out, String.valueOf(nodeInfo));
        ZooKeeperGate.get().writeRecord(IZooKeeperLayout.PATH_NODES_METRICS.append(nodeInfo.getNodeId()),
                CreateMode.PERSISTENT, out.toByteArray());
        if (CloudDebug.nodeMetrics) {
            LOG.debug("Node metrics reported successfully.{}{}", SystemUtils.LINE_SEPARATOR,
                    new String(out.toByteArray(), CharEncoding.ISO_8859_1));
        }
    } catch (final Exception e) {
        LOG.warn("Failed to update node metrics. {}", e.getMessage());
    } finally {
        // reschedule
        schedule(DELAY);
    }

    return Status.OK_STATUS;
}

From source file:org.jahia.bin.errors.ErrorFileDumper.java

public static void outputSystemInfo(PrintWriter strOut, boolean systemProperties, boolean environmentVariables,
        boolean jahiaSettings, boolean memory, boolean caches, boolean threads, boolean deadlocks,
        boolean loadAverage) {

    if (systemProperties) {
        // now let's output the system properties.
        strOut.println();/* w  w w .  j  a  va2  s  .  c om*/
        strOut.println("System properties:");
        strOut.println("-------------------");
        Map<Object, Object> orderedProperties = new TreeMap<Object, Object>(System.getProperties());
        Iterator<Map.Entry<Object, Object>> entrySetIter = orderedProperties.entrySet().iterator();
        while (entrySetIter.hasNext()) {
            Map.Entry<Object, Object> curEntry = entrySetIter.next();
            String curPropertyName = (String) curEntry.getKey();
            String curPropertyValue = (String) curEntry.getValue();
            strOut.println("   " + curPropertyName + " : " + curPropertyValue);
        }
    }

    if (environmentVariables) {
        // now let's output the environment variables.
        strOut.println();
        strOut.println("Environment variables:");
        strOut.println("-------------------");
        Map<String, String> orderedProperties = new TreeMap<String, String>(System.getenv());
        Iterator<Map.Entry<String, String>> entrySetIter = orderedProperties.entrySet().iterator();
        while (entrySetIter.hasNext()) {
            Map.Entry<String, String> curEntry = entrySetIter.next();
            String curPropertyName = curEntry.getKey();
            String curPropertyValue = curEntry.getValue();
            strOut.println("   " + curPropertyName + " : " + curPropertyValue);
        }
    }

    if (jahiaSettings) {
        strOut.println();

        if (SettingsBean.getInstance() != null) {
            strOut.append("Server configuration (").append(Jahia.getFullProductVersion()).append(" - ")
                    .append(Jahia.getBuildDate()).append("):");
            strOut.println();
            strOut.println("---------------------");
            SettingsBean settings = SettingsBean.getInstance();
            Map<Object, Object> jahiaOrderedProperties = new TreeMap<Object, Object>(
                    settings.getPropertiesFile());
            Iterator<Map.Entry<Object, Object>> jahiaEntrySetIter = jahiaOrderedProperties.entrySet()
                    .iterator();
            while (jahiaEntrySetIter.hasNext()) {
                Map.Entry<Object, Object> curEntry = jahiaEntrySetIter.next();
                String curPropertyName = (String) curEntry.getKey();
                String curPropertyValue = null;
                if (curEntry.getValue() == null) {
                    curPropertyValue = null;
                } else if (curEntry.getValue() instanceof String) {
                    curPropertyValue = (String) curEntry.getValue();
                } else {
                    curPropertyValue = curEntry.getValue().toString();
                }
                if (curPropertyName.toLowerCase().indexOf("password") == -1
                        && (!"mail_server".equals(curPropertyName)
                                || !StringUtils.contains(curPropertyValue, "&password=")
                                        && !StringUtils.contains(curPropertyValue, "?password="))) {
                    strOut.println("   " + curPropertyName + " = " + curPropertyValue);
                }
            }
        }
    }

    if (memory) {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
        printMemoryUsage(MemoryType.HEAP.toString(), memoryUsage, strOut);
        memoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        printMemoryUsage(MemoryType.NON_HEAP.toString(), memoryUsage, strOut);

        strOut.println("--------------");
        strOut.println("Memory pool details");
        strOut.println("--------------");
        List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
        for (MemoryPoolMXBean bean : memoryPoolMXBeans) {
            printMemoryUsage("Memory Pool \"" + bean.getName() + "\" (" + bean.getType().toString() + ")",
                    bean.getUsage(), strOut);
        }
    }

    if (caches) {
        strOut.println();
        DecimalFormat percentFormat = new DecimalFormat("###.##");
        if (SpringContextSingleton.getInstance().isInitialized()
                && (ServicesRegistry.getInstance().getCacheService() != null)) {
            strOut.println("Cache status:");
            strOut.println("--------------");

            // non Ehcaches
            SortedSet<String> sortedCacheNames = new TreeSet<>(
                    ServicesRegistry.getInstance().getCacheService().getNames());
            for (String sortedCacheName : sortedCacheNames) {
                final Cache<Object, Object> objectCache = ServicesRegistry.getInstance().getCacheService()
                        .getCache(sortedCacheName);
                if (objectCache != null
                        && !(((Cache<?, ?>) objectCache).getCacheImplementation() instanceof EhCacheImpl)) {
                    String efficiencyStr = "0";
                    if (!Double.isNaN(objectCache.getCacheEfficiency())) {
                        efficiencyStr = percentFormat.format(objectCache.getCacheEfficiency());
                    }
                    strOut.println(sortedCacheName + ": size=" + objectCache.size() + ", successful hits="
                            + objectCache.getSuccessHits() + ", total hits=" + objectCache.getTotalHits()
                            + ", efficiency=" + efficiencyStr + "%");
                }
            }
        }

        // Ehcaches
        List<CacheManager> cacheManagers = CacheManager.ALL_CACHE_MANAGERS;
        for (CacheManager ehcacheManager : cacheManagers) {
            String[] ehcacheNames = ehcacheManager.getCacheNames();
            java.util.Arrays.sort(ehcacheNames);
            for (String ehcacheName : ehcacheNames) {
                Ehcache ehcache = ehcacheManager.getEhcache(ehcacheName);
                strOut.append(ehcacheName).append(": ");
                if (ehcache != null) {
                    StatisticsGateway ehcacheStats = ehcache.getStatistics();
                    String efficiencyStr = "0";
                    if (ehcacheStats.cacheHitCount() + ehcacheStats.cacheMissCount() > 0) {
                        efficiencyStr = percentFormat.format(ehcacheStats.cacheHitCount() * 100f
                                / (ehcacheStats.cacheHitCount() + ehcacheStats.cacheMissCount()));
                    }
                    strOut.append("size=" + ehcacheStats.getSize() + ", successful hits="
                            + ehcacheStats.cacheHitCount() + ", total hits="
                            + (ehcacheStats.cacheHitCount() + ehcacheStats.cacheMissCount()) + ", efficiency="
                            + efficiencyStr + "%");
                    strOut.println();
                }
            }
        }
    }

    ThreadMonitor threadMonitor = null;
    if (threads) {
        strOut.println();
        strOut.println("Thread status:");
        strOut.println("--------------");
        threadMonitor = ThreadMonitor.getInstance();
        threadMonitor.generateThreadInfo(strOut);
    }

    if (deadlocks) {
        strOut.println();
        strOut.println("Deadlock status:");
        threadMonitor = threadMonitor != null ? threadMonitor : ThreadMonitor.getInstance();
        ;
        String deadlock = threadMonitor.findDeadlock();
        strOut.println(deadlock != null ? deadlock : "none");
    }

    if (loadAverage) {
        strOut.println();
        strOut.println("Request load average:");
        strOut.println("---------------------");
        RequestLoadAverage info = RequestLoadAverage.getInstance();
        if (info != null) {
            strOut.println("Over one minute=" + info.getOneMinuteLoad() + " Over five minute="
                    + info.getFiveMinuteLoad() + " Over fifteen minute=" + info.getFifteenMinuteLoad());
        } else {
            strOut.println("not available");
        }
        strOut.println();
    }

    strOut.flush();
}

From source file:org.jwebsocket.plugins.system.SystemPlugIn.java

private void getJVMInfo(WebSocketConnector aConnector, Token aToken) {
    // check if user is allowed to run 'getjvminfo' command
    if (!hasAuthority(aConnector, NS_SYSTEM + ".getjvminfo")) {
        sendToken(aConnector, aConnector, createAccessDenied(aToken));
        return;/*from   w w w  .  j  a va  2  s. c o m*/
    }

    Token lResponse = createResponse(aToken);
    RuntimeMXBean lBean = ManagementFactory.getRuntimeMXBean();
    MemoryMXBean lMemory = ManagementFactory.getMemoryMXBean();
    OperatingSystemMXBean lOS = ManagementFactory.getOperatingSystemMXBean();

    lResponse.setMap("data", new MapAppender().append("inputArguments", lBean.getInputArguments())
            .append("libraryPath", lBean.getLibraryPath())
            .append("managementSpecVersion", lBean.getManagementSpecVersion()).append("name", lBean.getName())
            .append("specName", lBean.getSpecName()).append("specVendor", lBean.getSpecVendor())
            .append("specVersion", lBean.getSpecVersion()).append("startTime", lBean.getStartTime())
            .append("systemProperties", lBean.getSystemProperties()).append("uptime", lBean.getUptime())
            .append("vmName", lBean.getVmName()).append("vmVendor", lBean.getVmVendor())
            .append("vmVersion", lBean.getVmVersion()).append("classPath", lBean.getClassPath())
            .append("osArch", lOS.getArch()).append("osAvailableProcessors", lOS.getAvailableProcessors())
            .append("osName", lOS.getName()).append("osVersion", lOS.getVersion())
            .append("osLoadAverage", lOS.getSystemLoadAverage())
            .append("heapMemoryUsed", lMemory.getHeapMemoryUsage().getUsed())
            .append("heapMemoryMax", lMemory.getHeapMemoryUsage().getMax())
            .append("heapMemoryInit", lMemory.getHeapMemoryUsage().getInit())
            .append("nonheapMemoryInit", lMemory.getNonHeapMemoryUsage().getInit())
            .append("nonheapMemoryMax", lMemory.getNonHeapMemoryUsage().getMax())
            .append("nonheapMemoryUsed", lMemory.getNonHeapMemoryUsage().getUsed()).getMap());

    sendToken(aConnector, lResponse);
}

From source file:org.liferayhub.pc.service.impl.PowerConsoleServiceImpl.java

public String runCommand(long userId, long companyId, String mode, String command) {
    String response = "";
    Date startDate = new Date();
    if ("server".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the Liferay Portal\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "uptime\t\t  Display the uptime of the portal\n" + "adduser\t\t Add a new user";
        } else if ("version".equalsIgnoreCase(command)) {
            response = ReleaseInfo.getReleaseInfo() + " running on "
                    + StringUtil.upperCaseFirstLetter(ServerDetector.getServerId());
        } else if ("date".equalsIgnoreCase(command)) {
            response = new Date().toString();
        } else if ("uptime".equalsIgnoreCase(command)) {
            response = getUptime(PortalUtil.getUptime().getTime());
        } else if (command.toLowerCase().startsWith("adduser")) {
            response = handleAddUser(userId, companyId, command);
        }// w  ww. j  a v  a2  s . c  o m
    } else if ("db".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the database\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "<sql query>\t Display result of any SQL query";
        } else if ("date".equalsIgnoreCase(command)) {
            response = runSQLQuery("select now() \"\"");
        } else if ("version".equalsIgnoreCase(command)) {
            response = runSQLQuery(
                    "select '" + DBFactoryUtil.getDBFactory().getDB().getType() + "' as '', version() ''");
        } else
            response = runSQLQuery(command);
    } else if ("jvm".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\tShow this help message\n"
                    + "mem\t\t Display memory usage of the JVM\n"
                    + "osinfo\t  Display operating system info of the running JVM\n"
                    + "vminfo\t  Display VM info";
        } else if ("mem".equalsIgnoreCase(command)) {
            MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
            response = "Heap        : " + mem.getHeapMemoryUsage().toString();
            response += "\nNon Heap    : " + mem.getNonHeapMemoryUsage().toString();
            response += "\nFinalization: " + mem.getObjectPendingFinalizationCount() + " objects pending";
        } else if ("osinfo".equalsIgnoreCase(command)) {
            OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
            response = os.getName() + "[" + os.getArch() + "] " + os.getVersion() + " ("
                    + os.getAvailableProcessors() + " processors)";
            response += "\nLoad Average: " + os.getSystemLoadAverage();
        } else if ("vminfo".equalsIgnoreCase(command)) {
            RuntimeMXBean vm = ManagementFactory.getRuntimeMXBean();
            response = vm.getVmName() + " " + vm.getVmVersion() + " by " + vm.getVmVendor();
            response += "\n" + vm.getSpecName() + " " + vm.getSpecVersion() + " by " + vm.getSpecVendor();
            response += "\nStarted at: " + DateFormat.getInstance().format(new Date(vm.getStartTime()));
            response += "\nUptime    : " + getUptime(vm.getStartTime());
        } else {
            response = UNRECOGNIZED_COMMAND;
        }
    }
    // save command to database if it is not 'help'
    if (!command.startsWith("help")) {
        try {
            // add to history
            Date endDate = new Date();
            long id = CounterLocalServiceUtil.increment(CommandHistory.class.getName());
            CommandHistory history = CommandHistoryLocalServiceUtil.createCommandHistory(id);
            history.setCommand(command);
            history.setExecutionDate(startDate);
            history.setExecutionTime(endDate.getTime() - startDate.getTime());
            history.setMode(mode);
            history.setUserId(userId);
            CommandHistoryLocalServiceUtil.updateCommandHistory(history);
            // TODO: delete the oldest entry > MAX_HISTORY_SIZE
            // get the history size
            long historySize = 100;
            List<CommandHistory> historyList = CommandHistoryLocalServiceUtil
                    .findCommandHistoryByUserId(userId);
            if (historyList.size() >= historySize) {
                CommandHistoryLocalServiceUtil.deleteCommandHistory(historyList.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
    return response;
}