Example usage for javax.management ObjectName ObjectName

List of usage examples for javax.management ObjectName ObjectName

Introduction

In this page you can find the example usage for javax.management ObjectName ObjectName.

Prototype

public ObjectName(String name) throws MalformedObjectNameException 

Source Link

Document

Construct an object name from the given string.

Usage

From source file:info.archinnov.achilles.embedded.ServerStarter.java

private boolean isAlreadyRunning() {
    log.trace("Check whether an embedded Cassandra is already running");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {//  w  w w  .ja  v  a  2s .  co  m
        MBeanInfo mBeanInfo = mbs.getMBeanInfo(new ObjectName("org.apache.cassandra.db:type=StorageService"));
        if (mBeanInfo != null) {
            return true;
        }
        return false;
    } catch (InstanceNotFoundException e) {
        return false;
    } catch (IntrospectionException e) {
        throw new IllegalStateException("Cannot check if cassandra is already running", e);
    } catch (MalformedObjectNameException e) {
        throw new IllegalStateException("Cannot check if cassandra is already running", e);
    } catch (ReflectionException e) {
        throw new IllegalStateException("Cannot check if cassandra is already running", e);
    }

}

From source file:ddf.metrics.reporting.internal.rrd4j.JmxCollector.java

/**
 * Configures a scheduled threaded executor to poll the metric's MBean periodically
 * and add a sample to the RRD file with the metric's current value.
 * /*from www . j  ava  2 s  .c  o  m*/
 * @throws CollectorException
 */
public void updateSamples() throws CollectorException {
    LOGGER.trace("ENTERING: updateSamples");

    if (executor == null) {
        executor = new ScheduledThreadPoolExecutor(1);
    }

    final Runnable updater = new Runnable() {
        public void run() {
            Object attr = null;
            try {
                attr = localMBeanServer.getAttribute(new ObjectName(mbeanName), mbeanAttributeName);

                LOGGER.trace("Sampling attribute " + mbeanAttributeName + " from MBean " + mbeanName);

                // Cast the metric's sampled value to the appropriate data type
                double val = 0;
                if (attr instanceof Integer) {
                    val = (Integer) attr;
                } else if (attr instanceof Long) {
                    val = ((Long) attr).intValue();
                } else if (attr instanceof Float) {
                    val = ((Float) attr);
                } else if (attr instanceof Double) {
                    val = ((Double) attr);
                } else {
                    throw new IllegalArgumentException(
                            "Unsupported type " + attr + " for attribute " + mbeanAttributeName);
                }

                LOGGER.trace("MBean attribute " + mbeanAttributeName + " has value = " + val);

                // If first time this metric has been sampled, then need to create a
                // sample in the RRD file
                if (sample == null) {
                    sample = rrdDb.createSample();
                }

                try {
                    // Add metric's sample to RRD file with current timestamp (i.e., "NOW")
                    sample.setAndUpdate("NOW:" + val);
                } catch (IllegalArgumentException iae) {
                    LOGGER.error("Dropping sample of datasource " + rrdDataSourceName, iae);
                }
            } catch (Exception e) {
                LOGGER.warn("Problems getting MBean attribute " + mbeanAttributeName, e);
            }
        }
    };

    // Setup threaded scheduler to retrieve this MBean attribute's value
    // at the specified sample rate
    LOGGER.debug("Setup ScheduledThreadPoolExecutor for MBean " + mbeanName);
    executor.scheduleWithFixedDelay(updater, 0, sampleRate, TimeUnit.SECONDS);

    LOGGER.trace("EXITING: updateSamples");
}

From source file:com.octo.captcha.j2ee.ImageCaptchaService.java

