Example usage for javax.management NotificationListener NotificationListener

List of usage examples for javax.management NotificationListener NotificationListener

Introduction

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

Prototype

NotificationListener

Source Link

Usage

From source file:org.jboss.resteasy.test.response.ResponseStreamPrematurelyClosedTest.java

@Test
public void testStream() throws Exception {
    Builder builder = client.target(generateURL("/test/document/abc/content")).request();

    try (MyByteArrayOutputStream baos = new MyByteArrayOutputStream()) {

        if (!TestUtil.isIbmJdk()) {
            //builder.get().readEntity explicitly on the same line below and not saved in any temp variable
            //to let the JVM try finalizing the ClientResponse object
            InputStream ins = builder.get().readEntity(InputStream.class);
            //suggest jvm to do gc and wait the gc notification
            final CountDownLatch coutDown = new CountDownLatch(1);

            List<GarbageCollectorMXBean> gcbeans = ManagementFactory.getGarbageCollectorMXBeans();
            NotificationListener listener = new NotificationListener() {
                public void handleNotification(Notification notification, Object handback) {
                    coutDown.countDown();
                }/*from   w ww . ja  va2  s.  co  m*/
            };
            try {
                for (GarbageCollectorMXBean gcbean : gcbeans) {
                    NotificationEmitter emitter = (NotificationEmitter) gcbean;
                    emitter.addNotificationListener(listener, null, null);
                }
                System.gc();
                coutDown.await(10, TimeUnit.SECONDS);

                IOUtils.copy(ins, baos);
                Assert.assertEquals("Received string: " + baos.toShortString(), 10000000, baos.size());
            } finally {
                //remove the listener
                for (GarbageCollectorMXBean gcbean : gcbeans) {
                    ((NotificationEmitter) gcbean).removeNotificationListener(listener);
                }
            }
        } else { // workaround for Ibm jdk - doesn't allow to use NotificationEmitter with GarbageCollectorMXBean
            //builder.get().readEntity explicitly on the same line below and not saved in any temp variable
            //to let the JVM try finalizing the ClientResponse object
            IOUtils.copy(builder.get().readEntity(InputStream.class), baos);
            Assert.assertEquals(100000000, baos.size());
        }
    }
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.jvm.GarbageCollectorMetricSet.java

GarbageCollectorMetricSet() {
    this.garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();

    this.minorGcTimer = new Timer();
    this.majorGcTimer = new Timer();

    // Determine the location of the gc log file (note that there's not support for rolling gc logs)
    String gcLogFilePath = null;//from w  ww . j a v  a2 s. com
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    List<String> inputArguments = runtimeMXBean.getInputArguments();
    for (String argument : inputArguments) {
        if (argument.startsWith(LOG_GC_JVM_PARAM)) {
            gcLogFilePath = argument.substring(LOG_GC_JVM_PARAM.length());
            break;
        }
    }

    if (gcLogFilePath != null && !gcLogFilePath.trim().isEmpty()) {
        final File gcLogFile = new File(gcLogFilePath);
        if (gcLogFile.exists()) {
            this.fullCollectionsCounter = new AtomicLong();

            this.gcLogTailer = Tailer.create(gcLogFile, new TailerListenerAdapter() {
                @Override
                public void handle(String line) {
                    if (line != null && line.contains(FULL_GC_LOG_STRING)) {
                        fullCollectionsCounter.incrementAndGet();
                    }
                }
            }, GC_LOG_FILE_TAIL_DELAY_IN_MILLIS);
        }
    }

    // Attach a listener to the GarbageCollectorMXBeans
    this.gcEventListener = new NotificationListener() {
        @Override
        public void handleNotification(Notification notification, Object handback) {
            String notificationType = notification.getType();
            if (notificationType.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                CompositeData compositeData = CompositeData.class.cast(notification.getUserData());
                GarbageCollectionNotificationInfo gcNotificationInfo = GarbageCollectionNotificationInfo
                        .from(compositeData);

                if (GC_NOTIFICATION_MINOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    minorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                } else if (GC_NOTIFICATION_MAJOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    majorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                }
            }
        }
    };

    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        if (NotificationEmitter.class.isInstance(garbageCollectorMXBean)) {
            NotificationEmitter emitter = NotificationEmitter.class.cast(garbageCollectorMXBean);
            emitter.addNotificationListener(gcEventListener, null, null);
        }
    }

    // Set up metrics
    Map<String, Metric> metricsByNames = new HashMap<>();

    if (fullCollectionsCounter != null) {
        this.fullCollectionsGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return fullCollectionsCounter.get();
            }
        };
        metricsByNames.put("fullCollections", fullCollectionsGauge);
    }

    metricsByNames.put("majorGcTimer", majorGcTimer);
    metricsByNames.put("minorGcTimer", minorGcTimer);

    List<GarbageCollectorStatus> garbageCollectorStatuses = new ArrayList<>();
    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        final String garbageCollectorName = garbageCollectorMXBean.getName();
        final String garbageCollectorNamespace = MetricNamingUtil.join("collectors",
                MetricNamingUtil.sanitize(garbageCollectorName));

        final Gauge<Long> collectionsGauge;
        if (garbageCollectorMXBean.getCollectionCount() >= 0) {
            collectionsGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionCount();
                }
            };
            metricsByNames.put(MetricNamingUtil.join(garbageCollectorNamespace, "collections"),
                    collectionsGauge);
        } else {
            collectionsGauge = null;
        }

        final Gauge<Long> totalCollectionDurationInMillisGauge;
        if (garbageCollectorMXBean.getCollectionTime() >= 0) {
            totalCollectionDurationInMillisGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionTime();
                }
            };
            metricsByNames.put(
                    MetricNamingUtil.join(garbageCollectorNamespace, "totalCollectionDurationInMillis"),
                    totalCollectionDurationInMillisGauge);
        } else {
            totalCollectionDurationInMillisGauge = null;
        }

        garbageCollectorStatuses.add(new GarbageCollectorStatus() {
            @Override
            public String getName() {
                return garbageCollectorName;
            }

            @Override
            public Gauge<Long> getCollectionsGauge() {
                return collectionsGauge;
            }

            @Override
            public Gauge<Long> getTotalCollectionDurationInMillisGauge() {
                return totalCollectionDurationInMillisGauge;
            }
        });
    }
    this.garbageCollectorStatuses = garbageCollectorStatuses;

    this.metricsByNames = metricsByNames;
}

