Example usage for java.lang.management ManagementFactory getOperatingSystemMXBean

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

Introduction

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

Prototype

public static OperatingSystemMXBean getOperatingSystemMXBean() 

Source Link

Document

Returns the managed bean for the operating system on which the Java virtual machine is running.

Usage

From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

public HandlerLoopbackLoadStress(Config config)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    this.config = config;
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();/* ww  w. j  a v  a  2s. c  o  m*/

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(), new TrustManager[] { new BlindTrustX509ExtendedTrustManager() }, null);

    mainHub = IOHub.create(executorService);
    // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector
    acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub;
    legacyHub = new NioChannelHub(executorService);
    executorService.submit(legacyHub);
    serverSocketChannel = ServerSocketChannel.open();

    JnlpProtocolHandler handler = null;
    for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub)
            .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio)
            .withClientDatabase(new JnlpClientDatabase() {
                @Override
                public boolean exists(String clientName) {
                    return true;
                }

                @Override
                public String getSecretOf(@Nonnull String clientName) {
                    return secretFor(clientName);
                }
            }).withSSLClientAuthRequired(false).handlers()) {
        if (config.name.equals(h.getName())) {
            handler = h;
            break;
        }
    }
    if (handler == null) {
        throw new RuntimeException("Unknown handler: " + config.name);
    }
    this.handler = handler;

    acceptor = new Acceptor(serverSocketChannel);
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean);
    garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>(
            ManagementFactory.getGarbageCollectorMXBeans());
    Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() {
        @Override
        public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    stats = new Stats();
}

From source file:net.bull.javamelody.internal.model.JavaInformations.java

private static long buildMaxFileDescriptorCount() {
    final OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
    if (isSunOsMBean(operatingSystem) && isSunUnixMBean(operatingSystem)) {
        try {//from   w  ww  . j av a2  s .  c o  m
            return MemoryInformations.getLongFromOperatingSystem(operatingSystem, "getMaxFileDescriptorCount");
        } catch (final Error e) {
            // pour issue 16 (using jsvc on ubuntu or debian)
            return -1;
        }
    }
    return -1;
}

From source file:org.wso2.carbon.oc.agent.internal.OCAgentDataExtractor.java

public double getSystemLoadAverage() {
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    return operatingSystemMXBean.getSystemLoadAverage();
}

From source file:sce.JobStoreTXCustom.java