/**
 * Register self to the first MBean server available in the JVM, if
 * any.//from  w  ww.  j  av a 2 s .c  om
 * @param theRegisteringName the name the service will be registered
 * to the MBean server.
 * @throws ImageCaptchaServiceException in case of error. Possible
 * error details are :
 * <ul>
 *  <li> ImageCaptchaServiceException.MALFORMED_REGISTERING_NAME</li>
 *  <li> ImageCaptchaServiceException.INSTANCE_ALREADY_REGISTERED</li>
 * </ul>
 * @see com.octo.captcha.j2ee.ImageCaptchaServiceException#MALFORMED_REGISTERING_NAME
 * @see com.octo.captcha.j2ee.ImageCaptchaServiceException#INSTANCE_ALREADY_REGISTERED
 */
public void registerToMBeanServer(String theRegisteringName) throws ImageCaptchaServiceException {
    ArrayList mbeanServers = MBeanServerFactory.findMBeanServer(null);
    if (mbeanServers.size() == 0) {
        log.warn("No current MBean Server, skiping the registering process");
    } else {
        MBeanServer mbeanServer = (MBeanServer) mbeanServers.get(0);
        try {
            ObjectName name = new ObjectName(theRegisteringName);
            mbeanServer.registerMBean(this, name);
            this.registeredName = theRegisteringName;
        } catch (MalformedObjectNameException e) {
            throw new ImageCaptchaServiceException(ImageCaptchaServiceException.MALFORMED_REGISTERING_NAME, e);
        } catch (InstanceAlreadyExistsException e) {
            throw new ImageCaptchaServiceException(ImageCaptchaServiceException.INSTANCE_ALREADY_REGISTERED, e);
        } catch (MBeanRegistrationException e) {
            // this exception should never be raised (raised
            // only by an MBean that implements the MBeanRegistration
            // interface.
            log.error("An unexpected exception has been raised : " + "ImageCaptchaService needs maintenance !",
                    e);
        } catch (NotCompliantMBeanException e) {
            // this should never happens
            log.error("Exception trying to register the service to" + " the MBean server", e);
        }
    }
}

From source file:com.spotify.reaper.cassandra.JmxProxy.java

/**
 * @return true if any repairs are running on the node.
 *///from  ww  w.j av  a 2s.  com
public boolean isValidationCompactionRunning() {
    // Check if AntiEntropySession is actually running on the node
    try {
        int activeCount = (Integer) mbeanServer.getAttribute(new ObjectName(VALIDATION_ACTIVE_OBJECT_NAME),
                VALUE_ATTRIBUTE);
        long pendingCount = (Long) mbeanServer.getAttribute(new ObjectName(VALIDATION_PENDING_OBJECT_NAME),
                VALUE_ATTRIBUTE);

        return activeCount + pendingCount != 0;
    } catch (IOException ignored) {
        LOG.warn(FAILED_TO_CONNECT_TO_USING_JMX, host, ignored);
    } catch (MalformedObjectNameException ignored) {
        LOG.error("Internal error, malformed name", ignored);
    } catch (InstanceNotFoundException e) {
        LOG.error("Error getting pending/active validation compaction attributes from JMX", e);
        return false;
    } catch (Exception e) {
        LOG.error(ERROR_GETTING_ATTR_JMX, e);
    }
    // If uncertain, assume it's not running
    return false;
}

From source file:com.springsource.hq.plugin.tcserver.plugin.TomcatMeasurementPlugin.java

