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:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doShutdown(String[] vals) throws Exception {
    StringBuilder buf = new StringBuilder("service:jmx:rmi://localhost/jndi/rmi://localhost:");
    String serviceName = vals[0];

    buf.append(vals[1]).append("/").append(serviceName);
    String serviceUrl = buf.toString();

    JMXServiceURL url = new JMXServiceURL(serviceUrl);
    JMXConnector jmxc = null;//from  www  .ja  v  a 2s  .c o  m
    try {
        jmxc = JMXConnectorFactory.connect(url, null);

    } catch (Exception e) {
        throw new Exception("Unable to establish JMX connection at " + serviceUrl);
    }

    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    Set<ObjectInstance> mBeansSet = mbsc.queryMBeans(new ObjectName(serviceName + ":*"), null);
    List<IServiceController> serviceProxies = new ArrayList<IServiceController>();
    Class serviceBusInterface = Class.forName(IServiceBusManager.class.getName());
    Class serviceControllerInterface = Class.forName(IServiceController.class.getName());

    for (ObjectInstance mBeanObject : mBeansSet) {
        ObjectName mbeanName = mBeanObject.getObjectName();
        Class mbeanClass = Class.forName(mBeanObject.getClassName());
        if (serviceBusInterface.isAssignableFrom(mbeanClass)) {
            IServiceBusManager requestConnector = JMX.newMBeanProxy(mbsc, mbeanName, IServiceBusManager.class,
                    true);
            System.out.print(mbeanName + " terminating....");
            requestConnector.disconnect();
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ie) {

                }

                if (!requestConnector.isConnected()) {
                    break;
                }
            }
            System.out.println(" Done");
        } else if (serviceControllerInterface.isAssignableFrom(mbeanClass)) {
            // save off the service proxies to make sure we disconnect
            // all connectors before shutting down the service itself
            IServiceController mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, IServiceController.class, true);
            serviceProxies.add(mbeanProxy);
        }
    }

    for (IServiceController mbeanProxy : serviceProxies) {
        try {
            mbeanProxy.shutdown();
        } catch (UndeclaredThrowableException ex) {
        }
    }

    System.out.println("Service terminated");
}

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

/**
 * Create a connection to the JMX agent and setup the M[X]Bean proxies.
 *
 * @throws IOException on connection failures
 *//* ww  w  . j a  va2 s. c o  m*/
private void connect() throws IOException {
    JMXServiceURL jmxUrl = new JMXServiceURL(String.format(fmtUrl, host, port));
    Map<String, Object> env = new HashMap<String, Object>();
    if (username != null) {
        String[] creds = { username, password };
        env.put(JMXConnector.CREDENTIALS, creds);
    }

    env.put("com.sun.jndi.rmi.factory.socket", getRMIClientSocketFactory());

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

    try {
        ObjectName name = new ObjectName(ssObjName);
        ssProxy = JMX.newMBeanProxy(mbeanServerConn, name, StorageServiceMBean.class);
        name = new ObjectName(MessagingService.MBEAN_NAME);
        msProxy = JMX.newMBeanProxy(mbeanServerConn, name, MessagingServiceMBean.class);
        name = new ObjectName(StreamManagerMBean.OBJECT_NAME);
        streamProxy = JMX.newMBeanProxy(mbeanServerConn, name, StreamManagerMBean.class);
        name = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME);
        compactionProxy = JMX.newMBeanProxy(mbeanServerConn, name, CompactionManagerMBean.class);
        name = new ObjectName(FailureDetector.MBEAN_NAME);
        fdProxy = JMX.newMBeanProxy(mbeanServerConn, name, FailureDetectorMBean.class);
        name = new ObjectName(CacheService.MBEAN_NAME);
        cacheService = JMX.newMBeanProxy(mbeanServerConn, name, CacheServiceMBean.class);
        name = new ObjectName(StorageProxy.MBEAN_NAME);
        spProxy = JMX.newMBeanProxy(mbeanServerConn, name, StorageProxyMBean.class);
        name = new ObjectName(HintedHandOffManager.MBEAN_NAME);
        hhProxy = JMX.newMBeanProxy(mbeanServerConn, name, HintedHandOffManagerMBean.class);
        name = new ObjectName(GCInspector.MBEAN_NAME);
        gcProxy = JMX.newMBeanProxy(mbeanServerConn, name, GCInspectorMXBean.class);
    } catch (MalformedObjectNameException e) {
        throw new RuntimeException("Invalid ObjectName? Please report this as a bug.", e);
    }

    memProxy = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConn, ManagementFactory.MEMORY_MXBEAN_NAME,
            MemoryMXBean.class);
    runtimeProxy = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConn,
            ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
}

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

