Java Code Examples for org.osgi.framework.ServiceRegistration

The following are top voted examples for showing how to use org.osgi.framework.ServiceRegistration. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: gemini.blueprint   File: OsgiServiceFactoryBeanTest.java   View source code 6 votes vote down vote up
public void testUpdateableProperties() throws Exception {
    UpdateableProperties properties = new UpdateableProperties();
    properties.setProperty("steve", "vai");

    exporter.setServiceProperties(properties);
    exporter.setTarget("string");
    exporter.setBeanName("string");
    exporter.setInterfaces(new Class<?>[]{Serializable.class});
    beanFactoryControl.replay();
    exporter.afterPropertiesSet();

    ServiceRegistration reg = exporter.getObject();
    assertEquals("vai", reg.getReference().getProperty("steve"));
    assertNull(reg.getReference().getProperty("updated"));

    properties.setProperty("steve", "jobs");
    properties.setProperty("updated", "true");
    properties.update();

    assertEquals("jobs", reg.getReference().getProperty("steve"));
    assertNotNull(reg.getReference().getProperty("updated"));
}
 
Example 2
Project: neoscada   File: ConnectionManager.java   View source code 6 votes vote down vote up
/**
 * Register the current connection as an OSGi service
 */
private EntryImpl registerConnection ( final ConnectionDescriptor connectionDescriptor, final ConnectionService connectionService )
{
    final Class<?>[] interfaces = connectionService.getSupportedInterfaces ();

    final String[] clazzes = new String[interfaces.length];

    int i = 0;
    for ( final Class<?> iface : interfaces )
    {
        clazzes[i] = iface.getName ();
        i++;
    }

    final Dictionary<String, String> properties = new Hashtable<String, String> ();
    properties.put ( ConnectionService.CONNECTION_URI, connectionDescriptor.getConnectionInformation ().toString () );
    if ( connectionDescriptor.getServiceId () != null )
    {
        properties.put ( Constants.SERVICE_PID, connectionDescriptor.getServiceId () );
    }
    final ServiceRegistration<?> serviceRegistration = this.context.registerService ( clazzes, connectionService, properties );
    return new EntryImpl ( connectionDescriptor, connectionService, serviceRegistration );
}
 
Example 3
Project: neoscada   File: ConnectionLoginHandler.java   View source code 6 votes vote down vote up
@Override
public synchronized void dispose ()
{
    if ( this.registrations != null )
    {
        for ( final ServiceRegistration<?> reg : this.registrations )
        {
            reg.unregister ();
        }
        this.registrations = null;
    }

    if ( this.connectionService != null )
    {
        if ( this.connectionStateListener != null )
        {
            this.connectionService.getConnection ().removeConnectionStateListener ( this.connectionStateListener );
        }

        this.connectionService.dispose ();
        this.connectionService = null;
    }
}
 
Example 4
Project: neoscada   File: Activator.java   View source code 6 votes vote down vote up
private void registerService ( final String id, final String uri, final ConnectionService service )
{
    final Dictionary<String, Object> properties = new Hashtable<String, Object> ();
    properties.put ( Constants.SERVICE_PID, id );
    properties.put ( ConnectionService.CONNECTION_URI, uri );

    final Class<?>[] clazzes = service.getSupportedInterfaces ();

    final String[] clazzStr = new String[clazzes.length];
    for ( int i = 0; i < clazzes.length; i++ )
    {
        clazzStr[i] = clazzes[i].getName ();
    }

    final ServiceRegistration<?> handle = getBundle ().getBundleContext ().registerService ( clazzStr, service, properties );
    this.registrations.add ( handle );
}
 