private MetricValue getPercentActiveThreads(MBeanServerConnection connection, Metric metric)
        throws MetricUnreachableException, MetricNotFoundException, PluginException {
    int currentThreadsBusy = 0;
    int maxThreads = 0;

    try {/*  w  ww.  j av  a  2s . c  o m*/
        ObjectName threadPoolObjectName = new ObjectName(metric.getObjectName());
        currentThreadsBusy = ((Integer) connection.getAttribute(threadPoolObjectName, "currentThreadsBusy"))
                .intValue();
        maxThreads = ((Integer) connection.getAttribute(threadPoolObjectName, "maxThreads")).intValue();
    } catch (MalformedObjectNameException e) {
        throw new MetricInvalidException("Error querying for Thread Pool MBeans: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MetricUnreachableException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (AttributeNotFoundException e) {
        throw new MetricNotFoundException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new MetricNotFoundException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (MBeanException e) {
        throw new PluginException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new PluginException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    } catch (NullPointerException e) {
        throw new PluginException("Error querying for Thread Pool MBeans:" + e.getMessage(), e);
    }

    return new MetricValue(100d * (double) currentThreadsBusy / (double) maxThreads);
}

From source file:com.cisco.oss.foundation.monitoring.RMIMonitoringAgent.java

private String javaRegister(MonitoringMXBean mxBean, String serviceURL) throws MalformedObjectNameException,
        IOException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
    serverInfo = new ServerInfo(mxBean, configuration);

    String strAppObjectName = Utility.getObjectName("Application", this.exposedObject);

    jurl = new JMXServiceURL(serviceURL);
    appObjectName = new ObjectName(strAppObjectName);

    jmxEnvironmentMap = null;//from   w w w.  j a  v  a  2s . c om

    int agentPort = configuration.getInt(FoundationMonitoringConstants.MX_PORT);
    if (!RMIRegistryManager.isRMIRegistryRunning(configuration, agentPort)) {
        RMIRegistryManager.startRMIRegistry(configuration, agentPort);
    } else {
        LOGGER.info("rmiregistry is already running on port " + agentPort);
    }

    String serviceName = serviceURL.substring(serviceURL.indexOf("jmxrmi/"));
    if (isServiceExported(configuration, serviceName)) {
        MonitoringClient client = new MonitoringClient(serviceURL, strAppObjectName);
        if (client.connect()) {
            client.disconnect();
        } else {
            jmxEnvironmentMap = Utility.prepareJmxEnvironmentMap();
            LOGGER.info("Found a stale entry for " + serviceName + " in rmiregistry , it will be overwritten");
        }
    }
    mbs = ManagementFactory.getPlatformMBeanServer();
    rmis = JMXConnectorServerFactory.newJMXConnectorServer(jurl, jmxEnvironmentMap, mbs);

    mbs.registerMBean(mxBean, appObjectName);
    registerComponentInfo();
    registerMonitoringConfiguration();
    registerServices();
    registerConnections();
    registerNotificationDetails();
    rmis.start();

    if (mxBean instanceof INotifier) {
        INotifier notifier = (INotifier) mxBean;
        notifier.setNotificationSender(serverInfo);
    }

    serverThread = new ServerRecoveryDaemon();
    serverThread.start();

    return strAppObjectName;
}

From source file:org.red5.server.winstone.WinstoneLoader.java

protected void registerJMX() {
    // register with jmx
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {/*from  w ww . ja  va2s.  c o  m*/
        ObjectName oName = new ObjectName("org.red5.server:type=WinstoneLoader");
        // check for existing registration before registering
        if (!mbs.isRegistered(oName)) {
            mbs.registerMBean(this, oName);
        } else {
            log.debug("ContextLoader is already registered in JMX");
        }
    } catch (Exception e) {
        log.warn("Error on jmx registration", e);
    }
}

From source file:com.sun.grizzly.http.jk.common.ChannelSocket.java

/**
 * jmx:managed-operation/*from w  ww.j av a  2 s. c o m*/
 */
public void init() throws IOException {
    // Find a port.
    if (startPort == 0) {
        port = 0;

        LoggerUtils.getLogger().info("JK: ajp13 disabling channelSocket");
        running = true;
        return;
    }
    if (maxPort < startPort) {
        maxPort = startPort;
    }
    for (int i = startPort; i <= maxPort; i++) {
        try {
            if (inet == null) {
                sSocket = new ServerSocket(i, 0);
            } else {
                sSocket = new ServerSocket(i, 0, inet);
            }
            port = i;
            break;
        } catch (IOException ex) {

            LoggerUtils.getLogger().info("Port busy " + i + " " + ex.toString());
            continue;
        }
    }

    if (sSocket == null) {
        LoggerUtils.getLogger().log(Level.SEVERE, "Can't find free port " + startPort + " " + maxPort);
        return;
    }

    LoggerUtils.getLogger().info("JK: ajp13 listening on " + getAddress() + ":" + port);

    // If this is not the base port and we are the 'main' channleSocket and
    // SHM didn't already set the localId - we'll set the instance id
    if ("channelSocket".equals(name) && port != startPort && (wEnv.getLocalId() == 0)) {
        wEnv.setLocalId(port - startPort);
    }
    if (serverTimeout > 0) {
        sSocket.setSoTimeout(serverTimeout);
    }

    // XXX Reverse it -> this is a notification generator !!
    if (next == null && wEnv != null) {
        if (nextName != null) {
            setNext(wEnv.getHandler(nextName));
        }
        if (next == null) {
            next = wEnv.getHandler("dispatch");
        }
        if (next == null) {
            next = wEnv.getHandler("request");
        }
    }
    JMXRequestNote = wEnv.getNoteId(WorkerEnv.ENDPOINT_NOTE, "requestNote");
    running = true;

    // Run a thread that will accept connections.
    // XXX Try to find a thread first - not sure how...
    if (this.domain != null) {
        try {
            tpOName = new ObjectName(domain + ":type=ThreadPool,name=" + getChannelName());

            Registry.getRegistry(null, null).registerComponent(tp, tpOName, null);

            rgOName = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getChannelName());
            Registry.getRegistry(null, null).registerComponent(global, rgOName, null);
        } catch (Exception e) {
            LoggerUtils.getLogger().log(Level.SEVERE, "Can't register threadpool");
        }
    }

    tp.start();
    SocketAcceptor acceptAjp = new SocketAcceptor(this);
    tp.runIt(acceptAjp);

}

