Example usage for javax.management.remote JMXConnector close

List of usage examples for javax.management.remote JMXConnector close

Introduction

In this page you can find the example usage for javax.management.remote JMXConnector close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes the client connection to its server.

Usage

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

/**
 * This tests to validate the RegionServer's ConnectorServer after unauthorised stopRegionServer
 * call./*  w ww.j  a v  a 2s.c  om*/
 */
@Test(timeout = 180000)
public void testRSConnectorServerWhenStopRegionServer() throws Exception {
    conf.set(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY,
            JMXListener.class.getName() + "," + MyAccessController.class.getName());
    conf.setInt("regionserver.rmi.registry.port", rmiRegistryPort);
    UTIL.startMiniCluster();
    admin = UTIL.getConnection().getAdmin();

    hasAccess = false;
    ServerName serverName = UTIL.getHBaseCluster().getRegionServer(0).getServerName();
    LOG.info("Stopping Region Server...");
    admin.stopRegionServer(serverName.getHostname() + ":" + serverName.getPort());

    // Check whether Region Sever 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 Region Server ConnectorServer.");
        }
    }
    Assert.assertNotNull("JMXConnector should not be null.", connector);
    connector.close();
}

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

/**
 * This tests to validate the HMaster's ConnectorServer after unauthorised stopMaster call.
 *///  w w w .j  a  v a 2s . c o  m
