Search in sources :

Example 46 with NotificationListener

use of javax.management.NotificationListener in project btrace by btraceio.

the class BTraceRuntime method initMemoryListener.

private void initMemoryListener() {
    initThreadPool();
    memoryListener = new NotificationListener() {

        @Override
        @SuppressWarnings("FutureReturnValueIgnored")
        public void handleNotification(Notification notif, Object handback) {
            boolean entered = BTraceRuntime.enter(BTraceRuntime.this);
            try {
                String notifType = notif.getType();
                if (notifType.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
                    CompositeData cd = (CompositeData) notif.getUserData();
                    final MemoryNotificationInfo info = MemoryNotificationInfo.from(cd);
                    String name = info.getPoolName();
                    final LowMemoryHandler handler = lowMemoryHandlerMap.get(name);
                    if (handler != null) {
                        threadPool.submit(new Runnable() {

                            @Override
                            public void run() {
                                boolean entered = BTraceRuntime.enter(BTraceRuntime.this);
                                try {
                                    if (handler.trackUsage) {
                                        handler.invoke(clazz, null, info.getUsage());
                                    } else {
                                        handler.invoke(clazz, null, (Object[]) null);
                                    }
                                } catch (Throwable th) {
                                } finally {
                                    if (entered) {
                                        BTraceRuntime.leave();
                                    }
                                }
                            }
                        });
                    }
                }
            } finally {
                if (entered) {
                    BTraceRuntime.leave();
                }
            }
        }
    };
}
Also used : MemoryNotificationInfo(java.lang.management.MemoryNotificationInfo) CompositeData(javax.management.openmbean.CompositeData) LowMemoryHandler(com.sun.btrace.shared.LowMemoryHandler) Notification(javax.management.Notification) NotificationListener(javax.management.NotificationListener)

Example 47 with NotificationListener

use of javax.management.NotificationListener in project spring-framework by spring-projects.

the class MBeanExporterTests method testRegisterNotificationListenerForNonExistentMBean.

@Test
void testRegisterNotificationListenerForNonExistentMBean() throws Exception {
    Map<String, NotificationListener> listeners = new HashMap<>();
    NotificationListener dummyListener = (notification, handback) -> {
        throw new UnsupportedOperationException();
    };
    // the MBean with the supplied object name does not exist...
    listeners.put("spring:type=Test", dummyListener);
    MBeanExporter exporter = new MBeanExporter();
    exporter.setBeans(getBeanMap());
    exporter.setServer(server);
    exporter.setNotificationListenerMappings(listeners);
    assertThatExceptionOfType(MBeanExportException.class).as("NotificationListener on a non-existent MBean").isThrownBy(() -> start(exporter)).satisfies(ex -> assertThat(ex.contains(InstanceNotFoundException.class)));
}
Also used : RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) Arrays(java.util.Arrays) NotificationListener(javax.management.NotificationListener) ObjectInstance(javax.management.ObjectInstance) NopInterceptor(org.springframework.aop.testfixture.interceptor.NopInterceptor) RegistrationPolicy(org.springframework.jmx.support.RegistrationPolicy) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) AbstractMBeanServerTests(org.springframework.jmx.AbstractMBeanServerTests) ArrayList(java.util.ArrayList) ModelMBeanInfo(javax.management.modelmbean.ModelMBeanInfo) JmxTestBean(org.springframework.jmx.JmxTestBean) FactoryBean(org.springframework.beans.factory.FactoryBean) Attribute(javax.management.Attribute) Map(java.util.Map) MBeanServer(javax.management.MBeanServer) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) TestBean(org.springframework.beans.testfixture.beans.TestBean) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) InstanceNotFoundException(javax.management.InstanceNotFoundException) SelfNaming(org.springframework.jmx.export.naming.SelfNaming) Collection(java.util.Collection) ObjectName(javax.management.ObjectName) SimpleReflectiveMBeanInfoAssembler(org.springframework.jmx.export.assembler.SimpleReflectiveMBeanInfoAssembler) Notification(javax.management.Notification) AutodetectCapableMBeanInfoAssembler(org.springframework.jmx.export.assembler.AutodetectCapableMBeanInfoAssembler) MalformedObjectNameException(javax.management.MalformedObjectNameException) Test(org.junit.jupiter.api.Test) List(java.util.List) JMException(javax.management.JMException) ObjectNameManager(org.springframework.jmx.support.ObjectNameManager) ProxyFactory(org.springframework.aop.framework.ProxyFactory) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) IJmxTestBean(org.springframework.jmx.IJmxTestBean) MBeanInfoAssembler(org.springframework.jmx.export.assembler.MBeanInfoAssembler) Collections(java.util.Collections) HashMap(java.util.HashMap) NotificationListener(javax.management.NotificationListener) Test(org.junit.jupiter.api.Test)

