Java Code Examples for org.osgi.framework.ServiceReference

The following are top voted examples for showing how to use org.osgi.framework.ServiceReference. 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: neoscada   File: ProxyValueSource.java   Source Code and License 6 votes vote down vote up
public ProxyValueSource ( final BundleContext context, final String id, final ProxyHistoricalItem item, final int priority ) throws InvalidSyntaxException
{

    this.item = item;
    this.priority = priority;

    this.listener = new SingleServiceListener<HistoricalItem> () {

        @Override
        public void serviceChange ( final ServiceReference<HistoricalItem> reference, final HistoricalItem service )
        {
            setService ( service );
        }
    };

    this.tracker = new SingleServiceTracker<HistoricalItem> ( context, FilterUtil.createClassAndPidFilter ( HistoricalItem.class.getName (), id ), this.listener );
    this.tracker.open ();
}
 
Example 2
Project: gemini.blueprint   File: OsgiDefaultsTests.java   Source Code and License 6 votes vote down vote up
protected void setUp() throws Exception {
	BundleContext bundleContext = new MockBundleContext() {
		// service reference already registered
		public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
			return new ServiceReference[] { new MockServiceReference(new String[] { Serializable.class.getName() }) };
		}
	};

	appContext = new GenericApplicationContext();
	appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
	appContext.setClassLoader(getClass().getClassLoader());

	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
	reader.loadBeanDefinitions(new ClassPathResource("osgiDefaults.xml", getClass()));
	appContext.refresh();
}
 
Example 3
Project: neoscada   File: Activator.java   Source Code and License 6 votes vote down vote up
@Override
public void start ( final BundleContext bundleContext ) throws Exception
{
    Activator.context = bundleContext;

    this.tracker = new SingleServiceTracker<Service> ( context, Service.class, new SingleServiceListener<Service> () {

        @Override
        public void serviceChange ( final ServiceReference<Service> reference, final Service service )
        {
            handleServiceChange ( service );
        }

    } );
    this.tracker.open ();
}
 
Example 4
Project: gemini.blueprint   File: OsgiServiceCollectionProxiesTest.java   Source Code and License 6 votes vote down vote up
protected void setUp() throws Exception {
	services = new LinkedHashMap();

	BundleContext ctx = new MockBundleContext() {

		public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
			return new ServiceReference[0];
		}

		public Object getService(ServiceReference reference) {
			Object service = services.get(reference);
			return (service == null ? new Object() : service);
		}

	};

	ClassLoader cl = getClass().getClassLoader();
	proxyCreator =
			new StaticServiceProxyCreator(new Class<?>[] { Cloneable.class }, cl, cl, ctx,
					ImportContextClassLoaderEnum.UNMANAGED, false, false);
}
 
Example 5
Project: neoscada   File: ServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void removedService ( final ServiceReference<HistoricalItem> reference, final HistoricalItem service )
{
    final String itemId = (String)reference.getProperty ( Constants.SERVICE_PID );

    synchronized ( this )
    {
        final HistoricalItem item = this.items.remove ( itemId );
        if ( item != null )
        {
            this.context.ungetService ( reference );
            this.itemInformations.remove ( item.getInformation () );
            fireListChanged ( null, new HashSet<String> ( Arrays.asList ( itemId ) ), false );
        }
    }
}
 
Example 6
Project: neoscada   File: DaveBlockConfigurator.java   Source Code and License 6 votes vote down vote up
protected void addOrReplaceBlock ( final ServiceReference<?> reference, final BlockConfiguration block )
{
    logger.info ( String.format ( "Adding or replace block - ref: %s, block: %s", new Object[] { reference, block } ) );

    final String oldBlock = this.blocks.put ( reference, block.getId () );

    if ( oldBlock != null )
    {
        logger.info ( "Replacing exisiting block" );
        this.device.removeBlock ( oldBlock );
    }

    final AbstractRequestBlock deviceBlock = makeBlock ( block );
    try
    {
        this.device.addBlock ( block.getId (), deviceBlock );
    }
    catch ( final Exception e )
    {
        logger.warn ( "Failed to add block", e );
        deviceBlock.dispose ();
    }
}
 
Example 7
Project: neoscada   File: ServiceDiscoverer.java   Source Code and License 6 votes vote down vote up
/**
 * Gather all ConnectionInformation objects and set them as connections
 */
private void update ()
{
    final Set<ConnectionDescriptor> infos = new HashSet<ConnectionDescriptor> ();
    for ( final ServiceReference<?> ref : this.references )
    {
        final ConnectionInformation ci = fromReference ( ref );
        if ( ci != null )
        {
            final Object o = ref.getProperty ( Constants.SERVICE_PID );
            final String id = o != null ? o.toString () : null;
            final Object description = ref.getProperty ( Constants.SERVICE_DESCRIPTION );
            final ConnectionDescriptor cd = new ConnectionDescriptor ( ci, id, description == null ? null : description.toString () );
            infos.add ( cd );
        }
    }
    setConnections ( infos );
}
 
