1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.nuiton.validator.xwork2;
23
24 import org.nuiton.validator.NuitonValidator;
25 import org.nuiton.validator.NuitonValidatorModel;
26 import org.nuiton.validator.NuitonValidatorResult;
27 import org.nuiton.validator.NuitonValidatorScope;
28
29 import java.util.Arrays;
30 import java.util.EnumMap;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35
36
37
38
39
40
41
42 public class XWork2NuitonValidator<O> implements NuitonValidator<O> {
43
44 protected NuitonValidatorModel<O> model;
45
46
47 protected Map<NuitonValidatorScope, XWork2ScopeValidator<O>> validators;
48
49 public XWork2NuitonValidator(NuitonValidatorModel<O> model) {
50
51 this.model = model;
52
53
54 validators = new EnumMap<NuitonValidatorScope, XWork2ScopeValidator<O>>(NuitonValidatorScope.class);
55
56 Class<O> type = model.getType();
57 String context = model.getContext();
58
59 Map<NuitonValidatorScope, String[]> fieldsMap = model.getFields();
60
61 for (Map.Entry<NuitonValidatorScope, String[]> entry : fieldsMap.entrySet()) {
62
63 NuitonValidatorScope scope = entry.getKey();
64
65 String scopeContext =
66 XWork2ValidatorUtil.getContextForScope(
67 context,
68 scope
69 );
70
71 Set<String> fields = new HashSet<String>(
72 Arrays.asList(entry.getValue()));
73
74 XWork2ScopeValidator<O> newValidator =
75 XWork2ValidatorUtil.newXWorkScopeValidator(
76 type,
77 scopeContext,
78 fields
79 );
80
81 validators.put(scope, newValidator);
82 }
83 }
84
85 @Override
86 public NuitonValidatorResult validate(O object) throws NullPointerException {
87
88 if (object == null) {
89 throw new NullPointerException("object parameter can not be null.");
90 }
91
92 NuitonValidatorResult result = new NuitonValidatorResult();
93
94 for (NuitonValidatorScope scope : validators.keySet()) {
95
96 XWork2ScopeValidator<O> validator = validators.get(scope);
97
98 Map<String, List<String>> newMessages = validator.validate(object);
99
100 result.addMessagesForScope(scope, newMessages);
101 }
102 return result;
103 }
104
105 @Override
106 public Set<NuitonValidatorScope> getEffectiveScopes() {
107 return validators.keySet();
108 }
109
110 @Override
111 public Set<String> getEffectiveFields() {
112 Set<String> result = new HashSet<String>();
113 for (XWork2ScopeValidator<O> scopeValidator : validators.values()) {
114 result.addAll(scopeValidator.getFieldNames());
115 }
116 return result;
117 }
118
119 @Override
120 public Set<String> getEffectiveFields(NuitonValidatorScope scope) {
121 Set<String> result = new HashSet<String>();
122 XWork2ScopeValidator<O> scopeValidator = validators.get(scope);
123 if (scopeValidator != null) {
124 result.addAll(scopeValidator.getFieldNames());
125 }
126 return result;
127 }
128
129 @Override
130 public NuitonValidatorModel<O> getModel() {
131 return model;
132 }
133 }