Java Code Examples for java.lang.management.ManagementFactory

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project advanced, under directory /server-advanced/src/main/java/org/neo4j/server/advanced/modules/.

Source file: JMXManagementModule.java

  15 
vote

@Override public void start(StringLogger logger){
  try {
    serverManagement=new ServerManagement(server);
    MBeanServer beanServer=ManagementFactory.getPlatformMBeanServer();
    beanServer.registerMBean(serverManagement,createObjectName());
  }
 catch (  Exception e) {
    throw new RuntimeException("Unable to initialize jmx management, see nested exception.",e);
  }
}
 

Example 2

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/utils/.

Source file: Util.java

  15 
vote

/** 
 * Prings memory usage both for heap and non-heap memory.
 */
public static void printMemoryUsage(Logger log){
  MemoryUsage hm=ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  MemoryUsage nhm=ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
  log.info("Heap Memory Usage: " + (hm.getUsed() / 1048576) + "/"+ (hm.getMax() / 1048576)+ " MB");
  log.info("NonHeap Memory Usage: " + (nhm.getUsed() / 1048576) + "/"+ (nhm.getMax() / 1048576)+ " MB");
}
 

Example 3

From project airlift, under directory /jmx/src/main/java/io/airlift/jmx/.

Source file: JmxInspector.java

  15 
vote

@Inject public JmxInspector(Injector injector) throws Exception {
  MBeanServer mBeanServer=ManagementFactory.getPlatformMBeanServer();
  Set<ObjectInstance> instances=mBeanServer.queryMBeans(null,null);
  Multimap<String,String> nameMap=ArrayListMultimap.create();
  for (  ObjectInstance i : instances) {
    nameMap.put(i.getClassName(),i.getObjectName().getCanonicalName());
  }
  ImmutableSortedSet.Builder<InspectorRecord> builder=ImmutableSortedSet.naturalOrder();
  GuiceInjectorIterator injectorIterator=new GuiceInjectorIterator(injector);
  for (  Class<?> clazz : injectorIterator) {
    addConfig(nameMap,clazz,builder);
  }
  inspectorRecords=builder.build();
}
 

Example 4

From project archaius, under directory /archaius-core/src/main/java/com/netflix/config/jmx/.

Source file: ConfigJMXManager.java

  15 
vote

public static ConfigMBean registerConfigMbean(AbstractConfiguration config){
  StandardMBean mbean=null;
  ConfigMBean bean=null;
  try {
    MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
    bean=new BaseConfigMBean(config);
    mbean=new StandardMBean(bean,ConfigMBean.class);
    mbs.registerMBean(mbean,getJMXObjectName(config,bean));
  }
 catch (  NotCompliantMBeanException e) {
    throw new RuntimeException("NotCompliantMBeanException",e);
  }
catch (  InstanceAlreadyExistsException e) {
    throw new RuntimeException("InstanceAlreadyExistsException",e);
  }
catch (  MBeanRegistrationException e) {
    throw new RuntimeException("MBeanRegistrationException",e);
  }
catch (  Exception e) {
    throw new RuntimeException("registerConfigMbeanException",e);
  }
  return bean;
}
 

Example 5

From project Arecibo, under directory /agent/src/main/java/com/ning/arecibo/agent/.

Source file: CoreMonitoringAgent.java

  15 
vote

/** 
 * @param args
 */
public static void main(String[] args){
  Injector injector=Guice.createInjector(Stage.PRODUCTION,new MBeanModule(),new AbstractModule(){
    @Override protected void configure(){
      bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
      bind(MBeanExporter.class).toInstance(MBeanExporter.withPlatformMBeanServer());
      bind(StatusPageHandler.class).asEagerSingleton();
    }
  }
,new LifecycleModule(),new DummyServiceLocatorModule(),new EventPublisherModule(EventSenderType.CLIENT),new EmbeddedJettyJerseyModule(),new RESTEventReceiverModule(EventProcessorImpl.class,"arecibo.agent:name=EventAPI"),new UDPEventReceiverModule(),new GalaxyModule(),new AgentModule());
  CoreMonitoringAgent coreMonitor=injector.getInstance(CoreMonitoringAgent.class);
  try {
    coreMonitor.run();
  }
 catch (  Exception e) {
    log.error(e,"Unable to start. Exiting.");
    System.exit(-1);
  }
}
 

Example 6

From project arquillian-extension-byteman, under directory /src/main/java/org/jboss/arquillian/extension/byteman/impl/client/.

Source file: AgentInstaller.java

  15 
vote

public void install(@Observes(precedence=1) BeforeSuite event){
  try {
    BytemanConfiguration config=BytemanConfiguration.from(descriptorInst.get());
    if (!config.autoInstallAgent()) {
      return;
    }
    try {
      Class<?> mainClass=Thread.currentThread().getContextClassLoader().loadClass("org.jboss.byteman.agent.Main");
      if (!(Boolean)mainClass.getDeclaredField("firstTime").get(null)) {
        return;
      }
    }
 catch (    ClassNotFoundException e) {
    }
    String pid=ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    File bytemanHome=File.createTempFile("byteman","agent");
    bytemanHome.delete();
    bytemanHome.mkdir();
    File bytemanLib=new File(bytemanHome,"lib");
    bytemanLib.mkdirs();
    InputStream bytemanInputJar=ShrinkWrap.create(JavaArchive.class).addPackages(true,"org.jboss.byteman").setManifest(new StringAsset("Manifest-Version: 1.0\n" + "Created-By: Arquillian\n" + "Implementation-Version: 0.0.0.Arq\n"+ "Premain-Class: org.jboss.byteman.agent.Main\n"+ "Agent-Class: org.jboss.byteman.agent.Main\n"+ "Can-Redefine-Classes: true\n"+ "Can-Retransform-Classes: true\n")).as(ZipExporter.class).exportAsInputStream();
    File bytemanJar=new File(bytemanLib,BytemanConfiguration.BYTEMAN_JAR);
    GenerateScriptUtil.copy(bytemanInputJar,new FileOutputStream(bytemanJar));
    VirtualMachine vm=VirtualMachine.attach(pid);
    String agentProperties=config.agentProperties();
    vm.loadAgent(bytemanJar.getAbsolutePath(),"listener:true,port:" + config.clientAgentPort() + (agentProperties != null ? ",prop:" + agentProperties : ""));
    vm.detach();
  }
 catch (  IOException e) {
    throw new RuntimeException("Could not write byteman.jar to disk",e);
  }
catch (  Exception e) {
    throw new RuntimeException("Could not install byteman agent",e);
  }
}
 

Example 7

From project azkaban, under directory /azkaban/src/java/azkaban/app/.

Source file: AzkabanApplication.java

  15 
vote

private void configureMBeanServer(){
  logger.info("Registering MBeans...");
  mbeanServer=ManagementFactory.getPlatformMBeanServer();
  try {
    jobRefresherName=new ObjectName("azkaban.app.jmx.RefreshJobs:name=jobRefresher");
    jobSchedulerName=new ObjectName("azkaban.app.jmx.jobScheduler:name=jobScheduler");
    mbeanServer.registerMBean(new RefreshJobs(this),jobRefresherName);
    logger.info("Bean " + jobRefresherName.getCanonicalName() + " registered.");
    mbeanServer.registerMBean(new JobScheduler(_schedulerManager,_jobManager),jobSchedulerName);
    logger.info("Bean " + jobSchedulerName.getCanonicalName() + " registered.");
  }
 catch (  Exception e) {
    logger.error("Failed to configure MBeanServer",e);
  }
}
 

Example 8

From project bam, under directory /modules/active-queries/active-collection-jee/src/main/java/org/overlord/bam/active/collection/jee/.

Source file: ACManagement.java

  15 
vote

/** 
 * The initialize method.
 */
@PostConstruct public void init(){
  LOG.info("Register the ACManagement MBean: " + _acManager);
  try {
    MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
    ObjectName objname=new ObjectName(OBJECT_NAME_DOMAIN + OBJECT_NAME_MANAGER);
    mbs.registerMBean(this,objname);
  }
 catch (  Exception e) {
    LOG.log(Level.SEVERE,java.util.PropertyResourceBundle.getBundle("active-collection-jee.Messages").getString("ACTIVE-COLLECTION-JEE-1"),e);
  }
  _acManager.addActiveCollectionListener(this);
}
 

Example 9

From project bel-editor, under directory /org.openbel.editor.core/src/org/openbel/editor/core/common/.

Source file: BELUtilities.java

  15 
vote

/** 
 * Returns the virtual machine's process identifier.
 * @return {@code int}
 */
public static int getPID(){
  if (pid == -1) {
    RuntimeMXBean mx=ManagementFactory.getRuntimeMXBean();
    String name=mx.getName();
    String token=name.split("@")[0];
    pid=parseInt(token);
  }
  return pid;
}
 

Example 10

From project bitcask-java, under directory /src/main/java/com/trifork/bitcask/.

Source file: OS.java

  15 
vote

public static int getpid(){
  RuntimeMXBean rtb=ManagementFactory.getRuntimeMXBean();
  String processName=rtb.getName();
  Integer pid=tryPattern1(processName);
  if (pid == null) {
    throw new UnsupportedOperationException("cannot get pid");
  }
  return pid.intValue();
}
 

Example 11

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: BoneCP.java

  15 
vote

/** 
 * Initialises JMX stuff.
 * @param doRegister if true, perform registration, if false unregister
 */
protected void registerUnregisterJMX(boolean doRegister){
  if (this.mbs == null) {
    this.mbs=ManagementFactory.getPlatformMBeanServer();
  }
  try {
    String suffix="";
    if (this.config.getPoolName() != null) {
      suffix="-" + this.config.getPoolName();
    }
    ObjectName name=new ObjectName(MBEAN_BONECP + suffix);
    ObjectName configname=new ObjectName(MBEAN_CONFIG + suffix);
    if (doRegister) {
      if (!this.mbs.isRegistered(name)) {
        this.mbs.registerMBean(this.statistics,name);
      }
      if (!this.mbs.isRegistered(configname)) {
        this.mbs.registerMBean(this.config,configname);
      }
    }
 else {
      if (this.mbs.isRegistered(name)) {
        this.mbs.unregisterMBean(name);
      }
      if (this.mbs.isRegistered(configname)) {
        this.mbs.unregisterMBean(configname);
      }
    }
  }
 catch (  Exception e) {
    logger.error("Unable to start/stop JMX",e);
  }
}
 

Example 12

From project byteman, under directory /sample/src/org/jboss/byteman/sample/helper/.

Source file: JMXHelper.java

  15 
vote

/** 
 * a getter called when the helper is activated which computes the mbean server to use
 */
