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:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

private Object invokeJMXMBeanOperation(String mBeanName, String operationName, Object[] params,
        String[] signature) {/*  w w w.  j  a va2s .co  m*/

    try {
        MBeanServerConnection mBeanServerConnection = getJMXConnection();
        return mBeanServerConnection.invoke(new ObjectName(mBeanName), operationName, params, signature);

    } catch (Exception e) {
        throw new RuntimeException(JMX_INVOKE_ERROR + mBeanName + ": " + operationName + " with arguments : "
                + Arrays.toString(params), e);
    }
}

From source file:org.helios.collector.jmx.connection.AbstractMBeanServerConnectionFactory.java

/**
 * Invokes the named operation on the named MBean
 * @param objectName/*from w  w  w .  ja v  a2  s .  c om*/
 * @param opName
 * @param params
 * @param signature
 * @return
 * @throws InstanceNotFoundException
 * @throws MBeanException
 * @throws ReflectionException
 * @throws IOException
 */
@Override
@ManagedOperation
public Object invoke(ObjectName objectName, String opName, Object[] params, String[] signature)
        throws InstanceNotFoundException, MBeanException, ReflectionException, IOException {
    validateConn();
    MBeanServerConnection conn = null;
    try {
        conn = getPooledConnection();
        return conn.invoke(objectName, opName, params, signature);
    } catch (MBeanServerConnectionFactoryException e) {
        throw new RuntimeException("Failed to get pooled connection", e);
    } finally {
        try {
            this.returnPooledConnection(conn);
        } catch (Exception e) {
            log.debug(e.getMessage());
        }
    }
}

From source file:dk.netarkivet.harvester.harvesting.controller.BnfHeritrixController.java

/**
 * Executes a JMX call (attribute read or single operation) on a given bean.
 *
 * @param beanName// ww  w  .  j av a  2s . c om
 *            the MBean name.
 * @param retry
 *            if true, will retry a number of times if the operation fails.
 * @param isOperation
 *            true if the call is an operation, false if it's an attribute
 *            read.
 * @param names
 *            name of operation or name of attributes
 * @param args
 *            optional arguments for operations
 * @return the object returned by the distant MBean
 */
private Object jmxCall(String beanName, boolean retry, boolean isOperation, String[] names, String... args) {

    MBeanServerConnection connection = getMBeanServerConnection();

    int maxTries = 1;
    if (retry) {
        maxTries = jmxMaxTries;
    }
    int tries = 0;
    Throwable lastException;
    do {
        tries++;
        try {
            if (isOperation) {
                final String[] signature = new String[args.length];
                Arrays.fill(signature, String.class.getName());
                return connection.invoke(JMXUtils.getBeanName(beanName), names[0], args, signature);
            } else {
                return connection.getAttributes(JMXUtils.getBeanName(beanName), names).asList();
            }
        } catch (IOException e) {
            lastException = e;
        } catch (ReflectionException e) {
            lastException = e;
        } catch (InstanceNotFoundException e) {
            lastException = e;
        } catch (MBeanException e) {
            lastException = e;
        }
        log.debug("Attempt " + tries + " out of " + maxTries + " attempts to make this jmxCall failed ");
        if (tries < maxTries) {
            TimeUtils.exponentialBackoffSleep(tries);
        }

    } while (tries < maxTries);

    String msg = "";
    if (isOperation) {
        msg = "Failed to execute " + names[0] + " with args " + Arrays.toString(args) + " on " + beanName;
    } else {
        msg = "Failed to read attributes " + Arrays.toString(names) + " of " + beanName;
    }

    if (lastException != null) {
        msg += ", last exception was " + lastException.getClass().getName();
    }
    msg += " after " + tries + " attempts";
    throw new IOFailure(msg, lastException);
}

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

