Search in sources :

Example 76 with ServiceReference

use of org.osgi.framework.ServiceReference in project sling by apache.

the class AbstractSlingRepositoryManager method start.

/**
     * This method actually starts the backing repository instannce and
     * registeres the repository service.
     * <p>
     * Multiple subsequent calls to this method without calling {@link #stop()}
     * first have no effect.
     *
     * @param bundleContext The {@code BundleContext} to register the repository
     *            service (and optionally more services required to operate the
     *            repository)
     * @param config The configuration to apply to this instance.
     */
protected final void start(final BundleContext bundleContext, final Config config) {
    // already setup ?
    if (this.bundleContext != null) {
        log.debug("start: Repository already started and registered");
        return;
    }
    this.bundleContext = bundleContext;
    this.defaultWorkspace = config.defaultWorkspace;
    this.disableLoginAdministrative = config.disableLoginAdministrative;
    this.repoInitializerTracker = new ServiceTracker<SlingRepositoryInitializer, SlingRepositoryInitializerInfo>(bundleContext, SlingRepositoryInitializer.class, new ServiceTrackerCustomizer<SlingRepositoryInitializer, SlingRepositoryInitializerInfo>() {

        @Override
        public SlingRepositoryInitializerInfo addingService(final ServiceReference<SlingRepositoryInitializer> reference) {
            final SlingRepositoryInitializer service = bundleContext.getService(reference);
            if (service != null) {
                final SlingRepositoryInitializerInfo info = new SlingRepositoryInitializerInfo(service, reference);
                synchronized (repoInitLock) {
                    if (masterSlingRepository != null) {
                        log.debug("Executing {}", info.initializer);
                        try {
                            info.initializer.processRepository(masterSlingRepository);
                        } catch (final Exception e) {
                            log.error("Exception in a SlingRepositoryInitializer: " + info.initializer, e);
                        }
                    }
                }
                return info;
            }
            return null;
        }

        @Override
        public void modifiedService(final ServiceReference<SlingRepositoryInitializer> reference, final SlingRepositoryInitializerInfo service) {
        // nothing to do
        }

        @Override
        public void removedService(final ServiceReference<SlingRepositoryInitializer> reference, final SlingRepositoryInitializerInfo service) {
            bundleContext.ungetService(reference);
        }
    });
    this.repoInitializerTracker.open();
    // If allowLoginAdministrativeForBundle is overridden we assume we don't need
    // a LoginAdminWhitelist service - that's the case if the derived class
    // implements its own strategy and the LoginAdminWhitelist interface is
    // not exported by this bundle anyway, so cannot be implemented differently.
    boolean enableWhitelist = !isAllowLoginAdministrativeForBundleOverridden();
    final CountDownLatch waitForWhitelist = new CountDownLatch(enableWhitelist ? 1 : 0);
    if (enableWhitelist) {
        whitelistTracker = new ServiceTracker<LoginAdminWhitelist, LoginAdminWhitelist>(bundleContext, LoginAdminWhitelist.class, null) {

            @Override
            public LoginAdminWhitelist addingService(final ServiceReference<LoginAdminWhitelist> reference) {
                try {
                    return super.addingService(reference);
                } finally {
                    waitForWhitelist.countDown();
                }
            }
        };
        whitelistTracker.open();
    }
    // start repository asynchronously to allow LoginAdminWhitelist to become available
    // NOTE: making this conditional allows tests to register a mock whitelist before
    // activating the RepositoryManager, so they don't need to deal with async startup
    new Thread("Apache Sling Repository Startup Thread") {

        @Override
        public void run() {
            try {
                waitForWhitelist.await();
                initializeAndRegisterRepositoryService();
            } catch (InterruptedException e) {
                throw new RuntimeException("Interrupted while waiting for LoginAdminWhitelist", e);
            }
        }
    }.start();
}
Also used : ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) LoginAdminWhitelist(org.apache.sling.jcr.base.internal.LoginAdminWhitelist) CountDownLatch(java.util.concurrent.CountDownLatch) ServiceReference(org.osgi.framework.ServiceReference) SlingRepositoryInitializer(org.apache.sling.jcr.api.SlingRepositoryInitializer)

