Example usage for java.lang.management RuntimeMXBean getName

List of usage examples for java.lang.management RuntimeMXBean getName

Introduction

In this page you can find the example usage for java.lang.management RuntimeMXBean getName.

Prototype

public String getName();

Source Link

Document

Returns the name representing the running Java virtual machine.

Usage

From source file:org.apache.hadoop.hbase.util.JVM.java

/**
 * Get the number of opened filed descriptor for the runtime jvm.
 * If Oracle java, it will use the com.sun.management interfaces.
 * Otherwise, this methods implements it (linux only).  
 * @return number of open file descriptors for the jvm
 *///from ww  w  .  j  ava 2s.c o m
public long getOpenFileDescriptorCount() {

    Long ofdc;

    if (!ibmvendor) {
        ofdc = runUnixMXBeanMethod("getOpenFileDescriptorCount");
        return (ofdc != null ? ofdc.longValue() : -1);
    }
    InputStream in = null;
    BufferedReader output = null;
    try {
        //need to get the PID number of the process first
        RuntimeMXBean rtmbean = ManagementFactory.getRuntimeMXBean();
        String rtname = rtmbean.getName();
        String[] pidhost = rtname.split("@");

        //using linux bash commands to retrieve info
        Process p = Runtime.getRuntime()
                .exec(new String[] { "bash", "-c", "ls /proc/" + pidhost[0] + "/fdinfo | wc -l" });
        in = p.getInputStream();
        output = new BufferedReader(new InputStreamReader(in));
        String openFileDesCount;
        if ((openFileDesCount = output.readLine()) != null)
            return Long.parseLong(openFileDesCount);
    } catch (IOException ie) {
        LOG.warn("Not able to get the number of open file descriptors", ie);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                LOG.warn("Not able to close the InputStream", e);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOG.warn("Not able to close the InputStream", e);
            }
        }
    }
    return -1;
}

From source file:org.broadleafcommerce.common.extensibility.InstrumentationRuntimeFactory.java

private static void loadAgent(String agentJar, Class<?> vmClass) {
    try {//w w w.  j a v a2  s  . com
        // first obtain the PID of the currently-running process
        // ### this relies on the undocumented convention of the
        // RuntimeMXBean's
        // ### name starting with the PID, but there appears to be no other
        // ### way to obtain the current process' id, which we need for
        // ### the attach process
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        String pid = runtime.getName();
        if (pid.contains("@"))
            pid = pid.substring(0, pid.indexOf("@"));

        // JDK1.6: now attach to the current VM so we can deploy a new agent
        // ### this is a Sun JVM specific feature; other JVMs may offer
        // ### this feature, but in an implementation-dependent way
        Object vm = vmClass.getMethod("attach", new Class<?>[] { String.class }).invoke(null, pid);
        vmClass.getMethod("loadAgent", new Class[] { String.class }).invoke(vm, agentJar);
        vmClass.getMethod("detach", new Class[] {}).invoke(vm);
    } catch (Throwable t) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Problem loading the agent", t);
        }
    }
}

From source file:org.fluentd.jvmwatcher.data.JvmWatchState.java

/**
 * @param clientPrixy//  w  w w  . j a va  2 s  .co m
 * @return
 */
