Example usage for javax.management MBeanServer unregisterMBean

List of usage examples for javax.management MBeanServer unregisterMBean

Introduction

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

Prototype

public void unregisterMBean(ObjectName name) throws InstanceNotFoundException, MBeanRegistrationException;

Source Link

Document

If this method successfully unregisters an MBean, a notification is sent as described above.

Usage

From source file:org.apache.cassandra.db.ColumnFamilyStore.java

void unregisterMBean() {
    try {//www . j  a  v a2 s . c om
        invalid = true;
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName nameObj = new ObjectName(mbeanName);
        if (mbs.isRegistered(nameObj))
            mbs.unregisterMBean(nameObj);
        for (ColumnFamilyStore index : indexedColumns.values())
            index.unregisterMBean();
    } catch (Exception e) {
        // this shouldn't block anything.
        logger.warn(e.getMessage(), e);
    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Unregister MBeans loaded by the web application class loader
 *//*from w  w w . j  av a2  s. com*/
protected void unregisterMBeans() {
    try {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
        for (ObjectName objectName : allMBeanNames) {
            try {
                final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
                if (isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
                    warn("MBean '" + objectName + "' was loaded in web application; unregistering");
                    mBeanServer.unregisterMBean(objectName);
                }
            } catch (Exception e) { // MBeanRegistrationException / InstanceNotFoundException
                error(e);
            }
        }
    } catch (Exception e) { // MalformedObjectNameException
        error(e);
    }
}

From source file:io.fabric8.test.smoke.JolokiaEndpointTestBase.java

@Test
public void testMXBeanEndpoint() throws Exception {

    ContainerManager cntManager = ContainerManagerLocator.getContainerManager();
    Container cnt = cntManager.getCurrentContainer();

    ServiceEndpoint sep = cnt.getServiceEndpoint(URLServiceEndpoint.JMX_SERVICE_ENDPOINT_IDENTITY);
    JMXServiceEndpoint jmxEndpoint = sep.adapt(JMXServiceEndpoint.class);
    String serviceURL = jmxEndpoint.getServiceURL();
    Assert.assertNotNull("JMX URL not null", serviceURL);

    // Get the local MBeanServer
    MBeanServer server = ServiceLocator.getRequiredService(MBeanServer.class);
    server.registerMBean(new Simple(), SimpleMXBean.OBJECT_NAME);
    try {//from  ww w  .  j a  v  a  2 s.  c o  m
        String[] userpass = RuntimeType.KARAF == RuntimeType.getRuntimeType() ? karafJmx : otherJmx;
        JMXConnector jmxConnector = jmxEndpoint.getJMXConnector(userpass[0], userpass[1], 200,
                TimeUnit.MILLISECONDS);
        MBeanServerConnection con = jmxConnector.getMBeanServerConnection();
        try {
            // Simple string echo
            Object[] params = new Object[] { "Kermit" };
            String[] signature = new String[] { String.class.getName() };
            Object result = con.invoke(SimpleMXBean.OBJECT_NAME, "echo", params, signature);
            Assert.assertEquals("Hello: Kermit", result);

            // Set Bean attribute using CompositeData
            Bean bean = new Bean("Hello", "Foo");
            CompositeData cdata = OpenTypeGenerator.toCompositeData(bean);
            con.setAttribute(SimpleMXBean.OBJECT_NAME, new Attribute("Bean", cdata));

            // Get Bean attribute using CompositeData
            cdata = (CompositeData) con.getAttribute(SimpleMXBean.OBJECT_NAME, "Bean");
            Assert.assertEquals(bean, OpenTypeGenerator.fromCompositeData(Bean.class, cdata));

            // Simple Bean echo using CompositeData
            params = new Object[] { cdata };
            signature = new String[] { CompositeData.class.getName() };
            cdata = (CompositeData) con.invoke(SimpleMXBean.OBJECT_NAME, "echoBean", params, signature);
            Assert.assertEquals(bean, OpenTypeGenerator.fromCompositeData(Bean.class, cdata));
        } finally {
            jmxConnector.close();
        }
    } finally {
        server.unregisterMBean(SimpleMXBean.OBJECT_NAME);
    }
}

From source file:org.apache.openejb.assembler.classic.Assembler.java

public synchronized void destroyApplication(AppInfo appInfo) throws UndeployException {
    deployedApplications.remove(appInfo.path);
    logger.info("destroyApplication.start", appInfo.path);

    fireBeforeApplicationDestroyed(appInfo);

    final AppContext appContext = containerSystem.getAppContext(appInfo.appId);

    for (Map.Entry<String, Object> value : appContext.getBindings().entrySet()) {
        String path = value.getKey();
        if (path.startsWith("global")) {
            path = "java:" + path;
        }//  w w w  .  j  av a  2  s  . c om
        if (!path.startsWith("java:global")) {
            continue;
        }

        try {
            containerSystem.getJNDIContext().unbind(path);
        } catch (NamingException ignored) {
            // no-op
        }
    }
    try {
        containerSystem.getJNDIContext().unbind("java:global");
    } catch (NamingException ignored) {
        // no-op
    }

    EjbResolver globalResolver = new EjbResolver(null, EjbResolver.Scope.GLOBAL);
    for (AppInfo info : deployedApplications.values()) {
        globalResolver.addAll(info.ejbJars);
    }
    SystemInstance.get().setComponent(EjbResolver.class, globalResolver);

    Context globalContext = containerSystem.getJNDIContext();
    UndeployException undeployException = new UndeployException(
            messages.format("destroyApplication.failed", appInfo.path));

    WebAppBuilder webAppBuilder = SystemInstance.get().getComponent(WebAppBuilder.class);
    if (webAppBuilder != null) {
        try {
            webAppBuilder.undeployWebApps(appInfo);
        } catch (Exception e) {
            undeployException.getCauses().add(new Exception("App: " + appInfo.path + ": " + e.getMessage(), e));
        }
    }

    // get all of the ejb deployments
    List<BeanContext> deployments = new ArrayList<BeanContext>();
    for (EjbJarInfo ejbJarInfo : appInfo.ejbJars) {
        for (EnterpriseBeanInfo beanInfo : ejbJarInfo.enterpriseBeans) {
            String deploymentId = beanInfo.ejbDeploymentId;
            BeanContext beanContext = containerSystem.getBeanContext(deploymentId);
            if (beanContext == null) {
                undeployException.getCauses().add(new Exception("deployment not found: " + deploymentId));
            } else {
                deployments.add(beanContext);
            }
        }
    }

    // Just as with startup we need to get things in an
    // order that respects the singleton @DependsOn information
    // Theoreticlly if a Singleton depends on something in its
    // @PostConstruct, it can depend on it in its @PreDestroy.
    // Therefore we want to make sure that if A dependsOn B,
    // that we destroy A first then B so that B will still be
    // usable in the @PreDestroy method of A.

    // Sort them into the original starting order
    deployments = sort(deployments);
    // reverse that to get the stopping order
    Collections.reverse(deployments);

    // stop
    for (BeanContext deployment : deployments) {
        String deploymentID = deployment.getDeploymentID() + "";
        try {
            Container container = deployment.getContainer();
            container.stop(deployment);
        } catch (Throwable t) {
            undeployException.getCauses()
                    .add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
        }
    }

    // undeploy
    for (BeanContext bean : deployments) {
        String deploymentID = bean.getDeploymentID() + "";
        try {
            Container container = bean.getContainer();
            container.undeploy(bean);
            bean.setContainer(null);
        } catch (Throwable t) {
            undeployException.getCauses()
                    .add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
        } finally {
            bean.setDestroyed(true);
        }
    }

    // get the client ids
    List<String> clientIds = new ArrayList<String>();
    for (ClientInfo clientInfo : appInfo.clients) {
        clientIds.add(clientInfo.moduleId);
        for (String className : clientInfo.localClients) {
            clientIds.add(className);
        }
        for (String className : clientInfo.remoteClients) {
            clientIds.add(className);
        }
    }

    if (appContext != null)
        for (WebContext webContext : appContext.getWebContexts()) {
            containerSystem.removeWebContext(webContext);
        }

    // Clear out naming for all components first
    for (BeanContext deployment : deployments) {
        String deploymentID = deployment.getDeploymentID() + "";
        try {
            containerSystem.removeBeanContext(deployment);
        } catch (Throwable t) {
            undeployException.getCauses().add(new Exception(deploymentID, t));
        }

        JndiBuilder.Bindings bindings = deployment.get(JndiBuilder.Bindings.class);
        if (bindings != null)
            for (String name : bindings.getBindings()) {
                try {
                    globalContext.unbind(name);
                } catch (Throwable t) {
                    undeployException.getCauses()
                            .add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
                }
            }
    }

    for (PersistenceUnitInfo unitInfo : appInfo.persistenceUnits) {
        try {
            Object object = globalContext.lookup(PERSISTENCE_UNIT_NAMING_CONTEXT + unitInfo.id);
            globalContext.unbind(PERSISTENCE_UNIT_NAMING_CONTEXT + unitInfo.id);

            // close EMF so all resources are released
            ReloadableEntityManagerFactory remf = ((ReloadableEntityManagerFactory) object);
            remf.close();
            persistenceClassLoaderHandler.destroy(unitInfo.id);
            remf.unregister();
        } catch (Throwable t) {
            undeployException.getCauses()
                    .add(new Exception("persistence-unit: " + unitInfo.id + ": " + t.getMessage(), t));
        }
    }

    for (String sId : moduleIds) {
        try {
            globalContext.unbind(VALIDATOR_FACTORY_NAMING_CONTEXT + sId);
            globalContext.unbind(VALIDATOR_NAMING_CONTEXT + sId);
        } catch (NamingException e) {
            undeployException.getCauses().add(new Exception("validator: " + sId + ": " + e.getMessage(), e));
        }
    }
    moduleIds.clear();

    try {
        if (globalContext instanceof IvmContext) {
            IvmContext ivmContext = (IvmContext) globalContext;
            ivmContext.prune("openejb/Deployment");
            ivmContext.prune("openejb/local");
            ivmContext.prune("openejb/remote");
            ivmContext.prune("openejb/global");
        }
    } catch (NamingException e) {
        undeployException.getCauses().add(new Exception(
                "Unable to prune openejb/Deployments and openejb/local namespaces, this could cause future deployments to fail.",
                e));
    }

    deployments.clear();

    for (String clientId : clientIds) {
        try {
            globalContext.unbind("/openejb/client/" + clientId);
        } catch (Throwable t) {
            undeployException.getCauses().add(new Exception("client: " + clientId + ": " + t.getMessage(), t));
        }
    }

    // mbeans
    MBeanServer server = LocalMBeanServer.get();
    for (String objectName : appInfo.jmx) {
        try {
            ObjectName on = new ObjectName(objectName);
            if (server.isRegistered(on)) {
                server.unregisterMBean(on);
            }
        } catch (InstanceNotFoundException e) {
            logger.warning("can't unregister " + objectName + " because the mbean was not found", e);
        } catch (MBeanRegistrationException e) {
            logger.warning("can't unregister " + objectName, e);
        } catch (MalformedObjectNameException mone) {
            logger.warning("can't unregister because the ObjectName is malformed: " + objectName, mone);
        }
    }

    containerSystem.removeAppContext(appInfo.appId);

    ClassLoaderUtil.destroyClassLoader(appInfo.path);

    if (undeployException.getCauses().size() > 0) {
        throw undeployException;
    }

    logger.debug("destroyApplication.success", appInfo.path);
}

From source file:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java

/** Unregister MBeans loaded by the web application class loader */
protected void unregisterMBeans() {
    try {//from  ww w  .jav  a 2s.  c o m
        JettyJMXRemover jettyJMXRemover = null;
        // If you enable jmx support in jetty 8 or 9  some mbeans (e.g. for the servletholder or sessionmanager) are instanciated in the web application thread 
        // and a reference to the WebappClassloader is stored in a private ObjectMBean._loader which is unfortunatly not the classloader that loaded the class.
        // So for unregisterMBeans to work even for the jetty mbeans we need to access the MBeanContainer class of the jetty container.  
        try {
            jettyJMXRemover = new JettyJMXRemover(getWebApplicationClassLoader());
        } catch (Exception ex) {
            error(ex);
        }

        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
        for (ObjectName objectName : allMBeanNames) {
            try {
                if (jettyJMXRemover != null && jettyJMXRemover.unregisterJettyJMXBean(objectName)) {
                    continue;
                }
                final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
                if (isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
                    warn("MBean '" + objectName + "' was loaded in web application; unregistering");
                    mBeanServer.unregisterMBean(objectName);
                }
            } catch (Exception e) { // MBeanRegistrationException / InstanceNotFoundException
                error(e);
            }
        }
    } catch (Exception e) { // MalformedObjectNameException
        error(e);
    }
}

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  av a 2  s  .  c  om*/
    }
    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;
}