public boolean checkConstraints(JobDataMap jobDataMap) {
    try {/*from   w w w.  j  a  v a2 s .c  om*/
        if (jobDataMap.containsKey("#jobConstraints")) {
            OperatingSystemMXBean omx = ManagementFactory.getOperatingSystemMXBean();
            com.sun.management.OperatingSystemMXBean osMxBean = null;
            if (omx instanceof com.sun.management.OperatingSystemMXBean) {
                osMxBean = (com.sun.management.OperatingSystemMXBean) omx;
            }
            if (osMxBean != null) {
                //read json from request
                JSONParser parser = new JSONParser();
                Object obj = parser.parse(jobDataMap.getString("#jobConstraints"));
                JSONArray jsonArray = (JSONArray) obj;
                String ipAddress = getIpAddress();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonobject = (JSONObject) jsonArray.get(i);
                    String systemParameterName = (String) jsonobject.get("systemParameterName"); //system parameter name (osArch, availableProcessors, freePhysicalMemorySize etc.)
                    String operator = (String) jsonobject.get("operator"); // ==, !=, <, >, <=, >=
                    String value = (String) jsonobject.get("value"); //value of the system parameter that must be satisfied
                    String systemParameterValue; //system parameter actual value
                    boolean ipAddressConstraint = false; //set ip address constraint as not satisfied by default

                    switch (systemParameterName) {
                    case "osArch":
                        systemParameterValue = osMxBean.getArch();
                        break;
                    case "availableProcessors":
                        systemParameterValue = Integer.toString(osMxBean.getAvailableProcessors());
                        break;
                    case "osName":
                        systemParameterValue = osMxBean.getArch();
                        break;
                    case "systemLoadAverage":
                        systemParameterValue = Double.toString(osMxBean.getSystemLoadAverage());
                        break;
                    case "osVersion":
                        systemParameterValue = osMxBean.getArch();
                        break;
                    case "committedVirtualMemorySize":
                        systemParameterValue = Long.toString(osMxBean.getCommittedVirtualMemorySize());
                        break;
                    case "freePhysicalMemorySize":
                        systemParameterValue = Long.toString(osMxBean.getFreePhysicalMemorySize());
                        break;
                    case "freeSwapSpaceSize":
                        systemParameterValue = Long.toString(osMxBean.getFreeSwapSpaceSize());
                        break;
                    case "processCpuLoad":
                        systemParameterValue = Double.toString(osMxBean.getProcessCpuLoad());
                        break;
                    case "processCpuTime":
                        systemParameterValue = Long.toString(osMxBean.getProcessCpuTime());
                        break;
                    case "systemCpuLoad":
                        systemParameterValue = Double.toString(osMxBean.getSystemCpuLoad());
                        break;
                    case "totalPhysicalMemorySize":
                        systemParameterValue = Long.toString(osMxBean.getTotalPhysicalMemorySize());
                        break;
                    case "totalSwapSpaceSize":
                        systemParameterValue = Long.toString(osMxBean.getTotalSwapSpaceSize());
                        break;
                    default:
                        systemParameterValue = null;
                    }

                    //if systemParameterName is ipAddress, and there is one ip address that is equal/not equal (depending on the operator) to the scheduler's ip address, then set the ipAddressConstraint to true
                    if (systemParameterName.equals("ipAddress")) {
                        String[] ipAddressesArray = value.split(";");
                        for (String tmp : ipAddressesArray) {
                            if ((operator.equals("==") && ipAddress.equals(tmp))
                                    || (operator.equals("!=") && !ipAddress.equals(tmp))) {
                                ipAddressConstraint = true;
                                break;
                            }
                        }
                        //if the ipAddressConstraint is false, the return false
                        if (!ipAddressConstraint) {
                            return false;
                        }
                    }

                    //if the constraint is not satisfied, then return false
                    //if systemParameterName = ipAddress, then systemParameterValue is null (default switch case) and this if condition is not satisfied
                    if (systemParameterValue != null && ((operator.equals("==")
                            && !isNumeric(systemParameterValue) && !isNumeric(value)
                            && !value.equalsIgnoreCase(systemParameterValue))
                            || (operator.equals("!=") && !isNumeric(systemParameterValue) && !isNumeric(value)
                                    && value.equalsIgnoreCase(systemParameterValue))
                            || (operator.equals("==") && isNumeric(systemParameterValue) && isNumeric(value)
                                    && Double.parseDouble(systemParameterValue) != Double.parseDouble(value))
                            || (operator.equals("!=") && isNumeric(systemParameterValue) && isNumeric(value)
                                    && Double.parseDouble(systemParameterValue) == Double.parseDouble(value))
                            || (operator.equals("<") && isNumeric(systemParameterValue) && isNumeric(value)
                                    && Double.parseDouble(systemParameterValue) >= Double.parseDouble(value))
                            || (operator.equals(">") && isNumeric(systemParameterValue) && isNumeric(value)
                                    && Double.parseDouble(systemParameterValue) <= Double.parseDouble(value))
                            || (operator.equals("<=") && isNumeric(systemParameterValue) && isNumeric(value)
                                    && Double.parseDouble(systemParameterValue) > Double.parseDouble(value))
                            || (operator.equals(">=") && isNumeric(systemParameterValue) && isNumeric(value)
                                    && Double.parseDouble(systemParameterValue) < Double.parseDouble(value)))) {
                        return false;
                    }
                }
            }
        }
        return true;
    } catch (ParseException e) {
        e.printStackTrace();
        return true;
    }
}

From source file:com.alibaba.otter.node.etl.OtterController.java

