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) throws IOException 

Source Link

Document

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

This method is equivalent to #connect(JMXServiceURL,Map) connect(serviceURL, null) .

Usage

From source file:com.redhat.poc.jdg.bankofchina.function.TestCase411RemoteMultiThreadsCustomMarshal.java

public static void registerProtofile(String jmxHost, int jmxPort, String cacheContainerName) throws Exception {
    JMXConnector jmxConnector = JMXConnectorFactory
            .connect(new JMXServiceURL("service:jmx:remoting-jmx://" + jmxHost + ":" + jmxPort));
    MBeanServerConnection jmxConnection = jmxConnector.getMBeanServerConnection();

    ObjectName protobufMetadataManagerObjName = new ObjectName("jboss.infinispan:type=RemoteQuery,name="
            + ObjectName.quote(cacheContainerName) + ",component=ProtobufMetadataManager");

    // initialize client-side serialization context via JMX
    byte[] descriptor = readClasspathResource("/model/userbaseinfo.protobin");
    jmxConnection.invoke(protobufMetadataManagerObjName, "registerProtofile", new Object[] { descriptor },
            new String[] { byte[].class.getName() });
    jmxConnector.close();/*from   ww w.  j a  va 2s .  com*/
}

From source file:org.apache.hadoop.hbase.TestJMXConnectorServer.java

/**
 * This tests to validate the HMaster's ConnectorServer after unauthorised shutdown call.
 *//*from   w  w  w.java 2s. com*/
@Test(timeout = 180000)
public void testHMConnectorServerWhenShutdownCluster() throws Exception {
    conf.set(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY,
            JMXListener.class.getName() + "," + MyAccessController.class.getName());
    conf.setInt("master.rmi.registry.port", rmiRegistryPort);

    UTIL.startMiniCluster();
    admin = UTIL.getConnection().getAdmin();

    boolean accessDenied = false;
    try {
        hasAccess = false;
        LOG.info("Stopping HMaster...");
        admin.shutdown();
    } catch (AccessDeniedException e) {
        LOG.error("Exception occured while stopping HMaster. ", e);
        accessDenied = true;
    }
    Assert.assertTrue(accessDenied);

    // Check whether HMaster JMX Connector server can be connected
    JMXConnector connector = null;
    try {
        connector = JMXConnectorFactory
                .connect(JMXListener.buildJMXServiceURL(rmiRegistryPort, rmiRegistryPort));
    } catch (IOException e) {
        if (e.getCause() instanceof ServiceUnavailableException) {
            Assert.fail("Can't connect to HMaster ConnectorServer.");
        }
    }
    Assert.assertNotNull("JMXConnector should not be null.", connector);
    connector.close();
}

From source file:org.lilyproject.lilyservertestfw.LilyProxy.java

public void start(SolrDefinition solrDef) throws Exception {
    if (started) {
        throw new IllegalStateException("LilyProxy is already started.");
    } else {//from  w  ww .ja  v  a  2 s .c  om
        started = true;
    }

    cleanOldTmpDirs();

    if (hasBeenStarted && this.mode == Mode.EMBED) {
        // In embed mode, we can't support multiple start-stop sequences since
        // HBase/Hadoop does not shut down all processes synchronously.
        throw new IllegalStateException("LilyProxy can only be started once in a JVM when using embed mode.");
    } else {
        hasBeenStarted = true;
    }

    System.out.println("LilyProxy mode: " + mode);

    if (mode == Mode.CONNECT) {
        // First reset the state
        System.out.println("Calling reset state flag on externally launched Lily...");
        try {
            String hostport = "localhost:10102";
            JMXServiceURL url = new JMXServiceURL(
                    "service:jmx:rmi://" + hostport + "/jndi/rmi://" + hostport + "/jmxrmi");
            JMXConnector connector = JMXConnectorFactory.connect(url);
            connector.connect();
            ObjectName lilyLauncher = new ObjectName("LilyLauncher:name=Launcher");
            connector.getMBeanServerConnection().invoke(lilyLauncher, "resetLilyState", new Object[0],
                    new String[0]);
            connector.close();
        } catch (Exception e) {
            throw new Exception("Resetting Lily state failed.", e);
        }
        System.out.println("State reset done.");
    }

    if (mode == Mode.EMBED || mode == Mode.HADOOP_CONNECT) {
        if (testHome == null) {
            testHome = TestHomeUtil.createTestHome(TEMP_DIR_PREFIX);
        }

        if (mode == Mode.EMBED) {
            hbaseProxy.setTestHome(new File(testHome, TemplateDir.HADOOP_DIR));
        }
        solrProxy.setTestHome(new File(testHome, TemplateDir.SOLR_DIR));
        lilyServerProxy.setTestHome(new File(testHome, TemplateDir.LILYSERVER_DIR));
    }

    if (mode == Mode.EMBED
            && Boolean.parseBoolean(System.getProperty(RESTORE_TEMPLATE_DIR_PROP_NAME, "true"))) {
        TemplateDir.restoreTemplateDir(testHome);
    }

    hbaseProxy.start();
    solrProxy.start(solrDef);
    lilyServerProxy.start();
    hbaseIndexerLauncherService.start(Collections.<String>emptyList());
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java

/**
 * Set the MBean attribute value via a remote JMX Connection and check whether the
 * returned value matches the set value/*  www. j  a v  a 2s .  c o m*/
 *
 * @throws Exception
 */
@Test
public void testSetGetMBeanRemote() throws Exception {
    JMXServiceURL jmxServiceUrl = jmxConnectorServer.getAddress();
    JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl);
    MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
    ObjectName name = new ObjectName(MMX_MBEAN_OBJECT_NAME);
    testSetGetAttribute(mbeanServerConnection, name);
}