From source file:io.fabric8.spi.process.AbstractProcessHandler.java

@Override
public final Future<ManagedProcess> start() {
    State state = managedProcess.getState();
    assertNotDestroyed(state);/*from  ww  w . ja va2s  .c om*/

    // Setup a call back notification to get the JMX connection of the started process
    final CountDownLatch latch = new CountDownLatch(1);
    String jmxAgentServiceURL = managedProcess
            .getAttribute(ContainerAttributes.ATTRIBUTE_KEY_AGENT_JMX_SERVER_URL);
    String jmxAgentUsername = managedProcess.getAttribute(ContainerAttributes.ATTRIBUTE_KEY_AGENT_JMX_USERNAME);
    String jmxAgentPassword = managedProcess.getAttribute(ContainerAttributes.ATTRIBUTE_KEY_AGENT_JMX_PASSWORD);
    JMXConnector connector = ManagementUtils.getJMXConnector(jmxAgentServiceURL, jmxAgentUsername,
            jmxAgentPassword, 200, TimeUnit.MILLISECONDS);
    try {
        final MBeanServerConnection server = connector.getMBeanServerConnection();
        server.addNotificationListener(Agent.OBJECT_NAME, new NotificationListener() {
            @Override
            public void handleNotification(Notification notification, Object handback) {
                String eventType = notification.getType();
                if (NOTIFICATION_TYPE_AGENT_REGISTRATION.equals(eventType)) {
                    AgentRegistration agentReg = (AgentRegistration) notification.getSource();
                    String agentName = agentReg.getIdentity().getName();
                    String procName = (String) handback;
                    if (agentName.equals(procName)) {
                        try {
                            server.removeNotificationListener(Agent.OBJECT_NAME, this);
                        } catch (Exception ex) {
                            // ignore
                        }
                        latch.countDown();
                    }
                }
            }
        }, null, managedProcess.getIdentity().getName());
    } catch (RuntimeException rte) {
        throw rte;
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    } finally {
        IOUtils.safeClose(connector);
    }

    try {
        if (state == State.CREATED || state == State.STOPPED) {
            doStart(managedProcess);
            IllegalStateAssertion.assertNotNull(process, "No process created");
            managedProcess.setState(State.STARTED);
        }
    } catch (Exception ex) {
        throw new LifecycleException("Cannot start container", ex);
    }

    return new ProcessFuture(managedProcess); //, latch);
}

