Example usage for javax.management MBeanServer registerMBean

List of usage examples for javax.management MBeanServer registerMBean

Introduction

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

Prototype

public ObjectInstance registerMBean(Object object, ObjectName name)
        throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException;

Source Link

Document

Registers a pre-existing object as an MBean with the MBean server.

Usage

From source file:com.neophob.sematrix.jmx.PixelControllerStatus.java

/**
 * Register the JMX Bean./*w  w  w . j a va 2  s.co  m*/
 *
 * @param configuredFps the configured fps
 */
public PixelControllerStatus(int configuredFps) {
    LOG.log(Level.INFO, "Initialize the PixelControllerStatus JMX Bean");

    this.configuredFps = configuredFps;

    // initialize all buffers 
    this.timeMeasureMapGlobal = new ConcurrentHashMap<TimeMeasureItemGlobal, CircularFifoBuffer>();
    for (TimeMeasureItemGlobal timeMeasureItem : TimeMeasureItemGlobal.values()) {
        this.timeMeasureMapGlobal.put(timeMeasureItem, new CircularFifoBuffer(this.configuredFps * SECONDS));
    }
    this.timeMeasureMapOutput = new ConcurrentHashMap<Output, Map<TimeMeasureItemOutput, CircularFifoBuffer>>();
    this.outputList = new ArrayList<Output>();

    startTime = System.currentTimeMillis();

    // register MBean
    try {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = new ObjectName(JMX_BEAN_NAME);
        // check if the MBean is already registered
        if (!server.isRegistered(name)) {
            server.registerMBean(this, name);
        }
    } catch (JMException ex) {
        LOG.log(Level.WARNING, "Error while registering class as JMX Bean.", ex);
    }
}

From source file:com.rackspacecloud.blueflood.cache.TtlCache.java

public TtlCache(String label, TimeValue expiration, int cacheConcurrency, final InternalAPI internalAPI) {
    try {// w w w.  j a v a 2 s .  co  m
        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        final String name = String.format(
                TtlCache.class.getPackage().getName() + ":type=%s,scope=%s,name=Stats",
                TtlCache.class.getSimpleName(), label);
        final ObjectName nameObj = new ObjectName(name);
        mbs.registerMBean(this, nameObj);
        instantiateYammerMetrics(TtlCache.class, label, nameObj);
    } catch (Exception ex) {
        log.error("Unable to register mbean for " + getClass().getName());
    }
    generalErrorMeter = Metrics.newMeter(TtlCache.class, "Load Errors", label, "Rollups", TimeUnit.MINUTES);
    httpErrorMeter = Metrics.newMeter(TtlCache.class, "Http Errors", label, "Rollups", TimeUnit.MINUTES);

    CacheLoader<String, Map<ColumnFamily<Locator, Long>, TimeValue>> loader = new CacheLoader<String, Map<ColumnFamily<Locator, Long>, TimeValue>>() {

        // values from the default account are used to build a ttl map for tenants that do not exist in the
        // internal API.  These values are put into the cache, meaning subsequent cache requests do not
        // incur a miss and hit the internal API.
        private final Account DEFAULT_ACCOUNT = new Account() {
            @Override
            public TimeValue getMetricTtl(String resolution) {
                return SAFETY_TTLS
                        .get(AstyanaxIO.getColumnFamilyMapper().get(Granularity.fromString(resolution).name()));
            }
        };

        @Override
        public Map<ColumnFamily<Locator, Long>, TimeValue> load(final String key) throws Exception {
            // load account, build ttl map.
            try {
                Account acct = internalAPI.fetchAccount(key);
                return buildTtlMap(acct);
            } catch (HttpResponseException ex) {
                // cache the default value on a 404. this means that we will not be hammering the API for values
                // that are constantly not there.  The other option was to let the Http error bubble out, use a
                // and value from SAFETY_TTLS.  But the same thing (an HTTP round trip) would happen the very next
                // time a TTL is requested.
                if (ex.getStatusCode() == 404) {
                    httpErrorMeter.mark();
                    log.warn(ex.getMessage());
                    return buildTtlMap(DEFAULT_ACCOUNT);
                } else
                    throw ex;
            }

        }
    };
    cache = CacheBuilder.newBuilder().expireAfterWrite(expiration.getValue(), expiration.getUnit())
            .concurrencyLevel(cacheConcurrency).recordStats().build(loader);
}