Example 8
Project: gemini.blueprint   File: OsgiServiceBindingUtils.java   Source Code and License 6 votes vote down vote up
public static void callListenersUnbind(Object serviceProxy, ServiceReference reference,
		OsgiServiceLifecycleListener[] listeners) {
	if (!ObjectUtils.isEmpty(listeners)) {
		boolean debug = log.isDebugEnabled();
		// get a Dictionary implementing a Map
		Dictionary properties =
				(reference != null ? OsgiServiceReferenceUtils.getServicePropertiesSnapshot(reference) : null);
		for (int i = 0; i < listeners.length; i++) {
			if (debug)
				log.debug("Calling unbind on " + listeners[i] + " w/ reference " + reference);
			try {
				listeners[i].unbind(serviceProxy, (Map) properties);
			} catch (Exception ex) {
				log.warn("Unbind method on listener " + listeners[i] + " threw exception ", ex);
			}
			if (debug)
				log.debug("Called unbind on " + listeners[i] + " w/ reference " + reference);
		}
	}
}
 
Example 9
Project: neoscada   File: ConfigurationManagerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Configuration getConfiguration ()
{
    final List<ConfigurationGroup> groups = new LinkedList<ConfigurationGroup> ();

    Long lastRanking = null;
    ConfigurationGroupImpl lastGroup = null;

    for ( final Map.Entry<ServiceReference<AuthenticationService>, AuthenticationService> entry : this.tracker.getTracked ().entrySet () )
    {
        final Object o = entry.getKey ().getProperty ( Constants.SERVICE_RANKING );
        final long ranking = o instanceof Number ? ( (Number)o ).longValue () : 0;

        if ( lastRanking == null || lastRanking != ranking )
        {
            lastGroup = new ConfigurationGroupImpl ();
            groups.add ( lastGroup );
            lastRanking = ranking;
        }

        lastGroup.add ( entry.getValue () );
    }

    return new ConfigurationImpl ( groups );
}
 
Example 10
Project: neoscada   File: Activator.java   Source Code and License 6 votes vote down vote up
@Override
public void start ( final BundleContext context ) throws Exception
{
    this.scheduler = Executors.newSingleThreadScheduledExecutor ( new NamedThreadFactory ( context.getBundle ().getSymbolicName () ) );
    final String driver = DataSourceHelper.getDriver ( DS_PREFIX, DataSourceHelper.DEFAULT_PREFIX );

    if ( driver == null )
    {
        logger.error ( "JDBC driver is not set" );
        throw new IllegalStateException ( "JDBC driver name is not set" );
    }

    this.dataSourceFactoryTracker = new DataSourceFactoryTracker ( context, driver, new SingleServiceListener<DataSourceFactory> () {

        @Override
        public void serviceChange ( final ServiceReference<DataSourceFactory> reference, final DataSourceFactory service )
        {
            unregister ();
            if ( service != null )
            {
                register ( service, context );
            }
        }
    } );
    this.dataSourceFactoryTracker.open ( true );
}
 
Example 11
Project: neoscada   File: EndpointExporter.java   Source Code and License 6 votes vote down vote up
@Override
protected void unexportService ( final ServiceReference<?> serviceReference )
{
    final Endpoint e;
    synchronized ( this )
    {
        e = this.endpoints.remove ( serviceReference );
    }

    if ( e != null )
    {
        if ( e.isPublished () )
        {
            try
            {
                e.stop ();
            }
            catch ( final Exception ex )
            {
                logger.warn ( "Failed to stop export", ex );
            }
        }
    }
}
 
Example 12
Project: gemini.blueprint   File: AbstractOsgiTests.java   Source Code and License 6 votes vote down vote up
/**
 * Determines through reflection the methods used for invoking the TestRunnerService.
 *
 * @throws Exception
 */
private void initializeServiceRunnerInvocationMethods() throws Exception {
    // get JUnit test service reference
    // this is a loose reference - update it if the JUnitTestActivator class is changed.

    BundleContext ctx = getRuntimeBundleContext();

    ServiceReference reference = ctx.getServiceReference(ACTIVATOR_REFERENCE);
    Assert.notNull(reference, "no OSGi service reference found at " + ACTIVATOR_REFERENCE);

    service = ctx.getService(reference);
    Assert.notNull(service, "no service found for reference: " + reference);

    serviceTrigger = service.getClass().getDeclaredMethod("executeTest", new Class[0]);
    ReflectionUtils.makeAccessible(serviceTrigger);
    Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass());
}
 
