Search in sources :

Example 1 with ProxyManager

use of org.apache.aries.proxy.ProxyManager in project aries by apache.

the class ServiceRegistryContextTest method registerProxyManager.

private void registerProxyManager() {
    ProxyManager mgr = Skeleton.newMock(ProxyManager.class);
    //   public Object createDelegatingProxy(Bundle clientBundle, Collection<Class<?>> classes, Callable<Object> dispatcher, Object template) throws UnableToProxyException;
    Skeleton.getSkeleton(mgr).registerMethodCallHandler(new MethodCall(ProxyManager.class, "createDelegatingProxy", Bundle.class, Collection.class, Callable.class, Object.class), new MethodCallHandler() {

        public Object handle(MethodCall methodCall, Skeleton skeleton) throws Exception {
            @SuppressWarnings("unchecked") Collection<Class<?>> interfaceClasses = (Collection<Class<?>>) methodCall.getArguments()[1];
            Class<?>[] classes = new Class<?>[interfaceClasses.size()];
            Iterator<Class<?>> it = interfaceClasses.iterator();
            for (int i = 0; it.hasNext(); i++) {
                classes[i] = it.next();
            }
            @SuppressWarnings("unchecked") final Callable<Object> target = (Callable<Object>) methodCall.getArguments()[2];
            return Proxy.newProxyInstance(this.getClass().getClassLoader(), classes, new InvocationHandler() {

                public Object invoke(Object mock, Method method, Object[] arguments) throws Throwable {
                    return method.invoke(target.call(), arguments);
                }
            });
        }
    });
    bc.registerService(ProxyManager.class.getName(), mgr, null);
}
Also used : MethodCallHandler(org.apache.aries.unittest.mocks.MethodCallHandler) Bundle(org.osgi.framework.Bundle) ProxyManager(org.apache.aries.proxy.ProxyManager) Method(java.lang.reflect.Method) MethodCall(org.apache.aries.unittest.mocks.MethodCall) InvocationHandler(java.lang.reflect.InvocationHandler) Callable(java.util.concurrent.Callable) ServiceException(org.osgi.framework.ServiceException) NamingException(javax.naming.NamingException) SQLException(java.sql.SQLException) NameNotFoundException(javax.naming.NameNotFoundException) Iterator(java.util.Iterator) Collection(java.util.Collection) Skeleton(org.apache.aries.unittest.mocks.Skeleton)

Example 2 with ProxyManager

use of org.apache.aries.proxy.ProxyManager in project aries by apache.

the class BlueprintExtender method createContainer.

private boolean createContainer(Bundle bundle, List<URL> paths, Collection<URI> namespaces) {
    try {
        if (paths == null || paths.isEmpty()) {
            // This bundle is not a blueprint bundle, so ignore it
            return false;
        }
        ProxyManager pm = proxyManager.getService();
        if (pm == null) {
            // The pm isn't available.  It may be because it is being untracked
            return false;
        }
        BundleContext bundleContext = bundle.getBundleContext();
        if (bundleContext == null) {
            // The bundle has been stopped in the mean time
            return false;
        }
        BlueprintContainerImpl blueprintContainer = new BlueprintContainerImpl(bundle, bundleContext, context.getBundle(), eventDispatcher, handlers, getExecutorService(bundle), executors, paths, pm, namespaces);
        synchronized (containers) {
            if (containers.putIfAbsent(bundle, blueprintContainer) != null) {
                return false;
            }
        }
        String val = context.getProperty("org.apache.aries.blueprint.synchronous");
        if (Boolean.parseBoolean(val)) {
            LOGGER.debug("Starting creation of blueprint bundle {}/{} synchronously", bundle.getSymbolicName(), bundle.getVersion());
            blueprintContainer.run();
        } else {
            LOGGER.debug("Scheduling creation of blueprint bundle {}/{} asynchronously", bundle.getSymbolicName(), bundle.getVersion());
            blueprintContainer.schedule();
        }
        return true;
    } catch (Throwable t) {
        LOGGER.warn("Error while creating blueprint container for bundle {}/{}", bundle.getSymbolicName(), bundle.getVersion(), t);
        return false;
    }
}
Also used : ProxyManager(org.apache.aries.proxy.ProxyManager) BundleContext(org.osgi.framework.BundleContext)