From source file:mondrian.server.MondrianServerImpl.java

/**
 * Registers the MonitorImpl associated with this server
 * as an MBean accessible via JMX.//w  w  w.  j a va  2  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);
    }
}

From source file:org.ow2.proactive.resourcemanager.core.jmx.RMJMXHelper.java

/**
 * {@inheritDoc}/*from  w w w  .  jav  a2s  .c  o m*/
 */
@Override
public void registerMBeans(final MBeanServer mbs) {
    // Register all mbeans into the server
    try {
        final RuntimeDataMBean anonymMBean = new RuntimeDataMBeanImpl(RMMonitoringImpl.rmStatistics);
        // Uniquely identify the MBean and register it to the MBeanServer
        final ObjectName name = new ObjectName(RMJMXBeans.RUNTIMEDATA_MBEAN_NAME);
        mbs.registerMBean(anonymMBean, name);

        String dataBaseName = PAResourceManagerProperties.RM_HOME.getValueAsString()
                + System.getProperty("file.separator")
                + PAResourceManagerProperties.RM_RRD_DATABASE_NAME.getValueAsString();
        FileUtils.forceMkdir(new File(dataBaseName).getParentFile());

        setDataStore(new RRDDataStore((StandardMBean) anonymMBean, dataBaseName,
                PAResourceManagerProperties.RM_RRD_STEP.getValueAsInt(), Logger.getLogger(RMJMXHelper.class)));
    } catch (Exception e) {
        LOGGER.error("Unable to register the ResourceManagerRuntimeMBean", e);
    }

    // Register the MyAccount MBean into the MBean server
    try {
        final MyAccountMBeanImpl myAccountMBean = new MyAccountMBeanImpl(this.accountsManager);
        final ObjectName name = new ObjectName(RMJMXBeans.MYACCOUNT_MBEAN_NAME);
        mbs.registerMBean(myAccountMBean, name);
    } catch (Exception e) {
        LOGGER.error("Unable to register the MyAccountMBean", e);
    }

    // Register the ViewAccount MBean into the MBean server
    try {
        final AllAccountsMBeanImpl viewAccountMBean = new AllAccountsMBeanImpl(this.accountsManager);
        final ObjectName name = new ObjectName(RMJMXBeans.ALLACCOUNTS_MBEAN_NAME);
        mbs.registerMBean(viewAccountMBean, name);
    } catch (Exception e) {
        LOGGER.error("Unable to register the AllAccountsMBean", e);
    }

    // Register the Management MBean into the MBean server
    try {
        final ManagementMBeanImpl managementMBean = new ManagementMBeanImpl(this.accountsManager);
        final ObjectName name = new ObjectName(RMJMXBeans.MANAGEMENT_MBEAN_NAME);
        mbs.registerMBean(managementMBean, name);
    } catch (Exception e) {
        LOGGER.error("Unable to register the ManagementMBean", e);
    }
}

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

