Search in sources :

Example 36 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project spring-framework by spring-projects.

the class AbstractExpressionEvaluatingCondition method evaluateExpression.

private <A extends Annotation> boolean evaluateExpression(String expression, boolean loadContext, Class<A> annotationType, ExtensionContext context) {
    Assert.state(context.getElement().isPresent(), "No AnnotatedElement");
    AnnotatedElement element = context.getElement().get();
    GenericApplicationContext gac = null;
    ApplicationContext applicationContext;
    if (loadContext) {
        applicationContext = SpringExtension.getApplicationContext(context);
    } else {
        gac = new GenericApplicationContext();
        gac.refresh();
        applicationContext = gac;
    }
    if (!(applicationContext instanceof ConfigurableApplicationContext)) {
        if (logger.isWarnEnabled()) {
            String contextType = applicationContext.getClass().getName();
            logger.warn(String.format("@%s(\"%s\") could not be evaluated on [%s] since the test " + "ApplicationContext [%s] is not a ConfigurableApplicationContext", annotationType.getSimpleName(), expression, element, contextType));
        }
        return false;
    }
    ConfigurableBeanFactory configurableBeanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
    BeanExpressionResolver expressionResolver = configurableBeanFactory.getBeanExpressionResolver();
    Assert.state(expressionResolver != null, "No BeanExpressionResolver");
    BeanExpressionContext beanExpressionContext = new BeanExpressionContext(configurableBeanFactory, null);
    Object result = expressionResolver.evaluate(configurableBeanFactory.resolveEmbeddedValue(expression), beanExpressionContext);
    if (gac != null) {
        gac.close();
    }
    if (result instanceof Boolean) {
        return (Boolean) result;
    } else if (result instanceof String) {
        String str = ((String) result).trim().toLowerCase();
        if ("true".equals(str)) {
            return true;
        }
        Assert.state("false".equals(str), () -> String.format("@%s(\"%s\") on %s must evaluate to \"true\" or \"false\", not \"%s\"", annotationType.getSimpleName(), expression, element, result));
        return false;
    } else {
        String message = String.format("@%s(\"%s\") on %s must evaluate to a String or a Boolean, not %s", annotationType.getSimpleName(), expression, element, (result != null ? result.getClass().getName() : "null"));
        throw new IllegalStateException(message);
    }
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) ApplicationContext(org.springframework.context.ApplicationContext) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) BeanExpressionResolver(org.springframework.beans.factory.config.BeanExpressionResolver) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) AnnotatedElement(java.lang.reflect.AnnotatedElement) BeanExpressionContext(org.springframework.beans.factory.config.BeanExpressionContext)

Example 37 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project spring-framework by spring-projects.

the class AbstractExpressionEvaluatingCondition method evaluateAnnotation.

/**
 * Evaluate the expression configured via the supplied annotation type on
 * the {@link AnnotatedElement} for the supplied {@link ExtensionContext}.
 * @param annotationType the type of annotation to process
 * @param expressionExtractor a function that extracts the expression from
 * the annotation
 * @param reasonExtractor a function that extracts the reason from the
 * annotation
 * @param loadContextExtractor a function that extracts the {@code loadContext}
 * flag from the annotation
 * @param enabledOnTrue indicates whether the returned {@code ConditionEvaluationResult}
 * should be {@link ConditionEvaluationResult#enabled enabled} if the expression
 * evaluates to {@code true}
 * @param context the {@code ExtensionContext}
 * @return {@link ConditionEvaluationResult#enabled enabled} if the container
 * or test should be enabled; otherwise {@link ConditionEvaluationResult#disabled disabled}
 */