@Override
public void updateResourceConfiguration(ConfigurationUpdateReport configurationUpdateReport) {
    try {/*from  w  w w .j  a  v a 2  s  .c  om*/
        MBeanServerConnection connection = this.mbeanUtils.getConnection();
        this.mbeanUtils.login();

        // As an example, if a particular service has the name FooService, vendor FooCompany, and version 1.0,
        // then the Object Name of a ServiceUsageMBean for that service would be:
        // javax.slee.management.usage:type=ServiceUsage,serviceName="FooService", serviceVendor="FooCompany",serviceVersion="1.0"
        ObjectName serviceUsageON = new ObjectName(ServiceUsageMBean.BASE_OBJECT_NAME + ','
                + ServiceUsageMBean.SERVICE_NAME_KEY + '=' + ObjectName.quote(serviceId.getName()) + ','
                + ServiceUsageMBean.SERVICE_VENDOR_KEY + '=' + ObjectName.quote(serviceId.getVendor()) + ','
                + ServiceUsageMBean.SERVICE_VERSION_KEY + '=' + ObjectName.quote(serviceId.getVersion()));

        ServiceUsageMBean serviceUsageMBean = (ServiceUsageMBean) MBeanServerInvocationHandler.newProxyInstance(
                connection, serviceUsageON, javax.slee.management.ServiceUsageMBean.class, false);

        PropertyList columnList = configurationUpdateReport.getConfiguration().getList("usageParameter");
        ObjectName sbbUsageON = serviceUsageMBean.getSbbUsageMBean(sbbId);

        for (Property p : columnList.getList()) {
            PropertyMap pMap = (PropertyMap) p;
            String usageParamName = ((PropertySimple) pMap.get("usageParameterName")).getStringValue();
            Object curValue = pMap.get("usageParameterValue");

            Object newValue = connection.invoke(sbbUsageON, "get" + usageParamName, new Object[] { false },
                    new String[] { "boolean" });
            if (newValue != null && !newValue.equals(curValue)) {
                if (log.isDebugEnabled()) {
                    log.debug("Changing Usage Parameter '" + usageParamName + "' from value [" + curValue
                            + "] to [" + newValue + "].");
                }
            }
        }
        configurationUpdateReport.setStatus(ConfigurationUpdateStatus.SUCCESS);
    } catch (Exception e) {
        log.error("Failed to update Resource Configuration.", e);
        configurationUpdateReport.setErrorMessageFromThrowable(e);
        configurationUpdateReport.setStatus(ConfigurationUpdateStatus.FAILURE);
    } finally {
        try {
            this.mbeanUtils.logout();
        } catch (LoginException e) {
            if (log.isDebugEnabled()) {
                log.debug("Failed to logout from secured JMX", e);
            }
        }
    }
}

From source file:org.hyperic.hq.plugin.weblogic.WeblogicServiceControlPlugin.java

protected Object invoke(MBeanServerConnection mServer, String objectName, String method, Object[] args,
        String[] sig) throws MetricUnreachableException, MetricNotFoundException, PluginException {

    ObjectName obj;/*from ww w . j  a  v  a 2s .co m*/
    try {
        obj = new ObjectName(objectName);
    } catch (MalformedObjectNameException e1) {
        throw new PluginException("Unable to create an ObjectName from " + objectName);
    }

    MBeanInfo info;
    try {
        info = mServer.getMBeanInfo(obj);
    } catch (Exception e1) {
        throw new PluginException("Unable to obtain MBeanInfo from " + objectName);
    }

    if (sig.length == 0) {
        MBeanUtil.OperationParams params = MBeanUtil.getOperationParams(info, method, args);
        if (params.isAttribute) {
            if (method.startsWith("set")) {
                try {
                    mServer.setAttribute(obj, new Attribute(method.substring(3), params.arguments[0]));
                } catch (AttributeNotFoundException e) {
                    throw new MetricNotFoundException(e.getMessage(), e);
                } catch (Exception e) {
                    throw new PluginException(e);
                }
                return null;
            } else {
                try {
                    return mServer.getAttribute(obj, method.substring(3));
                } catch (AttributeNotFoundException e) {
                    throw new MetricNotFoundException(e.getMessage(), e);
                } catch (Exception e) {
                    throw new PluginException(e);
                }
            }
        }
        sig = params.signature;
        args = params.arguments;
    }

    try {
        return mServer.invoke(obj, method, args, sig);
    } catch (Exception e) {
        throw new PluginException(e);
    }
}

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