private static MBeanServer getMBeanServer(){
  MBeanServer mbsToReturn=null;
  String mbeanServerDomainToLookFor=System.getProperty(SYSPROP_MBEAN_SERVER);
  if (mbeanServerDomainToLookFor == null || "*platform*".equals(mbeanServerDomainToLookFor)) {
    mbsToReturn=ManagementFactory.getPlatformMBeanServer();
  }
 else {
    ArrayList<MBeanServer> mbeanServers=MBeanServerFactory.findMBeanServer(null);
    if (mbeanServers != null) {
      for (      MBeanServer mbs : mbeanServers) {
        if (mbeanServerDomainToLookFor.equals(mbs.getDefaultDomain())) {
          mbsToReturn=mbs;
          break;
        }
      }
    }
    if (mbsToReturn == null) {
      mbsToReturn=MBeanServerFactory.createMBeanServer(mbeanServerDomainToLookFor);
    }
  }
  return mbsToReturn;
}
 

Example 13

From project camelpe, under directory /examples/loan-broker-jboss7/src/main/java/net/camelpe/examples/jboss7/loanbroker/queue/.

Source file: JBoss7CamelContextConfiguration.java

  15 
vote

@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);
  }
}
 

Example 14

From project chililog-server, under directory /src/main/java/org/chililog/server/engine/.

Source file: MqService.java

  15 
vote

/** 
 * Starts our HornetQ message queue
 * @throws Exception
 */
public void start() throws Exception {
  if (_hornetqServer != null) {
    _logger.info("Message Queue Already Started.");
    return;
  }
  _logger.info("Starting Message Queue ...");
  AppProperties appProperties=AppProperties.getInstance();
  org.hornetq.core.logging.Logger.setDelegateFactory(new Log4jLogDelegateFactory());
  Configuration config=new ConfigurationImpl();
  config.setPersistenceEnabled(appProperties.getMqJournallingEnabled());
  config.setJournalType(JournalType.NIO);
  config.setJournalDirectory(appProperties.getMqJournalDirectory());
  config.setPagingDirectory(appProperties.getMqPagingDirectory());
  config.setSecurityEnabled(true);
  config.setSecurityInvalidationInterval(appProperties.getMqSecurityInvalidationInterval());
  config.setLogDelegateFactoryClassName(Log4jLogDelegateFactory.class.getName());
  config.setClustered(appProperties.getMqClusteredEnabled());
  config.setClusterUser(appProperties.getMqSystemUsername());
  config.setClusterPassword(appProperties.getMqSystemPassword());
  config.setManagementAddress(new SimpleString("jms.queue.hornetq.management"));
  config.setAcceptorConfigurations(createHornetTransports());
  JAASSecurityManager securityManager=new JAASSecurityManager();
  securityManager.setConfigurationName("not_used");
  javax.security.auth.login.Configuration configObject=new JAASConfiguration();
  securityManager.setConfiguration(configObject);
  CallbackHandler callbackHandlerObject=new JAASCallbackHandler();
  securityManager.setCallbackHandler(callbackHandlerObject);
  _hornetqServer=new HornetQServerImpl(config,ManagementFactory.getPlatformMBeanServer(),securityManager);
  _hornetqServer.start();
  _sl=HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(InVMConnectorFactory.class.getName()));
  _csf=_sl.createSessionFactory();
  String adminRoleName=UserBO.SYSTEM_ADMINISTRATOR_ROLE_NAME;
  _hornetqServer.getHornetQServerControl().addSecuritySettings("jms.queue.hornetq.management",adminRoleName,adminRoleName,adminRoleName,adminRoleName,adminRoleName,adminRoleName,adminRoleName);
  _logger.info("Message Queue Started.");
  return;
}
 

Example 15

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/inputtools/mdl/.

Source file: LoaderServer.java

  15 
vote

public void init() throws IOException {
  String pidLong=ManagementFactory.getRuntimeMXBean().getName();
  String[] items=pidLong.split("@");
  String pid=items[0];
  String chukwaPath=System.getProperty("CHUKWA_HOME");
  StringBuffer pidFilesb=new StringBuffer();
  pidFilesb.append(chukwaPath).append("/var/run/").append(name).append(".pid");
  try {
    File pidFile=new File(pidFilesb.toString());
    pidFileOutput=new FileOutputStream(pidFile);
    pidFileOutput.write(pid.getBytes());
    pidFileOutput.flush();
    FileChannel channel=pidFileOutput.getChannel();
    LoaderServer.lock=channel.tryLock();
    if (LoaderServer.lock != null) {
      log.info("Initlization succeeded...");
    }
 else {
      throw (new IOException());
    }
  }
 catch (  IOException ex) {
    System.out.println("Initializaiton failed: can not write pid file.");
    log.error("Initialization failed...");
    log.error(ex.getMessage());
    System.exit(-1);
    throw ex;
  }
}
 

Example 16

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/.

Source file: ThreadUtil.java

  15 
vote

/** 
 * Gets all threads in the JVM.  This is really a snapshot of all threads at the time this method is called.
 * @return An array of all threads currently running in the JVM.
 */
static public Thread[] getAllThreads(){
  final ThreadGroup root=getRootThreadGroup();
  final ThreadMXBean thbean=ManagementFactory.getThreadMXBean();
  int nAlloc=thbean.getThreadCount();
  int n=0;
  Thread[] threads;
  do {
    nAlloc*=2;
    threads=new Thread[nAlloc];
    n=root.enumerate(threads,true);
  }
 while (n == nAlloc);
  return java.util.Arrays.copyOf(threads,n);
}
 

Example 17

From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/impl/.

Source file: DefaultSmppServer.java

  15 
vote

private void registerMBean(){
  if (configuration == null) {
    return;
  }
  if (configuration.isJmxEnabled()) {
    try {
      ObjectName name=new ObjectName(configuration.getJmxDomain() + ":name=" + configuration.getName());
      ManagementFactory.getPlatformMBeanServer().registerMBean(this,name);
    }
 catch (    Exception e) {
      logger.error("Unable to register DefaultSmppServerMXBean [{}]",configuration.getName(),e);
    }
  }
}
 

Example 18

From project clustermeister, under directory /driver/src/main/java/com/github/nethad/clustermeister/driver/.

Source file: ClustermeisterDriverStartUp.java

  15 
vote

@Override public void run(){
  printUUIDToSystemOut();
  if (isDivertStreamsToFile()) {
    divertStreamsToFile();
    logger.info("Output and Error streams diverted to files.");
  }
 else {
    ShutdownHandler shutdownHandler=new ShutdownHandler(System.in);
    shutdownHandler.start();
    logger.info("System.in shutdown command handler started.");
  }
  JPPFDriver.getInstance().getJobManager().addJobListener(new DriverJobListener(ManagementFactory.getPlatformMBeanServer(),MBeanUtils.objectNameFor(logger,DriverJobManagementMBean.MBEAN_NAME)));
  logger.info("Job listener registered.");
}
 

Example 19

From project collector, under directory /src/test/java/com/ning/metrics/collector/endpoint/resources/.

Source file: JettyTestModule.java

  15 
vote

@Override protected void configure(){
  final ConfigurationObjectFactory configFactory=new CollectorConfigurationObjectFactory(System.getProperties());
  final CollectorConfig config=configFactory.build(AutoFlushConfig.class);
  bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
  install(new AbstractModule(){
    @Override protected void configure(){
      bind(ConfigurationObjectFactory.class).toInstance(configFactory);
      bind(CollectorConfig.class).toInstance(config);
    }
  }
);
  install(new RequestHandlersModule());
  install(new EventCollectorModule());
  install(new RealTimeQueueModule());
  install(new FiltersModule(config));
  install(new ServletModule(){
    @Override protected void configureServlets(){
      final Map<String,String> params=new HashMap<String,String>();
      params.put(PackagesResourceConfig.PROPERTY_PACKAGES,"com.ning.metrics.collector.endpoint");
      serve("*").with(GuiceContainer.class,params);
    }
  }
);
  final MockEventWriter writer=new MockEventWriter();
  bind(MockEventWriter.class).toInstance(writer);
  bind(PersistentWriterFactory.class).toInstance(new MockPersistentWriterFactory(new ThresholdEventWriter(writer,0,1)));
}
 

Example 20

From project cometd, under directory /cometd-java/cometd-java-examples/src/main/java/org/cometd/benchmark/.

Source file: BenchmarkHelper.java

  15 
vote

public BenchmarkHelper(){
  this.operatingSystem=ManagementFactory.getOperatingSystemMXBean();
  this.jitCompiler=ManagementFactory.getCompilationMXBean();
  this.heapMemory=ManagementFactory.getMemoryMXBean();
  List<MemoryPoolMXBean> memoryPools=ManagementFactory.getMemoryPoolMXBeans();
  for (  MemoryPoolMXBean memoryPool : memoryPools) {
    if ("PS Eden Space".equals(memoryPool.getName()) || "Par Eden Space".equals(memoryPool.getName()) || "G1 Eden".equals(memoryPool.getName()))     youngMemoryPool=memoryPool;
 else     if ("PS Survivor Space".equals(memoryPool.getName()) || "Par Survivor Space".equals(memoryPool.getName()) || "G1 Survivor".equals(memoryPool.getName()))     survivorMemoryPool=memoryPool;
 else     if ("PS Old Gen".equals(memoryPool.getName()) || "CMS Old Gen".equals(memoryPool.getName()) || "G1 Old Gen".equals(memoryPool.getName()))     oldMemoryPool=memoryPool;
  }
  hasMemoryPools=youngMemoryPool != null && survivorMemoryPool != null && oldMemoryPool != null;
  List<GarbageCollectorMXBean> garbageCollectors=ManagementFactory.getGarbageCollectorMXBeans();
  for (  GarbageCollectorMXBean garbageCollector : garbageCollectors) {
    if ("PS Scavenge".equals(garbageCollector.getName()) || "ParNew".equals(garbageCollector.getName()) || "G1 Young Generation".equals(garbageCollector.getName()))     youngCollector=garbageCollector;
 else     if ("PS MarkSweep".equals(garbageCollector.getName()) || "ConcurrentMarkSweep".equals(garbageCollector.getName()) || "G1 Old Generation".equals(garbageCollector.getName()))     oldCollector=garbageCollector;
  }
  hasCollectors=youngCollector != null && oldCollector != null;
}
 

Example 21

From project commons-dbcp-jmx, under directory /jdbc3/src/test/java/org/apache/commons/dbcp/.

Source file: AbstractMBeanTest.java

  15 
vote

/** 
 * Open a connection on the platform MBean server before tests.
 * @throws IOException if the connection could not be opened.
 */
@BeforeTest public void prepareMBeanServerConnection() throws IOException {
  jmxConnectorServer=JMXConnectorServerFactory.newJMXConnectorServer(new JMXServiceURL("service:jmx:rmi://"),null,ManagementFactory.getPlatformMBeanServer());
  jmxConnectorServer.start();
  jmxConnector=JMXConnectorFactory.connect(jmxConnectorServer.getAddress());
  mBeanServerConnection=jmxConnector.getMBeanServerConnection();
}
 

Example 22

From project cp-common-utils, under directory /src/com/clarkparsia/common/base/.

