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);
}
}
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;
}
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());
}
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;
}
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);
}
Aggregations