Example 3 with ProxyManager

use of org.apache.aries.proxy.ProxyManager in project aries by apache.

the class BlueprintExtender method start.

public void start(BundleContext ctx) {
    LOGGER.debug("Starting blueprint extender...");
    this.context = ctx;
    boolean useSystemContext = Boolean.parseBoolean(ctx.getProperty("org.apache.aries.blueprint.use.system.context"));
    BundleContext trackingContext = useSystemContext ? ctx.getBundle(Constants.SYSTEM_BUNDLE_LOCATION).getBundleContext() : ctx;
    handlers = new NamespaceHandlerRegistryImpl(trackingContext);
    executors = new ScheduledExecutorServiceWrapper(ctx, "Blueprint Extender", new ScheduledExecutorServiceFactory() {

        public ScheduledExecutorService create(String name) {
            return Executors.newScheduledThreadPool(3, new BlueprintThreadFactory(name));
        }
    });
    eventDispatcher = new BlueprintEventDispatcher(ctx, executors);
    // Ideally we'd want to only track STARTING and ACTIVE bundle, but this is not supported
    // when using equinox composites.  This would ensure that no STOPPING event is lost while
    // tracking the initial bundles. To work around this issue, we need to register
    // a synchronous bundle listener that will ensure the stopping event will be correctly
    // handled.
    context.addBundleListener(this);
    int mask = Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE;
    bt = useSystemContext ? new BundleTracker(trackingContext, mask, this) : new RecursiveBundleTracker(ctx, mask, this);
    proxyManager = new SingleServiceTracker<ProxyManager>(ctx, ProxyManager.class, new SingleServiceListener() {

        public void serviceFound() {
            LOGGER.debug("Found ProxyManager service, starting to process blueprint bundles");
            if (bt instanceof BundleTracker) {
                ((BundleTracker) bt).open();
            } else if (bt instanceof RecursiveBundleTracker) {
                ((RecursiveBundleTracker) bt).open();
            }
        }

        public void serviceLost() {
            while (!containers.isEmpty()) {
                for (Bundle bundle : getBundlesToDestroy()) {
                    destroyContainer(bundle);
                }
            }
            if (bt instanceof BundleTracker) {
                ((BundleTracker) bt).close();
            } else if (bt instanceof RecursiveBundleTracker) {
                ((RecursiveBundleTracker) bt).close();
            }
        }

        public void serviceReplaced() {
        }
    });
    proxyManager.open();
    // Determine if the ParserService should ignore unknown namespace handlers
    boolean ignoreUnknownNamespaceHandlers = Boolean.parseBoolean(ctx.getProperty("org.apache.aries.blueprint.parser.service.ignore.unknown.namespace.handlers"));
    // Create and publish a ParserService
    parserServiceReg = ctx.registerService(ParserService.class.getName(), new ParserServiceImpl(handlers, ignoreUnknownNamespaceHandlers), new Hashtable<String, Object>());
    // Create and publish a BlueprintContainerService
    blueprintServiceReg = ctx.registerService(BlueprintExtenderService.class.getName(), new BlueprintContainerServiceImpl(), new Hashtable<String, Object>());
    try {
        ctx.getBundle().loadClass(QUIESCE_PARTICIPANT_CLASS);
        //Class was loaded, register
        quiesceParticipantReg = ctx.registerService(QUIESCE_PARTICIPANT_CLASS, new BlueprintQuiesceParticipant(ctx, this), new Hashtable<String, Object>());
    } catch (ClassNotFoundException e) {
        LOGGER.info("No quiesce support is available, so blueprint components will not participate in quiesce operations");
    }
    LOGGER.debug("Blueprint extender started");
}
Also used : SingleServiceListener(org.apache.aries.util.tracker.SingleServiceTracker.SingleServiceListener) ScheduledExecutorServiceWrapper(org.apache.aries.blueprint.utils.threading.ScheduledExecutorServiceWrapper) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) ProxyManager(org.apache.aries.proxy.ProxyManager) BundleTracker(org.osgi.util.tracker.BundleTracker) RecursiveBundleTracker(org.apache.aries.util.tracker.RecursiveBundleTracker) ScheduledExecutorServiceFactory(org.apache.aries.blueprint.utils.threading.ScheduledExecutorServiceWrapper.ScheduledExecutorServiceFactory) RecursiveBundleTracker(org.apache.aries.util.tracker.RecursiveBundleTracker) BundleContext(org.osgi.framework.BundleContext) NamespaceHandlerRegistryImpl(org.apache.aries.blueprint.namespace.NamespaceHandlerRegistryImpl)