Example 5
Project: neoscada   File: FactoryImpl.java   View source code 6 votes vote down vote up
@Override
protected Entry<ComponentFactory> createService ( final UserInformation userInformation, final String configurationId, final BundleContext context, final Map<String, String> parameters ) throws Exception
{
    final ConfigurationDataHelper cfg = new ConfigurationDataHelper ( parameters );
    final String xml = cfg.getStringNonEmpty ( "configuration" );

    final XMIResource xmi = new XMIResourceImpl ();
    final Map<?, ?> options = new HashMap<Object, Object> ();
    final InputSource is = new InputSource ( new StringReader ( xml ) );
    xmi.load ( is, options );

    final Object c = EcoreUtil.getObjectByType ( xmi.getContents (), ParserPackage.Literals.COMPONENT );
    if ( ! ( c instanceof Component ) )
    {
        throw new RuntimeException ( String.format ( "Configuration did not contain an object of type %s", Component.class.getName () ) );
    }

    final ComponentFactoryWrapper wrapper = new ComponentFactoryWrapper ( this.executor, (Component)c );

    final Dictionary<String, ?> properties = new Hashtable<> ();
    final ServiceRegistration<ComponentFactory> handle = context.registerService ( ComponentFactory.class, wrapper, properties );

    return new Entry<ComponentFactory> ( configurationId, wrapper, handle );
}
 
Example 6
Project: neoscada   File: ProxyEventQueryFactory.java   View source code 6 votes vote down vote up
@Override
protected Entry<ProxyEventQuery> createService ( final UserInformation userInformation, final String configurationId, final BundleContext context, final Map<String, String> parameters ) throws Exception
{
    logger.info ( "Creating new proxy query: {}", configurationId );

    final ConfigurationDataHelper cfg = new ConfigurationDataHelper ( parameters );

    final int poolSize = cfg.getIntegerChecked ( "poolSize", "'poolSize' must be set" );
    if ( poolSize <= 0 )
    {
        throw new IllegalArgumentException ( "'poolSize' must be a positive integer greater zero" );
    }

    final ProxyEventQuery service = new ProxyEventQuery ( context, this.executor, poolSize, parameters );

    final Hashtable<String, Object> properties = new Hashtable<String, Object> ();
    properties.put ( Constants.SERVICE_PID, configurationId );
    final ServiceRegistration<EventQuery> handle = context.registerService ( EventQuery.class, service, properties );

    return new Entry<ProxyEventQuery> ( configurationId, service, handle );
}
 
Example 7
Project: neoscada   File: JdbcAuthenticationServiceFactory.java   View source code 6 votes vote down vote up
@Override
protected Entry<JdbcAuthenticationService> createService ( final UserInformation userInformation, final String configurationId, final BundleContext context, final Map<String, String> parameters ) throws Exception
{
    logger.debug ( "Creating new service: {}", configurationId );
    final JdbcAuthenticationService service = new JdbcAuthenticationService ( context, configurationId );
    service.update ( parameters );

    final Dictionary<String, Object> properties = new Hashtable<String, Object> ();
    properties.put ( Constants.SERVICE_DESCRIPTION, "JDBC based authenticator" );
    properties.put ( Constants.SERVICE_PID, configurationId );
    properties.put ( Constants.SERVICE_VENDOR, "Eclipse SCADA Project" );

    final ServiceRegistration<?> handle;

    if ( service.isUserManager () )
    {
        handle = context.registerService ( new String[] { AuthenticationService.class.getName () }, service, properties );
    }
    else
    {
        handle = context.registerService ( new String[] { AuthenticationService.class.getName (), UserManagerService.class.getName () }, service, properties );
    }

    return new Entry<JdbcAuthenticationService> ( configurationId, service, handle );
}
 
Example 8
Project: neoscada   File: AbstractServiceFactory.java   View source code 6 votes vote down vote up
@Override
public synchronized void delete ( final UserInformation information, final String configurationId ) throws Exception
{
    final ServiceRegistration<?> reg = this.regs.remove ( configurationId );
    if ( reg != null )
    {
        reg.unregister ();
    }

    final Service service = this.instances.remove ( configurationId );

    if ( service != null )
    {
        service.dispose ();
    }
}
 
Example 9
Project: neoscada   File: BeanConfigurationFactory.java   View source code 6 votes vote down vote up
@Override
protected Entry<BeanServiceInstance> createService ( final UserInformation userInformation, final String configurationId, final BundleContext context, final Map<String, String> parameters ) throws Exception
{
    final BeanServiceInstance bean = new BeanServiceInstance ( this.beanClazz.newInstance () );

    if ( this.mergeIdField )
    {
        parameters.put ( "id", configurationId );
    }

    bean.update ( parameters );

    final ServiceRegistration<?> reg = context.registerService ( this.beanClazz.getName (), bean.getTargetBean (), bean.getProperties () );

    return new Entry<BeanServiceInstance> ( configurationId, bean, reg );
}
 
