@Test
  public void testRegBundleIsRefBundle() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();

      final CountDownLatch latch = new CountDownLatch(1);
      ServiceListener listener =
          new ServiceListener() {
            public void serviceChanged(ServiceEvent event) {
              latch.countDown();
            }
          };
      BundleContext context = bundle.getBundleContext();
      context.addServiceListener(listener);

      Object service = bundle.loadClass(A.class.getName()).newInstance();
      ServiceRegistration reg = context.registerService(A.class.getName(), service, null);

      ServiceReference ref = reg.getReference();
      assertTrue(ref.isAssignableTo(bundle, A.class.getName()));

      if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException();

    } finally {
      bundle.uninstall();
    }
  }
  /**
   * Removes the specified account from the list of accounts that this provider factory is handling.
   * If the specified accountID is unknown to the ProtocolProviderFactory, the call has no effect
   * and false is returned. This method is persistent in nature and once called the account
   * corresponding to the specified ID will not be loaded during future runs of the project.
   *
   * @param accountID the ID of the account to remove.
   * @return true if an account with the specified ID existed and was removed and false otherwise.
   */
  public boolean uninstallAccount(AccountID accountID) {
    // unregister the protocol provider
    ServiceReference serRef = getProviderForAccount(accountID);

    if (serRef == null) return false;

    ProtocolProviderService protocolProvider =
        (ProtocolProviderService) SipActivator.getBundleContext().getService(serRef);

    try {
      protocolProvider.unregister();
    } catch (OperationFailedException e) {
      logger.error(
          "Failed to unregister protocol provider for account : "
              + accountID
              + " caused by : "
              + e);
    }

    ServiceRegistration registration = (ServiceRegistration) registeredAccounts.remove(accountID);

    if (registration == null) return false;

    // kill the service
    registration.unregister();

    return removeStoredAccount(SipActivator.getBundleContext(), accountID);
  }