Example 4 with ProxyManager

use of org.apache.aries.proxy.ProxyManager in project aries by apache.

the class ReferencesTest method testWiring.

public void testWiring() throws Exception {
    ComponentDefinitionRegistryImpl registry = parse("/test-references.xml");
    ProxyManager proxyManager = new AbstractProxyManager() {

        @Override
        protected Object createNewProxy(Bundle bundle, Collection<Class<?>> classes, Callable<Object> objectCallable, InvocationListener invocationListener) throws UnableToProxyException {
            return new Object();
        }

        @Override
        protected InvocationHandler getInvocationHandler(Object o) {
            return null;
        }

        @Override
        protected boolean isProxyClass(Class<?> aClass) {
            return false;
        }
    };
    Repository repository = new TestBlueprintContainer(registry, proxyManager).getRepository();
    repository.create("refItf");
    try {
        repository.create("refClsErr");
        fail("Should have failed");
    } catch (ComponentDefinitionException e) {
    }
    repository.create("refClsOk");
}
Also used : Repository(org.apache.aries.blueprint.di.Repository) AbstractProxyManager(org.apache.aries.proxy.impl.AbstractProxyManager) ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException) Bundle(org.osgi.framework.Bundle) InvocationListener(org.apache.aries.proxy.InvocationListener) AbstractProxyManager(org.apache.aries.proxy.impl.AbstractProxyManager) ProxyManager(org.apache.aries.proxy.ProxyManager) Collection(java.util.Collection) ComponentDefinitionRegistryImpl(org.apache.aries.blueprint.parser.ComponentDefinitionRegistryImpl) Callable(java.util.concurrent.Callable)

Example 5 with ProxyManager

use of org.apache.aries.proxy.ProxyManager 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)

Aggregations

ProxyManager (org.apache.aries.proxy.ProxyManager)10 Bundle (org.osgi.framework.Bundle)8 Hashtable (java.util.Hashtable)6 BundleContext (org.osgi.framework.BundleContext)6 Dictionary (java.util.Dictionary)4 LinkedHashMap (java.util.LinkedHashMap)4 AsmProxyManager (org.apache.aries.proxy.impl.AsmProxyManager)4 ServiceRegistrationHolder (org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder)4 IAnswer (org.easymock.IAnswer)4 ServiceReference (org.osgi.framework.ServiceReference)4 ServiceRegistration (org.osgi.framework.ServiceRegistration)4 BundleWiring (org.osgi.framework.wiring.BundleWiring)4 HashMap (java.util.HashMap)3 CreateProxyRunnable (org.apache.karaf.service.guard.impl.GuardProxyCatalog.CreateProxyRunnable)3 ServiceFactory (org.osgi.framework.ServiceFactory)3 Collection (java.util.Collection)2 Callable (java.util.concurrent.Callable)2 Test (org.junit.Test)2 InvocationHandler (java.lang.reflect.InvocationHandler)1 Method (java.lang.reflect.Method)1