Java Code Examples for org.osgi.framework.BundleContext#ungetService()

The following examples show how to use org.osgi.framework.BundleContext#ungetService() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ThingFactoryHelper.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> T withChannelTypeRegistry(Function<ChannelTypeRegistry, T> consumer) {
    BundleContext bundleContext = FrameworkUtil.getBundle(ThingFactoryHelper.class).getBundleContext();
    ServiceReference ref = bundleContext.getServiceReference(ChannelTypeRegistry.class.getName());
    try {
        ChannelTypeRegistry channelTypeRegistry = null;
        if (ref != null) {
            channelTypeRegistry = (ChannelTypeRegistry) bundleContext.getService(ref);
        }
        return consumer.apply(channelTypeRegistry);
    } finally {
        if (ref != null) {
            bundleContext.ungetService(ref);
        }
    }
}
 
Example 2
Source File: CoreEPLPlugin.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the service described by the given arguments. Note that this is a helper class that <b>immediately</b>
 * ungets the service reference. This results in a window where the system thinks the service is not in use but
 * indeed the caller is about to use the returned service object.
 * 
 * @param context
 * @param name
 * @return The requested service
 */
public static Object getService(BundleContext context, String name)
{
	if (context == null)
	{
		return null;
	}
	// don't add <?> as it's for Eclipse 3.7's getServiceReference() only
	ServiceReference reference = context.getServiceReference(name);
	if (reference == null)
	{
		return null;
	}
	Object result = context.getService(reference);
	context.ungetService(reference);
	return result;
}
 
Example 3
Source File: XOSGi.java    From extended-objects with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link com.buschmais.xo.api.XOManagerFactory} for the given XO unit.
 * <p>
 * Internally it performs a lookup in the OSGi service registry to retrieve the
 * XOBootstrapService service.
 * </p>
 *
 * @param xoUnit
 *            The XO unit.
 * @return The {@link com.buschmais.xo.api.XOManagerFactory}.
 */
public static XOManagerFactory createXOManagerFactory(XOUnit xoUnit) {
    if (OSGiUtil.isXOLoadedAsOSGiBundle()) {
        BundleContext bundleContext = FrameworkUtil.getBundle(XOSGi.class).getBundleContext();
        ServiceReference<XOBootstrapService> xoBootstrapServiceReference = bundleContext.getServiceReference(XOBootstrapService.class);
        if (xoBootstrapServiceReference == null) {
            throw new XOException("Cannot get XO bootstrap service reference.");
        }
        XOBootstrapService xoBootstrapService = bundleContext.getService(xoBootstrapServiceReference);
        if (xoBootstrapService == null) {
            throw new XOException("Cannot get XO bootstrap service.");
        }
        XOManagerFactory xoManagerFactory = xoBootstrapService.createXOManagerFactory(xoUnit);
        bundleContext.ungetService(xoBootstrapServiceReference);
        return xoManagerFactory;
    }
    throw new XOException("Cannot bootstrap XO implementation.");
}
 
Example 4
Source File: ThingFactoryHelper.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> T withChannelGroupTypeRegistry(Function<ChannelGroupTypeRegistry, T> consumer) {
    BundleContext bundleContext = FrameworkUtil.getBundle(ThingFactoryHelper.class).getBundleContext();
    ServiceReference ref = bundleContext.getServiceReference(ChannelGroupTypeRegistry.class.getName());
    try {
        ChannelGroupTypeRegistry channelGroupTypeRegistry = null;
        if (ref != null) {
            channelGroupTypeRegistry = (ChannelGroupTypeRegistry) bundleContext.getService(ref);
        }
        return consumer.apply(channelGroupTypeRegistry);
    } finally {
        if (ref != null) {
            bundleContext.ungetService(ref);
        }
    }
}
 
Example 5
Source File: ThingFactoryHelper.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> T withChannelGroupTypeRegistry(Function<ChannelGroupTypeRegistry, T> consumer) {
    BundleContext bundleContext = FrameworkUtil.getBundle(ThingFactoryHelper.class).getBundleContext();
    ServiceReference ref = bundleContext.getServiceReference(ChannelGroupTypeRegistry.class.getName());
    try {
        ChannelGroupTypeRegistry channelGroupTypeRegistry = null;
        if (ref != null) {
            channelGroupTypeRegistry = (ChannelGroupTypeRegistry) bundleContext.getService(ref);
        }
        return consumer.apply(channelGroupTypeRegistry);
    } finally {
        if (ref != null) {
            bundleContext.ungetService(ref);
        }
    }
}
 
