Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source
   * Copyright 2013, Red Hat, Inc., and individual contributors
   * by the @authors tag. See the copyright.txt in the distribution for a
   * full listing of individual contributors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
  * http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.jboss.weld.bootstrap;
 
 import java.util.List;
 import java.util.Set;
 
 
Common bootstrapping functionality that is run at application startup and detects and register beans

Author(s):
Pete Muir
Ales Justin
Marko Luksa
public class WeldStartup {
    static {
        ..version(Formats.version(WeldBootstrap.class.getPackage()));
    }
    private Collection<ContextHolder<? extends Context>> contexts;
    private List<Metadata<? extends Extension>> extensions;
    private Environment environment;
    private Deployment deployment;
    private final ServiceRegistry initialServices = new SimpleServiceRegistry();
    private String contextId;
    public WeldStartup() {
    }
    public WeldRuntime startContainer(String contextIdEnvironment environmentDeployment deployment) {
        if (deployment == null) {
            throw ..deploymentRequired();
        }
        checkApiVersion();
        ..set(contextId);
        this. = contextId;
        if (this. == null) {
            setExtensions(deployment.getExtensions());
        }
        final ServiceRegistry registry = deployment.getServices();
        setupInitialServices();
        registry.addAll(.entrySet());
        new AdditionalServiceLoader(deployment).loadAdditionalServices(registry);
        if (!registry.contains(ResourceLoader.class)) {
            registry.add(ResourceLoader.class.);
        }
        // Weld configuration - must be set after the ResourceLoader fallback
        WeldConfiguration configuration = new WeldConfiguration(registrydeployment);
        registry.add(WeldConfiguration.classconfiguration);
        if (!registry.contains(ScheduledExecutorServiceFactory.class)) {
        }
        if (!registry.contains(ProxyServices.class)) {
            registry.add(ProxyServices.classnew SimpleProxyServices());
        }
        addImplementationServices(registry);
        verifyServices(registryenvironment.getRequiredDeploymentServices());
        if (!registry.contains(TransactionServices.class)) {
            ..jtaUnavailable();
        }
        this. = deployment;
        this. = environment;
        this. = BeanManagerImpl.newRootManager(contextId"deployment"registry);
        Container.initialize(contextId, ServiceRegistries.unmodifiableServiceRegistry(deployment.getServices()));
        this. = createContexts(registry);
        this. = new BeanDeploymentArchiveMapping();
        this. = new DeploymentVisitor(environmentdeployment);
        if (deployment instanceof CDI11Deployment) {
            registry.add(BeanManagerLookupService.classnew BeanManagerLookupService((CDI11Deploymentdeployment.getBdaToBeanManagerMap()));
        } else {
        }
        // Read the deployment structure, bdaMapping will be the physical structure
        // as caused by the presence of beans.xml
        .visit();
        ..remove();
        return new WeldRuntime(contextId.getBdaToBeanManagerMap());
    }
    private void checkApiVersion() {
        if (Bean.class.getInterfaces().length == 1) {
            // this means Bean only extends Contextual - since CDI 1.1 Bean also extends BeanAttributes
            // CDI 1.0 API is detected on classpath - since that would result in obscure exception later, we
            // throw an appropriate exception right now
            throw ..cdiApiVersionMismatch();
        }
    }
    private void setupInitialServices() {
        if (.contains(TypeStore.class)) {
            return;
        }
        // instantiate initial services which we need for this phase
        TypeStore store = new TypeStore();
        SharedObjectCache cache = new SharedObjectCache();
        ReflectionCache reflectionCache = ReflectionCacheFactory.newInstance(store);
        ClassTransformer classTransformer = new ClassTransformer(storecachereflectionCache);
        .add(TypeStore.classstore);
        .add(SharedObjectCache.classcache);
        .add(ReflectionCache.classreflectionCache);
        .add(ClassTransformer.classclassTransformer);
    }
    private void addImplementationServices(ServiceRegistry services) {
        final WeldConfiguration configuration = services.get(WeldConfiguration.class);
        services.add(SlimAnnotatedTypeStore.classnew SlimAnnotatedTypeStoreImpl());
        if (services.get(ClassTransformer.class) == null) {
            throw new IllegalStateException(ClassTransformer.class.getSimpleName() + " not installed.");
        }
        services.add(MemberTransformer.classnew MemberTransformer(services.get(ClassTransformer.class)));
        services.add(MetaAnnotationStore.classnew MetaAnnotationStore(services.get(ClassTransformer.class)));
        BeanIdentifierIndex beanIdentifierIndex = null;
            beanIdentifierIndex = new BeanIdentifierIndex();
            services.add(BeanIdentifierIndex.classbeanIdentifierIndex);
        }
        services.add(ContextualStore.classnew ContextualStoreImpl(beanIdentifierIndex));
        services.add(CurrentInjectionPoint.classnew CurrentInjectionPoint());
        services.add(SLSBInvocationInjectionPoint.classnew SLSBInvocationInjectionPoint());
        services.add(CurrentEventMetadata.classnew CurrentEventMetadata());
        services.add(MissingDependenciesRegistry.classnew MissingDependenciesRegistry());
        GlobalObserverNotifierService observerNotificationService = new GlobalObserverNotifierService(services);
        services.add(GlobalObserverNotifierService.classobserverNotificationService);
        /*
         * Setup ExecutorServices
         */
        ExecutorServices executor = services.get(ExecutorServices.class);
        if (executor == null) {
            executor = ExecutorServicesFactory.create(.configuration);
            if (executor != null) {
                services.add(ExecutorServices.classexecutor);
            }
        }
        services.add(RequiredAnnotationDiscovery.classnew RequiredAnnotationDiscovery(services.get(ReflectionCache.class)));
        /*
         * Setup Validator
         */
        if (configuration.getBooleanProperty(.) && services.contains(ExecutorServices.class)) {
            services.add(Validator.classnew ConcurrentValidator(executor));
        } else {
            services.add(Validator.classnew Validator());
        }
        /*
         * Preloader for container lifecycle events
         */
        ContainerLifecycleEventPreloader preloader = null;
        int preloaderThreadPoolSize = configuration.getIntegerProperty(.);
        if (preloaderThreadPoolSize > 0 && Permissions.hasPermission(.)) {
            preloader = new ContainerLifecycleEventPreloader(preloaderThreadPoolSizeobserverNotificationService.getGlobalLenientObserverNotifier());
        }
        services.add(ContainerLifecycleEvents.classnew ContainerLifecycleEvents(preloaderservices.get(RequiredAnnotationDiscovery.class)));
        services.add(GlobalEnablementBuilder.classnew GlobalEnablementBuilder());
        if (!services.contains(HttpContextActivationFilter.class)) {
        }
        services.add(ServletContextService.classnew ServletContextService());
        services.add(ProtectionDomainCache.classnew ProtectionDomainCache());
        services.add(ProxyInstantiator.class, ProxyInstantiator.Factory.create(configuration));
    }
    // needs to be resolved once extension beans are deployed
    private void installFastProcessAnnotatedTypeResolver(ServiceRegistry services) {
        ClassFileServices classFileServices = services.get(ClassFileServices.class);
        if (classFileServices != null) {
            final GlobalObserverNotifierService observers = services.get(GlobalObserverNotifierService.class);
            try {
                final FastProcessAnnotatedTypeResolver resolver = new FastProcessAnnotatedTypeResolver(observers.getAllObserverMethods());
                services.add(FastProcessAnnotatedTypeResolver.classresolver);
            } catch (UnsupportedObserverMethodException e) {
                ..notUsingFastResolver(e.getObserver());
                return;
            }
        }
    }
    public void startInitialization() {
        if ( == null) {
            throw ..managerNotInitialized();
        }
        Set<BeanDeploymentphysicalBeanDeploymentArchives = new HashSet<BeanDeployment>(getBeanDeployments());
        ExtensionBeanDeployer extensionBeanDeployer = new ExtensionBeanDeployer();
        extensionBeanDeployer.addExtensions();
        extensionBeanDeployer.deployBeans();
        // Add the Deployment BeanManager Bean to the Deployment BeanManager
        // Re-Read the deployment structure, bdaMapping will be the physical
        // structure, and will add in BDAs for any extensions outside a
        // physical BDA
        .visit();
        BeforeBeanDiscoveryImpl.fire();
        // for each physical BDA transform its classes into AnnotatedType instances
        for (BeanDeployment beanDeployment : physicalBeanDeploymentArchives) {
            beanDeployment.createClasses();
        }
        // Re-Read the deployment structure, bdaMapping will be the physical
        // structure, extensions and any classes added using addAnnotatedType
        // outside the physical BDA
        .visit();
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            beanDeployment.createTypes();
        }
        AfterTypeDiscoveryImpl.fire();
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            beanDeployment.createEnablement();
        }
    }
    public void deployBeans() {
        for (BeanDeployment deployment : getBeanDeployments()) {
            deployment.createBeans();
        }
        // we must use separate loops, otherwise cyclic specialization would not work
        for (BeanDeployment deployment : getBeanDeployments()) {
            deployment.getBeanDeployer().processClassBeanAttributes();
            deployment.getBeanDeployer().createProducersAndObservers();
        }
        for (BeanDeployment deployment : getBeanDeployments()) {
            deployment.getBeanDeployer().processProducerAttributes();
            deployment.getBeanDeployer().createNewBeans();
        }
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            beanDeployment.deploySpecialized();
        }
        // TODO keep a list of new bdas, add them all in, and deploy beans for them, then merge into existing
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            beanDeployment.deployBeans();
        }
        // Flush caches for BeanManager.getBeans() to be usable in ABD (WELD-1729)
        flushCaches();
        AfterBeanDiscoveryImpl.fire();
        // Extensions may have registered beans / observers. We need to flush caches.
        flushCaches();
        // Re-read the deployment structure, bdaMapping will be the physical
        // structure, extensions, classes, and any beans added using addBean
        // outside the physical structure
        .visit();
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            beanDeployment.getBeanManager().getServices().get(InjectionTargetService.class).initialize();
            beanDeployment.afterBeanDiscovery();
        }
    }
    public void validateBeans() {
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            BeanManagerImpl beanManager = beanDeployment.getBeanManager();
            beanManager.getBeanResolver().clear();
            .getServices().get(Validator.class).validateDeployment(beanManagerbeanDeployment);
            beanManager.getServices().get(InjectionTargetService.class).validate();
        }
        AfterDeploymentValidationImpl.fire();
    }
    public void endInitialization() {
        final BeanIdentifierIndex index = .getServices().get(BeanIdentifierIndex.class);
        if (index != null) {
            // Build a special index of bean identifiers
            index.build(getBeansForBeanIdentifierIndex());
        }
        // TODO rebuild the manager accessibility graph if the bdas have changed
        // Register the managers so external requests can handle them
        // clear the TypeSafeResolvers, so data that is only used at startup
        // is not kept around using up memory
        flushCaches();
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            BeanManagerImpl beanManager = beanDeployment.getBeanManager();
            beanManager.getInterceptorMetadataReader().cleanAfterBoot();
            beanManager.getServices().cleanupAfterBoot();
            beanManager.cleanupAfterBoot();
            // clean up beans
            for (Bean<?> bean : beanManager.getBeans()) {
                if (bean instanceof RIBean<?>) {
                    RIBean<?> riBean = (RIBean<?>) bean;
                    riBean.cleanupAfterBoot();
                }
            }
            // clean up decorators
            for (Decorator<?> decorator : beanManager.getDecorators()) {
                if (decorator instanceof DecoratorImpl<?>) {
                    Reflections.<DecoratorImpl<?>>cast(decorator).cleanupAfterBoot();
                }
            }
            // clean up interceptors
            for (Interceptor<?> interceptor : beanManager.getInterceptors()) {
                if (interceptor instanceof InterceptorImpl<?>) {
                    Reflections.<InterceptorImpl<?>>cast(interceptor).cleanupAfterBoot();
                }
            }
        }
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            beanDeployment.getBeanDeployer().cleanup();
        }
    }
    private void flushCaches() {
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            BeanManagerImpl beanManager = beanDeployment.getBeanManager();
            beanManager.getBeanResolver().clear();
            beanManager.getAccessibleLenientObserverNotifier().clear();
            beanManager.getDecoratorResolver().clear();
            beanManager.getInterceptorResolver().clear();
            beanManager.getNameBasedResolver().clear();
        }
    }
        return .getBeanDeployments();
    }
    private Container getContainer() {
        return Container.instance();
    }
    protected Collection<ContextHolder<? extends Context>> createContexts(ServiceRegistry services) {
        List<ContextHolder<? extends Context>> contexts = new ArrayList<ContextHolder<? extends Context>>();
        BeanIdentifierIndex beanIdentifierIndex = services.get(BeanIdentifierIndex.class);
        /*
        * Register a full set of bound and unbound contexts. Although we may not use all of
        * these (e.g. if we are running in a servlet environment) they may be
        * useful for an application.
        */
        contexts.add(new ContextHolder<BoundSessionContext>(new BoundSessionContextImpl(beanIdentifierIndex), BoundSessionContext.class.));
        contexts.add(new ContextHolder<DependentContext>(new DependentContextImpl(services.get(ContextualStore.class)), DependentContext.class.));
            // Register the Http contexts if not in
            contexts.add(new ContextHolder<HttpSessionContext>(new HttpSessionContextImpl(beanIdentifierIndex), HttpSessionContext.class.));
            contexts.add(new ContextHolder<HttpConversationContext>(new LazyHttpConversationContextImpl(beanIdentifierIndex), HttpConversationContext.class.));
        }
        if (isEjbServicesRegistered()) {
            // Register the EJB Request context if EjbServices are available
        }
        /*
        * Register the contexts with the bean manager and add the beans to the
        * deployment manager so that they are easily accessible (contexts are app
        * scoped)
        */
        for (ContextHolder<? extends Contextcontext : contexts) {
            .addContext(context.getContext());
            .addBean(ContextBean.of(context));
        }
        return contexts;
    }
    protected static void verifyServices(ServiceRegistry servicesSet<Class<? extends Service>> requiredServices) {
        for (Class<? extends ServiceserviceType : requiredServices) {
            if (!services.contains(serviceType)) {
                throw ..unspecifiedRequiredService(serviceType.getName());
            }
        }
    }
        setExtensions(extensions);
        // TODO: we should fire BeforeBeanDiscovery to allow extensions to register additional scopes
        @SuppressWarnings("unchecked")
        final Set<Class<? extends Annotation>> beanDefiningAnnotations = ImmutableSet.of(
                // built-in scopes
                Dependent.classRequestScoped.classConversationScoped.classSessionScoped.classApplicationScoped.class,
                javax.interceptor.Interceptor.classjavax.decorator.Decorator.class,
                // built-in stereotype
                Model.class,
                // meta-annotations
                NormalScope.classStereotype.class);
        return new TypeDiscoveryConfigurationImpl(beanDefiningAnnotations);
    }
    public BeanManagerImpl getManager(BeanDeploymentArchive beanDeploymentArchive) {
        BeanDeployment beanDeployment = .getBeanDeployment(beanDeploymentArchive);
        return beanDeployment == null ? null : beanDeployment.getBeanManager().getCurrent();
    }

    