Example 48 with NotificationListener

use of javax.management.NotificationListener in project aries by apache.

the class ServiceStateTest method createService.

private void createService(StateConfig stateConfig, final List<Notification> received, final List<AttributeChangeNotification> attributeChanges) throws Exception {
    BundleContext context = mock(BundleContext.class);
    Logger logger = mock(Logger.class);
    ServiceState serviceState = new ServiceState(context, stateConfig, logger);
    ServiceReference reference = mock(ServiceReference.class);
    Bundle b1 = mock(Bundle.class);
    when(b1.getBundleId()).thenReturn(new Long(9));
    when(b1.getSymbolicName()).thenReturn("bundle");
    when(b1.getLocation()).thenReturn("file:/location");
    when(reference.getBundle()).thenReturn(b1);
    when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(44));
    when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn(new String[] { "org.apache.aries.jmx.Mock" });
    when(context.getAllServiceReferences(null, null)).thenReturn(new ServiceReference[] { reference });
    ServiceEvent registeredEvent = mock(ServiceEvent.class);
    when(registeredEvent.getServiceReference()).thenReturn(reference);
    when(registeredEvent.getType()).thenReturn(ServiceEvent.REGISTERED);
    ServiceEvent modifiedEvent = mock(ServiceEvent.class);
    when(modifiedEvent.getServiceReference()).thenReturn(reference);
    when(modifiedEvent.getType()).thenReturn(ServiceEvent.MODIFIED);
    MBeanServer server = mock(MBeanServer.class);
    // setup for notification
    ObjectName objectName = new ObjectName(OBJECTNAME);
    serviceState.preRegister(server, objectName);
    serviceState.postRegister(true);
    // add NotificationListener to receive the events
    serviceState.addNotificationListener(new NotificationListener() {

        public void handleNotification(Notification notification, Object handback) {
            if (notification instanceof AttributeChangeNotification) {
                attributeChanges.add((AttributeChangeNotification) notification);
            } else {
                received.add(notification);
            }
        }
    }, null, null);
    // capture the ServiceListener registered with BundleContext to issue ServiceEvents
    ArgumentCaptor<AllServiceListener> argument = ArgumentCaptor.forClass(AllServiceListener.class);
    verify(context).addServiceListener(argument.capture());
    // send events
    AllServiceListener serviceListener = argument.getValue();
    serviceListener.serviceChanged(registeredEvent);
    serviceListener.serviceChanged(modifiedEvent);
    // shutdown dispatcher via unregister callback
    serviceState.postDeregister();
    // check the ServiceListener is cleaned up
    verify(context).removeServiceListener(serviceListener);
    ExecutorService dispatcher = serviceState.getEventDispatcher();
    assertTrue(dispatcher.isShutdown());
    dispatcher.awaitTermination(2, TimeUnit.SECONDS);
    assertTrue(dispatcher.isTerminated());
}
Also used : AttributeChangeNotification(javax.management.AttributeChangeNotification) Bundle(org.osgi.framework.Bundle) Logger(org.apache.aries.jmx.Logger) AttributeChangeNotification(javax.management.AttributeChangeNotification) Notification(javax.management.Notification) ServiceReference(org.osgi.framework.ServiceReference) ObjectName(javax.management.ObjectName) AllServiceListener(org.osgi.framework.AllServiceListener) ServiceEvent(org.osgi.framework.ServiceEvent) ExecutorService(java.util.concurrent.ExecutorService) BundleContext(org.osgi.framework.BundleContext) MBeanServer(javax.management.MBeanServer) NotificationListener(javax.management.NotificationListener)

Example 49 with NotificationListener

use of javax.management.NotificationListener in project aries by apache.

the class BundleStateMBeanTest method testAttributeChangeNotifications.