Example 10
Project: gemini.blueprint   File: ServiceRegistrationWrapperTest.java   View source code 6 votes vote down vote up
protected void setUp() throws Exception {
	actualRegistration = createMock(ServiceRegistration.class);

	final ListenerNotifier notifier =
			new ListenerNotifier(
					new OsgiServiceRegistrationListener[] { new SimpleOsgiServiceRegistrationListener() });

	ServiceRegistrationDecorator registrationDecorator = new ServiceRegistrationDecorator(actualRegistration);
	registrationDecorator.setNotifier(new UnregistrationNotifier() {

		public void unregister(Map properties) {
			notifier.callUnregister(null, properties);
		}
	});

	registration = registrationDecorator;

	SimpleOsgiServiceRegistrationListener.REGISTERED = 0;
	SimpleOsgiServiceRegistrationListener.UNREGISTERED = 0;
}
 
Example 11
Project: hashsdn-controller   File: OsgiRegistrationUtilTest.java   View source code 6 votes vote down vote up
@Test
public void testRegisterService() throws Exception {
    final BundleContext bundleContext = mock(BundleContext.class);
    ServiceRegistration<?> registration = mockServiceRegistration();
    doReturn(registration).when(bundleContext).registerService(String.class, "string", null);
    ServiceRegistration<?> registration2 = mockServiceRegistration();
    doReturn(registration2).when(bundleContext).registerService(Object.class, "string", null);

    AutoCloseable aggregatedRegister = OsgiRegistrationUtil.registerService(bundleContext, "string", String.class,
            Object.class);
    aggregatedRegister.close();

    InOrder inOrder = Mockito.inOrder(registration, registration2);
    inOrder.verify(registration2).unregister();
    inOrder.verify(registration).unregister();
}
 
Example 12
Project: gemini.blueprint   File: ListListenerAdapterTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public ServiceRegistration registerService(String[] clazzes, final Object service, Dictionary properties) {
    MockServiceRegistration reg = new MockServiceRegistration(properties);

    MockServiceReference ref = new MockServiceReference(getBundle(), properties, reg, clazzes) {

        @Override
        public Object getProperty(String key) {
            if (SERVICE_PROPERTY.equals(key)) {
                return service;
            } else {
                return super.getProperty(key);
            }
        }

    };
    ServiceEvent event = new ServiceEvent(ServiceEvent.REGISTERED, ref);

    for (Iterator iter = serviceListeners.iterator(); iter.hasNext();) {
        ServiceListener listener = (ServiceListener) iter.next();
        listener.serviceChanged(event);
    }

    return reg;
}
 
Example 13
Project: gemini.blueprint   File: CMUtils.java   View source code 6 votes vote down vote up
public static ServiceRegistration registerManagedService(BundleContext bundleContext, ManagedService listener,
		String pid) {

       Dictionary<String, Object> props = new Hashtable<String, Object>();
	props.put(Constants.SERVICE_PID, pid);
	Bundle bundle = bundleContext.getBundle();
	props.put(Constants.BUNDLE_SYMBOLICNAME, OsgiStringUtils.nullSafeSymbolicName(bundle));
	props.put(Constants.BUNDLE_VERSION, OsgiBundleUtils.getBundleVersion(bundle));

	return bundleContext.registerService(ManagedService.class.getName(), listener, props);
}
 
Example 14
Project: hashsdn-controller   File: BeanToOsgiServiceManager.java   View source code 6 votes vote down vote up
public synchronized void updateRegistrations(
        final Map<ServiceInterfaceAnnotation, String /* service ref name */> newAnnotationMapping,
        final BundleContext bundleContext, final AutoCloseable newInstance) {
    boolean notEquals = !this.instance.equals(newInstance);
    notEquals |= !newAnnotationMapping.equals(serviceNamesToAnnotations);
    if (notEquals) {
        // FIXME: changing from old state to new state can be improved by computing the
        // diff
        LOG.debug("Detected change in service registrations for {}: old: {}, new: {}", moduleIdentifier,
                serviceNamesToAnnotations, newAnnotationMapping);
        close();
        this.instance = newInstance;
        Set<ServiceRegistration<?>> newRegs = registerToSR(instance, bundleContext, newAnnotationMapping);
        serviceRegistrations.clear();
        serviceRegistrations.addAll(newRegs);
    }
}
 
