Search in sources :

Example 21 with ServiceListener

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

the class MultiPropertyFilterIndex method serviceChanged.

public void serviceChanged(ServiceEvent event) {
    if (isApplicable(event.getServiceReference())) {
        List<MultiPropertyKey> keys = createKeys(event.getServiceReference());
        List<ServiceListener> list = new ArrayList<ServiceListener>();
        synchronized (m_keyToListenersMap) {
            for (int i = 0; i < keys.size(); i++) {
                // TODO fix
                MultiPropertyKey key = keys.get(i);
                List<ServiceListener> listeners = m_keyToListenersMap.get(key);
                if (listeners != null) {
                    list.addAll(listeners);
                }
            }
        }
        if (list != null) {
            Iterator<ServiceListener> iterator = list.iterator();
            while (iterator.hasNext()) {
                ServiceListener listener = iterator.next();
                listener.serviceChanged(event);
            }
        }
    }
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 22 with ServiceListener

use of org.osgi.framework.ServiceListener 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 23 with ServiceListener

use of org.osgi.framework.ServiceListener in project karaf by apache.

the class MavenTest method awaitMavenResolver.

/**
 * Invoke config admin task and await reregistration of {@link MavenResolver} service
 */
private void awaitMavenResolver(Runnable task) throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    ServiceListener listener = new ServiceListener() {

        @Override
        public void serviceChanged(ServiceEvent event) {
            if (event.getType() == ServiceEvent.UNREGISTERING || event.getType() == ServiceEvent.REGISTERED) {
                latch.countDown();
            }
        }
    };
    bundleContext.addServiceListener(listener, "(objectClass=org.ops4j.pax.url.mvn.MavenResolver)");
    try {
        task.run();
        assertTrue(latch.await(5, TimeUnit.SECONDS));
    } finally {
        bundleContext.removeServiceListener(listener);
    }
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) ServiceEvent(org.osgi.framework.ServiceEvent) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 24 with ServiceListener

use of org.osgi.framework.ServiceListener 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)

Example 25 with ServiceListener

use of org.osgi.framework.ServiceListener in project ecf by eclipse.

the class Activator method start.

/* (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
public void start(final BundleContext context) throws Exception {
    final ServiceReference configAdminServiceRef = context.getServiceReference(ConfigurationAdmin.class.getName());
    if (configAdminServiceRef == null) {
        System.err.println("You don't have config admin deployed. Some tests will fail that require configuration!");
        return;
    }
    final ConfigurationAdmin configAdmin = (ConfigurationAdmin) context.getService(configAdminServiceRef);
    Configuration config = configAdmin.createFactoryConfiguration(DnsSdTestHelper.ECF_DISCOVERY_DNSSD + ".locator", null);
    Dictionary properties = new Hashtable();
    properties.put(IDnsSdDiscoveryConstants.CA_SEARCH_PATH, new String[] { DnsSdTestHelper.DOMAIN });
    properties.put(IDnsSdDiscoveryConstants.CA_RESOLVER, DnsSdTestHelper.DNS_RESOLVER);
    properties.put(IDnsSdDiscoveryConstants.CA_TSIG_KEY, DnsSdTestHelper.TSIG_KEY);
    properties.put(IDnsSdDiscoveryConstants.CA_TSIG_KEY_NAME, DnsSdTestHelper.TSIG_KEY_NAME);
    config.update(properties);
    String filter = "(" + Constants.SERVICE_PID + "=" + config.getPid() + ")";
    // add the service listener
    locListener = new ServiceListener() {

        public void serviceChanged(ServiceEvent event) {
            switch(event.getType()) {
                case ServiceEvent.REGISTERED:
                    ServiceReference serviceReference = event.getServiceReference();
                    discoveryLocator = (IDiscoveryLocator) context.getService(serviceReference);
                    synchronized (locLock) {
                        locLock.notifyAll();
                    }
            }
        }
    };
    context.addServiceListener(locListener, filter);
    // try to get the service initially
    ServiceReference[] references = context.getServiceReferences(IDiscoveryLocator.class.getName(), filter);
    if (references != null) {
        for (int i = 0; i < references.length; ) {
            ServiceReference serviceReference = references[i];
            discoveryLocator = (IDiscoveryLocator) context.getService(serviceReference);
            synchronized (locLock) {
                locLock.notifyAll();
            }
        }
    }
    // advertiser
    config = configAdmin.createFactoryConfiguration(DnsSdTestHelper.ECF_DISCOVERY_DNSSD + ".advertiser", null);
    properties = new Hashtable();
    properties.put(IDnsSdDiscoveryConstants.CA_SEARCH_PATH, new String[] { DnsSdTestHelper.DOMAIN });
    properties.put(IDnsSdDiscoveryConstants.CA_RESOLVER, DnsSdTestHelper.DNS_RESOLVER);
    properties.put(IDnsSdDiscoveryConstants.CA_TSIG_KEY, DnsSdTestHelper.TSIG_KEY);
    properties.put(IDnsSdDiscoveryConstants.CA_TSIG_KEY_NAME, DnsSdTestHelper.TSIG_KEY_NAME);
    config.update(properties);
    filter = "(" + Constants.SERVICE_PID + "=" + config.getPid() + ")";
    // add the service listener
    advListener = new ServiceListener() {

        public void serviceChanged(ServiceEvent event) {
            switch(event.getType()) {
                case ServiceEvent.REGISTERED:
                    ServiceReference serviceReference = event.getServiceReference();
                    discoveryAdvertiser = (IDiscoveryAdvertiser) context.getService(serviceReference);
                    synchronized (advLock) {
                        advLock.notifyAll();
                    }
            }
        }
    };
    context.addServiceListener(advListener, filter);
    // try to get the service initially
    references = context.getServiceReferences(IDiscoveryAdvertiser.class.getName(), filter);
    if (references != null) {
        for (int i = 0; i < references.length; ) {
            ServiceReference serviceReference = references[i];
            discoveryAdvertiser = (IDiscoveryAdvertiser) context.getService(serviceReference);
            synchronized (advLock) {
                advLock.notifyAll();
            }
        }
    }
}
Also used : Dictionary(java.util.Dictionary) ServiceListener(org.osgi.framework.ServiceListener) Configuration(org.osgi.service.cm.Configuration) IDiscoveryAdvertiser(org.eclipse.ecf.discovery.IDiscoveryAdvertiser) Hashtable(java.util.Hashtable) ServiceEvent(org.osgi.framework.ServiceEvent) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) IDiscoveryLocator(org.eclipse.ecf.discovery.IDiscoveryLocator) ServiceReference(org.osgi.framework.ServiceReference)

Aggregations

ServiceListener (org.osgi.framework.ServiceListener)28 ServiceEvent (org.osgi.framework.ServiceEvent)21 ServiceReference (org.osgi.framework.ServiceReference)16 Bundle (org.osgi.framework.Bundle)8 Test (org.junit.Test)7 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)6 IOException (java.io.IOException)5 File (java.io.File)4 FileInputStream (java.io.FileInputStream)4 ArrayList (java.util.ArrayList)4 TimeoutException (java.util.concurrent.TimeoutException)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 BundleContext (org.osgi.framework.BundleContext)4 BundleException (org.osgi.framework.BundleException)4 Hashtable (java.util.Hashtable)3 Dictionary (java.util.Dictionary)2 List (java.util.List)2 Entry (java.util.Map.Entry)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 ObjectName (javax.management.ObjectName)2