Example 77 with ServiceReference

use of org.osgi.framework.ServiceReference in project sling by apache.

the class FSClassLoaderProvider method activate.

/**
	 * Activate this component. Create the root directory.
	 *
	 * @param componentContext
	 * @throws MalformedURLException
	 * @throws InvalidSyntaxException
	 * @throws MalformedObjectNameException
	 */
@Activate
protected void activate(final ComponentContext componentContext) throws MalformedURLException, InvalidSyntaxException, MalformedObjectNameException {
    // get the file root
    this.root = new File(componentContext.getBundleContext().getDataFile(""), "classes");
    this.root.mkdirs();
    this.rootURL = this.root.toURI().toURL();
    this.callerBundle = componentContext.getUsingBundle();
    classLoaderWriterListeners.clear();
    if (classLoaderWriterServiceListener != null) {
        componentContext.getBundleContext().removeServiceListener(classLoaderWriterServiceListener);
        classLoaderWriterServiceListener = null;
    }
    classLoaderWriterServiceListener = new ServiceListener() {

        @Override
        public void serviceChanged(ServiceEvent event) {
            ServiceReference<ClassLoaderWriterListener> reference = (ServiceReference<ClassLoaderWriterListener>) event.getServiceReference();
            if (event.getType() == ServiceEvent.MODIFIED || event.getType() == ServiceEvent.REGISTERED) {
                classLoaderWriterListeners.put(getId(reference), reference);
            } else {
                classLoaderWriterListeners.remove(getId(reference));
            }
        }

        private Long getId(ServiceReference<ClassLoaderWriterListener> reference) {
            return (Long) reference.getProperty(Constants.SERVICE_ID);
        }
    };
    componentContext.getBundleContext().addServiceListener(classLoaderWriterServiceListener, LISTENER_FILTER);
    // handle the MBean Installation
    if (mbeanRegistration != null) {
        mbeanRegistration.unregister();
        mbeanRegistration = null;
    }
    Hashtable<String, String> jmxProps = new Hashtable<String, String>();
    jmxProps.put("type", "ClassLoader");
    jmxProps.put("name", "FSClassLoader");
    final Hashtable<String, Object> mbeanProps = new Hashtable<String, Object>();
    mbeanProps.put(Constants.SERVICE_DESCRIPTION, "Apache Sling FSClassLoader Controller Service");
    mbeanProps.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
    mbeanProps.put("jmx.objectname", new ObjectName("org.apache.sling.classloader", jmxProps));
    mbeanRegistration = componentContext.getBundleContext().registerService(FSClassLoaderMBean.class.getName(), new FSClassLoaderMBeanImpl(this, componentContext.getBundleContext()), mbeanProps);
}
Also used : ClassLoaderWriterListener(org.apache.sling.commons.classloader.ClassLoaderWriterListener) ServiceListener(org.osgi.framework.ServiceListener) Hashtable(java.util.Hashtable) ServiceReference(org.osgi.framework.ServiceReference) ObjectName(javax.management.ObjectName) ServiceEvent(org.osgi.framework.ServiceEvent) File(java.io.File) Activate(org.osgi.service.component.annotations.Activate)

Example 78 with ServiceReference

use of org.osgi.framework.ServiceReference in project aries by apache.

the class DSLTest method testConfigurationsAndRegistrations.

