List of usage examples for java.lang.management ManagementFactory getPlatformMBeanServer
public static synchronized MBeanServer getPlatformMBeanServer()
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
private ArrayList<String> browseMessagesViaJMX(BrokerService brokerService) throws Exception { ArrayList<String> rc = new ArrayList<String>(); ObjectName on = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + brokerService.getBrokerName() + ",destinationType=Queue,destinationName=FOO"); CompositeData[] browse = (CompositeData[]) ManagementFactory.getPlatformMBeanServer().invoke(on, "browse", null, null);/*from w ww . j a v a 2 s.com*/ for (CompositeData cd : browse) { rc.add(cd.get("Text").toString()); } return rc; }
From source file:io.soabase.core.SoaBundle.java
private void addMetrics(Environment environment) { Metric metric = new Gauge<Double>() { private double lastValue = 0.0; @Override//from w w w . j av a 2s .com public Double getValue() { try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem"); AttributeList list = mbs.getAttributes(name, new String[] { "SystemCpuLoad" }); if ((list != null) && (list.size() > 0)) { // unfortunately, this bean reports bad values occasionally. Filter them out. Object value = list.asList().get(0).getValue(); double d = (value instanceof Number) ? ((Number) value).doubleValue() : 0.0; d = ((d > 0.0) && (d < 1.0)) ? d : lastValue; lastValue = d; return d; } } catch (Exception ignore) { // ignore } return lastValue; } }; environment.metrics().register("system.cpu.load", metric); }
From source file:org.red5.server.winstone.WinstoneLoader.java
protected void unregisterJMX() { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try {/*from w w w .ja v a2s . c o m*/ ObjectName oName = new ObjectName("org.red5.server:type=WinstoneLoader"); mbs.unregisterMBean(oName); } catch (Exception e) { log.warn("Exception unregistering", e); } }
From source file:com.web.server.SARDeployer.java
/** * This method extracts the SAR archive and configures for the SAR and starts the services * @param file/*from w ww. j a v a2 s.c om*/ * @param warDirectoryPath * @throws IOException */ public void extractSar(File file, String warDirectoryPath) throws IOException { ZipFile zip = new ZipFile(file); ZipEntry ze = null; String fileName = file.getName(); fileName = fileName.substring(0, fileName.indexOf('.')); fileName += "sar"; String fileDirectory; CopyOnWriteArrayList classPath = new CopyOnWriteArrayList(); Enumeration<? extends ZipEntry> entries = zip.entries(); int numBytes; while (entries.hasMoreElements()) { ze = entries.nextElement(); // //System.out.println("Unzipping " + ze.getName()); String filePath = deployDirectory + "/" + fileName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //System.out.println(fileDirectory); createDirectory(fileDirectory); if (!ze.isDirectory()) { FileOutputStream fout = new FileOutputStream(filePath); byte[] inputbyt = new byte[8192]; InputStream istream = zip.getInputStream(ze); while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) { fout.write(inputbyt, 0, numBytes); } fout.close(); istream.close(); if (ze.getName().endsWith(".jar")) { classPath.add(filePath); } } } zip.close(); URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); WebClassLoader sarClassLoader = new WebClassLoader(urls); for (int index = 0; index < classPath.size(); index++) { System.out.println("file:" + classPath.get(index)); new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader); } new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader); sarsMap.put(fileName, sarClassLoader); System.out.println(sarClassLoader.geturlS()); try { Sar sar = (Sar) sardigester.parse(new InputSource( new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml"))); CopyOnWriteArrayList mbeans = sar.getMbean(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); System.out.println(mbs); ObjectName objName; for (int index = 0; index < mbeans.size(); index++) { Mbean mbean = (Mbean) mbeans.get(index); System.out.println(mbean.getObjectname()); System.out.println(mbean.getCls()); objName = new ObjectName(mbean.getObjectname()); Class helloWorldService = sarClassLoader.loadClass(mbean.getCls()); Object obj = helloWorldService.newInstance(); if (mbs.isRegistered(objName)) { mbs.invoke(objName, "stopService", null, null); //mbs.invoke(objName, "destroy", null, null); mbs.unregisterMBean(objName); } mbs.registerMBean(obj, objName); CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute(); if (attrlist != null) { for (int count = 0; count < attrlist.size(); count++) { MBeanAttribute attr = (MBeanAttribute) attrlist.get(count); Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue()); mbs.setAttribute(objName, mbeanattribute); } } mbs.invoke(objName, "startService", null, null); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedObjectNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceAlreadyExistsException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanRegistrationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotCompliantMBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReflectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAttributeValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (AttributeNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.apache.cassandra.db.ColumnFamilyStore.java
private ColumnFamilyStore(Table table, String columnFamilyName, IPartitioner partitioner, int generation, CFMetaData metadata) {//from w w w.j a v a 2 s . co m assert metadata != null : "null metadata for " + table + ":" + columnFamilyName; this.table = table; columnFamily = columnFamilyName; this.metadata = metadata; this.minCompactionThreshold = new DefaultInteger(metadata.getMinCompactionThreshold()); this.maxCompactionThreshold = new DefaultInteger(metadata.getMaxCompactionThreshold()); this.memtime = new DefaultInteger(metadata.getMemtableFlushAfterMins()); this.memsize = new DefaultInteger(metadata.getMemtableThroughputInMb()); this.memops = new DefaultDouble(metadata.getMemtableOperationsInMillions()); this.rowCacheSaveInSeconds = new DefaultInteger(metadata.getRowCacheSavePeriodInSeconds()); this.keyCacheSaveInSeconds = new DefaultInteger(metadata.getKeyCacheSavePeriodInSeconds()); this.partitioner = partitioner; fileIndexGenerator.set(generation); binaryMemtable = new AtomicReference<BinaryMemtable>(new BinaryMemtable(this)); if (logger.isDebugEnabled()) logger.debug("Starting CFS {}", columnFamily); ICache<Pair<Descriptor, DecoratedKey>, Long> kc = ConcurrentLinkedHashCache.create(0); keyCache = new AutoSavingKeyCache<Pair<Descriptor, DecoratedKey>, Long>(kc, table.name, columnFamilyName); ICache<DecoratedKey, ColumnFamily> rc = metadata.getRowCacheProvider().create(0); rowCache = new AutoSavingRowCache<DecoratedKey, ColumnFamily>(rc, table.name, columnFamilyName); // scan for sstables corresponding to this cf and load them data = new DataTracker(this); Set<DecoratedKey> savedKeys = keyCache.readSaved(); List<SSTableReader> sstables = new ArrayList<SSTableReader>(); for (Map.Entry<Descriptor, Set<Component>> sstableFiles : files(table.name, columnFamilyName, false) .entrySet()) { SSTableReader sstable; try { sstable = SSTableReader.open(sstableFiles.getKey(), sstableFiles.getValue(), savedKeys, data, metadata, this.partitioner); } catch (FileNotFoundException ex) { logger.error( "Missing sstable component in " + sstableFiles + "; skipped because of " + ex.getMessage()); continue; } catch (IOException ex) { logger.error("Corrupt sstable " + sstableFiles + "; skipped", ex); continue; } sstables.add(sstable); } data.addSSTables(sstables); // create the private ColumnFamilyStores for the secondary column indexes indexedColumns = new ConcurrentSkipListMap<ByteBuffer, ColumnFamilyStore>(getComparator()); for (ColumnDefinition info : metadata.getColumn_metadata().values()) { if (info.getIndexType() != null) addIndex(info); } // register the mbean String type = this.partitioner instanceof LocalPartitioner ? "IndexColumnFamilies" : "ColumnFamilies"; mbeanName = "org.apache.cassandra.db:type=" + type + ",keyspace=" + this.table.name + ",columnfamily=" + columnFamily; try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName nameObj = new ObjectName(mbeanName); mbs.registerMBean(this, nameObj); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.codice.ddf.admin.core.impl.SystemPropertiesAdmin.java
private void configureMBean() { mbeanServer = ManagementFactory.getPlatformMBeanServer(); try {/*from w w w. j a v a 2 s . co m*/ objectName = new ObjectName(SystemPropertiesAdminMBean.OBJECT_NAME); } catch (MalformedObjectNameException e) { LOGGER.debug("Exception while creating object name: " + SystemPropertiesAdminMBean.OBJECT_NAME, e); } try { registerSystemPropertiesAdminMBean(); } catch (Exception e) { LOGGER.info("Could not register mbean.", e); } }
From source file:com.cisco.oss.foundation.monitoring.RMIMonitoringAgent.java
private String javaRegister(MonitoringMXBean mxBean, String serviceURL) throws MalformedObjectNameException, IOException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { serverInfo = new ServerInfo(mxBean, configuration); String strAppObjectName = Utility.getObjectName("Application", this.exposedObject); jurl = new JMXServiceURL(serviceURL); appObjectName = new ObjectName(strAppObjectName); jmxEnvironmentMap = null;/*from w w w . ja v a 2 s .c o m*/ int agentPort = configuration.getInt(FoundationMonitoringConstants.MX_PORT); if (!RMIRegistryManager.isRMIRegistryRunning(configuration, agentPort)) { RMIRegistryManager.startRMIRegistry(configuration, agentPort); } else { LOGGER.info("rmiregistry is already running on port " + agentPort); } String serviceName = serviceURL.substring(serviceURL.indexOf("jmxrmi/")); if (isServiceExported(configuration, serviceName)) { MonitoringClient client = new MonitoringClient(serviceURL, strAppObjectName); if (client.connect()) { client.disconnect(); } else { jmxEnvironmentMap = Utility.prepareJmxEnvironmentMap(); LOGGER.info("Found a stale entry for " + serviceName + " in rmiregistry , it will be overwritten"); } } mbs = ManagementFactory.getPlatformMBeanServer(); rmis = JMXConnectorServerFactory.newJMXConnectorServer(jurl, jmxEnvironmentMap, mbs); mbs.registerMBean(mxBean, appObjectName); registerComponentInfo(); registerMonitoringConfiguration(); registerServices(); registerConnections(); registerNotificationDetails(); rmis.start(); if (mxBean instanceof INotifier) { INotifier notifier = (INotifier) mxBean; notifier.setNotificationSender(serverInfo); } serverThread = new ServerRecoveryDaemon(); serverThread.start(); return strAppObjectName; }
From source file:org.eclipse.virgo.web.test.AbstractWebIntegrationTests.java
@AfterClass public static void cleanup() throws Exception { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName( "org.eclipse.virgo.kernel:type=ArtifactModel,artifact-type=plan,name=org.eclipse.virgo.web.tomcat,version=" + CURRENT_VERSION + ",region=global"); try {// www . j a v a2 s . c o m mBeanServer.invoke(objectName, "stop", null, null); mBeanServer.invoke(objectName, "uninstall", null, null); } catch (JMException _) { } }
From source file:com.continuent.tungsten.common.jmx.JmxManager.java
/** * Server helper method to register a JMX MBean. MBeans are registered by a * combination of their MBean interface and the custom mbeanName argument. * The mbeanName permits multiple mBeans to be registered under the same * name.//from w w w . j a va2s .c o m * * @param mbeanInterface The MBean interface this instance implements * @param mbeanName A custom name for this MBean * @throws ServerRuntimeException */ public static void unregisterMBean(Class<?> mbeanInterface, String mbeanName) { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { ObjectName name = generateMBeanObjectName(mbeanInterface.getName(), mbeanName); if (mbs.isRegistered(name)) { logger.info("Unregistering mbean: " + name.toString()); mbs.unregisterMBean(name); } else { logger.warn("Ignoring attempt to unregister unknown mbean: " + name.toString()); } } catch (Exception e) { throw new ServerRuntimeException( "Unable to unregister mbean: interface=" + mbeanInterface + " name=" + mbeanName, e); } }
From source file:com.addthis.hydra.task.output.tree.TreeMapper.java
private void _init(TaskRunConfig runConfig) throws Exception { config = runConfig;/*from ww w . j av a2 s. c om*/ mapstats = new TreeMapperStats(log); resolve(); if (nodeCache != null) TreeCommonParameters.setDefaultCleanQueueSize(nodeCache); if (trashInterval != null) TreeCommonParameters.setDefaultTrashInterval(trashInterval); if (trashTimeLimit != null) TreeCommonParameters.setDefaultTrashTimeLimit(trashTimeLimit); if (storage != null) { if (storage.maxCacheSize != null) TreeCommonParameters.setDefaultMaxCacheSize(storage.maxCacheSize); if (storage.maxCacheMem != null) TreeCommonParameters.setDefaultMaxCacheMem(storage.maxCacheMem); if (storage.maxPageSize != null) TreeCommonParameters.setDefaultMaxPageSize(storage.maxCacheSize); if (storage.maxPageMem != null) TreeCommonParameters.setDefaultMaxPageMem(storage.maxPageMem); if (storage.memSample != null) TreeCommonParameters.setDefaultMemSample(storage.memSample); } if (Strings.isEmpty(localhost)) { localhost = InetAddress.getLocalHost().getHostAddress(); } log.info("[init] java=" + System.getProperty("java.vm.version") + " query=" + enableQuery + " http=" + enableHttp + " jmx=" + enableJmx + " live=" + live); log.info("[init] host=" + localhost + " port=" + port + " target=" + root + " job=" + config.jobId); Path treePath = Paths.get(runConfig.dir, "data"); tree = new ConcurrentTree(Files.initDirectory(treePath.toFile())); bench = new Bench(EnumSet.allOf(BENCH.class), 1000); if (enableHttp) { jetty = new Server(port > 0 ? port++ : 0); jetty.start(); int httpPort = jetty.getConnectors()[0].getLocalPort(); log.info("[init.http] http://" + localhost + ":" + httpPort + "/"); Files.write(new File("job.port"), Bytes.toBytes(Integer.toString(httpPort)), false); } if (enableJmx) { int queryPort = 0; jmxname = new ObjectName("com.addthis.hydra:type=Hydra,node=" + queryPort); ManagementFactory.getPlatformMBeanServer().registerMBean(mapstats, jmxname); ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(port > 0 ? new InetSocketAddress(port++) : null); int jmxport = ss.getLocalPort(); ss.close(); if (jmxport == -1) { log.warn("[init.jmx] failed to get a port"); } else { try { jmxremote = new MBeanRemotingSupport(jmxport); jmxremote.start(); log.info("[init.jmx] port=" + jmxport); } catch (Exception e) { log.warn("[init.jmx] err=" + e); } } } if (config.jobId != null && live && livePort > -1) { QueryEngine liveQueryEngine = new QueryEngine(tree); connectToMesh(treePath.toFile(), runConfig.jobId, liveQueryEngine); } startTime = System.currentTimeMillis(); if (pre != null) { log.warn("pre-chain: " + pre); processBundle(new KVBundle(), pre); } }