protected <A extends Annotation> ConditionEvaluationResult evaluateAnnotation(Class<A> annotationType, Function<A, String> expressionExtractor, Function<A, String> reasonExtractor, Function<A, Boolean> loadContextExtractor, boolean enabledOnTrue, ExtensionContext context) {
    Assert.state(context.getElement().isPresent(), "No AnnotatedElement");
    AnnotatedElement element = context.getElement().get();
    Optional<A> annotation = findMergedAnnotation(element, annotationType);
    if (!annotation.isPresent()) {
        String reason = String.format("%s is enabled since @%s is not present", element, annotationType.getSimpleName());
        if (logger.isDebugEnabled()) {
            logger.debug(reason);
        }
        return ConditionEvaluationResult.enabled(reason);
    }
    String expression = annotation.map(expressionExtractor).map(String::trim).filter(StringUtils::hasLength).orElseThrow(() -> new IllegalStateException(String.format("The expression in @%s on [%s] must not be blank", annotationType.getSimpleName(), element)));
    boolean loadContext = loadContextExtractor.apply(annotation.get());
    boolean evaluatedToTrue = evaluateExpression(expression, loadContext, annotationType, context);
    ConditionEvaluationResult result;
    if (evaluatedToTrue) {
        String adjective = (enabledOnTrue ? "enabled" : "disabled");
        String reason = annotation.map(reasonExtractor).filter(StringUtils::hasText).orElseGet(() -> String.format("%s is %s because @%s(\"%s\") evaluated to true", element, adjective, annotationType.getSimpleName(), expression));
        if (logger.isInfoEnabled()) {
            logger.info(reason);
        }
        result = (enabledOnTrue ? ConditionEvaluationResult.enabled(reason) : ConditionEvaluationResult.disabled(reason));
    } else {
        String adjective = (enabledOnTrue ? "disabled" : "enabled");
        String reason = String.format("%s is %s because @%s(\"%s\") did not evaluate to true", element, adjective, annotationType.getSimpleName(), expression);
        if (logger.isDebugEnabled()) {
            logger.debug(reason);
        }
        result = (enabledOnTrue ? ConditionEvaluationResult.disabled(reason) : ConditionEvaluationResult.enabled(reason));
    }
    // See https://github.com/spring-projects/spring-framework/issues/26694
    if (loadContext && result.isDisabled() && element instanceof Class) {
        Class<?> testClass = (Class<?>) element;
        DirtiesContext dirtiesContext = TestContextAnnotationUtils.findMergedAnnotation(testClass, DirtiesContext.class);
        if (dirtiesContext != null) {
            HierarchyMode hierarchyMode = dirtiesContext.hierarchyMode();
            SpringExtension.getTestContextManager(context).getTestContext().markApplicationContextDirty(hierarchyMode);
        }
    }
    return result;
}
Also used : HierarchyMode(org.springframework.test.annotation.DirtiesContext.HierarchyMode) ConditionEvaluationResult(org.junit.jupiter.api.extension.ConditionEvaluationResult) DirtiesContext(org.springframework.test.annotation.DirtiesContext) AnnotatedElement(java.lang.reflect.AnnotatedElement)

Example 38 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project hive by apache.

the class Log4jConfigExtension method beforeEach.

@Override
public void beforeEach(ExtensionContext context) throws Exception {
    if (!LOCK.tryLock(1, TimeUnit.MINUTES)) {
        throw new IllegalStateException("Lock acquisition failed cause another test is using a custom Log4j configuration.");
    }
    assert oldConfig == null;
    LoggerContext ctx = LoggerContext.getContext(false);
    oldConfig = ctx.getConfiguration();
    Optional<AnnotatedElement> element = context.getElement();
    if (!element.isPresent()) {
        throw new IllegalStateException("The extension needs an annotated method");
    }
    Log4jConfig annotation = element.get().getAnnotation(Log4jConfig.class);
    if (annotation == null) {
        throw new IllegalStateException(Log4jConfig.class.getSimpleName() + " annotation is missing.");
    }
    String configFileName = annotation.value();
    URL config = Log4jConfig.class.getClassLoader().getResource(configFileName);
    if (config == null) {
        throw new IllegalStateException("File " + configFileName + " was not found in resources.");
    }
    ctx.setConfigLocation(config.toURI());
}
Also used : AnnotatedElement(java.lang.reflect.AnnotatedElement) LoggerContext(org.apache.logging.log4j.core.LoggerContext) URL(java.net.URL)

Example 39 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project uPortal by Jasig.

the class ModelAttributeService method gatherModelAttributes.

