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 domain, String key, String value) throws MalformedObjectNameException 

Source Link

Document

Construct an object name with exactly one key property.

Usage

From source file:com.netsteadfast.greenstep.util.HostUtils.java

public static int getHttpPort() {
    int port = 8080;
    MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
    ObjectName name;//from   ww w.  j  av  a 2s.co m
    try {
        name = new ObjectName("Catalina", "type", "Server");
        try {
            Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
            Service[] services = server.findServices();
            for (Service service : services) {
                for (Connector connector : service.findConnectors()) {
                    ProtocolHandler protocolHandler = connector.getProtocolHandler();
                    if (protocolHandler instanceof Http11Protocol
                            || protocolHandler instanceof Http11AprProtocol
                            || protocolHandler instanceof Http11NioProtocol) {
                        port = connector.getPort();
                    }
                }
            }
        } catch (AttributeNotFoundException e) {
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            e.printStackTrace();
        } catch (MBeanException e) {
            e.printStackTrace();
        } catch (ReflectionException e) {
            e.printStackTrace();
        }
    } catch (MalformedObjectNameException e) {
        e.printStackTrace();
    }
    return port;
}

From source file:chronos.web.listener.ChronosServletListener.java

/**
 * @param mbeanServer//  www .  j  a  va2s  .com
 *        the MBeanServer
 */
private void initializeQuartzSchedulerAdapter(final MBeanServer mbeanServer) {
    try {
        logger.debug("Creating and registering QuartzSchedulerAdapter MBean...");

        final ObjectName objectName = new ObjectName(CHRONOS, "type", QUARTZ_SCHEDULER_ADAPTER);

        final QuartzSchedulerAdapter quartzSchedulerAdapter = new QuartzSchedulerAdapter();
        mbeanServer.registerMBean(quartzSchedulerAdapter, objectName);

        logger.debug("Invoking start() on QuartzSchedulerAdapter MBean...");
        try {
            mbeanServer.invoke(objectName, "start", null, null);
        } catch (final JMException e) {
            logger.error("QuartzSchedulerAdapter start() failed: " + e.getMessage(), e);
        }
    } catch (final JMException e) {
        logger.error("Registering QuartzSchedulerAdapter failed: " + e.getMessage(), e);
    }
}

From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

/**
 * Verifies that we can create a pooled jdbc data source using the JDBC .jar-file supplied in the global configuration
 * file.// w w w . ja  va2 s .com
 *
 * @throws Exception
 */
@Test
public void testLoadJdbcDriverUsingCustomClassLoader() throws Exception {
    ConnectionFactory driverConnectionFactory = createConnectionFactory(false);

    ObjectName poolName = new ObjectName("no.difi.oxalis", "connectionPool", "TestPool");
    PoolableConnectionFactory factory = new PoolableConnectionFactory(driverConnectionFactory, poolName);

    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<>(factory);
    factory.setPool(pool);

    pool.setMaxTotal(10);
    pool.setMaxWaitMillis(100);

    assertEquals(pool.getFactory(), factory);

    PoolableConnectionFactory pcf = (PoolableConnectionFactory) ((GenericObjectPool<?>) pool).getFactory();
    ObjectPool<PoolableConnection> pool1 = pcf.getPool();

    PoolingDataSource<PoolableConnection> poolingDataSource = new PoolingDataSource<>(pool);

    Connection connection = poolingDataSource.getConnection();
    assertNotNull(connection);

    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select current_date()");

    assertTrue(resultSet.next());
}

From source file:com.github.brandtg.switchboard.MysqlReplicator.java

@Override
public void start() throws Exception {
    // DBCP2 pool
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcString, user, password);
    ObjectName poolName = new ObjectName(JdbcBasedLogIndex.class.getCanonicalName(),
            URLEncoder.encode(jdbcString, ENCODING), "replicatorConnectionPool");
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            poolName);/*from w  w w .  j a va  2 s .  co m*/
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool);
    this.dataSource = new PoolingDataSource<PoolableConnection>(connectionPool);
    LOG.info("Opened connection pool to {} as {}", jdbcString, user);

    // Replication applier
    applier = new MysqlReplicationApplier(inputStream, dataSource);

    super.start();
}

From source file:chronos.web.listener.ChronosServletListener.java

/**
 * {@inheritDoc}//  w ww.j a v a 2 s.c  o m
 *
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 */
public void contextDestroyed(final ServletContextEvent event) {
    logger.debug("Chronos is shutting down...");
    final ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
    logger.debug("Got " + servers.size() + " MBean servers");
    if (servers.size() != 0) {
        final MBeanServer mbeanServer = servers.get(0);
        try {
            final ObjectName objectName = new ObjectName(CHRONOS, "type", QUARTZ_SCHEDULER_ADAPTER);

            logger.debug("Invoking shutdown() on QuartzSchedulerAdapter...");
            mbeanServer.invoke(objectName, "shutdown", null, null);

            logger.debug("Unregistering QuartzSchedulerAdapter Mbean");
            mbeanServer.unregisterMBean(objectName);
        } catch (final JMException e) {
            logger.error("Shutting down QuartzSchedulerAdapter failed: " + e.getMessage(), e);
        } catch (final NullPointerException e) {
            logger.error("Shutting down QuartzSchedulerAdapter failed: " + e.getMessage(), e);
        }
    } else {
        logger.warn("Unable to find MBeanServer!");
    }
    logger.info("Chronos shutdown");
}

From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImpl.java

/**
 * Creates a DataSource with connection pooling as provided by Apache DBCP
 *
 * @return a DataSource//from   ww w .  j  a  va 2 s  . c o m
 */
