Search in sources :

Example 41 with ServiceEvent

use of org.osgi.framework.ServiceEvent in project felix by apache.

the class TrackedTest method testHideAspect.

@Test
public void testHideAspect() {
    System.out.println("testHideAspect");
    TestCustomizer customizer = new TestCustomizer();
    ServiceTracker tracker = new TestTracker(customizer);
    tracker.open();
    Tracked tracked = tracker.getTracked();
    ServiceReference<?>[] initialReferences = new ServiceReference[] { createServiceReference(1L), createServiceReference(2L, 1L, 10), createServiceReference(3L), createServiceReference(4L, 1L, 5), createServiceReference(5L, 3L, 5) };
    tracked.setInitial(initialReferences);
    tracked.trackInitial();
    tracked.getExecutor().execute();
    assertArrayEquals(new Long[] { 2L, 5L }, customizer.getServiceReferenceIds());
    // create a service event that registers another but lower ranked aspect for service with id 1.
    ServiceReference<?> newReference = createServiceReference(6L, 1L, 8);
    ServiceEvent event = new ServiceEvent(ServiceEvent.REGISTERED, newReference);
    tracked.serviceChanged(event);
    assertArrayEquals(new Long[] { 2L, 5L }, customizer.getServiceReferenceIds());
    // create a service event that unregisters service with id 2, we would expect it to be swapped with 6.
    event = new ServiceEvent(ServiceEvent.UNREGISTERING, initialReferences[1]);
    tracked.serviceChanged(event);
    assertArrayEquals(new Long[] { 5L, 6L }, customizer.getServiceReferenceIds());
    // create a service event that unregisters service with id 6, we would expect it to be swapped with 4.
    event = new ServiceEvent(ServiceEvent.UNREGISTERING, newReference);
    tracked.serviceChanged(event);
    assertArrayEquals(new Long[] { 5L, 4L }, customizer.getServiceReferenceIds());
    // create a service event that registers a higher ranked aspect for service with id 1.
    ServiceReference<?> higherRankedReference = createServiceReference(7L, 1L, 15);
    ServiceEvent addHigherRankedEvent = new ServiceEvent(ServiceEvent.REGISTERED, higherRankedReference);
    tracked.serviceChanged(addHigherRankedEvent);
    assertArrayEquals(new Long[] { 5L, 7L }, customizer.getServiceReferenceIds());
}
Also used : Tracked(org.apache.felix.dm.tracker.ServiceTracker.Tracked) ServiceTracker(org.apache.felix.dm.tracker.ServiceTracker) ServiceEvent(org.osgi.framework.ServiceEvent) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Example 42 with ServiceEvent

use of org.osgi.framework.ServiceEvent in project felix by apache.

the class BundlesProbes method serviceChanged.

// //////////////////////////////////////////////////////
// ServiceListener                              //
// //////////////////////////////////////////////////////
public void serviceChanged(ServiceEvent event) {
    ServiceReference sref = event.getServiceReference();
    Object service = bc.getService(sref);
    if (this.server == null && event.getType() == ServiceEvent.REGISTERED && service instanceof MBeanServer) {
    // this.connectToAgent(sref);
    }
    if (this.server != null) {
        if (event.getType() == ServiceEvent.UNREGISTERING && service instanceof MBeanServer) {
        // this.disconnectFromAgent();
        } else {
            this.sendRemoteNotification(ServiceEvent.class.getName(), sref.getBundle().getBundleId(), event.getType(), (String) sref.getBundle().getHeaders().get(Constants.BUNDLE_NAME));
        }
    }
}
Also used : ServiceEvent(org.osgi.framework.ServiceEvent) ServiceReference(org.osgi.framework.ServiceReference) MBeanServer(javax.management.MBeanServer)

Example 43 with ServiceEvent

use of org.osgi.framework.ServiceEvent in project felix by apache.

the class ServiceRegistry method unregisterService.

/**
 * Unregister a service.
 * @param reg : the service registration to unregister
 */
