Example usage for javax.management MBeanServerFactory findMBeanServer

List of usage examples for javax.management MBeanServerFactory findMBeanServer

Introduction

In this page you can find the example usage for javax.management MBeanServerFactory findMBeanServer.

Prototype

public synchronized static ArrayList<MBeanServer> findMBeanServer(String agentId) 

Source Link

Document

Return a list of registered MBeanServer objects.

Usage

From source file:com.octo.captcha.j2ee.ImageCaptchaService.java

/**
 * Unregister self from the first MBean server available in the JVM, if any
 *//*w w  w  .j  a v  a  2s .co m*/
public void unregisterFromMBeanServer() {
    if (this.registeredName != null) {
        ArrayList mbeanServers = MBeanServerFactory.findMBeanServer(null);
        MBeanServer mbeanServer = (MBeanServer) mbeanServers.get(0);
        try {
            ObjectName name = new ObjectName(this.registeredName);
            mbeanServer.unregisterMBean(name);
        } catch (MalformedObjectNameException e) {
            // this should never happens
            log.error("Exception trying to create the object name under witch" + " the service is registered",
                    e);
        } catch (InstanceNotFoundException e) {
            // this should never happens
            log.error("Exception trying to unregister the ImageCaptchaFilter from" + " the MBean server", e);
        } catch (MBeanRegistrationException e) {
            // this remains silent for the client
            log.error("Exception trying to unregister the ImageCaptchaFilter from" + "the MBean server", e);
        }
    }
}

From source file:org.rhq.core.domain.server.PersistenceUtility.java

/**
 * Enables the hibernate statistics mbean to provide access to information on the ejb3 persistence tier.
 *
 * @param entityManager an inject entity manager whose session factory will be tracked with these statistics
 * @param server        the MBeanServer where the statistics MBean should be registered; if <code>null</code>, the
 *                      first one in the list returned by MBeanServerFactory.findMBeanServer(null) is used
 * @param flag          true if the stats are to be enabled; false to disable the stats
 *//* www. j a v  a 2s .  c o m*/
public static void enableHibernateStatistics(EntityManager entityManager, MBeanServer server, boolean flag) {
    SessionFactory sessionFactory = null;
    try {
        sessionFactory = PersistenceUtility.getHibernateSession(entityManager).getSessionFactory();

        if (server == null) {
            ArrayList<MBeanServer> list = MBeanServerFactory.findMBeanServer(null);
            server = list.get(0);
        }

        ObjectName objectName = new ObjectName(HIBERNATE_STATISTICS_MBEAN_OBJECTNAME);
        StatisticsService mBean = new StatisticsService();
        mBean.setSessionFactory(sessionFactory);
        server.registerMBean(mBean, objectName);
    } catch (InstanceAlreadyExistsException iaee) {
        LOG.info("Duplicate mbean registration ignored: " + HIBERNATE_STATISTICS_MBEAN_OBJECTNAME);
    } catch (Exception e) {
        LOG.warn("Couldn't register hibernate statistics mbean", e);
    }

    try {
        if (sessionFactory != null) {
            sessionFactory.getStatistics().setStatisticsEnabled(flag);
            LOG.info("Hibernate statistics enable flag set to [" + flag + "]");
        }
    } catch (Exception e) {
        LOG.warn("Couldn't set the statistics enable flag to [" + flag + "]", e);
    }
}

From source file:com.groupon.odo.proxylib.BackupService.java

/**
 * Returns an MBeanServer with the specified name
 *
 * @param name//  w  ww .  j a v a  2s .co m
 * @return
 */
