javax.enterprise.inject.spi.AnnotatedType Java Examples

The following examples show how to use javax.enterprise.inject.spi.AnnotatedType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpringCDIExtension.java    From datawave with Apache License 2.0 6 votes vote down vote up
public SpringCDIBean(SpringBean sb, Type targetType, BeanManager beanManager) {
    this.annotation = sb;
    this.targetType = targetType;
    this.name = sb.name();
    if ("".equals(name.trim())) {
        name = generateName();
    }
    
    AnnotatedType<Object> at = beanManager.createAnnotatedType(Object.class);
    injectionTarget = beanManager.createInjectionTarget(at);
    
    if (targetType instanceof ParameterizedType) {
        rawType = (Class<?>) ((ParameterizedType) targetType).getRawType();
    } else {
        rawType = (Class<?>) targetType;
    }
}
 
Example #2
Source File: ConverterAndValidatorProxyExtension.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
protected <T> Bean<T> createBean(Class<T> beanClass, BeanManager beanManager)
{
    Class<? extends InvocationHandler> invocationHandlerClass =
            Converter.class.isAssignableFrom(beanClass) ?
                    ConverterInvocationHandler.class : ValidatorInvocationHandler.class;

    AnnotatedType<T> annotatedType = new AnnotatedTypeBuilder<T>().readFromType(beanClass).create();

    DeltaSpikeProxyContextualLifecycle lifecycle = new DeltaSpikeProxyContextualLifecycle(beanClass,
            invocationHandlerClass, ConverterAndValidatorProxyFactory.getInstance(), beanManager);

    BeanBuilder<T> beanBuilder = new BeanBuilder<T>(beanManager)
            .readFromType(annotatedType)
            .passivationCapable(true)
            .beanLifecycle(lifecycle);

    return beanBuilder.create();
}
 
Example #3
Source File: BeanProvider.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: MessageHandlingBeanDefinition.java    From cdi with Apache License 2.0 6 votes vote down vote up
static Optional<MessageHandlingBeanDefinition> inspect(Bean<?> bean, Annotated annotated) {
    if (!(annotated instanceof AnnotatedType)) {
        return Optional.empty();
    }
    AnnotatedType at = (AnnotatedType) annotated;
    boolean isEventHandler = CdiUtilities.hasAnnotatedMethod(at, EventHandler.class);
    boolean isQueryHandler = CdiUtilities.hasAnnotatedMethod(at, QueryHandler.class);
    boolean isCommandHandler = CdiUtilities.hasAnnotatedMethod(at, CommandHandler.class);

    if (isEventHandler || isQueryHandler || isCommandHandler) {
        return Optional.of(new MessageHandlingBeanDefinition(bean,
                isEventHandler, isQueryHandler, isCommandHandler));
    }

    return Optional.empty();
}
 
Example #5
Source File: DeltaSpikeProxyContextualLifecycle.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public DeltaSpikeProxyContextualLifecycle(Class<T> targetClass,
                                          Class<H> delegateInvocationHandlerClass,
                                          DeltaSpikeProxyFactory proxyFactory,
                                          BeanManager beanManager)
{
    this.targetClass = targetClass;
    this.delegateInvocationHandlerClass = delegateInvocationHandlerClass;
    this.proxyClass = proxyFactory.getProxyClass(beanManager, targetClass);
    this.delegateMethods = proxyFactory.getDelegateMethods(targetClass);
    this.beanManager = beanManager;
    
    if (!targetClass.isInterface())
    {
        AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(this.targetClass);
        this.injectionTarget = beanManager.createInjectionTarget(annotatedType);
    }
}
 
Example #6
Source File: CDIInstanceManager.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Override
public void newInstance(final Object o) throws IllegalAccessException, InvocationTargetException, NamingException {
    if (WebBeansConfigurationListener.class.isInstance(o) || o.getClass().getName().startsWith("org.apache.catalina.servlets.")) {
        return;
    }

    final BeanManager bm = CDI.current().getBeanManager();
    final AnnotatedType<?> annotatedType = bm.createAnnotatedType(o.getClass());
    final InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
    final CreationalContext<Object> creationalContext = bm.createCreationalContext(null);
    injectionTarget.inject(o, creationalContext);
    try {
        injectionTarget.postConstruct(o);
    } catch (final RuntimeException e) {
        creationalContext.release();
        throw e;
    }
    destroyables.put(o, () -> {
        try {
            injectionTarget.preDestroy(o);
        } finally {
            creationalContext.release();
        }
    });
}
 
