Example usage for javax.management.remote JMXConnector getMBeanServerConnection

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

Introduction

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

Prototype

public MBeanServerConnection getMBeanServerConnection() throws IOException;

Source Link

Document

Returns an MBeanServerConnection object representing a remote MBean server.

Usage

From source file:com.linkedin.d2.balancer.util.LoadBalancerClientCli.java

public static void resetTogglingStores(String host, boolean enabled) throws Exception {

    MonitoredHost _host = MonitoredHost.getMonitoredHost(new HostIdentifier(host));

    for (Object pidObj : _host.activeVms()) {
        int pid = (Integer) pidObj;

        System.out.println("checking pid: " + pid);

        JMXServiceURL jmxUrl = null;
        com.sun.tools.attach.VirtualMachine vm = com.sun.tools.attach.VirtualMachine.attach(pid + "");

        try {//from  ww w. j a v a2 s .c om
            // get the connector address
            String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
            // establish connection to connector server
            if (connectorAddress != null) {
                jmxUrl = new JMXServiceURL(connectorAddress);
            }
        } finally {
            vm.detach();
        }

        if (jmxUrl != null) {
            System.out.println("got jmx url: " + jmxUrl);

            // connect to jmx
            JMXConnector connector = JMXConnectorFactory.connect(jmxUrl);

            connector.connect();

            MBeanServerConnection mbeanServer = connector.getMBeanServerConnection();

            // look for all beans in the d2 name space
            Set<ObjectInstance> objectInstances = mbeanServer.queryMBeans(new ObjectName("com.linkedin.d2:*"),
                    null);

            for (ObjectInstance objectInstance : objectInstances) {
                System.err.println("checking object: " + objectInstance.getObjectName());

                // if we've found a toggling store, then toggle it
                if (objectInstance.getObjectName().toString().endsWith("TogglingStore")) {
                    System.out.println("found toggling zk store, so toggling to: " + enabled);

                    mbeanServer.invoke(objectInstance.getObjectName(), "setEnabled", new Object[] { enabled },
                            new String[] { "boolean" });
                }
            }
        } else {
            System.out.println("pid is not a jmx process: " + pid);
        }
    }
}

From source file:io.galeb.router.tests.client.JmxClientService.java

@PostConstruct
public void start() {
    try {// w w w . j  a  va 2 s  .c om
        String jmxUrl = ConnectorAddressLink.importFrom(Info.getPid());
        if (jmxUrl != null) {
            final JMXServiceURL url = new JMXServiceURL(jmxUrl);
            final JMXConnector jmxConn = JMXConnectorFactory.connect(url);
            client = jmxConn.getMBeanServerConnection();
            enabled.set(true);
        }
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:com.googlecode.jmxtrans.connections.JmxConnectionFactory.java

/**
 * Validates that the connection is good.
 *///from   w w  w .  j  a va  2  s .  com
@Override
public boolean validateObject(JMXConnectionParams params, JMXConnector connector) {
    boolean result = false;
    try {
        connector.getConnectionId();
        connector.getMBeanServerConnection().getMBeanCount();
        result = true;
    } catch (IOException ex) {
        // ignored
    }
    return result;
}

From source file:net.nicoll.boot.daemon.SpringBootService.java

public void stop(String[] args) throws IOException {
    System.out.println("Stopping Spring Boot application...");
    int jmxPort = Integer.parseInt(args[0]);
    String jmxName = SpringApplicationAdminClient.DEFAULT_OBJECT_NAME;
    JMXConnector connector = SpringApplicationAdminClient.connect(jmxPort);
    try {/*from  w  ww  . ja  v a2 s  .  com*/
        MBeanServerConnection connection = connector.getMBeanServerConnection();
        try {
            new SpringApplicationAdminClient(connection, jmxName).stop();
        } catch (InstanceNotFoundException ex) {
            throw new IllegalStateException("Spring application lifecycle JMX bean not "
                    + "found, could not stop application gracefully", ex);
        }
    } finally {
        connector.close();
    }
}

From source file:org.pssframework.jmx.MBeanServerConnectionInterceptor.java

private void reconnect() throws IOException, MalformedURLException {
    JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(serviceUrl), null);
    this.connection = connector.getMBeanServerConnection();
}

From source file:org.pssframework.jmx.MBeanServerConnectionInterceptor.java

public Object getObject() throws Exception {
    JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(serviceUrl), null);
    this.connection = connector.getMBeanServerConnection();

    ProxyFactory connectionProxy = new ProxyFactory(this.connection);
    connectionProxy.addAdvice(this);
    return connectionProxy.getProxy();
}

