Example usage for javax.management MBeanServerConnection invoke

List of usage examples for javax.management MBeanServerConnection invoke

Introduction

In this page you can find the example usage for javax.management MBeanServerConnection invoke.

Prototype

public Object invoke(ObjectName name, String operationName, Object params[], String signature[])
        throws InstanceNotFoundException, MBeanException, ReflectionException, IOException;

Source Link

Document

Invokes an operation on an MBean.

Because of the need for a signature to differentiate possibly-overloaded operations, it is much simpler to invoke operations through an JMX#newMBeanProxy(MBeanServerConnection,ObjectName,Class) MBean proxy where possible.

Usage

From source file:org.jboss.test.web.test.RootContextUnitTestCase.java

/**
 *  Access http://localhost//*from   www. j  a  va2 s.c o  m*/
 */
private String hitRootContext(String deploymentUnit) throws Exception {
    // We need to suspend the default root context when running these tests
    ObjectName root = new ObjectName("jboss.web.deployment:war=/ROOT");
    MBeanServerConnection connection = getServer();
    connection.invoke(root, "stop", null, null);
    try {
        deploy(deploymentUnit);
        try {
            HttpMethodBase request = new GetMethod(baseURL);
            client.executeMethod(request);

            String responseBody = request.getResponseBodyAsString();
            if (responseBody == null) {
                throw new Exception("Unable to get response from server.");
            }

            return responseBody;
        } finally {
            undeploy(deploymentUnit);
        }
    } finally {
        connection.invoke(root, "start", null, null);
    }
}

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);
    }/* ww w  .  j  a  v 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();

    }
}

From source file:org.rhq.plugins.jslee.ServiceDiscoveryComponent.java

public Set<DiscoveredResourceDetails> discoverResources(
        ResourceDiscoveryContext<JainSleeServerComponent> context)
        throws InvalidPluginConfigurationException, Exception {
    if (log.isTraceEnabled()) {
        log.trace("discoverResources(" + context + ") called.");
    }//  w  w w . j  a  va 2  s.  c  o  m
    Set<DiscoveredResourceDetails> discoveredServices = new HashSet<DiscoveredResourceDetails>();
    ObjectName servicemanagement = new ObjectName(ServiceManagementMBean.OBJECT_NAME);

    MBeanServerUtils mbeanUtils = context.getParentResourceComponent().getMBeanServerUtils();

    try {
        MBeanServerConnection connection = mbeanUtils.getConnection();
        mbeanUtils.login();

        ServiceID[] activeServices = (ServiceID[]) connection.invoke(servicemanagement, "getServices",
                new Object[] { ServiceState.ACTIVE }, new String[] { ServiceState.class.getName() });

        ServiceID[] inactiveServices = (ServiceID[]) connection.invoke(servicemanagement, "getServices",
                new Object[] { ServiceState.INACTIVE }, new String[] { ServiceState.class.getName() });

        ServiceID[] stoppingServices = (ServiceID[]) connection.invoke(servicemanagement, "getServices",
                new Object[] { ServiceState.STOPPING }, new String[] { ServiceState.class.getName() });

        addService(activeServices, discoveredServices, context.getResourceType());
        addService(inactiveServices, discoveredServices, context.getResourceType());
        addService(stoppingServices, discoveredServices, context.getResourceType());

        if (log.isInfoEnabled()) {
            log.info("Discovered " + discoveredServices.size() + " JAIN SLEE Service Components.");
        }

        return discoveredServices;
    } finally {
        try {
            mbeanUtils.logout();
        } catch (LoginException e) {
            if (log.isDebugEnabled()) {
                log.debug("Failed to logout from secured JMX", e);
            }
        }
    }
}

From source file:com.dianping.cache.service.impl.ServiceMonitorServiceImpl.java

@Override
public String getClientStats(String clientIp, int skip, int size) throws Exception {
    int retry = 1;
    while (true) {
        try {/*from w w w. j  a  v a2s  .c  o  m*/
            MBeanServerConnFactoryExtend serverConnFactory = getMBeanConnection(clientIp);
            MBeanServerConnection serverConn = (MBeanServerConnection) serverConnFactory.factory.getObject();
            return (String) serverConn.invoke(getStatMbeanName(), "getServiceStats",
                    new Object[] { skip, size },
                    new String[] { Integer.TYPE.getName(), Integer.TYPE.getName() });
        } catch (IOException e) {
            if (retry-- <= 0) {
                logger.warn("Get servicestats from mbean server[" + clientIp + "] failed, detail["
                        + e.getMessage() + "].");
                throw e;
            } else {
                MBeanServerConnFactoryExtend removed = mbeanServerConnections.remove(clientIp);
                try {
                    if (removed != null) {
                        removed.factory.destroy();
                    }
                } catch (Throwable e1) {
                }
            }
        }
    }
}

From source file:org.jboss.as.test.integration.mgmt.access.AbstractJmxNonCoreMBeansSensitivityTestCase.java