public static JvmWatchState makeJvmWatchState(JvmClientProxy clientProxy) {
    // null check
    if (null == clientProxy) {
        return null;
    }
    if (null == clientProxy.getLocalJvmInfo()) {
        return null;
    }

    // create data object
    JvmWatchState ret = new JvmWatchState();

    // set Local JVM Information
    ret.commandLine_ = clientProxy.getLocalJvmInfo().getCommandLine_();
    ret.displayName_ = clientProxy.getLocalJvmInfo().getDisplayName();
    ret.jvmId_ = clientProxy.getLocalJvmInfo().getJvmid();
    ret.shortName_ = clientProxy.getLocalJvmInfo().getShortName();

    // create log line array
    ret.stateLog_ = new ArrayList<JvmStateLog>();

    // set JVM information
    try {
        // CompilationMXBean
        CompilationMXBean compilationBean = clientProxy.getCompilationMXBean();
        if (null != compilationBean) {
            ret.jitName_ = compilationBean.getName();
        }

        // OperatingSystemMXBean
        OperatingSystemMXBean OpeSysBean = clientProxy.getOperatingSystemMXBean();
        if (null != OpeSysBean) {
            ret.osArch_ = OpeSysBean.getArch();
            ret.osName_ = OpeSysBean.getName();
            ret.osVersion_ = OpeSysBean.getVersion();
        }

        // RuntimeMXBean
        RuntimeMXBean runtimeBean = clientProxy.getRuntimeMXBean();
        if (null != runtimeBean) {
            ret.jvmStartTime_ = runtimeBean.getStartTime();
            ret.jvmRuntimeName_ = runtimeBean.getName();
            ret.vmName_ = runtimeBean.getVmName();
            ret.vmVender_ = runtimeBean.getVmVendor();
            ret.vmVersion_ = runtimeBean.getVmVersion();
            ret.specName_ = runtimeBean.getSpecName();
            ret.specVender_ = runtimeBean.getSpecVendor();
            ret.specVersion_ = runtimeBean.getSpecVersion();
        }
    } catch (IOException ex) {
        log.error("get MXBean error.", ex);
        // close JvmClientProxy
        clientProxy.disconnect();
    } catch (Exception ex) {
        log.error("get MXBean error.", ex);
        // close JvmClientProxy
        clientProxy.disconnect();
    }

    return ret;
}

From source file:org.jbosson.plugins.amq.ArtemisServerDiscoveryComponent.java

protected ProcessInfo getJvmProcess(ResourceDiscoveryContext discoveryContext, EmsConnection connection,
        String connectorAddress) {

    // check whether native system is supported
    if (!discoveryContext.getSystemInformation().isNative()) {
        log.warn(// ww w. j  a  va2 s . c o m
                "Native layer is not available or has been disabled, process properties discovery not supported");
        return null;
    }

    ProcessInfo processInfo;
    final String resourceTypeName = discoveryContext.getResourceType().getName();
    try {
        final EmsBean runtimeEmsBean = connection.getBean(ManagementFactory.RUNTIME_MXBEAN_NAME);
        final RuntimeMXBean runtimeMXBean = runtimeEmsBean.getProxy(RuntimeMXBean.class);
        final String runtimeMXBeanName = runtimeMXBean != null ? runtimeMXBean.getName() : null;
        if (runtimeMXBeanName != null && runtimeMXBeanName.contains("@")) {
            final String pid = runtimeMXBeanName.substring(0, runtimeMXBeanName.indexOf('@'));
            processInfo = new ProcessInfo(Long.valueOf(pid));
            // validate process info to make sure command line args are accessible
            // this can happen for processes running with a user id different than the agent
            if (processInfo.getCommandLine() == null || processInfo.getCommandLine().length == 0) {
                log.debug("Unable to get command line args for PID [" + pid + "] for [" + resourceTypeName
                        + "], with connector address [" + connectorAddress
                        + "], using java.lang.management.RuntimeMXBean to get JVM args");
                final List<String> inputArguments = runtimeMXBean.getInputArguments();
                final String[] args = inputArguments.toArray(new String[inputArguments.size()]);
                log.debug("JVM args for PID[" + pid + "] using java.lang.management.RuntimeMXBean: "
                        + Arrays.toString(args));
                processInfo = new ProcessInfoWithArgs(Long.valueOf(pid), args);
            }
        } else {
            throw new RuntimeException(
                    "Unable to get Process PID using java.lang.management.RuntimeMXBean for ["
                            + resourceTypeName + "] , with connector address [" + connectorAddress + "]");
        }
    } catch (Exception e) {
        throw new RuntimeException("Error getting Process PID for resource [" + resourceTypeName
                + "] with JMX connector [" + connectorAddress + "]: " + e.getMessage(), e);
    }

    return processInfo;
}

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 2s  .  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.opencron.agent.Bootstrap.java