public void unregisterService(ServiceRegistrationImpl reg) {
    m_regs.remove(reg);
    fireServiceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, reg.getReference()));
}
Also used : ServiceEvent(org.osgi.framework.ServiceEvent)

Example 44 with ServiceEvent

use of org.osgi.framework.ServiceEvent in project felix by apache.

the class Activator method start.

// /////////////////////////////////////
// BundleActivator           //
// /////////////////////////////////////
public void start(BundleContext context) {
    m_context = context;
    // Listen for factory service events.
    ServiceListener sl = new ServiceListener() {

        public void serviceChanged(ServiceEvent event) {
            ServiceReference ref = event.getServiceReference();
            Object svcObj = m_context.getService(ref);
            if (event.getType() == ServiceEvent.REGISTERED) {
                synchronized (Activator.this) {
                    // !!!!!!!!!! ORDER MATTERS (Inheritance pb)
                    if (!m_pluginList.contains(svcObj)) {
                        if (svcObj instanceof CommonPlugin) {
                            m_commonpluginList.add(svcObj);
                            firePropertyChangedEvent(CommonPlugin.COMMON_PLUGIN_ADDED, null, svcObj);
                        } else if (svcObj instanceof Plugin) {
                            m_pluginList.add(svcObj);
                            firePropertyChangedEvent(Plugin.PLUGIN_ADDED, null, svcObj);
                        }
                    }
                }
            } else if (event.getType() == ServiceEvent.UNREGISTERING) {
                synchronized (Activator.this) {
                    removePropertyChangeListener((PropertyChangeListener) svcObj);
                    if (svcObj instanceof CommonPlugin) {
                        m_commonpluginList.remove(svcObj);
                        firePropertyChangedEvent(CommonPlugin.COMMON_PLUGIN_REMOVED, null, svcObj);
                    } else if (svcObj instanceof Plugin) {
                        m_pluginList.remove(svcObj);
                        firePropertyChangedEvent(Plugin.PLUGIN_REMOVED, null, svcObj);
                    }
                }
            } else {
                m_context.ungetService(ref);
            }
        }
    };
    try {
        m_context.addServiceListener(sl, "(|(objectClass=" + Plugin.class.getName() + ")(objectClass=" + CommonPlugin.class.getName() + "))");
    } catch (InvalidSyntaxException ex) {
        System.err.println("ShellGuiActivator: Cannot add service listener.");
        System.err.println("ShellGuiActivator: " + ex);
    }
    // Create and display the frame.
    if (m_frame == null) {
        m_frame = new JFrame("OSGi GUI Remote Manager");
        m_frame.setUndecorated(true);
        m_frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
        m_frame.setIconImage(Toolkit.getDefaultToolkit().getImage(m_context.getBundle().getResource("images/logo.gif")));
        // m_frame.setResizable(false);
        // m_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // TODO : add a windowListener and use a Preferences service to save screen size
        m_frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent we) {
                JFrame jf = (JFrame) we.getWindow();
                System.out.println(" Console.gui : window closing (" + jf.getSize().height + "*" + jf.getSize().width + ")");
            }

            public void windowClosed(WindowEvent we) {
                JFrame jf = (JFrame) we.getWindow();
                System.out.println(" Console.gui : window closed (" + jf.getSize().height + "*" + jf.getSize().width + ")");
            }
        });
        Dimension maxdim = m_frame.getToolkit().getScreenSize();
        int m_width = maxdim.width - 100;
        int m_height = maxdim.height - 100;
        m_frame.setBounds((int) ((maxdim.width - m_width) / 2), 20, m_width, m_height);
        // Right panel
        JSplitPane rightSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new NodePanel(this, context), new CommonPanel(this));
        rightSplitPane.setOneTouchExpandable(true);
        rightSplitPane.setDividerLocation((int) (m_height * 2 / 3));
        // General Panel
        this.nodesTree = new NodesTree(this, context);
        JSplitPane gSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, this.nodesTree, rightSplitPane);
        gSplitPane.setOneTouchExpandable(true);
        gSplitPane.setDividerLocation((int) (m_width / 4));
        m_frame.getContentPane().add(gSplitPane);
    }
    // Now try to manually initialize the plugin list
    // since some might already be available.
    // initializePlugins();
    m_frame.setVisible(true);
    this.nodesTree.runDiscovery();
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) PropertyChangeListener(java.beans.PropertyChangeListener) WindowAdapter(java.awt.event.WindowAdapter) Dimension(java.awt.Dimension) ServiceReference(org.osgi.framework.ServiceReference) CommonPlugin(org.apache.felix.mosgi.console.ifc.CommonPlugin) JFrame(javax.swing.JFrame) ServiceEvent(org.osgi.framework.ServiceEvent) WindowEvent(java.awt.event.WindowEvent) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) JSplitPane(javax.swing.JSplitPane) Plugin(org.apache.felix.mosgi.console.ifc.Plugin) CommonPlugin(org.apache.felix.mosgi.console.ifc.CommonPlugin)