Example 13
Project: neoscada   File: AbstractExporter.java   Source Code and License 6 votes vote down vote up
public void init () throws InvalidSyntaxException
{
    final String filter = String.format ( "(%s=%s)", JaxWsExporter.EXPORT_ENABLED, true );
    synchronized ( this )
    {
        this.context.addServiceListener ( this, filter );
        final ServiceReference<?>[] refs = this.context.getServiceReferences ( (String)null, filter );
        if ( refs != null )
        {
            for ( final ServiceReference<?> ref : refs )
            {
                addService ( ref );
            }
        }
    }
}
 
Example 14
Project: gemini.blueprint   File: OsgiServiceStaticInterceptorTest.java   Source Code and License 6 votes vote down vote up
public void testInvocationWhenServiceNA() throws Throwable {
	// service n/a
	ServiceReference reference = new MockServiceReference() {
		public Bundle getBundle() {
			return null;
		}
	};

	interceptor = new ServiceStaticInterceptor(new MockBundleContext(), reference);

	Object target = new Object();
	Method m = target.getClass().getDeclaredMethod("hashCode", null);

	MethodInvocation invocation = new MockMethodInvocation(m);
	try {
		interceptor.invoke(invocation);
		fail("should have thrown exception");
	}
	catch (ServiceUnavailableException ex) {
		// expected
	}
}
 
Example 15
Project: gemini.blueprint   File: AbstractOsgiCollectionTest.java   Source Code and License 6 votes vote down vote up
protected void setUp() throws Exception {
	services = new LinkedHashMap();

	context = new MockBundleContext() {

		public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
			return new ServiceReference[0];
		}

		public Object getService(ServiceReference reference) {
			Object service = services.get(reference);
			return (service == null ? new Object() : service);
		}
	};

	col = createCollection();
	col.setRequiredAtStartup(false);
	col.afterPropertiesSet();
}
 
Example 16
Project: gemini.blueprint   File: OsgiServiceLifecycleListenerAdapter.java   Source Code and License 6 votes vote down vote up
/**
 * Invoke method with signature <code>bla(ServiceReference ref)</code>.
 * 
 * @param target
 * @param method
 * @param service
 */
private void invokeCustomServiceReferenceMethod(Object target, Method method, Object service) {
	if (method != null) {
		boolean trace = log.isTraceEnabled();

		// get the service reference
		// find the compatible types (accept null service)
		if (trace)
			log.trace("invoking listener custom method " + method);

		ServiceReference ref =
				(service != null ? ((ImportedOsgiServiceProxy) service).getServiceReference() : null);

		try {
			ReflectionUtils.invokeMethod(method, target, new Object[] { ref });
		}
		// make sure to log exceptions and continue with the
		// rest of the listeners
		catch (Exception ex) {
			Exception cause = ReflectionUtils.getInvocationException(ex);
			log.warn("custom method [" + method + "] threw exception when passing service ["
					+ ObjectUtils.identityToString(service) + "]", cause);
		}
	}
}
 
Example 17
Project: gemini.blueprint   File: AbstractServiceProxyCreator.java   Source Code and License 6 votes vote down vote up
private Advice determineTCCLAdvice(ServiceReference reference) {
	try {

		switch (iccl) {
		case CLIENT:
			return clientTCCLAdvice;
		case SERVICE_PROVIDER:
			return createServiceProviderTCCLAdvice(reference);
		case UNMANAGED:
			// do nothing
			return null;
		default:
			return null;
		}

	} finally {
		if (log.isTraceEnabled()) {
			log.trace(iccl + " TCCL used for invoking " + OsgiStringUtils.nullSafeToString(reference));
		}
	}
}
 
Example 18
Project: gemini.blueprint   File: PackageAdminResolver.java   Source Code and License 5 votes vote down vote up
private PackageAdmin getPackageAdmin() {

		return AccessController.doPrivileged(new PrivilegedAction<PackageAdmin>() {

			public PackageAdmin run() {
				ServiceReference ref = bundleContext.getServiceReference(PackageAdmin.class.getName());
				if (ref == null)
					throw new IllegalStateException(PackageAdmin.class.getName() + " service is required");
				// don't do any proxying since PackageAdmin is normally a framework service
				// we can assume for now that it will always be available
				return (PackageAdmin) bundleContext.getService(ref);
			}
		});
	}
 
Example 19
Project: neoscada   File: ServiceDiscoverer.java   Source Code and License 5 votes vote down vote up
private void addReference ( final ServiceReference<?> ref )
{
    logger.info ( "Adding service: {}", ref );

    if ( this.references.add ( ref ) )
    {
        update ();
    }
}
 
Example 20
Project: gemini.blueprint   File: ServiceReferenceComparatorTest.java   Source Code and License 5 votes vote down vote up
public void testServiceRefsWithSameRankAndDifId() throws Exception {
	ServiceReference refA = createReference(new Long(1), new Integer(5));
	ServiceReference refB = createReference(new Long(2), new Integer(5));

	// same ranking, means id equality applies
	assertTrue(comparator.compare(refA, refB) > 0);
}
 