Source file: Memory.java

  15 
vote

/** 
 * Detailed memory information logged only at TRACE level.
 */
public static String detailedUsage(){
  StringBuilder sb=new StringBuilder();
  try {
    Formatter formatter=new Formatter(sb);
    formatter.format("%nDETAILED MEMORY INFO%n");
    formatter.format("Heap Memory Usage: %s%n",MEMORY.getHeapMemoryUsage());
    formatter.format("Non-Heap Memory Usage: %s%n",MEMORY.getNonHeapMemoryUsage());
    List<GarbageCollectorMXBean> gcmBeans=ManagementFactory.getGarbageCollectorMXBeans();
    for (    GarbageCollectorMXBean gcmBean : gcmBeans) {
      formatter.format("Name: %s%n",gcmBean.getName());
      formatter.format("\tCollection count: %s%n",gcmBean.getCollectionCount());
      formatter.format("\tCollection time: %s%n",gcmBean.getCollectionTime());
      formatter.format("\tMemory Pools: %s%n",Arrays.toString(gcmBean.getMemoryPoolNames()));
    }
    formatter.format("Memory Pools Info");
    List<MemoryPoolMXBean> mpBeans=ManagementFactory.getMemoryPoolMXBeans();
    for (    MemoryPoolMXBean mpBean : mpBeans) {
      formatter.format("Name: %s%n",mpBean.getName());
      formatter.format("\tUsage: %s%n",mpBean.getUsage());
      formatter.format("\tCollection Usage: %s%n",mpBean.getCollectionUsage());
      formatter.format("\tPeak Usage: %s%n",mpBean.getPeakUsage());
      formatter.format("\tType: %s%n",mpBean.getType());
      formatter.format("\tMemory Manager Names: %s%n",Arrays.toString(mpBean.getMemoryManagerNames()));
    }
  }
 catch (  Exception e) {
    LOGGER.warn("Cannot get memory info",e);
  }
  return sb.toString();
}
 

Example 23

From project dawn-isencia, under directory /com.isencia.passerelle.engine/src/main/java/com/isencia/passerelle/statistics/.

Source file: StatisticsServiceImpl.java

  15 
vote

protected StatisticsServiceImpl(){
  try {
    svr=ManagementFactory.getPlatformMBeanServer();
    start();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 24

From project dawn-isenciaui, under directory /com.isencia.passerelle.workbench.model/src/main/java/com/isencia/passerelle/workbench/model/jmx/.

Source file: RemoteManagerAgent.java

  15 
vote

/** 
 * Call this method to start the agent which will deploy the service on JMX.
 * @throws Exception 
 */
public void start() throws Exception {
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  try {
    try {
      stop(false);
    }
 catch (    Exception ignored) {
    }
    mbs.registerMBean(remoteManager,REMOTE_MANAGER);
    JMXConnectorServer cs=JMXConnectorServerFactory.newJMXConnectorServer(serverUrl,null,mbs);
    cs.start();
    logger.debug("Workflow service started on " + serverUrl);
  }
 catch (  Exception e) {
    logger.error("Cannot connect manager agent to provide rmi access to ptolomy manager",e);
    com.isencia.passerelle.workbench.model.activator.Activator.getDefault().getLog().log(new Status(Status.ERROR,Activator.PLUGIN_ID,"The connection of the workflow service has failed to " + serverUrl + ". No workflows can be run!",e));
    throw e;
  }
}
 

Example 25

From project dawn-workflow, under directory /org.dawb.workbench.jmx/src/org/dawb/workbench/jmx/.

Source file: RemoteWorkbenchAgent.java

  15 
vote

/** 
 * Call this method to start the agent which will deploy the service on JMX.
 */
public void start() throws Exception {
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  try {
    LocateRegistry.createRegistry(currentPort);
  }
 catch (  java.rmi.server.ExportException ne) {
    logger.debug("Found existing registry on " + currentPort);
  }
  try {
    if (mbs.getObjectInstance(REMOTE_WORKBENCH) != null) {
      mbs.unregisterMBean(REMOTE_WORKBENCH);
    }
  }
 catch (  Exception ignored) {
  }
  mbs.registerMBean(remoteManager,REMOTE_WORKBENCH);
  JMXConnectorServer cs=JMXConnectorServerFactory.newJMXConnectorServer(serverUrl,null,mbs);
  cs.start();
  logger.debug("Workbench service started on " + serverUrl);
}
 

Example 26

From project dcm4che, under directory /dcm4che-servlet/src/main/java/org/dcm4che/sample/servlet/.

Source file: EchoSCPServlet.java

  15 
vote

@Override public void init(ServletConfig config) throws ServletException {
  super.init(config);
  try {
    dicomConfig=(DicomConfiguration)Class.forName(config.getInitParameter("dicomConfigurationClass"),false,Thread.currentThread().getContextClassLoader()).newInstance();
    echoSCP=new EchoSCP(dicomConfig,config.getInitParameter("deviceName"));
    echoSCP.start();
    mbean=ManagementFactory.getPlatformMBeanServer().registerMBean(echoSCP,new ObjectName(config.getInitParameter("jmxName")));
  }
 catch (  Exception e) {
    destroy();
    throw new ServletException(e);
  }
}
 

Example 27

From project dozer, under directory /core/src/main/java/org/dozer/jmx/.

Source file: JMXPlatformImpl.java

  15 
vote

private void register(String name,Object bean,ObjectName mbeanObjectName) throws MBeanRegistrationException, NotCompliantMBeanException {
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  try {
    mbs.registerMBean(bean,mbeanObjectName);
    log.info("Dozer JMX MBean [" + name + "] auto registered with the Platform MBean Server");
  }
 catch (  InstanceAlreadyExistsException e) {
    log.info("JMX MBean instance exists, unable to overwrite [{}].",name);
  }
}
 

Example 28

From project EasySOA, under directory /easysoa-registry/easysoa-registry-api/easysoa-remote-frascati/src/main/java/org/easysoa/sca/frascati/.

Source file: RemoteFraSCAtiServiceProvider.java

  15 
vote

/** 
 * @throws Exception 
 */
public void stopFraSCAtiService() throws Exception {
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  ObjectName name;
  try {
    name=new ObjectName("SCA domain:name0=*,*");
    Set<ObjectName> names=mbs.queryNames(name,name);
    for (    ObjectName objectName : names) {
      mbs.unregisterMBean(objectName);
    }
    mbs.unregisterMBean(new ObjectName("org.ow2.frascati.jmx:name=FrascatiJmx"));
  }
 catch (  MalformedObjectNameException e) {
  }
catch (  NullPointerException e) {
  }
catch (  MBeanRegistrationException e) {
  }
catch (  InstanceNotFoundException e) {
  }
  Object lifeCycleController=componentClass.getDeclaredMethod("getFcInterface",new Class<?>[]{String.class}).invoke(factory,new Object[]{"lifecycle-controller"});
  lifecycleClass.getDeclaredMethod("stopFc").invoke(lifeCycleController);
  frascatiService=null;
  frascati=null;
  icl=null;
  Runtime.getRuntime().runFinalization();
  System.gc();
}
 

Example 29

From project en4j, under directory /NBPlatformApp/NoteRepositoryJDBM/src/main/java/com/rubenlaguna/en4j/noterepositoryjdbm/.

Source file: Installer.java

  15 
vote

@Override public void restored(){
  try {
    ManagementFactory.getPlatformMBeanServer().registerMBean(mbean,new ObjectName("com.rubenlaguna.en4j.noterepositoryjdbm:type=JdbmMgmt"));
  }
 catch (  JMException ex) {
  }
}
 

Example 30

From project erjang, under directory /src/main/java/erjang/m/erlang/.

Source file: ErlBif.java

  15 
vote

@BIF static public EObject statistics(EProc proc,EObject spec){
  if (spec == am_wall_clock) {
    long now=System.currentTimeMillis();
    long since_last=now - last_wall_clock;
    long since_epoch=now - wall_clock0;
    last_wall_clock=now;
    return ETuple.make(ERT.box(since_epoch),ERT.box(since_last));
  }
 else   if (spec == am_reductions) {
    long current_reds=proc.reds;
    long since_last=current_reds - last_reductions;
    last_reductions=current_reds;
    return new ETuple2(ERT.box(current_reds),ERT.box(since_last));
  }
 else   if (spec == am_runtime) {
    RuntimeMXBean b=ManagementFactory.getRuntimeMXBean();
    long current_runtime=b.getUptime();
    long since_last=current_runtime - last_runtime;
    last_runtime=current_runtime;
    return new ETuple2(ERT.box(current_runtime),ERT.box(since_last));
  }
 else   if (spec == am_garbage_collection) {
    List<GarbageCollectorMXBean> b=ManagementFactory.getGarbageCollectorMXBeans();
    long num_gcs=0;
    long time_gcs=0;
    for (    GarbageCollectorMXBean bb : b) {
      num_gcs+=bb.getCollectionCount();
      time_gcs+=bb.getCollectionTime();
    }
    return ETuple.make(ERT.box(num_gcs),ERT.box(time_gcs),ERT.box(0));
  }
 else   if (spec == am_run_queue) {
    return ERT.box(0);
  }
  throw new NotImplemented("erlang:statistics(" + spec + ")");
}
 

Example 31

From project fastjson, under directory /src/test/java/com/alibaba/json/test/benchmark/.

Source file: BenchmarkExecutor.java

  15 
vote

public long getYoungGC(){
  try {
    MBeanServer mbeanServer=ManagementFactory.getPlatformMBeanServer();
    ObjectName objectName;
    if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=ParNew"))) {
      objectName=new ObjectName("java.lang:type=GarbageCollector,name=ParNew");
    }
 else     if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=Copy"))) {
      objectName=new ObjectName("java.lang:type=GarbageCollector,name=Copy");
    }
 else {
      objectName=new ObjectName("java.lang:type=GarbageCollector,name=PS Scavenge");
    }
    return (Long)mbeanServer.getAttribute(objectName,"CollectionCount");
  }
 catch (  Exception e) {
    throw new RuntimeException("error");
  }
}
 

Example 32

From project flume, under directory /flume-ng-core/src/main/java/org/apache/flume/instrumentation/.

Source file: MonitoredCounterGroup.java

  15 
vote

protected MonitoredCounterGroup(Type type,String name,String... attrs){
  this.type=type;
  this.name=name;
  Map<String,AtomicLong> counterInitMap=new HashMap<String,AtomicLong>();
  for (  String attribute : attrs) {
    counterInitMap.put(attribute,new AtomicLong(0L));
  }
  counterMap=Collections.unmodifiableMap(counterInitMap);
  startTime=new AtomicLong(0L);
  stopTime=new AtomicLong(0L);
  try {
    ObjectName objName=new ObjectName("org.apache.flume." + type.name().toLowerCase() + ":type="+ this.name);
    ManagementFactory.getPlatformMBeanServer().registerMBean(this,objName);
    LOG.info("Monitoried counter group for type: " + type + ", name: "+ name+ ", registered successfully.");
  }
 catch (  Exception ex) {
    LOG.error("Failed to register monitored counter group for type: " + type + ", name: "+ name,ex);
  }
}
 

