List of usage examples for java.lang.management MemoryMXBean getNonHeapMemoryUsage
public MemoryUsage getNonHeapMemoryUsage();
From source file:org.apache.hadoop.gateway.websockets.WebsocketMultipleConnectionTest.java
/** * Test websocket proxying through gateway. * /*from ww w .jav a 2s . com*/ * @throws Exception */ @Test public void testMultipleConnections() throws Exception { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); final CountDownLatch latch = new CountDownLatch(MAX_CONNECTIONS); Session[] sessions = new Session[MAX_CONNECTIONS]; MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); System.gc(); final long heapt1 = memoryMXBean.getHeapMemoryUsage().getUsed(); final long nonHeapt1 = memoryMXBean.getNonHeapMemoryUsage().getUsed(); for (int i = 0; i < MAX_CONNECTIONS; i++) { sessions[i] = container.connectToServer(new WebsocketClient() { @Override public void onMessage(String message) { latch.countDown(); } }, new URI(serverUri.toString() + "gateway/websocket/ws")); } for (int i = 0; i < MAX_CONNECTIONS; i++) { /* make sure the session is active and valid before trying to connect */ if (sessions[i].isOpen() && sessions[i].getBasicRemote() != null) { sessions[i].getBasicRemote().sendText("OK"); } } latch.await(5 * MAX_CONNECTIONS, TimeUnit.MILLISECONDS); System.gc(); final long heapUsed = memoryMXBean.getHeapMemoryUsage().getUsed() - heapt1; final long nonHeapUsed = memoryMXBean.getNonHeapMemoryUsage().getUsed() - nonHeapt1; System.out.println("heapUsed = " + heapUsed); System.out.println("nonHeapUsed = " + nonHeapUsed); /* 90 KB per connection */ /* long expected = 90 * 1024 * MAX_CONNECTIONS; assertThat("heap used", heapUsed, lessThan(expected)); */ }
From source file:org.apache.hadoop.metrics.jvm.JvmMetrics.java
private void doMemoryUpdates() { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); MemoryUsage memNonHeap = memoryMXBean.getNonHeapMemoryUsage(); MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); Runtime runtime = Runtime.getRuntime(); metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed() / M); metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted() / M); metrics.setMetric("memHeapUsedM", memHeap.getUsed() / M); metrics.setMetric("memHeapCommittedM", memHeap.getCommitted() / M); metrics.setMetric("maxMemoryM", runtime.maxMemory() / M); }
From source file:org.apache.jxtadoop.metrics.jvm.JvmMetrics.java
private void doMemoryUpdates() { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); MemoryUsage memNonHeap = memoryMXBean.getNonHeapMemoryUsage(); MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed() / M); metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted() / M); metrics.setMetric("memHeapUsedM", memHeap.getUsed() / M); metrics.setMetric("memHeapCommittedM", memHeap.getCommitted() / M); }
From source file:org.artifactory.webapp.wicket.page.config.advanced.SystemInfoPage.java
/** * Return a formatted string of the system info to display * * @return//w w w. java2s .c o m */ private String collectSystemInfo() { StringBuilder infoBuilder = new StringBuilder(); StorageProperties storageProperties = ContextHelper.get().beanForType(StorageProperties.class); infoBuilder.append("Storage Info:").append("\n"); addInfo(infoBuilder, "Database Type", storageProperties.getDbType().toString()); BinaryProviderType binariesStorageType = storageProperties.getBinariesStorageType(); addInfo(infoBuilder, "Storage Type", binariesStorageType.toString()); if (BinaryProviderType.S3 == binariesStorageType) { // S3 properties addInfo(infoBuilder, "s3.bucket.name", storageProperties.getS3BucketName()); addInfo(infoBuilder, "s3.bucket.path", storageProperties.getS3BucketPath()); addInfo(infoBuilder, "s3.endpoint", storageProperties.getS3Entpoint()); // Retry properties addInfo(infoBuilder, "retry.max.retries.number", Integer.toString(storageProperties.getMaxRetriesNumber())); addInfo(infoBuilder, "retry.delay.between.retries", Integer.toString(storageProperties.getDelayBetweenRetries())); // Eventually persisted properties addInfo(infoBuilder, "eventually.persisted.max.number.of.threads", Integer.toString(storageProperties.getEventuallyPersistedMaxNumberOfThread())); addInfo(infoBuilder, "eventually.persisted.timeout", Integer.toString(storageProperties.getEventuallyPersistedTimeOut())); addInfo(infoBuilder, "eventually.dispatcher.sleep.time", Long.toString(storageProperties.getEventuallyPersistedDispatcherSleepTime())); } infoBuilder.append("\n").append("System Properties:").append("\n"); Properties properties = System.getProperties(); //// add Artifactory version to the properties, will be alphabetically sorted later. properties.setProperty(ConstantValues.artifactoryVersion.getPropertyName(), ConstantValues.artifactoryVersion.getString()); AddonsManager addonsManager = ContextHelper.get().beanForType(AddonsManager.class); addInfo(infoBuilder, "artifactory.running.mode", addonsManager.getArtifactoryRunningMode().name()); addInfo(infoBuilder, "artifactory.running.state", ContextHelper.get().isOffline() ? "Offline" : "Online"); addFromProperties(infoBuilder, properties); addHaProperties(infoBuilder); infoBuilder.append("\n").append("General JVM Info:").append("\n"); OperatingSystemMXBean systemBean = ManagementFactory.getOperatingSystemMXBean(); addInfo(infoBuilder, "Available Processors", Integer.toString(systemBean.getAvailableProcessors())); MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage(); addInfo(infoBuilder, "Heap Memory Usage-Committed", Long.toString(heapMemoryUsage.getCommitted())); addInfo(infoBuilder, "Heap Memory Usage-Init", Long.toString(heapMemoryUsage.getInit())); addInfo(infoBuilder, "Heap Memory Usage-Max", Long.toString(heapMemoryUsage.getMax())); addInfo(infoBuilder, "Heap Memory Usage-Used", Long.toString(heapMemoryUsage.getUsed())); MemoryUsage nonHeapMemoryUsage = memoryBean.getNonHeapMemoryUsage(); addInfo(infoBuilder, "Non-Heap Memory Usage-Committed", Long.toString(nonHeapMemoryUsage.getCommitted())); addInfo(infoBuilder, "Non-Heap Memory Usage-Init", Long.toString(nonHeapMemoryUsage.getInit())); addInfo(infoBuilder, "Non-Heap Memory Usage-Max", Long.toString(nonHeapMemoryUsage.getMax())); addInfo(infoBuilder, "Non-Heap Memory Usage-Used", Long.toString(nonHeapMemoryUsage.getUsed())); RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean(); StringBuilder vmArgumentBuilder = new StringBuilder(); List<String> vmArguments = RuntimemxBean.getInputArguments(); if (vmArguments != null) { for (String vmArgument : vmArguments) { if (InfoWriter.shouldMaskValue(vmArgument)) { vmArgument = Strings.maskKeyValue(vmArgument); } vmArgumentBuilder.append(vmArgument); if (vmArguments.indexOf(vmArgument) != (vmArguments.size() - 1)) { vmArgumentBuilder.append("\n"); } } } infoBuilder.append("\nJVM Arguments:\n").append(vmArgumentBuilder.toString()); return StringUtils.removeEnd(infoBuilder.toString(), "\n"); }
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()); });//from w w w . j ava 2 s . com }
From source file:org.eclipse.gyrex.cloud.internal.NodeMetricsReporter.java
@Override protected IStatus run(final IProgressMonitor monitor) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; }//from w w w .j a v a 2 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.fluentd.jvmwatcher.data.JvmStateLog.java
/** * @param clientPrixy/*from w w w . j a va2s.c om*/ * @return */ public static JvmStateLog makeJvmStateLog(JvmClientProxy clientProxy) { JvmStateLog ret = new JvmStateLog(); try { // set log time ret.logDateTime_ = System.currentTimeMillis(); // ClassLoadingMXBean ClassLoadingMXBean classLoadingBean = clientProxy.getClassLoadingMXBean(); if (null != classLoadingBean) { ret.classLoadedCount_ = classLoadingBean.getLoadedClassCount(); ret.classUnloadedCount_ = classLoadingBean.getUnloadedClassCount(); ret.classTotalLoadedCount_ = classLoadingBean.getTotalLoadedClassCount(); } // CompilationMXBean CompilationMXBean compilationBean = clientProxy.getCompilationMXBean(); if (null != compilationBean) { ret.compileTime_ = compilationBean.getTotalCompilationTime(); } // MemoryMXBean MemoryMXBean memoryBean = clientProxy.getMemoryMXBean(); if (null != memoryBean) { ret.heapSize_ = memoryBean.getHeapMemoryUsage(); ret.notheapSize_ = memoryBean.getNonHeapMemoryUsage(); ret.pendingFinalizationCount_ = memoryBean.getObjectPendingFinalizationCount(); } // ThreadMXBean ThreadMXBean threadBean = clientProxy.getThreadMXBean(); if (null != threadBean) { ret.threadCount_ = threadBean.getThreadCount(); ret.daemonThreadCount_ = threadBean.getDaemonThreadCount(); ret.peakThreadCount_ = threadBean.getPeakThreadCount(); } // OperatingSystemMXBean OperatingSystemMXBean OpeSysBean = clientProxy.getOperatingSystemMXBean(); if (null != OpeSysBean) { ret.osAvailableProcessors_ = OpeSysBean.getAvailableProcessors(); ret.osSystemLoadAverage_ = OpeSysBean.getSystemLoadAverage(); } // com.sun.management.OperatingSystemMXBean com.sun.management.OperatingSystemMXBean sunOpeSysBean = clientProxy.getSunOperatingSystemMXBean(); if (null != sunOpeSysBean) { ret.committedVirtualMemorySize_ = sunOpeSysBean.getCommittedVirtualMemorySize(); ret.freePhysicalMemorySize_ = sunOpeSysBean.getFreePhysicalMemorySize(); ret.freeSwapSpaceSize_ = sunOpeSysBean.getFreeSwapSpaceSize(); ret.processCpuTime_ = sunOpeSysBean.getProcessCpuTime(); ret.totalPhysicalMemorySize_ = sunOpeSysBean.getTotalPhysicalMemorySize(); ret.totalSwapSpaceSize_ = sunOpeSysBean.getTotalSwapSpaceSize(); } // RuntimeMXBean RuntimeMXBean runtimeBean = clientProxy.getRuntimeMXBean(); if (null != runtimeBean) { ret.jvmUpTime_ = runtimeBean.getUptime(); } // MemoryPoolMXBean Collection<MemoryPoolClientProxy> memoryPoolBeansColl = clientProxy.getMemoryPoolClientProxies(); if (null != memoryPoolBeansColl) { ret.memoryPoolStateColl_ = new ArrayList<MemoryPoolState>(); for (MemoryPoolClientProxy elem : memoryPoolBeansColl) { if (null != elem) { MemoryPoolState state = elem.getStat(); if (null != state) { // add MemoryPoolState ret.memoryPoolStateColl_.add(state); } } } } // GarbageCollectorMXBean Collection<GarbageCollectorMXBean> garbageCollBeansColl = clientProxy.getGarbageCollectorMXBeans(); if (null != garbageCollBeansColl) { ret.gcCollectorState_ = new ArrayList<GarbageCollectorState>(); for (GarbageCollectorMXBean elem : garbageCollBeansColl) { if (null != elem) { long collectionCount = elem.getCollectionCount(); long collectionTime = elem.getCollectionTime(); String memoryManagerName = elem.getName(); GarbageCollectorState state = new GarbageCollectorState(memoryManagerName, collectionCount, collectionTime); // add GarbageCollectorState ret.gcCollectorState_.add(state); } } } } catch (IOException ex) { log.error(ex); // close JvmClientProxy clientProxy.disconnect(); } catch (Exception ex) { log.error(ex); // close JvmClientProxy clientProxy.disconnect(); } return ret; }
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();//from ww w. j a v a 2 s . c o m 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 ava 2 s . c om*/ } 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); }//from www.ja va 2 s . com } 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; }