Example usage for java.lang.management ManagementFactory getPlatformMBeanServer

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

Introduction

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

Prototype

public static synchronized MBeanServer getPlatformMBeanServer() 

Source Link

Document

Returns the platform javax.management.MBeanServer MBeanServer .

Usage

From source file:org.opencastproject.userdirectory.ldap.LdapUserProviderInstance.java

/**
 * Registers an MXBean./* w w w. j  a  va  2  s.  co  m*/
 */
protected void registerMBean(String pid) {
    // register with jmx
    requests = new AtomicLong();
    ldapLoads = new AtomicLong();
    try {
        ObjectName name;
        name = LdapUserProviderFactory.getObjectName(pid);
        Object mbean = this;
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        try {
            mbs.unregisterMBean(name);
        } catch (InstanceNotFoundException e) {
            logger.debug(name + " was not registered");
        }
        mbs.registerMBean(mbean, name);
    } catch (Exception e) {
        logger.warn("Unable to register {} as an mbean: {}", this, e);
    }
}

From source file:org.apache.synapse.commons.snmp.SNMPAgent.java

@Override
protected void registerManagedObjects() {
    log.info("Initializing Synapse SNMP MIB");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectInstance> instances = mbs.queryMBeans(null, null);

    try {// w  w w.  j  av  a 2s  . c o  m
        for (ObjectInstance instance : instances) {
            ObjectName objectName = instance.getObjectName();
            if (objectName.getDomain().equals("org.apache.synapse")) {
                String oidString = SynapseMIBUtils.getOID(objectName);
                if (oidString == null) {
                    continue;
                }

                MBeanInfo info = mbs.getMBeanInfo(objectName);
                MBeanAttributeInfo[] attributes = info.getAttributes();
                List<String> attributeNames = new ArrayList<String>();
                List<String> mapAttributes = new ArrayList<String>();
                for (MBeanAttributeInfo attributeInfo : attributes) {
                    attributeNames.add(attributeInfo.getName());
                    if (Map.class.getName().equals(attributeInfo.getType())) {
                        mapAttributes.add(attributeInfo.getName());
                    }
                }
                Collections.sort(attributeNames);

                doRegister(attributeNames, mapAttributes, oidString, objectName);
            }
        }
    } catch (Exception e) {
        log.error("Error while initializing the SNMP MIB", e);
    }
}

From source file:io.fabric8.support.impl.SupportServiceImpl.java

@Activate
void activate() {
    activateComponent();//from  w  w  w . j av a  2  s. c om
    if (objectName == null) {
        try {
            objectName = getObjectName();
        } catch (Exception e) {
            LOGGER.warn("Failed to create object name: ", e);
            throw new RuntimeException("Failed to create object name: ", e);
        }
    }

    if (mBeanServer == null) {
        mBeanServer = ManagementFactory.getPlatformMBeanServer();
    }

    if (mBeanServer != null) {
        try {
            mbean = new StandardMBean(this, SupportService.class, false);
            mBeanServer.registerMBean(mbean, objectName);
        } catch (InstanceAlreadyExistsException iaee) {
            // Try to remove and re-register
            try {
                mBeanServer.unregisterMBean(objectName);
                mBeanServer.registerMBean(this, objectName);
            } catch (Exception e) {
                LOGGER.warn("Failed to register mbean: " + objectName, e);
                throw new RuntimeException("Failed to register mbean: " + objectName, e);
            }
        } catch (Exception e) {
            LOGGER.warn("Failed to register mbean: " + objectName, e);
            throw new RuntimeException("Failed to register mbean: " + objectName, e);
        }
    }
}

From source file:com.obergner.hzserver.snmp.SnmpBridgeFactoryBean.java

private MBeanServer getMBeanServer() {
    return this.mbeanServer != null ? this.mbeanServer : ManagementFactory.getPlatformMBeanServer();
}

From source file:org.codice.alliance.video.ui.service.StreamMonitorHelper.java

private void registerMbean() {
    try {/*from  www .j av  a2s  .c o  m*/
        objectName = new ObjectName(StreamMonitorHelper.class.getName() + ":service=stream");
        mBeanServer = ManagementFactory.getPlatformMBeanServer();
    } catch (MalformedObjectNameException e) {
        LOGGER.error("Unable to create FMV Stream Monitor Helper MBean.", e);
    }
    if (mBeanServer == null) {
        return;
    }
    try {
        try {
            mBeanServer.registerMBean(this, objectName);
            LOGGER.info("Registered FMV Stream Monitor Helper MBean under object name: {}",
                    objectName.toString());
        } catch (InstanceAlreadyExistsException e) {
            mBeanServer.unregisterMBean(objectName);
            mBeanServer.registerMBean(this, objectName);
            LOGGER.info("Re-registered FMV Stream Monitor Helper MBean");
        }
    } catch (MBeanRegistrationException | InstanceNotFoundException | InstanceAlreadyExistsException
            | NotCompliantMBeanException e) {
        LOGGER.error("Could not register MBean [{}].", objectName.toString(), e);
    }

}