Example 6
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Log message via specified BundleContext
 */
static void logBC(BundleContext bc, int level, String msg, Throwable t) {
  try {
    ServiceReference<LogService> sr = bc.getServiceReference(LogService.class);
    if (sr != null) {
      LogService log = bc.getService(sr);
      if (log != null) {
        log.log(level, msg, t);
        bc.ungetService(sr);
      }
    }
  } catch (IllegalStateException ise) {
    log(level, "Logging message for " + bc.getBundle() 
        + " since it was inactive: " + msg, t);
  }
}
 
Example 7
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void start(BundleContext bc) throws Exception { 
  System.out.println(bc.getBundle().getHeaders()
                     .get(Constants.BUNDLE_NAME) + 
                     " starting..."); 
  Activator.bc = bc; 
  ServiceReference reference = 
    bc.getServiceReference(DateService.class.getName()); 

  if(reference != null) {
    DateService service = (DateService)bc.getService(reference); 
    System.out.println("Using DateService: formatting date: " + 
                       service.getFormattedDate(new Date())); 
    bc.ungetService(reference); 
  } else {
    System.out.println("No Service available!"); 
  }
}
 
Example 8
Source File: CallerActivator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void start(BundleContext bc) throws IOException
{
  ServiceReference sRef =
    bc.getServiceReference(UserService.class.getName());
  if (sRef != null) {
    UserService us = (UserService) bc.getService(sRef);
    if (us != null) {
      us.login("joek");
    }
    bc.ungetService(sRef);
  }
}
 
Example 9
Source File: ChannelProviderTracker.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public ChannelProviderTracker ( final BundleContext context )
{
    final ReadWriteLock lock = new ReentrantReadWriteLock ( false );

    this.readLock = lock.readLock ();
    this.writeLock = lock.writeLock ();

    this.tracker = new ServiceTracker<> ( context, ChannelProvider.class, new ServiceTrackerCustomizer<ChannelProvider, ChannelProvider> () {

        @Override
        public ChannelProvider addingService ( final ServiceReference<ChannelProvider> reference )
        {
            final ChannelProvider service = context.getService ( reference );
            addService ( service );
            return service;
        }

        @Override
        public void modifiedService ( final ServiceReference<ChannelProvider> reference, final ChannelProvider service )
        {
        }

        @Override
        public void removedService ( final ServiceReference<ChannelProvider> reference, final ChannelProvider service )
        {
            try
            {
                removeService ( service );
            }
            finally
            {
                context.ungetService ( reference );
            }
        }
    } );
}
 
Example 10
Source File: ListenerEvent.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Send the event to the service.
 * 
 * @param bc
 *          The bundle context to use to get the service.
 */
public void sendEvent(BundleContext bc)
{
  if (sr != null) {
    ConfigurationListener configurationListener = (ConfigurationListener) bc
        .getService(sr);
    if (configurationListener != null) {
      configurationListener.configurationEvent(event);
    }
    bc.ungetService(sr);
  }
}
 
Example 11
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Unget a service from the target BC.
 */
public static boolean getTargetBC_ungetService(final ServiceReference<?> sr)
{
  final BundleContext tbc = getTargetBC();
  if(null != tbc) {
    return tbc.ungetService(sr);
  }
  return false;
}
 
Example 12
Source File: CallerActivator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void stop(BundleContext bc) throws IOException
{
  ServiceReference sRef =
    bc.getServiceReference(UserService.class.getName());
  if (sRef != null) {
    UserService us = (UserService) bc.getService(sRef);
    if (us != null) {
      us.logout();
    }
    bc.ungetService(sRef);
  }
}
 
Example 13
Source File: Activator.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected void log ( final int level, final String message )
{
    final BundleContext context = this.context;
    if ( context == null )
    {
        return;
    }

    final ServiceReference<LogService> ref = context.getServiceReference ( LogService.class );
    if ( ref == null )
    {
        return;
    }

    final LogService service = context.getService ( ref );
    if ( service == null )
    {
        return;
    }

    try
    {
        service.log ( level, message );
    }
    finally
    {
        context.ungetService ( ref );
    }
}
 