private MBeanServer getServerForName(String name) {
    try {
        MBeanServer mbeanServer = null;
        final ObjectName objectNameQuery = new ObjectName(name + ":type=Service,*");

        for (final MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {
            if (server.queryNames(objectNameQuery, null).size() > 0) {
                mbeanServer = server;
                // we found it, bail out
                break;
            }
        }

        return mbeanServer;
    } catch (Exception e) {
    }

    return null;
}

From source file:org.apache.solr.cloud.api.collections.CollectionsAPIDistributedZkTest.java

private void checkNoTwoShardsUseTheSameIndexDir() throws Exception {
    Map<String, Set<String>> indexDirToShardNamesMap = new HashMap<>();

    List<MBeanServer> servers = new LinkedList<>();
    servers.add(ManagementFactory.getPlatformMBeanServer());
    servers.addAll(MBeanServerFactory.findMBeanServer(null));
    for (final MBeanServer server : servers) {
        Set<ObjectName> mbeans = new HashSet<>();
        mbeans.addAll(server.queryNames(null, null));
        for (final ObjectName mbean : mbeans) {

            try {
                Map<String, String> props = mbean.getKeyPropertyList();
                String category = props.get("category");
                String name = props.get("name");
                if ((category != null && category.toString().equals(Category.CORE.toString()))
                        && (name != null && name.equals("indexDir"))) {
                    String indexDir = server.getAttribute(mbean, "Value").toString();
                    String key = props.get("dom2") + "." + props.get("dom3") + "." + props.get("dom4");
                    if (!indexDirToShardNamesMap.containsKey(indexDir)) {
                        indexDirToShardNamesMap.put(indexDir.toString(), new HashSet<>());
                    }//  w ww .j  a  v a2 s  . c om
                    indexDirToShardNamesMap.get(indexDir.toString()).add(key);
                }
            } catch (Exception e) {
                // ignore, just continue - probably a "Value" attribute
                // not found
            }
        }
    }

    assertTrue(
            "Something is broken in the assert for no shards using the same indexDir - probably something was changed in the attributes published in the MBean of "
                    + SolrCore.class.getSimpleName() + " : " + indexDirToShardNamesMap,
            indexDirToShardNamesMap.size() > 0);
    for (Entry<String, Set<String>> entry : indexDirToShardNamesMap.entrySet()) {
        if (entry.getValue().size() > 1) {
            fail("We have shards using the same indexDir. E.g. shards " + entry.getValue().toString()
                    + " all use indexDir " + entry.getKey());
        }
    }

}

From source file:org.jboss.web.tomcat.tc5.session.JBossCacheCluster.java

/**
 * Get the current Catalina MBean Server.
 * //from w  w w  .  ja va 2 s.  c o m
 * @return
 * @throws Exception
 */
private MBeanServer getMBeanServer() throws Exception {
    if (mserver == null) {
        ArrayList servers = MBeanServerFactory.findMBeanServer(null);
        if (servers.size() > 0) {
            mserver = (MBeanServer) servers.get(0);
        } else {
            mserver = MBeanServerFactory.createMBeanServer();
        }
    }
    return mserver;
}

From source file:com.evolveum.midpoint.gui.api.page.PageBase.java

protected void clearLessJsCache(AjaxRequestTarget target) {
    try {//from   ww w .j a  va  2 s. com
        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(Wro4jConfig.WRO_MBEAN_NAME + ":type=WroConfiguration");
        server.invoke(objectName, "reloadCache", new Object[] {}, new String[] {});
        if (target != null) {
            target.add(PageBase.this);
        }
    } catch (Exception ex) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't clear less/js cache", ex);
        error("Error occurred, reason: " + ex.getMessage());
        if (target != null) {
            target.add(getFeedbackPanel());
        }
    }
}

From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java

/**
 * Try figuring out on which port the server is running ...
 *//*  ww w .  ja va  2  s  . c  o  m*/
@Override
public int getServerPort() {

    if (serverPort == 0) {

        if (isTomcat6()) {
            // tomcat <= 6.x
            try {
                Object server = Class.forName("org.apache.catalina.ServerFactory").getMethod("getServer")
                        .invoke(null);
                Object service = Array.get(server.getClass().getMethod("findServices").invoke(server), 0);
                Object connector = Array.get(service.getClass().getMethod("findConnectors").invoke(service), 0);

                int port = (Integer) connector.getClass().getMethod("getPort").invoke(connector);
                log.info("Tomcat <= 6.x detected, server port: {}", port);
                serverPort = port;
            } catch (Exception e) {
            }
        } else if (isTomcat7()) {
            // tomcat 7.x
            try {
                MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
                ObjectName name = new ObjectName("Catalina", "type", "Server");
                Object server = mBeanServer.getAttribute(name, "managedResource");

                Object service = Array.get(server.getClass().getMethod("findServices").invoke(server), 0);
                Object connector = Array.get(service.getClass().getMethod("findConnectors").invoke(service), 0);

                int port = (Integer) connector.getClass().getMethod("getPort").invoke(connector);
                log.info("Tomcat 7.x detected, server port: {}", port);
                serverPort = port;
            } catch (Exception e) {
            }
        } else {

            log.warn("not running on Tomcat, could not determine server port, returning default of 8080");
            serverPort = 8080;
        }
    }

    return serverPort;

}

From source file:com.cyberway.issue.crawler.Heritrix.java

/**
 * Get MBeanServer.//w w w.  j  a v  a2s . com
 * Currently uses first MBeanServer found.  This will definetly not be whats
 * always wanted. TODO: Make which server settable. Also, if none, put up
 * our own MBeanServer.
 * @return An MBeanServer to register with or null.
 */
public static MBeanServer getMBeanServer() {
    MBeanServer result = null;
    List servers = MBeanServerFactory.findMBeanServer(null);
    if (servers == null) {
        return result;
    }
    for (Iterator i = servers.iterator(); i.hasNext();) {
        MBeanServer server = (MBeanServer) i.next();
        if (server == null) {
            continue;
        }
        result = server;
        break;
    }
    return result;
}

From source file:org.alfresco.solr.SolrInformationServer.java

private String getHttpPort(String defaultPort) {
    try {//from w w  w  .  j a  va2  s.com
        MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
        QueryExp query = Query.and(Query.eq(Query.attr("scheme"), Query.value("http")),
                Query.eq(Query.attr("protocol"), Query.value("HTTP/1.1")));
        Set<ObjectName> objectNames = mBeanServer.queryNames(null, query);

        if (objectNames != null && objectNames.size() > 0) {
            for (ObjectName objectName : objectNames) {
                String name = objectName.toString();
                if (name.indexOf("port=") > -1) {
                    String[] parts = name.split("port=");
                    String port = parts[1];
                    try {
                        Integer.parseInt(port);
                        return port;
                    } catch (NumberFormatException e) {
                        log.error("Error parsing http port:" + port);
                        return defaultPort;
                    }
                }
            }
        }
    } catch (Throwable t) {
        log.error("Error getting https port:", t);
    }

    return defaultPort;
}