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.rhq.enterprise.server.plugin.pc.perspective.PerspectiveServerPluginManager.java

private void undeployWar(File deployFile) {
    try {/*from www  .  j a v a  2s .c  o m*/
        // get reference to MBean server
        Context ic = new InitialContext();
        MBeanServerConnection server = (MBeanServerConnection) ic.lookup("jmx/invoker/RMIAdaptor");

        // get reference to MainDeployer MBean
        ObjectName mainDeployer = new ObjectName("jboss.system:service=MainDeployer");

        URL fileUrl = deployFile.toURI().toURL();

        Boolean isDeployed = (Boolean) server.invoke(mainDeployer, "isDeployed", new Object[] { fileUrl },
                new String[] { URL.class.getName() });

        if (isDeployed) {
            server.invoke(mainDeployer, "undeploy", new Object[] { fileUrl },
                    new String[] { URL.class.getName() });
        }
    } catch (Exception e) {
        log.error("Failed to undeploy perspective WAR [" + deployFile + "].", e);
    }
}

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

private boolean hasClassLoader(String key, MBeanServerConnection adaptor) throws Exception {
    ObjectName on = new ObjectName(ClassLoaderTrackerMBean.OBJECT_NAME);
    Object[] params = { key };//w w  w . j  a v a  2 s  . co  m
    String[] signature = new String[] { String.class.getName() };
    return ((Boolean) adaptor.invoke(on, "hasClassLoader", params, signature)).booleanValue();
}

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

private boolean hasClassLoaderBeenReleased(String key, MBeanServerConnection adaptor) throws Exception {
    ObjectName on = new ObjectName(ClassLoaderTrackerMBean.OBJECT_NAME);
    Object[] params = { key };/*from  w  ww  .j a va  2s.  c  o m*/
    String[] signature = new String[] { String.class.getName() };
    return ((Boolean) adaptor.invoke(on, "hasClassLoaderBeenReleased", params, signature)).booleanValue();
}

From source file:com.springsource.hq.plugin.tcserver.plugin.TomcatMeasurementPlugin.java

private int getDeadlockedThreadCount(MBeanServerConnection connection)
        throws MetricInvalidException, MetricUnreachableException {
    int deadlockCount = 0;
    try {// ww  w  .j a  v a2  s .c  om
        // in version 1.6+ there is a findDeadlockedThreads method
        long[] deadlocks;
        try {
            deadlocks = (long[]) connection.invoke(new ObjectName("java.lang:type=Threading"),
                    "findDeadlockedThreads", null, null);
        } catch (MalformedObjectNameException e) {
            throw new MetricInvalidException("Error querying for deadlock thread mbean: " + e.getMessage(), e);
        } catch (JMException e) {
            LOGGER.debug("Method 'findDeadlockedThreads' for objectname 'java.lang:type=Threading'"
                    + "was not found. Trying method findMonitorDeadlockedThreads...", e);
            // If this occurs then the issue is most likely related to the
            // Java version.
            // Now check for the method on java 1.5
            try {
                deadlocks = (long[]) connection.invoke(new ObjectName("java.lang:type=Threading"),
                        "findMonitorDeadlockedThreads", null, null);
            } catch (MalformedObjectNameException me) {
                throw new MetricInvalidException("Error querying for deadlock thread mbean: " + me.getMessage(),
                        me);
            } catch (JMException ex) {
                LOGGER.debug("Unable to retrieve DeadlockedThreads count: ", ex);
                throw new MetricUnreachableException(
                        "Unable to reach deadlock thread mbean: " + ex.getMessage(), ex);
            }
        }

        if (deadlocks != null) {
            deadlockCount = deadlocks.length;
        }
        return deadlockCount;
    } catch (IOException e) {
        throw new MetricUnreachableException("Error querying for deadlock thread mbean: " + e.getMessage(), e);
    }
}

From source file:com.ngdata.hbaseindexer.impl.IndexerModelImplTest.java

public int terminateZooKeeperConnections() throws Exception {
    MBeanServerConnection connection = java.lang.management.ManagementFactory.getPlatformMBeanServer();
    ObjectName replicationSources = new ObjectName(
            "org.apache.ZooKeeperService:name0=*,name1=Connections,name2=*,name3=*");
    Set<ObjectName> mbeans = connection.queryNames(replicationSources, null);
    int connectionCount = mbeans.size();

    for (ObjectName name : mbeans) {
        connection.invoke(name, "terminateConnection", new Object[] {}, new String[] {});
    }//from  w  ww  . ja v  a  2s. co  m

    return connectionCount;
}

