Example usage for java.lang.management ManagementFactory getPlatformMBeanServer

List of usage examples for java.lang.management ManagementFactory getPlatformMBeanServer

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getPlatformMBeanServer.

Prototype

public static synchronized MBeanServer getPlatformMBeanServer() 

Source Link

Document

Returns the platform javax.management.MBeanServer MBeanServer .

Usage

From source file:org.lilyproject.lilyservertestfw.launcher.LilyLauncher.java

@Override
public int run(CommandLine cmd) throws Exception {
    int result = super.run(cmd);
    if (result != 0) {
        return result;
    }/*from   w ww  .j  ava2  s . co m*/

    // Forward JDK logging to SLF4J
    LogManager.getLogManager().reset();
    LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler());
    LogManager.getLogManager().getLogger("").setLevel(Level.ALL);

    boolean prepareMode = cmd.hasOption(prepareOption.getOpt());

    //
    // Figure out what to start
    //
    enableHadoop = cmd.hasOption(enableHadoopOption.getOpt());
    enableSolr = cmd.hasOption(enableSolrOption.getOpt());
    enableLily = cmd.hasOption(enableLilyOption.getOpt());
    enableHbaseIndexer = cmd.hasOption(enableHbaseIndexerOption.getOpt());

    // When running prepare mode, or if none of the services are explicitly enabled,
    // we default to starting them all. Otherwise we only start those that are enabled.
    if (!enableHadoop && !enableSolr && !enableLily && !enableHbaseIndexer) {
        enableHadoop = true;
        enableSolr = true;
        enableLily = true;
        enableHbaseIndexer = true;
    }

    if (prepareMode) {
        // (in prepare mode: always start everything)
        System.out.println("-------------------------------------------------------------");
        System.out.println("Running in prepare mode (ignoring --hadoop, --lily, --solr).");
        System.out.println("Will start up, stop, and then snapshot the data directory.");
        System.out.println("Please be patient.");
        System.out.println("-------------------------------------------------------------");

        // If there would be an old template dir, drop it
        TemplateDir.deleteTemplateDir();
    }

    if (enableHadoop) {
        enabledServices.add(hadoopService);
    }
    if (enableSolr) {
        enabledServices.add(solrService);
    }
    if (enableLily) {
        enabledServices.add(lilyService);
    }
    if (enableHbaseIndexer) {
        enabledServices.add(hbaseIndexerLauncherService);
    }

    //
    // Determine directory below which all services will store their data
    //
    if (!prepareMode && cmd.hasOption(dataDirOption.getOpt())) {
        String dataDir = cmd.getOptionValue(dataDirOption.getOpt());
        testHome = new File(dataDir);
        if (testHome.exists() && !testHome.isDirectory()) {
            System.err.println("Specified data directory exists and is not a directory:");
            System.err.println(testHome.getAbsolutePath());
            return -1;
        } else if (testHome.exists() && testHome.isDirectory() && testHome.list().length > 0) {
            System.out.println("Specified data directory exists: will re-use data from previous run!");
        } else if (!testHome.exists()) {
            FileUtils.forceMkdir(testHome);
        }
        // If the user specified the storage directory, do not delete it
        clearData = false;
    } else {
        testHome = TestHomeUtil.createTestHome("lily-launcher-");
        if (!prepareMode) {
            TemplateDir.restoreTemplateDir(testHome);
        }
    }

    //
    // Start the services
    //

    // Informational messages to be outputted after startup has completed.
    List<String> postStartupInfo = new ArrayList<String>();

    for (LauncherService service : enabledServices) {
        if ((result = service.setup(cmd, testHome, clearData)) != 0) {
            return result;
        }
    }

    for (LauncherService service : enabledServices) {
        if ((result = service.start(postStartupInfo)) != 0) {
            return result;
        }
    }

    if (prepareMode) {
        System.out.println("----------------------------------------------------------");
        System.out.println("Prepare mode: stopping all services");
        System.out.println("----------------------------------------------------------");
        lilyService.stop();
        solrService.stop();
        hadoopService.stop();

        System.out.println("----------------------------------------------------------");
        System.out.println("Prepare mode: creating template data directory");
        TemplateDir.makeTemplateDir(testHome);
        System.out.println("----------------------------------------------------------");
        System.out.println("Done");

        System.exit(0);
    }

    // Register MBean
    ManagementFactory.getPlatformMBeanServer().registerMBean(this,
            new ObjectName("LilyLauncher:name=Launcher"));

    // Add shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook()));

    //
    // Finished startup, print messages
    //
    for (String msg : postStartupInfo) {
        System.out.println(msg);
    }

    // redirect all jdk logging (e.g. from Restlet) to log4j (done after startup of all services, to make sure
    // all loggers registered during startup of some services are also redirected)
    JavaLoggingToLog4jRedirector.activate();

    return 0;
}

