Search in sources :

Example 1 with ServiceFactory

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

the class ServiceRegistryContextTest method registerService.

/**
   * Register a service in our map.
   * 
   * @param service2 The service to register.
   */
private void registerService(Runnable service2) {
    ServiceFactory factory = Skeleton.newMock(ServiceFactory.class);
    Skeleton skel = Skeleton.getSkeleton(factory);
    skel.setReturnValue(new MethodCall(ServiceFactory.class, "getService", Bundle.class, ServiceRegistration.class), service2);
    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put("rubbish", "smelly");
    reg = bc.registerService(new String[] { "java.lang.Runnable" }, factory, props);
}
Also used : ServiceFactory(org.osgi.framework.ServiceFactory) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) Skeleton(org.apache.aries.unittest.mocks.Skeleton) MethodCall(org.apache.aries.unittest.mocks.MethodCall) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 2 with ServiceFactory

use of org.osgi.framework.ServiceFactory in project karaf by apache.

the class GuardProxyCatalogTest method testCreateProxy.

@SuppressWarnings({ "unchecked", "rawtypes" })
public Dictionary<String, Object> testCreateProxy(BundleContext bc, Class intf, final Class proxyRegClass, Object testService) throws Exception {
    // Create the object that is actually being tested here
    GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
    // The service being proxied has these properties
    long serviceID = 456L;
    final Hashtable<String, Object> serviceProps = new Hashtable<>();
    serviceProps.put(Constants.OBJECTCLASS, new String[] { intf.getName() });
    serviceProps.put(Constants.SERVICE_ID, serviceID);
    serviceProps.put(".foo", 123L);
    final Map<ServiceReference<?>, Object> serviceMap = new HashMap<>();
    // The mock bundle context for the bundle providing the service is set up here
    BundleContext providerBC = EasyMock.createMock(BundleContext.class);
    // These are the expected service properties of the proxy registration. Note the proxy marker...
    final Hashtable<String, Object> expectedProxyProps = new Hashtable<>(serviceProps);
    expectedProxyProps.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE);
    // This will check that the right proxy is being registered.
    EasyMock.expect(providerBC.registerService(EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> {
        if (!runningUnderCoverage) {
            assertArrayEquals(new String[] { proxyRegClass.getName() }, (String[]) EasyMock.getCurrentArguments()[0]);
            Object svc = EasyMock.getCurrentArguments()[1];
            assertTrue(svc instanceof ServiceFactory);
        }
        Dictionary<String, Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
        for (String key : expectedProxyProps.keySet()) {
            assertEquals(expectedProxyProps.get(key), props.get(key));
        }
        ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
        ServiceReference sr = mockServiceReference(props);
        EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
        reg.unregister();
        EasyMock.expectLastCall().once();
        EasyMock.replay(reg);
        serviceMap.put(sr, EasyMock.getCurrentArguments()[1]);
        return reg;
    }).once();
    EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(() -> serviceMap.get(EasyMock.getCurrentArguments()[0])).anyTimes();
    EasyMock.replay(providerBC);
    // In some cases the proxy-creating code is looking for a classloader (e.g. when run through
    // a coverage tool such as EclEmma). This will satisfy that.
    BundleWiring bw = EasyMock.createMock(BundleWiring.class);
    EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader()).anyTimes();
    EasyMock.replay(bw);
    // The mock bundle that provides the original service (and also the proxy is registered with this)
    Bundle providerBundle = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(providerBundle.getBundleContext()).andReturn(providerBC).anyTimes();
    EasyMock.expect(providerBundle.adapt(BundleWiring.class)).andReturn(bw).anyTimes();
    EasyMock.replay(providerBundle);
    ServiceReference sr = mockServiceReference(providerBundle, serviceProps);
    assertEquals("Precondition", 0, gpc.proxyMap.size());
    assertEquals("Precondition", 0, gpc.createProxyQueue.size());
    // Create the proxy for the service
    gpc.proxyIfNotAlreadyProxied(sr);
    assertEquals(1, gpc.proxyMap.size());
    // The actual proxy creation is done asynchronously.
    GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID);
    assertNull("The registration shouldn't have happened yet", holder.registration);
    assertEquals(1, gpc.createProxyQueue.size());
    // Mimic the thread that works the queue to create the proxy
    GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take();
    ProxyManager pm = getProxyManager();
    runnable.run(pm);
    // The runnable should have put the actual registration in the holder
    ServiceReference<?> proxySR = holder.registration.getReference();
    for (String key : expectedProxyProps.keySet()) {
        assertEquals(expectedProxyProps.get(key), proxySR.getProperty(key));
    }
    // Check that the proxy registration was done on the original provider bundle's context
    EasyMock.verify(providerBC);
    // Test that the actual proxy invokes the original service...
    Object proxyService = serviceMap.get(proxySR);
    assertNotSame("The proxy should not be the same object as the original service", testService, proxyService);
    // Attempt to proxy the service again, make sure that no re-proxying happens
    assertEquals("Precondition", 1, gpc.proxyMap.size());
    assertEquals("Precondition", 0, gpc.createProxyQueue.size());
    gpc.proxyIfNotAlreadyProxied(sr);
    assertEquals("No additional proxy should have been created", 1, gpc.proxyMap.size());
    assertEquals("No additional work on the queue is expected", 0, gpc.createProxyQueue.size());
    Dictionary<String, Object> proxyProps = getServiceReferenceProperties(proxySR);
    gpc.close();
    // checks that the unregister call was made
    EasyMock.verify(holder.registration);
    return proxyProps;
}
Also used : Dictionary(java.util.Dictionary) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ServiceFactory(org.osgi.framework.ServiceFactory) CreateProxyRunnable(org.apache.karaf.service.guard.impl.GuardProxyCatalog.CreateProxyRunnable) Hashtable(java.util.Hashtable) Bundle(org.osgi.framework.Bundle) ServiceRegistrationHolder(org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder) BundleWiring(org.osgi.framework.wiring.BundleWiring) ProxyManager(org.apache.aries.proxy.ProxyManager) AsmProxyManager(org.apache.aries.proxy.impl.AsmProxyManager) ServiceReference(org.osgi.framework.ServiceReference) IAnswer(org.easymock.IAnswer) BundleContext(org.osgi.framework.BundleContext) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 3 with ServiceFactory

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