Exemplo n.º 3
0
  public void testGetExtHttpService() {
    final BundleContext bundleContext = getContext();
    assertNotNull(bundleContext);
    final ExtHttpServiceMock extHttpService = new ExtHttpServiceMock(new UrlUtilImpl());
    assertNotNull(extHttpService);
    // zum start: keine Dienste registriert
    assertEquals(0, extHttpService.getRegisterFilterCallCounter());
    assertEquals(0, extHttpService.getRegisterServletCallCounter());
    assertEquals(0, extHttpService.getUnregisterFilterCallCounter());
    assertEquals(0, extHttpService.getUnregisterServletCallCounter());
    final ServiceRegistration serviceRegistration =
        bundleContext.registerService(ExtHttpService.class.getName(), extHttpService, null);
    assertNotNull(serviceRegistration);
    // nach start: Dienste vorhanden?
    assertTrue("no filters registered", extHttpService.getRegisterFilterCallCounter() > 0);
    assertTrue("no servlets registered.", extHttpService.getRegisterServletCallCounter() > 0);
    assertEquals(0, extHttpService.getUnregisterFilterCallCounter());
    assertEquals(0, extHttpService.getUnregisterServletCallCounter());

    // do unregister
    serviceRegistration.unregister();

    assertTrue("no servlets unregistered", extHttpService.getUnregisterServletCallCounter() > 0);
    assertEquals(
        extHttpService.getRegisterServletCallCounter(),
        extHttpService.getRegisterServletCallCounter());
    assertEquals(
        extHttpService.getRegisterFilterCallCounter(),
        extHttpService.getUnregisterFilterCallCounter());
  }
  @Test
  public void testOwnerCannotSeeServiceClass() throws Exception {
    final Bundle bundleA = installBundle(getBundleArchiveA());
    final Bundle bundleB = installBundle(getBundleArchiveB());
    try {
      bundleA.start();
      bundleB.start();

      BundleContext contextA = bundleA.getBundleContext();
      BundleContext contextB = bundleB.getBundleContext();

      final CountDownLatch latch = new CountDownLatch(1);
      ServiceListener listener =
          new ServiceListener() {
            public void serviceChanged(ServiceEvent event) {
              latch.countDown();
            }
          };
      contextB.addServiceListener(listener);

      Object service = bundleB.loadClass(B.class.getName()).newInstance();
      ServiceRegistration reg = contextA.registerService(B.class.getName(), service, null);

      ServiceReference ref = reg.getReference();
      assertTrue(ref.isAssignableTo(bundleA, B.class.getName()));
      assertTrue(ref.isAssignableTo(bundleB, B.class.getName()));

      if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException();

    } finally {
      bundleA.uninstall();
      bundleB.uninstall();
    }
  }
  @Test
  public void testUnkeyedServiceReferencesBalanceRefCount() {
    RegistryWrapper registryWrapper = getRegistryWrapper();

    try (ServiceTrackerMap<TrackedOne, TrackedOne> serviceTrackerMap =
        ServiceTrackerCollections.singleValueMap(
            TrackedOne.class,
            null,
            new ServiceReferenceMapper<TrackedOne, TrackedOne>() {

              @Override
              public void map(
                  ServiceReference<TrackedOne> serviceReference, Emitter<TrackedOne> emitter) {}
            })) {

      serviceTrackerMap.open();

      ServiceRegistration<TrackedOne> serviceRegistration1 = registerService(new TrackedOne());
      ServiceRegistration<TrackedOne> serviceRegistration2 = registerService(new TrackedOne());

      Map<ServiceReference<?>, AtomicInteger> serviceReferenceCountsMap =
          registryWrapper.getServiceReferenceCountsMap();

      Collection<AtomicInteger> serviceReferenceCounts = serviceReferenceCountsMap.values();

      Assert.assertEquals(0, serviceReferenceCounts.size());

      serviceRegistration1.unregister();
      serviceRegistration2.unregister();

      Assert.assertEquals(0, serviceReferenceCounts.size());
    } finally {
      RegistryUtil.setRegistry(registryWrapper.getWrappedRegistry());
    }
  }
  @Test
  public void testObjectClassFilter() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext context = bundle.getBundleContext();
      assertNotNull(context);
      assertNoServiceEvent();

      String filter = "(" + Constants.OBJECTCLASS + "=" + BundleContext.class.getName() + ")";
      context.addServiceListener(this, filter);

      ServiceRegistration sreg =
          context.registerService(BundleContext.class.getName(), context, null);
      ServiceReference sref = sreg.getReference();

      assertServiceEvent(ServiceEvent.REGISTERED, sref);

      sreg.unregister();
      assertServiceEvent(ServiceEvent.UNREGISTERING, sref);

      filter = "(objectClass=dummy)";
      context.addServiceListener(this, filter);

      sreg = context.registerService(BundleContext.class.getName(), context, null);
      assertNoServiceEvent();

      sreg.unregister();
      assertNoServiceEvent();
    } finally {
      bundle.uninstall();
    }
  }
  /** @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */
  public void stop(BundleContext bundleContext) {
    // shut down the trackers.
    m_eventAdmin.destroy();

    // Clean up the listeners.
    bundleContext.removeBundleListener(m_frameworkHandler);
    bundleContext.removeFrameworkListener(m_frameworkHandler);
    bundleContext.removeServiceListener(m_frameworkHandler);

    // Remove the global handler for all JDK Logging (java.util.logging).
    if (m_JdkHandler != null) {
      Logger rootLogger = LogManager.getLogManager().getLogger("");
      rootLogger.removeHandler(m_JdkHandler);
      m_JdkHandler.flush();
      m_JdkHandler.close();
      m_JdkHandler = null;
    }

    m_RegistrationPaxLogging.unregister();
    m_RegistrationPaxLogging = null;

    m_registrationLogReaderService.unregister();
    m_registrationLogReaderService = null;

    m_paxLogging.stop();
    m_paxLogging = null;
  }
  public void terminatingConfigurationContext(ConfigurationContext configurationContext) {
    String tenantDomain =
        SuperTenantCarbonContext.getCurrentContext(configurationContext).getTenantDomain();

    log.info("Shutting down the persistence manager for the tenant: " + tenantDomain);

    Parameter p =
        configurationContext
            .getAxisConfiguration()
            .getParameter(ServiceBusConstants.PERSISTENCE_MANAGER);
    if (p != null && p.getValue() instanceof MediationPersistenceManager) {
      ((MediationPersistenceManager) p.getValue()).destroy();
    }

    // unregister the service so that components get to know about the tenant termination
    int tenantId = SuperTenantCarbonContext.getCurrentContext(configurationContext).getTenantId();
    ServiceRegistration tenantRegistration =
        ConfigurationHolder.getInstance().getSynapseRegistration(tenantId);

    if (tenantRegistration != null) {
      ConfigurationHolder.getInstance()
          .getBundleContext()
          .ungetService(tenantRegistration.getReference());
    }
  }
 final ServiceReference<S> getServiceReference() {
   ServiceRegistration<S> reg = getServiceRegistration();
   if (reg != null) {
     return reg.getReference();
   }
   return null;
 }
