Example usage for java.lang.management ManagementFactory getRuntimeMXBean

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

Introduction

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

Prototype

public static RuntimeMXBean getRuntimeMXBean() 

Source Link

Document

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

Usage

From source file:com.eurelis.opencms.admin.systeminformation.CmsSystemInformationOverviewDialog.java

/**
 * Initializes the infos object.<p>
 *///from  w  ww.j  a v  a 2  s .  c  om
protected void initInfosObject() {

    com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    java.lang.management.OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    java.lang.management.ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    java.lang.management.RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    java.lang.management.ClassLoadingMXBean classesBean = ManagementFactory.getClassLoadingMXBean();

    //JVM uptime
    Date date = new Date(runtimeBean.getUptime());
    java.text.SimpleDateFormat simpleFormatH = new java.text.SimpleDateFormat("HH");
    java.text.SimpleDateFormat simpleFormatM = new java.text.SimpleDateFormat("mm");
    java.text.SimpleDateFormat simpleFormatS = new java.text.SimpleDateFormat("ss");
    String jvmuptimestring = simpleFormatH.format(date) + "h " + simpleFormatM.format(date) + "min "
            + simpleFormatS.format(date) + "s ";

    //JVM start time
    date = new Date(runtimeBean.getStartTime());
    String jvmstarttimestring = simpleFormatH.format(date) + "h " + simpleFormatM.format(date) + "min "
            + simpleFormatS.format(date) + "s ";

    //OpenCms runtime
    date = new Date(OpenCms.getSystemInfo().getRuntime());
    String opencmsruntimestring = simpleFormatH.format(date) + "h " + simpleFormatM.format(date) + "min "
            + simpleFormatS.format(date) + "s ";

    //OpenCms startup time
    date = new Date(OpenCms.getSystemInfo().getStartupTime());
    String opencmsstartuptimestring = simpleFormatH.format(date) + "h " + simpleFormatM.format(date) + "min "
            + simpleFormatS.format(date) + "s ";

    setOperatingSystem("" + osBean.getName());
    setJavaVersion(System.getProperty("java.version"));
    setJvmUptime("" + jvmuptimestring);
    setJvmStarttime("" + jvmstarttimestring);
    setOpenCmsVersion(OpenCms.getSystemInfo().getVersionNumber());
    setOpenCmsRuntime("" + opencmsruntimestring);
    setOpenCmsStartupTime("" + opencmsstartuptimestring);

    Object o;
    if (CmsStringUtil.isEmpty(getParamAction())) {
        o = new CmsAdminSettings(getSession());
    } else {
        // this is not the initial call, get the job object from session
        o = getDialogObject();
    }
    if (!(o instanceof CmsAdminSettings)) {
        // create a new history settings handler object
        m_adminSettings = new CmsAdminSettings(getSession());
    } else {
        // reuse html import handler object stored in session
        m_adminSettings = (CmsAdminSettings) o;
    }

}

From source file:org.terracotta.management.entity.tms.TmsAgentTest.java