@Test(timeout = 180000)
public void testHMConnectorServerWhenStopMaster() 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();

    // try to stop master
    boolean accessDenied = false;
    try {
        hasAccess = false;
        LOG.info("Stopping HMaster...");
        admin.stopMaster();
    } catch (AccessDeniedException e) {
        LOG.info("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.apache.hadoop.hbase.TestJMXConnectorServer.java

/**
 * This tests to validate the HMaster's ConnectorServer after unauthorised shutdown call.
 *///from  w  ww  .  j a v  a  2s .  c o m
@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.wso2.carbon.integration.test.metrics.CarbonMetricsTestCase.java

/**
 * This method will force metric manager to collect metrics by invoking report() method
 * using remote jmx//from  ww w .  j a v  a 2s.com
 * @throws IOException
 * @throws MalformedObjectNameException
 */
private void invokeJMXReportOperation()
        throws IOException, MalformedObjectNameException, XPathExpressionException {
    int JMXServicePort = Integer.parseInt(cepServer.getInstance().getPorts().get("jmxserver"));
    int RMIRegistryPort = Integer.parseInt(cepServer.getInstance().getPorts().get("rmiregistry"));
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + JMXServicePort
            + "/jndi/rmi://localhost:" + RMIRegistryPort + "/jmxrmi");
    Map<String, String[]> env = new HashMap<>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(url, env);
    MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
    ObjectName mbeanName = new ObjectName("org.wso2.carbon:type=MetricManager");
    MetricManagerMXBean mbeanProxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServerConnection,
            mbeanName, MetricManagerMXBean.class, true);
    mbeanProxy.report();
    jmxConnector.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  w w .j a v a  2 s.  co  m*/
        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.citrix.g2w.webdriver.util.InvokeMBean.java

/**
 * Method to invoke m bean./*w  w w  .  java2  s  .  c om*/
 * 
 * @param userName
 *            (user name)
 * @param password
 *            (password)
 * @param rmiHost
 *            (rmi host)
 * @param rmiPort
 *            (rmi port)
 * @param objectName
 *            (object name)
 * @param methodName
 *            (method name)
 * @param params
 *            (array of objects)
 * @param signature
 *            (array of params type)
 * @return mBeanResult 
 *            (list of string containing mbean result)
 */
public List<String> invokeMBean(final String userName, final String password, final String rmiHost,
        final int rmiPort, final String objectName, final String methodName, final Object[] params,
        final String[] signature) {
    List<String> mBeanResult = new ArrayList<String>(2);
    try {
        String[] credentials = { userName, password };

        Map<String, String[]> env = new HashMap<String, String[]>();
        env.put("jmx.remote.credentials", credentials);

        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + rmiHost + ":" + rmiPort + "/jndi/rmi://"
                + rmiHost + ":" + rmiPort + "/jmxrmi");

        JMXConnector connector = JMXConnectorFactory.connect(url, env);

        MBeanServerConnection connection = connector.getMBeanServerConnection();
        ObjectName destConfigName = new ObjectName(objectName);

        Object returnValue = connection.invoke(destConfigName, methodName, params, signature);

        if (returnValue != null) {
            if (returnValue instanceof Collection) {
                Collection c = (Collection) returnValue;
                if (CollectionUtils.isNotEmpty(c)) {
                    for (Object val : c) {
                        mBeanResult.add(val.toString());
                    }
                }
            } else {
                mBeanResult.add(returnValue.toString());
            }
        }
        connector.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return mBeanResult;
}

From source file:org.hyperic.hq.plugin.activemq.EmbeddedActiveMQServerDetector.java

@Override
public List getServerResources(ConfigResponse platformConfig) throws PluginException {
    log.debug("[getServerResources] platformConfig=" + platformConfig);
    List<ServerResource> servers = super.getServerResources(platformConfig);
    List<ServerResource> serversOK = new ArrayList();

    for (ServerResource server : servers) {
        JMXConnector connector = null;
        MBeanServerConnection mServer;
        try {//w w  w  .j  a v  a  2s  .c  o  m
            connector = MxUtil.getMBeanConnector(server.getProductConfig().toProperties());
            mServer = connector.getMBeanServerConnection();
            Set<ObjectName> objs = mServer.queryNames(new ObjectName("org.apache.activemq:*"), null);
            log.debug("[getServerResources] objs.size=" + objs.size());
            if (objs.size() > 0) { // Only discover servers with jmx obects on activeMQ domain.
                serversOK.add(server);
            }
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        } finally {
            try {
                if (connector != null) {
                    connector.close();
                }
            } catch (IOException e) {
                throw new PluginException(e.getMessage(), e);
            }
        }

    }
    return serversOK;
}

From source file:com.dsf.dbxtract.cdc.AppJournalWindowTest.java

@Test(dependsOnMethods = { "testAppWithJournalWindow" })
public void testInfoStatistics() throws Exception {

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:5000/jmxrmi");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    ObjectName mbeanName = new ObjectName("com.dsf.dbxtract:type=InfoMBean");

    TabularDataSupport info = (TabularDataSupport) mbsc.getAttribute(mbeanName, InfoMBean.ATTR_INFO);
    Collection<?> list = info.values();
    boolean hasHandlerEntry = false;
    for (Iterator<?> it = list.iterator(); it.hasNext();) {
        CompositeDataSupport entry = (CompositeDataSupport) it.next();

        if (entry.get("handler").equals(TestWindowHandler.class.getName())) {
            assert (((Long) entry.get("readCount")).longValue() == TEST_SIZE);
            hasHandlerEntry = true;/*from  ww w  .  java2s. c om*/
        }
    }
    assert (hasHandlerEntry);
    jmxc.close();
}

From source file:com.mustardgrain.solr.SolrClient.java

private static Runnable getStatsRunner(final WeakReference<SolrClient> lbRef) {
    return new Runnable() {

        @Override// w  ww .ja v  a  2s  . c o  m
        public void run() {
            SolrClient lb = lbRef.get();
            if (lb != null && lb.serverStats != null && LOG.isInfoEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("server responses over past ");
                sb.append(TimeUnit.MILLISECONDS.toMinutes(lb.statsInterval));
                sb.append(" mins (good/timeout/zero found) and cache hit ratio: ");
                boolean appendComma = false;

                for (Map.Entry<String, SolrStats> entry : lb.serverStats.entrySet()) {
                    if (appendComma)
                        sb.append(", ");

                    String server = entry.getKey();
                    SolrStats stats = entry.getValue();
                    String hitRatio = getHitRatio(server);

                    sb.append(server);
                    sb.append(": ");
                    sb.append(stats.getSuccesses());
                    sb.append("/");
                    sb.append(stats.getReadTimeouts());
                    sb.append("/");
                    sb.append(stats.getEmptyResults());
                    sb.append(" ");
                    sb.append(hitRatio);

                    appendComma = true;

                    stats.reset(); // Reset the counters once printed
                }

                LOG.info(sb);
            }
        }

        /**
         * Determines the hit ratio for the query result cache by calling
         * the SolrServer via JMX and reading its MBean containing that
         * information.
         * @param server Server from which to pull information
         * @return String form of hit ratio (either "n/a" or "xx%")
         */

        private String getHitRatio(String server) {
            String hitRatio = "n/a";
            JMXConnector jmxc = null;

            try {
                URL url = new URL(server);
                String domain = url.getPath();

                if (domain.startsWith("/"))
                    domain = domain.substring(1);

                ObjectName name = new ObjectName(
                        domain + ":id=org.apache.solr.search.LRUCache,type=queryResultCache");
                JMXServiceURL jmxUrl = new JMXServiceURL(
                        "service:jmx:rmi:///jndi/rmi://" + url.getHost() + ":7199/jmxrmi");
                jmxc = JMXConnectorFactory.connect(jmxUrl, null);
                MBeanServerConnection con = jmxc.getMBeanServerConnection();

                Object result = con.getAttribute(name, "hitratio");
                hitRatio = (int) (Float.parseFloat(String.valueOf(result)) * 100.0f) + "%";
            } catch (Exception e) {
                LOG.error(getNestedErrorMessages(e));
            } finally {
                if (jmxc != null) {
                    try {
                        jmxc.close();
                    } catch (Exception e) {
                        LOG.error(getNestedErrorMessages(e));
                    }
                }
            }

            return hitRatio;
        }

    };
}

From source file:org.hyperic.hq.plugin.weblogic.jmx.WeblogicRuntimeDiscoverer.java

private RuntimeResourceReport discover(int serverId, AIPlatformValue aiplatform, ConfigResponse config)
        throws PluginException {

    String installpath = config.getValue(ProductPlugin.PROP_INSTALLPATH);
    // incase jaas is disabled; generatePlatform may use this.
    this.aiplatform = aiplatform;

    log.debug("discover using: " + config);

    String domainName = config.getValue(WeblogicMetric.PROP_DOMAIN);
    String serverName = config.getValue(WeblogicMetric.PROP_SERVER);

    RuntimeResourceReport rrr = new RuntimeResourceReport(serverId);

    Properties props = config.toProperties();

    WeblogicDiscover discover = new WeblogicDiscover(this.version, props);

    try {//from   www.  j a  v a 2s . c  o  m
        MBeanServer mServer = discover.getMBeanServer();

        discover.init(mServer);

        NodeManagerQuery nodemgrQuery = new NodeManagerQuery();
        ServerQuery serverQuery = new ServerQuery();
        serverQuery.setDiscover(discover);

        ArrayList servers = new ArrayList();

        discover.find(mServer, serverQuery, servers);

        WeblogicQuery[] serviceQueries = discover.getServiceQueries();

        // ensure admin is first incase we need version
        serverQuery.sort(servers);

        String adminVersion = null;

        for (int i = 0; i < servers.size(); i++) {
            serverQuery = (ServerQuery) servers.get(i);
            if (!serverQuery.isRunning())
                continue;

            if (serverQuery.isAdmin()) {
                adminVersion = serverQuery.getVersion();
            } else if (serverQuery.getVersion() == null) {
                // will be the case if a server was create but never started
                // safely assume it was created by the admin server in this
                // case and hence is the same version.
                serverQuery.setVersion(adminVersion);
            }

            AIPlatformValue aPlatform;
            AIServerExtValue aServer = generateServer(serverQuery);

            // Set the ID, so when this report is processed at the server,
            // there is no mistaking this server in the report for any other
            // server
            // in appdef (or worse, not matching anything and adding a new
            // server).
            if (serverQuery.getName().equals(serverName)
                    && serverQuery.getDiscover().getDomain().equals(domainName)) {
                aServer.setId(new Integer(serverId));
                aServer.setPlaceholder(true);
                // maintain existing installpath,
                // MBeanServer CurrentDirectory might be different
                if (installpath != null) {
                    aServer.setInstallPath(installpath);
                }
                aiplatform.addAIServerValue(aServer);
                rrr.addAIPlatform(aiplatform);
            } else {
                aPlatform = generatePlatform(serverQuery);
                aPlatform.addAIServerValue(aServer);
                rrr.addAIPlatform(aPlatform);
            }

            if (!serverQuery.isRunning()) {
                continue;
            }

            mServer = discover.getMBeanServer(serverQuery.getUrl());

            ArrayList aServices = new ArrayList();
            ArrayList services = new ArrayList();

            for (int j = 0; j < serviceQueries.length; j++) {
                WeblogicQuery serviceQuery = serviceQueries[j];

                serviceQuery.setParent(serverQuery);
                serviceQuery.setVersion(serverQuery.getVersion());

                discover.find(mServer, serviceQuery, services);
            }

            // Dynamic services can only be discovered on WebLogic 9.1 or
            // higher
            if (DYNAMIC_SVC_SUPPORTED_WEBLOGIC_VERSION
                    .compareTo(Double.valueOf(serverQuery.getVersion())) <= 0) {
                final JMXConnector jmxConnector = WeblogicUtil.getManagedServerConnection(props);
                Set serviceTypes = new HashSet();
                try {
                    discoverDynamicServices(discover, jmxConnector.getMBeanServerConnection(), serverQuery,
                            services, serviceTypes);
                } catch (IOException e) {
                    throw new PluginException("Error discovering dynamic services", e);
                } finally {
                    try {
                        jmxConnector.close();
                    } catch (IOException e) {
                    }
                }
                final AIServiceTypeValue[] serviceTypeValues = new AIServiceTypeValue[serviceTypes.size()];
                int count = 0;
                for (Iterator iterator = serviceTypes.iterator(); iterator.hasNext();) {
                    serviceTypeValues[count] = ((ServiceType) iterator.next()).getAIServiceTypeValue();
                    count++;
                }
                aServer.setAiServiceTypes(serviceTypeValues);
                pluginUpdater.updateServiceTypes(plugin.getProductPlugin(), serviceTypes);
            }

            for (int k = 0; k < services.size(); k++) {
                boolean valid = true;
                ServiceQuery service = (ServiceQuery) services.get(k);
                if (service instanceof ApplicationQuery) {
                    valid = ((ApplicationQuery) service).isEAR();
                }
                if (valid) {
                    aServices.add(generateService(service));

                } else {
                    log.debug("skipped service:" + service.getName());
                }
            }

            AIServiceValue[] aiservices = (AIServiceValue[]) aServices.toArray(new AIServiceValue[0]);
            aServer.setAIServiceValues(aiservices);

            if (serverQuery.isAdmin()) {
                ArrayList mgrs = new ArrayList();
                nodemgrQuery.setAdminServer(serverQuery);
                discover.find(mServer, nodemgrQuery, mgrs);

                for (int n = 0; n < mgrs.size(); n++) {
                    nodemgrQuery = (NodeManagerQuery) mgrs.get(n);
                    aServer = generateServer(nodemgrQuery);
                    aPlatform = generatePlatform(nodemgrQuery);
                    aPlatform.addAIServerValue(aServer);
                    rrr.addAIPlatform(aPlatform);
                }
            }
        }
    } catch (WeblogicDiscoverException e) {
        throw new PluginException(e.getMessage(), e);
    }

    return rrr;
}