private static Integer getPid() {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    String name = runtime.getName();
    try {// www .j a  va2s  . c o  m
        return Integer.parseInt(name.substring(0, name.indexOf('@')));
    } catch (Exception e) {
    }
    return -1;
}

From source file:org.rhq.plugins.jmx.JMXDiscoveryComponent.java

private static Long getJvmPid(RuntimeMXBean runtimeMXBean) {
    Long pid;/*from   w ww  .j  a v  a 2s . c  o  m*/
    String jvmName = runtimeMXBean.getName();
    int atIndex = jvmName.indexOf('@');
    pid = (atIndex != -1) ? Long.valueOf(jvmName.substring(0, atIndex)) : null;
    return pid;
}

From source file:org.springframework.boot.util.SystemUtils.java

/**
 * Looks for application PID//  w  ww. j  a va2  s.c o  m
 * @return application PID
 * @throws java.lang.IllegalStateException if PID could not be determined
 */
public static String getApplicationPid() {
    String pid = null;
    try {
        RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        String jvmName = runtimeBean.getName();
        if (StringUtils.isEmpty(jvmName)) {
            LOG.warn("Cannot get JVM name");
        }
        if (!jvmName.contains("@")) {
            LOG.warn("JVM name doesn't contain process id");
        }
        pid = jvmName.split("@")[0];
    } catch (Throwable e) {
        LOG.warn("Cannot get RuntimeMXBean", e);
    }

    if (pid == null) {
        throw new IllegalStateException("Application PID not found");
    }

    return pid;
}

From source file:org.tango.server.ServerManager.java

/**
 * WARNING: it is jvm dependent (works for sun')
 *
 * @throws DevFailed/* ww  w  .j a  va 2 s . c  om*/
 */
private void initPIDAndHostName() throws DevFailed {

    final RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
    final String pidAndHost = rmxb.getName();
    final String[] splitted = pidAndHost.split("@");
    if (splitted.length > 1) {
        pid = splitted[0];
    }

    try {
        final InetAddress addr;
        if (ORBManager.OAI_ADDR != null && !ORBManager.OAI_ADDR.isEmpty()) {
            addr = InetAddress.getByName(ORBManager.OAI_ADDR);
        } else {
            addr = InetAddress.getLocalHost();
        }
        hostName = addr.getCanonicalHostName();
    } catch (final UnknownHostException e) {
        DevFailedUtils.throwDevFailed(e);
    }

    logger.debug("pid: " + pid);
    logger.debug("hostName: " + hostName);

}

From source file:ro.nextreports.server.web.debug.InfoUtil.java

public static List<Info> getGeneralJVMInfo() {
    List<Info> infos = new ArrayList<Info>();

    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    infos.add(new Info("uptime", "" + Duration.milliseconds(runtimeBean.getUptime()).toString()));
    infos.add(new Info("name", runtimeBean.getName()));
    infos.add(new Info("pid", runtimeBean.getName().split("@")[0]));

    OperatingSystemMXBean systemBean = ManagementFactory.getOperatingSystemMXBean();
    infos.add(new Info("os name", "" + systemBean.getName()));
    infos.add(new Info("os version", "" + systemBean.getVersion()));
    infos.add(new Info("system load average", "" + systemBean.getSystemLoadAverage()));
    infos.add(new Info("available processors", "" + systemBean.getAvailableProcessors()));

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    infos.add(new Info("thread count", "" + threadBean.getThreadCount()));
    infos.add(new Info("peak thread count", "" + threadBean.getPeakThreadCount()));

    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    infos.add(new Info("heap memory used",
            FileUtils.byteCountToDisplaySize(memoryBean.getHeapMemoryUsage().getUsed())));
    infos.add(new Info("non-heap memory used",
            FileUtils.byteCountToDisplaySize(memoryBean.getNonHeapMemoryUsage().getUsed())));

    return infos;
}