the class Activator method start.

public void start(BundleContext bundleContext) {
    // install handler for uncaught exceptions
    oldHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
    // install thread handler shell command
    register(bundleContext, new String[] { "org.apache.felix.shell.Command" }, new ServiceFactory() {

        public void ungetService(final Bundle bundle, final ServiceRegistration reg, final Object consoleObject) {
        // nothing to do
        }

        public Object getService(final Bundle bundle, final ServiceRegistration reg) {
            return new ThreadDumpCommand();
        }
    }, null);
    // install Web Console configuration printer
    final Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("felix.webconsole.label", "slingthreads");
    props.put("felix.webconsole.title", "Threads");
    props.put("felix.webconsole.configprinter.modes", "always");
    final ThreadDumperPanel tdp = new ThreadDumperPanel();
    register(bundleContext, new String[] { tdp.getClass().getName() }, tdp, props);
}
Also used : ServiceFactory(org.osgi.framework.ServiceFactory) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 4 with ServiceFactory

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

the class AbstractSlingRepositoryManager method registerService.

/**
     * Registers this component as an OSGi service with the types provided by
     * the {@link #getServiceRegistrationInterfaces()} method and properties
     * provided by the {@link #getServiceRegistrationProperties()} method.
     * <p>
     * The repository is actually registered as an OSGi {@code ServiceFactory}
     * where the {@link #create(Bundle)} method is called to create an actual
     * {@link AbstractSlingRepository2} repository instance for a calling
     * (using) bundle. When the bundle is done using the repository instance,
     * the {@link #destroy(AbstractSlingRepository2)} method is called to clean
     * up.
     *
     * @return The OSGi <code>ServiceRegistration</code> object representing the
     *         registered service.
     * @see #start(BundleContext, String, boolean)
     * @see #getServiceRegistrationInterfaces()
     * @see #getServiceRegistrationProperties()
     * @see #create(Bundle)
     * @see #destroy(AbstractSlingRepository2)
     */
protected final ServiceRegistration registerService() {
    final Dictionary<String, Object> props = getServiceRegistrationProperties();
    final String[] interfaces = getServiceRegistrationInterfaces();
    return bundleContext.registerService(interfaces, new ServiceFactory() {

        @Override
        public Object getService(Bundle bundle, ServiceRegistration registration) {
            return AbstractSlingRepositoryManager.this.create(bundle);
        }

        @Override
        public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) {
            AbstractSlingRepositoryManager.this.destroy((AbstractSlingRepository2) service);
        }
    }, props);
}
Also used : ServiceFactory(org.osgi.framework.ServiceFactory) Bundle(org.osgi.framework.Bundle) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 5 with ServiceFactory

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

the class MDCInsertingFilter method activate.

@Activate
private void activate(BundleContext context, Map<String, Object> config) {
    Properties p = new Properties();
    p.setProperty("filter.scope", "REQUEST");
    //The MDC Filter might be running in a non Sling container. Hence to avoid
    //direct dependency on Sling we use a ServiceFactory
    filterReg = context.registerService(Filter.class.getName(), new ServiceFactory() {

        private Object instance;

        public synchronized Object getService(Bundle bundle, ServiceRegistration serviceRegistration) {
            if (instance == null) {
                instance = new SlingMDCFilter();
            }
            return instance;
        }

        public void ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object o) {
        }
    }, p);
    modified(config);
}
Also used : ServiceFactory(org.osgi.framework.ServiceFactory) Bundle(org.osgi.framework.Bundle) Properties(java.util.Properties) ServiceRegistration(org.osgi.framework.ServiceRegistration) Activate(org.apache.felix.scr.annotations.Activate)

Aggregations

ServiceFactory (org.osgi.framework.ServiceFactory)12 Bundle (org.osgi.framework.Bundle)10 ServiceRegistration (org.osgi.framework.ServiceRegistration)9 Dictionary (java.util.Dictionary)5 Hashtable (java.util.Hashtable)5 IAnswer (org.easymock.IAnswer)4 BundleContext (org.osgi.framework.BundleContext)4 ServiceReference (org.osgi.framework.ServiceReference)4 LinkedHashMap (java.util.LinkedHashMap)3 ProxyManager (org.apache.aries.proxy.ProxyManager)3 AsmProxyManager (org.apache.aries.proxy.impl.AsmProxyManager)3 CreateProxyRunnable (org.apache.karaf.service.guard.impl.GuardProxyCatalog.CreateProxyRunnable)3 ServiceRegistrationHolder (org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder)3 BundleWiring (org.osgi.framework.wiring.BundleWiring)3 HashMap (java.util.HashMap)2 Properties (java.util.Properties)2 Test (org.junit.Test)2 Annotation (java.lang.annotation.Annotation)1 Collection (java.util.Collection)1 Convertible (org.apache.aries.blueprint.container.AggregateConverter.Convertible)1