/**
 * Creates a connection to an MBean Server identified by
 * <code>remoteJMXServerHostName and remoteJMXServerPort</code>
 * /*from   w w  w  . ja  v  a  2  s. co  m*/
 * @param remoteJMXServerHostName
 *          - MBeanServer host name
 * @param remoteJMXServerPort
 *          - MBeanServer port
 * @return - none
 * 
 * @throws Exception
 */
private static void initialize(String jmxDomain, String remoteJMXServerHostname, String remoteJMXServerPort)
        throws Exception {
    // Construct connect string to the JMX MBeanServer
    String remoteJmxUrl = "service:jmx:rmi:///jndi/rmi://" + remoteJMXServerHostname + ":" + remoteJMXServerPort
            + "/jmxrmi";

    try {
        JMXServiceURL url = new JMXServiceURL(remoteJmxUrl);
        jmxc = JMXConnectorFactory.connect(url, null);
        brokerMBeanServer = jmxc.getMBeanServerConnection();
        // Its possible that the above code succeeds even though the broker runs
        // with no JMX Connector. At least on windows the above does not throw an
        // exception as expected. It appears that the broker registers self JVMs MBeanServer
        // but it does *not* register any Connections, nor Queues. The code below 
        // checks if the MBean server we are connected to has any QueueMBeans registered.
        // A broker with jmx connector should have queue mbeans registered and thus
        //  the code below should always succeed. Conversely, a broker with no jmx connector
        // reports no queue mbeans.

        //  Query broker MBeanServer for QueueMBeans
        Set queueSet = brokerMBeanServer.queryNames(new ObjectName(jmxDomain + ":*,Type=Queue"),
                (QueryExp) null);
        if (queueSet.isEmpty()) { //  No QueueMBeans, meaning no JMX support
            throw new JmxException("ActiveMQ Broker Not Configured With JMX Support");
        }
    } catch (Exception e) {
        return;
    }
    // Query JMX Server for Broker MBean. We need the broker's name from an MBean to construct
    // queue query string.

    for (Object nameObject : brokerMBeanServer.queryNames(new ObjectName(jmxDomain + ":*,Type=Broker"),
            (QueryExp) null)) {
        ObjectName brokerObjectName = (ObjectName) nameObject;
        if (brokerObjectName.getCanonicalName().endsWith("Type=Broker")) {
            // Extract just the name from the canonical name
            brokerName = brokerObjectName.getCanonicalName().substring(0,
                    brokerObjectName.getCanonicalName().indexOf(","));
            initialized = true;
            break; // got the broker name
        }
    }
}

From source file:org.eclipse.virgo.server.svt.watchrepo.WatchedRepositoryTests.java

private static MBeanServerConnection getMBeanServerConnection() throws Exception {
    String severDir = null;/*from  w  w w.  j  a  va 2  s  . com*/
    String[] creds = { "admin", "springsource" };
    Map<String, String[]> env = new HashMap<String, String[]>();

    File testExpanded = new File("./../org.eclipse.virgo.server.svt/target/test-expanded/");
    for (File mainDir : testExpanded.listFiles()) {
        if (mainDir.isDirectory()) {
            severDir = new File(mainDir.toURI()).getCanonicalPath();
        }
    }
    env.put(JMXConnector.CREDENTIALS, creds);
    System.setProperty("javax.net.ssl.trustStore", severDir + KEYSTORE);
    System.setProperty("javax.net.ssl.trustStorePassword", KEYPASSWORD);
    JMXServiceURL url = new JMXServiceURL(JMXURL);
    connection = JMXConnectorFactory.connect(url, env).getMBeanServerConnection();
    return connection;
}

From source file:eu.itesla_project.online.tools.RunForecastErrorsAnalysisMpiTool.java