Example 33

From project Flume-Hive, under directory /src/java/com/cloudera/flume/agent/.

Source file: MemoryMonitor.java

  15 
vote

private MemoryMonitor(){
  final MemoryMXBean mbean=ManagementFactory.getMemoryMXBean();
  NotificationEmitter emitter=(NotificationEmitter)mbean;
  emitter.addNotificationListener(new NotificationListener(){
    public void handleNotification(    Notification n,    Object hb){
      if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
        long maxMemory=tenuredGenPool.getUsage().getMax();
        long usedMemory=tenuredGenPool.getUsage().getUsed();
        for (        Listener listener : listeners) {
          listener.memoryUsageLow(usedMemory,maxMemory);
        }
      }
    }
  }
,null,null);
}
 

Example 34

From project flume_1, under directory /flume-core/src/main/java/com/cloudera/flume/agent/.

Source file: MemoryMonitor.java

  15 
vote

private MemoryMonitor(){
  final MemoryMXBean mbean=ManagementFactory.getMemoryMXBean();
  NotificationEmitter emitter=(NotificationEmitter)mbean;
  emitter.addNotificationListener(new NotificationListener(){
    public void handleNotification(    Notification n,    Object hb){
      if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
        long maxMemory=tenuredGenPool.getUsage().getMax();
        long usedMemory=tenuredGenPool.getUsage().getUsed();
        for (        Listener listener : listeners) {
          listener.memoryUsageLow(usedMemory,maxMemory);
        }
      }
    }
  }
,null,null);
}
 

Example 35

From project fr.obeo.performance, under directory /fr.obeo.performance/src/fr/obeo/performance/api/.

Source file: MemoryMeter.java

  15 
vote

private long getMemUsage(){
  long usageAmount=0;
  for (  MemoryPoolMXBean mpool : ManagementFactory.getMemoryPoolMXBeans()) {
    MemoryUsage usage=mpool.getUsage();
    usageAmount+=usage.getUsed();
  }
  return usageAmount;
}
 

Example 36

From project galaxy, under directory /src/co/paralleluniverse/common/monitoring/.

Source file: Monitor.java

  15 
vote

public void registerMBean(){
  try {
    LOG.info("Registering MBean {}",name);
    MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
    ObjectName mxbeanName=new ObjectName(name);
    mbs.registerMBean(this,mxbeanName);
    this.registered=true;
  }
 catch (  InstanceAlreadyExistsException ex) {
    throw new RuntimeException(ex);
  }
catch (  MBeanRegistrationException ex) {
    throw new RuntimeException(ex);
  }
catch (  NotCompliantMBeanException ex) {
    throw new AssertionError(ex);
  }
catch (  MalformedObjectNameException ex) {
    throw new AssertionError(ex);
  }
}
 

Example 37

From project gemini.web.gemini-web-container, under directory /org.eclipse.gemini.web.tomcat/src/test/java/org/eclipse/gemini/web/tomcat/internal/.

Source file: TomcatMBeanManagerTests.java

  15 
vote

@Test public void testStartAndStop() throws Exception {
  String domain="foo";
  MBeanServer server=ManagementFactory.getPlatformMBeanServer();
  ObjectName oname=new ObjectName(domain,"bar","baz");
  server.registerMBean(new Foo(),oname);
  TomcatMBeanManager mgr=new TomcatMBeanManager(domain);
  assertTrue(server.isRegistered(oname));
  mgr.start();
  assertFalse(server.isRegistered(oname));
  server.registerMBean(new Foo(),oname);
  assertTrue(server.isRegistered(oname));
  mgr.stop();
  assertFalse(server.isRegistered(oname));
}
 

Example 38

From project glg2d, under directory /src/test/java/glg2d/misc/.

Source file: InstrumentPaint.java

  15 
vote

/** 
 * I hacked this together with duct tape and wire hangers, along with help from these two sites: <a href= "http://sleeplessinslc.blogspot.com/2008/09/java-instrumentation-with-jdk-16x-class.html" >http://sleeplessinslc.blogspot.com/2008/09/java-instrumentation-with-jdk- 16x-class.html</a> and <a href= "http://sleeplessinslc.blogspot.com/2008/07/java-instrumentation.html" >http://sleeplessinslc.blogspot.com/2008/07/java-instrumentation.html</a>.
 */
private static void instrument0() throws Exception {
  File jarFile=File.createTempFile("agent",".jar");
  jarFile.deleteOnExit();
  Manifest manifest=new Manifest();
  Attributes mainAttributes=manifest.getMainAttributes();
  mainAttributes.put(Attributes.Name.MANIFEST_VERSION,"1.0");
  mainAttributes.put(new Attributes.Name("Agent-Class"),InstrumentPaint.class.getName());
  mainAttributes.put(new Attributes.Name("Can-Retransform-Classes"),"true");
  mainAttributes.put(new Attributes.Name("Can-Redefine-Classes"),"true");
  JarOutputStream jos=new JarOutputStream(new FileOutputStream(jarFile),manifest);
  JarEntry agent=new JarEntry(InstrumentPaint.class.getName().replace('.','/') + ".class");
  jos.putNextEntry(agent);
  CtClass ctClass=ClassPool.getDefault().get(InstrumentPaint.class.getName());
  jos.write(ctClass.toBytecode());
  jos.closeEntry();
  JarEntry snip=new JarEntry("instrumentation.snip");
  jos.putNextEntry(snip);
  jos.write(getInstrumentationCode().getBytes());
  jos.closeEntry();
  jos.close();
  String name=ManagementFactory.getRuntimeMXBean().getName();
  VirtualMachine vm=VirtualMachine.attach(name.substring(0,name.indexOf('@')));
  vm.loadAgent(jarFile.getAbsolutePath());
  vm.detach();
}
 

Example 39

From project gnip4j, under directory /core/src/main/java/com/zaubersoftware/gnip4j/api/support/jmx/sun/.

Source file: SunJMXProvider.java

  15 
vote

