javax.enterprise.inject.spi.DefinitionException Java Examples

The following examples show how to use javax.enterprise.inject.spi.DefinitionException. 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: Injection.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param beanTarget
 * @param beanDeployment
 * @return the list of injections
 */
static List<Injection> forBean(AnnotationTarget beanTarget, BeanInfo declaringBean, BeanDeployment beanDeployment,
        InjectionPointModifier transformer) {
    if (Kind.CLASS.equals(beanTarget.kind())) {
        List<Injection> injections = new ArrayList<>();
        forClassBean(beanTarget.asClass(), beanTarget.asClass(), beanDeployment, injections, transformer, false);
        Set<AnnotationTarget> injectConstructors = injections.stream().filter(Injection::isConstructor)
                .map(Injection::getTarget).collect(Collectors.toSet());
        if (injectConstructors.size() > 1) {
            throw new DefinitionException(
                    "Multiple @Inject constructors found on " + beanTarget.asClass().name() + ":\n"
                            + injectConstructors.stream().map(Object::toString).collect(Collectors.joining("\n")));
        }
        return injections;
    } else if (Kind.METHOD.equals(beanTarget.kind())) {
        if (beanTarget.asMethod().parameters().isEmpty()) {
            return Collections.emptyList();
        }
        // All parameters are injection points
        return Collections.singletonList(
                new Injection(beanTarget.asMethod(),
                        InjectionPointInfo.fromMethod(beanTarget.asMethod(), declaringBean.getImplClazz(),
                                beanDeployment, transformer)));
    }
    throw new IllegalArgumentException("Unsupported annotation target");
}
 
Example #2
Source File: CdiEjbBean.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public InjectionTarget<T> createInjectionTarget(final Bean<T> bean) {
    final EjbInjectionTargetImpl<T> injectionTarget = new EjbInjectionTargetImpl<>(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<>(injectionTarget, it);
    }
    return it;
}
 
Example #3
Source File: CheckInjectionPointUsage.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void validate(final EjbModule ejbModule) {
    if (ejbModule.getBeans() == null) {
        return;
    }

    try {
        for (final Field field : ejbModule.getFinder().findAnnotatedFields(Inject.class)) {
            if (!field.getType().equals(InjectionPoint.class) || !HttpServlet.class.isAssignableFrom(field.getDeclaringClass())) {
                continue;
            }

            final Annotation[] annotations = field.getAnnotations();
            if (annotations.length == 1 || (annotations.length == 2 && field.getAnnotation(Default.class) != null)) {
                throw new DefinitionException("Can't inject InjectionPoint in " + field.getDeclaringClass());
            } // else we should check is there is no other qualifier than @Default but too early
        }
    } catch (final NoClassDefFoundError noClassDefFoundError) {
        // ignored: can't check but maybe it is because of an optional dep so ignore it
        // not important to skip it since the failure will be reported elsewhere
        // this validator doesn't check it
    }
}
 
Example #4
Source File: AppValidator.java    From tomee with Apache License 2.0 6 votes vote down vote up
public AppModule validate(final AppModule appModule) {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(appModule.getClassLoader()); // be sure to not mix classloaders
    try {
        final ValidationRule[] rules = getValidationRules();
        for (ValidationRule rule : rules) {
            rule.validate(appModule);
        }
    } catch (final DefinitionException de) {
        throw de;
    } catch (final Throwable e) {
        e.printStackTrace(System.out);
        final ValidationError err = new ValidationError("cannot.validate");
        err.setCause(e);
        err.setDetails(e.getMessage());
        appModule.getValidation().addError(err);
    } finally {
        Thread.currentThread().setContextClassLoader(loader);
    }
    return appModule;
}
 