@Override
public void run(CommandLine line) throws Exception {

    OnlineWorkflowStartParameters startconfig = OnlineWorkflowStartParameters.loadDefault();

    String host = line.getOptionValue(OnlineWorkflowCommand.HOST);
    String port = line.getOptionValue(OnlineWorkflowCommand.PORT);
    String threads = line.getOptionValue(OnlineWorkflowCommand.THREADS);
    if (host != null)
        startconfig.setJmxHost(host);/*  w  ww .ja va 2s .  co m*/
    if (port != null)
        startconfig.setJmxPort(Integer.valueOf(port));
    if (threads != null)
        startconfig.setThreads(Integer.valueOf(threads));

    String analysisId = line.getOptionValue("analysis");
    DateTime baseCaseDate = line.hasOption("base-case-date")
            ? DateTime.parse(line.getOptionValue("base-case-date"))
            : getDefaultParameters().getBaseCaseDate();
    Interval histoInterval = line.hasOption("history-interval")
            ? Interval.parse(line.getOptionValue("history-interval"))
            : getDefaultParameters().getHistoInterval();
    double ir = line.hasOption("ir") ? Double.parseDouble(line.getOptionValue("ir"))
            : getDefaultParameters().getIr();
    int flagPQ = line.hasOption("flagPQ") ? Integer.parseInt(line.getOptionValue("flagPQ"))
            : getDefaultParameters().getFlagPQ();
    int method = line.hasOption("method") ? Integer.parseInt(line.getOptionValue("method"))
            : getDefaultParameters().getMethod();
    Integer nClusters = line.hasOption("nClusters") ? Integer.parseInt(line.getOptionValue("nClusters"))
            : getDefaultParameters().getnClusters();
    double percentileHistorical = line.hasOption("percentileHistorical")
            ? Double.parseDouble(line.getOptionValue("percentileHistorical"))
            : getDefaultParameters().getPercentileHistorical();
    Integer modalityGaussian = line.hasOption("modalityGaussian")
            ? Integer.parseInt(line.getOptionValue("modalityGaussian"))
            : getDefaultParameters().getModalityGaussian();
    Integer outliers = line.hasOption("outliers") ? Integer.parseInt(line.getOptionValue("outliers"))
            : getDefaultParameters().getOutliers();
    Integer conditionalSampling = line.hasOption("conditionalSampling")
            ? Integer.parseInt(line.getOptionValue("conditionalSampling"))
            : getDefaultParameters().getConditionalSampling();
    Integer nSamples = line.hasOption("nSamples") ? Integer.parseInt(line.getOptionValue("nSamples"))
            : getDefaultParameters().getnSamples();
    Set<Country> countries = line.hasOption("countries")
            ? Arrays.stream(line.getOptionValue("countries").split(",")).map(Country::valueOf).collect(
                    Collectors.toSet())
            : getDefaultParameters().getCountries();
    CaseType caseType = line.hasOption("case-type") ? CaseType.valueOf(line.getOptionValue("case-type"))
            : getDefaultParameters().getCaseType();

    ForecastErrorsAnalysisParameters parameters = new ForecastErrorsAnalysisParameters(baseCaseDate,
            histoInterval, analysisId, ir, flagPQ, method, nClusters, percentileHistorical, modalityGaussian,
            outliers, conditionalSampling, nSamples, countries, caseType);

    String urlString = "service:jmx:rmi:///jndi/rmi://" + startconfig.getJmxHost() + ":"
            + startconfig.getJmxPort() + "/jmxrmi";

    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    Map<String, String> jmxEnv = new HashMap<>();
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, jmxEnv);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();

    ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME);
    LocalOnlineApplicationMBean application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name,
            LocalOnlineApplicationMBean.class, false);
    String timeHorizonS = "";
    if (line.hasOption("time-horizon")) {
        timeHorizonS = line.getOptionValue("time-horizon");
    }
    application.runFeaAnalysis(startconfig, parameters, timeHorizonS);

}

From source file:eu.itesla_project.online.tools.OnlineWorkflowTool.java

