Search in sources :

Example 21 with NotificationListener

use of javax.management.NotificationListener in project quasar by puniverse.

the class MonitoringServices method killTimerOnExit.

private void killTimerOnExit() {
    // unfortunately, there's no way to make the timer thread a daemon,
    // wo kill timer thread if it's the last non-daemon thread.
    timer.addNotification("isLastThreadTest", null, null, new Date(System.currentTimeMillis()), 1500);
    timer.addNotificationListener(new NotificationListener() {

        @Override
        public void handleNotification(Notification notification, Object handback) {
            final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
            int tCount = mbean.getThreadCount();
            int dCount = mbean.getDaemonThreadCount();
            if (tCount - dCount <= 2) {
                boolean stop = true;
                Thread[] ts;
                for (; ; ) {
                    ts = new Thread[mbean.getThreadCount() + 3];
                    if (Thread.enumerate(ts) < ts.length)
                        break;
                }
                for (Thread t : ts) {
                    if (t == null)
                        break;
                    if (t.isDaemon() || t == Thread.currentThread())
                        continue;
                    if (!t.getName().equals("DestroyJavaVM"))
                        stop = false;
                }
                if (stop)
                    timer.stop();
            }
        }
    }, new NotificationFilter() {

        @Override
        public boolean isNotificationEnabled(Notification notification) {
            return "isLastThreadTest".equals(notification.getType());
        }
    }, null);
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) NotificationFilter(javax.management.NotificationFilter) Date(java.util.Date) Notification(javax.management.Notification) NotificationListener(javax.management.NotificationListener)

Example 22 with NotificationListener

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

the class ServiceStateMBeanTest method testMBeanInterface.

@Test
public void testMBeanInterface() throws Exception {
    // get bundles
    Bundle a = getBundleByName("org.apache.aries.jmx.test.bundlea");
    assertBundleStarted(a);
    Bundle b = getBundleByName("org.apache.aries.jmx.test.bundleb");
    assertBundleStarted(b);
    // get services
    ServiceReference refA = bundleContext.getServiceReference(InterfaceA.class.getName());
    assertNotNull(refA);
    long serviceAId = (Long) refA.getProperty(Constants.SERVICE_ID);
    assertTrue(serviceAId > -1);
    ServiceReference refB = bundleContext.getServiceReference(InterfaceB.class.getName());
    assertNotNull(refB);
    long serviceBId = (Long) refB.getProperty(Constants.SERVICE_ID);
    assertTrue(serviceBId > -1);
    ServiceReference[] refs = bundleContext.getServiceReferences(ManagedServiceFactory.class.getName(), "(" + Constants.SERVICE_PID + "=jmx.test.B.factory)");
    assertNotNull(refs);
    assertEquals(1, refs.length);
    ServiceReference msf = refs[0];
    // getBundleIdentifier
    assertEquals(a.getBundleId(), mbean.getBundleIdentifier(serviceAId));
    // getObjectClass
    String[] objectClass = mbean.getObjectClass(serviceAId);
    assertEquals(2, objectClass.length);
    List<String> classNames = Arrays.asList(objectClass);
    assertTrue(classNames.contains(InterfaceA.class.getName()));
    assertTrue(classNames.contains(ManagedService.class.getName()));
    // getProperties
    TabularData serviceProperties = mbean.getProperties(serviceBId);
    assertNotNull(serviceProperties);
    assertEquals(JmxConstants.PROPERTIES_TYPE, serviceProperties.getTabularType());
    assertTrue(serviceProperties.values().size() > 1);
    assertEquals("org.apache.aries.jmx.test.ServiceB", PropertyData.from(serviceProperties.get(new Object[] { Constants.SERVICE_PID })).getValue());
    // getUsingBundles
    long[] usingBundles = mbean.getUsingBundles(serviceBId);
    assertEquals(1, usingBundles.length);
    assertEquals(a.getBundleId(), usingBundles[0]);
    // listServices
    ServiceReference[] allSvsRefs = bundleContext.getAllServiceReferences(null, null);
    TabularData allServices = mbean.listServices();
    assertNotNull(allServices);
    assertEquals(allSvsRefs.length, allServices.values().size());
    // notifications
    final List<Notification> received = new ArrayList<Notification>();
    final List<AttributeChangeNotification> attributeChanges = new ArrayList<AttributeChangeNotification>();
    mbeanServer.addNotificationListener(objectName, new NotificationListener() {

        public void handleNotification(Notification notification, Object handback) {
            if (notification instanceof AttributeChangeNotification) {
                attributeChanges.add((AttributeChangeNotification) notification);
            } else {
                received.add(notification);
            }
        }
    }, null, null);
    assertNotNull(refB);
    assertNotNull(msf);
    b.stop();
    refB = bundleContext.getServiceReference(InterfaceB.class.getName());
    refs = bundleContext.getServiceReferences(ManagedServiceFactory.class.getName(), "(" + Constants.SERVICE_PID + "=jmx.test.B.factory)");
    assertNull(refs);
    assertNull(refB);
    b.start();
    refB = bundleContext.getServiceReference(InterfaceB.class.getName());
    refs = bundleContext.getServiceReferences(ManagedServiceFactory.class.getName(), "(" + Constants.SERVICE_PID + "=jmx.test.B.factory)");
    assertNotNull(refB);
    assertNotNull(refs);
    assertEquals(1, refs.length);
    waitForListToReachSize(received, 4);
    assertEquals(4, received.size());
    assertEquals(4, attributeChanges.size());
}
Also used : InterfaceA(org.apache.aries.jmx.test.bundlea.api.InterfaceA) InterfaceB(org.apache.aries.jmx.test.bundleb.api.InterfaceB) AttributeChangeNotification(javax.management.AttributeChangeNotification) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) AttributeChangeNotification(javax.management.AttributeChangeNotification) Notification(javax.management.Notification) ServiceReference(org.osgi.framework.ServiceReference) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) TabularData(javax.management.openmbean.TabularData) NotificationListener(javax.management.NotificationListener) Test(org.junit.Test) AbstractIntegrationTest(org.apache.aries.jmx.AbstractIntegrationTest)