Example #7
Source File: AnnotatedMethods.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public static AnnotatedMethod<?> findMethod(final AnnotatedType<?> type, final Method method)
{
    AnnotatedMethod<?> annotatedMethod = null;
    for (final AnnotatedMethod<?> am : type.getMethods())
    {
        if (am.getJavaMember().equals(method))
        {
            annotatedMethod = am;
            break;
        }
    }
    if (annotatedMethod == null)
    {
        throw new IllegalStateException("No annotated method for " + method);
    }
    return annotatedMethod;
}
 
Example #8
Source File: WebContext.java    From tomee with Apache License 2.0 6 votes vote down vote up
private ConstructorInjectionBean<Object> getConstructorInjectionBean(final Class beanClass, final WebBeansContext webBeansContext) {
    if (webBeansContext == null) {
        return null;
    }

    ConstructorInjectionBean<Object> beanDefinition = constructorInjectionBeanCache.get(beanClass);
    if (beanDefinition == null) {
        synchronized (this) {
            beanDefinition = constructorInjectionBeanCache.get(beanClass);
            if (beanDefinition == null) {
                final AnnotatedType annotatedType = webBeansContext.getAnnotatedElementFactory().newAnnotatedType(beanClass);
                if (isWeb(beanClass)) {
                    beanDefinition = new ConstructorInjectionBean<>(webBeansContext, beanClass, annotatedType, false);
                } else {
                    beanDefinition = new ConstructorInjectionBean<>(webBeansContext, beanClass, annotatedType);
                }

                constructorInjectionBeanCache.put(beanClass, beanDefinition);
            }
        }
    }
    return beanDefinition;
}
 
Example #9
Source File: MessageBundleExtension.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
protected void installMessageBundleProducerBeans(@Observes AfterBeanDiscovery abd, BeanManager beanManager)
{
    if (!deploymentErrors.isEmpty())
    {
        abd.addDefinitionError(new IllegalArgumentException("The following MessageBundle problems where found: " +
                Arrays.toString(deploymentErrors.toArray())));
        return;
    }

    MessageBundleExtension parentExtension = ParentExtensionStorage.getParentExtension(this);
    if (parentExtension != null)
    {
        messageBundleTypes.addAll(parentExtension.messageBundleTypes);
    }

    for (AnnotatedType<?> type : messageBundleTypes)
    {
        abd.addBean(createMessageBundleBean(type, beanManager));
    }
}
 
Example #10
Source File: AnnotatedTypeProcessor.java    From krazo with Apache License 2.0 6 votes vote down vote up
private <T> AnnotatedMethod<? super T> getReplacement(AnnotatedType<T> type,
                                                      AnnotatedMethod<? super T> method) {

    // added to methods to intercept calls with our interceptors
    Set<Annotation> markerAnnotations = new LinkedHashSet<>(Arrays.asList(
            () -> ValidationInterceptorBinding.class,
            () -> AroundController.class
    ));

    // drop Hibernate Validator's marker annotations to skip the native validation
    Predicate<Class> annotationBlacklist = clazz -> isHibernateValidatorMarkerAnnotation(clazz);

    if (ControllerUtils.isControllerMethod(method.getJavaMember())) {

        log.log(Level.FINE, "Found controller method: {0}#{1}", new Object[]{
            type.getJavaClass().getName(),
            method.getJavaMember().getName()
        });

        return new AnnotatedMethodWrapper<>(method, markerAnnotations, annotationBlacklist);

    }

    return null;

}
 
Example #11
Source File: AnnotatedTypeProcessor.java    From krazo with Apache License 2.0 6 votes vote down vote up
public <T> AnnotatedType<T> getReplacement(AnnotatedType<T> originalType) {

        boolean modified = false;
        Set<AnnotatedMethod<? super T>> methods = new LinkedHashSet<>();

        for (AnnotatedMethod<? super T> originalMethod : originalType.getMethods()) {
            AnnotatedMethod<? super T> replacement = getReplacement(originalType, originalMethod);
            if (replacement != null) {
                methods.add(replacement);
                modified = true;
            } else {
                methods.add(originalMethod);
            }
        }

        if (modified) {
            return new AnnotatedTypeWrapper<T>(originalType, methods);
        }
        return null;

    }
 
