Search in sources :

Example 1 with Startable

use of org.picocontainer.Startable in project kernel by exoplatform.

the class ConcurrentContainerMT method start.

/**
 * Starts all the provided adapters
 */
protected void start(Collection<ComponentAdapter<?>> adapters, final Map<ComponentAdapter<?>, Object> alreadyStarted, final Set<ComponentAdapter<?>> startInProgress, final AtomicReference<Exception> error, final boolean skippable) {
    if (adapters == null || adapters.isEmpty())
        return;
    boolean enableMultiThreading = Mode.hasMode(Mode.MULTI_THREADED) && adapters.size() > 1;
    List<Future<?>> submittedTasks = null;
    ThreadPoolExecutor executor = enableMultiThreading ? getExecutor() : null;
    if (enableMultiThreading && executor == null) {
        enableMultiThreading = false;
    }
    for (final ComponentAdapter<?> adapter : adapters) {
        if (error.get() != null)
            break;
        if (ExoContainer.class.isAssignableFrom(adapter.getComponentImplementation())) {
            // Only non containers are expected and it is a container
            continue;
        } else if (alreadyStarted.containsKey(adapter) || (skippable && startInProgress.contains(adapter))) {
            // The component has already been started or is in progress
            continue;
        }
        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() {
                            if (error.get() != null) {
                                return null;
                            } else if (alreadyStarted.containsKey(adapter) || (skippable && startInProgress.contains(adapter))) {
                                // The component has already been started or is in progress
                                return null;
                            }
                            ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent();
                            ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
                            try {
                                ExoContainerContext.setCurrentContainer(container);
                                Thread.currentThread().setContextClassLoader(cl);
                                if (adapter instanceof ComponentAdapterDependenciesAware) {
                                    ComponentAdapterDependenciesAware<?> cada = (ComponentAdapterDependenciesAware<?>) adapter;
                                    startDependencies(alreadyStarted, startInProgress, error, cada);
                                }
                                if (!Startable.class.isAssignableFrom(adapter.getComponentImplementation())) {
                                    alreadyStarted.put(adapter, adapter);
                                    return null;
                                } else if (alreadyStarted.containsKey(adapter)) {
                                    // The component has already been started
                                    return null;
                                }
                                synchronized (adapter) {
                                    if (alreadyStarted.containsKey(adapter)) {
                                        // The component has already been started
                                        return null;
                                    }
                                    try {
                                        Startable startable = (Startable) adapter.getComponentInstance();
                                        startable.start();
                                    } finally {
                                        alreadyStarted.put(adapter, adapter);
                                    }
                                }
                            } catch (Exception e) {
                                error.compareAndSet(null, e);
                            } finally {
                                Thread.currentThread().setContextClassLoader(oldCl);
                                ExoContainerContext.setCurrentContainer(oldContainer);
                            }
                            return null;
                        }
                    });
                }
            };
            if (submittedTasks == null) {
                submittedTasks = new ArrayList<Future<?>>();
            }
            submittedTasks.add(executor.submit(task));
        } else {
            if (adapter instanceof ComponentAdapterDependenciesAware) {
                ComponentAdapterDependenciesAware<?> cada = (ComponentAdapterDependenciesAware<?>) adapter;
                startDependencies(alreadyStarted, startInProgress, error, cada);
            }
            if (!Startable.class.isAssignableFrom(adapter.getComponentImplementation())) {
                alreadyStarted.put(adapter, adapter);
                continue;
            } else if (alreadyStarted.containsKey(adapter)) {
                // The component has already been started
                continue;
            }
            synchronized (adapter) {
                if (alreadyStarted.containsKey(adapter)) {
                    // The component has already been started
                    continue;
                }
                try {
                    Startable startable = (Startable) adapter.getComponentInstance();
                    startable.start();
                } catch (Exception e) {
                    error.compareAndSet(null, e);
                } finally {
                    alreadyStarted.put(adapter, 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();
            }
        }
    }
}
Also used : ContainerException(org.exoplatform.container.spi.ContainerException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExecutionException(java.util.concurrent.ExecutionException) Startable(org.picocontainer.Startable) Future(java.util.concurrent.Future) RunnableFuture(java.util.concurrent.RunnableFuture) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ExecutionException(java.util.concurrent.ExecutionException)

Example 2 with Startable

use of org.picocontainer.Startable in project kernel by exoplatform.

the class MX4JComponentAdapter method create.

/**
 * {@inheritDoc}
 */
public T create(CreationalContext<T> creationalContext) {
    // 
    T instance;
    Component component = null;
    ConfigurationManager manager;
    String componentKey;
    InitParams params = null;
    boolean debug = false;
    CreationalContextComponentAdapter<T> ctx = (CreationalContextComponentAdapter<T>) creationalContext;
    try {
        // Avoid to create duplicate instances if it is called at the same time by several threads
        if (instance_ != null)
            return instance_;
        else if (ctx.get() != null)
            return ctx.get();
        // Get the component
        Object key = getComponentKey();
        if (key instanceof String)
            componentKey = (String) key;
        else
            componentKey = ((Class<?>) key).getName();
        manager = exocontainer.getComponentInstanceOfType(ConfigurationManager.class);
        component = manager == null ? null : manager.getComponent(componentKey);
        if (component != null) {
            params = component.getInitParams();
            debug = component.getShowDeployInfo();
        }
        instance = createInstance(ctx, component, manager, componentKey, params, debug);
        if (instance instanceof Startable && exocontainer.canBeStopped()) {
            // Start the component if the container is already started
            ((Startable) instance).start();
        }
    } catch (Exception ex) {
        String msg = "Cannot instantiate component " + getComponentImplementation();
        if (component != null) {
            msg = "Cannot instantiate component key=" + component.getKey() + " type=" + component.getType() + " found at " + component.getDocumentURL();
        }
        throw new RuntimeException(msg, ex);
    }
    return instance;
}
Also used : InitParams(org.exoplatform.container.xml.InitParams) PrivilegedActionException(java.security.PrivilegedActionException) DefinitionException(org.exoplatform.container.context.DefinitionException) Startable(org.picocontainer.Startable) Component(org.exoplatform.container.xml.Component) ConfigurationManager(org.exoplatform.container.configuration.ConfigurationManager) CreationalContextComponentAdapter(org.exoplatform.container.ConcurrentContainer.CreationalContextComponentAdapter)

Example 3 with Startable

use of org.picocontainer.Startable in project kernel by exoplatform.

the class MX4JComponentAdapterMT method create.

/**
 * {@inheritDoc}
 */
public T create(CreationalContext<T> creationalContext) {
    CreationalContextComponentAdapter<T> ctx = (CreationalContextComponentAdapter<T>) creationalContext;
    // Avoid to create duplicate instances if it is called at the same time by several threads
    if (instance_ != null)
        return instance_;
    else if (ctx.get() != null)
        return ctx.get();
    ComponentTaskContext taskCtx = container.getComponentTaskContext();
    boolean isRoot = taskCtx.isRoot();
    if (!isRoot) {
        container.setComponentTaskContext(taskCtx = taskCtx.setLastTaskType(ComponentTaskType.CREATE));
    }
    try {
        ComponentTask<T> task = createTask.get();
        T result = task.call(ctx);
        if (instance_ != null) {
            // to component plugins
            return instance_;
        } else if (ctx.get() != null)
            return ctx.get();
        ctx.push(result);
    } catch (CyclicDependencyException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException("Cannot create component " + getComponentImplementation(), e);
    }
    if (isRoot) {
        container.setComponentTaskContext(taskCtx = taskCtx.resetDependencies(getComponentKey(), ComponentTaskType.INIT));
    } else {
        container.setComponentTaskContext(taskCtx = taskCtx.setLastTaskType(ComponentTaskType.INIT));
    }
    Collection<ComponentTask<Void>> tasks = initTasks.get();
    ComponentTask<Void> task = null;
    try {
        if (tasks != null && !tasks.isEmpty()) {
            container.loadDependencies(getComponentKey(), taskCtx, getInitDependencies(), ComponentTaskType.INIT);
            for (Iterator<ComponentTask<Void>> it = tasks.iterator(); it.hasNext(); ) {
                task = it.next();
                task.call(ctx);
                task = null;
            }
        }
        if (instance_ != null) {
            return instance_;
        } else if (instance_ == null && isSingleton) {
            // In case of cyclic dependency the component could be already initialized
            // so we need to recheck the state
            instance_ = ctx.get();
        }
    } catch (CyclicDependencyException e) {
        throw e;
    } catch (Exception e) {
        if (task != null) {
            throw new RuntimeException("Cannot " + task.getName() + " for the component " + getComponentImplementation(), e);
        }
        throw new RuntimeException("Cannot initialize component " + getComponentImplementation(), e);
    }
    if (ctx.get() instanceof Startable && exocontainer.canBeStopped()) {
        try {
            // Start the component if the container is already started
            ((Startable) ctx.get()).start();
        } catch (Exception e) {
            throw new RuntimeException("Cannot auto-start component " + getComponentImplementation(), e);
        }
    }
    return ctx.get();
}
Also used : ComponentTaskContext(org.exoplatform.container.ComponentTaskContext) CyclicDependencyException(org.exoplatform.container.CyclicDependencyException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Startable(org.picocontainer.Startable) ConcurrentContainerMT(org.exoplatform.container.ConcurrentContainerMT) ComponentTask(org.exoplatform.container.ComponentTask) CreationalContextComponentAdapter(org.exoplatform.container.ConcurrentContainer.CreationalContextComponentAdapter) CyclicDependencyException(org.exoplatform.container.CyclicDependencyException)

Aggregations

Startable (org.picocontainer.Startable)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 CreationalContextComponentAdapter (org.exoplatform.container.ConcurrentContainer.CreationalContextComponentAdapter)2 PrivilegedActionException (java.security.PrivilegedActionException)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 ComponentTask (org.exoplatform.container.ComponentTask)1 ComponentTaskContext (org.exoplatform.container.ComponentTaskContext)1 ConcurrentContainerMT (org.exoplatform.container.ConcurrentContainerMT)1 CyclicDependencyException (org.exoplatform.container.CyclicDependencyException)1 ConfigurationManager (org.exoplatform.container.configuration.ConfigurationManager)1 DefinitionException (org.exoplatform.container.context.DefinitionException)1 ContainerException (org.exoplatform.container.spi.ContainerException)1 Component (org.exoplatform.container.xml.Component)1 InitParams (org.exoplatform.container.xml.InitParams)1