protected <T> void processBeanRegistration( BeanRegistration registration, GlobalEnablementBuilder globalEnablementBuilder) { Bean<?> bean = registration.getBean(); BeanManagerImpl beanManager = registration.getBeanManager(); if (beanManager == null) { // Get the bean manager for beans added via ABD#addBean() beanManager = getOrCreateBeanDeployment(bean.getBeanClass()).getBeanManager(); } else { // Also validate the bean produced by a builder ExternalBeanAttributesFactory.validateBeanAttributes(bean, getBeanManager()); validateBean(bean); } // Custom beans (alternatives, interceptors, decorators) may also implement // javax.enterprise.inject.spi.Prioritized Integer priority = (bean instanceof Prioritized) ? ((Prioritized) bean).getPriority() : null; if (bean instanceof Interceptor<?>) { beanManager.addInterceptor((Interceptor<?>) bean); if (priority != null) { globalEnablementBuilder.addInterceptor(bean.getBeanClass(), priority); } } else if (bean instanceof Decorator<?>) { beanManager.addDecorator(CustomDecoratorWrapper.of((Decorator<?>) bean, beanManager)); if (priority != null) { globalEnablementBuilder.addDecorator(bean.getBeanClass(), priority); } } else { beanManager.addBean(bean); if (priority != null && bean.isAlternative()) { globalEnablementBuilder.addAlternative(bean.getBeanClass(), priority); } } containerLifecycleEvents.fireProcessBean(beanManager, bean, registration.getExtension()); }
private void validateDecorators(BeanManagerImpl beanManager, AbstractClassBean<?> classBean) { if (classBean.getDecorators().size() > 0) { boolean passivationCapabilityCheckRequired = isPassivationCapabilityCheckRequired(beanManager, classBean); for (Decorator<?> decorator : classBean.getDecorators()) { if (passivationCapabilityCheckRequired) { boolean isSerializable = (decorator instanceof WeldDecorator<?>) ? (((WeldDecorator<?>) decorator).getWeldAnnotated().isSerializable()) : (decorator instanceof PassivationCapable); if (!isSerializable) { throw new UnserializableDependencyException( PASSIVATING_BEAN_WITH_NONSERIALIZABLE_DECORATOR, classBean, decorator); } } for (InjectionPoint ij : decorator.getInjectionPoints()) { if (!ij.isDelegate()) { Bean<?> resolvedBean = beanManager.resolve(beanManager.getBeans(ij)); validateInjectionPoint(ij, beanManager); if (passivationCapabilityCheckRequired) { validateInjectionPointPassivationCapable(ij, resolvedBean, beanManager); } } } } } }
public T createFor(InterceptorReference<Object> interceptorReference) { if (interceptorReference.getInterceptor() instanceof ClassMetadata<?>) { try { // this is not a managed instance - assume no-argument constructor exists Class<T> clazz = cast(interceptorReference.getClassMetadata().getJavaClass()); Constructor<T> constructor = SecureReflections.getDeclaredConstructor(clazz); T interceptorInstance = SecureReflections.ensureAccessible(constructor).newInstance(); // inject AnnotatedType<T> type = manager.createAnnotatedType(clazz); InjectionTarget<T> target = manager.createInjectionTarget(type); target.inject(interceptorInstance, creationalContext); return interceptorInstance; } catch (Exception e) { throw new DeploymentException(e); } } if (interceptorReference.getInterceptor() instanceof SerializableContextual) { try { // this is not a managed instance - assume no-argument constructor exists SerializableContextual<Interceptor<T>, T> serializableContextual = cast(interceptorReference.getInterceptor()); return Reflections.<T>cast( manager.getReference(serializableContextual.get(), creationalContext, false)); } catch (Exception e) { throw new DeploymentException(e); } } throw new IllegalStateException(); }
protected BeanDeployerEnvironment( Set<SlimAnnotatedTypeContext<?>> annotatedTypes, Set<Class<?>> vetoedClasses, SetMultimap<Class<?>, AbstractClassBean<?>> classBeanMap, Set<ProducerField<?, ?>> producerFields, SetMultimap<WeldMethodKey, ProducerMethod<?, ?>> producerMethodBeanMap, Set<RIBean<?>> beans, Set<ObserverInitializationContext<?, ?>> observers, Set<DisposalMethod<?, ?>> allDisposalBeans, Set<DisposalMethod<?, ?>> resolvedDisposalBeans, Set<DecoratorImpl<?>> decorators, Set<InterceptorImpl<?>> interceptors, Set<Type> newBeanTypes, BeanManagerImpl manager) { this.annotatedTypes = annotatedTypes; this.vetoedClasses = vetoedClasses; this.classBeanMap = classBeanMap; this.producerFields = producerFields; this.producerMethodBeanMap = producerMethodBeanMap; this.beans = beans; this.observers = observers; this.allDisposalBeans = allDisposalBeans; this.resolvedDisposalBeans = resolvedDisposalBeans; this.decorators = decorators; this.interceptors = interceptors; this.disposalMethodResolver = new TypeSafeDisposerResolver( allDisposalBeans, manager.getServices().get(WeldConfiguration.class)); this.classTransformer = manager.getServices().get(ClassTransformer.class); this.newBeanTypes = newBeanTypes; this.manager = manager; }
/* * It may in theory happen that an app calls BeanManager.createAnnotatedType() for a previously unknown class on node1 and then * stores this annotated type in session. On node2, this annotated type is not know. We'll try to load it. */ private SlimAnnotatedType<?> tryToLoadUnknownBackedAnnotatedType() { if (identifier.getSuffix() != null || identifier.isModified()) { return null; // this is not a backed annotated type } // first, obtain the BeanManager for a given BDA final BeanManagerImpl manager = Container.instance(identifier).getBeanManager(identifier.getBdaId()); if (manager == null) { return null; } // second, try to load the class final ResourceLoader resourceLoader = manager.getServices().get(ResourceLoader.class); Class<?> clazz = null; try { clazz = resourceLoader.classForName(identifier.getClassName()); } catch (ResourceLoadingException e) { MetadataLogger.LOG.catchingDebug(e); return null; } // finally, try to load the annotated type try { return manager .getServices() .get(ClassTransformer.class) .getBackedAnnotatedType(clazz, identifier.getBdaId()); } catch (ResourceLoadingException e) { MetadataLogger.LOG.catchingDebug(e); return null; } }
/** finds pseudo beans and adds them to the list of beans to be validated */ private static void validatePseudoScopedInjectionPoint( InjectionPoint ij, BeanManagerImpl beanManager, Set<Bean<?>> dependencyPath, Set<Bean<?>> validatedBeans) { Set<Bean<?>> resolved = beanManager.getBeans(ij); try { Bean<? extends Object> bean = beanManager.resolve(resolved); if (bean != null) { if (!(bean instanceof AbstractBuiltInBean<?>)) { boolean normalScoped = beanManager .getServices() .get(MetaAnnotationStore.class) .getScopeModel(bean.getScope()) .isNormal(); if (!normalScoped) { reallyValidatePseudoScopedBean(bean, beanManager, dependencyPath, validatedBeans); } } } } catch (AmbiguousResolutionException e) { // this is handled by another validator } }
@Test(expected = InjectionException.class) @Category(Broken.class) public void testSameBeanTypeInChildAsParentInjection() { BeanManagerImpl childActivity = beanManager.createActivity(); Bean<?> anotherMyBean = createDummyBean(childActivity); childActivity.addBean(anotherMyBean); }
@Test( description = "A simple test to check session replication, doesn't carefully check if a bean ids are correct") public void testSimpleSessionReplication() throws Exception { TestContainer container1 = bootstrapContainer(1, Collections.singletonList(Foo.class)); BeanManagerImpl beanManager1 = getBeanManager(container1); Bean<?> fooBean1 = beanManager1.resolve(beanManager1.getBeans(Foo.class)); TestContainer container2 = bootstrapContainer(2, Collections.singletonList(Foo.class)); BeanManagerImpl beanManager2 = getBeanManager(container2); Bean<?> fooBean2 = beanManager2.resolve(beanManager2.getBeans(Foo.class)); use(1); // Set a value into Foo1 Foo foo1 = (Foo) beanManager1.getReference( fooBean1, Foo.class, beanManager1.createCreationalContext(fooBean1)); foo1.setName("container 1"); replicateSession(1, container1, 2, container2); use(2); Foo foo2 = (Foo) beanManager2.getReference( fooBean2, Foo.class, beanManager2.createCreationalContext(fooBean2)); assert foo2.getName().equals("container 1"); use(2); container2.stopContainer(); use(1); container1.stopContainer(); }
@Test(expectedExceptions = IllegalStateException.class) public void testVariableBeanDeploymentStructure() throws Exception { Collection<Class<?>> classes1 = Arrays.<Class<?>>asList(Stable.class, Horse.class, Fodder.class); Collection<Class<?>> classes2 = Arrays.<Class<?>>asList(Stable.class, Horse.class, Fodder.class, Foo.class); TestContainer container1 = bootstrapContainer(1, classes1); BeanManagerImpl beanManager1 = getBeanManager(container1); Bean<?> stableBean1 = beanManager1.resolve(beanManager1.getBeans(Stable.class)); TestContainer container2 = bootstrapContainer(2, classes2); use(1); // Set a value into Foo1 Stable stable1 = (Stable) beanManager1.getReference( stableBean1, Stable.class, beanManager1.createCreationalContext(stableBean1)); stable1.getFodder().setAmount(10); stable1.getHorse().setName("George"); try { replicateSession(1, container1, 2, container2); } finally { use(1); container1.stopContainer(); use(2); container2.stopContainer(); } }
public void shutdown() { try { // First, the container must destroy all contexts. deploymentManager.instance().select(ApplicationContext.class).get().invalidate(); deploymentManager.instance().select(SingletonContext.class).get().invalidate(); } finally { try { // fire @Destroyed(ApplicationScoped.class) for non-web modules // web modules are handled by HttpContextLifecycle for (BeanDeploymentModule module : deploymentManager.getServices().get(BeanDeploymentModules.class)) { if (!module.isWebModule()) { module.fireEvent( Object.class, ContextEvent.APPLICATION_DESTROYED, DestroyedLiteral.APPLICATION); } } } catch (Exception ignored) { } try { // Finally, the container must fire an event of type BeforeShutdown. BeforeShutdownImpl.fire(deploymentManager); } finally { Container container = Container.instance(contextId); container.setState(ContainerState.SHUTDOWN); container.cleanup(); } } }
private Object readResolve() throws ObjectStreamException { InterceptionModel<ClassMetadata<?>> interceptionModel = manager.getInterceptorModelRegistry().get(targetClass); MetadataCachingReader reader = manager.getInterceptorMetadataReader(); TargetClassInterceptorMetadata<?> targetClassInterceptorMetadata = reader.getTargetClassInterceptorMetadata(reader.getClassMetadata(targetClass)); return new InterceptionContext( interceptorInstances, manager, targetClassInterceptorMetadata, interceptionModel); }
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<ApplicationContext>( new ApplicationContextImpl(contextId), ApplicationContext.class, UnboundLiteral.INSTANCE)); contexts.add( new ContextHolder<SingletonContext>( new SingletonContextImpl(contextId), SingletonContext.class, UnboundLiteral.INSTANCE)); contexts.add( new ContextHolder<BoundSessionContext>( new BoundSessionContextImpl(contextId, beanIdentifierIndex), BoundSessionContext.class, BoundLiteral.INSTANCE)); contexts.add( new ContextHolder<BoundConversationContext>( new BoundConversationContextImpl(contextId, services), BoundConversationContext.class, BoundLiteral.INSTANCE)); contexts.add( new ContextHolder<BoundRequestContext>( new BoundRequestContextImpl(contextId), BoundRequestContext.class, BoundLiteral.INSTANCE)); contexts.add( new ContextHolder<RequestContext>( new RequestContextImpl(contextId), RequestContext.class, UnboundLiteral.INSTANCE)); contexts.add( new ContextHolder<DependentContext>( new DependentContextImpl(services.get(ContextualStore.class)), DependentContext.class, UnboundLiteral.INSTANCE)); services.get(WeldModules.class).postContextRegistration(contextId, services, contexts); /* * 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 Context> context : contexts) { deploymentManager.addContext(context.getContext()); deploymentManager.addBean(ContextBean.of(context, deploymentManager)); } return contexts; }
/** * @param id * @param manager * @param bootstrap */ private WeldContainer(String id, WeldManager manager, Bootstrap bootstrap) { super(); this.id = id; this.manager = manager; this.bootstrap = bootstrap; this.creationalContext = manager.createCreationalContext(null); BeanManagerImpl beanManagerImpl = ((BeanManagerImpl) manager.unwrap()); this.instance = beanManagerImpl.getInstance(creationalContext); this.event = beanManagerImpl.event(); }
private void processAdditionalObserver(ObserverMethod<?> observer) { validateObserverMethod(observer, getBeanManager(), null); BeanManagerImpl manager = getOrCreateBeanDeployment(observer.getBeanClass()).getBeanManager(); if (Observers.isObserverMethodEnabled(observer, manager)) { ObserverMethod<?> processedObserver = containerLifecycleEvents.fireProcessObserverMethod(manager, observer); if (processedObserver != null) { manager.addObserver(processedObserver); } } }
protected AfterTypeDiscoveryImpl( BeanManagerImpl beanManager, BeanDeploymentArchiveMapping bdaMapping, Deployment deployment, Collection<ContextHolder<? extends Context>> contexts) { super(beanManager, AfterTypeDiscovery.class, bdaMapping, deployment, contexts); this.builder = beanManager.getServices().get(GlobalEnablementBuilder.class); this.events = beanManager.getServices().get(ContainerLifecycleEvents.class); this.transformer = beanManager.getServices().get(ClassTransformer.class); this.store = beanManager.getServices().get(SlimAnnotatedTypeStore.class); }
public void validateBeans() { BootstrapLogger.LOG.validatingBeans(); for (BeanDeployment beanDeployment : getBeanDeployments()) { BeanManagerImpl beanManager = beanDeployment.getBeanManager(); beanManager.getBeanResolver().clear(); deployment.getServices().get(Validator.class).validateDeployment(beanManager, beanDeployment); beanManager.getServices().get(InjectionTargetService.class).validate(); } getContainer().setState(ContainerState.VALIDATED); AfterDeploymentValidationImpl.fire(deploymentManager); }
public void validateDeployment(BeanManagerImpl manager, BeanDeployerEnvironment environment) { validateDecorators(manager.getDecorators(), new ArrayList<RIBean<?>>(), manager); validateInterceptors(manager.getInterceptors()); validateBeans(manager.getBeans(), new ArrayList<RIBean<?>>(), manager); validateEnabledDecoratorClasses(manager); validateEnabledInterceptorClasses(manager); validateEnabledAlternatives(manager); validateDisposalMethods(environment); validateObserverMethods(environment.getObservers(), manager); validateBeanNames(manager); }
public static WeldClass<?> getWeldClassOfDecoratedType(BeanManagerImpl beanManager, Type type) { if (type instanceof Class<?>) { return (WeldClass<?>) beanManager.createAnnotatedType((Class<?>) type); } if (type instanceof ParameterizedType && (((ParameterizedType) type).getRawType() instanceof Class)) { return (WeldClass<?>) beanManager.createAnnotatedType((Class<?>) ((ParameterizedType) type).getRawType()); } throw new IllegalStateException(UNABLE_TO_PROCESS, type); }
private void validateEnabledInterceptorClasses(BeanManagerImpl beanManager) { Set<Class<?>> interceptorBeanClasses = new HashSet<Class<?>>(); for (Interceptor<?> interceptor : beanManager.getAccessibleInterceptors()) { interceptorBeanClasses.add(interceptor.getBeanClass()); } for (Metadata<Class<?>> enabledInterceptorClass : beanManager.getEnabled().getInterceptors()) { if (!interceptorBeanClasses.contains(enabledInterceptorClass.getValue())) { throw new DeploymentException( INTERCEPTOR_NOT_ANNOTATED_OR_REGISTERED, enabledInterceptorClass); } } }
private AfterBeanDiscoveryImpl( BeanManagerImpl beanManager, Deployment deployment, BeanDeploymentArchiveMapping bdaMapping, Collection<ContextHolder<? extends Context>> contexts) { super(beanManager, WeldAfterBeanDiscovery.class, bdaMapping, deployment, contexts); this.slimAnnotatedTypeStore = beanManager.getServices().get(SlimAnnotatedTypeStore.class); this.containerLifecycleEvents = beanManager.getServices().get(ContainerLifecycleEvents.class); this.additionalBeans = new LinkedList<BeanRegistration>(); this.additionalObservers = new LinkedList<ObserverMethod<?>>(); this.additionalObserverConfigurators = new LinkedList<ObserverMethodConfigurator<?>>(); }
@Override public ManagedReference getReference() { final BeanManagerImpl beanManager = this.beanManager.getValue(); final CreationalContext<?> ctx; if (bean == null) { ctx = beanManager.createCreationalContext(null); } else { ctx = beanManager.createCreationalContext(bean); } final Object instance = injectionTarget.produce(ctx); return new WeldManagedReference(ctx, instance, injectionTarget, interceptorInjections); }
private void validateEnabledDecoratorClasses(BeanManagerImpl beanManager) { // TODO Move building this list to the boot or sth Set<Class<?>> decoratorBeanClasses = new HashSet<Class<?>>(); for (Decorator<?> bean : beanManager.getAccessibleDecorators()) { decoratorBeanClasses.add(bean.getBeanClass()); } for (Metadata<Class<?>> clazz : beanManager.getEnabled().getDecorators()) { if (!decoratorBeanClasses.contains(clazz.getValue())) { throw new DeploymentException( DECORATOR_CLASS_NOT_BEAN_CLASS_OF_DECORATOR, clazz, decoratorBeanClasses); } } }
@Test public void testMultipleDependentObjectsSessionReplication() throws Exception { Collection<Class<?>> classes = Arrays.<Class<?>>asList(Stable.class, Horse.class, Fodder.class); TestContainer container1 = bootstrapContainer(1, classes); BeanManagerImpl beanManager1 = getBeanManager(container1); Bean<?> stableBean1 = beanManager1.resolve(beanManager1.getBeans(Stable.class)); TestContainer container2 = bootstrapContainer(2, classes); BeanManagerImpl beanManager2 = getBeanManager(container2); Bean<?> stableBean2 = beanManager2.resolve(beanManager2.getBeans(Stable.class)); use(1); // Set a value into Foo1 Stable stable1 = (Stable) beanManager1.getReference( stableBean1, Stable.class, beanManager1.createCreationalContext(stableBean1)); stable1.getFodder().setAmount(10); stable1.getHorse().setName("George"); replicateSession(1, container1, 2, container2); use(2); Stable stable2 = (Stable) beanManager2.getReference( stableBean2, Stable.class, beanManager2.createCreationalContext(stableBean2)); assert stable2.getFodder().getAmount() == stable1.getFodder().getAmount(); assert stable2.getHorse().getName() == null; use(1); assert stable1.getFodder().getAmount() == 10; assert stable1.getHorse().getName().equals("George"); use(2); stable2.getFodder().setAmount(11); replicateSession(2, container2, 1, container1); use(1); int i = stable1.getFodder().getAmount(); assert stable1.getFodder().getAmount() == 11; use(1); container1.stopContainer(); use(2); container2.stopContainer(); }
private HttpConversationContext httpConversationContext() { if (httpConversationContextCache == null) { this.httpConversationContextCache = beanManager.instance().select(HttpConversationContext.class).get(); } return httpConversationContextCache; }
protected void activateConversationContext(HttpServletRequest request) { HttpConversationContext conversationContext = httpConversationContext(); String cid = getConversationId(request, httpConversationContext()); log.debug(RESUMING_CONVERSATION, cid); /* * Don't try to reactivate the ConversationContext if we have already activated it for this request WELD-877 */ if (!isContextActivatedInRequest(request)) { setContextActivatedInRequest(request); conversationContext.activate(cid); if (cid == null) { // transient conversation beanManager .getAccessibleLenientObserverNotifier() .fireEvent(request, InitializedLiteral.CONVERSATION); } } else { /* * We may have previously been associated with a ConversationContext, but the reference to that context may have * been lost during a Servlet forward WELD-877 */ conversationContext.dissociate(request); conversationContext.associate(request); conversationContext.activate(cid); } }
/** * Extracts the complete set of interception bindings from a given set of annotations. * * @param beanManager * @param annotations * @return */ protected static Set<Annotation> flattenInterceptorBindings( BeanManagerImpl beanManager, Set<Annotation> annotations) { Set<Annotation> foundInterceptionBindingTypes = new HashSet<Annotation>(); for (Annotation annotation : annotations) { if (beanManager.isInterceptorBinding(annotation.annotationType())) { foundInterceptionBindingTypes.add(annotation); foundInterceptionBindingTypes.addAll( beanManager .getServices() .get(MetaAnnotationStore.class) .getInterceptorBindingModel(annotation.annotationType()) .getInheritedInterceptionBindingTypes()); } } return foundInterceptionBindingTypes; }
@Test public void testDestroyDoesntTryToRemoveSLSB() { Bean<BeanLocal> bean = Utils.getBean(beanManager, BeanLocal.class); Assert.assertNotNull("Expected a bean for stateless session bean BeanLocal", bean); CreationalContext<BeanLocal> creationalContext = beanManager.createCreationalContext(bean); BeanLocal instance = bean.create(creationalContext); bean.destroy(instance, creationalContext); }
public void startInitialization() { if (deploymentManager == null) { throw BootstrapLogger.LOG.managerNotInitialized(); } Set<BeanDeployment> physicalBeanDeploymentArchives = new HashSet<BeanDeployment>(getBeanDeployments()); ExtensionBeanDeployer extensionBeanDeployer = new ExtensionBeanDeployer(deploymentManager, deployment, bdaMapping, contexts); extensionBeanDeployer.addExtensions(extensions); extensionBeanDeployer.deployBeans(); installFastProcessAnnotatedTypeResolver(deploymentManager.getServices()); // Add the Deployment BeanManager Bean to the Deployment BeanManager deploymentManager.addBean(new BeanManagerBean(deploymentManager)); deploymentManager.addBean(new BeanManagerImplBean(deploymentManager)); // Re-Read the deployment structure, bdaMapping will be the physical // structure, and will add in BDAs for any extensions outside a // physical BDA deploymentVisitor.visit(); BeforeBeanDiscoveryImpl.fire(deploymentManager, deployment, bdaMapping, contexts); // 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 deploymentVisitor.visit(); for (BeanDeployment beanDeployment : getBeanDeployments()) { beanDeployment.createTypes(); } AfterTypeDiscoveryImpl.fire(deploymentManager, deployment, bdaMapping, contexts); for (BeanDeployment beanDeployment : getBeanDeployments()) { beanDeployment.createEnablement(); } }
public BeanManagerProxy(BeanManagerImpl manager) { this.manager = manager; this.nonPortableMode = manager .getServices() .get(WeldConfiguration.class) .getBooleanProperty(ConfigurationKey.NON_PORTABLE_MODE); }
public InjectionTargetService(BeanManagerImpl beanManager) { this.validator = beanManager.getServices().get(Validator.class); this.producersToValidate = new ConcurrentLinkedQueue<Producer<?>>(); this.injectionTargetsToInitialize = new ConcurrentLinkedQueue<InjectionTargetInitializationContext<?>>(); this.container = Container.instance(beanManager); this.beanManager = beanManager; }