From source file:com.bigdata.dastor.db.ColumnFamilyStore.java

public static ColumnFamilyStore createColumnFamilyStore(String table, String columnFamily) throws IOException {
    /*//from  ww  w .j a  v  a  2  s  .c  om
     * Get all data files associated with old Memtables for this table.
     * These files are named as follows <Table>-1.db, ..., <Table>-n.db. Get
     * the max which in this case is n and increment it to use it for next
     * index.
     */
    List<Integer> generations = new ArrayList<Integer>();
    String[] dataFileDirectories = DatabaseDescriptor.getAllDataFileLocationsForTable(table);
    for (String directory : dataFileDirectories) {
        File fileDir = new File(directory);
        File[] files = fileDir.listFiles();

        for (File file : files) {
            String filename = file.getName();
            String cfName = getColumnFamilyFromFileName(filename);

            if (cfName.equals(columnFamily)) {
                generations.add(getGenerationFromFileName(filename));
            }
        }
    }
    Collections.sort(generations);
    int value = (generations.size() > 0) ? (generations.get(generations.size() - 1)) : 0;

    ColumnFamilyStore cfs = new ColumnFamilyStore(table, columnFamily,
            "Super".equals(DatabaseDescriptor.getColumnType(table, columnFamily)), value);

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {
        String mbeanName = "com.bigdata.dastor.db:type=ColumnFamilyStores,keyspace=" + table + ",columnfamily="
                + columnFamily;
        mbs.registerMBean(cfs, new ObjectName(mbeanName));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return cfs;
}

From source file:mondrian.server.MondrianServerImpl.java

/**
 * Registers the MonitorImpl associated with this server
 * as an MBean accessible via JMX.//from  w ww  .  ja v a2  s  .  c  om
 */
private void registerMBean() {
    if (Util.PreJdk16) {
        LOGGER.info("JMX is supported in Mondrian only on Java 6+.");
        return;
    }
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName mxbeanName = new ObjectName("mondrian.server:type=Server-" + id);
        mbs.registerMBean(getMonitor(), mxbeanName);
    } catch (MalformedObjectNameException e) {
        LOGGER.warn("Failed to register JMX MBean", e);
    } catch (NotCompliantMBeanException e) {
        LOGGER.warn("Failed to register JMX MBean", e);
    } catch (InstanceAlreadyExistsException e) {
        LOGGER.warn("Failed to register JMX MBean", e);
    } catch (MBeanRegistrationException e) {
        LOGGER.warn("Failed to register JMX MBean", e);
    }
}