@Test
public void testConfigurationsAndRegistrations() throws InvalidSyntaxException, IOException, InterruptedException {
    ServiceReference<ConfigurationAdmin> serviceReference = bundleContext.getServiceReference(ConfigurationAdmin.class);
    ConfigurationAdmin configurationAdmin = bundleContext.getService(serviceReference);
    /*  For each factory configuration register a service with the property
            key set to the value of the property key that comes with the
            configuration */
    OSGi<ServiceRegistration<Service>> program = configurations("test.configuration").map(d -> d.get("key")).flatMap(key -> register(Service.class, new Service(), new HashMap<String, Object>() {

        {
            put("key", key);
        }
    }));
    OSGiResult<ServiceRegistration<Service>> result = program.run(bundleContext);
    assertEquals(0, bundleContext.getServiceReferences(Service.class, "(test.configuration=*)").size());
    CountDownLatch addedLatch = new CountDownLatch(3);
    ServiceRegistration<?> addedServiceRegistration = bundleContext.registerService(ManagedServiceFactory.class, new ManagedServiceFactory() {

        @Override
        public String getName() {
            return "";
        }

        @Override
        public void updated(String s, Dictionary<String, ?> dictionary) throws ConfigurationException {
            addedLatch.countDown();
        }

        @Override
        public void deleted(String s) {
        }
    }, new Hashtable<String, Object>() {

        {
            put("service.pid", "test.configuration");
        }
    });
    CountDownLatch deletedLatch = new CountDownLatch(3);
    ServiceRegistration<?> deletedServiceRegistration = bundleContext.registerService(ManagedServiceFactory.class, new ManagedServiceFactory() {

        @Override
        public String getName() {
            return "";
        }

        @Override
        public void updated(String s, Dictionary<String, ?> dictionary) throws ConfigurationException {
        }

        @Override
        public void deleted(String s) {
            deletedLatch.countDown();
        }
    }, new Hashtable<String, Object>() {

        {
            put("service.pid", "test.configuration");
        }
    });
    Configuration configuration = configurationAdmin.createFactoryConfiguration("test.configuration");
    configuration.update(new Hashtable<String, Object>() {

        {
            put("key", "service one");
        }
    });
    Configuration configuration2 = configurationAdmin.createFactoryConfiguration("test.configuration");
    configuration2.update(new Hashtable<String, Object>() {

        {
            put("key", "service two");
        }
    });
    Configuration configuration3 = configurationAdmin.createFactoryConfiguration("test.configuration");
    configuration3.update(new Hashtable<String, Object>() {

        {
            put("key", "service three");
        }
    });
    assertTrue(addedLatch.await(10, TimeUnit.SECONDS));
    assertEquals(1, bundleContext.getServiceReferences(Service.class, "(key=service one)").size());
    assertEquals(1, bundleContext.getServiceReferences(Service.class, "(key=service two)").size());
    assertEquals(1, bundleContext.getServiceReferences(Service.class, "(key=service three)").size());
    configuration3.delete();
    configuration2.delete();
    configuration.delete();
    assertTrue(deletedLatch.await(10, TimeUnit.SECONDS));
    assertEquals(0, bundleContext.getServiceReferences(Service.class, "(test.configuration=*)").size());
    addedServiceRegistration.unregister();
    deletedServiceRegistration.unregister();
    result.close();
    bundleContext.ungetService(serviceReference);
}
Also used : OSGi.configurations(org.apache.aries.osgi.functional.OSGi.configurations) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) OSGi.onClose(org.apache.aries.osgi.functional.OSGi.onClose) OSGi.register(org.apache.aries.osgi.functional.OSGi.register) HighestRankingRouter.highest(org.apache.aries.osgi.functional.test.HighestRankingRouter.highest) Configuration(org.osgi.service.cm.Configuration) ConfigurationException(org.osgi.service.cm.ConfigurationException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) OSGi.configuration(org.apache.aries.osgi.functional.OSGi.configuration) ServiceReference(org.osgi.framework.ServiceReference) Hashtable(java.util.Hashtable) ServiceRegistration(org.osgi.framework.ServiceRegistration) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) OSGi.serviceReferences(org.apache.aries.osgi.functional.OSGi.serviceReferences) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) BundleContext(org.osgi.framework.BundleContext) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) OSGi.just(org.apache.aries.osgi.functional.OSGi.just) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) OSGi.services(org.apache.aries.osgi.functional.OSGi.services) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) OSGi(org.apache.aries.osgi.functional.OSGi) FrameworkUtil(org.osgi.framework.FrameworkUtil) OSGiResult(org.apache.aries.osgi.functional.OSGiResult) Dictionary(java.util.Dictionary) Assert.assertEquals(org.junit.Assert.assertEquals) Configuration(org.osgi.service.cm.Configuration) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) ConfigurationException(org.osgi.service.cm.ConfigurationException) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Example 79 with ServiceReference

