@Test public void testInjectionTarget() { BeanManager beanManager = current().getBeanManager(); // CDI uses an AnnotatedType object to read the annotations of a class AnnotatedType<String> type = beanManager.createAnnotatedType(String.class); // The extension uses an InjectionTarget to delegate instantiation, // dependency injection // and lifecycle callbacks to the CDI container InjectionTarget<String> it = beanManager.createInjectionTarget(type); // each instance needs its own CDI CreationalContext CreationalContext<String> ctx = beanManager.createCreationalContext(null); // instantiate the framework component and inject its dependencies String instance = it.produce(ctx); // call the constructor it.inject(instance, ctx); // call initializer methods and perform field // injection it.postConstruct(instance); // call the @PostConstruct method // destroy the framework component instance and clean up dependent // objects assertNotNull("the String instance is injected now", instance); assertTrue("the String instance is injected now but it's empty", instance.isEmpty()); it.preDestroy(instance); // call the @PreDestroy method it.dispose(instance); // it is now safe to discard the instance ctx.release(); // clean up dependent objects }
@Override public Producer createProducer() throws IllegalAccessException { // FIXME: to be replaced once event firing with dynamic parameterized type // is properly supported (see https://issues.jboss.org/browse/CDI-516) TypeLiteral<T> literal = new TypeLiteral<T>() { }; for (Field field : TypeLiteral.class.getDeclaredFields()) { if (field.getType().equals(Type.class)) { field.setAccessible(true); field.set(literal, type); break; } } InjectionTarget<AnyEvent> target = manager.createInjectionTarget(manager.createAnnotatedType(AnyEvent.class)); CreationalContext<AnyEvent> ctx = manager.createCreationalContext(null); AnyEvent instance = target.produce(ctx); target.inject(instance, ctx); return new CdiEventProducer<>(this, instance.event .select(literal, qualifiers.stream().toArray(Annotation[]::new))); }
@Test public void createAndDestroyFSShouldRegisterUnregisterOnPriorityDisposableRegistry() throws Exception { when(bm.getBeans("configIO")).thenReturn(configIOBeans); when(bm.getReference(eq(ioServiceBean), eq(IOService.class), any(CreationalContext.class))) .thenReturn(ioServiceMock); when(ioServiceMock.newFileSystem(any(URI.class), any(Map.class))) .thenReturn(fs); final Bean fileSystemBean = producer.createFileSystemBean(bm, mock(InjectionTarget.class)); assertNull(PriorityDisposableRegistry.get("systemFS")); fileSystemBean.create(mock(CreationalContext.class)); assertNotNull(PriorityDisposableRegistry.get("systemFS")); fileSystemBean.destroy(fs, mock(CreationalContext.class)); assertNull(PriorityDisposableRegistry.get("systemFS")); }
/** * Prepares the injection process of properties from a property file. * * @param pit * The actual target of process injection * @param <T> * the generic type of the injection target */ public <T> void initializePropertyLoading(@Observes final ProcessInjectionTarget<T> pit) throws IOException { AnnotatedType<T> at = pit.getAnnotatedType(); if (!at.isAnnotationPresent(PropertyFile.class)) { return; } try { PropertyFile propertyFile = at.getAnnotation(PropertyFile.class); Properties properties = loadProperties(propertyFile, pit.getAnnotatedType().getJavaClass()); Map<Field, Object> fieldValues = assignPropertiesToFields(at.getFields(), properties); InjectionTarget<T> wrapped = new PropertyInjectionTarget<T>(fieldValues, pit, pit.getInjectionTarget()); pit.setInjectionTarget(wrapped); } catch (Exception e) { pit.addDefinitionError(e); } }
@SuppressWarnings("unchecked") private static <T> InjectionTarget<T> createInjectionTarget( final CompletableFuture<Registry> injector, final Class<T> type) { return Reflection.newProxy(InjectionTarget.class, (proxy, method, args) -> { final String name = method.getName(); switch (name) { case "produce": return injector.get().require(type); case "inject": return null; case "postConstruct": return null; case "preDestroy": return null; case "dispose": return null; default: throw new UnsupportedOperationException(method.toString()); } }); }
private static <T> T newInstance(final OpenEjbConfig config, final Class<T> clazz) throws Exception { final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb( Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE); if (webBeansContext == null) { return clazz.newInstance(); } final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl(); if (!beanManager.isInUse()) { return clazz.newInstance(); } final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz); final InjectionTarget<T> it = beanManager.createInjectionTarget(annotatedType); final CreationalContext<T> context = beanManager.createCreationalContext(null); final T instance = it.produce(context); it.inject(instance, context); it.postConstruct(instance); config.releasables.add(new Releasable<T>(context, it, instance)); return instance; }
@Override public InjectionTarget<T> createInjectionTarget(final Bean<T> bean) { final EjbInjectionTargetImpl<T> injectionTarget = new EjbInjectionTargetImpl<T>(getAnnotatedType(), createInjectionPoints(bean), getWebBeansContext()); final InjectionTarget<T> it = getWebBeansContext().getWebBeansUtil().fireProcessInjectionTargetEvent(injectionTarget, getAnnotatedType()).getInjectionTarget(); for (final InjectionPoint ip : it.getInjectionPoints()) { if (ip.getType() != UserTransaction.class) { continue; } if (beanContext.getTransactionType() != TransactionType.BeanManaged) { throw new DefinitionException("@Inject UserTransaction is only valid for BeanManaged beans"); } } if (!EjbInjectionTargetImpl.class.isInstance(it)) { return new EjbInjectionTargetImpl<T>(injectionTarget, it); } return it; }
/** * Manually inject dependencies. Inspired by https://developer.jboss.org/thread/196807 * * @param clazz * @param injectionObject * @throws NamingException */ public static <T> T programmaticInjection(Class<T> clazz, T injectionObject) throws NamingException { InitialContext initialContext = new InitialContext(); Object lookup = initialContext.lookup("java:comp/BeanManager"); BeanManager beanManager = (BeanManager) lookup; AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz); InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget(annotatedType); CreationalContext<T> creationalContext = beanManager.createCreationalContext(null); injectionTarget.inject(injectionObject, creationalContext); injectionTarget.postConstruct(injectionObject); //call the @PostConstruct method creationalContext.release(); return injectionObject; }
@Before public final void setUp() throws Exception { System.out.printf("AbstractCdiContainerTest#setUp() containerRefCount=%d, cdiContainer=%s\n", containerRefCount.get(), cdiContainer ); if ( cdiContainer != null ) { containerRefCount.incrementAndGet(); final ContextControl ctxCtrl = BeanProvider.getContextualReference(ContextControl.class); //stop the RequestContext to dispose of the @RequestScoped EntityManager ctxCtrl.stopContext(RequestScoped.class); //immediately restart the context again ctxCtrl.startContext(RequestScoped.class); // perform injection into the very own test class final BeanManager beanManager = cdiContainer.getBeanManager(); final CreationalContext creationalContext = beanManager.createCreationalContext(null); final AnnotatedType annotatedType = beanManager.createAnnotatedType(this.getClass()); final InjectionTarget injectionTarget = beanManager.createInjectionTarget(annotatedType); injectionTarget.inject(this, creationalContext); } }
private <T> void projectInjectionTarget(MybatisExtension extension, Type type) { ProcessInjectionTarget<T> event = mock(ProcessInjectionTarget.class); InjectionTarget<T> injectTarget = mock(InjectionTarget.class); Set<InjectionPoint> injectionPoints = new HashSet<InjectionPoint>(); InjectionPoint injectionPoint = mock(InjectionPoint.class); Annotated annotated = mock(Annotated.class); when(injectionPoint.getAnnotated()).thenReturn(annotated); when(annotated.getBaseType()).thenReturn(type); when(annotated.getAnnotations()).thenReturn(new HashSet<Annotation>()); injectionPoints.add(injectionPoint); when(event.getInjectionTarget()).thenReturn(injectTarget); when(injectTarget.getInjectionPoints()).thenReturn(injectionPoints); extension.processInjectionTarget(event); }
/** * Performs dependency injection on an instance. Useful for instances which aren't managed by CDI. * <p/> * <b>Attention:</b><br/> * The resulting instance isn't managed by CDI; only fields annotated with @Inject get initialized. * * @param instance current instance * @param <T> current type * * @return instance with injected fields (if possible - or null if the given instance is null) */ @SuppressWarnings("unchecked") public static <T> T injectFields(T instance) { if (instance == null) { return null; } BeanManager beanManager = getBeanManager(); CreationalContext<T> creationalContext = beanManager.createCreationalContext(null); AnnotatedType<T> annotatedType = beanManager.createAnnotatedType((Class<T>) instance.getClass()); InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget(annotatedType); injectionTarget.inject(instance, creationalContext); return instance; }
@SuppressWarnings("unchecked") private void withProducer(final Object o, final BiConsumer<Bean, InjectionTarget> consumer) { final Bean<Object> bean = resolveUnique((Class<Object>) o.getClass()); if (!(bean instanceof AbstractClassBean)) { throw new TestEEfiException("Injection of " + bean + " is not supported"); } consumer.accept(bean, ((AbstractClassBean) bean).getProducer()); }
void inject() { BeanManager beanManager = container.getBeanManager(); CreationalContext<Object> ctx = beanManager.createCreationalContext(null); @SuppressWarnings("unchecked") InjectionTarget<Object> injectionTarget = (InjectionTarget<Object>) beanManager .getInjectionTargetFactory(beanManager.createAnnotatedType(instance.getClass())).createInjectionTarget(null); injectionTarget.inject(instance, ctx); creationalContext = ctx; }
@Test public void captureProducerTypes() { final ProcessInjectionPoint<?, ?> pip = mock(ProcessInjectionPoint.class); final InjectionPoint ip = mock(InjectionPoint.class); when(pip.getInjectionPoint()).thenReturn(ip); final Annotated annotated = mock(Annotated.class); when(ip.getAnnotated()).thenReturn(annotated); when(annotated.isAnnotationPresent(Body.class)).thenReturn(true); when(ip.getType()).thenReturn(COLLECTION.getClass()); @SuppressWarnings("unchecked") final InjectionTarget<Object> injectionTarget = mock(InjectionTarget.class); when(this.beanManager.createInjectionTarget(Mockito.any())).thenReturn(injectionTarget); final Member member = mock(Member.class); when(ip.getMember()).thenReturn(member); final List<Bean<?>> found = ReflectionUtil.get(this.extension, "found"); assertTrue(found.isEmpty()); this.extension.captureProducerTypes(pip, this.beanManager); assertEquals(1, found.size()); verify(pip, times(2)).getInjectionPoint(); verify(ip).getAnnotated(); verify(annotated).isAnnotationPresent(Body.class); verify(ip).getType(); verify(ip).getMember(); verify(member).getName(); verify(ip).getQualifiers(); verify(injectionTarget).getInjectionPoints(); verify(this.beanManager).createInjectionTarget(Mockito.any()); verifyNoMoreInteractions(pip, ip, annotated, injectionTarget, member); }
/** * Perform injection into a non-CDI managed bean. * <p> * An example of this is a JSP Tag * <p> * @param <T> * @param bean */ public static <T> T inject( T bean ) { BeanManager beanManager = getBeanManager(); AnnotatedType<T> annotatedType = beanManager.<T>createAnnotatedType( (Class<T>) bean.getClass() ); InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget( annotatedType ); CreationalContext ctx = beanManager.createCreationalContext( null ); injectionTarget.inject( bean, ctx ); return bean; }
/** * Creates an instance of the CDI managed bean. * Calls CDI API to inject into the bean. * * @param componentClass bean class to be instantiated. * @return New instance of bean class with injected content. */ @Override @SuppressWarnings("unchecked") public <T> T getOrCreateComponent(Class<T> componentClass) { return (T) injectionTargets.computeIfAbsent(componentClass, clazz -> { final AnnotatedType<T> aType = beanManager.createAnnotatedType(componentClass); final InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget(aType); CreationalContext<T> creationalContext = beanManager.createCreationalContext(null); final T beanInstance = injectionTarget.produce(creationalContext); injectionTarget.inject(beanInstance, creationalContext); injectionTarget.postConstruct(beanInstance); return new CDIManagedBean(beanInstance, injectionTarget, creationalContext); }).getInstance(); }
@SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> void programmaticInjection(Class clazz, T injectionObject) throws NamingException { InitialContext initialContext = new InitialContext(); Object lookup = initialContext.lookup("java:comp/BeanManager"); BeanManager beanManager = (BeanManager) lookup; AnnotatedType annotatedType = beanManager.createAnnotatedType(clazz); InjectionTarget injectionTarget = beanManager.createInjectionTarget(annotatedType); CreationalContext creationalContext = beanManager.createCreationalContext(null); injectionTarget.inject(injectionObject, creationalContext); creationalContext.release(); }
@Override public <T> InjectionTarget<T> createInjectionTarget(final AnnotatedType<T> type) { return new NoopInjectionTarget<T>() { @Override public T produce(CreationalContext<T> ctx) { return objectLocator.autobuild(type.getJavaClass()); } @Override public void preDestroy(T instance) { try { for (Method method : type.getJavaClass().getMethods()) { if (method.getAnnotation(PreDestroy.class) != null) { method.invoke(instance); } } } catch (Exception e) { logger.error("Error invoking @PreDestroy callback on instance of class " + type.getJavaClass(), e); } } }; }
private void buildSystemFS(final AfterBeanDiscovery abd, final BeanManager bm) { final InjectionTarget<DummyFileSystem> it = bm.createInjectionTarget(bm.createAnnotatedType(DummyFileSystem.class)); abd.addBean(createFileSystemBean(bm, it)); }
@SuppressWarnings("unchecked") public static <T> T injectFields(final BeanManager beanManager, final T instance) { if (instance == null) { return null; } CreationalContext<T> creationalContext = beanManager.createCreationalContext(null); AnnotatedType<T> annotatedType = beanManager .createAnnotatedType((Class<T>) instance.getClass()); InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget(annotatedType); injectionTarget.inject(instance, creationalContext); return instance; }
@SuppressWarnings("unchecked") public void injectMembers(Object instance) { final BeanManager bm = getBeanManager(); final CreationalContext creationalContext = getCreationalContext(); InjectionTarget<Object> injectionTarget = (InjectionTarget<Object>) bm.createInjectionTarget( bm.createAnnotatedType(instance.getClass())); injectionTarget.inject(instance, creationalContext); }
public PropertyResolverInjectionTarget(InjectionTarget<T> injectionTarget, AnnotatedType<T> annotatedType, PropertyResolverBean propertyResolverBean, PropertyFormat propertyFormat) { this.injectionTarget = injectionTarget; this.annotatedType = annotatedType; this.propertyResolverBean = propertyResolverBean; this.propertyFormat = propertyFormat; }
@SuppressWarnings({"unchecked", "rawtypes"}) @Test public void beanManager() throws Exception { new GuiceBeanManager(); Listener value = new Listener(); new MockUnit(CompletableFuture.class, Registry.class) .expect(unit -> { Registry registry = unit.get(Registry.class); expect(registry.require(Listener.class)).andReturn(value); CompletableFuture future = unit.get(CompletableFuture.class); expect(future.get()).andReturn(registry); }) .run(unit -> { BeanManager bm = GuiceBeanManager.beanManager(unit.get(CompletableFuture.class)); AnnotatedType<Listener> type = bm.createAnnotatedType(Listener.class); assertNotNull(type); InjectionTarget<Listener> injectionTarget = bm.createInjectionTarget(type); CreationalContext<Listener> ctx = bm.createCreationalContext(null); assertEquals(value, injectionTarget.produce(ctx)); injectionTarget.inject(value, ctx); injectionTarget.postConstruct(value); injectionTarget.preDestroy(value); injectionTarget.dispose(value); ctx.release(); }); }
@Test(expected = UnsupportedOperationException.class) public void itUOE() throws Exception { BeanManager bm = GuiceBeanManager.beanManager(null); AnnotatedType<Listener> type = bm.createAnnotatedType(Listener.class); InjectionTarget<Listener> injectionTarget = bm.createInjectionTarget(type); injectionTarget.getInjectionPoints(); }
@SuppressWarnings({ "rawtypes", "unchecked" }) private static void createAnnotatedTypeForExistingBeanClass(BeanManagerImpl beanManager, Class<?> beanClass, InjectionTargetBean bean) { WebBeansContext wbc = beanManager.getWebBeansContext(); AnnotatedElementFactory annotatedElementFactory = wbc.getAnnotatedElementFactory(); // Clear AnnotatedElementFactory caches annotatedElementFactory.clear(); AnnotatedType annotatedType = annotatedElementFactory.newAnnotatedType(beanClass); ReflectionHelper.set(bean, InjectionTargetBean.class, "annotatedType", annotatedType); // Updated members that were set by bean attributes BeanAttributesImpl attributes = BeanAttributesBuilder.forContext(wbc).newBeanAttibutes(annotatedType).build(); ReflectionHelper.set(bean, BeanAttributesImpl.class, "types", attributes.getTypes()); ReflectionHelper.set(bean, BeanAttributesImpl.class, "qualifiers", attributes.getQualifiers()); ReflectionHelper.set(bean, BeanAttributesImpl.class, "scope", attributes.getScope()); ReflectionHelper.set(bean, BeanAttributesImpl.class, "name", attributes.getName()); ReflectionHelper.set(bean, BeanAttributesImpl.class, "stereotypes", attributes.getStereotypes()); ReflectionHelper.set(bean, BeanAttributesImpl.class, "alternative", attributes.isAlternative()); InjectionTargetFactory factory = new InjectionTargetFactoryImpl(annotatedType, bean.getWebBeansContext()); InjectionTarget injectionTarget = factory.createInjectionTarget(bean); ReflectionHelper.set(bean, InjectionTargetBean.class, "injectionTarget", injectionTarget); LOGGER.debug("New annotated type created for bean '{}'", beanClass.getName()); }
@Override public <T> InjectionTarget<T> createInjectionTarget(final AnnotatedType<T> type) { try { return super.createInjectionTarget(type); } catch (final RuntimeException e) { try { return getParentBm().createInjectionTarget(type); } catch (final RuntimeException ignored) { throw e; } } }
/** * Collect all targets to match Mappers and Session providers dependency. * * @param <X> the generic type * @param event the event */ protected <X> void processInjectionTarget(@Observes ProcessInjectionTarget<X> event) { final InjectionTarget<X> it = event.getInjectionTarget(); for (final InjectionPoint ip : it.getInjectionPoints()) { injectionPoints.add(ip); } }
public MockAwareInjectionTargetWrapper(BeanManager beanManager, InjectionTarget<T> wrapped, List<Type> beanTypes, List<Annotation> qualifiers) { this.beanManager = beanManager; this.wrapped = wrapped; this.beanTypes = beanTypes; this.qualifiers = qualifiers; }
/** * Set the ContextualLifecycle and the InjectionPoints for the AnnotatedType * @param type */ protected void setDefaultBeanLifecycle(AnnotatedType<T> type) { InjectionTarget<T> injectionTarget; if (!type.getJavaClass().isInterface()) { injectionTarget = beanManager.createInjectionTarget(type); } else { injectionTarget = new DummyInjectionTarget<T>(); } this.beanLifecycle = new DelegatingContextualLifecycle<T>(injectionTarget); this.injectionPoints = injectionTarget.getInjectionPoints(); }
@Override public InjectionTarget<T> createInjectionTarget(Bean<T> bean) { return new OrientInjectionTarget<>(beanClass, profile); }
public ConfigurableInjectionTarget(InjectionTarget<T> delegate, ConfigurableManager configurableManager) { this.delegate = delegate; this.configurableManager = configurableManager; }
public CDIManagedBean(T instance, InjectionTarget<T> injectionTarget, CreationalContext<T> creationalContext) { this.instance = instance; this.injectionTarget = injectionTarget; this.creationalContext = creationalContext; }
/** * @return CDI InjectionTarget */ private InjectionTarget<T> getInjectionTarget() { return injectionTarget; }
<T extends CamelContext> InjectionTarget<T> camelContextInjectionTarget(InjectionTarget<T> delegate, Annotated annotated, BeanManager manager, CdiCamelExtension extension) { CamelContextProducer<T> producer = new CamelContextProducer<>(delegate, annotated, manager, extension); return new CamelContextInjectionTarget<>(delegate, hasBundleContext ? new CamelContextOsgiProducer<>(producer) : producer); }
DelegateInjectionTarget(InjectionTarget<T> delegate) { super(delegate); this.delegate = delegate; }
DelegateInjectionTarget(InjectionTarget<T> target, Producer<T> producer) { super(producer); this.delegate = target; }
CamelContextInjectionTarget(InjectionTarget<T> target, Producer<T> producer) { super(target, producer); }
CamelBeanInjectionTarget(InjectionTarget<T> delegate, BeanManager manager) { super(delegate); this.delegate = delegate; this.processor = new CdiCamelBeanPostProcessor(manager); }
SyntheticBean(BeanManager manager, SyntheticAnnotated annotated, Class<?> type, InjectionTarget<T> target, Function<Bean<T>, String> toString) { super(manager, annotated); this.type = type; this.target = target; this.toString = toString; }
public DolphinPlatformContextualLifecycle(InjectionTarget<T> injectionTarget, PostConstructInterceptor<T> interceptor) { this.injectionTarget = Assert.requireNonNull(injectionTarget, "injectionTarget"); this.interceptor = Assert.requireNonNull(interceptor, "interceptor"); }