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:com.frameworkset.commons.dbcp2.PoolableConnectionFactory.java

@Override
public PooledObject<PoolableConnection> makeObject() throws Exception {
    Connection conn = _connFactory.createConnection();
    if (conn == null) {
        throw new IllegalStateException("Connection factory returned null from createConnection");
    }/*from   w w w.  j av  a2s  . c  o  m*/
    try {
        initializeConnection(conn);
    } catch (SQLException sqle) {
        // Make sure the connection is closed
        try {
            conn.close();
        } catch (SQLException ignore) {
            // ignore
        }
        // Rethrow original exception so it is visible to caller
        throw sqle;
    }

    long connIndex = connectionIndex.getAndIncrement();

    if (poolStatements) {
        conn = new PoolingConnection(conn);
        GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
        config.setMaxTotalPerKey(-1);
        config.setBlockWhenExhausted(false);
        config.setMaxWaitMillis(0);
        config.setMaxIdlePerKey(1);
        config.setMaxTotal(maxOpenPreparedStatements);
        if (dataSourceJmxName != null) {
            StringBuilder base = new StringBuilder(dataSourceJmxName.toString());
            base.append(Constants.JMX_CONNECTION_BASE_EXT);
            base.append(Long.toString(connIndex));
            config.setJmxNameBase(base.toString());
            config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
        } else {
            config.setJmxEnabled(false);
        }
        KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement>(
                (PoolingConnection) conn, config);
        ((PoolingConnection) conn).setStatementPool(stmtPool);
        ((PoolingConnection) conn).setCacheState(_cacheState);
    }

    // Register this connection with JMX
    ObjectName connJmxName;
    if (dataSourceJmxName == null) {
        connJmxName = null;
    } else {
        connJmxName = new ObjectName(
                dataSourceJmxName.toString() + Constants.JMX_CONNECTION_BASE_EXT + connIndex);
    }

    PoolableConnection pc = new PoolableConnection(conn, _pool, connJmxName, _disconnectionSqlCodes,
            _fastFailValidation);

    return new DefaultPooledObject<PoolableConnection>(pc);
}

From source file:de.innovationgate.webgate.api.jdbc.pool.DBCPConnectionProvider.java