Example #12
Source File: MakeJCacheCDIInterceptorFriendly.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
public HelperBean(final AnnotatedType<CDIJCacheHelper> annotatedType,
                  final InjectionTarget<CDIJCacheHelper> injectionTarget,
                  final String id) {
    this.at = annotatedType;
    this.it = injectionTarget;
    this.id =  "JCS#CDIHelper#" + id;

    this.qualifiers = new HashSet<>();
    this.qualifiers.add(new AnnotationLiteral<Default>() {

        /**
         * 
         */
        private static final long serialVersionUID = 3314657767813459983L;});
    this.qualifiers.add(new AnnotationLiteral<Any>() {

        /**
         * 
         */
        private static final long serialVersionUID = 7419841275942488170L;});
}
 
Example #13
Source File: RouteExtension.java    From weld-vertx with Apache License 2.0 6 votes vote down vote up
private boolean isRouteHandler(AnnotatedType<?> annotatedType) {
    if (!Reflections.isTopLevelOrStaticNestedClass(annotatedType.getJavaClass())) {
        LOGGER.warn("Ignoring {0} - class annotated with @WebRoute must be top-level or static nested class", annotatedType.getJavaClass());
        return false;
    }
    Set<Type> types = new HierarchyDiscovery(annotatedType.getBaseType()).getTypeClosure();
    for (Type type : types) {
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            if (parameterizedType.getRawType().equals(Handler.class)) {
                Type[] arguments = parameterizedType.getActualTypeArguments();
                if (arguments.length == 1 && arguments[0].equals(RoutingContext.class)) {
                    return true;
                }
            }
        }
    }
    LOGGER.warn("Ignoring {0} - class annotated with @WebRoute must implement io.vertx.core.Handler<RoutingContext>", annotatedType.getJavaClass());
    return false;
}
 
Example #14
Source File: ValidatorBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
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<>(context, it, instance));

    return instance;
}
 
Example #15
Source File: ConfigProducerUtil.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
static String getConfigKey(InjectionPoint ip, ConfigProperty configProperty) {
    String key = configProperty.name();
    if (!key.trim().isEmpty()) {
        return key;
    }
    if (ip.getAnnotated() instanceof AnnotatedMember) {
        AnnotatedMember<?> member = (AnnotatedMember<?>) ip.getAnnotated();
        AnnotatedType<?> declaringType = member.getDeclaringType();
        if (declaringType != null) {
            String[] parts = declaringType.getJavaClass().getCanonicalName().split("\\.");
            StringBuilder sb = new StringBuilder(parts[0]);
            for (int i = 1; i < parts.length; i++) {
                sb.append(".").append(parts[i]);
            }
            sb.append(".").append(member.getJavaMember().getName());
            return sb.toString();
        }
    }
    throw InjectionMessages.msg.noConfigPropertyDefaultName(ip);
}
 
Example #16
Source File: Jsf2BeanWrapper.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
Jsf2BeanWrapper(AnnotatedType wrapped,
                Class<? extends Annotation> cdiScopeAnnotation,
                Class<? extends Annotation> jsf2ScopeAnnotation)
{
    this.wrapped = wrapped;
    Set<Annotation> originalAnnotationSet = wrapped.getAnnotations();
    this.annotations = new HashMap<Class<? extends Annotation>, Annotation>(originalAnnotationSet.size());

    for (Annotation originalAnnotation : originalAnnotationSet)
    {
        if (!originalAnnotation.annotationType().equals(jsf2ScopeAnnotation))
        {
            this.annotations.put(originalAnnotation.annotationType(), originalAnnotation);
        }
    }

    this.annotations.put(cdiScopeAnnotation, AnnotationInstanceProvider.of(cdiScopeAnnotation));

    this.annotationSet = new HashSet<Annotation>(this.annotations.size());
    this.annotationSet.addAll(this.annotations.values());
}
 