From source file:org.apache.giraph.graph.GraphTaskManager.java

/**
 * Install GC monitoring. This method intercepts all GC, log the gc, and
 * notifies an out-of-core engine (if any is used) about the GC.
 *//*ww w .  j a  v a  2 s. co m*/
private void installGCMonitoring() {
    List<GarbageCollectorMXBean> mxBeans = ManagementFactory.getGarbageCollectorMXBeans();
    final OutOfCoreEngine oocEngine = serviceWorker.getServerData().getOocEngine();
    for (GarbageCollectorMXBean gcBean : mxBeans) {
        NotificationEmitter emitter = (NotificationEmitter) gcBean;
        NotificationListener listener = new NotificationListener() {
            @Override
            public void handleNotification(Notification notification, Object handle) {
                if (notification.getType()
                        .equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                    GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo
                            .from((CompositeData) notification.getUserData());

                    if (LOG.isInfoEnabled()) {
                        LOG.info("installGCMonitoring: name = " + info.getGcName() + ", action = "
                                + info.getGcAction() + ", cause = " + info.getGcCause() + ", duration = "
                                + info.getGcInfo().getDuration() + "ms");
                    }
                    gcTimeMetric.inc(info.getGcInfo().getDuration());
                    if (oocEngine != null) {
                        oocEngine.gcCompleted(info);
                    }
                }
            }
        };
        //Add the listener
        emitter.addNotificationListener(listener, null, null);
    }
}

From source file:org.apache.geode.admin.jmx.internal.MBeanUtil.java

static void registerServerNotificationListener() {
    if (mbeanServer == null) {
        return;/* www .j a  va 2 s  .  c  o  m*/
    }
    try {
        // the MBeanServerDelegate name is spec'ed as the following...
        ObjectName delegate = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
        mbeanServer.addNotificationListener(delegate, new NotificationListener() {
            public void handleNotification(Notification notification, Object handback) {
                MBeanServerNotification serverNotification = (MBeanServerNotification) notification;
                if (MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(serverNotification.getType())) {
                    ObjectName objectName = serverNotification.getMBeanName();
                    synchronized (MBeanUtil.managedResources) {
                        Object entry = MBeanUtil.managedResources.get(objectName);
                        if (entry == null)
                            return;
                        if (!(entry instanceof ManagedResource)) {
                            throw new ClassCastException(LocalizedStrings.MBeanUtil_0_IS_NOT_A_MANAGEDRESOURCE
                                    .toLocalizedString(new Object[] { entry.getClass().getName() }));
                        }
                        ManagedResource resource = (ManagedResource) entry;
                        {
                            // call cleanup on managedResource
                            cleanupResource(resource);
                        }
                    }
                }
            }
        }, null, null);
    } catch (JMException e) {
        logStackTrace(Level.WARN, e,
                LocalizedStrings.MBeanUtil_FAILED_TO_REGISTER_SERVERNOTIFICATIONLISTENER.toLocalizedString());
    } catch (JMRuntimeException e) {
        logStackTrace(Level.WARN, e,
                LocalizedStrings.MBeanUtil_FAILED_TO_REGISTER_SERVERNOTIFICATIONLISTENER.toLocalizedString());
    }
}