public void configure(Map propsMap) throws HibernateException {
    try {/* w  w w  . ja  v a 2  s  . c om*/
        log.debug("Configure DBCPConnectionProvider");
        Properties props = new Properties();
        props.putAll(propsMap);

        String jdbcUrl = (String) props.getProperty(Environment.URL);

        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();

        // DriverClass & url
        String jdbcDriverClass = props.getProperty(Environment.DRIVER);

        // Try to determine driver by jdbc-URL
        if (jdbcDriverClass == null) {
            Driver driver = DriverManager.getDriver(jdbcUrl);
            if (driver != null) {
                jdbcDriverClass = driver.getClass().getName();
            } else {
                throw new HibernateException("Driver class not available");
            }
        }

        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);

        // Username / password
        String username = props.getProperty(Environment.USER);
        if (username != null) {
            dbcpProperties.put("username", username);
        }

        String password = props.getProperty(Environment.PASS);
        if (password != null) {
            dbcpProperties.put("password", password);
        }

        // Isolation level
        String isolationLevel = props.getProperty(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }

        // Turn off autocommit (unless autocommit property is set) 
        String autocommit = props.getProperty(AUTOCOMMIT);
        if ((autocommit != null) && (autocommit.trim().length() > 0)) {
            dbcpProperties.put("defaultAutoCommit", autocommit);
        } else {
            dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        }

        // Pool size
        String poolSize = props.getProperty(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }

        // Copy all "driver" properties into "connectionProperties"
        Properties driverProps = ConnectionProviderInitiator.getConnectionProperties(props);
        if (driverProps.size() > 0) {
            StringBuffer connectionProperties = new StringBuffer();
            for (Iterator iter = driverProps.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = driverProps.getProperty(key);
                connectionProperties.append(key).append('=').append(value);
                if (iter.hasNext()) {
                    connectionProperties.append(';');
                }
            }
            dbcpProperties.put("connectionProperties", connectionProperties.toString());
        }

        // Copy all DBCP properties removing the prefix
        for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
            String key = String.valueOf(iter.next());
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = props.getProperty(key);
                dbcpProperties.put(property, value);
            }
        }

        // Backward-compatibility
        if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
            dbcpProperties.put("poolPreparedStatements", String.valueOf(Boolean.TRUE));
            dbcpProperties.put("maxOpenPreparedStatements", props.getProperty(DBCP_PS_MAXACTIVE));
        }
        if (props.getProperty(DBCP_MAXACTIVE) != null) {
            dbcpProperties.put("maxTotal", props.getProperty(DBCP_MAXACTIVE));
        }
        if (props.getProperty(DBCP_MAXWAIT) != null) {
            dbcpProperties.put("maxWaitMillis", props.getProperty(DBCP_MAXWAIT));
        }

        // Some debug info
        if (log.isDebugEnabled()) {
            log.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            log.debug(sw.toString());
        }

        String dbKey = (String) props.get("hibernate.dbcp.dbkey");
        String databaseServerId = (String) props.get("hibernate.dbcp.dbserver.id");

        // Enable DBCP2 JMX monitoring information
        if (dbKey != null) {
            dbcpProperties.put("jmxName",
                    JMX_DBCP2_DBPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(dbKey));
        } else if (databaseServerId != null) {
            String entityTitle = props.getProperty("hibernate.dbcp.dbserver.title");
            dbcpProperties.put("jmxName",
                    JMX_DBCP2_SERVERPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(entityTitle));
        }

        // Let the factory create the pool
        _ds = BasicDataSourceFactory.createDataSource(dbcpProperties);
        _ds.setLogExpiredConnections(false);

        // The BasicDataSource has lazy initialization
        // borrowing a connection will start the DataSource
        // and make sure it is configured correctly.
        Connection conn = _ds.getConnection();
        conn.close();

        // Create Legacy JMX monitoring information, provided by WGA
        if ("true".equals(props.getProperty("hibernate.dbcp.legacyJMX"))) {
            try {
                if (dbKey != null) {
                    _entityKey = dbKey;
                    _entityTitle = dbKey;
                    _jmxManager = new JmxManager(new DBCPPoolInformation(this),
                            new ObjectName(JMX_DBPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(dbKey)));
                } else if (databaseServerId != null) {
                    _server = true;
                    _entityKey = databaseServerId;
                    _entityTitle = (String) props.get("hibernate.dbcp.dbserver.title");
                    _jmxManager = new JmxManager(new DBCPPoolInformation(this), new ObjectName(
                            JMX_SERVERPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(_entityTitle)));
                }
            } catch (Throwable e) {
                log.error("Error enabling JMX metrics for connection pool", e);
            }
        }

    } catch (Exception e) {
        String message = "Could not create a DBCP pool";
        if (_ds != null) {
            try {
                _ds.close();
            } catch (Exception e2) {
                // ignore
            }
            _ds = null;
        }
        throw new HibernateException(message, e);
    }
    log.debug("Configure DBCPConnectionProvider complete");

}

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

