setBeanFactory(BeanFactory)   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
dl 0
loc 3
rs 10
ccs 1
cts 1
cp 1
crap 1
1
package io.github.ro4.spelvalidation;
2
3
import org.springframework.beans.BeansException;
4
import org.springframework.beans.factory.BeanFactory;
5
import org.springframework.beans.factory.BeanFactoryAware;
6
import org.springframework.context.expression.BeanFactoryResolver;
7
import org.springframework.expression.spel.standard.SpelExpressionParser;
8
import org.springframework.expression.spel.support.StandardEvaluationContext;
9
import org.springframework.util.ObjectUtils;
10
import org.springframework.util.StringUtils;
11
12
import javax.validation.ConstraintValidator;
13
import javax.validation.ConstraintValidatorContext;
14
15 1
public class SpELValidator implements ConstraintValidator<SpELAssert, Object>, BeanFactoryAware {
16
17 1
    private static final SpelExpressionParser PARSER = new SpelExpressionParser();
18
19
    private String expression;
20
21
    private StandardEvaluationContext spELCtx;
22
23
    private BeanFactory beanFactory;
24
25
    private String alias;
26
27
    private String message;
28
29
    private String reportOn;
30
31
    @Override
32
    public void initialize(SpELAssert anno) {
33 1
        if (!ObjectUtils.isEmpty(anno.expression())) {
34 1
            expression = StringUtils.arrayToDelimitedString(anno.expression(), " ");
35 1
        } else if (!ObjectUtils.isEmpty(anno.value())) {
36 1
            expression = anno.value();
37
        }
38 1
        this.spELCtx = new StandardEvaluationContext();
39 1
        spELCtx.setBeanResolver(new BeanFactoryResolver(beanFactory));
40 1
        this.alias = anno.alias();
41 1
        this.message = anno.message();
42 1
        this.reportOn = anno.reportOn();
43 1
    }
44
45
    @Override
46
    public boolean isValid(Object value, ConstraintValidatorContext context) {
47 1
        spELCtx.setVariable(alias, value);
48 1
        boolean result = Boolean.TRUE.equals(PARSER.parseExpression(expression).getValue(spELCtx, Boolean.TYPE));
49 1
        if (!result && !reportOn.isEmpty()) {
50
            context.disableDefaultConstraintViolation();
51
            context.buildConstraintViolationWithTemplate(message).addPropertyNode(reportOn).addConstraintViolation();
52
        }
53 1
        return result;
54
    }
55
56
    @Override
57
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
58 1
        this.beanFactory = beanFactory;
59 1
    }
60
}
61