Example 23 with NotificationListener

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

the class BundleStateMBeanTest method testMBeanInterface.

@Test
public void testMBeanInterface() throws Exception {
    // exportedPackages
    String[] exports = mbean.getExportedPackages(a.getBundleId());
    assertEquals(2, exports.length);
    List<String> packages = Arrays.asList(exports);
    assertTrue(packages.contains("org.apache.aries.jmx.test.bundlea.api;2.0.0"));
    assertTrue(packages.contains("org.apache.aries.jmx.test.fragmentc;0.0.0"));
    // fragments
    long[] fragments = mbean.getFragments(a.getBundleId());
    assertEquals(1, fragments.length);
    assertEquals(fragc.getBundleId(), fragments[0]);
    // headers
    TabularData headers = mbean.getHeaders(b.getBundleId());
    assertNotNull(headers);
    assertEquals(BundleStateMBean.HEADERS_TYPE, headers.getTabularType());
    assertTrue(headers.values().size() >= 4);
    assertEquals("org.apache.aries.jmx.test.bundleb", Header.from(headers.get(new Object[] { Constants.BUNDLE_SYMBOLICNAME })).getValue());
    // hosts
    long[] hosts = mbean.getHosts(fragc.getBundleId());
    assertEquals(1, hosts.length);
    assertEquals(a.getBundleId(), hosts[0]);
    // imported packages
    String[] imports = mbean.getImportedPackages(a.getBundleId());
    assertTrue(imports.length >= 3);
    List<String> importedPackages = Arrays.asList(imports);
    Version version = getPackageVersion("org.osgi.framework");
    assertTrue(importedPackages.contains("org.osgi.framework;" + version.toString()));
    assertTrue(importedPackages.contains("org.apache.aries.jmx.test.bundleb.api;1.1.0"));
    // last modified
    assertTrue(mbean.getLastModified(b.getBundleId()) > 0);
    // location
    assertEquals(b.getLocation(), mbean.getLocation(b.getBundleId()));
    // registered services
    long[] serviceIds = mbean.getRegisteredServices(a.getBundleId());
    assertEquals(1, serviceIds.length);
    // required bundles
    long[] required = mbean.getRequiredBundles(d.getBundleId());
    assertEquals(1, required.length);
    assertEquals(a.getBundleId(), required[0]);
    // requiring bundles
    long[] requiring = mbean.getRequiringBundles(a.getBundleId());
    assertEquals(2, requiring.length);
    assertTrue(fragc.getSymbolicName(), arrayContains(fragc.getBundleId(), requiring));
    assertTrue(d.getSymbolicName(), arrayContains(d.getBundleId(), requiring));
    // services in use
    long[] servicesInUse = mbean.getServicesInUse(a.getBundleId());
    assertEquals(1, servicesInUse.length);
    // start level
    long startLevel = mbean.getStartLevel(b.getBundleId());
    assertTrue(startLevel >= 0);
    // state
    assertEquals("ACTIVE", mbean.getState(b.getBundleId()));
    // isFragment
    assertFalse(mbean.isFragment(b.getBundleId()));
    assertTrue(mbean.isFragment(fragc.getBundleId()));
    // isRemovalPending
    assertFalse(mbean.isRemovalPending(b.getBundleId()));
    // isRequired
    assertTrue(mbean.isRequired(a.getBundleId()));
    assertTrue(mbean.isRequired(b.getBundleId()));
    // listBundles
    TabularData bundlesTable = mbean.listBundles();
    assertNotNull(bundlesTable);
    assertEquals(BundleStateMBean.BUNDLES_TYPE, bundlesTable.getTabularType());
    assertEquals(bundleContext.getBundles().length, bundlesTable.values().size());
    // notifications
    final List<Notification> received = new ArrayList<Notification>();
    mbeanServer.addNotificationListener(objectName, new NotificationListener() {

        public void handleNotification(Notification notification, Object handback) {
            received.add(notification);
        }
    }, null, null);
    assertEquals(Bundle.ACTIVE, b.getState());
    b.stop();
    assertEquals(Bundle.RESOLVED, b.getState());
    b.start();
    assertEquals(Bundle.ACTIVE, b.getState());
    int i = 0;
    while (received.size() < 2 && i < 3) {
        Thread.sleep(1000);
        i++;
    }
    assertEquals(2, received.size());
}
Also used : ArrayList(java.util.ArrayList) AttributeChangeNotification(javax.management.AttributeChangeNotification) Notification(javax.management.Notification) TabularData(javax.management.openmbean.TabularData) Version(org.osgi.framework.Version) NotificationListener(javax.management.NotificationListener) Test(org.junit.Test) AbstractIntegrationTest(org.apache.aries.jmx.AbstractIntegrationTest)