From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java

/**
 * Try to find a nonssl connector to retrieve shared resources like stylesheets, images etc. Fallback: Use request
 * url./*from w  w  w.j ava2 s . co  m*/
 *
 * @param request
 * @return
 */
private String getLocalURL(final HttpServletRequest request) {

    final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        for (final Object mbean : beanServer.queryMBeans(new ObjectName("*:type=Connector,*"), null)) {
            final ObjectInstance oi = (ObjectInstance) mbean;
            final Boolean isSecure = (Boolean) beanServer.getAttribute(oi.getObjectName(), "secure");
            final String protocol = (String) beanServer.getAttribute(oi.getObjectName(), "protocol");
            final int port = (Integer) beanServer.getAttribute(oi.getObjectName(), "port");
            if (!isSecure && protocol.startsWith("HTTP")) {
                log.debug(String.format("Using unsecured tomcat connector at port %d", port));
                return "http://localhost:" + port;
            }
        }
    } catch (final MalformedObjectNameException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final NullPointerException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final AttributeNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final InstanceNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final MBeanException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final ReflectionException e) {
        log.warn("Could not access JMX mbeans.", e);
    }
    String requestURL = request.getRequestURL().toString();
    log.warn("No mbeans of type '*:type=Connector,*' configured, using request url (assuming non-ssl): "
            + requestURL);
    return requestURL;
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * Get the name of the application server [fleXive] is running on
 *
 * @return name of the application server [fleXive] is running on
 * @since 3.1// w w  w. j  av  a 2 s  . c om
 */