@Test
public void testAttributeChangeNotifications() throws Exception {
    final List<AttributeChangeNotification> attributeChanges = new ArrayList<AttributeChangeNotification>();
    AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter();
    filter.disableAllAttributes();
    filter.enableAttribute("BundleIds");
    mbeanServer.addNotificationListener(objectName, new NotificationListener() {

        public void handleNotification(Notification notification, Object handback) {
            attributeChanges.add((AttributeChangeNotification) notification);
        }
    }, filter, null);
    long[] idsWithout = mbean.getBundleIds();
    assertEquals("Precondition", 0, attributeChanges.size());
    Manifest mf = new Manifest();
    mf.getMainAttributes().putValue("Bundle-ManifestVersion", "2");
    mf.getMainAttributes().putValue("Bundle-SymbolicName", "empty-test-bundle");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream jos = new JarOutputStream(baos, mf);
    jos.closeEntry();
    jos.close();
    InputStream bais = new ByteArrayInputStream(baos.toByteArray());
    Bundle bundle = bundleContext.installBundle("http://somelocation", bais);
    long[] idsWith = new long[idsWithout.length + 1];
    System.arraycopy(idsWithout, 0, idsWith, 0, idsWithout.length);
    idsWith[idsWith.length - 1] = bundle.getBundleId();
    Arrays.sort(idsWith);
    waitForListToReachSize(attributeChanges, 1);
    assertEquals(1, attributeChanges.size());
    AttributeChangeNotification ac = attributeChanges.get(0);
    assertEquals("BundleIds", ac.getAttributeName());
    long oldSequence = ac.getSequenceNumber();
    assertTrue(Arrays.equals(idsWithout, (long[]) ac.getOldValue()));
    assertTrue(Arrays.equals(idsWith, (long[]) ac.getNewValue()));
    bundle.uninstall();
    waitForListToReachSize(attributeChanges, 2);
    AttributeChangeNotification ac2 = attributeChanges.get(1);
    assertEquals("BundleIds", ac2.getAttributeName());
    assertEquals(oldSequence + 1, ac2.getSequenceNumber());
    assertTrue(Arrays.equals(idsWith, (long[]) ac2.getOldValue()));
    assertTrue(Arrays.equals(idsWithout, (long[]) ac2.getNewValue()));
}
Also used : AttributeChangeNotification(javax.management.AttributeChangeNotification) AttributeChangeNotificationFilter(javax.management.AttributeChangeNotificationFilter) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) JarOutputStream(java.util.jar.JarOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Manifest(java.util.jar.Manifest) AttributeChangeNotification(javax.management.AttributeChangeNotification) Notification(javax.management.Notification) ByteArrayInputStream(java.io.ByteArrayInputStream) NotificationListener(javax.management.NotificationListener) Test(org.junit.Test) AbstractIntegrationTest(org.apache.aries.jmx.AbstractIntegrationTest)

Example 50 with NotificationListener

use of javax.management.NotificationListener in project tomcat by apache.

the class ConnectionPool method notify.

/**
 * Return true if the notification was sent successfully, false otherwise.
 * @param type The notification type
 * @param message The message
 * @return true if the notification succeeded
 */
public boolean notify(final String type, String message) {
    try {
        Notification n = new Notification(type, this, sequence.incrementAndGet(), System.currentTimeMillis(), "[" + type + "] " + message);
        sendNotification(n);
        for (NotificationListener listener : listeners) {
            listener.handleNotification(n, this);
        }
        return true;
    } catch (Exception x) {
        if (log.isDebugEnabled()) {
            log.debug("Notify failed. Type=" + type + "; Message=" + message, x);
        }
        return false;
    }
}
Also used : Notification(javax.management.Notification) NotificationListener(javax.management.NotificationListener)

Aggregations

NotificationListener (javax.management.NotificationListener)51 Notification (javax.management.Notification)35 ObjectName (javax.management.ObjectName)17 MBeanServer (javax.management.MBeanServer)10 NotificationFilter (javax.management.NotificationFilter)10 JMXConnector (javax.management.remote.JMXConnector)10 JMXServiceURL (javax.management.remote.JMXServiceURL)10 AttributeChangeNotification (javax.management.AttributeChangeNotification)9 MBeanServerConnection (javax.management.MBeanServerConnection)9 ArrayList (java.util.ArrayList)8 HashMap (java.util.HashMap)8 NotificationEmitter (javax.management.NotificationEmitter)8 JMXConnectorServer (javax.management.remote.JMXConnectorServer)8 Attribute (javax.management.Attribute)7 Test (org.junit.Test)6 JMXPluggableAuthenticator (com.sun.jmx.remote.security.JMXPluggableAuthenticator)5 RemoteException (java.rmi.RemoteException)5 LocateRegistry (java.rmi.registry.LocateRegistry)5 Registry (java.rmi.registry.Registry)5 Properties (java.util.Properties)5