@Override
public Configuration loadResourceConfiguration() throws Exception {
    try {/*from  w  w  w .j  a va 2  s.  c  o  m*/
        Configuration config = new Configuration();

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

        // As an example, if a particular service has the name FooService, vendor FooCompany, and version 1.0,
        // then the Object Name of a ServiceUsageMBean for that service would be:
        // javax.slee.management.usage:type=ServiceUsage,serviceName="FooService", serviceVendor="FooCompany",serviceVersion="1.0"
        ObjectName serviceUsageON = new ObjectName(ServiceUsageMBean.BASE_OBJECT_NAME + ','
                + ServiceUsageMBean.SERVICE_NAME_KEY + '=' + ObjectName.quote(serviceId.getName()) + ','
                + ServiceUsageMBean.SERVICE_VENDOR_KEY + '=' + ObjectName.quote(serviceId.getVendor()) + ','
                + ServiceUsageMBean.SERVICE_VERSION_KEY + '=' + ObjectName.quote(serviceId.getVersion()));

        ServiceUsageMBean serviceUsageMBean = (ServiceUsageMBean) MBeanServerInvocationHandler.newProxyInstance(
                connection, serviceUsageON, javax.slee.management.ServiceUsageMBean.class, false);

        PropertyList columnList = new PropertyList("usageParameter");
        ObjectName sbbUsageON = null;
        if (usageParameterSetName != null && !usageParameterSetName.equals("<default>")) {
            sbbUsageON = serviceUsageMBean.getSbbUsageMBean(sbbId, usageParameterSetName);
        } else {
            sbbUsageON = serviceUsageMBean.getSbbUsageMBean(sbbId);
        }

        MBeanInfo usageInfo = connection.getMBeanInfo(sbbUsageON);

        for (MBeanOperationInfo operation : usageInfo.getOperations()) {
            String opName = operation.getName();
            if (opName.startsWith("get")) {
                PropertyMap col = new PropertyMap("usageParameterDefinition");

                col.put(new PropertySimple("usageParameterName", opName.replaceFirst("get", "")));

                boolean isSampleType = operation.getReturnType().equals("javax.slee.usage.SampleStatistics");
                col.put(new PropertySimple("usageParameterType", isSampleType ? "Sample" : "Counter"));

                Object value = connection.invoke(sbbUsageON, opName, new Object[] { false },
                        new String[] { "boolean" });
                col.put(new PropertySimple("usageParameterValue", value));

                columnList.add(col);
            }
        }
        config.put(columnList);

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

From source file:com.stumbleupon.hbaseadmin.JMXQuery.java

protected Object doBeanOperation(MBeanServerConnection mbsc, ObjectInstance instance, String command,
        MBeanOperationInfo[] infos) throws Exception {

    final CommandParse parse = new CommandParse(command);

    final MBeanOperationInfo op = (MBeanOperationInfo) getFeatureInfo(infos, parse.getCmd());

    Object result = null;// w  ww  . j  ava2s  .  c  o m

    if (op == null) {
        result = "Operation " + parse.getCmd() + " not found.";
    } else {
        final MBeanParameterInfo[] paraminfos = op.getSignature();
        final int paraminfosLength = (paraminfos == null) ? 0 : paraminfos.length;
        int objsLength = (parse.getArgs() == null) ? 0 : parse.getArgs().length;

        // FIXME: bad solution for comma containing parameter
        if (paraminfosLength == 1) {
            // concat all to one string
            String realParameter = parse.getArgs()[0];
            for (int j = 1; j < objsLength; j++) {
                realParameter = realParameter + "," + parse.getArgs()[j];
            }
            objsLength = 1;
            parse.setArgs(new String[] { realParameter });
        }

        if (paraminfosLength != objsLength) {
            result = "Passed param count does not match signature count";
        } else {
            final String[] signature = new String[paraminfosLength];
            final Object[] params = (paraminfosLength == 0) ? null : new Object[paraminfosLength];

            for (int i = 0; i < paraminfosLength; ++i) {
                final MBeanParameterInfo paraminfo = paraminfos[i];
                // System.out.println( "paraminfo.getType() = " + paraminfo.getType());
                final String classType = paraminfo.getType();
                // Constructor c = Class.forName(classType).getConstructor(new Class[] { String.class });
                final Constructor c = getResolvedClass(paraminfo.getType())
                        .getConstructor(new Class[] { String.class });

                params[i] = c.newInstance(new Object[] { parse.getArgs()[i] });
                signature[i] = classType;
            }

            result = mbsc.invoke(instance.getObjectName(), parse.getCmd(), params, signature);
        }
    }

    return result;
}

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

@Override
protected boolean executeWithOptions(final CommandLine line) throws Exception {
    if (line.hasOption(OPTION_LISTBEANS)) {
        execute(new IJmxTemplate<Object>() {
            @Override/*from   w  w w .ja v a  2 s.c  om*/
            public Object execute(String engineName, MBeanServerConnection mbeanConn) throws Exception {
                Set<ObjectName> beanSet = mbeanConn.queryNames(null, null);
                for (ObjectName objectName : beanSet) {
                    if (objectName.getDomain().startsWith("org.jumpmind.symmetric." + engineName)) {
                        System.out.println(objectName.toString());
                    }
                }
                return null;
            }
        });
    } else if (line.hasOption(OPTION_LISTMETHODS) || line.hasOption(OPTION_METHOD)) {
        if (line.hasOption(OPTION_BEAN)) {

            execute(new IJmxTemplate<Object>() {
                @Override
                public Object execute(String engineName, MBeanServerConnection mbeanConn) throws Exception {
                    String beanName = line.getOptionValue(OPTION_BEAN);
                    MBeanInfo info = mbeanConn.getMBeanInfo(new ObjectName(beanName));
                    if (info != null) {
                        if (line.hasOption(OPTION_LISTMETHODS)) {
                            MBeanOperationInfo[] operations = info.getOperations();
                            Map<String, MBeanOperationInfo> orderedMap = new TreeMap<String, MBeanOperationInfo>();
                            for (MBeanOperationInfo methodInfo : operations) {
                                orderedMap.put(methodInfo.getName(), methodInfo);
                            }
                            for (MBeanOperationInfo methodInfo : orderedMap.values()) {
                                System.out.print(methodInfo.getName() + "(");
                                MBeanParameterInfo[] params = methodInfo.getSignature();
                                int index = 0;
                                for (MBeanParameterInfo p : params) {
                                    if (index > 0) {
                                        System.out.print(", ");
                                    }
                                    System.out.print(p.getType() + " " + p.getName());
                                    index++;
                                }
                                System.out.print(")");
                                if (methodInfo.getReturnType() != null
                                        && !methodInfo.getReturnType().equals("void")) {
                                    System.out.print(" : " + methodInfo.getReturnType());
                                }
                                System.out.println();
                            }
                        } else if (line.hasOption(OPTION_METHOD)) {
                            String argsDelimiter = line.getOptionValue(OPTION_ARGS_DELIM);
                            if (isBlank(argsDelimiter)) {
                                argsDelimiter = ",";
                            } else {
                                argsDelimiter = argsDelimiter.trim();
                            }
                            String methodName = line.getOptionValue(OPTION_METHOD);
                            String[] args = null;
                            if (line.hasOption(OPTION_ARGS)) {
                                String argLine = line.getOptionValue(OPTION_ARGS);
                                args = argsDelimiter == "," ? CsvUtils.tokenizeCsvData(argLine)
                                        : argLine.split(argsDelimiter);
                                ;
                            } else {
                                args = new String[0];
                            }

                            MBeanOperationInfo[] operations = info.getOperations();
                            for (MBeanOperationInfo methodInfo : operations) {
                                MBeanParameterInfo[] paramInfos = methodInfo.getSignature();
                                if (methodInfo.getName().equals(methodName)
                                        && paramInfos.length == args.length) {
                                    String[] signature = new String[args.length];
                                    Object[] objArgs = new Object[args.length];
                                    int index = 0;
                                    for (MBeanParameterInfo paramInfo : paramInfos) {
                                        signature[index] = paramInfo.getType();
                                        if (!paramInfo.getType().equals(String.class.getName())) {
                                            Class<?> clazz = Class.forName(paramInfo.getType());
                                            Constructor<?> constructor = clazz.getConstructor(String.class);
                                            objArgs[index] = constructor.newInstance(args[index]);
                                        } else {
                                            objArgs[index] = args[index];
                                        }
                                        index++;
                                    }
                                    Object returnValue = mbeanConn.invoke(new ObjectName(beanName), methodName,
                                            objArgs, signature);
                                    if (methodInfo.getReturnType() != null
                                            && !methodInfo.getReturnType().equals("void")) {
                                        System.out.println(returnValue);
                                    }
                                    System.exit(0);
                                }
                            }

                            System.out.println("ERROR: Could not locate a JMX method named: " + methodName
                                    + " with " + args.length + " arguments on bean: " + beanName);
                            System.exit(1);

                            return null;

                        }
                    } else {
                        System.out.println("ERROR: Could not locate a JMX bean with the name of: " + beanName);
                        System.exit(1);
                    }
                    return null;
                }
            });
        } else {
            System.out.println("ERROR: Must specifiy the --bean option.");
            System.exit(1);
        }
    } else {
        return false;
    }

    return true;
}