Example 15
Project: gemini.blueprint   File: OsgiBundleScope.java   View source code 6 votes vote down vote up
/**
 * Called if a bundle requests a service for the first time (start the
 * scope).
 * 
 * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle,
 *      org.osgi.framework.ServiceRegistration)
 */
public Object getService(Bundle bundle, ServiceRegistration registration) {
	try {
		// tell the scope, it's an outside bundle that does the call
		EXTERNAL_BUNDLE.set(Boolean.TRUE);

		// create the new object (call the container)
		Object obj = decoratedServiceFactory.getService(bundle, registration);

		// get callback (registered through the scope)
		Object passedObject = OsgiBundleScope.EXTERNAL_BUNDLE.get();

		// make sure it's not the marker object
		if (passedObject != null && passedObject instanceof Runnable) {
			Runnable callback = (Runnable) OsgiBundleScope.EXTERNAL_BUNDLE.get();
			if (callback != null)
				callbacks.put(bundle, callback);
		}
		return obj;
	}
	finally {
		// clean ThreadLocal
		OsgiBundleScope.EXTERNAL_BUNDLE.set(null);
	}
}
 
Example 16
Project: gemini.blueprint   File: PublishingServiceFactory.java   View source code 6 votes vote down vote up
public void ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object service) {

		if (log.isTraceEnabled()) {
			log.trace("Unget service called by bundle " + OsgiStringUtils.nullSafeName(bundle) + " on registration "
					+ OsgiStringUtils.nullSafeToString(serviceRegistration.getReference()));
		}

		Class<?> type = targetResolver.getType();
		// handle SF beans
		if (ServiceFactory.class.isAssignableFrom(type)) {
			ServiceFactory sf = (ServiceFactory) targetResolver.getBean();
			sf.ungetService(bundle, serviceRegistration, service);
		}

		if (createTCCLProxy) {
			synchronized (proxyCache) {
				// trigger purging of unused entries
				proxyCache.size();
			}
		}
	}
 
Example 17
Project: com-liferay-apio-architect   File: ManagerUtil.java   View source code 5 votes vote down vote up
/**
 * Creates a {@code ServiceTracker} that will register its managed services
 * as the classes provided in the {@code classes} parameter.
 *
 * @param  bundleContext the bundle context
 * @param  clazz the managed class
 * @param  classes the list of classes with which the service will be
 *         registered
 * @param  biConsumer function that can be used to alter the properties
 *         dictionary
 * @return the service tracker
 * @review
 */
public static <T> ServiceTracker<T, ServiceRegistration<?>>
	createServiceTracker(
		BundleContext bundleContext, Class<T> clazz, String[] classes,
		BiConsumer<Dictionary<String, Object>, T> biConsumer) {

	return new ServiceTracker<>(
		bundleContext, clazz,
		(ServiceRegistrationServiceTrackerCustomizer<T>)
			serviceReference -> {
				Dictionary<String, Object> properties = getProperties(
					serviceReference);

				T t = null;

				try {
					t = bundleContext.getService(serviceReference);
				}
				catch (Exception e) {
					return null;
				}

				biConsumer.accept(properties, t);

				return bundleContext.registerService(
					classes, t, properties);
			});
}
 
Example 18
Project: aries-jpa   File: TMTracker.java   View source code 5 votes vote down vote up
@Override
public void removedService(ServiceReference<TransactionManager> reference, ServiceRegistration reg) {
    try {
        reg.unregister();
        context.ungetService(reference);
    } catch (Exception e) {
        LOG.debug("Exception during unregister", e);
    }
}
 