@Override public final void registerBean(final GnipStream stream,final StreamStats streamStats){
  final MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  try {
    ObjectName mbeanName=getStreamName(stream);
    mbs.registerMBean(new com.zaubersoftware.gnip4j.api.support.jmx.sun.StreamStats(streamStats),mbeanName);
  }
 catch (  InstanceAlreadyExistsException e) {
    throw new IllegalArgumentException(e);
  }
catch (  MBeanRegistrationException e) {
    throw new IllegalArgumentException(e);
  }
catch (  NotCompliantMBeanException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 40

From project heritrix3, under directory /engine/src/main/java/org/archive/crawler/framework/.

Source file: ToeThread.java

  15 
vote

/** 
 * @param t Thread
 * @param pw PrintWriter
 */
static public void reportThread(Thread t,PrintWriter pw){
  ThreadMXBean tmxb=ManagementFactory.getThreadMXBean();
  ThreadInfo info=tmxb.getThreadInfo(t.getId());
  pw.print("Java Thread State: ");
  pw.println(info.getThreadState());
  pw.print("Blocked/Waiting On: ");
  if (info.getLockOwnerId() >= 0) {
    pw.print(info.getLockName());
    pw.print(" which is owned by ");
    pw.print(info.getLockOwnerName());
    pw.print("(");
    pw.print(info.getLockOwnerId());
    pw.println(")");
  }
 else {
    pw.println("NONE");
  }
  StackTraceElement[] ste=t.getStackTrace();
  for (int i=0; i < ste.length; i++) {
    pw.print("    ");
    pw.print(ste[i].toString());
    pw.println();
  }
}
 

Example 41

From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/inputtools/mdl/.

Source file: LoaderServer.java

  15 
vote

public void init() throws IOException {
  String pidLong=ManagementFactory.getRuntimeMXBean().getName();
  String[] items=pidLong.split("@");
  String pid=items[0];
  String chukwaPath=System.getProperty("CHUKWA_HOME");
  StringBuffer pidFilesb=new StringBuffer();
  pidFilesb.append(chukwaPath).append("/var/run/").append(name).append(".pid");
  try {
    File pidFile=new File(pidFilesb.toString());
    pidFileOutput=new FileOutputStream(pidFile);
    pidFileOutput.write(pid.getBytes());
    pidFileOutput.flush();
    FileChannel channel=pidFileOutput.getChannel();
    LoaderServer.lock=channel.tryLock();
    if (LoaderServer.lock != null) {
      log.info("Initlization succeeded...");
    }
 else {
      throw (new IOException());
    }
  }
 catch (  IOException ex) {
    System.out.println("Initializaiton failed: can not write pid file.");
    log.error("Initialization failed...");
    log.error(ex.getMessage());
    System.exit(-1);
    throw ex;
  }
}
 

Example 42

From project HMS, under directory /common/src/main/java/org/apache/hms/common/util/.

Source file: PidFile.java

  15 
vote

public void init(int port) throws IOException {
  String pidLong=ManagementFactory.getRuntimeMXBean().getName();
  String[] items=pidLong.split("@");
  String pid=items[0];
  String chukwaPath=System.getProperty("HMS_HOME");
  StringBuffer pidFilesb=new StringBuffer();
  String pidDir=System.getenv("HMS_PID_DIR");
  if (pidDir == null) {
    pidDir=chukwaPath + File.separator + "var"+ File.separator+ "run";
  }
  pidFilesb.append(pidDir).append(File.separator).append(name).append(".pid");
  try {
    serverSocket=new ServerSocket(port);
    File existsFile=new File(pidDir);
    if (!existsFile.exists()) {
      boolean success=(new File(pidDir)).mkdirs();
      if (!success) {
        throw (new IOException());
      }
    }
    File pidFile=new File(pidFilesb.toString());
    pidFileOutput=new FileOutputStream(pidFile);
    pidFileOutput.write(pid.getBytes());
    pidFileOutput.flush();
    log.debug("Initlization succeeded...");
  }
 catch (  IOException ex) {
    System.out.println("Initialization failed: can not write pid file to " + pidFilesb);
    log.error("Initialization failed...");
    log.error(ex.getMessage());
    System.exit(-1);
    throw ex;
  }
}
 

Example 43

From project Honu, under directory /src/org/apache/hadoop/chukwa/util/.

Source file: PidFile.java

  15 
vote

public void init() throws IOException {
  String pidLong=ManagementFactory.getRuntimeMXBean().getName();
  String[] items=pidLong.split("@");
  String pid=items[0];
  String chukwaPath=System.getProperty("CHUKWA_HOME");
  StringBuffer pidFilesb=new StringBuffer();
  String pidDir=System.getenv("CHUKWA_PID_DIR");
  if (pidDir == null) {
    pidDir=chukwaPath + File.separator + "var"+ File.separator+ "run";
  }
  pidFilesb.append(pidDir).append(File.separator).append(name).append(".pid");
  try {
    File existsFile=new File(pidDir);
    if (!existsFile.exists()) {
      boolean success=(new File(pidDir)).mkdirs();
      if (!success) {
        throw (new IOException());
      }
    }
    File pidFile=new File(pidFilesb.toString());
    pidFileOutput=new FileOutputStream(pidFile);
    pidFileOutput.write(pid.getBytes());
    pidFileOutput.flush();
    FileChannel channel=pidFileOutput.getChannel();
    PidFile.lock=channel.tryLock();
    if (PidFile.lock != null) {
      log.debug("Initlization succeeded...");
    }
 else {
      throw (new IOException());
    }
  }
 catch (  IOException ex) {
    System.out.println("Initializaiton failed: can not write pid file.");
    log.error("Initialization failed...");
    log.error(ex.getMessage());
    System.exit(-1);
    throw ex;
  }
}
 

Example 44

From project ihbase, under directory /src/main/java/org/apache/hadoop/hbase/.

Source file: JmxHelper.java

  15 
vote

/** 
 * Registers an MBean with the platform MBean server. if an MBean with the same name exists it will be unregistered and the provided MBean would replace it
 * @param objectName the object name
 * @param mbean      the mbean class
 */
public static void registerMBean(ObjectName objectName,Object mbean){
  final MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  if (mbs.isRegistered(objectName)) {
    try {
      LOG.info("unregister: " + objectName);
      mbs.unregisterMBean(objectName);
    }
 catch (    InstanceNotFoundException e) {
      throw new IllegalStateException("mbean " + objectName + " failed unregistration",e);
    }
catch (    MBeanRegistrationException e) {
      throw new IllegalStateException("mbean " + objectName + " failed unregistration",e);
    }
  }
  try {
    LOG.info("register: " + objectName);
    mbs.registerMBean(mbean,objectName);
  }
 catch (  InstanceAlreadyExistsException e) {
    throw new IllegalStateException("mbean " + objectName + " failed registration",e);
  }
catch (  MBeanRegistrationException e) {
    throw new IllegalStateException("mbean " + objectName + " failed registration",e);
  }
catch (  NotCompliantMBeanException e) {
    throw new IllegalStateException("mbean " + objectName + " failed registration",e);
  }
}
 

Example 45

From project iPage, under directory /src/test/java/com/github/zhongl/api/.

Source file: IPageTest.java

  15 
vote

@Test public void mbeanRegistration() throws Exception {
  dir=testDir("mbeanRegistration");
  MBeanServer server=ManagementFactory.getPlatformMBeanServer();
  iPage=stringIPage(dir,1,1,Long.MAX_VALUE);
  String domain="com.github.zhongl.ipage";
  String name=iPage.toString();
  ObjectName ephemerons=new ObjectNameBuilder(domain).withType("Ephemerons").withName(name).build();
  ObjectName storage=new ObjectNameBuilder(domain).withType("Storage").withName(name).build();
  ObjectName defragPolicy=new ObjectNameBuilder(domain).withType("DefragPolicy").withName(name).build();
  server.getMBeanInfo(ephemerons);
  server.getMBeanInfo(defragPolicy);
  iPage.stop();
  try {
    server.getMBeanInfo(ephemerons);
    fail("MBean should be unregistered.");
  }
 catch (  InstanceNotFoundException e) {
  }
  try {
    server.getMBeanInfo(storage);
    fail("MBean should be unregistered.");
  }
 catch (  InstanceNotFoundException e) {
  }
  try {
    server.getMBeanInfo(defragPolicy);
    fail("MBean should be unregistered.");
  }
 catch (  InstanceNotFoundException e) {
  }
}
 

Example 46

From project IronCount, under directory /src/main/java/com/jointhegrid/ironcount/manager/.

Source file: WorkerThread.java

  15 
vote

public WorkerThread(WorkloadManager m,Workload w){
  messagesProcessesed=new AtomicLong(0);
  processingTime=new AtomicLong(0);
  status=WorkerThreadStatus.NEW;
  wtId=UUID.randomUUID();
  workload=w;
  goOn=true;
  this.m=m;
  executor=Executors.newFixedThreadPool(1);
  try {
    zk=new ZooKeeper(m.getProps().getProperty(WorkloadManager.ZK_SERVER_LIST),3000,this);
  }
 catch (  IOException ex) {
    logger.error(ex);
    throw new RuntimeException(ex);
  }
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  try {
    mbs.registerMBean(this,new ObjectName(MBEAN_OBJECT_NAME + ",uuid=" + wtId));
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 47

From project jafka, under directory /src/main/java/com/sohu/jafka/utils/.

Source file: Utils.java

  15 
vote

/** 
 * Register the given mbean with the platform mbean server, unregistering any mbean that was there before. Note, this method will not throw an exception if the registration fails (since there is nothing you can do and it isn't fatal), instead it just returns false indicating the registration failed.
 * @param mbean The object to register as an mbean
 * @param name The name to register this mbean with
 * @returns true if the registration succeeded
 */
static boolean registerMBean(Object mbean,String name){
  try {
    MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
synchronized (mbs) {
      ObjectName objName=new ObjectName(name);
      if (mbs.isRegistered(objName)) {
        mbs.unregisterMBean(objName);
      }
      mbs.registerMBean(mbean,objName);
    }
    return true;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return false;
}
 

Example 48

From project jagger, under directory /diagnostics/src/main/java/com/griddynamics/jagger/diagnostics/thread/sampling/.

Source file: RemoteMultiThreadInfoProvider.java

  15 
vote

@Override public Map<String,ThreadInfo[]> getThreadInfo(){
  long startTimeLog=System.currentTimeMillis();
  Map<String,ThreadInfo[]> result=Maps.newHashMap();
  for (  String serviceURL : this.connector.keySet()) {
    try {
      ObjectName srvThrdName=new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME);
      long[] threadIDs=(long[])this.mbs.get(serviceURL).getAttribute(srvThrdName,"AllThreadIds");
      MBeanServerConnection mBeanServerConnection=this.mbs.get(serviceURL);
      CompositeData[] compositeDatas=(CompositeData[])(mBeanServerConnection.invoke(srvThrdName,"getThreadInfo",new Object[]{threadIDs,Integer.MAX_VALUE},new String[]{"[J","int"}));
      ThreadInfo[] threadInfos=new ThreadInfo[compositeDatas.length];
      for (int i=0; i < compositeDatas.length; i++) {
        threadInfos[i]=ThreadInfo.from(compositeDatas[i]);
      }
      result.put(serviceURL,threadInfos);
    }
 catch (    JMException e) {
      log.error("JMException",e);
    }
catch (    IOException e) {
      log.error("IOException",e);
    }
  }
  log.debug("collected threadInfos through jmx for profiling on agent: time {} ms",System.currentTimeMillis() - startTimeLog);
  return result;
}
 

Example 49

From project james, under directory /mailetcontainer-camel/src/main/java/org/apache/james/mailetcontainer/impl/jmx/.

Source file: JMXStateMailetProcessorListener.java

  15 
vote

public JMXStateMailetProcessorListener(String name,AbstractStateMailetProcessor processor) throws MalformedObjectNameException, JMException {
  this.processor=processor;
  this.name=name;
  mbeanserver=ManagementFactory.getPlatformMBeanServer();
  registerMBeans();
}
 

Example 50

From project jboss-modules, under directory /src/main/java/org/jboss/modules/.

Source file: ModuleLoader.java

  15 
vote

RealMBeanReg(){
  server=AccessController.doPrivileged(new PrivilegedAction<MBeanServer>(){
    public MBeanServer run(){
      return ManagementFactory.getPlatformMBeanServer();
    }
  }
);
}
 

Example 51

From project jboss-remoting, under directory /src/main/java/org/jboss/remoting3/remote/.

Source file: RemoteConnectionProvider.java

  15 
vote

RemoteConnectionProvider(final OptionMap optionMap,final ConnectionProviderContext connectionProviderContext) throws IOException {
  super(connectionProviderContext.getExecutor());
  xnio=connectionProviderContext.getXnio();
  sslEnabled=optionMap.get(Options.SSL_ENABLED,true);
  xnioWorker=connectionProviderContext.getXnioWorker();
  this.connectionProviderContext=connectionProviderContext;
  final int messageBufferSize=optionMap.get(RemotingOptions.RECEIVE_BUFFER_SIZE,8192);
  messageBufferPool=false ? new ByteBufferSlicePool(BufferAllocator.BYTE_BUFFER_ALLOCATOR,messageBufferSize,optionMap.get(RemotingOptions.BUFFER_REGION_SIZE,messageBufferSize * 2)) : Buffers.allocatedBufferPool(BufferAllocator.BYTE_BUFFER_ALLOCATOR,messageBufferSize);
  final int framingBufferSize=messageBufferSize + 4;
  framingBufferPool=false ? new ByteBufferSlicePool(BufferAllocator.BYTE_BUFFER_ALLOCATOR,framingBufferSize,optionMap.get(RemotingOptions.BUFFER_REGION_SIZE,framingBufferSize * 2)) : Buffers.allocatedBufferPool(BufferAllocator.BYTE_BUFFER_ALLOCATOR,framingBufferSize);
  try {
    final MBeanServer server=ManagementFactory.getPlatformMBeanServer();
    server.registerMBean(new RemoteConnectionProviderMXBean(){
      public void dumpConnectionState(){
        doDumpConnectionState();
      }
      public String dumpConnectionStateToString(){
        return doGetConnectionState();
      }
    }
,new ObjectName("jboss.remoting.handler","name",connectionProviderContext.getEndpoint().getName() + "-" + hashCode()));
  }
 catch (  Exception e) {
  }
}
 

Example 52

From project jcollectd, under directory /src/main/java/org/collectd/mx/.

Source file: MBeanReceiver.java

  15 
vote

private static String getPid(){
  String name=ManagementFactory.getRuntimeMXBean().getName();
  int ix=name.indexOf('@');
  if (ix == -1) {
    return null;
  }
  return name.substring(0,ix);
}
 

Example 53

From project jesque, under directory /src/main/java/net/greghaines/jesque/worker/.

Source file: WorkerImpl.java

  15 
vote

/** 
 * Creates a unique name, suitable for use with Resque.
 * @return a unique name for this worker
 */
protected String createName(){
  final StringBuilder sb=new StringBuilder(128);
  try {
    sb.append(InetAddress.getLocalHost().getHostName()).append(COLON).append(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]).append('-').append(this.workerId).append(COLON).append(JAVA_DYNAMIC_QUEUES);
    for (    final String queueName : this.queueNames) {
      sb.append(',').append(queueName);
    }
  }
 catch (  UnknownHostException uhe) {
    throw new RuntimeException(uhe);
  }
  return sb.toString();
}
 

Example 54

From project jetty-project, under directory /jetty-jmx-ws/src/test/java/org/mortbay/jetty/jmx/ws/service/impl/.

Source file: JMXServiceTest.java

  15 
vote

@Before public void setUp() throws Exception {
  server=new Server();
  mBeanServer=ManagementFactory.getPlatformMBeanServer();
  mBeanContainer=new MBeanContainer(mBeanServer);
  mBeanContainer.start();
  server.getContainer().addEventListener(mBeanContainer);
  server.addBean(mBeanContainer,true);
  server.addConnector(new SocketConnector());
  ServletContextHandler context=new ServletContextHandler(server,"/");
  ServletHandler servletHandler=context.getServletHandler();
  createServlets(servletHandler);
  server.start();
}
 

Example 55

From project Jetwick, under directory /src/main/java/de/jetwick/util/.

Source file: PermGenDetect.java

  15 
vote

public void memoryUsage(JMXServiceURL target,boolean details) throws Exception {
  Map<String,Object> env=new LinkedHashMap<String,Object>();
  String[] creds={"monitorRole","diff4%&pw"};
  env.put(JMXConnector.CREDENTIALS,creds);
  final JMXConnector connector=JMXConnectorFactory.connect(target,env);
  final MBeanServerConnection remote=connector.getMBeanServerConnection();
  final MemoryMXBean memoryBean=ManagementFactory.newPlatformMXBeanProxy(remote,ManagementFactory.MEMORY_MXBEAN_NAME,MemoryMXBean.class);
  long MB=1024 * 1024;
  long free=(memoryBean.getNonHeapMemoryUsage().getMax() - memoryBean.getNonHeapMemoryUsage().getUsed()) / MB;
  System.out.println(free);
  if (details) {
    RuntimeMXBean remoteRuntime=ManagementFactory.newPlatformMXBeanProxy(remote,ManagementFactory.RUNTIME_MXBEAN_NAME,RuntimeMXBean.class);
    System.out.println("Target VM is: " + remoteRuntime.getName());
    System.out.println("VM version: " + remoteRuntime.getVmVersion());
    System.out.println("VM vendor: " + remoteRuntime.getVmVendor());
    System.out.println("Started since: " + remoteRuntime.getUptime());
    System.out.println("With Classpath: " + remoteRuntime.getClassPath());
    System.out.println("And args: " + remoteRuntime.getInputArguments() + "\n");
    System.out.println("---Memory Usage--- " + new Date());
    System.out.println("Committed Perm Gen:" + memoryBean.getNonHeapMemoryUsage().getCommitted());
    System.out.println("init Perm Gen     :" + memoryBean.getNonHeapMemoryUsage().getInit());
    System.out.println("max Perm Gen      :" + memoryBean.getNonHeapMemoryUsage().getMax());
    System.out.println("Used Perm Gen     :" + memoryBean.getNonHeapMemoryUsage().getUsed() + "\n");
    for (    MemoryPoolMXBean mb : ManagementFactory.getMemoryPoolMXBeans()) {
      System.out.println("\n" + mb.getName());
      System.out.println(mb.getType().toString());
      if (mb.getCollectionUsage() != null)       System.out.println("coll max:" + mb.getCollectionUsage().getMax());
      System.out.println("committed:" + mb.getUsage().getCommitted());
      System.out.println("init:" + mb.getUsage().getInit());
      System.out.println("max :" + mb.getUsage().getMax());
      System.out.println("used:" + mb.getUsage().getUsed());
    }
  }
  connector.close();
}
 

Example 56

From project JitCask, under directory /src/com/afewmoreamps/util/.

Source file: DirectMemoryUtils.java

  15 
vote

/** 
 * @return the setting of -XX:MaxDirectMemorySize as a long. Returns 0 if-XX:MaxDirectMemorySize is not set.
 */
public static long getDirectMemorySize(){
  RuntimeMXBean RuntimemxBean=ManagementFactory.getRuntimeMXBean();
  List<String> arguments=RuntimemxBean.getInputArguments();
  long multiplier=1;
  for (  String s : arguments) {
    if (s.contains("-XX:MaxDirectMemorySize=")) {
      String memSize=s.toLowerCase().replace("-xx:maxdirectmemorysize=","").trim();
      if (memSize.contains("k")) {
        multiplier=1024;
      }
 else       if (memSize.contains("m")) {
        multiplier=1048576;
      }
 else       if (memSize.contains("g")) {
        multiplier=1073741824;
      }
      memSize=memSize.replaceAll("[^\\d]","");
      long retValue=Long.parseLong(memSize);
      return retValue * multiplier;
    }
  }
  return 0;
}
 

Example 57

From project jmx-cli, under directory /src/test/java/org/clamshellcli/jmx/.

Source file: JmxAgent.java

  15 
vote

public void start() throws Exception {
  System.out.println("Starting JmxAgent on RMI port " + port);
  System.setProperty("java.rmi.server.randomIDs","true");
  reg=LocateRegistry.createRegistry(port);
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  HashMap<String,Object> env=new HashMap<String,Object>();
  JMXServiceURL url=new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi");
  server=JMXConnectorServerFactory.newJMXConnectorServer(url,env,mbs);
  System.out.println("Agent RMI connector exported with url " + url.toString());
  server.start();
}
 

Example 58

From project jmxmonitor, under directory /jmxmonitor/src/main/java/uk/co/gidley/jmxmonitor/services/.

Source file: InternalJmx.java

  15 
vote

public InternalJmx(MainConfiguration configuration,RegistryShutdownHub registryShutdownHub) throws InitialisationException, MalformedObjectNameException {
  this.PROPERTY_PREFIX=ThreadManager.PROPERTY_PREFIX;
  registryShutdownHub.addRegistryShutdownListener(this);
  connectorServerName=ObjectName.getInstance("connectors:protocol=rmi");
  MBEAN_SERVER=ManagementFactory.getPlatformMBeanServer();
  start(configuration.getConfiguration());
}
 

Example 59

From project jmxutils, under directory /src/test/java/org/weakref/jmx/guice/.

Source file: TestMBeanModule.java

  15 
vote

@Test public void testExportedInDevelopmentStageToo() throws IntrospectionException, InstanceNotFoundException, ReflectionException {
  final ObjectName name=Util.getUniqueObjectName();
  Injector injector=Guice.createInjector(new MBeanModule(),new AbstractModule(){
    @Override protected void configure(){
      binder().requireExplicitBindings();
      binder().disableCircularProxies();
      bind(SimpleObject.class).asEagerSingleton();
      bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
      ExportBinder.newExporter(binder()).export(SimpleObject.class).as(name.getCanonicalName());
    }
  }
);
  MBeanServer server=injector.getInstance(MBeanServer.class);
  Assert.assertNotNull(server.getMBeanInfo(name));
}
 

Example 60

From project jolokia, under directory /agent/core/src/main/java/org/jolokia/backend/.

Source file: MBeanServerHandler.java

  15 
vote

/** 
 * Use various ways for getting to the MBeanServer which should be exposed via this servlet. <ul> <li>If running in JBoss, use <code>org.jboss.mx.util.MBeanServerLocator</code> <li>Use  {@link javax.management.MBeanServerFactory#findMBeanServer(String)} forregistered MBeanServer and take the <b>first</b> one in the returned list <li>Finally, use the  {@link java.lang.management.ManagementFactory#getPlatformMBeanServer()}</ul>
 * @throws IllegalStateException if no MBeanServer could be found.
 * @param pDetectors detectors which might have extra possibilities to add MBeanServers
 */
private void initMBeanServers(List<ServerDetector> pDetectors){
  mBeanServers=new LinkedHashSet<MBeanServer>();
  for (  ServerDetector detector : pDetectors) {
    detector.addMBeanServers(mBeanServers);
  }
  List<MBeanServer> beanServers=MBeanServerFactory.findMBeanServer(null);
  if (beanServers != null) {
    mBeanServers.addAll(beanServers);
  }
  mBeanServers.add(ManagementFactory.getPlatformMBeanServer());
  mBeanServerConnections=new LinkedHashSet<MBeanServerConnection>();
  for (  MBeanServer server : mBeanServers) {
    mBeanServerConnections.add(server);
  }
}
 

Example 61

From project jsr107tck, under directory /cache-tests/src/test/java/org/jsr107/tck/statistics/.

Source file: JMXTest.java

  15 
vote

public static void main(String[] args) throws Exception {
  System.out.println("Starting -----------------");
  CacheManager cacheManager=Caching.getCacheManager("Yannis");
  MBeanServerRegistrationUtility mBeanServerRegistrationUtility=null;
  try {
    MBeanServer mBeanServer=ManagementFactory.getPlatformMBeanServer();
    cacheManager.createCacheBuilder("cache1").setStatisticsEnabled(true).build();
    cacheManager.createCacheBuilder("cache2").setStatisticsEnabled(true).build();
    mBeanServerRegistrationUtility=new MBeanServerRegistrationUtility(cacheManager,mBeanServer);
    ObjectName search=new ObjectName("javax.cache:*");
    System.out.println("size=" + mBeanServer.queryNames(search,null).size());
    Thread.sleep(60 * 1000);
    System.out.println("Done -----------------");
  }
  finally {
    if (mBeanServerRegistrationUtility != null)     mBeanServerRegistrationUtility.dispose();
    cacheManager.shutdown();
  }
}
 

Example 62

From project karaf, under directory /diagnostic/core/src/main/java/org/apache/karaf/diagnostic/core/internal/.

Source file: ThreadDumpProvider.java

  15 
vote

@Override protected void writeDump(OutputStreamWriter outputStream) throws Exception {
  ThreadMXBean threadMXBean=ManagementFactory.getThreadMXBean();
  outputStream.write("Number of threads: " + threadMXBean.getThreadCount() + "\n");
  for (  ThreadInfo threadInfo : threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(),Integer.MAX_VALUE)) {
    outputStream.write(threadInfo.toString() + "\n\n");
  }
}
 

Example 63

From project KeptCollections, under directory /src/java/net/killa/kept/.

Source file: KeptLock.java

  15 
vote

private boolean lockIt(long t,TimeUnit tu) throws KeeperException, InterruptedException {
  final CountDownLatch latch=new CountDownLatch(1);
  long last=System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(t,tu);
  do {
    if (this.keeper.exists(this.znode,new Watcher(){
      @Override public void process(      WatchedEvent event){
        if (event.getType() == EventType.NodeDeleted)         latch.countDown();
 else         if (event.getType() == EventType.NodeCreated)         ;
 else         throw new RuntimeException("unexpected event type" + event.getType());
      }
    }
) != null) {
      if (!latch.await(t,tu))       try {
        this.keeper.create(this.znode,ManagementFactory.getRuntimeMXBean().getName().getBytes(),this.acl,CreateMode.EPHEMERAL);
        return true;
      }
 catch (      KeeperException.NodeExistsException e) {
      }
catch (      KeeperException e) {
        throw e;
      }
 else       return false;
    }
 else {
      try {
        this.keeper.create(this.znode,ManagementFactory.getRuntimeMXBean().getName().getBytes(),this.acl,CreateMode.EPHEMERAL);
        return true;
      }
 catch (      KeeperException.NodeExistsException e) {
      }
catch (      KeeperException e) {
        throw e;
      }
    }
  }
 while (System.currentTimeMillis() < last);
  return false;
}
 

Example 64

From project kernel_1, under directory /exo.kernel.container/src/main/java/org/exoplatform/container/monitor/jvm/.

Source file: AddJVMComponentsToRootContainer.java

  15 
vote

public void initContainer(ExoContainer container){
  attemptToRegisterMXComponent(container,ManagementFactory.getOperatingSystemMXBean());
  attemptToRegisterMXComponent(container,ManagementFactory.getRuntimeMXBean());
  attemptToRegisterMXComponent(container,ManagementFactory.getThreadMXBean());
  attemptToRegisterMXComponent(container,ManagementFactory.getClassLoadingMXBean());
  attemptToRegisterMXComponent(container,ManagementFactory.getCompilationMXBean());
  attemptToRegisterMXComponent(container,new MemoryInfo());
  attemptToRegisterMXComponent(container,JVMRuntimeInfo.MEMORY_MANAGER_MXBEANS,ManagementFactory.getMemoryManagerMXBeans());
  attemptToRegisterMXComponent(container,JVMRuntimeInfo.MEMORY_POOL_MXBEANS,ManagementFactory.getMemoryPoolMXBeans());
  attemptToRegisterMXComponent(container,JVMRuntimeInfo.GARBAGE_COLLECTOR_MXBEANS,ManagementFactory.getGarbageCollectorMXBeans());
}
 

Example 65

From project kwegg, under directory /ExperioGenerator/src/com/kwegg/extractor/.

Source file: BaseExperioExtractor.java

  15 
vote

public static void main(String[] args){
  RuntimeMXBean RuntimemxBean=ManagementFactory.getRuntimeMXBean();
  List<String> aList=RuntimemxBean.getInputArguments();
  for (int i=0; i < aList.size(); i++) {
    System.out.println(aList.get(i));
  }
  String phrase="In this evening of dueling announcements (RED announced their compact high-res camera system tonight as well), Canon has shown that it? serious in the area of digital cinema with its new Cinema EOS system. The first camera in the line is the C300, a compact camera that, contrary to expectations, doesn? produce a 4K image. They?e instead focused on maximizing the performance of a Super 35-sized sensor producing 1080p footage.";
  try {
    BaseExperio[] exps=BaseExperioExtractor.getInstance().extractExperios(phrase);
    for (    BaseExperio exp : exps) {
      System.out.println(exp.toString());
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 66

From project Lily, under directory /global/hbase-util/src/main/java/org/lilyproject/util/hbase/metrics/.

Source file: MBeanUtil.java

  15 
vote

public static ObjectName registerMBean(final String serviceName,final String nameName,final Object theMbean){
  final MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  ObjectName name=getMBeanName(serviceName,nameName);
  try {
    mbs.registerMBean(theMbean,name);
    return name;
  }
 catch (  InstanceAlreadyExistsException ie) {
  }
catch (  Exception e) {
    throw new RuntimeException(e);
  }
  return null;
}
 

Example 67

From project log4mongo-java, under directory /src/main/java/org/log4mongo/.

Source file: LoggingEventBsonifierImpl.java

  15 
vote

private void setupNetworkInfo(){
  hostInfo.put(KEY_PROCESS,ManagementFactory.getRuntimeMXBean().getName());
  try {
    hostInfo.put(KEY_HOSTNAME,InetAddress.getLocalHost().getHostName());
    hostInfo.put(KEY_IP,InetAddress.getLocalHost().getHostAddress());
  }
 catch (  UnknownHostException e) {
    LogLog.warn(e.getMessage());
  }
}
 

Example 68

From project logback, under directory /logback-access/src/main/java/ch/qos/logback/access/filter/.

Source file: CountingFilter.java

  15 
vote

@Override public void start(){
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  try {
    ObjectName on=new ObjectName(domain + ":Name=" + getName());
    StandardMBean mbean=new StandardMBean(accessStatsImpl,StatisticalView.class);
    if (mbs.isRegistered(on)) {
      mbs.unregisterMBean(on);
    }
    mbs.registerMBean(mbean,on);
    super.start();
  }
 catch (  Exception e) {
    addError("Failed to create mbean",e);
  }
}
 

Example 69

From project ManalithBot, under directory /ManalithBot/src/main/java/org/manalith/ircbot/plugin/admin/.

Source file: AdminPlugin.java

  15 
vote

@Override public void onMessage(MessageEvent event){
  String message=event.getMessage();
  Channel channel=event.getChannel();
  if (isAdmin(event.getUser())) {
    if (message.equals("[email protected]")) {
      int i=0;
      for (      User user : channel.getUsers()) {
        if (!channel.getOps().contains(user) && !channel.getSuperOps().contains(user) && !channel.getOwners().contains(user)) {
          channel.op(user);
          i++;
        }
      }
      if (i == 0) {
        event.respond("??? ?????? ??? ??? ??????.");
      }
    }
 else     if (message.equals("!uptime")) {
      RuntimeMXBean bean=ManagementFactory.getRuntimeMXBean();
      long upTime=bean.getUptime();
      event.respond(String.format("Up Time = %d (ms)",upTime));
    }
 else     if (message.equals("!quit")) {
      event.getBot().quitServer();
      System.exit(-1);
    }
  }
}
 

Example 70

From project maven-surefire, under directory /surefire-integration-tests/src/test/resources/fork-fail/src/test/java/forkMode/.

Source file: Test1.java

  15 
vote

public static void dumpPidFile(TestCase test) throws IOException {
  String fileName=test.getName() + "-pid";
  File target=new File("target");
  if (!(target.exists() && target.isDirectory())) {
    target=new File(".");
  }
  File pidFile=new File(target,fileName);
  FileWriter fw=new FileWriter(pidFile);
  String pid=ManagementFactory.getRuntimeMXBean().getName();
  fw.write(pid);
  fw.flush();
  fw.close();
}
 

Example 71

From project mcore, under directory /src/com/massivecraft/mcore4/xlib/mongodb/.

Source file: DBPortPool.java

  15 
vote

Holder(MongoOptions options){
  _options=options;
{
    MBeanServer temp=null;
    try {
      temp=ManagementFactory.getPlatformMBeanServer();
    }
 catch (    Throwable t) {
    }
    _server=temp;
  }
}
 

Example 72

From project Metamorphosis, under directory /metamorphosis-commons/src/main/java/com/taobao/common/store/util/.

Source file: MyMBeanServer.java

  15 
vote

private MyMBeanServer(){
  try {
    final boolean useJmx=Boolean.parseBoolean(System.getProperty("store4j.useJMX","false"));
    if (useJmx) {
      mbs=ManagementFactory.getPlatformMBeanServer();
    }
  }
 catch (  final Exception e) {
    log.error("create MBServer error",e);
  }
}
 

Example 73

From project meteo, under directory /core/src/main/java/com/ning/metrics/meteo/binder/.

Source file: RealtimeSystemModule.java

  15 
vote

/** 
 * Contributes bindings and other configurations for this module to  {@code binder}. <p/> <p><strong>Do not invoke this method directly</strong> to install submodules. Instead use {@link com.google.inject.Binder#install(com.google.inject.Module)}, which ensures that  {@link com.google.inject.Provides provider methods} arediscovered.
 */
@Override public void configure(final Binder binder){
  binder.bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
  binder.bind(JacksonJsonProvider.class).asEagerSingleton();
  final RealtimeSystemConfig config=new ConfigurationObjectFactory(System.getProperties()).build(RealtimeSystemConfig.class);
  binder.bind(RealtimeSystemConfig.class).toInstance(config);
  final Configuration configuration=new Configuration();
  if (!config.getEsperConfigurationFile().equals("")) {
    configuration.configure(new File(config.getEsperConfigurationFile()));
  }
  binder.bind(EPServiceProvider.class).toInstance(EPServiceProviderManager.getDefaultProvider(configuration));
  configureFromFile(binder,config.getConfigurationFile());
}
 

Example 74

From project mungbean, under directory /mungbean-java/src/main/java/mungbean/.

Source file: Pid.java

  15 
vote

public static int guessPid(){
  RuntimeMXBean rtb=ManagementFactory.getRuntimeMXBean();
  String processName=rtb.getName();
  Pattern pattern=Pattern.compile("^([0-9]+)@.+$",Pattern.CASE_INSENSITIVE);
  Matcher matcher=pattern.matcher(processName);
  if (matcher.matches()) {
    return new Integer(Integer.parseInt(matcher.group(1)));
  }
  return (int)TimeSource.instance().startTime();
}
 

Example 75

From project ning-service-skeleton, under directory /core/src/main/java/com/ning/jetty/core/server/.

Source file: HttpServer.java

  15 
vote

public void configure(final CoreConfig config,final Iterable<EventListener> eventListeners,final Map<FilterHolder,String> filterHolders){
  server.setStopAtShutdown(true);
  configureJMX(ManagementFactory.getPlatformMBeanServer());
  configureMainConnector(config.isJettyStatsOn(),config.getServerHost(),config.getServerPort());
  if (config.isSSLEnabled()) {
    configureSslConnector(config.isJettyStatsOn(),config.getServerSslPort(),config.getSSLkeystoreLocation(),config.getSSLkeystorePassword());
  }
  configureThreadPool(config);
  final HandlerCollection handlers=new HandlerCollection();
  final ServletContextHandler servletContextHandler=createServletContextHandler(config.getResourceBase(),eventListeners,filterHolders);
  handlers.addHandler(servletContextHandler);
  final RequestLogHandler logHandler=createLogHandler(config);
  handlers.addHandler(logHandler);
  final HandlerList rootHandlers=new HandlerList();
  rootHandlers.addHandler(handlers);
  server.setHandler(rootHandlers);
}
 

Example 76

From project nuxeo-dam, under directory /nuxeo-dam-web/src/test/java/org/nuxeo/dam/webapp/fileimporter/.

Source file: TestZipImporter.java

  15 
vote

@After public void checkShutdown(){
  Framework.getLocalService(EventService.class).waitForAsyncCompletion();
  ThreadMXBean threadMgmt=ManagementFactory.getThreadMXBean();
  boolean stillRunning=false;
  for (  ThreadInfo info : threadMgmt.dumpAllThreads(false,false)) {
    String threadName=info.getThreadName();
    if (isRunningAsyncThread(info)) {
      Throwable context=new Throwable("Thread stack trace");
      context.setStackTrace(info.getStackTrace());
      log.warn(threadName + " is still running",context);
      stillRunning=true;
    }
  }
  if (stillRunning) {
    throw new Error("event services async thread are still running");
  }
}
 

Example 77

From project nuxeo-jsf, under directory /nuxeo-platform-webapp-base/src/main/java/org/nuxeo/ecm/webapp/seam/.

Source file: NuxeoSeamFlusher.java

  15 
vote

protected void invalidateWebSessions() throws IOException, MalformedObjectNameException {
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  for (  ObjectInstance oi : mbs.queryMBeans(new ObjectName("Catalina:type=Manager,path=/nuxeo,host=*"),null)) {
    WebSessionFlusher flusher=JMX.newMBeanProxy(mbs,oi.getObjectName(),WebSessionFlusher.class);
    StringTokenizer tokenizer=new StringTokenizer(flusher.listSessionIds()," ");
    while (tokenizer.hasMoreTokens()) {
      String id=tokenizer.nextToken();
      flusher.expireSession(id);
    }
  }
}
 

Example 78

From project nuxeo-tycho-osgi, under directory /nuxeo-runtime/nuxeo-runtime-management/src/main/java/org/nuxeo/runtime/management/.

Source file: ServerLocatorService.java

  15 
vote

protected void doUnregisterLocator(ServerLocatorDescriptor descriptor){
  servers.remove(descriptor.domainName);
  if (descriptor.isDefault) {
    defaultServer=ManagementFactory.getPlatformMBeanServer();
  }
}
 

Example 79

From project obpro_team_p, under directory /twitter/twitter4j-core/src/test/java/twitter4j/.

Source file: MBeanServerRunner.java

  15 
vote

public static void main(String[] args) throws Exception {
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  ObjectName name=new ObjectName("twitter4j.mbean:type=APIStatistics");
  ObjectName name2=new ObjectName("twitter4j.mbean:type=APIStatisticsOpenMBean");
  APIStatistics statsMBean=new APIStatistics(100);
  mbs.registerMBean(statsMBean,name);
  APIStatisticsOpenMBean openMBean=new APIStatisticsOpenMBean(statsMBean);
  mbs.registerMBean(openMBean,name2);
  for (int i=0; i < 10; i++) {
    statsMBean.methodCalled("foo",5,true);
    statsMBean.methodCalled("bar",2,true);
    statsMBean.methodCalled("baz",10,true);
    statsMBean.methodCalled("foo",2,false);
  }
  Thread.sleep(1000 * 60 * 60);
}
 

Example 80

From project ODE-X, under directory /cli/src/test/java/org/apache/ode/cli/.

Source file: CLITest.java

  15 
vote

@BeforeClass public static void setUpBeforeClass() throws Exception {
  ServerSocket server=new ServerSocket(0);
  port=server.getLocalPort();
  server.close();
  LocateRegistry.createRegistry(port);
  log.info("Registry created");
  JMXServiceURL address=new JMXServiceURL("service:jmx:rmi://localhost:" + port + "/jndi/rmi://localhost:"+ port+ "/jmxrmi");
  log.log(Level.INFO,"JMXServer address:{0} ",address);
  Map environment=null;
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  cntorServer=JMXConnectorServerFactory.newJMXConnectorServer(address,environment,mbs);
  mbs.registerMBean(new RepositoryImpl(),ObjectName.getInstance(Repository.OBJECTNAME));
  cntorServer.start();
  log.info("JMXServer started");
}
 

Example 81

From project org.openscada.aurora, under directory /org.openscada.utils.deadlogger/src/org/openscada/utils/deadlogger/.

Source file: JmxDetector.java

  15 
vote

protected ThreadMXBean lookup() throws IOException {
  if (this.hostname == null) {
    return ManagementFactory.getThreadMXBean();
  }
 else {
    final Map<Object,Object> localHashMap=new HashMap<Object,Object>();
    final String[] arrayOfString=new String[2];
    arrayOfString[0]="";
    arrayOfString[1]="";
    localHashMap.put("jmx.remote.credentials",arrayOfString);
    final JMXServiceURL localJMXServiceURL=new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + this.hostname + ":"+ this.port+ "/jmxrmi");
    this.localJMXConnector=JMXConnectorFactory.connect(localJMXServiceURL);
    final MBeanServerConnection localMBeanServerConnection=this.localJMXConnector.getMBeanServerConnection();
    return ManagementFactory.newPlatformMXBeanProxy(localMBeanServerConnection,"java.lang:type=Threading",ThreadMXBean.class);
  }
}
 

Example 82

From project orientdb, under directory /server/src/main/java/com/orientechnologies/orient/server/.

Source file: OServer.java

  15 
vote

public OServer() throws ClassNotFoundException, MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
  threadGroup=new ThreadGroup("OrientDB Server");
  OCommandManager.instance().register(OCommandScript.class,OCommandExecutorScript.class);
  OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(true);
  System.setProperty("com.sun.management.jmxremote","true");
  MBeanServer mBeanServer=ManagementFactory.getPlatformMBeanServer();
  mBeanServer.registerMBean(OProfiler.getInstance().startRecording(),new ObjectName("OrientDB:type=Profiler"));
  managedServer=new OrientServer();
  mBeanServer.registerMBean(managedServer,new ObjectName("OrientDB:type=Server"));
  shutdownHook=new OServerShutdownHook();
}
 

Example 83

From project penrose-server, under directory /services/JMX/SERVICE-INF/src/java/org/safehaus/penrose/management/.

Source file: PenroseJMXService.java

  15 
vote

public void init() throws Exception {
  super.init();
  ServiceConfig serviceConfig=getServiceConfig();
  String s=serviceConfig.getParameter(RMI_PORT);
  rmiPort=s == null ? PenroseClient.DEFAULT_RMI_PORT : Integer.parseInt(s);
  s=serviceConfig.getParameter(RMI_TRANSPORT_PORT);
  rmiTransportPort=s == null ? PenroseClient.DEFAULT_RMI_TRANSPORT_PORT : Integer.parseInt(s);
  mbeanServer=ManagementFactory.getPlatformMBeanServer();
  penroseService=new PenroseService(this,serviceContext.getPenroseServer());
  penroseService.init();
  if (rmiPort > 0) {
    LocateRegistry.createRegistry(rmiPort);
    String url="service:jmx:rmi://localhost";
    if (rmiTransportPort != PenroseClient.DEFAULT_RMI_TRANSPORT_PORT)     url+=":" + rmiTransportPort;
    url+="/jndi/rmi://localhost";
    if (rmiPort != PenroseClient.DEFAULT_RMI_PORT)     url+=":" + rmiPort;
    url+="/penrose";
    JMXServiceURL serviceURL=new JMXServiceURL(url);
    authenticator=new PenroseAuthenticator(serviceContext.getPenroseServer().getPenrose());
    HashMap<String,Object> environment=new HashMap<String,Object>();
    environment.put(JMXConnectorServer.AUTHENTICATOR,authenticator);
    connectorServer=new PenroseConnectorServer(serviceURL,environment,mbeanServer);
    connectorServer.start();
    log.warn("Listening to port " + rmiPort + " (RMI).");
    if (rmiTransportPort != PenroseClient.DEFAULT_RMI_TRANSPORT_PORT)     log.warn("Listening to port " + rmiTransportPort + " (RMI Transport).");
  }
}
 

Example 84

From project perf4j, under directory /src/test/java/org/perf4j/log4j/.

Source file: JmxAppenderTest.java

  15 
vote

public void testCollisionDonothing() throws Exception {
  MBeanServer server=ManagementFactory.getPlatformMBeanServer();
  ObjectName statisticsMBeanName=new ObjectName(StatisticsExposingMBean.DEFAULT_MBEAN_NAME);
  initJmxMBean();
  assertTrue(server.isRegistered(statisticsMBeanName));
  MBeanInfo mbeanInfo=server.getMBeanInfo(statisticsMBeanName);
  assertTrue(mbeanInfo.toString(),mbeanInfo.getAttributes().length == 1 * 6);
  try {
    JmxAttributeStatisticsAppender appender=new JmxAttributeStatisticsAppender();
    appender.setTagNamesToExpose("donothing1,donothing2,donothing3");
    appender.activateOptions();
    fail("should cause an exception");
  }
 catch (  Exception ex) {
    assertTrue(true);
  }
  mbeanInfo=server.getMBeanInfo(statisticsMBeanName);
  assertTrue(mbeanInfo.toString(),mbeanInfo.getAttributes().length == 1 * 6);
}
 

Example 85

From project pillage, under directory /pillage-core/src/main/java/com/ticketfly/pillage/.

Source file: StatsCollectorImpl.java

  15 
vote

/** 
 * Refer to the static final strings for the jvm stats returned.
 * @return
 */
public Map<String,Double> getJvmStats(){
  MemoryMXBean memory=ManagementFactory.getMemoryMXBean();
  ThreadMXBean threads=ManagementFactory.getThreadMXBean();
  RuntimeMXBean runtime=ManagementFactory.getRuntimeMXBean();
  ClassLoadingMXBean classes=ManagementFactory.getClassLoadingMXBean();
  Map<String,Double> map=new HashMap<String,Double>();
  MemoryUsage heapUsed=memory.getHeapMemoryUsage();
  map.put(HEAP_USED_INIT,(double)heapUsed.getInit() / (1024 * 1024));
  map.put(HEAP_USED_MAX,(double)heapUsed.getMax() / (1024 * 1024));
  map.put(HEAP_USED_COMMITTED,(double)heapUsed.getCommitted() / (1024 * 1024));
  map.put(HEAP_USED,(double)heapUsed.getUsed() / (1024 * 1024));
  MemoryUsage nonheapUsed=memory.getNonHeapMemoryUsage();
  map.put(NONHEAP_USED_INIT,(double)nonheapUsed.getInit() / (1024 * 1024));
  map.put(NONHEAP_USED_MAX,(double)nonheapUsed.getMax() / (1024 * 1024));
  map.put(NONHEAP_USED_COMMITTED,(double)nonheapUsed.getCommitted() / (1024 * 1024));
  map.put(NONHEAP_USED,(double)nonheapUsed.getUsed() / (1024 * 1024));
  map.put(THREAD_CNT,(double)threads.getThreadCount());
  map.put(THREAD_DAEMON_CNT,(double)threads.getDaemonThreadCount());
  map.put(THREAD_PEAK_CNT,(double)threads.getPeakThreadCount());
  map.put(THREAD_STARTED_CNT,(double)threads.getTotalStartedThreadCount());
  map.put(START_TIME,(double)runtime.getStartTime());
  map.put(UPTIME,(double)runtime.getUptime());
  map.put(LOADED_CLASS_CNT,(double)classes.getLoadedClassCount());
  map.put(UNLOADED_CLASS_CNT,(double)classes.getUnloadedClassCount());
  map.put(TOTAL_LOADED_CLASS_CNT,(double)classes.getTotalLoadedClassCount());
  for (  GarbageCollectorMXBean gbean : ManagementFactory.getGarbageCollectorMXBeans()) {
    map.put(GC + gbean.getName().replace(" ","_") + CNT,(double)gbean.getCollectionCount());
    map.put(GC + gbean.getName().replace(" ","_") + MILLIS,(double)gbean.getCollectionTime());
  }
  return map;
}