Right now we only index all session and conversation scoped beans.

Returns:
the set of beans the index should be built from
    private Set<Bean<?>> getBeansForBeanIdentifierIndex() {
        Set<Bean<?>> beans = new HashSet<Bean<?>>();
        for (BeanDeployment beanDeployment : getBeanDeployments()) {
            for (Bean<?> bean : beanDeployment.getBeanManager().getBeans()) {
                if (bean.getScope().equals(SessionScoped.class) || bean.getScope().equals(ConversationScoped.class)) {
                    beans.add(bean);
                }
            }
        }
        return beans;
    }
    private boolean isEjbServicesRegistered() {
        if(.getServices().contains(EjbServices.class)) {
            // For backwards compatibility with older integrators that register EjbServices
            // as a deployment service
            return true;
        }
        // EjbServices is a bean deployment archive service
        for (BeanDeploymentArchive beanDeploymentArchive : .getBeanDeploymentArchives()) {
            if (beanDeploymentArchive.getServices().contains(EjbServices.class)) {
                return true;
            }
        }
        return false;
    }
    private void setExtensions(Iterable<Metadata<Extension>> extensions) {
        this. = new ArrayList<Metadata<? extends Extension>>();
        Iterables.addAll(this.extensions);
    }
New to GrepCode? Check out our FAQ X