Exemplo n.º 10
0
 /**
  * unregisters the Engines service registration, closes the SolrCore and rests the fields. If no
  * engine is registered this does nothing!
  */
 private void unregisterEngine() {
   // use local copies for method calls to avoid concurrency issues
   ServiceRegistration engineRegistration = this.engineRegistration;
   if (engineRegistration != null) {
     log.info(" ... unregister Lucene FSTLinkingEngine {}", engineName);
     engineRegistration.unregister();
     this.engineRegistration = null; // reset the field
   }
   solrServerReference = null;
   SolrCore solrServer = this.solrCore;
   if (solrServer != null) {
     log.debug(" ... unregister SolrCore {}", solrServer.getName());
     solrServer.close(); // decrease the reference count!!
     this.solrCore = null; // rest the field
   }
   // deactivate the index configuration if present
   if (indexConfig != null) {
     log.debug(" ... deactivate IndexingConfiguration");
     indexConfig.deactivate();
     // close the EntityCacheManager (if present
     EntityCacheManager cacheManager = indexConfig.getEntityCacheManager();
     if (cacheManager != null) {
       log.debug(" ... deactivate {}", cacheManager.getClass().getSimpleName());
       cacheManager.close();
     }
     indexConfig = null;
   }
 }
  @Test
  public void testGetServiceWithCustomResolver() {
    try (ServiceTrackerMap<String, TrackedOne> serviceTrackerMap =
        ServiceTrackerCollections.singleValueMap(
            TrackedOne.class,
            "(&(other=*)(target=*))",
            new ServiceReferenceMapper<String, TrackedOne>() {

              @Override
              public void map(ServiceReference<TrackedOne> serviceReference, Emitter<String> keys) {

                keys.emit(
                    serviceReference.getProperty("other")
                        + " - "
                        + serviceReference.getProperty("target"));
              }
            })) {

      serviceTrackerMap.open();

      Dictionary<String, String> properties = new Hashtable<>();

      properties.put("other", "aProperty");
      properties.put("target", "aTarget");

      ServiceRegistration<TrackedOne> serviceRegistration =
          _bundleContext.registerService(TrackedOne.class, new TrackedOne(), properties);

      Assert.assertNotNull(serviceTrackerMap.getService("aProperty - aTarget"));

      serviceRegistration.unregister();
    }
  }