Example 19
Project: aries-jpa   File: EmfTrackerTest.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testLifecycle() {
    BundleContext context = mock(BundleContext.class);
    Coordinator coordinator = mock(Coordinator.class);
    EMFTracker tracker = new EMFTracker(context, coordinator);
    ServiceReference<EntityManagerFactory> ref = mock(ServiceReference.class);
    Mockito.when(ref.getProperty(EntityManagerFactoryBuilder.JPA_UNIT_NAME)).thenReturn("testunit");
    Mockito.when(ref.getProperty(PersistenceUnitTransactionType.class.getName())).thenReturn("JTA");
    
    Bundle puBundle = mock(Bundle.class);
    BundleContext puContext = mock(BundleContext.class);
    when(puBundle.getBundleContext()).thenReturn(puContext);
    when(ref.getBundle()).thenReturn(puBundle);
    EntityManagerFactory emf = mock(EntityManagerFactory.class);
    when(puContext.getService(ref)).thenReturn(emf);
    ServiceRegistration<?> emSupplierReg = mock(ServiceRegistration.class, "emSupplierReg");
    ServiceRegistration<?> emProxyReg = mock(ServiceRegistration.class, "emProxyReg");
    when(puContext.registerService(any(Class.class), any(), any(Dictionary.class)))
        .thenReturn(emSupplierReg, emProxyReg);

    EMFTracker.TrackedEmf tracked = (TrackedEmf)tracker.addingService(ref);
    Assert.assertEquals(emf, tracked.emf);
    Assert.assertEquals(emSupplierReg, tracked.emSupplierReg);
    Assert.assertEquals(emProxyReg, tracked.emProxyReg);
    Assert.assertNotNull(tracked.tmTracker);
    Assert.assertNull(tracked.rlTxManagerReg);
    
    tracker.removedService(ref, tracked);
    verify(emSupplierReg, times(1)).unregister();
    verify(emProxyReg, times(1)).unregister();
    verify(puContext, times(1)).ungetService(ref);
}
 
Example 20
Project: aries-jpa   File: Activator.java   View source code 5 votes vote down vote up
@Override
public void bundleChanged(BundleEvent event) {
    if ((event.getType() & (BundleEvent.RESOLVED)) != 0) {
        handlePotentialEclipseLink(event.getBundle());
    } else if (event.getType() == BundleEvent.UNRESOLVED || event.getType() == BundleEvent.UNINSTALLED) {
        ServiceRegistration<?> reg = registeredProviders.remove(event.getBundle());
        if (reg != null) {
            reg.unregister();
        }
    }
}
 
Example 21
Project: neoscada   File: ConnectionManager.java   View source code 5 votes vote down vote up
public EntryImpl ( final ConnectionDescriptor connectionDescriptor, final ConnectionService connectionService, final ServiceRegistration<?> serviceRegistration )
{
    this.connectionDescriptor = connectionDescriptor;
    this.connectionService = connectionService;
    this.serviceRegistration = serviceRegistration;

    connectionService.getConnection ().addConnectionStateListener ( this );
}
 
Example 22
Project: neoscada   File: Activator.java   View source code 5 votes vote down vote up
private void disposeConnections ()
{
    for ( final ServiceRegistration<?> reg : this.registrations )
    {
        reg.unregister ();
    }
    for ( final ConnectionService service : this.services )
    {
        service.dispose ();
    }
    this.services.clear ();
    this.registrations.clear ();
}
 
Example 23
Project: neoscada   File: Activator.java   View source code 5 votes vote down vote up
@Override
public void stop ( final BundleContext context ) throws Exception
{
    for ( final ServiceRegistration<?> reg : this.regs )
    {
        reg.unregister ();
    }
    this.regs.clear ();

    // now shutdown
    this.executor.shutdown ();
}
 
Example 24
Project: neoscada   File: TimeItemFactory.java   View source code 5 votes vote down vote up
@Override
protected Entry<TimeDataItem> createService ( final UserInformation userInformation, final String configurationId, final BundleContext context, final Map<String, String> parameters ) throws Exception
{
    final TimeDataItem dataItem = new TimeDataItem ( configurationId, this.executor );

    dataItem.update ( parameters );

    final Dictionary<String, Object> properties = new Hashtable<String, Object> ();
    final ServiceRegistration<DataItem> handle = context.registerService ( DataItem.class, dataItem, properties );

    return new Entry<TimeDataItem> ( configurationId, dataItem, handle );
}
 
