Search in sources :

Example 1 with ComponentAdapter

use of org.exoplatform.container.spi.ComponentAdapter in project kernel by exoplatform.

the class TestGuiceContainer method testIntegration.

public void testIntegration() {
    URL rootURL = getClass().getResource("test-exo-container.xml");
    URL portalURL = getClass().getResource("test-exo-container2.xml");
    assertNotNull(rootURL);
    assertNotNull(portalURL);
    // 
    new ContainerBuilder().withRoot(rootURL).withPortal(portalURL).build();
    RootContainer root = RootContainer.getInstance();
    testIntegration(root);
    ComponentAdapter<H> adapterH = root.getComponentAdapterOfType(H.class);
    assertNull(adapterH);
    PortalContainer portal = PortalContainer.getInstance();
    adapterH = portal.getComponentAdapterOfType(H.class);
    assertNotNull(adapterH);
    H h = root.getComponentInstanceOfType(H.class);
    assertNull(h);
    h = portal.getComponentInstanceOfType(H.class);
    assertNotNull(h);
    assertSame(h, portal.getComponentInstanceOfType(H.class));
    assertSame(h, adapterH.getComponentInstance());
    List<ComponentAdapter<H>> adapters = root.getComponentAdaptersOfType(H.class);
    assertTrue(adapters == null || adapters.isEmpty());
    adapters = portal.getComponentAdaptersOfType(H.class);
    assertNotNull(adapters);
    assertEquals(1, adapters.size());
    assertSame(h, adapters.get(0).getComponentInstance());
    List<H> allH = root.getComponentInstancesOfType(H.class);
    assertTrue(allH == null || allH.isEmpty());
    allH = portal.getComponentInstancesOfType(H.class);
    assertNotNull(allH);
    assertEquals(1, allH.size());
    assertSame(h, allH.get(0));
}
Also used : ContainerBuilder(org.exoplatform.container.ContainerBuilder) RootContainer(org.exoplatform.container.RootContainer) URL(java.net.URL) ComponentAdapter(org.exoplatform.container.spi.ComponentAdapter) PortalContainer(org.exoplatform.container.PortalContainer)

Example 2 with ComponentAdapter

use of org.exoplatform.container.spi.ComponentAdapter in project kernel by exoplatform.

the class ConcurrentContainerMT method getComponentInstancesOfType.

/**
 * A multi-threaded implementation of the start method
 */