@Override
public void run(CommandLine line) throws Exception {

    OnlineWorkflowStartParameters startconfig = OnlineWorkflowStartParameters.loadDefault();

    String host = line.getOptionValue(OnlineWorkflowCommand.HOST);
    String port = line.getOptionValue(OnlineWorkflowCommand.PORT);
    String threads = line.getOptionValue(OnlineWorkflowCommand.THREADS);
    if (host != null)
        startconfig.setJmxHost(host);//from w ww  . j  av  a 2s  . c o  m
    if (port != null)
        startconfig.setJmxPort(Integer.valueOf(port));
    if (threads != null)
        startconfig.setThreads(Integer.valueOf(threads));

    Set<DateTime> baseCasesSet = null;

    OnlineWorkflowParameters params = OnlineWorkflowParameters.loadDefault();
    boolean atLeastOneBaseCaseLineParam = line.hasOption(OnlineWorkflowCommand.CASE_TYPE)
            || line.hasOption(OnlineWorkflowCommand.COUNTRIES)
            || line.hasOption(OnlineWorkflowCommand.BASE_CASE)
            || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL);
    boolean allNeededBaseCaseLineParams = line.hasOption(OnlineWorkflowCommand.CASE_TYPE)
            && line.hasOption(OnlineWorkflowCommand.COUNTRIES)
            && (line.hasOption(OnlineWorkflowCommand.BASE_CASE)
                    || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL));

    if (line.hasOption(OnlineWorkflowCommand.CASE_FILE)) {
        if (atLeastOneBaseCaseLineParam) {
            showHelp("parameter " + OnlineWorkflowCommand.CASE_FILE
                    + " cannot be used together with parameters: " + OnlineWorkflowCommand.CASE_TYPE + ", "
                    + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE + ", "
                    + OnlineWorkflowCommand.BASECASES_INTERVAL);
            return;
        }
        params.setCaseFile(line.getOptionValue(OnlineWorkflowCommand.CASE_FILE));
    } else {
        if (params.getCaseFile() != null) {
            if (atLeastOneBaseCaseLineParam) {
                if (!allNeededBaseCaseLineParams) {
                    showHelp("to override default parameter " + OnlineWorkflowCommand.CASE_FILE
                            + ", all these parameters must be specified: " + OnlineWorkflowCommand.CASE_TYPE
                            + ", " + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE
                            + " or " + OnlineWorkflowCommand.BASECASES_INTERVAL);
                    return;
                }
                params.setCaseFile(null);
            }
        }
        if (line.hasOption(OnlineWorkflowCommand.CASE_TYPE))
            params.setCaseType(CaseType.valueOf(line.getOptionValue(OnlineWorkflowCommand.CASE_TYPE)));
        if (line.hasOption(OnlineWorkflowCommand.COUNTRIES)) {
            params.setCountries(Arrays.stream(line.getOptionValue(OnlineWorkflowCommand.COUNTRIES).split(","))
                    .map(Country::valueOf).collect(Collectors.toSet()));
        }
        if (line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL)) {
            Interval basecasesInterval = Interval
                    .parse(line.getOptionValue(OnlineWorkflowCommand.BASECASES_INTERVAL));
            OnlineConfig oConfig = OnlineConfig.load();
            CaseRepository caseRepo = oConfig.getCaseRepositoryFactoryClass().newInstance()
                    .create(new LocalComputationManager());
            baseCasesSet = caseRepo.dataAvailable(params.getCaseType(), params.getCountries(),
                    basecasesInterval);
            System.out.println("Base cases available for interval " + basecasesInterval.toString());
            baseCasesSet.forEach(x -> {
                System.out.println(" " + x);
            });
        }
        if (baseCasesSet == null) {
            baseCasesSet = new HashSet<>();
            String base = line.getOptionValue(OnlineWorkflowCommand.BASE_CASE);
            if (base != null) {
                baseCasesSet.add(DateTime.parse(base));
            } else {
                baseCasesSet.add(params.getBaseCaseDate());
            }
        }
    }

    String histo = line.getOptionValue(OnlineWorkflowCommand.HISTODB_INTERVAL);
    if (histo != null)
        params.setHistoInterval(Interval.parse(histo));

    String states = line.getOptionValue(OnlineWorkflowCommand.STATES);
    if (states != null)
        params.setStates(Integer.parseInt(states));

    String timeHorizon = line.getOptionValue(OnlineWorkflowCommand.TIME_HORIZON);
    if (timeHorizon != null)
        params.setTimeHorizon(TimeHorizon.fromName(timeHorizon));

    String workflowid = line.getOptionValue(OnlineWorkflowCommand.WORKFLOW_ID);
    if (workflowid != null)
        params.setOfflineWorkflowId(workflowid);

    String feAnalysisId = line.getOptionValue(OnlineWorkflowCommand.FEANALYSIS_ID);
    if (feAnalysisId != null)
        params.setFeAnalysisId(feAnalysisId);

    String rulesPurity = line.getOptionValue(OnlineWorkflowCommand.RULES_PURITY);
    if (rulesPurity != null)
        params.setRulesPurityThreshold(Double.parseDouble(rulesPurity));

    if (line.hasOption(OnlineWorkflowCommand.STORE_STATES))
        params.setStoreStates(true);

    if (line.hasOption(OnlineWorkflowCommand.ANALYSE_BASECASE))
        params.setAnalyseBasecase(true);

    if (line.hasOption(OnlineWorkflowCommand.VALIDATION)) {
        params.setValidation(true);
        params.setStoreStates(true); // if validation then store states
        params.setAnalyseBasecase(true); // if validation then analyze base case
    }

    Set<SecurityIndexType> securityIndexes = null;
    if (line.hasOption(OnlineWorkflowCommand.SECURITY_INDEXES)) {
        if (!"ALL".equals(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES)))
            securityIndexes = Arrays
                    .stream(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES).split(","))
                    .map(SecurityIndexType::valueOf).collect(Collectors.toSet());
        params.setSecurityIndexes(securityIndexes);
    }

    if (line.hasOption(OnlineWorkflowCommand.MERGE_OPTIMIZED))
        params.setMergeOptimized(true);

    String limitReduction = line.getOptionValue(OnlineWorkflowCommand.LIMIT_REDUCTION);
    if (limitReduction != null)
        params.setLimitReduction(Float.parseFloat(limitReduction));

    if (line.hasOption(OnlineWorkflowCommand.HANDLE_VIOLATION_IN_N)) {
        params.setHandleViolationsInN(true);
        params.setAnalyseBasecase(true); // if I need to handle violations in N, I need to analyze base case
    }

    String constraintMargin = line.getOptionValue(OnlineWorkflowCommand.CONSTRAINT_MARGIN);
    if (constraintMargin != null)
        params.setConstraintMargin(Float.parseFloat(constraintMargin));

    String urlString = "service:jmx:rmi:///jndi/rmi://" + startconfig.getJmxHost() + ":"
            + startconfig.getJmxPort() + "/jmxrmi";

    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    Map<String, String> jmxEnv = new HashMap<>();
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, jmxEnv);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();

    ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME);
    LocalOnlineApplicationMBean application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name,
            LocalOnlineApplicationMBean.class, false);

    if (line.hasOption(OnlineWorkflowCommand.START_CMD)) {
        if (params.getCaseFile() != null) {
            System.out.println("starting Online Workflow, caseFile " + params.getCaseFile());
            String workflowId = application.startWorkflow(startconfig, params);
            System.out.println("workflowId=" + workflowId);

        } else {
            for (DateTime basecase : baseCasesSet) {
                params.setBaseCaseDate(basecase);
                System.out.println("starting Online Workflow, basecase " + basecase.toString());
                String workflowId = application.startWorkflow(startconfig, params);
                System.out.println("workflowId=" + workflowId);
            }
        }
    } else if (line.hasOption(OnlineWorkflowCommand.SHUTDOWN_CMD)) {
        application.shutdown();
    } else {
        showHelp("");
    }

}