Example 25
Project: neoscada   File: ProxyItemFactory.java   View source code 5 votes vote down vote up
@Override
protected Entry<ProxyHistoricalItem> createService ( final UserInformation userInformation, final String configurationId, final BundleContext context, final Map<String, String> parameters ) throws Exception
{
    final ProxyHistoricalItem service = new ProxyHistoricalItem ( context, this.executor, configurationId, parameters );

    final Dictionary<String, Object> properties = new Hashtable<String, Object> ();
    properties.put ( Constants.SERVICE_DESCRIPTION, "A proxy to historical items" );
    properties.put ( Constants.SERVICE_PID, configurationId );
    properties.put ( Constants.SERVICE_VENDOR, "Eclipse SCADA Project" );

    final ServiceRegistration<HistoricalItem> handle = context.registerService ( HistoricalItem.class, service, properties );
    return new Entry<ProxyHistoricalItem> ( configurationId, service, handle );
}
 
Example 26
Project: neoscada   File: ConfigurationFactoryImpl.java   View source code 5 votes vote down vote up
private ItemWrapper createItem ( final String configurationId, final Map<String, String> properties ) throws InvalidSyntaxException
{
    final String masterId = properties.get ( DataSource.DATA_SOURCE_ID );
    if ( masterId == null )
    {
        throw new IllegalArgumentException ( String.format ( "'%s' is not set", DataSource.DATA_SOURCE_ID ) );
    }

    final Dictionary<String, String> serviceProperties = new Hashtable<String, String> ();
    serviceProperties.put ( Constants.SERVICE_PID, configurationId );
    serviceProperties.put ( Constants.SERVICE_DESCRIPTION, "A historical item implementation" );
    serviceProperties.put ( Constants.SERVICE_VENDOR, "Eclipse SCADA Project" );

    final Map<String, Variant> attributes = new HashMap<String, Variant> ();
    attributes.put ( Constants.SERVICE_DESCRIPTION, Variant.valueOf ( "A historical item implementation" ) );
    attributes.put ( Constants.SERVICE_VENDOR, Variant.valueOf ( "openSCADA.org" ) );
    attributes.put ( Constants.SERVICE_PID, Variant.valueOf ( configurationId ) );
    attributes.put ( "master.id", Variant.valueOf ( masterId ) );

    final ConfigurationDataHelper cfg = new ConfigurationDataHelper ( properties );
    for ( final Map.Entry<String, String> entry : cfg.getPrefixed ( "information." ).entrySet () )
    {
        attributes.put ( entry.getKey (), VariantEditor.toVariant ( entry.getValue () ) );
    }

    final HistoricalItemImpl item = new HistoricalItemImpl ( configurationId, attributes, masterId, this.context );

    final ServiceRegistration<HistoricalItem> registration = this.context.registerService ( HistoricalItem.class, item, serviceProperties );

    item.start ();

    return new ItemWrapper ( item, registration );
}
 
Example 27
Project: neoscada   File: Activator.java   View source code 5 votes vote down vote up
protected void handleServiceChange ( final Hive service )
{
    logger.warn ( "Exporting new service: {}", service );

    try
    {
        if ( this.exporter != null )
        {
            this.exporter.stop ();
            this.exporter = null;
        }

        // unregister all
        unregisterAllExportInformations ();

        if ( service != null )
        {
            this.exporter = new Exporter ( service, ConnectionInformation.fromURI ( System.getProperty ( "org.eclipse.scada.da.server.exporter.ngp.exportUri", "da:ngp://0.0.0.0:2101" ) ) );
            this.exporter.start ();

            this.exportedInformation = this.exporter.getExporterInformation ();
            for ( final ExporterInformation ei : this.exportedInformation )
            {
                final ServiceRegistration<ExporterInformation> reg = context.registerService ( ExporterInformation.class, ei, null );
                if ( reg != null )
                {
                    this.registeredExportInformation.add ( reg );
                }
            }
        }
    }
    catch ( final Exception e )
    {
        logger.warn ( "Failed to export da service", e );
    }
}
 