Example 21
Project: gemini.blueprint   File: ExtenderConfigurationTest.java   Source Code and License 5 votes vote down vote up
public void testExtenderConfigAppCtxPublished() throws Exception {
	ServiceReference[] refs =
			bundleContext.getAllServiceReferences("org.springframework.context.ApplicationContext", null);
	for (int i = 0; i < refs.length; i++) {
		System.out.println(OsgiStringUtils.nullSafeToString(refs[i]));
	}
	assertNotNull(context);
}
 
Example 22
Project: incubator-netbeans   File: NetigsoServices.java   Source Code and License 5 votes vote down vote up
NetigsoServices(Netigso netigso, Framework f) {
    this.netigso = netigso;
    for (ServiceReference ref : f.getRegisteredServices()) {
        MainLookup.register(ref, this);
    }
    f.getBundleContext().addServiceListener(this);
    f.getBundleContext().addBundleListener(this);
}
 
Example 23
Project: gemini.blueprint   File: OsgiServiceReferenceUtilsTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test method for
 * {@link org.eclipse.gemini.blueprint.util.OsgiServiceReferenceUtils#getServiceId(org.osgi.framework.ServiceReference)}.
 */
public void testGetServiceId() {
	long id = 12345;
	Dictionary dict = new Hashtable();
	dict.put(Constants.SERVICE_ID, id);
	ServiceReference ref = new MockServiceReference(null, dict, null);
	assertEquals(id, OsgiServiceReferenceUtils.getServiceId(ref));
}
 
Example 24
Project: gemini.blueprint   File: PublishedInterfacesTest.java   Source Code and License 5 votes vote down vote up
private void checkedPublishedOSGiService(int expectedContexts) throws Exception {
	ServiceReference[] refs = bundleContext.getServiceReferences(
		ConfigurableOsgiBundleApplicationContext.class.getName(), null);
	assertEquals("different number of published contexts encountered", expectedContexts, refs.length);

	for (int i = 0; i < refs.length; i++) {
		ServiceReference serviceReference = refs[i];
		String[] interfaces = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
		assertEquals("not enough interfaces published", 15, interfaces.length);
		assertEquals(Version.emptyVersion, serviceReference.getProperty(Constants.BUNDLE_VERSION));
		assertEquals(bundleContext.getBundle().getSymbolicName(),
			serviceReference.getProperty(Constants.BUNDLE_SYMBOLICNAME));
	}
}
 
Example 25
Project: gemini.blueprint   File: NamespaceProviderAndConsumerTest.java   Source Code and License 5 votes vote down vote up
public void testNSBundlePublishedOkay() throws Exception {
	ServiceReference ref = OsgiServiceReferenceUtils.getServiceReference(bundleContext,
		ApplicationContext.class.getName(), "(" + Constants.BUNDLE_SYMBOLICNAME + "=" + BND_SYM_NAME + ")");
	assertNotNull(ref);
	ApplicationContext ctx = (ApplicationContext) bundleContext.getService(ref);
	assertNotNull(ctx);
	assertNotNull(ctx.getBean("nsBean"));
	assertNotNull(ctx.getBean("nsDate"));

}
 
Example 26
Project: gemini.blueprint   File: OsgiServiceReferenceUtilsTest.java   Source Code and License 5 votes vote down vote up
public void testGetServiceRankingWithNonExistingRanking() {
	Dictionary dict = new Hashtable() {
		// forbid adding the service ranking
		public synchronized Object put(Object key, Object value) {
			if (!Constants.SERVICE_RANKING.equals(key))
				return super.put(key, value);
			return null;
		}
	};

	ServiceReference ref = new MockServiceReference(null, dict, null);

	assertNull(ref.getProperty(Constants.SERVICE_RANKING));
	assertEquals(0, OsgiServiceReferenceUtils.getServiceRanking(ref));
}
 
Example 27
Project: neoscada   File: ServiceImpl.java   Source Code and License 5 votes vote down vote up
private String getQueryId ( final ServiceReference<?> ref )
{
    final Object p = ref.getProperty ( Constants.SERVICE_PID );
    if ( p != null )
    {
        return p.toString ();
    }
    else
    {
        return null;
    }

}
 
Example 28
Project: gemini.blueprint   File: LifecycleTest.java   Source Code and License 5 votes vote down vote up
private void printServiceRefs(ServiceReference[] refs) {
    for (ServiceReference ref : refs) {
        String[] keys = ref.getPropertyKeys();
        logger.info(ref);
        for (String key : keys) {
            if (Constants.OBJECTCLASS.equals(key)) {
                logger.info("\t" + key + " = " + Arrays.toString((String[]) ref.getProperty(key)));
            } else {
                logger.info("\t" + key + " = " + ref.getProperty(key));
            }
        }
    }
}
 
Example 29
Project: gemini.blueprint   File: InvalidOsgiDefaultsTest.java   Source Code and License 5 votes vote down vote up
protected void setUp() throws Exception {
	BundleContext bundleContext = new MockBundleContext() {
		// service reference already registered
		public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
			return new ServiceReference[] { new MockServiceReference(new String[] { Serializable.class.getName() }) };
		}
	};

	appContext = new GenericApplicationContext();
	appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
	appContext.setClassLoader(getClass().getClassLoader());

}
 