Example 14
Source File: ReChargeLabOpenCons.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
private void deInitBillingService(){
	BundleContext context =
		FrameworkUtil.getBundle(ReChargeTarmedOpenCons.class).getBundleContext();
	if (billingServiceRef != null) {
		context.ungetService(billingServiceRef);
		billingService = null;
	}
}
 
Example 15
Source File: Client.java    From ice with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This operation releases the ICore service references and stops the Client
 * service.
 *
 * @param context
 *            the bundle's context from the OSGi
 */
@Override
public void stop(BundleContext context) throws Exception {

	// Release the service reference
	if (iCoreServiceRef != null) {
		context.ungetService(iCoreServiceRef);
	}

	// Unregister this service from the framework
	registration.unregister();

	return;
}
 
Example 16
Source File: ConnectionAnalyzerFactory.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public ConnectionAnalyzerFactory ( final ScheduledExecutorService executor, final BundleContext context )
{
    this.executor = executor;
    this.context = context;
    this.connectionTracker = new ServiceTracker<ConnectionService, ConnectionService> ( context, ConnectionService.class, new ServiceTrackerCustomizer<ConnectionService, ConnectionService> () {

        @Override
        public void removedService ( final ServiceReference<ConnectionService> reference, final ConnectionService service )
        {
            ConnectionAnalyzerFactory.this.removeService ( service );
        }

        @Override
        public void modifiedService ( final ServiceReference<ConnectionService> reference, final ConnectionService service )
        {

        }

        @Override
        public ConnectionService addingService ( final ServiceReference<ConnectionService> reference )
        {
            try
            {
                logger.debug ( "Found new service: {}", reference );
                final ConnectionService service = context.getService ( reference );
                ConnectionAnalyzerFactory.this.addService ( reference, service );
                return service;
            }
            catch ( final Throwable e )
            {
                logger.warn ( "Failed to add service", e );
            }
            context.ungetService ( reference );
            return null;
        }
    } );
    this.connectionTracker.open ();
}
 
Example 17
Source File: ObjectPoolTracker.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public ObjectPoolTracker ( final BundleContext context, final String poolClass ) throws InvalidSyntaxException
{
    final Map<String, String> parameters = new HashMap<String, String> ();
    parameters.put ( ObjectPool.OBJECT_POOL_CLASS, poolClass );
    final Filter filter = FilterUtil.createAndFilter ( ObjectPool.class.getName (), parameters );

    this.poolTracker = new ServiceTracker<ObjectPool<S>, ObjectPool<S>> ( context, filter, new ServiceTrackerCustomizer<ObjectPool<S>, ObjectPool<S>> () {

        @Override
        public void removedService ( final ServiceReference<ObjectPool<S>> reference, final ObjectPool<S> service )
        {
            context.ungetService ( reference );
            ObjectPoolTracker.this.removePool ( service );
        }

        @Override
        public void modifiedService ( final ServiceReference<ObjectPool<S>> reference, final ObjectPool<S> service )
        {
            ObjectPoolTracker.this.modifyPool ( service, reference );
        }

        @Override
        public ObjectPool<S> addingService ( final ServiceReference<ObjectPool<S>> reference )
        {
            final ObjectPool<S> o = context.getService ( reference );
            ObjectPoolTracker.this.addPool ( o, reference );
            return o;
        }
    } );
}
 