/* package-private */
Map<String, Object> gatherModelAttributes(String viewName, HttpServletRequest req, HttpServletResponse res, PortalRequest portalRequest, Bearer bearer, Preferences preferences, Definition definition) {
    final Map<String, Object> rslt = new HashMap<>();
    logger.debug("Processing model attributes for viewName='{}'", viewName);
    for (Map.Entry<AnnotatedElement, Object> y : modelAttributes.entrySet()) {
        final AnnotatedElement annotatedElement = y.getKey();
        final Object bean = y.getValue();
        final SoffitModelAttribute sma = annotatedElement.getAnnotation(SoffitModelAttribute.class);
        if (attributeAppliesToView(sma, viewName)) {
            logger.debug("The following  SoffitModelAttribute applies to viewName='{}':  {}", viewName, sma);
            final String modelAttributeName = sma.value();
            // Are we looking at a class or a method?
            if (annotatedElement instanceof Class) {
                // The bean itself is the model attribute
                rslt.put(modelAttributeName, bean);
            } else if (annotatedElement instanceof Method) {
                final Method m = (Method) annotatedElement;
                final Object modelAttribute = getModelAttributeFromMethod(bean, m, req, res, portalRequest, bearer, preferences, definition);
                rslt.put(modelAttributeName, modelAttribute);
            } else {
                final String msg = "Unsupported AnnotatedElement type:  " + AnnotatedElement.class.getName();
                throw new UnsupportedOperationException(msg);
            }
        }
    }
    logger.debug("Calculated the following model attributes for viewName='{}':  {}", viewName, rslt);
    return rslt;
}
Also used : HashMap(java.util.HashMap) AnnotatedElement(java.lang.reflect.AnnotatedElement) Method(java.lang.reflect.Method) HashMap(java.util.HashMap) Map(java.util.Map)

Example 40 with AnnotatedElement

use of java.lang.reflect.AnnotatedElement in project uPortal by Jasig.

the class ModelAttributeService method init.

@PostConstruct
public void init() {
    /*
         * Gather classes & methods that reference @SoffitMoldelAttribute
         */
    final Map<AnnotatedElement, Object> map = new HashMap<>();
    final String[] beanNames = applicationContext.getBeanDefinitionNames();
    for (String name : beanNames) {
        final Object bean = applicationContext.getBean(name);
        final Class clazz = AopUtils.isAopProxy(bean) ? AopUtils.getTargetClass(bean) : bean.getClass();
        if (clazz.isAnnotationPresent(SoffitModelAttribute.class)) {
            // The bean itself is the model attribute
            map.put(clazz, bean);
        } else {
            // Check the bean for annotated methods...
            for (Method m : clazz.getMethods()) {
                if (m.isAnnotationPresent(SoffitModelAttribute.class)) {
                    map.put(m, bean);
                }
            }
        }
    }
    logger.debug("Found {} beans and/or methods referencing @SoffitModelAttribute", map.size());
    modelAttributes = Collections.unmodifiableMap(map);
}
Also used : HashMap(java.util.HashMap) AnnotatedElement(java.lang.reflect.AnnotatedElement) Method(java.lang.reflect.Method) PostConstruct(javax.annotation.PostConstruct)

Aggregations

AnnotatedElement (java.lang.reflect.AnnotatedElement)106 Method (java.lang.reflect.Method)23 Annotation (java.lang.annotation.Annotation)17 Field (java.lang.reflect.Field)17 ArrayList (java.util.ArrayList)12 Test (org.junit.Test)11 HashMap (java.util.HashMap)9 Test (org.junit.jupiter.api.Test)8 Member (java.lang.reflect.Member)7 LinkedHashSet (java.util.LinkedHashSet)7 List (java.util.List)7 Constructor (java.lang.reflect.Constructor)6 Type (java.lang.reflect.Type)6 Map (java.util.Map)6 HashSet (java.util.HashSet)5 By (org.openqa.selenium.By)5 Statement (org.junit.runners.model.Statement)4 FindBy (org.openqa.selenium.support.FindBy)4 EntityType (com.querydsl.codegen.EntityType)3 Collection (java.util.Collection)3