public <T> List<T> getComponentInstancesOfType(final Class<T> componentType) throws ContainerException {
    if (componentType == null) {
        return Collections.emptyList();
    }
    List<ComponentAdapter<T>> adapters = getComponentAdaptersOfType(componentType);
    if (adapters == null || adapters.isEmpty())
        return Collections.emptyList();
    boolean enableMultiThreading = Mode.hasMode(Mode.MULTI_THREADED) && adapters.size() > 1;
    List<Future<?>> submittedTasks = null;
    final Map<ComponentAdapter<T>, Object> adapterToInstanceMap = enableMultiThreading ? new ConcurrentHashMap<ComponentAdapter<T>, Object>() : new HashMap<ComponentAdapter<T>, Object>();
    ThreadPoolExecutor executor = enableMultiThreading ? getExecutor() : null;
    if (enableMultiThreading && executor == null) {
        enableMultiThreading = false;
    }
    for (final ComponentAdapter<T> adapter : adapters) {
        if (enableMultiThreading && LockManager.getInstance().getTotalUncompletedTasks() < executor.getCorePoolSize() && !(adapter instanceof InstanceComponentAdapter)) {
            final ExoContainer container = ExoContainerContext.getCurrentContainerIfPresent();
            final ClassLoader cl = Thread.currentThread().getContextClassLoader();
            Runnable task = new Runnable() {

                public void run() {
                    SecurityHelper.doPrivilegedAction(new PrivilegedAction<Void>() {

                        public Void run() {
                            ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent();
                            ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
                            try {
                                ExoContainerContext.setCurrentContainer(container);
                                Thread.currentThread().setContextClassLoader(cl);
                                Object o = getInstance(adapter, componentType, false);
                                if (o != null)
                                    adapterToInstanceMap.put(adapter, o);
                                // This is to ensure all are added. (Indirect dependencies will be added
                                // from InstantiatingComponentAdapter).
                                addOrderedComponentAdapter(adapter);
                            } finally {
                                Thread.currentThread().setContextClassLoader(oldCl);
                                ExoContainerContext.setCurrentContainer(oldContainer);
                            }
                            return null;
                        }
                    });
                }
            };
            if (submittedTasks == null) {
                submittedTasks = new ArrayList<Future<?>>();
            }
            submittedTasks.add(executor.submit(task));
        } else if (enableMultiThreading) {
            Object o = getInstance(adapter, componentType, false);
            if (o != null)
                adapterToInstanceMap.put(adapter, o);
            // This is to ensure all are added. (Indirect dependencies will be added
            // from InstantiatingComponentAdapter).
            addOrderedComponentAdapter(adapter);
        } else {
            adapterToInstanceMap.put(adapter, getInstance(adapter, componentType, false));
            // This is to ensure all are added. (Indirect dependencies will be added
            // from InstantiatingComponentAdapter).
            addOrderedComponentAdapter(adapter);
        }
    }
    if (submittedTasks != null) {
        for (int i = 0, length = submittedTasks.size(); i < length; i++) {
            Future<?> task = submittedTasks.get(i);
            try {
                task.get();
            } catch (ExecutionException e) {
                Throwable cause = e.getCause();
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                }
                throw new RuntimeException(cause);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
    List<T> result = new ArrayList<T>();
    for (Iterator<ComponentAdapter<?>> iterator = orderedComponentAdapters.iterator(); iterator.hasNext(); ) {
        Object componentAdapter = iterator.next();
        final Object componentInstance = adapterToInstanceMap.get(componentAdapter);
        if (componentInstance != null) {
            // may be null in the case of the "implicit" adapter
            // representing "this".
            result.add(componentType.cast(componentInstance));
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) ManageableComponentAdapterFactoryMT(org.exoplatform.container.management.ManageableComponentAdapterFactoryMT) ExecutionException(java.util.concurrent.ExecutionException) ComponentAdapter(org.exoplatform.container.spi.ComponentAdapter) Future(java.util.concurrent.Future) RunnableFuture(java.util.concurrent.RunnableFuture) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 3 with ComponentAdapter

use of org.exoplatform.container.spi.ComponentAdapter in project kernel by exoplatform.

the class GuiceContainer method start.

/**
 * {@inheritDoc}
 */
@Override
public void start() {
    ConfigurationManager cm = super.getComponentInstanceOfType(ConfigurationManager.class, false);
    // We check if the component has been defined in the configuration of the current container
    // The goal is to enable the GuicegContainer only if it is needed
    Component component = cm.getComponent(ModuleProvider.class);
    if (component == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No ModuleProvider has been defined, thus the GuiceContainer will be disabled." + " To enable the Guice Integration please define a ModuleProvider");
        }
    } else {
        ModuleProvider provider = super.getComponentInstanceOfType(ModuleProvider.class, false);
        injector = Guice.createInjector(provider.getModule(), new AbstractModule() {

            @SuppressWarnings({ "unchecked", "rawtypes" })
            @Override
            protected void configure() {
                Collection<ComponentAdapter<?>> adapters = delegate.getComponentAdapters();
                Binder binder = binder();
                for (ComponentAdapter<?> adapter : adapters) {
                    Object key = adapter.getComponentKey();
                    Class<?> type;
                    Annotation annotation = null;
                    Class<? extends Annotation> annotationType = null;
                    if (key instanceof Class<?> && !((Class<?>) key).isAnnotation()) {
                        type = (Class<?>) key;
                    } else {
                        if (key instanceof String) {
                            annotation = Names.named((String) key);
                        } else if (key instanceof Class<?>) {
                            annotationType = (Class<? extends Annotation>) key;
                        }
                        type = adapter.getComponentImplementation();
                    }
                    if (annotation == null && annotationType == null) {
                        binder.bind(type).toProvider(new ComponentAdapterProvider(type, adapter));
                    } else {
                        // As we don't know the type, we will bind it for each super classes and interfaces too
                        ComponentAdapterProvider provider = new ComponentAdapterProvider(type, adapter);
                        bindAll(binder, type, provider, annotation, annotationType);
                    }
                }
            }
        });
        LOG.info("A GuiceContainer has been enabled using the ModuleProvider " + provider.getClass());
    }
    super.start();
}
Also used : Annotation(java.lang.annotation.Annotation) AbstractModule(com.google.inject.AbstractModule) Binder(com.google.inject.Binder) Component(org.exoplatform.container.xml.Component) ConfigurationManager(org.exoplatform.container.configuration.ConfigurationManager) AbstractComponentAdapter(org.exoplatform.container.AbstractComponentAdapter) ComponentAdapter(org.exoplatform.container.spi.ComponentAdapter)

Example 4 with ComponentAdapter

use of org.exoplatform.container.spi.ComponentAdapter in project kernel by exoplatform.

the class SpringContainer method start.

/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void start() {
    ConfigurationManager cm = super.getComponentInstanceOfType(ConfigurationManager.class, false);
    // We check if the component has been defined in the configuration of the current container
    // The goal is to enable the SpringContainer only if it is needed
    Component component = cm.getComponent(ApplicationContextProvider.class);
    if (component == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No ApplicationContextProvider has been defined, thus the SpringContainer will be disabled." + " To enable the Spring Integration please define an ApplicationContextProvider");
        }
    } else {
        DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
        bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
        Collection<ComponentAdapter<?>> adapters = delegate.getComponentAdapters();
        for (ComponentAdapter<?> adapter : adapters) {
            Object key = adapter.getComponentKey();
            String name = keyToBeanName(key);
            String factoryName = name + "#factory";
            RootBeanDefinition def = new RootBeanDefinition(adapter.getComponentImplementation(), AbstractBeanDefinition.AUTOWIRE_NO, false);
            def.setScope(BeanDefinition.SCOPE_PROTOTYPE);
            def.setFactoryBeanName(factoryName);
            def.setFactoryMethodName("getInstance");
            def.setLazyInit(true);
            def.setTargetType(adapter.getComponentImplementation());
            if (key instanceof String) {
                def.addQualifier(new AutowireCandidateQualifier(Named.class, key));
            } else if (key instanceof Class<?> && ((Class<?>) key).isAnnotation()) {
                def.addQualifier(new AutowireCandidateQualifier((Class<?>) key));
            } else {
                def.setPrimary(true);
            }
            bf.registerBeanDefinition(name, def);
            bf.registerSingleton(factoryName, new ComponentAdapterFactoryBean(adapter));
        }
        GenericApplicationContext parentContext = new GenericApplicationContext(bf);
        parentContext.refresh();
        ApplicationContextProvider provider = super.getComponentInstanceOfType(ApplicationContextProvider.class, false);
        ctx = provider.getApplicationContext(parentContext);
        LOG.info("A SpringContainer has been enabled using the ApplicationContextProvider " + provider.getClass());
    }
    super.start();
}
Also used : Named(javax.inject.Named) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) AutowireCandidateQualifier(org.springframework.beans.factory.support.AutowireCandidateQualifier) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) QualifierAnnotationAutowireCandidateResolver(org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver) Component(org.exoplatform.container.xml.Component) ConfigurationManager(org.exoplatform.container.configuration.ConfigurationManager) ComponentAdapter(org.exoplatform.container.spi.ComponentAdapter) AbstractComponentAdapter(org.exoplatform.container.AbstractComponentAdapter)