public synchronized static String getApplicationServerName() {
    if (appserver != null)
        return appserver;
    if (System.getProperty("product.name") != null) {
        // Glassfish 2 / Sun AS
        String ver = System.getProperty("product.name");
        if (System.getProperty("com.sun.jbi.domain.name") != null)
            ver += " (Domain: " + System.getProperty("com.sun.jbi.domain.name") + ")";
        appserver = ver;
    } else if (System.getProperty("glassfish.version") != null) {
        // Glassfish 3+
        appserver = System.getProperty("glassfish.version");
    } else if (System.getProperty("jboss.home.dir") != null) {
        appserver = "JBoss (unknown version)";
        boolean found = false;
        try {
            final Class<?> cls = Class.forName("org.jboss.Version");
            Method m = cls.getMethod("getInstance");
            Object v = m.invoke(null);
            Method pr = cls.getMethod("getProperties");
            Map props = (Map) pr.invoke(v);
            String ver = inspectJBossVersionProperties(props);
            found = true;
            appserver = ver;
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        }
        if (!found) {
            // try JBoss 7 MBean lookup
            try {
                final ObjectName name = new ObjectName("jboss.as:management-root=server");
                final Object version = ManagementFactory.getPlatformMBeanServer().getAttribute(name,
                        "releaseVersion");
                if (version != null) {
                    appserver = "JBoss (" + version + ")";
                    found = true;
                }
            } catch (Exception e) {
                // ignore
            }
        }
        if (!found) {
            //try again with a JBoss 6.x specific locations
            try {
                final ClassLoader jbossCL = Class.forName("org.jboss.Main").getClassLoader();
                if (jbossCL.getResource(JBOSS6_VERSION_PROPERTIES) != null) {
                    Properties prop = new Properties();
                    prop.load(jbossCL.getResourceAsStream(JBOSS6_VERSION_PROPERTIES));
                    if (prop.containsKey("version.name")) {
                        appserver = inspectJBossVersionProperties(prop);
                        //noinspection UnusedAssignment
                        found = true;
                    }
                }
            } catch (ClassNotFoundException e) {
                //ignore
            } catch (IOException e) {
                //ignore
            }
        }
    } else if (System.getProperty("openejb.version") != null) {
        // try to get Jetty version
        String jettyVersion = "";
        try {
            final Class<?> cls = Class.forName("org.mortbay.jetty.Server");
            jettyVersion = " (Jetty " + cls.getPackage().getImplementationVersion() + ")";
        } catch (ClassNotFoundException e) {
            // no Jetty version...
        }
        appserver = "OpenEJB " + System.getProperty("openejb.version") + jettyVersion;
    } else if (System.getProperty("weblogic.home") != null) {
        String server = System.getProperty("weblogic.Name");
        String wlVersion = "";
        try {
            final Class<?> cls = Class.forName("weblogic.common.internal.VersionInfo");
            Method m = cls.getMethod("theOne");
            Object serverVersion = m.invoke(null);
            Method sv = m.invoke(null).getClass().getMethod("getImplementationVersion");
            wlVersion = " " + String.valueOf(sv.invoke(serverVersion));
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        }
        if (StringUtils.isEmpty(server))
            appserver = "WebLogic" + wlVersion;
        else
            appserver = "WebLogic" + wlVersion + " (server: " + server + ")";
    } else if (System.getProperty("org.apache.geronimo.home.dir") != null) {
        String gVersion = "";
        try {
            final Class<?> cls = Class.forName("org.apache.geronimo.system.serverinfo.ServerConstants");
            Method m = cls.getMethod("getVersion");
            gVersion = " " + String.valueOf(m.invoke(null));
            m = cls.getMethod("getBuildDate");
            gVersion = gVersion + " (" + String.valueOf(m.invoke(null)) + ")";
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        }
        appserver = "Apache Geronimo " + gVersion;
    } else {
        appserver = "unknown";
    }
    return appserver;
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDataNodeMetrics.java

@Test(timeout = 60000)
public void testTimeoutMetric() throws Exception {
    final Configuration conf = new HdfsConfiguration();
    final Path path = new Path("/test");

    final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();

    final List<FSDataOutputStream> streams = Lists.newArrayList();
    try {/*from   ww w. ja v a  2  s. com*/
        final FSDataOutputStream out = cluster.getFileSystem().create(path, (short) 2);
        final DataNodeFaultInjector injector = Mockito.mock(DataNodeFaultInjector.class);
        Mockito.doThrow(new IOException("mock IOException")).when(injector).writeBlockAfterFlush();
        DataNodeFaultInjector.instance = injector;
        streams.add(out);
        out.writeBytes("old gs data\n");
        out.hflush();

        /* Test the metric. */
        final MetricsRecordBuilder dnMetrics = getMetrics(cluster.getDataNodes().get(0).getMetrics().name());
        assertCounter("DatanodeNetworkErrors", 1L, dnMetrics);

        /* Test JMX datanode network counts. */
        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        final ObjectName mxbeanName = new ObjectName("Hadoop:service=DataNode,name=DataNodeInfo");
        final Object dnc = mbs.getAttribute(mxbeanName, "DatanodeNetworkCounts");
        final String allDnc = dnc.toString();
        assertTrue("expected to see loopback address", allDnc.indexOf("127.0.0.1") >= 0);
        assertTrue("expected to see networkErrors", allDnc.indexOf("networkErrors") >= 0);
    } finally {
        IOUtils.cleanup(LOG, streams.toArray(new Closeable[0]));
        if (cluster != null) {
            cluster.shutdown();
        }
        DataNodeFaultInjector.instance = new DataNodeFaultInjector();
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestNameNodeMXBean.java

@SuppressWarnings({ "unchecked" })
@Test//  w  ww .j a v a2  s  . c o  m
public void testLastContactTime() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1);
    conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 1);
    MiniDFSCluster cluster = null;
    FileSystem localFileSys = null;
    Path dir = null;

    try {
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
        cluster.waitActive();

        FSNamesystem fsn = cluster.getNameNode().namesystem;

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName("Hadoop:service=NameNode,name=NameNodeInfo");

        // Define include file to generate deadNodes metrics
        localFileSys = FileSystem.getLocal(conf);
        Path workingDir = localFileSys.getWorkingDirectory();
        dir = new Path(workingDir, "build/test/data/temp/TestNameNodeMXBean");
        Path includeFile = new Path(dir, "include");
        assertTrue(localFileSys.mkdirs(dir));
        StringBuilder includeHosts = new StringBuilder();
        for (DataNode dn : cluster.getDataNodes()) {
            includeHosts.append(dn.getDisplayName()).append("\n");
        }
        DFSTestUtil.writeFile(localFileSys, includeFile, includeHosts.toString());
        conf.set(DFSConfigKeys.DFS_HOSTS, includeFile.toUri().getPath());
        fsn.getBlockManager().getDatanodeManager().refreshNodes(conf);

        cluster.stopDataNode(0);
        while (fsn.getBlockManager().getDatanodeManager().getNumLiveDataNodes() != 2) {
            Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
        }

        // get attribute deadnodeinfo
        String deadnodeinfo = (String) (mbs.getAttribute(mxbeanName, "DeadNodes"));
        assertEquals(fsn.getDeadNodes(), deadnodeinfo);
        Map<String, Map<String, Object>> deadNodes = (Map<String, Map<String, Object>>) JSON
                .parse(deadnodeinfo);
        assertTrue(deadNodes.size() > 0);
        for (Map<String, Object> deadNode : deadNodes.values()) {
            assertTrue(deadNode.containsKey("lastContact"));
            assertTrue(deadNode.containsKey("decommissioned"));
            assertTrue(deadNode.containsKey("xferaddr"));
        }
    } finally {
        if ((localFileSys != null) && localFileSys.exists(dir)) {
            FileUtils.deleteQuietly(new File(dir.toUri().getPath()));
        }
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:com.espertech.esper.metrics.codahale_metrics.metrics.reporting.JmxReporter.java

/**
 * Creates a new {@link JmxReporter} for the given registry.
 *
 * @param registry    a {@link MetricsRegistry}
 *///from www  .j  a  v  a 2 s . co m
public JmxReporter(MetricsRegistry registry) {
    super(registry);
    this.registeredBeans = new ConcurrentHashMap<MetricName, ObjectName>(100);
    this.server = ManagementFactory.getPlatformMBeanServer();
}

From source file:org.apache.james.protocols.lib.netty.AbstractConfigurableAsyncServer.java

@PostConstruct
public final void init() throws Exception {

    if (isEnabled()) {

        buildSSLContext();/*w w  w  .  j a  va 2 s . com*/
        preInit();
        executionHandler = createExecutionHander();
        bind();

        mbeanServer = ManagementFactory.getPlatformMBeanServer();
        registerMBean();

        getLogger().info("Init " + getServiceType() + " done");

    }

}

From source file:org.apache.cassandra.service.StorageService.java

public StorageService() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {/*ww  w  .  j av  a  2 s  . c o  m*/
        mbs.registerMBean(this, new ObjectName("org.apache.cassandra.db:type=StorageService"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    /* register the verb handlers */
    MessagingService.instance().registerVerbHandlers(Verb.BINARY, new BinaryVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.MUTATION, new RowMutationVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.READ_REPAIR, new ReadRepairVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.READ, new ReadVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.RANGE_SLICE, new RangeSliceVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.INDEX_SCAN, new IndexScanVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.COUNTER_MUTATION, new CounterMutationVerbHandler());
    // see BootStrapper for a summary of how the bootstrap verbs interact
    MessagingService.instance().registerVerbHandlers(Verb.BOOTSTRAP_TOKEN,
            new BootStrapper.BootstrapTokenVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.STREAM_REQUEST, new StreamRequestVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.STREAM_REPLY, new StreamReplyVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.REPLICATION_FINISHED,
            new ReplicationFinishedVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.REQUEST_RESPONSE, new ResponseVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.INTERNAL_RESPONSE, new ResponseVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.TREE_REQUEST, new TreeRequestVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.TREE_RESPONSE,
            new AntiEntropyService.TreeResponseVerbHandler());

    MessagingService.instance().registerVerbHandlers(Verb.GOSSIP_DIGEST_SYN, new GossipDigestSynVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.GOSSIP_DIGEST_ACK, new GossipDigestAckVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.GOSSIP_DIGEST_ACK2,
            new GossipDigestAck2VerbHandler());

    MessagingService.instance().registerVerbHandlers(Verb.DEFINITIONS_ANNOUNCE,
            new DefinitionsAnnounceVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.DEFINITIONS_UPDATE_RESPONSE,
            new DefinitionsUpdateResponseVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.TRUNCATE, new TruncateVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.SCHEMA_CHECK, new SchemaCheckVerbHandler());

    MessagingService.instance().registerVerbHandlers(Verb.PAXOSPREPARE, new PaxosPrepareVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.PAXOSPROMISE, new PaxosPromiseVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.PAXOSACCEPT, new PaxosAcceptVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.PAXOSACCEPTED, new PaxosAcceptedVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.PAXOSDELIVER, new PaxosDeliverVerbHandler());
    MessagingService.instance().registerVerbHandlers(Verb.PAXOSDELIVERRESPONSE,
            new PaxosDeliverResponseVerbHandler());

    // spin up the streaming serivice so it is available for jmx tools.
    if (StreamingService.instance == null)
        throw new RuntimeException("Streaming service is unavailable.");
}

From source file:com.enioka.jqm.tools.Loader.java

private void endOfRun() {
    // Register end date as soon as possible to be as exact as possible (sending mails may take time for example)
    endDate = GregorianCalendar.getInstance(Locale.getDefault());

    // This block is needed for external payloads, as the single runner may forcefully call endOfRun.
    synchronized (this) {
        if (!isDone) {
            isDone = true;/*from w w  w .ja va  2s.  c  o m*/
        } else {
            return;
        }
    }

    // Release the slot so as to allow other job instances to run (first op!)
    if (p != null) {
        p.decreaseNbThread(this.job.getId());
    }

    // Send e-mail before releasing the slot - it may be long
    if (job.getEmail() != null) {
        try {
            Helpers.sendEndMessage(job);
        } catch (Exception e) {
            jqmlogger.warn("An e-mail could not be sent. No impact on the engine.", e);
        }
    }

    // Clean class loader
    ClassLoaderLeakCleaner.clean(Thread.currentThread().getContextClassLoader());

    // Clean JDBC connections
    ClassLoaderLeakCleaner.cleanJdbc(Thread.currentThread());

    // Restore class loader
    if (this.classLoaderToRestoreAtEnd != null) {
        Thread.currentThread().setContextClassLoader(classLoaderToRestoreAtEnd);
        jqmlogger.trace("Class Loader was correctly restored");
    }

    // Clean temp dir (if it exists)
    File tmpDir = new File(FilenameUtils.concat(node.getTmpDirectory(), "" + job.getId()));
    if (tmpDir.isDirectory()) {
        try {
            if (FileUtils.deleteQuietly(tmpDir)) {
                jqmlogger.trace("temp directory was removed");
            } else {
                jqmlogger.warn("Could not remove temp directory " + tmpDir.getAbsolutePath()
                        + "for this job instance. There may be open handlers remaining open.");
            }
        } catch (Exception e) {
            jqmlogger.warn("Could not remove temp directory for unusual reasons", e);
        }
    }

    // Unregister MBean
    if (p != null && this.p.getEngine().loadJmxBeans) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            mbs.unregisterMBean(name);
        } catch (Exception e) {
            jqmlogger.error("Could not unregister JobInstance JMX bean", e);
        }
    }

    // Unregister logger
    unregisterLogger();

    // Part needing DB connection with specific failure handling code.
    endOfRunDb();
}