private void doOperation(boolean successExpected, String operationName, JmxManagementInterface jmx)
        throws Exception {
    MBeanServerConnection connection = jmx.getConnection();
    ObjectName domain = new ObjectName("jboss.test:service=testdeployments");
    try {/*  ww  w.ja  va  2  s.co m*/
        connection.invoke(domain, operationName, ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY);
        assertTrue("Failure was expected but success happened", successExpected);
    } catch (JMRuntimeException e) {
        if (e.getMessage().contains("WFLYJMX0037")) {
            assertFalse("Success was expected but failure happened: " + e, successExpected);
        } else {
            throw e;
        }
    }
}

From source file:com.citrix.g2w.webdriver.util.InvokeMBean.java

/**
 * Method to invoke m bean.//w  w w . j av a 2  s  . c  o  m
 * 
 * @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.jolokia.detector.GlassfishDetector.java

private synchronized boolean bootAmx(MBeanServerExecutor pServers, final LogHandler pLoghandler) {
    ObjectName bootMBean = null;// w w  w  .  ja v a  2 s  .  c o m
    try {
        bootMBean = new ObjectName("amx-support:type=boot-amx");
    } catch (MalformedObjectNameException e) {
        // Cannot happen ....
    }
    try {
        pServers.call(bootMBean, new MBeanServerExecutor.MBeanAction<Void>() {
            /** {@inheritDoc} */
            public Void execute(MBeanServerConnection pConn, ObjectName pName, Object... extraArgs)
                    throws ReflectionException, InstanceNotFoundException, IOException, MBeanException {
                pConn.invoke(pName, "bootAMX", null, null);
                return null;
            }
        });
        return true;
    } catch (InstanceNotFoundException e) {
        pLoghandler.error("No bootAmx MBean found: " + e, e);
        // Can happen, when a call to bootAmx comes to early before the bean
        // is registered
        return false;
    } catch (IllegalArgumentException e) {
        pLoghandler.error("Exception while booting AMX: " + e, e);
        // We dont try it again
        return true;
    } catch (Exception e) {
        pLoghandler.error("Exception while executing bootAmx: " + e, e);
        // dito
        return true;
    }
}

From source file:org.rhq.plugins.jslee.ServiceComponent.java

public AvailabilityType getAvailability() {
    if (log.isTraceEnabled()) {
        log.trace("getAvailability() called.");
    }//from ww  w.  ja  v  a 2s .  c o m

    try {
        MBeanServerConnection connection = this.mbeanUtils.getConnection();
        this.mbeanUtils.login();

        serviceState = (ServiceState) connection.invoke(this.servicemanagement, "getState",
                new Object[] { this.serviceId }, new String[] { ServiceID.class.getName() });
    } catch (Exception e) {
        log.error("getAvailability failed for ServiceID = " + this.serviceId);
        this.serviceState = ServiceState.INACTIVE;
        return AvailabilityType.DOWN;
    } finally {
        try {
            this.mbeanUtils.logout();
        } catch (LoginException e) {
            if (log.isDebugEnabled()) {
                log.debug("Failed to logout from secured JMX", e);
            }
        }
    }

    return AvailabilityType.UP;
}

From source file:com.cognifide.aet.runner.util.MessagesManager.java

/**
 * Removes all messages with given correlationID. AETException is thrown when failed to remove messages.
 *
 * @param correlationID - correlationId of messages that will be removed.
 *//* w  ww.  j a  v  a  2s . com*/
public void remove(String correlationID) throws AETException {
    Object[] removeSelector = { JMS_CORRELATION_ID + "='" + correlationID + "'" };
    String[] signature = { STRING_SIGNATURE };

    try (JMXConnector jmxc = getJmxConnection(jmxUrl)) {
        MBeanServerConnection connection = jmxc.getMBeanServerConnection();
        for (ObjectName queue : getAetQueuesObjects(connection)) {
            String queueName = queue.getKeyProperty(DESTINATION_NAME_PROPERTY);
            int deletedMessagesNumber = (Integer) connection.invoke(queue, REMOVE_OPERATION_NAME,
                    removeSelector, signature);
            LOGGER.debug("Deleted: {} jmsMessages from: {} queue", deletedMessagesNumber, queueName);
        }
    } catch (Exception e) {
        throw new AETException(
                String.format("Error while removing messages with correlationID: %s", correlationID), e);
    }
}

From source file:org.jboss.test.cluster.classloader.leak.test.ClassloaderLeakTestBase.java

private void flushSecurityCache(String domain) throws Exception {
    log.debug("Flushing security cache " + domain);
    ObjectName on = new ObjectName(ClassLoaderTrackerMBean.OBJECT_NAME);
    Object[] params = { domain };
    String[] signature = new String[] { String.class.getName() };
    MBeanServerConnection[] adaptors = getAdaptors();
    for (MBeanServerConnection adaptor : adaptors) {
        adaptor.invoke(on, "flushSecurityCache", params, signature);
    }// w  ww.  jav a  2  s .c o m
}