Exemplo n.º 12
0
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
   */
  public void stop(final BundleContext context) throws Exception {
    // TODO-mkuppe here we should do something like a deregisterAll(), but see ungetService(...);
    if (serviceRegistration != null && serviceFactory.isActive()) {
      ServiceReference reference = serviceRegistration.getReference();
      IDiscoveryLocator aLocator = (IDiscoveryLocator) context.getService(reference);

      serviceRegistration.unregister();

      IContainer container = (IContainer) aLocator.getAdapter(IContainer.class);
      container.disconnect();
      container.dispose();

      serviceRegistration = null;
    }
    plugin = null;
    bundleContext = null;
    if (advertiserSt != null) {
      advertiserSt.close();
      advertiserSt = null;
    }
    if (locatorSt != null) {
      locatorSt.close();
      locatorSt = null;
    }
  }
  @Test
  public void testSetPropertiesAfterStop() throws Exception {
    Bundle bundle = installBundle(getBundleArchiveA());
    try {
      bundle.start();
      BundleContext bundleContext = bundle.getBundleContext();
      assertNotNull(bundleContext);

      ServiceRegistration registration =
          bundleContext.registerService(BundleContext.class.getName(), bundleContext, null);
      assertNotNull(registration);

      bundle.stop();

      try {
        registration.setProperties(new Hashtable<String, Object>());
        fail("Should not be here!");
      } catch (IllegalStateException t) {
        // expected
      }
      assertNoServiceEvent();
    } finally {
      bundle.uninstall();
    }
  }
  /**
   * Returns the ServiceReference for the protocol provider corresponding to the specified accountID
   * or null if the accountID is unknown.
   *
   * @param accountID the accountID of the protocol provider we'd like to get
   * @return a ServiceReference object to the protocol provider with the specified account id and
   *     null if the account id is unknown to the provider factory.
   */
  public ServiceReference getProviderForAccount(AccountID accountID) {
    ServiceRegistration registration;

    synchronized (registeredAccounts) {
      registration = registeredAccounts.get(accountID);
    }
    return (registration == null) ? null : registration.getReference();
  }
Exemplo n.º 15
0
 public void stop(BundleContext bundleContext) throws Exception {
   if (userCredentialsService != null) {
     userCredentialsService.unregister();
   }
   if (userProfileService != null) {
     userProfileService.unregister();
   }
 }
Exemplo n.º 16
0
 @Override
 public boolean unsubscribe(EventHandler eventHandler) {
   Collection<ServiceRegistration<?>> handled = registrations.remove(eventHandler);
   if (handled == null || handled.isEmpty()) return false;
   for (ServiceRegistration<?> r : handled) {
     r.unregister();
   }
   return true;
 }
Exemplo n.º 17
0
 @PreDestroy
 void dispose() {
   Collection<Collection<ServiceRegistration<?>>> values = new ArrayList<>(registrations.values());
   registrations.clear();
   for (Collection<ServiceRegistration<?>> handled : values) {
     for (ServiceRegistration<?> registration : handled) {
       registration.unregister();
     }
   }
 }