Example 30
Project: incubator-netbeans   File: NetigsoHasSAXParserTest.java   Source Code and License 5 votes vote down vote up
public void testSAXParserAvailable() throws Exception {
    Framework f = IntegrationTest.findFramework();
    BundleContext bc = f.getBundleContext();
    
    ServiceReference sr = bc.getServiceReference(SAXParserFactory.class.getName());
    assertNotNull("SAX Service found", sr);
    Object srvc = bc.getService(sr);
    assertTrue("Instance of the right type: " + srvc, srvc instanceof SAXParserFactory);
        
}
 
Example 31
Project: gemini.blueprint   File: ManagedServiceFactoryTest.java   Source Code and License 5 votes vote down vote up
protected void setUp() throws Exception {


		final Configuration cfg = createMock(Configuration.class);
		expect(cfg.getProperties()).andReturn(new Hashtable<String, Object>());
		replay(cfg);

		BundleContext bundleContext = new MockBundleContext() {

			// always return a ConfigurationAdmin
			public Object getService(ServiceReference reference) {
				return new MockConfigurationAdmin() {

					public Configuration getConfiguration(String pid) throws IOException {
						return cfg;
					}
				};
			}
		};

		appContext = new GenericApplicationContext();
		appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
		appContext.setClassLoader(getClass().getClassLoader());

		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
		reader.loadBeanDefinitions(new ClassPathResource("managedServiceFactory.xml", getClass()));
		appContext.refresh();
	}
 
Example 32
Project: directory-ldap-api   File: ApiLdapNetMinaOsgiTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testLookupLdapProtocolCodecFactory()
{
    ServiceReference<LdapProtocolCodecFactory> serviceReference = context.getServiceReference( LdapProtocolCodecFactory.class );
    Object service = context.getService( serviceReference );
    assertNotNull( service );
    assertTrue( service instanceof LdapProtocolCodecFactory );
}
 
Example 33
Project: directory-ldap-api   File: LdapProtocolCodecActivator.java   Source Code and License 5 votes vote down vote up
@Override
public LdapApiService addingService( ServiceReference<LdapApiService> reference )
{
    LdapApiService ldapApiService = bundleContext.getService( reference );
    LdapProtocolCodecFactory factory = new LdapProtocolCodecFactory( ldapApiService );
    registration = bundleContext.registerService( LdapProtocolCodecFactory.class.getName(), factory, null );
    ldapApiService.registerProtocolCodecFactory( factory );
    return ldapApiService;
}
 
Example 34
Project: gemini.blueprint   File: OsgiServiceReferenceUtilsTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test method for
 * {@link org.eclipse.gemini.blueprint.util.OsgiServiceReferenceUtils#getServiceRanking(org.osgi.framework.ServiceReference)}.
 */
public void testGetServiceRankingAvailable() {
	int ranking = 12345;
	Dictionary dict = new Hashtable();
	dict.put(Constants.SERVICE_RANKING, ranking);
	ServiceReference ref = new MockServiceReference(null, dict, null);
	assertEquals(ranking, OsgiServiceReferenceUtils.getServiceRanking(ref));
}
 
Example 35
Project: gemini.blueprint   File: ScopingTest.java   Source Code and License 5 votes vote down vote up
private ConfigurableApplicationContext getAppCtx(String symBundle) {
	ServiceReference ref = OsgiServiceReferenceUtils.getServiceReference(bundleContext, "("
			+ ConfigurableOsgiBundleApplicationContext.APPLICATION_CONTEXT_SERVICE_PROPERTY_NAME + "=" + symBundle
			+ ")");

	if (ref == null)
		throw new IllegalArgumentException("cannot find appCtx for bundle " + symBundle);
	return (ConfigurableApplicationContext) bundleContext.getService(ref);
}
 
Example 36
Project: neoscada   File: DaveBlockConfigurator.java   Source Code and License 5 votes vote down vote up
protected void modifyBlock ( final ServiceReference<?> reference, final BlockConfiguration service )
{
    logger.info ( "Modify block: {}", reference );

    // will be a quick remove and add operation
    addOrReplaceBlock ( reference, service );
}
 
Example 37
Project: neoscada   File: OsgiFactory.java   Source Code and License 5 votes vote down vote up
protected ComponentFactory handleAddingService ( final ServiceReference<ComponentFactory> reference, final ComponentFactory service )
{
    try
    {
        final ComponentHandle handle = this.componentHost.registerComponent ( service );
        this.refMap.put ( reference, handle );
        return service;
    }
    catch ( final Exception e )
    {
        return null;
    }

}
 
Example 38
Project: gemini.blueprint   File: ServiceAvailableDuringUnregistrationTest.java   Source Code and License 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 39
Project: org.ops4j.pax.transx   File: OsgiServer.java   Source Code and License 5 votes vote down vote up
protected void warn(String message, Throwable t) {
    ServiceReference<LogService> ref = bundleContext.getServiceReference(LogService.class);
    if (ref != null) {
        LogService svc = bundleContext.getService(ref);
        svc.log(LogService.LOG_WARNING, message, t);
        bundleContext.ungetService(ref);
    }
}
 
Example 40
Project: gemini.blueprint   File: OsgiServiceProxyEqualityTest.java   Source Code and License 5 votes vote down vote up
protected void setUp() throws Exception {
	ref = new MockServiceReference();
	bundleContext = new MockBundleContext() {

		public ServiceReference getServiceReference(String clazz) {
			return ref;
		}

		public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
			return new ServiceReference[] { ref };
		}
	};

	classLoader = getClass().getClassLoader();
}
 