private MetricValue getPercentActiveConnections(MBeanServerConnection connection, Metric metric)
        throws MetricUnreachableException, MetricNotFoundException, PluginException {
    int numActiveConnections = 0;
    int maxActiveConnections = 0;

    try {/*from  w w  w.  java2  s .c  o  m*/
        ObjectName dataSourceObjectName = new ObjectName(metric.getObjectName());
        numActiveConnections = ((Integer) connection.getAttribute(dataSourceObjectName, "numActive"))
                .intValue();
        maxActiveConnections = ((Integer) connection.getAttribute(dataSourceObjectName, "maxActive"))
                .intValue();
    } catch (MalformedObjectNameException e) {
        throw new MetricInvalidException("Error querying for DataSource MBeans: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MetricUnreachableException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (AttributeNotFoundException e) {
        throw new MetricNotFoundException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new MetricNotFoundException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (MBeanException e) {
        throw new PluginException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new PluginException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    } catch (NullPointerException e) {
        throw new PluginException("Error querying for DataSource MBeans:" + e.getMessage(), e);
    }

    return new MetricValue(100d * (double) numActiveConnections / (double) maxActiveConnections);
}

From source file:org.apache.uima.examples.as.GetMetaRequest.java

private static QueueState isQueueAvailable(String queueName) throws Exception {
    if (!initialized) {
        return QueueState.jmxnot;
    }/*from ww  w.j  a v  a 2  s .co  m*/
    ObjectName uimaServiceQueuePattern = new ObjectName(brokerName + ",Type=Queue,Destination=" + queueName);
    // Tests if queue exists. If a client terminates, the reply queue will be removed and we
    // expect null from getQueueMBean()
    if (isServerAvailable() && getQueueMBean(queueName, uimaServiceQueuePattern) == null) {
        return QueueState.existsnot;
    }
    return QueueState.exists;
}

From source file:JDBCPool.dbcp.demo.sourcecode.PoolableConnectionFactory.java

/**
 * ?PoolDefaultPooledObject??Connection//w w w . ja  v a 2  s  . com
 */
@Override
public PooledObject<PoolableConnection> makeObject() throws Exception {
    Connection conn = _connFactory.createConnection();
    if (conn == null) {
        throw new IllegalStateException("Connection factory returned null from createConnection");
    }

    try {
        initializeConnection(conn); //?SQL?SQL
    } catch (SQLException sqle) {
        // Make sure the connection is closed
        try {
            conn.close();
        } catch (SQLException ignore) {
            // ignore
        }
        // Rethrow original exception so it is visible to caller
        throw sqle;
    }

    long connIndex = connectionIndex.getAndIncrement();

    if (poolStatements) {
        conn = new PoolingConnection(conn);
        GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
        config.setMaxTotalPerKey(-1);
        config.setBlockWhenExhausted(false);
        config.setMaxWaitMillis(0);
        config.setMaxIdlePerKey(1);
        config.setMaxTotal(maxOpenPreparedStatements);
        if (dataSourceJmxName != null) {
            StringBuilder base = new StringBuilder(dataSourceJmxName.toString());
            base.append(Constants.JMX_CONNECTION_BASE_EXT);
            base.append(Long.toString(connIndex));
            config.setJmxNameBase(base.toString());
            config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
        } else {
            config.setJmxEnabled(false);
        }
        KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<>(
                (PoolingConnection) conn, config);
        ((PoolingConnection) conn).setStatementPool(stmtPool);
        ((PoolingConnection) conn).setCacheState(_cacheState);
    }

    // Register this connection with JMX
    ObjectName connJmxName;
    if (dataSourceJmxName == null) {
        connJmxName = null;
    } else {
        connJmxName = new ObjectName(
                dataSourceJmxName.toString() + Constants.JMX_CONNECTION_BASE_EXT + connIndex);
    }

    PoolableConnection pc = new PoolableConnection(conn, _pool, connJmxName, _disconnectionSqlCodes,
            _fastFailValidation);

    return new DefaultPooledObject<>(pc);
}

From source file:com.impetus.ankush2.cassandra.monitor.CassandraClusterMonitor.java

private void nodeoverview() throws AnkushException {
    // getting node's hostname for which monitoring details is to be fetched
    String hostName = (String) parameterMap.get(Constant.Keys.HOST);
    // if hostname is null
    if (hostName == null || hostName.isEmpty()) {
        throw new AnkushException("Hostname is missing.");
    }/*w  w w.j  a v  a 2 s . c  om*/
    JmxUtil jmxUtil = null;
    Map<String, Object> nodeData = new HashMap<String, Object>();
    try {
        NodeMonitoring nodeMonitoring = new MonitoringManager().getMonitoringData(hostName);
        if (nodeMonitoring == null) {
            throw new AnkushException("Could not get monitoring data for node: " + hostName);
        }
        // Cassandra service status
        Map<String, Boolean> serviceStatus = nodeMonitoring.getServiceStatus(Constant.Component.Name.CASSANDRA);
        if (serviceStatus == null) {
            throw new AnkushException("Could not get service status for " + Constant.Component.Name.CASSANDRA);
        }
        // getting node role
        String role = CassandraUtils.getNodeRole(clusterConf.getNodes().get(hostName).getRoles());
        if (serviceStatus.get(role) == null || serviceStatus.get(role) == false) {
            throw new AnkushException(
                    "Could not get node details as " + Constant.Component.Name.CASSANDRA + "service is down.");
        }
        jmxUtil = getJMXConnection(hostName,
                (Integer) advanceConf.get(CassandraConstants.ClusterProperties.JMX_PORT));
        if (jmxUtil == null) {
            throw new AnkushException("Unable to get JMX connection.");
        }

        ObjectName mObjNameStorageService = new ObjectName(CassandraConstants.ORG_APACHE_CASSANDRA + "db:type="
                + CassandraConstants.Cassandra_JMX_Attributes.CASSANDRA_JMX_OBJECT_STORAGESERVICE);
        ObjectName mObjNameCaches = new ObjectName(CassandraConstants.ORG_APACHE_CASSANDRA + "db:type="
                + CassandraConstants.Cassandra_JMX_Attributes.CASSANDRA_JMX_OBJECT_CACHES);
        ObjectName mObjNameFailureDetector = new ObjectName(
                CassandraConstants.ORG_APACHE_CASSANDRA + "net:type="
                        + CassandraConstants.Cassandra_JMX_Attributes.CASSANDRA_JMX_OBJECT_FAILUREDETECTOR);
        if (mObjNameStorageService == null || mObjNameCaches == null || mObjNameFailureDetector == null) {
            throw new AnkushException("Could not get node details.");
        }
        List<String> tokens = getNodeTokens(jmxUtil, hostName, mObjNameStorageService);
        nodeData.put("ownership", getNodeOwnership(jmxUtil, mObjNameStorageService, hostName));
        nodeData.put("load", getNodeLoad(jmxUtil, mObjNameStorageService, hostName));
        nodeData.put("status", getNodeStatus(jmxUtil, hostName, mObjNameFailureDetector));
        nodeData.put("tokens", tokens);
        nodeData.put("tokenCount", tokens.size());
        nodeData.put("host", hostName);
        nodeData.put("keyCache", getCache(mObjNameCaches, getKeyCacheList(), jmxUtil));
        nodeData.put("rowCache", getCache(mObjNameCaches, getRowCacheList(), jmxUtil));
        getNodeTopology(nodeData, hostName, jmxUtil, mObjNameFailureDetector);
        result.put(Constant.Keys.NODEDATA, nodeData);
    } catch (AnkushException e) {
        addAndLogError(e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        addAndLogError("Could not get node details.");
    } finally {
        if (jmxUtil != null) {
            jmxUtil.disconnect();
        }
    }
}

From source file:ie.deri.wsmx.core.management.httpadapter.HttpAdapter.java

/**
 * Sets the factory's object name which will create the server sockets
 * /*from  ww w.j  a  va2s.c om*/
 * @param factoryName
 *            the socket factory
 */
public void setSocketFactoryNameString(String factoryName) throws MalformedObjectNameException {
    this.socketFactory = null;
    this.factoryName = new ObjectName(factoryName);
}

From source file:catalina.mbeans.MBeanFactory.java

/**
 * Create a new AjpConnector/*from  w  ww .jav a2s  .  c  om*/
 *
 * @param parent MBean Name of the associated parent component
 * @param address The IP address on which to bind
 * @param port TCP port number to listen on
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createAjpConnector(String parent, String address, int port) throws Exception {

    Object retobj = null;

    try {

        // Create a new CoyoteConnector instance for AJP
        // use reflection to avoid j-t-c compile-time circular dependencies
        Class cls = Class.forName("org.apache.coyote.tomcat4.CoyoteConnector");
        Constructor ct = cls.getConstructor(null);
        retobj = ct.newInstance(null);
        Class partypes1[] = new Class[1];
        // Set address
        String str = new String();
        partypes1[0] = str.getClass();
        Method meth1 = cls.getMethod("setAddress", partypes1);
        Object arglist1[] = new Object[1];
        arglist1[0] = address;
        meth1.invoke(retobj, arglist1);
        // Set port number
        Class partypes2[] = new Class[1];
        partypes2[0] = Integer.TYPE;
        Method meth2 = cls.getMethod("setPort", partypes2);
        Object arglist2[] = new Object[1];
        arglist2[0] = new Integer(port);
        meth2.invoke(retobj, arglist2);
        // set protocolHandlerClassName for AJP
        Class partypes3[] = new Class[1];
        partypes3[0] = str.getClass();
        Method meth3 = cls.getMethod("setProtocolHandlerClassName", partypes3);
        Object arglist3[] = new Object[1];
        arglist3[0] = new String("org.apache.jk.server.JkCoyoteHandler");
        meth3.invoke(retobj, arglist3);

    } catch (Exception e) {
        throw new MBeanException(e);
    }

    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    Server server = ServerFactory.getServer();
    Service service = server.findService(pname.getKeyProperty("name"));
    service.addConnector((Connector) retobj);

    // Return the corresponding MBean name
    ManagedBean managed = registry.findManagedBean("CoyoteConnector");
    ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), (Connector) retobj);
    return (oname.toString());

}

From source file:ddf.metrics.collector.rrd4j.RrdJmxCollector.java

/**
 * Verify MBean and its attribute exists and can be collected, i.e., is numeric data (vs.
 * CompositeData)/*  w  w w  .  j  av  a2  s. c o m*/
 *
 * @return true if MBean can be accessed, false otherwise
 */
private boolean isMbeanAccessible() {
    Object attr = null;
    long startTime = System.currentTimeMillis();
    while (attr == null && (System.currentTimeMillis() - startTime < mbeanTimeoutMillis)) {
        try {
            attr = localMBeanServer.getAttribute(new ObjectName(mbeanName), mbeanAttributeName);

            if (!isNumeric(attr)) {
                LOGGER.debug("{} from MBean {} has non-numeric data", mbeanAttributeName, mbeanName);
                return false;
            }

            if (!(attr instanceof Integer) && !(attr instanceof Long) && !(attr instanceof Float)
                    && !(attr instanceof Double)) {
                return false;
            }
        } catch (Exception e) {
            try {
                LOGGER.trace("MBean [{}] not found, sleeping...", mbeanName);
                Thread.sleep(1000);
            } catch (InterruptedException ie) {
                // Ignore this
            }
        }
    }

    return attr != null;
}

From source file:net.sf.ehcache.management.ManagementServiceTest.java

/**
 * Creates an RMI JMXConnectorServer, connects to it and demonstrates what attributes are traversable.
 * The answer is not all./*from  w w w.  j  ava2  s  . c  om*/
 *
 * Note that this test creates a Registry which will keep running until the JVM Exists. There
 * is no way to stop it but it should do no harm.
 *
 *
 */
public void testJMXConnectorServer() throws Exception {

    ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true);

    LocateRegistry.createRegistry(55000);
    String serverUrl = "service:jmx:rmi:///jndi/rmi://localhost:55000/server";
    JMXServiceURL url = new JMXServiceURL(serverUrl);
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer);
    cs.start();
    JMXConnector connector = cs.toJMXConnector(null);
    connector.connect(null);
    MBeanServerConnection connection = connector.getMBeanServerConnection();
    assertEquals(OBJECTS_IN_TEST_EHCACHE,
            connection.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());

    Ehcache ehcache = manager.getCache("sampleCache1");

    ehcache.put(new Element("key1", "value1"));
    ehcache.put(new Element("key2", "value1"));
    assertNotNull(ehcache.get("key1"));
    assertNotNull(ehcache.get("key2"));

    //Test CacheManager
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "CacheManager");

    //Test Cache
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "Cache");

    //Test CacheStatistics
    traverseMBeanAttributes(connection, "CacheStatistics");

    //Test CacheConfiguration
    traverseMBeanAttributes(connection, "CacheConfiguration");

    cs.stop();
}