Example usage for javax.management.remote JMXConnectorFactory connect

List of usage examples for javax.management.remote JMXConnectorFactory connect

Introduction

In this page you can find the example usage for javax.management.remote JMXConnectorFactory connect.

Prototype

public static JMXConnector connect(JMXServiceURL serviceURL, Map<String, ?> environment) throws IOException 

Source Link

Document

Creates a connection to the connector server at the given address.

This method is equivalent to:

 JMXConnector conn = JMXConnectorFactory.newJMXConnector(serviceURL, environment); conn.connect(environment); 

Usage

From source file:org.zenoss.jmxnl.NotificationListener.java

@SuppressWarnings("unchecked")
private void connect() throws IOException {
    log.info(url + ": Attempting connection (timeout in 180 seconds)");
    JMXConnector connector = JMXConnectorFactory.connect(url, environment);
    connector.addConnectionNotificationListener(this, null, "placeholder");
    MBeanServerConnection connection = connector.getMBeanServerConnection();

    log.info(url + ": Connected.");
    sendConnectionEvent("0", "JMX connection has been restored");

    Set<ObjectName> results = connection.queryNames(scope, null);
    java.util.Iterator<ObjectName> iter = results.iterator();
    while (iter.hasNext()) {
        ObjectName objName = (ObjectName) iter.next();
        String type = objName.getKeyProperty("type");
        if (type == null || !type.equals("alias")) {
            try {
                connection.addNotificationListener(objName, this, attributeFilter, zenossDevice);
                log.debug("Added notification listener: " + objName);
            } catch (IllegalArgumentException e) {
                log.debug("Can't listen to " + objName + " because it is not a notification broadcaster.");
            } catch (InstanceNotFoundException e) {
                log.debug("Can't listen to " + objName + " because it was not found on the server.");
            }//from  w  w w . j av  a  2  s  .co m
        }

        // There can be a lot of listeners to add. Give other threads a
        // chance to get work done while this happens.
        Thread.yield();
    }
}

From source file:org.apache.cassandra.tools.AbstractJmxClient.java

private void connect() throws IOException {
    JMXServiceURL jmxUrl = new JMXServiceURL(String.format(FMT_URL, host, port));
    Map<String, Object> env = new HashMap<String, Object>();

    if (username != null)
        env.put(JMXConnector.CREDENTIALS, new String[] { username, password });

    jmxc = JMXConnectorFactory.connect(jmxUrl, env);
    mbeanServerConn = jmxc.getMBeanServerConnection();
}

From source file:org.rhq.plugins.cassandra.CassandraNodeComponent.java

private boolean isStorageServiceReachable() {
    JMXConnector connector = null;
    try {//from  www.  j  a  va2  s. com
        Configuration pluginConfig = getResourceContext().getPluginConfiguration();
        String url = pluginConfig.getSimpleValue("connectorAddress");
        JMXServiceURL serviceURL = new JMXServiceURL(url);
        connector = JMXConnectorFactory.connect(serviceURL, null);

        MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
        ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");

        // query an attribute to make sure it is in fact available
        serverConnection.getAttribute(storageService, "NativeTransportRunning");

        return true;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to make JMX connection to StorageService", e);
        }
        return false;
    } finally {
        if (connector != null) {
            try {
                connector.close();
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("An error occurred closing the JMX connector", e);
                }
            }
        }
    }
}

From source file:org.apache.hadoop.hdfs.tools.DataNodeAdmin.java

/**
 * Creates the mbean server connection/*from w w  w .j  av a2 s. co  m*/
 * @throws MalformedObjectNameException
 * @throws IOException
 */
private MBeanServerConnection mBeanServerConnection() throws MalformedObjectNameException, IOException {
    return JMXConnectorFactory.connect(new JMXServiceURL(SERVER_URL), null).getMBeanServerConnection();
}

From source file:com.clustercontrol.jmx.factory.RunMonitorJmx.java

/**
 * JMX ??//from ww w.jav a 2s. c o m
 * 
 * @param facilityId ID
 * @return ???????true
 */
