Example usage for javax.management MBeanServer invoke

List of usage examples for javax.management MBeanServer invoke

Introduction

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

Prototype

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

Source Link

Usage

From source file:chronos.web.listener.ChronosServletListener.java

/**
 * {@inheritDoc}//from   w ww .j a va  2 s.  c o m
 *
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 */
public void contextDestroyed(final ServletContextEvent event) {
    logger.debug("Chronos is shutting down...");
    final ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
    logger.debug("Got " + servers.size() + " MBean servers");
    if (servers.size() != 0) {
        final MBeanServer mbeanServer = servers.get(0);
        try {
            final ObjectName objectName = new ObjectName(CHRONOS, "type", QUARTZ_SCHEDULER_ADAPTER);

            logger.debug("Invoking shutdown() on QuartzSchedulerAdapter...");
            mbeanServer.invoke(objectName, "shutdown", null, null);

            logger.debug("Unregistering QuartzSchedulerAdapter Mbean");
            mbeanServer.unregisterMBean(objectName);
        } catch (final JMException e) {
            logger.error("Shutting down QuartzSchedulerAdapter failed: " + e.getMessage(), e);
        } catch (final NullPointerException e) {
            logger.error("Shutting down QuartzSchedulerAdapter failed: " + e.getMessage(), e);
        }
    } else {
        logger.warn("Unable to find MBeanServer!");
    }
    logger.info("Chronos shutdown");
}

From source file:net.camelpe.examples.jboss7.loanbroker.queue.JBoss7CamelContextConfiguration.java

@PostConstruct
public void createQueues() throws Exception {
    this.log.info("Creating queues ...");
    final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
    this.log.info("Found PlatformMBeanServer [{}]", mbeanServer);
    this.log.info("JMX Domains: {}", Arrays.toString(mbeanServer.getDomains()));
    for (final JmsResources.QueueDefinition queueDef : JmsResources.loanBrokerQueues()) {
        mbeanServer.invoke(new ObjectName("org.hornetq:module=JMS,type=Server"), "createQueue",
                new Object[] { queueDef.getName(), queueDef.getBinding() },
                new String[] { "java.lang.String", "java.lang.String" });
        this.log.info("Created queue [{}]", queueDef);
    }//  ww  w.  j  a  v a 2  s  .  co m
}

From source file:psiprobe.controllers.threads.ThreadStackController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    long threadId = ServletRequestUtils.getLongParameter(request, "id", -1);
    String threadName = ServletRequestUtils.getStringParameter(request, "name", null);

    List<ThreadStackElement> stack = null;
    MBeanServer mbeanServer = new Registry().getMBeanServer();
    ObjectName threadingOName = new ObjectName("java.lang:type=Threading");

    if (threadId == -1 && threadName != null) {
        // find thread by name
        for (long id : (long[]) mbeanServer.getAttribute(threadingOName, "AllThreadIds")) {
            CompositeData cd = (CompositeData) mbeanServer.invoke(threadingOName, "getThreadInfo",
                    new Object[] { id }, new String[] { "long" });
            String name = JmxTools.getStringAttr(cd, "threadName");
            if (threadName.equals(name)) {
                threadId = id;//from  www .j  a  v  a 2  s .c  o m
                break;
            }
        }
    }

    if (mbeanServer.queryMBeans(threadingOName, null) != null && threadId != -1) {

        CompositeData cd = (CompositeData) mbeanServer.invoke(threadingOName, "getThreadInfo",
                new Object[] { threadId, stackElementCount }, new String[] { "long", "int" });
        if (cd != null) {
            CompositeData[] elements = (CompositeData[]) cd.get("stackTrace");
            threadName = JmxTools.getStringAttr(cd, "threadName");

            stack = new ArrayList<>(elements.length);

            for (CompositeData cd2 : elements) {
                ThreadStackElement tse = new ThreadStackElement();
                tse.setClassName(JmxTools.getStringAttr(cd2, "className"));
                tse.setFileName(JmxTools.getStringAttr(cd2, "fileName"));
                tse.setMethodName(JmxTools.getStringAttr(cd2, "methodName"));
                tse.setLineNumber(JmxTools.getIntAttr(cd2, "lineNumber", -1));
                tse.setNativeMethod(JmxTools.getBooleanAttr(cd2, "nativeMethod"));
                stack.add(tse);
            }
        }
    }

    return new ModelAndView(getViewName(), "stack", stack).addObject("threadName", threadName);
}