@Test
public void test_basic_tms_entity() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

    try (org.terracotta.connection.Connection connection = ConnectionFactory
            .connect(URI.create("passthrough://server-1:9510/cluster-1"), new Properties())) {
        EntityRef<TmsAgentEntity, TmsAgentConfig> ref = connection.getEntityRef(TmsAgentEntity.class,
                TmsAgentVersion.LATEST.version(), getClass().getSimpleName());
        ref.create(new TmsAgentConfig());

        TmsAgentEntity entity = ref.fetchEntity();

        Cluster cluster = entity.readTopology().get();

        // reset runtime data
        expectedCluster.serverStream().forEach(expectedServer -> {
            Server server = cluster.getStripe("stripe-1").get().getServerByName(expectedServer.getServerName())
                    .get();/*from   w w w .j av a 2 s .c om*/
            expectedServer.setUpTimeSec(server.getUpTimeSec());
            expectedServer.setStartTime(server.getStartTime());
            expectedServer.setActivateTime(server.getActivateTime());
            expectedServer.setBuildId(server.getBuildId());
        });
        long realConnectionPort = cluster.getClients().values().iterator().next().connectionStream().findFirst()
                .get().getClientEndpoint().getPort();
        String uuid = cluster.getClients().values().iterator().next().getLogicalConnectionUid();
        String expected = mapper.writeValueAsString(expectedCluster.toMap()).replace("uuid", uuid)
                .replace(":-1", ":" + realConnectionPort).replace(": -1", ": " + realConnectionPort);

        System.out.println("EXPECTED:");
        System.out.println(expected);

        String actual = mapper.writeValueAsString(cluster.toMap());
        System.out.println("ACTUAL");
        System.out.println(actual);

        assertEquals(expected, actual);

        List<Message> messages = entity.readMessages().get();
        assertEquals(3, messages.size());

        // ensure a second read without any topology modifications leads to 0 messages
        assertEquals(0, entity.readMessages().get().size());

        System.out.println(messages.stream().map(Message::toString).collect(Collectors.joining("\n")));

        assertEquals("TOPOLOGY", messages.get(messages.size() - 1).getType());
        assertEquals(cluster, messages.get(messages.size() - 1).unwrap(Cluster.class));

        assertEquals("NOTIFICATION", messages.get(0).getType());
        ContextualNotification firstNotif = messages.get(0).unwrap(ContextualNotification.class);
        assertEquals("SERVER_ENTITY_CREATED", firstNotif.getType());
        assertEquals(expectedCluster.serverEntityStream().findFirst().get().getContext(),
                firstNotif.getContext());

        assertEquals("NOTIFICATION", messages.get(1).getType());
        ContextualNotification secondNotif = messages.get(1).unwrap(ContextualNotification.class);
        assertEquals("SERVER_ENTITY_FETCHED", secondNotif.getType());
        assertEquals(expectedCluster.serverEntityStream().findFirst().get().getContext(),
                firstNotif.getContext());
        assertEquals(expectedCluster.clientStream().findFirst().get().getClientId().replace("uuid", uuid),
                secondNotif.getAttributes().get(Client.KEY));

        entity.readMessages().get();

        // not connects a client management registry

        ManagementRegistry registry = new AbstractManagementRegistry() {
            @Override
            public ContextContainer getContextContainer() {
                return new ContextContainer("cacheManagerName", "my-cm-name");
            }
        };
        registry.addManagementProvider(new MyManagementProvider());

        try (org.terracotta.connection.Connection secondConnection = ConnectionFactory
                .connect(URI.create("passthrough://server-1:9510/cluster-1"), new Properties())) {

            ManagementAgentService managementAgent = new ManagementAgentService(
                    new ManagementAgentEntityFactory(secondConnection)
                            .retrieveOrCreate(new ManagementAgentConfig()));
            managementAgent.setManagementCallExecutor(executorService);

            ClientIdentifier clientIdentifier = managementAgent.getClientIdentifier();
            //System.out.println(clientIdentifier);
            assertEquals(Long.parseLong(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]),
                    clientIdentifier.getPid());
            assertEquals("UNKNOWN", clientIdentifier.getName());
            assertNotNull(clientIdentifier.getConnectionUid());

            managementAgent.bridge(registry);
            managementAgent.setTags("EhcachePounder", "webapp-1", "app-server-node-1");

            messages = entity.readMessages().get();
            System.out.println(messages.stream().map(Message::toString).collect(Collectors.joining("\n")));
            assertEquals(6, messages.size());
            for (int i = 0; i < 5; i++) {
                assertEquals("NOTIFICATION", messages.get(0).getType());
            }
            assertEquals("CLIENT_CONNECTED", messages.get(0).unwrap(ContextualNotification.class).getType());
            assertEquals("SERVER_ENTITY_CREATED",
                    messages.get(1).unwrap(ContextualNotification.class).getType());
            assertEquals("SERVER_ENTITY_FETCHED",
                    messages.get(2).unwrap(ContextualNotification.class).getType());
            assertEquals("CLIENT_REGISTRY_UPDATED",
                    messages.get(3).unwrap(ContextualNotification.class).getType());
            assertEquals("CLIENT_TAGS_UPDATED", messages.get(4).unwrap(ContextualNotification.class).getType());
            assertEquals("TOPOLOGY", messages.get(5).getType());

            registry.register(new MyObject("myCacheManagerName", "myCacheName1"));
            registry.register(new MyObject("myCacheManagerName", "myCacheName2"));

            messages = entity.readMessages().get();
            System.out.println(messages.stream().map(Message::toString).collect(Collectors.joining("\n")));
            assertEquals(3, messages.size());
            assertEquals("NOTIFICATION", messages.get(0).getType());
            assertEquals("NOTIFICATION", messages.get(1).getType());
            assertEquals("CLIENT_REGISTRY_UPDATED",
                    messages.get(0).unwrap(ContextualNotification.class).getType());
            assertEquals("CLIENT_REGISTRY_UPDATED",
                    messages.get(1).unwrap(ContextualNotification.class).getType());
            assertEquals("TOPOLOGY", messages.get(2).getType());
        }

    }
}