@Override
public boolean collect(String facilityId) {
    boolean result = false;

    if (m_now != null) {
        m_nodeDate = m_now.getTime();
    }
    m_value = 0;
    exception = null;

    NodeInfo node = null;
    if (!m_isMonitorJob) {
        node = nodeInfo.get(facilityId);
    } else {
        try {
            // ??
            node = new RepositoryControllerBean().getNode(facilityId);
        } catch (Exception e) {
            m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES.getMessage();
            return false;
        }
    }

    JMXServiceURL url = null;
    try {
        String rmiFormat = HinemosPropertyUtil.getHinemosPropertyStr("monitor.jmx.rmi.format",
                "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi");
        String urlStr = String.format(rmiFormat, node.getAvailableIpAddress(), jmx.getPort());
        m_log.debug("facilityId=" + facilityId + ", url=" + urlStr);
        url = new JMXServiceURL(urlStr);
    } catch (Exception e) {
        m_log.warn("fail to initialize JMXServiceURL : " + e.getMessage() + " (" + e.getClass().getName() + ")",
                e);
        exception = e;
        return result;
    }

    JMXConnector jmxc = null;
    try {
        Map<String, Object> env = new HashMap<>();

        if (jmx.getAuthUser() != null)
            env.put(JMXConnector.CREDENTIALS, new String[] { jmx.getAuthUser(), jmx.getAuthPassword() });

        System.setProperty("sun.rmi.transport.tcp.responseTimeout", Integer.toString(HinemosPropertyUtil
                .getHinemosPropertyNum("system.sun.rmi.transport.tcp.responseTimeout", Long.valueOf(10 * 1000))
                .intValue()));
        jmxc = JMXConnectorFactory.connect(url, env);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        JmxMasterInfo jmxMasterInfo = QueryUtil.getJmxMasterInfoPK(jmx.getMasterId());
        Object value = mbsc.getAttribute(new ObjectName(jmxMasterInfo.getObjectName()),
                jmxMasterInfo.getAttributeName());
        m_value = Double.parseDouble(
                searchTargetValue(value, Arrays.asList(KeyParser.parseKeys(jmxMasterInfo.getKeys())))
                        .toString());

        // ??
        if (m_convertFlg == ConvertValueConstant.TYPE_DELTA) {

            // ??
            MonitorJmxValue valueEntity = null;
            Double prevValue = 0d;
            Long prevDate = 0l;

            if (!m_isMonitorJob) {
                // ??
                // cache??
                valueEntity = MonitorJmxCache.getMonitorJmxValue(m_monitorId, facilityId);

                // ???
                prevValue = valueEntity.getValue();
                if (valueEntity.getGetDate() != null) {
                    prevDate = valueEntity.getGetDate();
                }
            } else {
                // ??
                valueEntity = new MonitorJmxValue(new MonitorJmxValuePK(m_monitorId, facilityId));
                if (m_prvData instanceof MonitorJmxValue) {
                    // ????
                    prevValue = ((MonitorJmxValue) m_prvData).getValue();
                    prevDate = ((MonitorJmxValue) m_prvData).getGetDate();
                }
            }

            // JMX????
            valueEntity.setValue(Double.valueOf(m_value));
            valueEntity.setGetDate(m_nodeDate);

            if (!m_isMonitorJob) {
                // ???ID?????
                if (m_monitor.getMonitorFlg())
                    MonitorJmxCache.update(m_monitorId, facilityId, valueEntity);

                int m_validSecond = HinemosPropertyUtil
                        .getHinemosPropertyNum("monitor.jmx.valid.second", Long.valueOf(15)).intValue();
                // ???????????
                int tolerance = (m_runInterval + m_validSecond) * 1000;

                if (prevDate > m_nodeDate - tolerance) {

                    // ??null???
                    if (prevValue == null) {
                        m_log.debug("collect() : prevValue is null");
                        m_prevNullchk = true;
                        return false;
                    }

                    m_value = m_value - prevValue;
                } else {
                    if (prevDate != 0l) {
                        DateFormat df = DateFormat.getDateTimeInstance();
                        df.setTimeZone(HinemosTime.getTimeZone());
                        String[] args = { df.format(new Date(prevDate)) };
                        m_message = MessageConstant.MESSAGE_TOO_OLD_TO_CALCULATE.getMessage(args);
                        return false;
                    } else {
                        // ???0??
                        m_nodeDate = 0l;
                    }
                }
            } else {
                m_value = m_value - prevValue;
                m_curData = valueEntity;
            }
        }

        m_log.debug(jmxMasterInfo.getName() + " : " + m_value + " " + jmxMasterInfo.getMeasure());

        result = true;
    } catch (NumberFormatException e) {
        m_log.info("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        String[] args = { Double.toString(m_value) };
        m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NUMERIC_VALUE.getMessage(args);
        return false;
    } catch (Exception e) {
        String message = e.getMessage();
        if (message != null) {
            message = message.replaceAll("\n", "");
        }
        m_log.warn("fail to access JMXService : " + message + " (" + e.getClass().getName() + ")");
        exception = e;
    } finally {
        try {
            if (jmxc != null) {
                jmxc.close();
            }
        } catch (IOException e) {
            m_log.info("fail to close JMXService : " + e.getMessage() + " (" + e.getClass().getName() + ")");
            exception = e;
        }
    }

    return result;
}

From source file:fullThreadDump.java

private void connect(boolean jbossRemotingJMX, String hostname, String user, String passwd) {
    String urlString;//from   ww  w .j  av  a 2  s . com
    try {
        HashMap<String, String[]> env = new HashMap<String, String[]>();
        String[] creds = new String[2];
        creds[0] = user;
        creds[1] = passwd;
        env.put(JMXConnector.CREDENTIALS, creds);
        if (jbossRemotingJMX) {
            urlString = "service:jmx:remoting-jmx://" + hostname;
            this.serviceURL = new JMXServiceURL(urlString);
            System.out.println("\n\nConnecting to " + urlString);
        } else {
            urlString = "/jndi/rmi://" + hostname + "/jmxrmi";
            this.serviceURL = new JMXServiceURL("rmi", "", 0, urlString);
            System.out.println("\n\nConnecting to " + urlString);
        }

        //this.jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
        this.jmxConnector = JMXConnectorFactory.connect(serviceURL, env);
        this.server = jmxConnector.getMBeanServerConnection();
    } catch (MalformedURLException e) {
        // should not reach here
    } catch (IOException e) {
        System.err.println("\nCommunication error: " + e.getMessage());
        System.exit(1);
    }
}

From source file:org.wso2.dss.integration.test.datasource.DataSourceInitializationAtStartUpTestCase.java

@Test(dependsOnMethods = { "isServiceExistAfterRestarting" }, enabled = false)
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
public void testMBeanForDatasource() throws AxisFault {
    Map<String, String[]> env = new HashMap<String, String[]>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    try {//from   w ww . j  a  v  a  2s.  c o  m
        String url = "service:jmx:rmi://localhost:11111/jndi/rmi://localhost:9999/jmxrmi";
        JMXServiceURL jmxUrl = new JMXServiceURL(url);
        JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mBeanServer = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanObject = new ObjectName(dataSourceName + ",-1234:type=DataSource");
        MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(mbeanObject);
        Assert.assertNotNull(mBeanInfo, "Data Source is registered in the MBean server");
    } catch (MalformedURLException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (IOException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (MalformedObjectNameException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (IntrospectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    }

}

From source file:org.wso2.ei.dataservice.integration.test.datasource.DataSourceInitializationAtStartUpTestCase.java

@Test(dependsOnMethods = { "isServiceExistAfterRestarting" }, enabled = false)
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
public void testMBeanForDatasource() throws AxisFault {
    Map<String, String[]> env = new HashMap<String, String[]>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    try {// w w w  .j av  a  2 s.c  o  m
        String url = "service:jmx:rmi://localhost:11111/jndi/rmi://localhost:9999/jmxrmi";
        JMXServiceURL jmxUrl = new JMXServiceURL(url);
        JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mBeanServer = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanObject = new ObjectName(dataSourceName + ",-1234:type=DataSource");
        MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(mbeanObject);
        Assert.assertNotNull(mBeanInfo, "Datasource is registered in the MBean server");
    } catch (MalformedURLException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (IOException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (MalformedObjectNameException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (IntrospectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    }

}

From source file:org.opendaylight.infrautils.diagstatus.MBeanUtils.java

public static <T, R> R invokeRemoteMBeanOperation(String remoteURL, String jmxName, Class<T> klass,
        Function<T, R> function) throws MalformedObjectNameException, IOException {
    JMXServiceURL jmxURL = new JMXServiceURL(remoteURL);
    try (JMXConnector jmxc = JMXConnectorFactory.connect(jmxURL, null)) {
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        T remoteMBean = getMBean(jmxName, klass, mbsc);
        return function.apply(remoteMBean);
    }/*from   w ww  .  jav a  2 s  .  c  o m*/
}

From source file:com.adaptris.core.jmx.JmxConnection.java

private MBeanServerConnection createConnection() throws IOException, AdaptrisSecurityException {
    MBeanServerConnection result = null;
    if (!isBlank(getJmxServiceUrl())) {
        Map env = KeyValuePairBag.asMap(getJmxProperties());
        if (!isBlank(getUsername())) {
            if (!env.containsKey(JMX_REMOTE_PROFILES)) {
                env.put(JMX_REMOTE_PROFILES, SASL_PLAIN);
            }/*ww w.  j a v a  2 s  .c o m*/
            env.put(JMXConnector.CREDENTIALS,
                    new String[] { getUsername(), Password.decode(ExternalResolver.resolve(getPassword())) });
        }
        connector = JMXConnectorFactory.connect(new JMXServiceURL(getJmxServiceUrl()),
                env.size() == 0 ? null : env);
        result = connector.getMBeanServerConnection();
    } else {
        result = JmxHelper.findMBeanServer();
    }
    return result;
}