From source file:com.heliosapm.script.AbstractDeployedScript.java

/**
 * Finds the ObjectName of the configuration MBean to watch
 * @return the ObjectName of the configuration MBean to watch
 *//*from www.  ja v  a  2  s.c  om*/
protected ObjectName findWatchedConfiguration() {
    /*
     * if extension != config
     *       look for {shortName}.config
     *       if not found
     *          look for {pwd}.config   (error if not found)
     *          listen for registration of a future {shortName}.config
     *             when notified:
     *                stop listening on {pwd}.config and listen on {shortName}.config  
     * 
     * else   (we are a config)
     *       if(shortName != {pwd})
     *          look for {pwd}.config
     *       else  (we are the {pwd}.config
     *          look for {pwd.parent}.config (error if not found)
     */

    final Hashtable<String, String> keyAttrs = new Hashtable<String, String>(objectName.getKeyPropertyList());

    final String pwd = sourceFile.getParentFile().getName();

    if (!"config".equals(extension)) {
        // look for {shortName}.config
        keyAttrs.put("extension", "config");
        ObjectName watchedObjectName = JMXHelper.objectName(CONFIG_DOMAIN, keyAttrs);
        if (JMXHelper.isRegistered(watchedObjectName)) {
            return watchedObjectName;
        }
        // nope. register a listener in case he shows up, then look for {pwd}.config
        final NotificationListener lateComerListener = new NotificationListener() {
            @Override
            public void handleNotification(Notification notification, Object handback) {

            }
        };
        JMXHelper.addMBeanRegistrationListener(watchedObjectName, lateComerListener, 1);
        keyAttrs.put("name", pwd);
        watchedObjectName = JMXHelper.objectName(CONFIG_DOMAIN, keyAttrs);
        if (JMXHelper.isRegistered(watchedObjectName)) {
            return watchedObjectName;
        }
        log.warn("Failed to find expected dir watched configuration \n\tfor [" + objectName
                + "] \n\tat ObjectName [" + watchedObjectName + "]");
        throw new RuntimeException("Failed to find expected dir watched configuration for [" + objectName
                + "] at ObjectName [" + watchedObjectName + "]");
    }
    // we're a config
    if (!shortName.equals(pwd)) {
        // we're a script config, so look for {pwd}.config
        keyAttrs.put("name", pwd);
        ObjectName watchedObjectName = JMXHelper.objectName(CONFIG_DOMAIN, keyAttrs);
        if (JMXHelper.isRegistered(watchedObjectName)) {
            return watchedObjectName;
        }
        log.warn("Failed to find expected dir watched configuration \n\tfor [" + objectName
                + "] \n\tat ObjectName [" + watchedObjectName + "]");
        return null;
        //throw new RuntimeException("Failed to find expected dir watched configuration for [" + objectName + "] at ObjectName [" + watchedObjectName + "]");            
    }
    // we're a {pwd}.connfig, so we need to find {pwd.parent}.config
    // yank the highest d# attribute so we go up one dir
    Integer high = JMXHelper.getHighestKey(objectName, "d");
    if (high == null) {
        return null;
    }
    keyAttrs.remove("d" + JMXHelper.getHighestKey(objectName, "d"));
    if (this.rootDir.equals(sourceFile.getParentFile().getParentFile().getAbsolutePath())) {
        return null;
    }
    // update the name to the {pwd.parent}            
    keyAttrs.put("name", sourceFile.getParentFile().getParentFile().getName());
    ObjectName watchedObjectName = JMXHelper.objectName(CONFIG_DOMAIN, keyAttrs);
    if (JMXHelper.isRegistered(watchedObjectName)) {
        return watchedObjectName;
    }
    log.warn("Failed to find expected parent dir watched configuration \n\tfor [" + objectName
            + "] \n\tat ObjectName [" + watchedObjectName + "]");
    throw new RuntimeException("Failed to find expected parent dir watched configuration for [" + objectName
            + "] at ObjectName [" + watchedObjectName + "]");
}