use of org.osgi.framework.ServiceReference in project hibernate-orm by hibernate.

the class HibernateUtil method getEntityManagerFactory.

private EntityManagerFactory getEntityManagerFactory() {
    if (emf == null) {
        Bundle thisBundle = FrameworkUtil.getBundle(HibernateUtil.class);
        // Could get this by wiring up OsgiTestBundleActivator as well.
        BundleContext context = thisBundle.getBundleContext();
        ServiceReference serviceReference = context.getServiceReference(PersistenceProvider.class.getName());
        PersistenceProvider persistenceProvider = (PersistenceProvider) context.getService(serviceReference);
        emf = persistenceProvider.createEntityManagerFactory("unmanaged-jpa", null);
    }
    return emf;
}
Also used : Bundle(org.osgi.framework.Bundle) PersistenceProvider(javax.persistence.spi.PersistenceProvider) BundleContext(org.osgi.framework.BundleContext) ServiceReference(org.osgi.framework.ServiceReference)

Example 80 with ServiceReference

use of org.osgi.framework.ServiceReference in project gocd by gocd.

the class FelixGoPluginOSGiFrameworkTest method registerServices.

private void registerServices(SomeInterface... someInterfaces) throws InvalidSyntaxException {
    ArrayList<ServiceReference<SomeInterface>> references = new ArrayList<>();
    for (int i = 0; i < someInterfaces.length; ++i) {
        ServiceReference reference = mock(ServiceReference.class);
        when(reference.getBundle()).thenReturn(bundle);
        when(bundle.getSymbolicName()).thenReturn(TEST_SYMBOLIC_NAME);
        when(bundleContext.getService(reference)).thenReturn(someInterfaces[i]);
        setExpectationForFilterBasedServiceReferenceCall(someInterfaces[i], reference);
        references.add(reference);
    }
    when(bundleContext.getServiceReferences(SomeInterface.class, null)).thenReturn(references);
}
Also used : ArrayList(java.util.ArrayList) ServiceReference(org.osgi.framework.ServiceReference)

Aggregations

ServiceReference (org.osgi.framework.ServiceReference)1690 Test (org.junit.Test)926 Properties (java.util.Properties)396 Architecture (org.apache.felix.ipojo.architecture.Architecture)263 CheckService (org.apache.felix.ipojo.runtime.core.test.services.CheckService)233 BundleContext (org.osgi.framework.BundleContext)231 InstanceDescription (org.apache.felix.ipojo.architecture.InstanceDescription)227 ComponentInstance (org.apache.felix.ipojo.ComponentInstance)215 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)183 ArrayList (java.util.ArrayList)167 Bundle (org.osgi.framework.Bundle)144 FooService (org.apache.felix.ipojo.runtime.core.services.FooService)141 Hashtable (java.util.Hashtable)124 IOException (java.io.IOException)107 CheckService (org.apache.felix.ipojo.runtime.core.services.CheckService)92 Dictionary (java.util.Dictionary)82 Configuration (org.osgi.service.cm.Configuration)74 CheckService (org.apache.felix.ipojo.handler.temporal.services.CheckService)70 FooService (org.apache.felix.ipojo.handler.temporal.services.FooService)70 CheckService (org.apache.felix.ipojo.handler.transaction.services.CheckService)65