Example 41
Project: gemini.blueprint   File: ConfigPropertiesHandlerTest.java   Source Code and License 5 votes vote down vote up
protected void setUp() throws Exception {
    adminControl = createControl();
    admin = adminControl.createMock(ConfigurationAdmin.class);
    cfg = createMock(Configuration.class);

    config = new Hashtable<String, Object>();

    expect(admin.getConfiguration(persistentId)).andReturn(cfg).atLeastOnce();
    expect(cfg.getProperties()).andReturn(config).atLeastOnce();

    adminControl.replay();
    replay(cfg);

    bundleContext = new MockBundleContext() {

        // add Configuration admin support
        @Override
        public Object getService(ServiceReference reference) {
            return admin;
        }

        // ManagedService registration
        @Override
        public ServiceRegistration registerService(String clazz, Object service, Dictionary properties) {
            // save the callback
            if (ManagedService.class.getName().equals(clazz)) {
                msCallback = (ManagedService) service;
            }
            return super.registerService(clazz, service, properties);
        }
    };

    appContext = new GenericApplicationContext();
    appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
    // reader.setEventListener(this.listener);
    reader.loadBeanDefinitions(new ClassPathResource("configProperties.xml", getClass()));
    appContext.refresh();
}
 
Example 42
Project: aries-jpa   File: EMFTracker.java   Source Code and License 5 votes vote down vote up
@Override
public void removedService(ServiceReference reference, Object trackedO) {
    TrackedEmf tracked = (TrackedEmf)trackedO;
    if (tracked.tmTracker != null) {
        tracked.tmTracker.close();
    }
    if (tracked.rlTxManagerReg != null) {
        tracked.rlTxManagerReg.unregister();
    }
    tracked.emSupplierReg.unregister();
    tracked.emProxyReg.unregister();
    tracked.emSupplier.close();
    reference.getBundle().getBundleContext().ungetService(reference);
}
 
Example 43
Project: aries-jpa   File: OSGiTSWrapper.java   Source Code and License 5 votes vote down vote up
@Override
protected TransactionManager acquireTransactionManager() throws Exception {
    BundleContext ctx = FrameworkUtil.getBundle(OSGiTSWrapper.class).getBundleContext();
    
    if (ctx != null) {
        ServiceReference ref = ctx.getServiceReference(TransactionManager.class.getName());
        
        if (ref != null) {
            return (TransactionManager) ctx.getService(ref);
        }            
    }
    
    return super.acquireTransactionManager();
}
 
Example 44
Project: neoscada   File: AbstractConfigurationAdministrator.java   Source Code and License 5 votes vote down vote up
private String getDescription ( final ServiceReference<?> reference )
{
    String description;
    if ( reference.getProperty ( Constants.SERVICE_DESCRIPTION ) instanceof String )
    {
        description = (String)reference.getProperty ( Constants.SERVICE_DESCRIPTION );
    }
    else
    {
        description = null;
    }
    return description;
}
 
Example 45
Project: gemini.blueprint   File: ListListenerAdapterTest.java   Source Code and License 5 votes vote down vote up
public Object getService(ServiceReference reference) {
    if (reference != null) {
        Object service = reference.getProperty(SERVICE_PROPERTY);
        if (service != null) {
            return service;
        }
    }

    return super.getService(reference);
}
 