Exemplo n.º 18
0
    protected synchronized void close() {
      for (ServiceRegistration<?> serviceRegistration : _serviceRegistrations) {

        serviceRegistration.unregister();
      }

      _bundlePortletApp = null;

      _serviceRegistrations.clear();
    }
 @After
 public void tearDown() {
   for (ServiceRegistration<?> serviceRegistration : serviceRegistrations) {
     try {
       serviceRegistration.unregister();
     } catch (IllegalStateException e) {
       // Service was already unregistered.
     }
   }
 }
  @Test
  public void testGetServiceWithServiceCustomizer() {
    final Registry registry = RegistryUtil.getRegistry();

    try (ServiceTrackerMap<String, TrackedTwo> serviceTrackerMap =
        ServiceTrackerCollections.singleValueMap(
            TrackedOne.class,
            "target",
            new ServiceTrackerCustomizer<TrackedOne, TrackedTwo>() {

              @Override
              public TrackedTwo addingService(ServiceReference<TrackedOne> serviceReference) {

                return new TrackedTwo(registry.getService(serviceReference));
              }

              @Override
              public void modifiedService(
                  ServiceReference<TrackedOne> serviceReference, TrackedTwo service) {

                removedService(serviceReference, service);
              }

              @Override
              public void removedService(
                  ServiceReference<TrackedOne> serviceReference, TrackedTwo service) {

                registry.ungetService(serviceReference);
              }
            })) {

      serviceTrackerMap.open();

      TrackedOne trackedOne1 = new TrackedOne();

      ServiceRegistration<TrackedOne> serviceRegistration1 =
          registerService(trackedOne1, "trackedOne1");

      TrackedOne trackedOne2 = new TrackedOne();

      ServiceRegistration<TrackedOne> serviceRegistration2 =
          registerService(trackedOne2, "trackedOne2");

      TrackedTwo trackedTwo1 = serviceTrackerMap.getService("trackedOne1");

      Assert.assertEquals(trackedOne1, trackedTwo1.getTrackedOne());

      TrackedTwo trackedTwo2 = serviceTrackerMap.getService("trackedOne2");

      Assert.assertEquals(trackedOne2, trackedTwo2.getTrackedOne());

      serviceRegistration1.unregister();
      serviceRegistration2.unregister();
    }
  }
  @Test
  public void testGetServiceWithSimpleRegistration() {
    try (ServiceTrackerMap<String, TrackedOne> serviceTrackerMap = createServiceTrackerMap()) {

      ServiceRegistration<TrackedOne> serviceRegistration = registerService(new TrackedOne());

      Assert.assertNotNull(serviceTrackerMap.getService("aTarget"));

      serviceRegistration.unregister();
    }
  }
  @Test
  public void testWhiteBoardFiltered() throws Exception {
    Dictionary<String, String> props = new Hashtable<String, String>();
    props.put("urlPatterns", "*");
    ServiceRegistration<Filter> filter =
        bundleContext.registerService(Filter.class, new WhiteboardFilter(), props);

    testWebPath("http://127.0.0.1:8181/", "Filter was there before");

    filter.unregister();
  }
 @Test
 public void createServiceTrackerAndUnregisterService_shouldNotBeInTracker() throws Exception {
   ServiceRegistration serviceRegistration =
       bundleContext.registerService(
           Collection.class.getName(), new HashSet<Object>(), new Hashtable<String, Object>());
   ServiceTracker serviceTracker =
       new ServiceTracker(bundleContext, Collection.class.getName(), null);
   serviceTracker.open();
   serviceRegistration.unregister();
   assertNull(serviceTracker.getService());
 }
  static List<Runner> startRunners(BundleContext ctx, int numThreads) {
    ServiceRegistration<String> reg = ctx.registerService(String.class, new PSF(), null);

    List<Runner> runners = new ArrayList<>();
    for (int i = 0; i < numThreads; i++) {
      SingleBundlePrototypeRunner r = new SingleBundlePrototypeRunner(ctx, reg.getReference());
      runners.add(r);
      r.start();
    }
    return runners;
  }
Exemplo n.º 25
0
 @Override
 public void stop(@Nonnull BundleContext context) throws Exception {
   ServiceRegistration<XmlParser> registration = this.registration;
   if (registration != null) {
     try {
       registration.unregister();
     } catch (Exception ignore) {
     }
     this.registration = null;
   }
 }
  @Override
  public void removingEntries(Bundle bundle, List<String> resources) {
    List<ServiceRegistration> srList = serviceRegistrationMap.get(bundle);
    for (ServiceRegistration sr : srList) {
      LOGGER.debug(
          "{} bundle uninstalled and unregistered.",
          sr.getReference().getBundle().getSymbolicName());
      sr.unregister();
    }

    serviceRegistrationMap.remove(bundle);
  }