From source file:com.frameworkset.commons.dbcp2.BasicDataSource.java

/**
 * <p>Closes and releases all idle connections that are currently stored in the connection pool
 * associated with this data source.</p>
 *
 * <p>Connections that are checked out to clients when this method is invoked are not affected.
 * When client applications subsequently invoke {@link Connection#close()} to return
 * these connections to the pool, the underlying JDBC connections are closed.</p>
 *
 * <p>Attempts to acquire connections using {@link #getConnection()} after this method has been
 * invoked result in SQLExceptions.</p>
 *
 * <p>This method is idempotent - i.e., closing an already closed BasicDataSource has no effect
 * and does not generate exceptions.</p>
 *
 * @throws SQLException if an error occurs closing idle connections
 *///  w  w w. jav a 2  s .  c  o  m
public synchronized void close() throws SQLException {
    if (registeredJmxName != null) {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        try {
            mbs.unregisterMBean(registeredJmxName);
        } catch (JMException e) {
            log.warn("Failed to unregister the JMX name: " + registeredJmxName, e);
        } finally {
            registeredJmxName = null;
        }
    }
    closed = true;
    GenericObjectPool<?> oldpool = connectionPool;
    connectionPool = null;
    dataSource = null;
    try {
        if (oldpool != null) {
            oldpool.close();
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLException(Utils.getMessage("pool.close.fail"), e);
    }
}