From source file:io.fabric8.cxf.endpoint.jaxrs.RestJsonSchemaJMXTest.java

private void connectToMBserver() throws IOException {
    jmxServerURL = jmxServerURL == null ? DEFAULT_JMXSERVICE_URL : jmxServerURL;
    JMXServiceURL url = new JMXServiceURL(jmxServerURL);
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    mbsc = jmxc.getMBeanServerConnection();
}

From source file:com.espertech.esper.example.servershellclient.ServerShellClientMain.java

public ServerShellClientMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellClientMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }/*from ww w.jav  a 2  s .  co m*/
    properties.load(propertiesIS);

    // Attached via JMX to running server
    log.info("Attach to server via JMX");
    JMXServiceURL url = new JMXServiceURL(properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL));
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mBeanName = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMXMBean proxy = (EPServiceProviderJMXMBean) MBeanServerInvocationHandler
            .newProxyInstance(mbsc, mBeanName, EPServiceProviderJMXMBean.class, true);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    // Create statement via JMX
    log.info("Creating a statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.createEPL("select * from SampleEvent where duration > 9.9", "filterStatement",
            new ClientSideUpdateListener());

    // Get producer
    jmsCtx.getConnection().start();
    MessageProducer producer = jmsCtx.getSession().createProducer(jmsCtx.getDestination());

    Random random = new Random();
    String[] ipAddresses = { "127.0.1.0", "127.0.2.0", "127.0.3.0", "127.0.4.0" };
    NumberFormat format = NumberFormat.getInstance();

    // Send messages
    for (int i = 0; i < 1000; i++) {
        String ipAddress = ipAddresses[random.nextInt(ipAddresses.length)];
        double duration = 10 * random.nextDouble();
        String durationStr = format.format(duration);
        String payload = ipAddress + "," + durationStr;

        BytesMessage bytesMessage = jmsCtx.getSession().createBytesMessage();
        bytesMessage.writeBytes(payload.getBytes());
        bytesMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
        producer.send(bytesMessage);

        if (i % 100 == 0) {
            log.info("Sent " + i + " messages");
        }
    }

    // Create statement via JMX
    log.info("Destroing statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.destroy("filterStatement");

    log.info("Shutting down JMS client connection");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}

From source file:eu.itesla_project.online.tools.RunTDSimulationsMpiTool.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  w  w.  j  a v a 2s  .c  om
    if (port != null)
        startconfig.setJmxPort(Integer.valueOf(port));
    if (threads != null)
        startconfig.setThreads(Integer.valueOf(threads));

    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);

    boolean emptyContingency = line.hasOption("empty-contingency");
    Path caseFile = Paths.get(line.getOptionValue("case-file"));
    application.runTDSimulations(startconfig, caseFile.toString(), line.getOptionValue("contingencies"),
            Boolean.toString(emptyContingency), line.getOptionValue("output-folder"));
}

From source file:com.adaptris.core.services.jmx.JmxOperationInvoker.java

public Object invoke(String serviceUrl, String objectName, String username, String password, String methodName,
        Object[] params, String[] signatures) throws Exception {
    Map<String, String[]> env = new HashMap<>();
    if ((!StringUtils.isEmpty(username)) && (!StringUtils.isEmpty(password))) {
        String[] credentials = { username, Password.decode(password) };
        env.put(JMXConnector.CREDENTIALS, credentials);
    }//from   www .j  av  a  2  s .c o m
    JMXServiceURL jmxServiceUrl = new JMXServiceURL(serviceUrl);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl, env);
    ObjectName objectNameInst = ObjectName.getInstance(objectName);
    MBeanServerConnection mbeanConn = jmxConnector.getMBeanServerConnection();
    try {
        return mbeanConn.invoke(objectNameInst, methodName, params, signatures);
    } finally {
        jmxConnector.close();

    }
}