Example 24 with NotificationListener

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

the class ServiceStateMBeanTest method testAttributeChangeNotifications.

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

        public void handleNotification(Notification notification, Object handback) {
            if (notification instanceof AttributeChangeNotification) {
                attributeChanges.add((AttributeChangeNotification) notification);
            }
        }
    }, null, null);
    assertEquals("Precondition", 0, attributeChanges.size());
    long[] idsWithout = mbean.getServiceIds();
    String svc = "A String Service";
    ServiceRegistration reg = bundleContext.registerService(String.class.getName(), svc, null);
    long id = (Long) reg.getReference().getProperty(Constants.SERVICE_ID);
    long[] idsWith = new long[idsWithout.length + 1];
    System.arraycopy(idsWithout, 0, idsWith, 0, idsWithout.length);
    idsWith[idsWith.length - 1] = id;
    Arrays.sort(idsWith);
    waitForListToReachSize(attributeChanges, 1);
    AttributeChangeNotification ac = attributeChanges.get(0);
    assertEquals("ServiceIds", ac.getAttributeName());
    long seq1 = ac.getSequenceNumber();
    assertTrue(Arrays.equals(idsWithout, (long[]) ac.getOldValue()));
    assertTrue(Arrays.equals(idsWith, (long[]) ac.getNewValue()));
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("somekey", "someval");
    reg.setProperties(props);
    // Setting the properties updates the service registration, however it should not cause the attribute notification
    // Give the system a bit of time to send potential notifications
    Thread.sleep(500);
    assertEquals("Changing the service registration should not cause an attribute notification", 1, attributeChanges.size());
    reg.unregister();
    waitForListToReachSize(attributeChanges, 2);
    AttributeChangeNotification ac2 = attributeChanges.get(1);
    assertEquals("ServiceIds", ac2.getAttributeName());
    assertEquals(seq1 + 1, ac2.getSequenceNumber());
    assertTrue(Arrays.equals(idsWith, (long[]) ac2.getOldValue()));
    assertTrue(Arrays.equals(idsWithout, (long[]) ac2.getNewValue()));
}
Also used : AttributeChangeNotification(javax.management.AttributeChangeNotification) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) AttributeChangeNotification(javax.management.AttributeChangeNotification) Notification(javax.management.Notification) NotificationListener(javax.management.NotificationListener) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test) AbstractIntegrationTest(org.apache.aries.jmx.AbstractIntegrationTest)