public String getNodeSystemInfo() {
    OperatingSystemMXBean mbean = ManagementFactory.getOperatingSystemMXBean();
    StringBuilder buf = new StringBuilder();
    buf.append("").append(mbean.getName()).append(' ').append(mbean.getVersion()).append(' ')
            .append(mbean.getArch());/*from  w w  w  .  ja va 2s . com*/
    buf.append(" @ ").append(mbean.getAvailableProcessors()).append(" cores");
    buf.append(" , ? load average:").append(mbean.getSystemLoadAverage()).append(" ");
    return buf.toString();
}

From source file:com.emc.ecs.sync.EcsSync.java

public void run() {
    try {//from  w ww . j a  v  a2 s . c o  m
        assert syncConfig != null : "syncConfig is null";
        assert syncConfig.getOptions() != null : "syncConfig.options is null";
        final SyncOptions options = syncConfig.getOptions();

        // Some validation (must have source and target)
        assert source != null || syncConfig.getSource() != null : "source must be specified";
        assert target != null || syncConfig.getTarget() != null : "target plugin must be specified";

        if (source == null)
            source = PluginUtil.newStorageFromConfig(syncConfig.getSource(), options);
        else
            syncConfig.setSource(source.getConfig());

        if (target == null)
            target = PluginUtil.newStorageFromConfig(syncConfig.getTarget(), options);
        else
            syncConfig.setTarget(target.getConfig());

        if (filters == null) {
            if (syncConfig.getFilters() != null)
                filters = PluginUtil.newFiltersFromConfigList(syncConfig.getFilters(), options);
            else
                filters = new ArrayList<>();
        } else {
            List<Object> filterConfigs = new ArrayList<>();
            for (SyncFilter filter : filters) {
                filterConfigs.add(filter.getConfig());
            }
            syncConfig.setFilters(filterConfigs);
        }

        // Summarize config for reference
        if (log.isInfoEnabled())
            log.info(summarizeConfig());

        // Ask each plugin to configure itself and validate the chain (resolves incompatible plugins)
        String currentPlugin = "source storage";
        try {
            source.configure(source, filters.iterator(), target);
            currentPlugin = "target storage";
            target.configure(source, filters.iterator(), target);
            for (SyncFilter filter : filters) {
                currentPlugin = filter.getClass().getSimpleName() + " filter";
                filter.configure(source, filters.iterator(), target);
            }
        } catch (Exception e) {
            log.error("Error configuring " + currentPlugin);
            throw e;
        }

        // Build the plugin chain
        Iterator<SyncFilter> i = filters.iterator();
        SyncFilter next, previous = null;
        while (i.hasNext()) {
            next = i.next();
            if (previous != null)
                previous.setNext(next);
            previous = next;
        }

        // add target to chain
        SyncFilter targetFilter = new TargetFilter(target, options);
        if (previous != null)
            previous.setNext(targetFilter);

        firstFilter = filters.isEmpty() ? targetFilter : filters.get(0);

        // register for timings
        if (options.isTimingsEnabled())
            TimingUtil.register(options);
        else
            TimingUtil.unregister(options); // in case of subsequent runs with same options instance

        log.info("Sync started at " + new Date());
        // make sure any old stats are closed to terminate the counter threads
        try (SyncStats oldStats = stats) {
            stats = new SyncStats();
        }
        stats.setStartTime(System.currentTimeMillis());
        stats.setCpuStartTime(
                ((OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getProcessCpuTime()
                        / 1000000);

        // initialize DB Service if necessary
        if (dbService == null) {
            if (options.getDbFile() != null) {
                dbService = new SqliteDbService(options.getDbFile());
            } else if (options.getDbConnectString() != null) {
                dbService = new MySQLDbService(options.getDbConnectString(), null, null);
            } else {
                dbService = new NoDbService();
            }
            if (options.getDbTable() != null)
                dbService.setObjectsTableName(options.getDbTable());
        }

        // create thread pools
        listExecutor = new EnhancedThreadPoolExecutor(options.getThreadCount(),
                new LinkedBlockingDeque<Runnable>(options.getThreadCount() * 20), "list-pool");
        estimateExecutor = new EnhancedThreadPoolExecutor(options.getThreadCount(),
                new LinkedBlockingDeque<Runnable>(options.getThreadCount() * 20), "estimate-pool");
        queryExecutor = new EnhancedThreadPoolExecutor(options.getThreadCount() * 2,
                new LinkedBlockingDeque<Runnable>(), "query-pool");
        syncExecutor = new EnhancedThreadPoolExecutor(options.getThreadCount(),
                new LinkedBlockingDeque<Runnable>(options.getThreadCount() * 20), "sync-pool");
        retrySubmitter = new EnhancedThreadPoolExecutor(options.getThreadCount(),
                new LinkedBlockingDeque<Runnable>(), "retry-submitter");

        // initialize verifier
        verifier = new Md5Verifier(options);

        // setup performance reporting
        startPerformanceReporting();

        // set status to running
        syncControl.setRunning(true);
        stats.reset();
        log.info("syncing from {} to {}", ConfigUtil.generateUri(syncConfig.getSource()),
                ConfigUtil.generateUri(syncConfig.getTarget()));

        // start estimating
        syncEstimate = new SyncEstimate();
        estimateExecutor.submit(new Runnable() {
            @Override
            public void run() {
                // do we have a list-file?
                if (options.getSourceListFile() != null) {
                    FileLineIterator lineIterator = new FileLineIterator(options.getSourceListFile());
                    while (lineIterator.hasNext()) {
                        estimateExecutor
                                .blockingSubmit(new EstimateTask(lineIterator.next(), source, syncEstimate));
                    }
                } else {
                    for (ObjectSummary summary : source.allObjects()) {
                        estimateExecutor.blockingSubmit(new EstimateTask(summary, source, syncEstimate));
                    }
                }
            }
        });

        // iterate through root objects and submit tasks for syncing and crawling (querying).
        if (options.getSourceListFile() != null) { // do we have a list-file?
            FileLineIterator lineIterator = new FileLineIterator(options.getSourceListFile());
            while (lineIterator.hasNext()) {
                if (!syncControl.isRunning())
                    break;
                final String listLine = lineIterator.next();
                listExecutor.blockingSubmit(new Runnable() {
                    @Override
                    public void run() {
                        ObjectSummary summary = source.parseListLine(listLine);
                        submitForSync(source, summary);
                        if (summary.isDirectory())
                            submitForQuery(source, summary);
                    }
                });
            }
        } else {
            for (ObjectSummary summary : source.allObjects()) {
                if (!syncControl.isRunning())
                    break;
                submitForSync(source, summary);
                if (summary.isDirectory())
                    submitForQuery(source, summary);
            }
        }

        // now we must wait until all submitted tasks are complete
        while (syncControl.isRunning()) {
            if (listExecutor.getUnfinishedTasks() <= 0 && queryExecutor.getUnfinishedTasks() <= 0
                    && syncExecutor.getUnfinishedTasks() <= 0) {
                // done
                log.info("all tasks complete");
                break;
            } else {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.warn("interrupted while sleeping", e);
                }
            }
        }

        // run a final timing log
        TimingUtil.logTimings(options);
    } catch (Throwable t) {
        log.error("unexpected exception", t);
        runError = t;
        throw t;
    } finally {
        if (!syncControl.isRunning())
            log.warn("terminated early!");
        syncControl.setRunning(false);
        if (paused) {
            paused = false;
            // must interrupt the threads that are blocked
            if (listExecutor != null)
                listExecutor.shutdownNow();
            if (estimateExecutor != null)
                estimateExecutor.shutdownNow();
            if (queryExecutor != null)
                queryExecutor.shutdownNow();
            if (retrySubmitter != null)
                retrySubmitter.shutdownNow();
            if (syncExecutor != null)
                syncExecutor.shutdownNow();
        } else {
            if (listExecutor != null)
                listExecutor.shutdown();
            if (estimateExecutor != null)
                estimateExecutor.shutdown();
            if (queryExecutor != null)
                queryExecutor.shutdown();
            if (retrySubmitter != null)
                retrySubmitter.shutdown();
            if (syncExecutor != null)
                syncExecutor.shutdown();
        }
        if (stats != null)
            stats.setStopTime(System.currentTimeMillis());

        // clean up any resources in the plugins
        cleanup();
    }
}

From source file:org.apache.syncope.core.logic.SyncopeLogic.java

private void initSystemInfo() {
    if (SYSTEM_INFO == null) {
        OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

        SYSTEM_INFO = new SystemInfo();
        try {// www . ja va2s.  c o m
            SYSTEM_INFO.setHostname(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            LOG.error("Could not get host name", e);
        }

        SYSTEM_INFO.setOs(operatingSystemMXBean.getName() + " " + operatingSystemMXBean.getVersion() + " "
                + operatingSystemMXBean.getArch());
        SYSTEM_INFO.setAvailableProcessors(operatingSystemMXBean.getAvailableProcessors());
        SYSTEM_INFO.setJvm(runtimeMXBean.getVmName() + " " + System.getProperty("java.version") + " "
                + runtimeMXBean.getVmVendor());
        SYSTEM_INFO.setStartTime(runtimeMXBean.getStartTime());
    }
}

From source file:net.bull.javamelody.internal.model.JavaInformations.java

private static double buildSystemCpuLoad() {
    // System cpu load.
    // The "recent cpu usage" for the whole system.
    // This value is a double in the [0.0,1.0] interval.
    // A value of 0.0 means that all CPUs were idle during the recent period of time observed,
    // while a value of 1.0 means that all CPUs were actively running 100% of the time during the recent period being observed.
    final OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean();
    if (SYSTEM_CPU_LOAD_ENABLED && isSunOsMBean(operatingSystem)) {
        // systemCpuLoad n'existe qu' partir du jdk 1.7
        return MemoryInformations.getDoubleFromOperatingSystem(operatingSystem, "getSystemCpuLoad") * 100;
    }/*from w w  w  . ja v  a  2  s .  c  om*/
    return -1;
}

From source file:org.pepstock.jem.node.swarm.Swarm.java

/**
 * Initializes the nodeInfo that will be store in the SWARM NODES MAP
 * /*from w  ww  .j av  a2 s  .com*/
 * @see org.pepstock.jem.gwt.server.swarm.SwarmQueues#NODES_MAP
 * @param member this hazelcast member of the swarm environment
 */
private void initNodeInfo(Member member) {
    // set uuid of member of hazelcast as key
    nodeInfo.setKey(member.getUuid());
    // set port and ip address
    InetSocketAddress address = member.getInetSocketAddress();
    nodeInfo.setPort(address.getPort());
    nodeInfo.setIpaddress(address.getAddress().getHostAddress());
    // sets label to be displayed by GRS
    nodeInfo.setLabel(nodeInfo.getIpaddress() + ":" + nodeInfo.getPort());
    // use JMX to extract current process id
    nodeInfo.setProcessId(ManagementFactory.getRuntimeMXBean().getName());
    // set hostname
    String hostname = StringUtils.substringAfter(nodeInfo.getProcessId(), "@");
    nodeInfo.setHostname(hostname);
    OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
    nodeInfo.getNodeInfoBean().setSystemArchitecture(bean.getArch());
    nodeInfo.getNodeInfoBean().setAvailableProcessors(bean.getAvailableProcessors());
    nodeInfo.getNodeInfoBean().setSystemName(bean.getName());
    ExecutionEnvironment executionEnvironment = new ExecutionEnvironment();
    // the environment will be that of jem one not the swarm one.
    executionEnvironment.setEnvironment(Main.EXECUTION_ENVIRONMENT.getEnvironment());
    nodeInfo.setExecutionEnvironment(executionEnvironment);
    nodeInfo.setJemVersion(Main.getNode().getJemVersion());
}

From source file:com.obergner.hzserver.ServerInfo.java

private OperatingSystemMXBean os() {
    return ManagementFactory.getOperatingSystemMXBean();
}