Example 45 with ServiceEvent

use of org.osgi.framework.ServiceEvent in project fabric8 by jboss-fuse.

the class ZooKeeperClusterBootstrapImpl method cleanInternal.

private BootstrapConfiguration cleanInternal(final BundleContext syscontext, final BootstrapConfiguration bootConfig, RuntimeProperties runtimeProps) throws TimeoutException {
    LOGGER.debug("Begin clean fabric");
    try {
        Configuration zkClientCfg = null;
        Configuration zkServerCfg = null;
        Configuration[] configsSet = configAdmin.get().listConfigurations("(|(service.factoryPid=io.fabric8.zookeeper.server)(service.pid=io.fabric8.zookeeper))");
        if (configsSet != null) {
            for (Configuration cfg : configsSet) {
                // let's explicitly delete client config first
                if ("io.fabric8.zookeeper".equals(cfg.getPid())) {
                    zkClientCfg = cfg;
                }
                if ("io.fabric8.zookeeper.server".equals(cfg.getFactoryPid())) {
                    zkServerCfg = cfg;
                }
            }
        }
        File karafData = new File(data);
        // Setup the listener for unregistration of {@link BootstrapConfiguration}
        final CountDownLatch unregisterLatch = new CountDownLatch(1);
        ServiceListener listener = new ServiceListener() {

            @Override
            public void serviceChanged(ServiceEvent event) {
                if (event.getType() == ServiceEvent.UNREGISTERING) {
                    LOGGER.debug("Unregistering BootstrapConfiguration");
                    bootConfig.getComponentContext().getBundleContext().removeServiceListener(this);
                    unregisterLatch.countDown();
                }
            }
        };
        String filter = "(objectClass=" + BootstrapConfiguration.class.getName() + ")";
        // FABRIC-1052: register listener using the same bundle context that is used for listeners related to SCR
        bootConfig.getComponentContext().getBundleContext().addServiceListener(listener, filter);
        CountDownLatch unregisterLatch2 = null;
        if (syscontext.getServiceReference(CuratorComplete.class) != null) {
            unregisterLatch2 = new CountDownLatch(1);
            final CountDownLatch finalUnregisterLatch = unregisterLatch2;
            listener = new ServiceListener() {

                @Override
                public void serviceChanged(ServiceEvent event) {
                    if (event.getType() == ServiceEvent.UNREGISTERING) {
                        LOGGER.debug("Unregistering CuratorComplete");
                        bootConfig.getComponentContext().getBundleContext().removeServiceListener(this);
                        finalUnregisterLatch.countDown();
                    }
                }
            };
            bootConfig.getComponentContext().getBundleContext().addServiceListener(listener, "(objectClass=" + CuratorComplete.class.getName() + ")");
        }
        // Disable the BootstrapConfiguration component
        // ENTESB-4827: disabling BootstrapConfiguration leads to deactivation of FabricService and ProfileUrlHandler
        // and we have race condition if we're --cleaning after recently created fabric. previous fabric
        // started FabricConfigAdminBridge which scheduled CM updates for tens of PIDs - among others,
        // org.ops4j.pax.web, which leads to an attempt to reconfigure Jetty with "profile:jetty.xml"
        // and if we disable ProfileUrlHandler we may loose Jetty instance
        LOGGER.debug("Disable BootstrapConfiguration");
        ComponentContext componentContext = bootConfig.getComponentContext();
        componentContext.disableComponent(BootstrapConfiguration.COMPONENT_NAME);
        if (!unregisterLatch.await(30, TimeUnit.SECONDS))
            throw new TimeoutException("Timeout for unregistering BootstrapConfiguration service");
        if (unregisterLatch2 != null && !unregisterLatch2.await(30, TimeUnit.SECONDS))
            throw new TimeoutException("Timeout for unregistering CuratorComplete service");
        // Do the cleanup
        runtimeProps.clearRuntimeAttributes();
        cleanConfigurations(syscontext, zkClientCfg, zkServerCfg);
        cleanZookeeperDirectory(karafData);
        cleanGitDirectory(karafData);
        // Setup the registration listener for the new {@link BootstrapConfiguration}
        final CountDownLatch registerLatch = new CountDownLatch(1);
        final AtomicReference<ServiceReference<?>> sref = new AtomicReference<ServiceReference<?>>();
        listener = new ServiceListener() {

            @Override
            public void serviceChanged(ServiceEvent event) {
                if (event.getType() == ServiceEvent.REGISTERED) {
                    LOGGER.debug("Registered BootstrapConfiguration");
                    syscontext.removeServiceListener(this);
                    sref.set(event.getServiceReference());
                    registerLatch.countDown();
                }
            }
        };
        syscontext.addServiceListener(listener, "(objectClass=" + BootstrapConfiguration.class.getName() + ")");
        // Enable the {@link BootstrapConfiguration} component and await the registration of the respective service
        LOGGER.debug("Enable BootstrapConfiguration");
        componentContext.enableComponent(BootstrapConfiguration.COMPONENT_NAME);
        if (!registerLatch.await(30, TimeUnit.SECONDS))
            throw new TimeoutException("Timeout for registering BootstrapConfiguration service");
        return (BootstrapConfiguration) syscontext.getService(sref.get());
    } catch (RuntimeException rte) {
        throw rte;
    } catch (TimeoutException toe) {
        throw toe;
    } catch (Exception ex) {
        throw new FabricException("Unable to delete zookeeper configuration", ex);
    } finally {
        LOGGER.debug("End clean fabric");
    }
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) Configuration(org.osgi.service.cm.Configuration) ComponentContext(org.osgi.service.component.ComponentContext) BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) FabricException(io.fabric8.api.FabricException) AtomicReference(java.util.concurrent.atomic.AtomicReference) CuratorComplete(io.fabric8.api.CuratorComplete) CountDownLatch(java.util.concurrent.CountDownLatch) TimeoutException(java.util.concurrent.TimeoutException) BundleException(org.osgi.framework.BundleException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException) ServiceReference(org.osgi.framework.ServiceReference) ServiceEvent(org.osgi.framework.ServiceEvent) File(java.io.File) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

ServiceEvent (org.osgi.framework.ServiceEvent)57 ServiceReference (org.osgi.framework.ServiceReference)31 Test (org.junit.Test)24 BundleContext (org.osgi.framework.BundleContext)24 ServiceListener (org.osgi.framework.ServiceListener)20 Bundle (org.osgi.framework.Bundle)18 Hashtable (java.util.Hashtable)15 ServiceRegistration (org.osgi.framework.ServiceRegistration)13 Collection (java.util.Collection)6 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)6 IOException (java.io.IOException)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 File (java.io.File)4 FileInputStream (java.io.FileInputStream)4 Dictionary (java.util.Dictionary)4 HashMap (java.util.HashMap)4 ServiceRegistrationHolder (org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder)4 ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3