Example 5 with ComponentAdapter

use of org.exoplatform.container.spi.ComponentAdapter in project kernel by exoplatform.

the class SpringContainer method getComponentAdapter.

/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public <T> ComponentAdapter<T> getComponentAdapter(Object componentKey, Class<T> bindType, boolean autoRegistration) {
    ComponentAdapter<?> result = super.getComponentAdapter(componentKey, bindType, autoRegistration);
    if (ctx != null && result == null) {
        if (componentKey instanceof Class<?> && !((Class<?>) componentKey).isAnnotation()) {
            return getAdapterOfType(bindType);
        } else if (!(componentKey instanceof String) && !(componentKey instanceof Class<?>)) {
            return null;
        }
        String beanName = keyToBeanName(componentKey);
        if (ctx.containsBean(beanName) && bindType.isAssignableFrom(ctx.getType(beanName))) {
            return createComponentAdapter(bindType, beanName);
        }
        String[] names = ctx.getBeanNamesForType(bindType);
        if (names != null && names.length > 0) {
            for (int i = 0, length = names.length; i < length; i++) {
                String name = names[i];
                if (componentKey instanceof String) {
                    Named n = ctx.findAnnotationOnBean(name, Named.class);
                    if (n != null && componentKey.equals(n.value())) {
                        return createComponentAdapter(bindType, name);
                    }
                } else {
                    Annotation a = ctx.findAnnotationOnBean(name, (Class<? extends Annotation>) componentKey);
                    if (a != null) {
                        return createComponentAdapter(bindType, name);
                    }
                }
            }
        }
    }
    return (ComponentAdapter<T>) result;
}
Also used : Named(javax.inject.Named) Annotation(java.lang.annotation.Annotation) ComponentAdapter(org.exoplatform.container.spi.ComponentAdapter) AbstractComponentAdapter(org.exoplatform.container.AbstractComponentAdapter)

Aggregations

ComponentAdapter (org.exoplatform.container.spi.ComponentAdapter)8 AbstractComponentAdapter (org.exoplatform.container.AbstractComponentAdapter)3 PortalContainer (org.exoplatform.container.PortalContainer)3 Annotation (java.lang.annotation.Annotation)2 URL (java.net.URL)2 Named (javax.inject.Named)2 ContainerBuilder (org.exoplatform.container.ContainerBuilder)2 RootContainer (org.exoplatform.container.RootContainer)2 ConfigurationManager (org.exoplatform.container.configuration.ConfigurationManager)2 Component (org.exoplatform.container.xml.Component)2 AbstractModule (com.google.inject.AbstractModule)1 Binder (com.google.inject.Binder)1 ArrayList (java.util.ArrayList)1 ExecutionException (java.util.concurrent.ExecutionException)1 Future (java.util.concurrent.Future)1 RunnableFuture (java.util.concurrent.RunnableFuture)1 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)1 ManageableComponentAdapterFactoryMT (org.exoplatform.container.management.ManageableComponentAdapterFactoryMT)1 ContainerException (org.exoplatform.container.spi.ContainerException)1 QualifierAnnotationAutowireCandidateResolver (org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver)1