Java Code Examples for org.osgi.util.tracker.ServiceTracker#waitForService()

The following examples show how to use org.osgi.util.tracker.ServiceTracker#waitForService() . 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: OsgiConfigurationServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Wait for an OSGi service to become active.
 *
 * @param serviceImpl The service implementation class
 * @param timeout The length of time to wait for the service
 */
private void waitForService(Class serviceImpl, long timeout) {
    Class serviceInterface = serviceImpl.getInterfaces()[0];
    BundleContext bundleContext = FrameworkUtil.getBundle(serviceInterface).getBundleContext();
    ServiceReference factoryRef = bundleContext.getServiceReference(serviceInterface.getName());

    ServiceTracker serviceTracker = new ServiceTracker(bundleContext, factoryRef, null);
    serviceTracker.open();

    try {
        serviceTracker.waitForService(timeout);
    } catch (InterruptedException e) {
        LOGGER.error("Could not get service", e);
    }

    serviceTracker.close();
}
 
Example 2
Source File: LaunchServiceTest.java    From JaxRSProviders with Apache License 2.0 6 votes vote down vote up
static <T> T getService(Class<T> clazz) {
	Bundle bundle = FrameworkUtil.getBundle(LaunchServiceTest.class);
	bundle.getBundleContext().getBundles();
	if (bundle != null) {
		ServiceTracker<T, T> st = new ServiceTracker<T, T>(bundle.getBundleContext(), clazz, null);
		st.open();
		if (st != null) {
			try {
				// give the runtime some time to startup
				return st.waitForService(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	return null;
}
 
Example 3
Source File: ServiceRule.java    From osgi-best-practices with Apache License 2.0 5 votes vote down vote up
public <T> T require(Class<T> serviceClass) {
    ServiceTracker<T, T> tracker = new ServiceTracker<T, T>(bundle.getBundleContext(), serviceClass, null);
    tracker.open();
    trackers.add(()->tracker.close());
    try {
        return tracker.waitForService(10000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IllegalStateException("Timeout waiting for service " + serviceClass.getName());
    }
}
 
Example 4
Source File: KarafTestSupport.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void waitForService(String filter, long timeout) throws InvalidSyntaxException, InterruptedException {
    ServiceTracker st = new ServiceTracker(bundleContext, bundleContext.createFilter(filter), null);
    try {
        st.open();
        st.waitForService(timeout);
    } finally {
        st.close();
    }
}
 
Example 5
Source File: ArtemisFeatureTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected Object waitForService(String filter, long timeout) throws InvalidSyntaxException, InterruptedException {
   ServiceTracker<Object, Object> st = new ServiceTracker<>(bundleContext, bundleContext.createFilter(filter), null);
   try {
      st.open();
      return st.waitForService(timeout);
   } finally {
      st.close();
   }
}
 
Example 6
Source File: AbstractServerActivator.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void awaitService(BundleContext bundleContext, String filter, long timeout)
        throws InvalidSyntaxException, InterruptedException {
    Filter serviceFilter = bundleContext.createFilter(filter);
    ServiceTracker<Object, ?> tracker = new ServiceTracker<>(bundleContext, serviceFilter, null);
    tracker.open();
    Object service = tracker.waitForService(timeout);
    tracker.close();
    if (service == null) {
        throw new IllegalStateException("Expected service with filter " + filter + " was not found");
    }
}
 
Example 7
Source File: BootstrapListener.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private static void installNexusEdition(final BundleContext ctx, final Properties properties)
    throws Exception
{
  String editionName = properties.getProperty(NEXUS_EDITION);
  if (editionName != null && editionName.length() > 0) {
    final ServiceTracker<?, FeaturesService> tracker = new ServiceTracker<>(ctx, FeaturesService.class, null);
    tracker.open();
    try {
      FeaturesService featuresService = tracker.waitForService(1000);
      Feature editionFeature = featuresService.getFeature(editionName);
      properties.put(NEXUS_FULL_EDITION, editionFeature.toString());

      Feature dbFeature = featuresService.getFeature(properties.getProperty(NEXUS_DB_FEATURE));

      log.info("Installing: {} ({})", editionFeature, dbFeature);

      Set<String> featureIds = new LinkedHashSet<>();
      if (!featuresService.isInstalled(editionFeature)) {
        featureIds.add(editionFeature.getId());
      }
      if (!featuresService.isInstalled(dbFeature)) {
        featureIds.add(dbFeature.getId());
      }

      if (detectMixedMode(properties)) {
        Feature mybatisFeature = featuresService.getFeature("nexus-datastore-mybatis");
        if (!featuresService.isInstalled(mybatisFeature)) {
          featureIds.add(mybatisFeature.getId());
        }
      }

      // edition might already be installed in the cache; if so then skip installation
      if (!featureIds.isEmpty()) {
        // avoid auto-refreshing bundles as that could trigger unwanted restart/lifecycle events
        EnumSet<Option> options = EnumSet.of(NoAutoRefreshBundles, NoAutoRefreshManagedBundles);
        featuresService.installFeatures(featureIds, options);
      }

      log.info("Installed: {} ({})", editionFeature, dbFeature);
    }
    finally {
      tracker.close();
    }
  }
}
 
Example 8
Source File: PCEPTunnelClusterSingletonService.java    From bgpcep with Eclipse Public License 1.0 4 votes vote down vote up
public PCEPTunnelClusterSingletonService(
        final TunnelProviderDependencies dependencies,
        final InstanceIdentifier<Topology> pcepTopology,
        final TopologyId tunnelTopologyId
) {
    this.dependencies = requireNonNull(dependencies);
    this.tunnelTopologyId = requireNonNull(tunnelTopologyId);
    final TopologyId pcepTopologyId = pcepTopology.firstKeyOf(Topology.class).getTopologyId();

    final InstructionScheduler scheduler;
    ServiceTracker<InstructionScheduler, ?> tracker = null;
    try {
        tracker = new ServiceTracker<>(dependencies.getBundleContext(),
                dependencies.getBundleContext().createFilter(String.format("(&(%s=%s)%s)", Constants.OBJECTCLASS,
                        InstructionScheduler.class.getName(), "(" + InstructionScheduler.class.getName()
                        + "=" + pcepTopologyId.getValue() + ")")), null);
        tracker.open();
        scheduler = (InstructionScheduler) tracker.waitForService(
                TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES));
        Preconditions.checkState(scheduler != null, "InstructionScheduler service not found");
    } catch (InvalidSyntaxException | InterruptedException e) {
        throw new IllegalStateException("Error retrieving InstructionScheduler service", e);
    } finally {
        if (tracker != null) {
            tracker.close();
        }
    }

    final InstanceIdentifier<Topology> tunnelTopology = InstanceIdentifier.builder(NetworkTopology.class)
            .child(Topology.class, new TopologyKey(tunnelTopologyId)).build();
    this.ttp = new PCEPTunnelTopologyProvider(dependencies.getDataBroker(), pcepTopology, pcepTopologyId,
            tunnelTopology, tunnelTopologyId);


    this.sgi = scheduler.getIdentifier();
    this.tp = new TunnelProgramming(scheduler, dependencies);


    final Dictionary<String, String> properties = new Hashtable<>();
    properties.put(PCEPTunnelTopologyProvider.class.getName(), tunnelTopologyId.getValue());
    this.serviceRegistration = dependencies.getBundleContext()
            .registerService(DefaultTopologyReference.class.getName(), this.ttp, properties);

    LOG.info("PCEP Tunnel Cluster Singleton service {} registered", getIdentifier().getName());
    this.pcepTunnelCssReg = dependencies.getCssp().registerClusterSingletonService(this);
}