From source file:org.wso2.carbon.andes.cluster.mgt.internal.managementBeans.ClusterManagementBeans.java

/**
 * Gets the IP addresses and ports of the nodes in a cluster
 *
 * @return A list of addresses of the nodes in a cluster
 * @throws ClusterMgtException//  w  w  w  .  j av a 2 s . c o m
 */
public List<String> getAllClusterNodeAddresses() throws ClusterMgtException {
    List<String> allClusterNodeAddresses = new ArrayList<String>();
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {

        ObjectName objectName = new ObjectName(
                "org.wso2.andes:type=ClusterManagementInformation," + "name=ClusterManagementInformation");
        Object result = mBeanServer.getAttribute(objectName, ClusterMgtConstants.ALL_CLUSTER_NODE_ADDRESSES);

        if (result != null) {
            allClusterNodeAddresses = (List<String>) result;
        }
        return allClusterNodeAddresses;

    } catch (MalformedObjectNameException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    } catch (ReflectionException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    } catch (MBeanException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    } catch (InstanceNotFoundException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    } catch (AttributeNotFoundException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    }
}

From source file:org.ofbiz.core.entity.transaction.DBCPConnectionFactory.java

private static void unregisterDatasourceFromJmx(BasicDataSource dataSource) {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {/* w  w  w . j a v  a  2 s .  co  m*/
        mbs.unregisterMBean(ObjectName.getInstance(dataSource.getJmxName()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.googlecode.jmxtrans.model.output.StatsDWriter.java

@Override
public void start() throws LifecycleException {
    try {//  www  . j  a v a2  s  . c  o m
        pool = new GenericKeyedObjectPool<>(new DatagramSocketFactory());
        pool.setTestOnBorrow(true);
        pool.setMaxActive(-1);
        pool.setMaxIdle(-1);
        pool.setTimeBetweenEvictionRunsMillis(MILLISECONDS.convert(5, MINUTES));
        pool.setMinEvictableIdleTimeMillis(MILLISECONDS.convert(5, MINUTES));

        this.mbean = new ManagedGenericKeyedObjectPool((GenericKeyedObjectPool) pool, "StatsdConnectionPool");
        ManagementFactory.getPlatformMBeanServer().registerMBean(this.mbean, this.mbean.getObjectName());
    } catch (Exception e) {
        throw new LifecycleException(e);
    }
}

From source file:com.aerofs.baseline.Service.java

public final void runWithConfiguration(T configuration) throws Exception {
    // initialize the validation subsystem
    ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
            .buildValidatorFactory();/*from   w  w  w  .j a v  a 2 s . c o  m*/
    Validator validator = validatorFactory.getValidator();

    // validate the configuration
    Configuration.validateConfiguration(validator, configuration);

    // at this point we have a valid configuration
    // we can start logging to the correct location,
    // initialize common services, and start up
    // the jersey applications

    // reset the logging subsystem with the configured levels
    Logging.setupLogging(configuration.getLogging());

    // display the server banner if it exists
    displayBanner();

    // add a shutdown hook to release all resources cleanly
    Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));

    // setup some default metrics for the JVM
    MetricRegistries.getRegistry().register(Constants.JVM_BUFFERS,
            new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    MetricRegistries.getRegistry().register(Constants.JVM_GC, new GarbageCollectorMetricSet());
    MetricRegistries.getRegistry().register(Constants.JVM_MEMORY, new MemoryUsageGaugeSet());
    MetricRegistries.getRegistry().register(Constants.JVM_THREADS, new ThreadStatesGaugeSet());

    // create the root service locator
    ServiceLocator rootLocator = ServiceLocatorFactory.getInstance().create("root");
    rootLocatorReference.set(rootLocator);

    // grab a reference to our system-wide class loader (we'll use this for the jersey service locators)
    ClassLoader classLoader = rootLocator.getClass().getClassLoader();

    // create the lifecycle manager
    LifecycleManager lifecycleManager = new LifecycleManager(rootLocator);
    lifecycleManagerReference.set(lifecycleManager);

    // after this point any services
    // added to the LifecycleManager will be
    // shut down cleanly

    // create and setup the system-wide Jackson object mapper
    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    // create a few singleton objects
    Authenticators authenticators = new Authenticators();
    RegisteredCommands registeredCommands = new RegisteredCommands();
    RegisteredHealthChecks registeredHealthChecks = new RegisteredHealthChecks();

    // create the root environment
    Environment environment = new Environment(rootLocator, lifecycleManager, validator, mapper, authenticators,
            registeredCommands, registeredHealthChecks);

    // start configuring injectable objects
    // we'll be adding all instances and implementation classes to the root service locator
    // this makes them visible to the jersey applications

    environment.addBinder(new ConfigurationBinder<>(configuration, configuration.getClass()));
    environment.addBinder(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(name).to(String.class).named(Constants.SERVICE_NAME_INJECTION_KEY);
            bind(validator).to(Validator.class);
            bind(mapper).to(ObjectMapper.class);
            bind(environment).to(Environment.class);
            bind(lifecycleManager.getScheduledExecutorService()).to(ScheduledExecutorService.class);
            bind(lifecycleManager.getTimer()).to(Timer.class); // FIXME (AG): use our own timer interface
            bind(authenticators).to(Authenticators.class);
            bind(registeredCommands).to(RegisteredCommands.class);
            bind(registeredHealthChecks).to(RegisteredHealthChecks.class);
        }
    });

    // register some basic commands
    environment.registerCommand("gc", GarbageCollectionCommand.class);
    environment.registerCommand("metrics", MetricsCommand.class);
    environment.addAdminProvider(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(GarbageCollectionCommand.class).to(GarbageCollectionCommand.class).in(Singleton.class);
            bind(MetricsCommand.class).to(MetricsCommand.class).in(Singleton.class);
        }
    });

    // add exception mappers that only apply to the admin environment
    environment.addAdminProvider(InvalidCommandExceptionMapper.class);

    // add the resources we expose via the admin api
    environment.addAdminResource(CommandsResource.class);
    environment.addAdminResource(HealthCheckResource.class);

    // create the two environments (admin and service)
    String adminName = name + "-" + Constants.ADMIN_IDENTIFIER;
    initializeJerseyApplication(adminName, classLoader, validator, mapper, environment.getAdminResourceConfig(),
            configuration.getAdmin());

    String serviceName = name + "-" + Constants.SERVICE_IDENTIFIER;
    initializeJerseyApplication(serviceName, classLoader, validator, mapper,
            environment.getServiceResourceConfig(), configuration.getService());

    // punt to subclasses for further configuration
    init(configuration, environment);

    // after this point we can't add any more jersey providers
    // resources, etc. and we're ready to expose our server to the world

    // list the objects that are registered with the root service locator
    listInjected(rootLocator);

    // initialize the admin http server
    if (configuration.getAdmin().isEnabled()) {
        ApplicationHandler adminHandler = new ApplicationHandler(environment.getAdminResourceConfig(), null,
                rootLocator);
        listInjected(adminHandler.getServiceLocator());
        HttpServer adminHttpServer = new HttpServer(Constants.ADMIN_IDENTIFIER, configuration.getAdmin(),
                lifecycleManager.getTimer(), adminHandler);
        lifecycleManager.add(adminHttpServer);
    }

    // initialize the service http server
    if (configuration.getService().isEnabled()) {
        ApplicationHandler serviceHandler = new ApplicationHandler(environment.getServiceResourceConfig(), null,
                rootLocator);
        listInjected(serviceHandler.getServiceLocator());
        HttpServer serviceHttpServer = new HttpServer(Constants.SERVICE_IDENTIFIER, configuration.getService(),
                lifecycleManager.getTimer(), serviceHandler);
        lifecycleManager.add(serviceHttpServer);
    }

    // finally, start up all managed services (which includes the two servers above)
    lifecycleManager.start();
}