Example #17
Source File: BValInterceptor.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void initClassConfig(Class<?> targetClass) {
    if (classConfiguration == null) {
        synchronized (this) {
            if (classConfiguration == null) {
                final AnnotatedType<?> annotatedType = CDI.current().getBeanManager()
                        .createAnnotatedType(targetClass);

                if (annotatedType.isAnnotationPresent(ValidateOnExecution.class)) {
                    // implicit does not apply at the class level:
                    classConfiguration = ExecutableTypes.interpret(
                            removeFrom(Arrays.asList(annotatedType.getAnnotation(ValidateOnExecution.class).type()),
                                    ExecutableType.IMPLICIT));
                } else {
                    classConfiguration = globalConfiguration.getGlobalExecutableTypes();
                }
            }
        }
    }
}
 
Example #18
Source File: MessageBundleExtension.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
protected void detectInterfaces(@Observes ProcessAnnotatedType processAnnotatedType)
{
    if (!isActivated)
    {
        return;
    }

    AnnotatedType<?> type = processAnnotatedType.getAnnotatedType();

    if (type.isAnnotationPresent(MessageBundle.class))
    {
        if (validateMessageBundle(type.getJavaClass()))
        {
            messageBundleTypes.add(type);
        }
    }
}
 
Example #19
Source File: MakeJCacheCDIInterceptorFriendly.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
protected void addHelper(final @Observes AfterBeanDiscovery afterBeanDiscovery,
                         final BeanManager bm)
{
    if (!needHelper) {
        return;
    }
    /* CDI >= 1.1 only. Actually we shouldn't go here with CDI 1.1 since we defined the annotated type for the helper
    final AnnotatedType<CDIJCacheHelper> annotatedType = bm.createAnnotatedType(CDIJCacheHelper.class);
    final BeanAttributes<CDIJCacheHelper> beanAttributes = bm.createBeanAttributes(annotatedType);
    final InjectionTarget<CDIJCacheHelper> injectionTarget = bm.createInjectionTarget(annotatedType);
    final Bean<CDIJCacheHelper> bean = bm.createBean(beanAttributes, CDIJCacheHelper.class, new InjectionTargetFactory<CDIJCacheHelper>() {
        @Override
        public InjectionTarget<CDIJCacheHelper> createInjectionTarget(Bean<CDIJCacheHelper> bean) {
            return injectionTarget;
        }
    });
    */
    final AnnotatedType<CDIJCacheHelper> annotatedType = bm.createAnnotatedType(CDIJCacheHelper.class);
    final InjectionTarget<CDIJCacheHelper> injectionTarget = bm.createInjectionTarget(annotatedType);
    final HelperBean bean = new HelperBean(annotatedType, injectionTarget, findIdSuffix());
    afterBeanDiscovery.addBean(bean);
}
 
Example #20
Source File: JerseyCdiExtension.java    From hammock with Apache License 2.0 5 votes vote down vote up
public <T> void observeResources(@WithAnnotations({ Path.class }) @Observes ProcessAnnotatedType<T> event) {
    AnnotatedType<T> annotatedType = event.getAnnotatedType();

    if (!annotatedType.getJavaClass().isInterface()) {
        this.resources.add(annotatedType.getJavaClass());
    }
}
 
Example #21
Source File: AnnotatedTypeBuilderTest.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Test
public void buildValidAnnotationAnnotatedType()
{
    final AnnotatedTypeBuilder<Small> builder = new AnnotatedTypeBuilder<Small>();
    builder.readFromType(Small.class);
    final AnnotatedType<Small> smallAnnotatedType = builder.create();

    assertThat(smallAnnotatedType.getMethods().size(), is(1));
    assertThat(smallAnnotatedType.getConstructors().size(), is(0));
    assertThat(smallAnnotatedType.getFields().size(), is(0));
}
 
Example #22
Source File: JerseyCdiExtension.java    From hammock with Apache License 2.0 5 votes vote down vote up
public <T> void observeProviders(@WithAnnotations({ Provider.class }) @Observes ProcessAnnotatedType<T> event) {
    AnnotatedType<T> annotatedType = event.getAnnotatedType();

    if (!annotatedType.getJavaClass().isInterface()) {
        this.providers.add(annotatedType.getJavaClass());
    }
}
 
Example #23
Source File: BValCdiFilter.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accept(final AnnotatedType<?> annotatedType) {
    final String name = annotatedType.getJavaClass().getName();
    if (name.startsWith("org.apache.openejb.")) {
        final String sub = name.substring("org.apache.openejb.".length());
        return !sub.startsWith("cdi.transactional") && !sub.startsWith("resource.activemq.jms2");
    }
    return delegate.accept(name);
}
 