Example 46
Project: gemini.blueprint   File: ScopingTest.java   Source Code and License 5 votes vote down vote up
protected ScopeTestService getService(String bundleName) {
	ServiceReference ref = OsgiServiceReferenceUtils.getServiceReference(bundleContext,
		ScopeTestService.class.getName(), "(Bundle-SymbolicName=org.eclipse.gemini.blueprint.iandt.scope." + bundleName
				+ ")");
	if (ref == null) {
		String filter = OsgiFilterUtils.unifyFilter(ScopeTestService.class, null);
		System.out.println(ObjectUtils.nullSafeToString(OsgiServiceReferenceUtils.getServiceReferences(
			bundleContext, filter)));
		throw new IllegalStateException("cannot find service with owning bundle " + bundleName);
	}
	return (ScopeTestService) bundleContext.getService(ref);
}
 
Example 47
Project: neoscada   File: Activator.java   Source Code and License 5 votes vote down vote up
private void addService ( final ServiceReference<?> serviceReference )
{
    if ( serviceReference == null )
    {
        return;
    }
    this.service = (HttpService)this.context.getService ( serviceReference );
    this.serviceReference = serviceReference;
    if ( this.service != null )
    {
        configureService ();
    }
}
 
Example 48
Project: gemini.blueprint   File: PropertyPlaceholderTest.java   Source Code and License 5 votes vote down vote up
private void prepareConfiguration() throws Exception {

		ServiceReference ref = OsgiServiceReferenceUtils.getServiceReference(bundleContext,
			ConfigurationAdmin.class.getName(), null);

		ConfigurationAdmin admin = (ConfigurationAdmin) bundleContext.getService(ref);
		Configuration config = admin.getConfiguration(ID);
		config.update(DICT);
	}
 
Example 49
Project: hashsdn-controller   File: NettyThreadgroupModuleTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Before
public void setUp() throws Exception {
    factory = new NettyThreadgroupModuleFactory();
    super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,factory));

    Filter mockFilter = mock(Filter.class);
    doReturn("mock").when(mockFilter).toString();
    doReturn(mockFilter).when(mockedContext).createFilter(anyString());
    doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
    ServiceReference mockServiceRef = mock(ServiceReference.class);
    doReturn(new ServiceReference[]{mockServiceRef}).when(mockedContext).
            getServiceReferences(anyString(), anyString());
    doReturn(mock(EventLoopGroup.class)).when(mockedContext).getService(mockServiceRef);
}
 
Example 50
Project: gemini.blueprint   File: InfrastructureProxyTest.java   Source Code and License 5 votes vote down vote up
public void tstBlueprintExceptions() throws Exception {
	MockServiceReference ref = new MockServiceReference(new String[] { Comparable.class.getName() });
	MockBundleContext ctx = new MockBundleContext() {

		@Override
		public Object getService(ServiceReference reference) {
			return null;
		}
	};
	ClassLoader cl = getClass().getClassLoader();
	StaticServiceProxyCreator creator =
			new StaticServiceProxyCreator(classes, cl, cl, ctx, ImportContextClassLoaderEnum.UNMANAGED, true, true);
	Comparable proxy = (Comparable) creator.createServiceProxy(ref).proxy;
	System.out.println(proxy.compareTo(null));
}
 
Example 51
Project: neoscada   File: AbstractConnectionManager.java   Source Code and License 5 votes vote down vote up
@Override
public void serviceChange ( final ServiceReference<DriverFactory> reference, final DriverFactory factory )
{
    logger.info ( "Service changed: {}/{}", reference, factory );
    disposeConnection ();
    this.factory = factory;

    if ( factory != null )
    {
        createConnection ();
    }
}
 
Example 52
Project: gemini.blueprint   File: ServiceProxyTst.java   Source Code and License 5 votes vote down vote up
public void testDynamicEndProxy() throws Exception {
	long time = 123456;
	Date date = new Date(time);
	ServiceRegistration reg = publishService(date);
	BundleContext ctx = bundleContext;

	try {
		ServiceReference ref = ctx.getServiceReference(Date.class.getName());
		assertNotNull(ref);
		Date proxy = (Date) createProxy(Date.class, createCardinalityAdvice(Date.class));
		assertEquals(time, proxy.getTime());
		// take down service
		reg.unregister();
		// reference is invalid
		assertNull(ref.getBundle());

		try {
			proxy.getTime();
			fail("should have thrown exception");
		}
		catch (ServiceUnavailableException sue) {
			// service failed
		}

		// rebind the service
		reg = publishService(date);
		// retest the service
		assertEquals(time, proxy.getTime());
	}
	finally {
		if (reg != null)
			try {
				reg.unregister();
			}
			catch (Exception ex) {
				// ignore
			}
	}
}
 
Example 53
Project: neoscada   File: ObjectPoolTracker.java   Source Code and License 5 votes vote down vote up
protected int getPriority ( final ServiceReference<ObjectPool<S>> reference, final int defaultPriority )
{
    final Object o = reference.getProperty ( Constants.SERVICE_RANKING );
    if ( o instanceof Number )
    {
        return ( (Number)o ).intValue ();
    }
    else
    {
        return defaultPriority;
    }
}
 