From source file:org.apache.hadoop.hive.common.metrics.metrics2.CodahaleMetrics.java

public CodahaleMetrics(HiveConf conf) throws Exception {
    this.conf = conf;
    //Codahale artifacts are lazily-created.
    timers = CacheBuilder.newBuilder().build(new CacheLoader<String, com.codahale.metrics.Timer>() {
        @Override//  ww  w.  j av  a2  s. c om
        public com.codahale.metrics.Timer load(String key) throws Exception {
            Timer timer = new Timer(new ExponentiallyDecayingReservoir());
            metricRegistry.register(key, timer);
            return timer;
        }
    });
    counters = CacheBuilder.newBuilder().build(new CacheLoader<String, Counter>() {
        @Override
        public Counter load(String key) throws Exception {
            Counter counter = new Counter();
            metricRegistry.register(key, counter);
            return counter;
        }
    });
    gauges = new ConcurrentHashMap<String, Gauge>();

    //register JVM metrics
    registerAll("gc", new GarbageCollectorMetricSet());
    registerAll("buffers", new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    registerAll("memory", new MemoryUsageGaugeSet());
    registerAll("threads", new ThreadStatesGaugeSet());
    registerAll("classLoading", new ClassLoadingGaugeSet());

    //Metrics reporter
    Set<MetricsReporting> finalReporterList = new HashSet<MetricsReporting>();
    List<String> metricsReporterNames = Lists.newArrayList(Splitter.on(",").trimResults().omitEmptyStrings()
            .split(conf.getVar(HiveConf.ConfVars.HIVE_METRICS_REPORTER)));

    if (metricsReporterNames != null) {
        for (String metricsReportingName : metricsReporterNames) {
            try {
                MetricsReporting reporter = MetricsReporting.valueOf(metricsReportingName.trim().toUpperCase());
                finalReporterList.add(reporter);
            } catch (IllegalArgumentException e) {
                LOGGER.warn(
                        "Metrics reporter skipped due to invalid configured reporter: " + metricsReportingName);
            }
        }
    }
    initReporting(finalReporterList);
}