Exemplo n.º 27
0
  @Test
  public void testDirectoryAgentListenerServiceTracker() throws Exception {
    UserAgent userAgent = SLP.newUserAgent(newSettings());
    StandardDirectoryAgentServer directoryAgentServer =
        StandardDirectoryAgentServer.newInstance(newSettings());
    final AtomicInteger counter = new AtomicInteger();

    userAgent.start();

    DirectoryAgentListenerServiceTracker tracker =
        new DirectoryAgentListenerServiceTracker(bundleContext, userAgent);
    tracker.open();

    ServiceRegistration serviceRegistration =
        bundleContext.registerService(
            DirectoryAgentListener.class.getName(),
            new DirectoryAgentListener() {
              public void directoryAgentBorn(DirectoryAgentEvent event) {
                counter.incrementAndGet();
              }

              public void directoryAgentDied(DirectoryAgentEvent event) {
                counter.decrementAndGet();
              }
            },
            null);

    directoryAgentServer.start();

    Thread.sleep(1000);

    Assert.assertEquals(1, tracker.size());
    Assert.assertEquals(1, counter.get());

    directoryAgentServer.stop();

    Thread.sleep(1000);

    Assert.assertEquals(1, tracker.size());
    Assert.assertEquals(0, counter.get());

    serviceRegistration.unregister();

    Thread.sleep(500);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    tracker.close();

    directoryAgentServer.stop();
    userAgent.stop();
  }
 private void unregisterEventingService() {
   if (eventingServiceRegistration != null) {
     EventingDataHolder.getInstance().setRegistryEventingService(null);
     eventingServiceRegistration.unregister();
     eventingServiceRegistration = null;
     notificationServiceRegistration.unregister();
     notificationServiceRegistration = null;
     emailVerificationServiceRegistration.unregister();
     emailVerificationServiceRegistration = null;
     service = null;
     log.debug("Successfully unregistered the Eventing OGSi Service");
   }
 }
Exemplo n.º 29
0
 @PreDestroy
 void dispose() {
   Collection<Collection<ServiceRegistration<?>>> values =
       new ArrayList<Collection<ServiceRegistration<?>>>(registrations.values());
   registrations.clear();
   for (Collection<ServiceRegistration<?>> handled : values) {
     for (ServiceRegistration<?> registration : handled) {
       // System.out.println("EventBroker dispose:" + registration[i] +
       // ")");
       registration.unregister();
     }
   }
 }
Exemplo n.º 30
0
  @Test
  public void testByServiceInfoServiceTracker() throws Exception {
    ServiceAgent serviceAgent = SLP.newServiceAgent(newSettings());
    UserAgent userAgent = SLP.newUserAgent(newSettings());
    final AtomicInteger counter = new AtomicInteger();

    userAgent.addServiceNotificationListener(
        new ServiceNotificationListener() {
          public void serviceRegistered(ServiceNotificationEvent event) {
            counter.incrementAndGet();
          }

          public void serviceDeregistered(ServiceNotificationEvent event) {
            counter.decrementAndGet();
          }
        });

    serviceAgent.start();
    userAgent.start();

    ByServiceInfoServiceTracker tracker =
        new ByServiceInfoServiceTracker(bundleContext, serviceAgent);
    tracker.open();

    ServiceRegistration serviceRegistration =
        bundleContext.registerService(
            ServiceInfo.class.getName(),
            new ServiceInfo(
                new ServiceURL("service:printer:lpr://myprinter/myqueue"),
                Locale.ENGLISH.getLanguage(),
                Scopes.DEFAULT,
                Attributes.from("(printer-compression-supported=deflate, gzip)")),
            null);

    Thread.sleep(500);

    Assert.assertEquals(1, tracker.size());
    Assert.assertEquals(1, counter.get());

    serviceRegistration.unregister();

    Thread.sleep(500);

    Assert.assertEquals(0, tracker.size());
    Assert.assertEquals(0, counter.get());

    tracker.close();

    userAgent.stop();
    serviceAgent.stop();
  }