From source file:org.apache.geode.test.dunit.standalone.ProcessManager.java

/**
 * Get the java agent passed to this process and pass it to the child VMs. This was added to
 * support jacoco code coverage reports/*w w w.j  a va 2  s  . co  m*/
 */
private String getAgentString() {
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    if (runtimeBean != null) {
        for (String arg : runtimeBean.getInputArguments()) {
            if (arg.contains("-javaagent:")) {
                // HACK for gradle bug GRADLE-2859. Jacoco is passing a relative path
                // That won't work when we pass this to dunit VMs in a different
                // directory
                arg = arg.replace("-javaagent:..",
                        "-javaagent:" + System.getProperty("user.dir") + File.separator + "..");
                arg = arg.replace("destfile=..",
                        "destfile=" + System.getProperty("user.dir") + File.separator + "..");
                return arg;
            }
        }
    }

    return "-DdummyArg=true";
}

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

private RuntimeMXBean runtime() {
    return ManagementFactory.getRuntimeMXBean();
}

From source file:com.jredrain.startup.Bootstrap.java

private static int getPid() {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    String name = runtime.getName();
    try {//from w  ww . j ava  2 s .  co  m
        return Integer.parseInt(name.substring(0, name.indexOf('@')));
    } catch (Exception e) {
    }
    return -1;
}

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 {//from  w  ww  . ja va 2s .  com
            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:org.apache.storm.util.CoreUtil.java

@ClojureClass(className = "backtype.storm.util#process-pid")
public static String processPid() {
    // Gets the pid of this JVM. Hacky because Java doesn't provide a real
    // way to do this.
    String name = ManagementFactory.getRuntimeMXBean().getName();
    String[] split = name.split("@");
    if (split.length != 2) {
        throw new RuntimeException("Got unexpected process name: " + name);
    }// w  w  w.  ja v a2  s.co  m

    return split[0];
}

From source file:com.emarsys.dyson.storage.DefaultDysonStorage.java

/**
 * ugly hack to get the PID, only works in SUN VMs
 *///from   w w w  . j a v  a  2  s .  c o  m
protected String getPID() {
    String pid = ManagementFactory.getRuntimeMXBean().getName();
    return pid.substring(0, pid.indexOf('@'));
}

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

/**
 * Initializes the nodeInfo that will be store in the SWARM NODES MAP
 * /*w  ww .j  a  va 2 s .  c o  m*/
 * @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:org.pepstock.jem.util.ReverseURLClassLoader.java

/**
 * Loads all JARS of the bootstrap classpath. If JRE/jDK doesn't support bootstrap, could create 
 * issues. Uses java.management to get these information
 *//*from   w  ww  .  java 2  s  . c  om*/
private void loadBootstrapFiles() {
    // 
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    // checks if bootstrap classpath is supporte
    if (runtime.isBootClassPathSupported()) {
        // gets all files
        String longFiles = ManagementFactory.getRuntimeMXBean().getBootClassPath();
        // splits by path separator
        String[] files = StringUtils.split(longFiles, File.pathSeparator);
        // reads all JAR files
        for (int i = 0; i < files.length; i++) {
            try {
                JarFile jFile = new JarFile(files[i]);
                bootstrap.add(jFile);
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}