From source file:net.testdriven.psiprobe.controllers.threads.ThreadStackController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    long threadID = ServletRequestUtils.getLongParameter(request, "id", -1);
    String threadName = ServletRequestUtils.getStringParameter(request, "name", null);

    List<ThreadStackElement> stack = null;
    MBeanServer mBeanServer = new Registry().getMBeanServer();
    ObjectName threadingOName = new ObjectName("java.lang:type=Threading");

    if (threadID == -1 && threadName != null) {
        // find thread by name
        long[] allIds = (long[]) mBeanServer.getAttribute(threadingOName, "AllThreadIds");
        for (long allId : allIds) {
            CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                    new Object[] { allId }, new String[] { "long" });
            String name = JmxTools.getStringAttr(cd, "threadName");
            if (threadName.equals(name)) {
                threadID = allId;// w  ww  .j a  v  a 2s  .  c  o m
                break;
            }
        }
    }

    if (mBeanServer.queryMBeans(threadingOName, null) != null && threadID != -1) {

        CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                new Object[] { threadID, stackElementCount }, new String[] { "long", "int" });
        if (cd != null) {
            CompositeData[] elements = (CompositeData[]) cd.get("stackTrace");
            threadName = JmxTools.getStringAttr(cd, "threadName");

            stack = new ArrayList<>(elements.length);

            for (CompositeData cd2 : elements) {
                ThreadStackElement tse = new ThreadStackElement();
                tse.setClassName(JmxTools.getStringAttr(cd2, "className"));
                tse.setFileName(JmxTools.getStringAttr(cd2, "fileName"));
                tse.setMethodName(JmxTools.getStringAttr(cd2, "methodName"));
                tse.setLineNumber(JmxTools.getIntAttr(cd2, "lineNumber", -1));
                tse.setNativeMethod(JmxTools.getBooleanAttr(cd2, "nativeMethod"));
                stack.add(tse);
            }
        }
    }

    return new ModelAndView(getViewName(), "stack", stack).addObject("threadName", threadName);
}

From source file:com.googlecode.psiprobe.controllers.threads.ThreadStackController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    long threadID = ServletRequestUtils.getLongParameter(request, "id", -1);
    String threadName = ServletRequestUtils.getStringParameter(request, "name", null);

    List stack = null;/*from   w w w. j  ava2s  .c  o  m*/
    MBeanServer mBeanServer = new Registry().getMBeanServer();
    ObjectName threadingOName = new ObjectName("java.lang:type=Threading");

    if (threadID == -1 && threadName != null) {
        // find thread by name
        long[] allIds = (long[]) mBeanServer.getAttribute(threadingOName, "AllThreadIds");
        for (int i = 0; i < allIds.length; i++) {
            CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                    new Object[] { new Long(allIds[i]) }, new String[] { "long" });
            String name = JmxTools.getStringAttr(cd, "threadName");
            if (threadName.equals(name)) {
                threadID = allIds[i];
                break;
            }
        }
    }

    if (mBeanServer.queryMBeans(threadingOName, null) != null && threadID != -1) {

        CompositeData cd = (CompositeData) mBeanServer.invoke(threadingOName, "getThreadInfo",
                new Object[] { new Long(threadID), new Integer(stackElementCount) },
                new String[] { "long", "int" });
        if (cd != null) {
            CompositeData[] elements = (CompositeData[]) cd.get("stackTrace");
            threadName = JmxTools.getStringAttr(cd, "threadName");

            stack = new ArrayList(elements.length);

            for (int i = 0; i < elements.length; i++) {
                CompositeData cd2 = elements[i];
                ThreadStackElement tse = new ThreadStackElement();
                tse.setClassName(JmxTools.getStringAttr(cd2, "className"));
                tse.setFileName(JmxTools.getStringAttr(cd2, "fileName"));
                tse.setMethodName(JmxTools.getStringAttr(cd2, "methodName"));
                tse.setLineNumber(JmxTools.getIntAttr(cd2, "lineNumber", -1));
                tse.setNativeMethod(JmxTools.getBooleanAttr(cd2, "nativeMethod"));
                stack.add(tse);
            }
        }
    }

    return new ModelAndView(getViewName(), "stack", stack).addObject("threadName", threadName);
}