From source file:org.apache.hadoop.hbase.TestStochasticBalancerJmxMetrics.java

/**
 * Read the attributes from Hadoop->HBase->Master->Balancer in JMX
 * @throws IOException //  w  ww  .j  a  v a 2  s .  c o  m
 */
private Set<String> readJmxMetrics() throws IOException {
    JMXConnector connector = null;
    ObjectName target = null;
    MBeanServerConnection mb = null;
    try {
        connector = JMXConnectorFactory.connect(JMXListener.buildJMXServiceURL(connectorPort, connectorPort));
        mb = connector.getMBeanServerConnection();

        Hashtable<String, String> pairs = new Hashtable<>();
        pairs.put("service", "HBase");
        pairs.put("name", "Master");
        pairs.put("sub", "Balancer");
        target = new ObjectName("Hadoop", pairs);
        MBeanInfo beanInfo = mb.getMBeanInfo(target);

        Set<String> existingAttrs = new HashSet<String>();
        for (MBeanAttributeInfo attrInfo : beanInfo.getAttributes()) {
            existingAttrs.add(attrInfo.getName());
        }
        return existingAttrs;
    } catch (Exception e) {
        LOG.warn("Failed to get bean!!! " + target, e);
        if (mb != null) {
            Set<ObjectInstance> instances = mb.queryMBeans(null, null);
            Iterator<ObjectInstance> iterator = instances.iterator();
            System.out.println("MBean Found:");
            while (iterator.hasNext()) {
                ObjectInstance instance = iterator.next();
                System.out.println("Class Name: " + instance.getClassName());
                System.out.println("Object Name: " + instance.getObjectName());
            }
        }
    } finally {
        if (connector != null) {
            try {
                connector.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:org.apache.geode.internal.process.MBeanProcessController.java

/**
 * Connects to the JMX agent in the local process.
 * /*from  w  w w.  ja v a 2 s . c o  m*/
 * @throws ConnectionFailedException if there was a failure to connect to the local JMX connector
 *         in the process
 * @throws IOException if the JDK management agent cannot be found and loaded
 */
private void connect() throws ConnectionFailedException, IOException {
    try {
        JMXServiceURL jmxUrl = getJMXServiceURL();
        jmxc = JMXConnectorFactory.connect(jmxUrl);
        server = jmxc.getMBeanServerConnection();
    } catch (AttachNotSupportedException e) {
        throw new ConnectionFailedException("Failed to connect to process '" + pid + "'", e);
    }
}

From source file:com.hellblazer.process.impl.JavaProcessImpl.java

/**
 * @throws ConnectException//from   w  ww .jav  a 2s  . co  m
 */
@Override
public JMXConnector getLocalJmxConnector(String connectorName)
        throws ConnectException, NoLocalJmxConnectionException {
    if (jmxc != null) {
        return jmxc;
    }

    if (!process.isActive()) {
        throw new ConnectException("Cannot establish local JMX connection as process is not active: " + this);
    }

    String address;
    try {
        VirtualMachine vm = VirtualMachine.attach("" + process.getPid());
        Properties props = vm.getSystemProperties();
        address = props.getProperty(connectorName);

        if (address == null) {
            throw new ConnectException(
                    "Unable to find address for remote JMX connection with name = " + connectorName);
        }
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot obtain local JMX connector address of: " + this);
        cex.initCause(e);
        throw cex;
    } catch (AttachNotSupportedException e) {
        throw new RuntimeException(e);
    }

    JMXServiceURL jmxUrl;
    try {
        jmxUrl = new JMXServiceURL(address);
    } catch (MalformedURLException e) {
        ConnectException cex = new ConnectException("Invalid local JMX URL for " + this + " : " + address);
        cex.initCause(e);
        throw cex;
    }

    try {
        jmxc = JMXConnectorFactory.connect(jmxUrl);
    } catch (java.rmi.ConnectException e) {
        if (e.getMessage().startsWith("Connection refused")) {
            throw new NoLocalJmxConnectionException("Local JMX connector address does not exist for: " + this);
        }
        ConnectException cex = new ConnectException("Underlying RMI communications exception");
        cex.initCause(e);
        throw cex;
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
        cex.initCause(e);
        throw cex;
    }

    try {
        jmxc.connect();
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
        cex.initCause(e);
        throw cex;
    }

    return jmxc;
}

From source file:JTop.java

private static MBeanServerConnection connect(String hostname, int port) {
    // Create an RMI connector client and connect it to
    // the RMI connector server
    String urlPath = "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi";
    MBeanServerConnection server = null;
    try {/*  w  ww  .  ja  v a2 s .  c om*/
        JMXServiceURL url = new JMXServiceURL("rmi", "", 0, urlPath);
        JMXConnector jmxc = JMXConnectorFactory.connect(url);
        server = jmxc.getMBeanServerConnection();
    } catch (MalformedURLException e) {
        // should not reach here
    } catch (IOException e) {
        System.err.println("\nCommunication error: " + e.getMessage());
        System.exit(1);
    }
    return server;
}

From source file:org.opennms.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

/**
 * This method gets the JmxConnector to connect with the given jmxServiceURL.
 *
 * @param username may be null//from w  w  w.  jav  a2 s . c om
 * @param password may be null
 * @param jmxServiceURL should not be null!
 * @return a jmxConnector
 * @throws IOException if the connection to the given jmxServiceURL fails (e.g. authentication failure or not reachable)
 */
private JMXConnector getJmxConnector(String username, String password, JMXServiceURL jmxServiceURL)
        throws IOException {
    JMXConnector jmxConnector;
    if (username != null && password != null) {
        jmxConnector = JMXConnectorFactory.newJMXConnector(jmxServiceURL, null);
        HashMap<String, String[]> env = new HashMap<String, String[]>();
        String[] credentials = new String[] { username, password };
        env.put("jmx.remote.credentials", credentials);
        jmxConnector.connect(env);
    } else {
        jmxConnector = JMXConnectorFactory.connect(jmxServiceURL);
        jmxConnector.connect();
    }
    return jmxConnector;
}

From source file:org.rhq.plugins.jmx.JMXDiscoveryComponent.java

@Override
public ResourceUpgradeReport upgrade(ResourceUpgradeContext inventoriedResource) {
    JvmResourceKey oldKey = JvmResourceKey.valueOf(inventoriedResource.getResourceKey());
    JvmResourceKey.Type oldKeyType = oldKey.getType();
    if (oldKeyType == JvmResourceKey.Type.Legacy || oldKeyType == JvmResourceKey.Type.JmxRemotingPort) {
        if (!inventoriedResource.getSystemInformation().isNative()) {
            log.warn("Cannot attempt to upgrade Resource key [" + inventoriedResource.getResourceKey()
                    + "] of JVM Resource, because this Agent is not running with native system info support (i.e. SIGAR).");
            return null;
        }//from   www.j av  a2  s. c  om

        Configuration pluginConfig = inventoriedResource.getPluginConfiguration();
        String connectorAddress = pluginConfig.getSimpleValue(CONNECTOR_ADDRESS_CONFIG_PROPERTY, null);
        JMXServiceURL jmxServiceURL;
        try {
            jmxServiceURL = new JMXServiceURL(connectorAddress);
        } catch (MalformedURLException e) {
            throw new RuntimeException("Failed to parse connector address: " + connectorAddress, e);
        }

        Long pid;
        try {
            JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL);
            MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
            RuntimeMXBean runtimeMXBean = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConnection,
                    ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
            pid = getJvmPid(runtimeMXBean);
            if (pid == null) {
                throw new RuntimeException("Failed to determine JVM pid by parsing JVM name.");
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to determine JVM pid.", e);
        }

        List<ProcessInfo> processes = inventoriedResource.getSystemInformation()
                .getProcesses("process|pid|match=" + pid);
        if (processes.size() != 1) {
            throw new IllegalStateException("Failed to find process with PID [" + pid + "].");
        }
        ProcessInfo process = processes.get(0);
        String mainClassName = getJavaMainClassName(process);
        String explicitKeyValue = getSystemPropertyValue(process, SYSPROP_RHQ_RESOURCE_KEY);
        if (oldKeyType == JvmResourceKey.Type.Legacy || explicitKeyValue != null) {
            // We need to upgrade the key.
            JvmResourceKey newKey;
            if (explicitKeyValue != null) {
                newKey = JvmResourceKey.fromExplicitValue(mainClassName, explicitKeyValue);
            } else {
                newKey = JvmResourceKey.fromJmxRemotingPort(mainClassName, oldKey.getJmxRemotingPort());
            }

            ResourceUpgradeReport resourceUpgradeReport = new ResourceUpgradeReport();
            resourceUpgradeReport.setNewResourceKey(newKey.toString());
            return resourceUpgradeReport;
        }
    }

    return null;
}