Example #5
Source File: Assembler.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void checkBuiltInResourceTypes(final ResourceReference reference, final String jndi) {
    final Class<?> resourceType = reference.getResourceType();
    if ("java:comp/BeanManager".equals(jndi) && resourceType != BeanManager.class) {
        throw new DefinitionException(
                "Resource " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast to a BeanManager");
    } else if ("java:comp/TransactionSynchronizationRegistry".equals(jndi) && resourceType != TransactionSynchronizationRegistry.class) {
        throw new DefinitionException(
                "Resource " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast to a TransactionSynchronizationRegistry");
    } else if ("java:comp/TransactionManager".equals(jndi) && resourceType != TransactionManager.class) {
        throw new DefinitionException(
                "Resource " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast to a TransactionManager");
    } else if ("java:comp/ValidatorFactory".equals(jndi) && resourceType != ValidatorFactory.class) {
        throw new DefinitionException(
                "Resource " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast to a ValidatorFactory");
    } else if ("java:comp/Validator".equals(jndi) && resourceType != Validator.class) {
        throw new DefinitionException(
                "Resource " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast to a Validator");
    }
}
 
Example #6
Source File: SpringDIProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Get a single scope from the available options or throw a {@link DefinitionException} explaining
 * where the annotations conflict.
 *
 * @param clazz The class annotated with the scopes
 * @param scopes The scopes from the class and its stereotypes
 * @param scopeStereotypes The stereotype annotations that declared the conflicting scopes
 * @return The scope for the target class
 */
private DotName validateScope(final ClassInfo clazz, final Set<DotName> scopes, final Set<DotName> scopeStereotypes) {
    final int size = scopes.size();
    switch (size) {
        case 0:
            // Spring default
            return CDI_SINGLETON_ANNOTATION;
        case 1:
            return scopes.iterator().next();
        default:
            throw new DefinitionException(
                    "Components annotated with multiple conflicting scopes must declare an explicit @Scope. "
                            + clazz.name() + " declares scopes: "
                            + scopes.stream().map(DotName::toString).collect(Collectors.joining(", "))
                            + " through the stereotypes: "
                            + scopeStereotypes.stream().map(DotName::toString)
                                    .collect(Collectors.joining(", ")));
    }
}
 
Example #7
Source File: DisposerInfo.java    From quarkus with Apache License 2.0 5 votes vote down vote up
MethodParameterInfo initDisposedParam(MethodInfo disposerMethod) {
    List<MethodParameterInfo> disposedParams = new ArrayList<>();
    for (AnnotationInstance annotation : disposerMethod.annotations()) {
        if (Kind.METHOD_PARAMETER.equals(annotation.target().kind()) && annotation.name().equals(DotNames.DISPOSES)) {
            disposedParams.add(annotation.target().asMethodParameter());
        }
    }
    if (disposedParams.isEmpty()) {
        throw new DefinitionException("No disposed parameters found for " + disposerMethod);
    } else if (disposedParams.size() > 1) {
        throw new DefinitionException("Multiple disposed parameters found for " + disposerMethod);
    }
    return disposedParams.get(0);
}
 
Example #8
Source File: CdiEjbBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
public CdiEjbBean(final BeanContext bc, final WebBeansContext webBeansContext, final Class beanClass, final AnnotatedType<T> at,
                  final InjectionTargetFactoryImpl<T> factory, final BeanAttributes<T> attributes) {
    super(webBeansContext, toSessionType(bc.getComponentType()), at,
            new EJBBeanAttributesImpl<T>(bc, attributes),
            beanClass, factory);
    this.beanContext = bc;
    bc.set(Bean.class, this);
    passivatingId = bc.getDeploymentID() + getReturnType().getName();

    final boolean stateful = BeanType.STATEFUL.equals(bc.getComponentType());
    final boolean isDependent = getScope().equals(Dependent.class);
    isDependentAndStateful = isDependent && stateful;
    if (webBeansContext.getBeanManagerImpl().isPassivatingScope(getScope()) && stateful) {
        if (!getBeanContext().isPassivable()) {
            throw new DefinitionException(
                    getBeanContext().getBeanClass()
                            + " is a not apssivation-capable @Stateful with a scope "
                            + getScope().getSimpleName() + " which need passivation");
        }
        passivable = true;
    } else {
        passivable = false;
    }
    if (!isDependent) {
        for (final Type type : attributes.getTypes()) {
            if (ParameterizedType.class.isInstance(type)) {
                throw new DefinitionException("Parameterized session bean should be @Dependent: " + beanClass);
            }
        }
    }
    if (getAnnotatedType().isAnnotationPresent(Interceptor.class) || getAnnotatedType().isAnnotationPresent(Decorator.class)) {
        throw new DefinitionException("An EJB can't be an interceptor or a decorator: " + beanClass);
    }
}
 
Example #9
Source File: BeanDeployment.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private DisposerInfo findDisposer(BeanInfo declaringBean, AnnotationTarget annotationTarget, List<DisposerInfo> disposers) {
    List<DisposerInfo> found = new ArrayList<>();
    Type beanType;
    Set<AnnotationInstance> qualifiers = new HashSet<>();
    List<AnnotationInstance> allAnnotations;
    if (Kind.FIELD.equals(annotationTarget.kind())) {
        allAnnotations = annotationTarget.asField().annotations();
        beanType = annotationTarget.asField().type();
    } else if (Kind.METHOD.equals(annotationTarget.kind())) {
        allAnnotations = annotationTarget.asMethod().annotations();
        beanType = annotationTarget.asMethod().returnType();
    } else {
        throw new RuntimeException("Unsupported annotation target: " + annotationTarget);
    }
    allAnnotations.forEach(a -> extractQualifiers(a).forEach(qualifiers::add));
    for (DisposerInfo disposer : disposers) {
        if (disposer.getDeclaringBean().equals(declaringBean)) {
            boolean hasQualifier = true;
            for (AnnotationInstance disposerQualifier : disposer.getDisposedParameterQualifiers()) {
                if (!Beans.hasQualifier(getQualifier(disposerQualifier.name()), disposerQualifier, qualifiers)) {
                    hasQualifier = false;
                }
            }
            if (hasQualifier && beanResolver.matches(beanType, disposer.getDisposedParameterType())) {
                found.add(disposer);
            }
        }
    }
    if (found.size() > 1) {
        throw new DefinitionException("Multiple disposer methods found for " + annotationTarget);
    }
    return found.isEmpty() ? null : found.get(0);
}
 
Example #10
Source File: BeanDeployment.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static ScopeInfo getValidScope(Collection<ScopeInfo> stereotypeScopes, AnnotationTarget target) {
    switch (stereotypeScopes.size()) {
        case 0:
            return null;
        case 1:
            return stereotypeScopes.iterator().next();
        default:
            throw new DefinitionException("All stereotypes must specify the same scope or the bean must declare a scope: "
                    + target + " declares scopes " + stereotypeScopes.stream().map(ScopeInfo::getDotName)
                            .map(DotName::toString).collect(Collectors.joining(", ")));
    }
}
 
Example #11
Source File: SwarmDeploymentExceptionTransformer.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public Throwable transform(Throwable throwable) {

        // Arquillian sometimes returns InvocationException with nested
        // exception and sometimes exception itself
        @SuppressWarnings("unchecked")
        List<Throwable> throwableList = ExceptionUtils.getThrowableList(throwable);
        if (throwableList.isEmpty())
            return throwable;

        Throwable root = null;

        if (throwableList.size() == 1) {
            root = throwable;
        } else {
            root = ExceptionUtils.getRootCause(throwable);
        }

        if (root instanceof DeploymentException || root instanceof DefinitionException) {
            return root;
        }
        if (isFragmentFound(DEPLOYMENT_EXCEPTION_FRAGMENTS, root)) {
            return new DeploymentException(root.getMessage());
        }
        if (isFragmentFound(DEFINITION_EXCEPTION_FRAGMENTS, root)) {
            return new DefinitionException(root.getMessage());
        }
        return throwable;
    }
 
Example #12
Source File: SpringDIProcessorTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void getAnnotationsToAddMultipleNamesThrows() {
    final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
    final ClassInfo target = index.getClassByName(DotName.createSimple(ConflictNamedBean.class.getName()));

    Assertions.assertThrows(DefinitionException.class, () -> {
        processor.getAnnotationsToAdd(target, scopes, null);
    });
}
 
Example #13
Source File: SpringDIProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Get the name of a bean or throw a {@link DefinitionException} if it has more than one name
 *
 * @param clazz The class annotated with the names
 * @param names The names
 * @return The bane name
 */
private String validateName(final ClassInfo clazz, final Set<String> names) {
    final int size = names.size();
    switch (size) {
        case 0:
            return null;
        case 1:
            return names.iterator().next();
        default:
            throw new DefinitionException(
                    "Component " + clazz.name() + " is annotated with multiple conflicting names: "
                            + String.join(", ", names));
    }
}
 
Example #14
Source File: Interceptors.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param interceptorClass
 * @param beanDeployment
 * @return a new interceptor info
 */
static InterceptorInfo createInterceptor(ClassInfo interceptorClass, BeanDeployment beanDeployment,
        InjectionPointModifier transformer, AnnotationStore store) {
    Set<AnnotationInstance> bindings = new HashSet<>();
    Integer priority = 0;
    boolean priorityDeclared = false;
    for (AnnotationInstance annotation : store.getAnnotations(interceptorClass)) {
        if (beanDeployment.getInterceptorBinding(annotation.name()) != null) {
            bindings.add(annotation);
            // can also be a transitive binding
            Set<AnnotationInstance> transitiveInterceptorBindings = beanDeployment
                    .getTransitiveInterceptorBindings(annotation.name());
            if (transitiveInterceptorBindings != null) {
                bindings.addAll(transitiveInterceptorBindings);
            }
        } else if (annotation.name().equals(DotNames.PRIORITY)) {
            priority = annotation.value().asInt();
            priorityDeclared = true;
        }
    }
    if (bindings.isEmpty()) {
        throw new DefinitionException("Interceptor has no bindings: " + interceptorClass);
    }
    if (!priorityDeclared) {
        LOGGER.info("An interceptor " + interceptorClass + " does not declare any @Priority. " +
                "It will be assigned a default priority value of 0.");
    }
    return new InterceptorInfo(interceptorClass, beanDeployment,
            bindings.size() == 1 ? Collections.singleton(bindings.iterator().next())
                    : Collections.unmodifiableSet(bindings),
            Injection.forBean(interceptorClass, null, beanDeployment, transformer), priority);
}
 
Example #15
Source File: ObserverInfo.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static MethodParameterInfo initEventParam(MethodInfo observerMethod, BeanDeployment beanDeployment) {
    List<MethodParameterInfo> eventParams = new ArrayList<>();
    for (AnnotationInstance annotation : beanDeployment.getAnnotations(observerMethod)) {
        if (Kind.METHOD_PARAMETER == annotation.target().kind()
                && (annotation.name().equals(DotNames.OBSERVES) || annotation.name().equals(DotNames.OBSERVES_ASYNC))) {
            eventParams.add(annotation.target().asMethodParameter());
        }
    }
    if (eventParams.isEmpty()) {
        throw new DefinitionException("No event parameters found for " + observerMethod);
    } else if (eventParams.size() > 1) {
        throw new DefinitionException("Multiple event parameters found for " + observerMethod);
    }
    return eventParams.get(0);
}
 
Example #16
Source File: StereotypeOnMethodTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that DefinitionException is thrown if there is a stereotype applied on a non-producer method.
 */
@Test
public void testStereotypeOnNonProducerMethod() {
    Throwable error = container.getFailure();
    assertNotNull(error);
    assertTrue(error instanceof DefinitionException);
    assertTrue(error.getMessage().contains("auditedMethod"));
}
 
Example #17
Source File: InvalidSubscriberSignatureTest.java    From microprofile-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Deployment(managed = false, name = "incoming-returning-non-void-cs")
@ShouldThrowException(value = DefinitionException.class, testable = true)
public static Archive<JavaArchive> incomingReturningNonVoidCompletionStage() {
    JavaArchive archive = ShrinkWrap.create(JavaArchive.class)
        .addClasses(IncomingReturningNonVoidCompletionStage.class, ArchiveExtender.class)
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");

    ServiceLoader.load(ArchiveExtender.class).iterator().forEachRemaining(ext -> ext.extend(archive));
    return archive;
}
 
Example #18
Source File: InvalidSubscriberSignatureTest.java    From microprofile-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Deployment(managed = false, name = "incoming-returning-object")
@ShouldThrowException(value = DefinitionException.class, testable = true)
public static Archive<JavaArchive> incomingReturningNonVoid() {
    JavaArchive archive = ShrinkWrap.create(JavaArchive.class)
        .addClasses(IncomingReturningNonVoid.class, ArchiveExtender.class)
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");

    ServiceLoader.load(ArchiveExtender.class).iterator().forEachRemaining(ext -> ext.extend(archive));
    return archive;
}
 
Example #19
Source File: StereotypeOnFieldTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that DefinitionException is thrown if there is a stereotype applied on a non-producer field.
 */
@Test
public void testStereotypeOnNonProducerField() {
    Throwable error = container.getFailure();
    assertNotNull(error);
    assertTrue(error instanceof DefinitionException);
    assertTrue(error.getMessage().contains("auditedField"));
}
 
Example #20
Source File: ProducerFieldWithInjectTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testFailure() {
    Throwable error = container.getFailure();
    assertNotNull(error);
    assertTrue(error instanceof DefinitionException);
}
 
Example #21
Source File: ClassBeanMultipleScopesTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testFailure() {
    Throwable error = container.getFailure();
    assertNotNull(error);
    assertTrue(error instanceof DefinitionException);
}
 
Example #22
Source File: ProducerFieldMultipleScopesTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testFailure() {
    Throwable error = container.getFailure();
    assertNotNull(error);
    assertTrue(error instanceof DefinitionException);
}
 
Example #23
Source File: ProducerMethodMultipleScopesTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testFailure() {
    Throwable error = container.getFailure();
    assertNotNull(error);
    assertTrue(error instanceof DefinitionException);
}
 
Example #24
Source File: Beans.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private static DefinitionException multipleScopesFound(String baseMessage, List<ScopeInfo> scopes) {
    return new DefinitionException(baseMessage + " declares multiple scope type annotations: "
            + scopes.stream().map(s -> s.getDotName().toString()).collect(Collectors.joining(", ")));
}
 
Example #25
Source File: MultiInjectConstructorFailureTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testInjection() {
    Throwable error = container.getFailure();
    assertNotNull(error);
    assertTrue(error instanceof DefinitionException);
}
 
Example #26
Source File: EventMetadataWrongInjectionTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testMetadata() {
    Throwable error = container.getFailure();
    assertNotNull(error);
    assertTrue(error instanceof DefinitionException);
}
 
Example #27
Source File: ProviderExceptions.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Message(id = 49, value = "Invalid method annotated with %s: %s - when returning a %s, one parameter is expected")
DefinitionException definitionOnParam(String annotation, String methodAsString, String returnType);
 
Example #28
Source File: ProviderExceptions.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Message(id = 48, value = "Invalid method annotated with %s: %s - the returned Subscriber must declare a type parameter")
DefinitionException definitionSubscriberTypeParam(String annotation, String methodAsString);
 
Example #29
Source File: ProviderExceptions.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Message(id = 47, value = "Invalid method annotated with %s: %s - when returning a Subscriber or a SubscriberBuilder, no parameters are expected")
DefinitionException definitionNoParamOnSubscriber(String annotation, String methodAsString);
 
Example #30
Source File: ProviderExceptions.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Message(id = 6, value = "Invalid method annotated with %s: %s - The @Acknowledgment annotation is only supported for method annotated with @Incoming")
DefinitionException definitionExceptionUnsupported(String annotation, String methodAsString);