Example #24
Source File: BeanTestExtension.java    From BeanTest with Apache License 2.0 5 votes vote down vote up
/**
 * Adds {@link Transactional} and {@link RequestScoped} to the given annotated type and converts
 * its EJB injection points into CDI injection points (i.e. it adds the {@link Inject})
 * @param <X> the type of the annotated type
 * @param pat the process annotated type.
 */
private <X> void modifiyAnnotatedTypeMetadata(ProcessAnnotatedType<X> pat) {
    AnnotatedType at = pat.getAnnotatedType();
    
    AnnotatedTypeBuilder<X> builder = new AnnotatedTypeBuilder<X>().readFromType(at);
    builder.addToClass(AnnotationInstances.TRANSACTIONAL).addToClass(AnnotationInstances.REQUEST_SCOPED);

    InjectionHelper.addInjectAnnotation(at, builder);
    //Set the wrapper instead the actual annotated type
    pat.setAnnotatedType(builder.create());

}
 
Example #25
Source File: MeecrowaveExtension.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
void onPat(@Observes final ProcessAnnotatedType<?> pat, final BeanManager bm) {
    final AnnotatedType<?> at = pat.getAnnotatedType();
    if (isJaxRsEndpoint(bm, at)) {
        pat.setAnnotatedType(new JAXRSFIeldInjectionAT(this, at));
    } else if (isVetoedMeecrowaveCore(at.getJavaClass().getName())) {
        pat.veto();
    }
}
 
Example #26
Source File: Injector.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
public static CreationalContext<?> inject(final Object testInstance) {
    if (testInstance == null) {
        return null;
    }
    final BeanManager bm = CDI.current().getBeanManager();
    final AnnotatedType<?> annotatedType = bm.createAnnotatedType(testInstance.getClass());
    final InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
    final CreationalContext<?> creationalContext = bm.createCreationalContext(null);
    injectionTarget.inject(testInstance, creationalContext);
    return creationalContext;
}
 
Example #27
Source File: PartialBeanBindingExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
protected <T> Bean<T> createPartialBean(Class<T> beanClass, PartialBeanDescriptor descriptor,
        AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager)
{
    if (descriptor.getHandler() == null)
    {
        afterBeanDiscovery.addDefinitionError(new IllegalStateException("A class which implements "
                + InvocationHandler.class.getName()
                + " and is annotated with @" + descriptor.getBinding().getName()
                + " is needed as a handler for " + beanClass.getName()
                + ". See the documentation about @" + PartialBeanBinding.class.getName() + "."));

        return null;
    }

    AnnotatedType<T> annotatedType = new AnnotatedTypeBuilder<T>().readFromType(beanClass).create();

    DeltaSpikeProxyContextualLifecycle lifecycle = new DeltaSpikeProxyContextualLifecycle(beanClass,
            descriptor.getHandler(),
            PartialBeanProxyFactory.getInstance(),
            beanManager);

    BeanBuilder<T> beanBuilder = new BeanBuilder<T>(beanManager)
            .readFromType(annotatedType)
            .passivationCapable(true)
            .beanLifecycle(lifecycle);

    return beanBuilder.create();
}
 
Example #28
Source File: AnnotatedTypeBuilderTest.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Test
public void testEnumWithParam()
{
    final AnnotatedTypeBuilder<EnumWithParams> builder = new AnnotatedTypeBuilder<EnumWithParams>();
    builder.readFromType(EnumWithParams.class);
    builder.addToClass(new AnnotationLiteral<Default>() {});

    AnnotatedType<EnumWithParams> newAt = builder.create();
    assertNotNull(newAt);
}
 
Example #29
Source File: AnnotatedMemberImpl.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
protected AnnotatedMemberImpl(AnnotatedType<X> declaringType, M member, Class<?> memberType,
                              AnnotationStore annotations, Type genericType, Type overriddenType)
{
    super(memberType, annotations, genericType, overriddenType);
    this.declaringType = declaringType;
    javaMember = member;
}
 
Example #30
Source File: SecurityMetaDataStorage.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
void addSecuredType(AnnotatedType<?> annotatedType)
{
    for (AnnotatedMethod<?> securedMethod : annotatedType.getMethods())
    {
        addSecuredMethod(securedMethod);
    }
}