From source file:org.jumpmind.symmetric.JmxCommand.java

protected <T> T execute(IJmxTemplate<T> template) throws Exception {
    String host = "localhost";
    String url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + System.getProperty("jmx.agent.port", "31418")
            + "/jmxrmi";
    JMXServiceURL serviceUrl = new JMXServiceURL(url);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceUrl, null);
    TypedProperties properties = getTypedProperties();
    String engineName = properties.get(ParameterConstants.ENGINE_NAME, "unknown");
    try {/*from  w w  w  .j  a  va2s .co  m*/
        MBeanServerConnection mbeanConn = jmxConnector.getMBeanServerConnection();
        return template.execute(engineName, mbeanConn);
    } finally {
        jmxConnector.close();
    }
}

From source file:org.apache.geode.tools.pulse.internal.data.JMXDataUpdater.java

/**
 * Get the jmx connection/* ww w  .j a v  a 2s .  com*/
 */
public JMXConnector connect(String username, String password) {
    // Reference to repository
    Repository repository = Repository.get();
    try {

        String jmxSerURL = "";

        logger.info("{}:{}", resourceBundle.getString("LOG_MSG_USE_LOCATOR_VALUE"),
                repository.getJmxUseLocator());

        if (repository.getJmxUseLocator()) {
            JmxManagerInfo jmxManagerInfo = getManagerInfoFromLocator(repository);

            if (jmxManagerInfo.port == 0) {
                logger.info(resourceBundle.getString("LOG_MSG_LOCATOR_COULD_NOT_FIND_MANAGER"));
            } else {
                logger.info("{}: {}={} & {}={}, {}", resourceBundle.getString("LOG_MSG_LOCATOR_FOUND_MANAGER"),
                        resourceBundle.getString("LOG_MSG_HOST"), jmxManagerInfo.host,
                        resourceBundle.getString("LOG_MSG_PORT"), jmxManagerInfo.port,
                        (jmxManagerInfo.ssl ? resourceBundle.getString("LOG_MSG_WITH_SSL")
                                : resourceBundle.getString("LOG_MSG_WITHOUT_SSL")));

                jmxSerURL = formJMXServiceURLString(jmxManagerInfo.host, String.valueOf(jmxManagerInfo.port));
            }
        } else {
            logger.info("{}={} & {}={}", resourceBundle.getString("LOG_MSG_HOST"), this.serverName,
                    resourceBundle.getString("LOG_MSG_PORT"), this.port);
            jmxSerURL = formJMXServiceURLString(this.serverName, this.port);
        }

        if (StringUtils.isNotBlank(jmxSerURL)) {
            JMXServiceURL url = new JMXServiceURL(jmxSerURL);
            String[] creds = { username, password };
            Map<String, Object> env = new HashMap<String, Object>();
            env.put(JMXConnector.CREDENTIALS, creds);

            if (repository.isUseSSLManager()) {
                // use ssl to connect
                env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
            }
            logger.info("Connecting to jmxURL : {}", jmxSerURL);
            this.conn = JMXConnectorFactory.connect(url, env);
            this.mbs = this.conn.getMBeanServerConnection();
            cluster.setConnectedFlag(true);
        }
    } catch (Exception e) {
        cluster.setConnectedFlag(false);
        cluster.setConnectionErrorMsg(e.getMessage());
        logger.fatal(e.getMessage(), e);
        if (this.conn != null) {
            try {
                this.conn.close();
            } catch (Exception e1) {
                logger.fatal(e1.getMessage(), e1);
            }
            this.conn = null;
        }
    }
    return this.conn;
}