Example 54
Project: neoscada   File: EventPoolManager.java   Source Code and License 5 votes vote down vote up
public EventPoolManager ( final BundleContext context, final String id, final String filter, final int size ) throws InvalidSyntaxException
{
    this.context = context;
    this.id = id;
    this.filter = filter;
    this.size = size;

    this.executor = ExportedExecutorService.newSingleThreadExportedExecutor ( "EventPoolManager/" + id );

    this.eventManagerTracker = new SingleServiceTracker<Object> ( this.context, FilterUtil.createClassFilter ( EventManager.class.getName () ), new SingleServiceListener<Object> () {

        @Override
        public void serviceChange ( final ServiceReference<Object> reference, final Object service )
        {
            EventPoolManager.this.setEventManager ( (EventManager)service );
        }
    } );
    this.eventManagerTracker.open ();

    this.storageTracker = new SingleServiceTracker<Object> ( this.context, FilterUtil.createClassFilter ( Storage.class.getName () ), new SingleServiceListener<Object> () {

        @Override
        public void serviceChange ( final ServiceReference<Object> reference, final Object service )
        {
            EventPoolManager.this.setStorageService ( (Storage)service );
        }
    } );
    this.storageTracker.open ();
}
 
Example 55
Project: gemini.blueprint   File: CMUtils.java   Source Code and License 4 votes vote down vote up
/**
 * Returns a map containing the Configuration Admin entry with given pid. Waits until a non-null (initialized)
 * object is returned if initTimeout is bigger then 0.
 * 
 * @param bundleContext
 * @param pid
 * @param initTimeout
 * @return
 * @throws IOException
 */
public static Map getConfiguration(BundleContext bundleContext, final String pid, long initTimeout)
		throws IOException {
	ServiceReference ref = bundleContext.getServiceReference(ConfigurationAdmin.class.getName());
	if (ref != null) {
		ConfigurationAdmin cm = (ConfigurationAdmin) bundleContext.getService(ref);
		if (cm != null) {
			Dictionary dict = cm.getConfiguration(pid).getProperties();
			// if there are properties or no timeout, return as is
			if (dict != null || initTimeout == 0) {
				return new MapBasedDictionary(dict);
			}
			// no valid props, register a listener and start waiting
			final Object monitor = new Object();
			Dictionary<String, Object> props = new Hashtable<String, Object>();
			props.put(Constants.SERVICE_PID, pid);
			
			ServiceRegistration reg =
					bundleContext.registerService(ConfigurationListener.class.getName(),
							new ConfigurationListener() {
								public void configurationEvent(ConfigurationEvent event) {
									if (ConfigurationEvent.CM_UPDATED == event.getType()
											&& pid.equals(event.getPid())) {
										synchronized (monitor) {
											monitor.notify();
										}
									}
								}
							}, props);

			try {
				// try to get the configuration one more time (in case the update was fired before the service was
				// registered)
				dict = cm.getConfiguration(pid).getProperties();
				if (dict != null) {
					return new MapBasedDictionary(dict);
				}

				// start waiting
				synchronized (monitor) {
					try {
						monitor.wait(initTimeout);
					} catch (InterruptedException ie) {
						// consider the timeout has passed
					}
				}

				// return whatever is available (either we timed out or an update occured)
				return new MapBasedDictionary(cm.getConfiguration(pid).getProperties());

			} finally {
				OsgiServiceUtils.unregisterService(reg);
			}
		}
	}
	return Collections.EMPTY_MAP;
}
 
Example 56
Project: magic-bundle   File: Activator.java   Source Code and License 4 votes vote down vote up
private void setServiceReference(ServiceReference<RandomNumberGenerator> reference) {
    serviceReference = reference;
}
 
Example 57
Project: neoscada   File: ServiceListenerHiveSource.java   Source Code and License 4 votes vote down vote up
@Override
public void serviceChange ( final ServiceReference<Hive> reference, final Hive service )
{
    handleServiceChange ( service );
}
 
Example 58
Project: incubator-netbeans   File: NetigsoServices.java   Source Code and License 4 votes vote down vote up
@Override
public String displayName(ServiceReference obj) {
    return (String) obj.getProperty(Constants.SERVICE_DESCRIPTION);
}
 
Example 59
Project: gemini.blueprint   File: StaticServiceProxyCreator.java   Source Code and License 4 votes vote down vote up
ServiceInvoker createDispatcherInterceptor(ServiceReference reference) {
	ServiceStaticInterceptor interceptor = new ServiceStaticInterceptor(bundleContext, reference);
	interceptor.setUseBlueprintExceptions(useBlueprintExceptions);
	return interceptor;
}
 
Example 60
Project: hashsdn-controller   File: ConfigPusherCustomizer.java   Source Code and License 4 votes vote down vote up
@Override
public void removedService(final ServiceReference<ConfigPusher> configPusherServiceReference,
                           final ConfigPusher configPusher) {
    this.close();
}