Example 25 with NotificationListener

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

the class BundleStateTest method createBundle.

private void createBundle(StateConfig stateConfig, final List<Notification> received, final List<AttributeChangeNotification> attributeChanges) throws Exception {
    BundleContext context = mock(BundleContext.class);
    when(context.getBundles()).thenReturn(new Bundle[] {});
    PackageAdmin admin = mock(PackageAdmin.class);
    StartLevel startLevel = mock(StartLevel.class);
    Logger logger = mock(Logger.class);
    BundleState bundleState = new BundleState(context, admin, startLevel, stateConfig, logger);
    Bundle b1 = mock(Bundle.class);
    when(b1.getBundleId()).thenReturn(new Long(9));
    when(b1.getSymbolicName()).thenReturn("bundle");
    when(b1.getLocation()).thenReturn("file:/location");
    BundleEvent installedEvent = mock(BundleEvent.class);
    when(installedEvent.getBundle()).thenReturn(b1);
    when(installedEvent.getType()).thenReturn(BundleEvent.INSTALLED);
    BundleEvent resolvedEvent = mock(BundleEvent.class);
    when(resolvedEvent.getBundle()).thenReturn(b1);
    when(resolvedEvent.getType()).thenReturn(BundleEvent.RESOLVED);
    MBeanServer server = mock(MBeanServer.class);
    // setup for notification
    ObjectName objectName = new ObjectName(OBJECTNAME);
    bundleState.preRegister(server, objectName);
    bundleState.postRegister(true);
    // add NotificationListener to receive the events
    bundleState.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 BundleListener registered with BundleContext to issue BundleEvents
    ArgumentCaptor<BundleListener> argument = ArgumentCaptor.forClass(BundleListener.class);
    verify(context).addBundleListener(argument.capture());
    // send events
    BundleListener listener = argument.getValue();
    listener.bundleChanged(installedEvent);
    listener.bundleChanged(resolvedEvent);
    // shutdown dispatcher via unregister callback
    bundleState.postDeregister();
    // check the BundleListener is cleaned up
    verify(context).removeBundleListener(listener);
    ExecutorService dispatcher = bundleState.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) ObjectName(javax.management.ObjectName) PackageAdmin(org.osgi.service.packageadmin.PackageAdmin) ExecutorService(java.util.concurrent.ExecutorService) StartLevel(org.osgi.service.startlevel.StartLevel) BundleEvent(org.osgi.framework.BundleEvent) BundleListener(org.osgi.framework.BundleListener) BundleContext(org.osgi.framework.BundleContext) MBeanServer(javax.management.MBeanServer) NotificationListener(javax.management.NotificationListener)

Aggregations

NotificationListener (javax.management.NotificationListener)52 Notification (javax.management.Notification)36 ObjectName (javax.management.ObjectName)18 MBeanServer (javax.management.MBeanServer)11 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