Example 18
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void start(BundleContext bc)
{

  Activator.bc = bc;

  log = new LogRef(bc, true);

  serverFactory = new HttpServerFactory(bc, log);

  final Dictionary<String, String> parameters =
    new Hashtable<String, String>();
  parameters.put("service.pid", FACTORY_PID);
  configReg =
    bc.registerService(ManagedServiceFactory.class, serverFactory, parameters);

  ServiceReference<ConfigurationAdmin> adminRef = null;
  try {
    ConfigurationAdmin admin = null;
    Configuration[] configs = null;
    try {
      adminRef = bc.getServiceReference(ConfigurationAdmin.class);

      // Potential start order problem!
      if (adminRef != null) {
        admin = bc.getService(adminRef);
        final String filter =
          "(&(service.factoryPid=" + FACTORY_PID + ")"
              + "(|(service.bundleLocation=" + bc.getBundle().getLocation()
              + ")" + "(service.bundleLocation=NULL)"
              + "(!(service.bundleLocation=*))))";
        configs = admin.listConfigurations(filter);
      }
    } catch (final Exception e) {
      if (log.doDebug()) {
        log.debug("Exception when trying to get CM", e);
      }
    }
    if (admin == null) {
      if (log.doInfo()) {
        log.info("No CM present, using default configuration");
      }
      serverFactory.updated(HttpServerFactory.DEFAULT_PID,
                            HttpConfig.getDefaultConfig(bc));
    } else {
      if (configs == null || configs.length == 0) {
        if (log.doInfo()) {
          log.info("No configuration present, creating default configuration");
        }

        serverFactory.updated(HttpServerFactory.DEFAULT_PID,
                              HttpConfig.getDefaultConfig(bc));
      }
    }
  } catch (final ConfigurationException ce) {
    if (log.doError()) {
      log.error("Configuration error", ce);
    }

  } finally {
    if (adminRef != null) {
      bc.ungetService(adminRef);
    }
  }
  registerCommandGroup();

}
 
Example 19
Source File: ChannelAspectProcessor.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
public ChannelAspectProcessor ( final BundleContext context )
{

    this.tracker = new ServiceTracker<ChannelAspectFactory, FactoryEntry> ( context, ChannelAspectFactory.class, new ServiceTrackerCustomizer<ChannelAspectFactory, FactoryEntry> () {

        @Override
        public FactoryEntry addingService ( final ServiceReference<ChannelAspectFactory> reference )
        {
            return makeEntry ( context, reference );
        }

        @Override
        public void modifiedService ( final ServiceReference<ChannelAspectFactory> reference, final FactoryEntry service )
        {
        }

        @Override
        public void removedService ( final ServiceReference<ChannelAspectFactory> reference, final FactoryEntry service )
        {
            context.ungetService ( reference ); // makeEntry got the service
        }
    } );
    this.tracker.open ();

    this.groupTracker = new ServiceTracker<Group, GroupInformation> ( context, Group.class, new ServiceTrackerCustomizer<Group, GroupInformation> () {

        @Override
        public GroupInformation addingService ( final ServiceReference<Group> reference )
        {
            final Group group = context.getService ( reference );
            return group.getInformation ();
        }

        @Override
        public void modifiedService ( final ServiceReference<Group> reference, final GroupInformation service )
        {
        }

        @Override
        public void removedService ( final ServiceReference<Group> reference, final GroupInformation service )
        {
            context.ungetService ( reference );
        }
    } );
    this.groupTracker.open ();
}
 
Example 20
Source File: DaveBlockConfigurator.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DaveBlockConfigurator ( final DaveDevice device, final BundleContext context )
{
    this.device = device;
    this.context = context;

    final Map<String, String> parameters = new HashMap<String, String> ();
    parameters.put ( "daveDevice", device.getId () );
    try
    {
        final Filter filter = FilterUtil.createAndFilter ( BlockConfiguration.class.getName (), parameters );
        this.tracker = new ServiceTracker<Object, Object> ( context, filter, new ServiceTrackerCustomizer<Object, Object> () {

            @Override
            public void removedService ( final ServiceReference<Object> reference, final Object service )
            {
                if ( service instanceof BlockConfiguration )
                {
                    if ( DaveBlockConfigurator.this.removeBlock ( reference, (BlockConfiguration)service ) )
                    {
                        context.ungetService ( reference );
                    }
                }
            }

            @Override
            public void modifiedService ( final ServiceReference<Object> reference, final Object service )
            {
                DaveBlockConfigurator.this.modifyBlock ( reference, (BlockConfiguration)service );
            }

            @Override
            public Object addingService ( final ServiceReference<Object> reference )
            {
                final Object o = DaveBlockConfigurator.this.context.getService ( reference );
                try
                {
                    DaveBlockConfigurator.this.addOrReplaceBlock ( reference, (BlockConfiguration)o );
                    return o;
                }
                catch ( final Throwable e )
                {
                    logger.warn ( "Failed to add block", e );
                    return o;
                }
            }
        } );
    }
    catch ( final Exception e )
    {
        logger.warn ( "Failed to configure", e );
    }
    if ( this.tracker != null )
    {
        this.tracker.open ();
    }
}