Example 28
Project: neoscada   File: AbstractDataSourceFactory.java   View source code 5 votes vote down vote up
public synchronized void dispose ()
{
    for ( final ServiceRegistration<DataSource> reg : this.regs.values () )
    {
        reg.unregister ();
    }
    this.regs.clear ();

    for ( final DefaultDataSource source : this.dataSources.values () )
    {
        source.dispose ();
    }
    this.dataSources.clear ();
}
 
Example 29
Project: gemini.blueprint   File: ConfigurationAdminManagerTest.java   View source code 5 votes vote down vote up
protected void setUp() throws Exception {
	services = new LinkedHashMap();
	IMocksControl mc = createNiceControl();
	cfg = mc.createMock(Configuration.class);
	expect(cfg.getProperties()).andReturn(new Hashtable<String, Object>());
	mc.replay();
	bundleContext = new MockBundleContext() {

		public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) {
			services.put(service, properties);
			return super.registerService(clazzes, service, properties);
		}

		public Object getService(ServiceReference reference) {
			String[] clazzes = (String[]) reference.getProperty(Constants.OBJECTCLASS);
			if (clazzes[0].equals(ConfigurationAdmin.class.getName())) {
				return new MockConfigurationAdmin() {

					public Configuration getConfiguration(String pid) throws IOException {
						return cfg;
					}
				};
			}
			else
				return super.getService(reference);
		}

	};

	pid = "Peter Pan";
	cam = new ConfigurationAdminManager(pid, bundleContext);
}
 
Example 30
Project: neoscada   File: DataItemFactory.java   View source code 5 votes vote down vote up
protected void registerItem ( final DataItem newItem, final String localId, final Map<String, Variant> properties )
{
    final Dictionary<String, String> props = new Hashtable<String, String> ();

    fillProperties ( properties, props );

    final ServiceRegistration<DataItem> handle = this.context.registerService ( DataItem.class, newItem, props );
    this.items.put ( localId, newItem );
    this.itemRegs.put ( localId, handle );
}
 
Example 31
Project: neoscada   File: DataItemFactory.java   View source code 5 votes vote down vote up
@Override
public synchronized void disposeAllItems ()
{
    for ( final ServiceRegistration<DataItem> reg : this.itemRegs.values () )
    {
        reg.unregister ();
    }
    this.items.clear ();
    this.itemRegs.clear ();
}
 
Example 32
Project: hashsdn-controller   File: BeanToOsgiServiceManager.java   View source code 5 votes vote down vote up
@Override
public synchronized void close() {
    for (ServiceRegistration<?> serviceRegistration : serviceRegistrations) {
        try {
            serviceRegistration.unregister();
        } catch (final IllegalStateException e) {
            LOG.trace("Cannot unregister {}", serviceRegistration, e);
        }
    }
    serviceRegistrations.clear();
}
 
Example 33
Project: neoscada   File: AbstractServiceFactory.java   View source code 5 votes vote down vote up
public synchronized void dispose ()
{
    for ( final ServiceRegistration<?> reg : this.regs.values () )
    {
        reg.unregister ();
    }
    for ( final Service service : this.instances.values () )
    {
        service.dispose ();
    }
    this.instances.clear ();
    this.regs.clear ();
}
 
Example 34
Project: neoscada   File: AbstractServiceFactory.java   View source code 5 votes vote down vote up
@Override
public synchronized void update ( final UserInformation information, final String configurationId, final Map<String, String> properties ) throws Exception
{
    final Service service = this.instances.get ( configurationId );
    if ( service != null )
    {
        // update
        service.update ( information, properties );
    }
    else
    {
        // create
        final Service newService = createService ( information, configurationId, properties );
        if ( newService != null )
        {
            final ServiceRegistration<?> reg = registerService ( information, this.context, configurationId, newService );

            if ( reg != null )
            {
                this.regs.put ( configurationId, reg );
                this.instances.put ( configurationId, newService );
            }
            else
            {
                newService.dispose ();
            }
        }
    }
}
 
Example 35
Project: neoscada   File: AbstractServiceConfigurationFactory.java   View source code 5 votes vote down vote up
/**
 * Unregister the service entry with OSGi
 * 
 * @param entry
 *            the entry to unregister
 */