From source file:org.jboss.wsf.test.JBossWSTestHelper.java

private static MBeanServerConnection getServerConnection(String jmxServiceUrl) {
    final String urlString = System.getProperty("jmx.service.url", jmxServiceUrl);
    JMXServiceURL serviceURL = null;
    JMXConnector connector = null;
    try {// w  ww. j  av  a 2 s  .  c  o  m
        serviceURL = new JMXServiceURL(urlString);
    } catch (MalformedURLException e1) {
        throw new IllegalStateException(e1);
    }
    //add more tries to get the connection. Workaround to fix some test failures caused by connection is not established in 5 seconds
    for (int i = 0; i < AS_SERVER_CONN_RETRIEVAL_ATTEMPTS && connector == null; i++) {
        try {
            connector = JMXConnectorFactory.connect(serviceURL, null);
        } catch (IOException ex) {
            throw new IllegalStateException("Cannot obtain MBeanServerConnection to: " + urlString, ex);
        } catch (RuntimeException e) {
            if (e.getMessage().contains("WAITING") && i < AS_SERVER_CONN_RETRIEVAL_ATTEMPTS - 1) {
                continue;
            } else {
                throw e;
            }
        }
    }

    try {
        return connector.getMBeanServerConnection();
    } catch (Exception e) {
        throw new IllegalStateException("Cannot obtain MBeanServerConnection to: " + urlString, e);
    }
}

From source file:org.rhq.cassandra.ClusterInitService.java

public boolean isNativeTransportRunning(String storageNode, int jmxPort) throws Exception {
    Boolean nativeTransportRunning = false;
    String url = getJMXConnectionURL(storageNode, jmxPort);
    JMXServiceURL serviceURL = new JMXServiceURL(url);
    Map<String, String> env = new HashMap<String, String>();
    JMXConnector connector = null;

    try {/*from   w  w  w  .j a va2 s . c  om*/
        connector = JMXConnectorFactory.connect(serviceURL, env);
        MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
        ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");
        String attribute = "NativeTransportRunning";
        try {
            nativeTransportRunning = (Boolean) serverConnection.getAttribute(storageService, attribute);
        } catch (Exception e) {
            // It is ok to just catch and log exceptions here particularly in an integration
            // test environment where we could potentially try to do the JMX query before
            // Cassandra is fully initialized. We can query StorageService before the native
            // transport server is initialized which will result in Cassandra throwing a NPE.
            // We do not want propagate that exception because it is just a matter of waiting
            // for Cassandra to finish initializing.
            if (log.isDebugEnabled()) {
                log.debug("Failed to read attribute [" + attribute + "] from " + storageService, e);
            } else {
                log.info("Faied to read attribute [" + attribute + "] from " + storageService + ": "
                        + e.getMessage());
            }
        }
    } finally {
        if (connector != null) {
            connector.close();
        }
    }
    return nativeTransportRunning;
}