DataSource configureAndCreateDataSource(RepositoryConfiguration configuration) {

    log.debug("Configuring DataSource wrapped in a Database Connection Pool, using custom loader");

    String jdbcDriverClassPath = configuration.getJdbcDriverClassPath();

    log.debug("Loading JDBC Driver with custom class path: " + jdbcDriverClassPath);
    // Creates a new class loader, which will be used for loading our JDBC driver
    URLClassLoader urlClassLoader = getOxalisClassLoaderForJdbc(jdbcDriverClassPath);

    String className = configuration.getJdbcDriverClassName();
    String connectURI = configuration.getJdbcConnectionUri().toString();
    String userName = configuration.getJdbcUsername();
    String password = configuration.getJdbcPassword();

    log.debug("className=" + className);
    log.debug("connectURI=" + connectURI);
    log.debug("userName=" + userName);
    log.debug("password=" + password);

    // Loads the JDBC Driver in a separate class loader
    Driver driver = getJdbcDriver(jdbcDriverClassPath, urlClassLoader, className);

    Properties properties = new Properties();
    properties.put("user", userName);
    properties.put("password", password);

    // DBCP factory which will produce JDBC Driver instances
    ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectURI, properties);

    // DBCP Factory holding the pooled connection, which are created by the driver connection factory and held in the supplied pool
    ObjectName dataSourceJmxName = null;
    try {
        dataSourceJmxName = new ObjectName("no.difi.oxalis", "connectionPool", "OxalisDB");
    } catch (MalformedObjectNameException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
            dataSourceJmxName);

    String validationQuery = configuration.getValidationQuery();
    if (validationQuery != null) {
        poolableConnectionFactory.setValidationQuery(validationQuery);
    }
    // DBCP object pool holding our driver connections
    GenericObjectPool<PoolableConnection> genericObjectPool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);
    poolableConnectionFactory.setPool(genericObjectPool);
    genericObjectPool.setMaxTotal(100);
    genericObjectPool.setMaxIdle(30);
    genericObjectPool.setMaxWaitMillis(10000);

    genericObjectPool.setTestOnBorrow(true); // Test the connection returned from the pool

    genericObjectPool.setTestWhileIdle(true); // Test idle instances visited by the pool maintenance thread and destroy any that fail validation
    genericObjectPool.setTimeBetweenEvictionRunsMillis(60 * 60 * 1000); // Test every hour

    // Creates the actual DataSource instance
    PoolingDataSource poolingDataSource = new PoolingDataSource(genericObjectPool);

    return poolingDataSource;

}

From source file:com.parallels.desktopcloud.ParallelsDesktopConnectorSlaveComputer.java

private static VMResources getHostResources(Channel ch) throws Exception {
    return ch.call(new MasterToSlaveCallable<VMResources, Exception>() {
        private long getHostPhysicalMemory() {
            try {
                MBeanServer server = ManagementFactory.getPlatformMBeanServer();
                Object attribute = server.getAttribute(new ObjectName("java.lang", "type", "OperatingSystem"),
                        "TotalPhysicalMemorySize");
                return (Long) attribute;
            } catch (JMException e) {
                LOGGER.log(Level.SEVERE, "Failed to get host RAM size: %s", e);
                return Long.MAX_VALUE;
            }/*w  w w . ja v a 2s . co m*/
        }

        @Override
        public VMResources call() throws Exception {
            int cpus = Runtime.getRuntime().availableProcessors();
            long ram = getHostPhysicalMemory();
            return new VMResources(cpus, ram);
        }
    });
}

From source file:com.github.brandtg.switchboard.TestMysqlReplicationApplier.java

private PoolingDataSource<PoolableConnection> getDataSource() throws Exception {
    // DBCP2 pool
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbc, "root", "");
    ObjectName poolName = new ObjectName(JdbcBasedLogIndex.class.getCanonicalName(),
            URLEncoder.encode(jdbc, "UTF-8"), "replicatorConnectionPool");
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            poolName);//w  w  w  .j a v  a2 s . c  o  m
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool);
    return new PoolingDataSource<PoolableConnection>(connectionPool);
}

From source file:io.fabric8.mq.autoscaler.MQAutoScaler.java

public void start() throws Exception {
    if (started.compareAndSet(false, true)) {
        setBrokerSelector("container=java,name=" + getBrokerName() + ",group=" + getGroupName());
        setConsumerSelector("container=java,name=fabric8MQConsumer,group=fabric8MQConsumer");
        setProducerSelector("container=java,name=fabric8MQProducer,group=fabric8MQProducer");
        MQAutoScalerObjectName = new ObjectName(DEFAULT_DOMAIN, "type", "mq-autoscaler");
        JMXUtils.registerMBean(this, MQAutoScalerObjectName);

        kubernetes = new DefaultKubernetesClient();
        clients = new JolokiaClients(kubernetes);

        timer = new Timer("MQAutoScaler timer");
        startTimerTask();//from w w  w  .ja v a 2  s. c o  m
        LOG.info("MQAutoScaler started, using Kubernetes master " + kubernetes.getMasterUrl());
    }
}

From source file:org.wso2.carbon.metrics.impl.ReporterTest.java

private AttributeList getAttributes(String name, String... attributeNames) {
    ObjectName n;/*w w w .j  a  va2 s  .c o m*/
    try {
        n = new ObjectName("org.wso2.carbon.metrics", "name", name);
        return mBeanServer.getAttributes(n, attributeNames);
    } catch (MalformedObjectNameException e) {
        fail(e.getMessage());
    } catch (InstanceNotFoundException e) {
        fail(e.getMessage());
    } catch (ReflectionException e) {
        fail(e.getMessage());
    }
    return null;
}