From source file:net.sfr.tv.mom.mgt.handlers.InvocationHandler.java

@Override
public Object execute(MBeanServerConnection connection, Object[] args) {
    if (this.expression.indexOf("{") != -1) {
        this.expression = renderExpression(new Object[] { "\"".concat(args[0].toString()).concat("\"") });
        args = Arrays.copyOfRange(args, 1, args.length);
    }//from w  w w.j  a  va 2 s .  c o m

    try {
        final Set<ObjectName> oNames = connection.queryNames(new ObjectName(expression), null);
        if (oNames == null || oNames.isEmpty()) {
            LOGGER.severe("No object names returns for expression '" + expression + "'");
            return null;
        } else {
            final Object result = connection.invoke(oNames.iterator().next(), operation.getName(), args,
                    operation.getSignature());
            if (result == null) {
                LOGGER.warning("Result of operation '" + operation.getName() + "'is null");
                return result;
            }
            return formatter.format(result);
        }
        //result = connection.invoke(new ObjectName(expression), operation.getName(), new Object[operation.getSignature().length], operation.getSignature());
    } catch (MBeanException | IllegalArgumentException | InstanceNotFoundException
            | MalformedObjectNameException | ReflectionException | IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return null;
    }
}

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 {//  www .  ja  v a  2s.co  m
            // 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:org.eclipse.virgo.ide.runtime.internal.core.command.AbstractJmxServerDeployerCommand.java

/**
 * Method to be called by sub-classes to execute given command against the MBean
 *///from   w w  w. j  av  a  2  s.co m
@SuppressWarnings("unchecked")
protected final T doExecute() throws IOException, TimeoutException {

    JmxServerCommandTemplate template = new JmxServerCommandTemplate() {

        public Object invokeOperation(MBeanServerConnection connection) throws Exception {

            ObjectName name = ObjectName.getInstance(getMBeanName());

            Object[] operationArguments = getOperationArguments();

            String[] classNames = new String[operationArguments.length];
            for (int i = 0; i < operationArguments.length; i++) {
                if (operationArguments[i] instanceof Boolean) {
                    classNames[i] = boolean.class.getName();
                } else {
                    classNames[i] = operationArguments[i].getClass().getName();
                }
            }

            return connection.invoke(name, getOperationName(), operationArguments, classNames);
        }
    };

    return (T) execute(template);
}

From source file:com.custardsource.maven.plugins.jmx.Invoke.java

@Override
public Object execute(MBeanServerConnection connection) throws Exception {
    ObjectName name = new ObjectName(objectName);
    int len = parameters == null ? 0 : parameters.length;
    String[] signature = new String[len];
    Object[] arguments = new Object[len];

    ConvertUtilsBean converter = new ConvertUtilsBean();

    for (int i = 0; i < len; i++) {
        signature[i] = parameters[i].getType();
        arguments[i] = converter.convert(parameters[i].getValue(),
                ClassUtils.getClass(parameters[i].getType()));
        if (signature[i].equals("java.lang.String") && arguments[i] == null) {
            arguments[i] = "";
        }/*  w w  w. j  a  v a2  s  . co m*/
    }
    return connection.invoke(name, operation, arguments, signature);
}

From source file:com.clustercontrol.HinemosManagerCli.java

private void invoke() {
    System.setProperty("sun.rmi.transport.connectionTimeout", String.valueOf(connectTimeout));
    System.setProperty("sun.rmi.transport.tcp.responseTimeout", String.valueOf(responseTimeout));

    try {/*from   w  w w.ja va2  s.com*/
        JMXServiceURL url = new JMXServiceURL(
                String.format("service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi", ip, port));
        Map<String, Object> env = new HashMap<String, Object>();
        if (user != null && password != null) {
            env.put(JMXConnector.CREDENTIALS, new String[] { user, password });
        }
        MBeanServerConnection mbsc = JMXConnectorFactory.connect(url, env).getMBeanServerConnection();

        ObjectName mbeanName = new ObjectName("com.clustercontrol.mbean:type=" + name);
        if (doesOutputInfo) {
            printMBeanInfo(mbsc.getMBeanInfo(mbeanName));
            return;
        }

        Object ret;
        if (attribute != null) {
            ret = mbsc.getAttribute(mbeanName, attribute);
        } else {
            String[] signature = new String[operationArgs.length];
            for (int i = 0; i < signature.length; i++) {
                signature[i] = String.class.getName();
            }
            ret = mbsc.invoke(mbeanName, operation, operationArgs, signature);
        }
        System.out.println(ret);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(2);
    }
}