From source file:com.avanza.ymer.YmerMirrorIntegrationTest.java

@Test
public void mbeanInvoke() throws Exception {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    ObjectName nameTemplate = ObjectName.getInstance(
            "se.avanzabank.space.mirror:type=DocumentWriteExceptionHandler,name=documentWriteExceptionHandler");
    Set<ObjectName> names = server.queryNames(nameTemplate, null);
    assertThat(names.size(), is(greaterThan(0)));
    server.invoke(names.toArray(new ObjectName[1])[0], "useCatchesAllHandler", null, null);
}

From source file:chronos.web.listener.ChronosServletListener.java

/**
 * @param mbeanServer/*from  w ww . j a va  2s.  c  om*/
 *        the MBeanServer
 */
private void initializeQuartzSchedulerAdapter(final MBeanServer mbeanServer) {
    try {
        logger.debug("Creating and registering QuartzSchedulerAdapter MBean...");

        final ObjectName objectName = new ObjectName(CHRONOS, "type", QUARTZ_SCHEDULER_ADAPTER);

        final QuartzSchedulerAdapter quartzSchedulerAdapter = new QuartzSchedulerAdapter();
        mbeanServer.registerMBean(quartzSchedulerAdapter, objectName);

        logger.debug("Invoking start() on QuartzSchedulerAdapter MBean...");
        try {
            mbeanServer.invoke(objectName, "start", null, null);
        } catch (final JMException e) {
            logger.error("QuartzSchedulerAdapter start() failed: " + e.getMessage(), e);
        }
    } catch (final JMException e) {
        logger.error("Registering QuartzSchedulerAdapter failed: " + e.getMessage(), e);
    }
}

From source file:org.apache.camel.example.management.ManagementExampleTest.java

@Test
public void testManagementExample() throws Exception {
    // Give it a bit of time to run
    Thread.sleep(2000);/*from  w  ww .  jav  a2s.c  o m*/

    MBeanServer mbeanServer = context.getManagementStrategy().getManagementAgent().getMBeanServer();

    // Find the endpoints
    Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=endpoints,*"), null);

    // now there is no managed endpoint for the dead queue
    // CAMEL-7076 there is no spring-event:default endpoint any more
    assertEquals(4, set.size());

    // Find the routes
    set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null);
    assertEquals(3, set.size());

    // Stop routes
    for (ObjectName on : set) {
        mbeanServer.invoke(on, "stop", null, null);
    }
}

From source file:com.evolveum.midpoint.web.page.PageTemplate.java

protected void clearLessJsCache(AjaxRequestTarget target) {
    try {/*from   w w  w.  j a  va  2 s . co m*/
        ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
        if (servers.size() > 1) {
            LOGGER.info("Too many mbean servers, cache won't be cleared.");
            for (MBeanServer server : servers) {
                LOGGER.info(server.getDefaultDomain());
            }
            return;
        }
        MBeanServer server = servers.get(0);
        ObjectName objectName = ObjectName.getInstance("wro4j-idm:type=WroConfiguration");
        server.invoke(objectName, "reloadCache", new Object[] {}, new String[] {});
        if (target != null) {
            target.add(PageTemplate.this);
        }
    } catch (Exception ex) {
        LoggingUtils.logException(LOGGER, "Couldn't clear less/js cache", ex);
        error("Error occurred, reason: " + ex.getMessage());
        if (target != null) {
            target.add(getFeedbackPanel());
        }
    }
}

From source file:org.jboss.console.plugins.monitor.ManageSnapshotServlet.java