public static ColumnFamilyStore createColumnFamilyStore(String table, String columnFamily) throws IOException {
    /*//  w w w.j av  a  2  s .co m
     * 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:com.fatwire.dta.sscrawler.URLReaderService.java

public void start(final ProgressMonitor monitor) {

    connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.getParams().setConnectionTimeout(30000);
    connectionManager.getParams().setDefaultMaxConnectionsPerHost(1500);
    connectionManager.getParams().setMaxTotalConnections(30000);
    final MBeanServer platform = java.lang.management.ManagementFactory.getPlatformMBeanServer();
    try {//from   w w w.j a  v  a2 s.c  o m
        platform.registerMBean(new ReaderService(scheduler, connectionManager),
                new ObjectName("com.fatwire.crawler:name=scheduler"));
    } catch (final Throwable t) {
        log.error(t.getMessage(), t);
    }

    monitor.beginTask("Crawling on " + hostConfig.toString(), maxPages == Integer.MAX_VALUE ? -1 : maxPages);
    scheduler.monitor = monitor;
    for (final QueryString thingToDo : startUrls) {

        scheduler.schedulePage(thingToDo);
    }
    scheduler.waitForlAllTasksToFinish();
    try {
        connectionManager.shutdown();
    } catch (final Throwable t) {
        log.error(t.getMessage(), t);
    }
    try {
        platform.unregisterMBean(new ObjectName("com.fatwire.crawler:name=scheduler"));
    } catch (final Throwable t) {
        log.error(t.getMessage(), t);
    }

    monitor.done();

}

From source file:org.apache.streams.local.queues.ThroughputQueue.java

/**
 * Creates a bounded, registered {@code ThroughputQueue}
 *
 * @param maxSize maximum capacity of queue, if maxSize < 1 then unbounded
 * @param id      unique id for this queue to be registered with. if id == NULL then not registered
 *//*from   w w w  . j  a  va  2  s.  c o m*/
public ThroughputQueue(int maxSize, String id, String streamIdentifier, long startedAt) {
    if (maxSize < 1) {
        this.underlyingQueue = new LinkedBlockingQueue<>();
    } else {
        this.underlyingQueue = new LinkedBlockingQueue<>(maxSize);
    }
    this.elementsAdded = new AtomicLong(0);
    this.elementsRemoved = new AtomicLong(0);
    this.startTime = new AtomicLong(-1);
    this.active = false;
    this.maxQueuedTime = 0;
    this.maxQueueTimeLock = new ReentrantReadWriteLock();
    this.totalQueueTime = new AtomicLong(0);
    if (id != null) {
        try {
            ObjectName name = new ObjectName(String.format(NAME_TEMPLATE, id, streamIdentifier, startedAt));
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            mbs.registerMBean(this, name);
        } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException
                | NotCompliantMBeanException e) {
            LOGGER.error("Failed to register MXBean : {}", e);
            throw new RuntimeException(e);
        }
    }
}

From source file:com.liferay.portal.dao.jdbc.DataSourceFactoryImpl.java

protected DataSource initDataSourceTomcat(Properties properties) throws Exception {

    PoolProperties poolProperties = new PoolProperties();

    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();

        // Ignore Liferay properties

        if (isPropertyLiferay(key)) {
            continue;
        }/*from   w w w .j  av  a  2s  .  co m*/

        // Ignore C3P0 properties

        if (isPropertyC3PO(key)) {
            continue;
        }

        // Ignore Primrose properties

        if (isPropertyPrimrose(key)) {
            continue;
        }

        try {
            BeanUtil.setProperty(poolProperties, key, value);
        } catch (Exception e) {
            if (_log.isWarnEnabled()) {
                _log.warn("Property " + key + " is not a valid Tomcat JDBC " + "Connection Pool property");
            }
        }
    }

    String poolName = PwdGenerator.getPassword(PwdGenerator.KEY2, 8);

    poolProperties.setName(poolName);

    org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(
            poolProperties);

    if (poolProperties.isJmxEnabled()) {
        org.apache.tomcat.jdbc.pool.ConnectionPool jdbcConnectionPool = dataSource.createPool();

        ConnectionPool jmxConnectionPool = jdbcConnectionPool.getJmxPool();

        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

        ObjectName objectName = new ObjectName(_TOMCAT_JDBC_POOL_OBJECT_NAME_PREFIX + poolName);

        mBeanServer.registerMBean(jmxConnectionPool, objectName);
    }

    return dataSource;
}