protected void unregisterService ( final Entry<T> entry )
{
    final ServiceRegistration<?> handle = entry.getHandle ();
    if ( handle != null )
    {
        handle.unregister ();
    }
}
 
Example 36
Project: ch-inofix-timetracker   File: BackgroundTaskExecutorConfigurator.java   View source code 5 votes vote down vote up
@Deactivate
protected void deactivate() {
    for (ServiceRegistration<BackgroundTaskExecutor> serviceRegistration : _serviceRegistrations) {

        serviceRegistration.unregister();
    }
}
 
Example 37
Project: osc-core   File: InstallerIntegrationTest.java   View source code 5 votes vote down vote up
@Test
public void testErrorFromInvalidArchive() throws Exception {
    Object[] artifactInstallers = this.artifactInstallerTracker.getServices();
    assertNotNull("Should be exactly one ArtifactInstaller service", artifactInstallers);
    assertEquals("Should be exactly one ArtifactInstaller service", 1, artifactInstallers.length);

    // Register mock InstallableListener
    List<String> installEvents = new LinkedList<>();
    InstallableListener mockInstallListener = new InstallableListener() {
        @Override
        public void installableUnitsChanged(Collection<InstallableUnitEvent> events) {
            for (InstallableUnitEvent event : events) {
                String message = String.format("%s %s", event.getNewState(), event.getUnit().getSymbolicName());
                installEvents.add(message);
            }
        }
    };

    ServiceRegistration<InstallableListener> mockListenerReg = this.bundleContext.registerService(InstallableListener.class, mockInstallListener, null);
    try {
        assertEquals("Shouldn't be any install events yet", 0, installEvents.size());

        // Provide the sample archive
        File sampleArchive = new File(this.dataDir, "org.example.invalid-missing-rb.bar");
        ArtifactInstaller installer = this.artifactInstallerTracker.getService();
        assertTrue("installer should handle sample archive", installer.canHandle(sampleArchive));
        installer.install(sampleArchive);

        // Wait for resolve to occur
        Thread.sleep(2000);
        assertEquals(1, installEvents.size());
        assertEquals("ERROR org.example.invalid-missing-rb", installEvents.get(0));
    } finally {
        mockListenerReg.unregister();
    }
}
 
Example 38
Project: org.ops4j.pax.transx   File: OsgiServer.java   View source code 5 votes vote down vote up
protected <T> void register(Class<T> clazz, T service) {
    Hashtable<String, String> props = new Hashtable<>();
    props.put("provider", "narayana");
    ServiceRegistration<T> registration = bundleContext.registerService(clazz, service, props);
    if (registrations == null) {
        registrations = new ArrayList<>();
    }
    registrations.add(registration);
}
 
Example 39
Project: gemini.blueprint   File: ServiceAvailableDuringUnregistrationTest.java   View source code 5 votes vote down vote up
public void testServiceAliveDuringUnregistration() throws Exception {
	service = new Polygon();

	ServiceRegistration reg = bundleContext.registerService(Shape.class.getName(), service, null);

	String filter = OsgiFilterUtils.unifyFilter(Shape.class, null);

	ServiceListener listener = new ServiceListener() {

		public void serviceChanged(ServiceEvent event) {
			if (ServiceEvent.UNREGISTERING == event.getType()) {
				ServiceReference ref = event.getServiceReference();
				Object aliveService = bundleContext.getService(ref);
				assertNotNull("services not available during unregistration", aliveService);
				assertSame(service, aliveService);
			}
		}
	};

	try {
		bundleContext.addServiceListener(listener, filter);
		reg.unregister();
	}
	finally {
		bundleContext.removeServiceListener(listener);
	}
}
 
Example 40
Project: gemini.blueprint   File: OsgiServiceFactoryBeanTest.java   View source code 5 votes vote down vote up
public void testUnregisterService() throws Exception {
    ServiceRegistration reg = createMock(ServiceRegistration.class);

    reg.unregister();
    expectLastCall();
    replay(reg);
    exporter.unregisterService(reg);
    verify(reg);
}