protected void doit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter("action");
    if (action == null) {
        error("unknown action: ", req, resp);
        return;//from  w  w w  .j  a v a  2  s  .co m
    }
    action = action.trim();
    MBeanServer mbeanServer = MBeanServerLocator.locateJBoss();
    ObjectName monitorObjectName;
    String attribute = null;
    try {
        monitorObjectName = new ObjectName(req.getParameter("monitorObjectName"));
        attribute = (String) mbeanServer.getAttribute(monitorObjectName, "ObservedAttribute");
    } catch (Exception ex) {
        error("Malformed Monitor ObjectName: " + req.getParameter("monitorObjectName"), req, resp);
        return;
    }
    if (action.equals("Start Snapshot")) {
        Object[] nullArgs = {};
        String[] nullSig = {};
        try {
            mbeanServer.invoke(monitorObjectName, "startSnapshot", nullArgs, nullSig);
        } catch (Exception ex) {
            error("Problem invoking startSnapshot: " + ex.toString(), req, resp);
            return;
        }
        req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
        return;
    } else if (action.equals("Stop Snapshot")) {
        Object[] nullArgs = {};
        String[] nullSig = {};
        try {
            mbeanServer.invoke(monitorObjectName, "endSnapshot", nullArgs, nullSig);
        } catch (Exception ex) {
            error("Problem invoking endSnapshot: " + ex.toString(), req, resp);
            return;
        }
        req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
        return;
    } else if (action.equals("Clear Dataset")) {
        Object[] nullArgs = {};
        String[] nullSig = {};
        try {
            mbeanServer.invoke(monitorObjectName, "clearData", nullArgs, nullSig);
        } catch (Exception ex) {
            error("Problem invoking clearData: " + ex.toString(), req, resp);
            return;
        }
        req.setAttribute("error", "Dataset Cleared!");
        req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
        return;
    } else if (action.equals("Remove Snapshot")) {
        try {
            log.debug("removing snapshot: " + monitorObjectName.toString());
            mbeanServer.unregisterMBean(monitorObjectName);
            req.getRequestDispatcher("/ServerInfo.jsp").forward(req, resp);
        } catch (Exception ex) {
            error("Failed to Remove Monitor: " + ex.toString(), req, resp);
        }
        return;
    } else if (action.equals("Show Dataset")) {
        ArrayList data = null;
        long start, end = 0;
        try {
            data = (ArrayList) mbeanServer.getAttribute(monitorObjectName, "Data");
            start = ((Long) mbeanServer.getAttribute(monitorObjectName, "StartTime")).longValue();
            end = ((Long) mbeanServer.getAttribute(monitorObjectName, "EndTime")).longValue();
        } catch (Exception ex) {
            error("Problem invoking getData: " + ex.toString(), req, resp);
            return;
        }
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        writer.println("<html>");
        writer.println("<body>");
        writer.println("<b>Start Time:</b> " + start + "ms<br>");
        writer.println("<b>End Time:</b> " + end + "ms<br>");
        writer.println("<b>Total Time:</b> " + (end - start) + "ms<br>");
        writer.println("<br><table border=\"0\">");
        for (int i = 0; i < data.size(); i++) {
            writer.println("<tr><td>" + data.get(i) + "</td></tr");
        }
        writer.println("</table></body></html>");
        return;
    } else if (action.equals("Graph Dataset")) {
        ArrayList data = null;
        long start, end = 0;
        try {
            data = (ArrayList) mbeanServer.getAttribute(monitorObjectName, "Data");
            start = ((Long) mbeanServer.getAttribute(monitorObjectName, "StartTime")).longValue();
            end = ((Long) mbeanServer.getAttribute(monitorObjectName, "EndTime")).longValue();
        } catch (Exception ex) {
            error("Problem invoking getData: " + ex.toString(), req, resp);
            return;
        }
        XYSeries set = new XYSeries(attribute, false, false);
        for (int i = 0; i < data.size(); i++) {
            set.add(new Integer(i), (Number) data.get(i));
        }
        DefaultTableXYDataset dataset = new DefaultTableXYDataset(false);
        dataset.addSeries(set);
        JFreeChart chart = ChartFactory.createXYLineChart("JMX Attribute: " + attribute, "count", attribute,
                dataset, PlotOrientation.VERTICAL, true, true, false);
        resp.setContentType("image/png");
        OutputStream out = resp.getOutputStream();
        ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
        out.close();
        return;
    }
    error("Unknown Action", req, resp);
    return;
}