-
Notifications
You must be signed in to change notification settings - Fork 674
Expand file tree
/
Copy pathValidationPlugin.java
More file actions
201 lines (183 loc) · 7.65 KB
/
ValidationPlugin.java
File metadata and controls
201 lines (183 loc) · 7.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package play.data.validation;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.context.MethodParameterContext;
import net.sf.oval.guard.Guard;
import play.PlayPlugin;
import play.exceptions.ActionNotFoundException;
import play.exceptions.UnexpectedException;
import play.mvc.ActionInvoker;
import play.mvc.Http;
import play.mvc.Http.Cookie;
import play.mvc.Scope;
import play.mvc.results.Result;
import play.utils.Java;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidationPlugin extends PlayPlugin {
public static final ThreadLocal<Map<Object, String>> keys = new ThreadLocal<>();
private boolean isAwakingFromAwait() {
Http.Request request = Http.Request.current();
if (request == null) {
return false;
}
// if CONTINUATIONS_STORE_VALIDATIONS is present we know that
// we are awaking from await()
return request.args.containsKey(ActionInvoker.CONTINUATIONS_STORE_VALIDATIONS);
}
@Override
public void beforeInvocation() {
keys.set(new HashMap<Object, String>());
Validation.current.set(new Validation());
}
@Override
public void beforeActionInvocation(Method actionMethod) {
// when using await, this code get called multiple times.
// When recovering from await() we're going to restore (overwrite) validation.current
// with the object-instance from the previous part of the execution.
// If this is happening it is no point in doing anything here, since
// we overwrite it later on.
if (isAwakingFromAwait()) {
return ;
}
try {
Validation.current.set(restore());
boolean verify = false;
for (Annotation[] annotations : actionMethod.getParameterAnnotations()) {
if (annotations.length > 0) {
verify = true;
break;
}
}
if (!verify) {
return;
}
List<ConstraintViolation> violations = new Validator().validateAction(actionMethod);
ArrayList<Error> errors = new ArrayList<>();
String[] paramNames = Java.parameterNames(actionMethod);
for (ConstraintViolation violation : violations) {
errors.add(new Error(
paramNames[((MethodParameterContext) violation
.getContext()).getParameterIndex()], violation
.getMessage(),
violation.getMessageVariables() == null ? new String[0]
: violation.getMessageVariables().values()
.toArray(new String[0]), violation
.getSeverity()));
}
Validation.current.get().errors.addAll(errors);
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
@Override
public void onActionInvocationResult(Result result) {
save();
}
@Override
public void onInvocationException(Throwable e) {
clear();
}
@Override
public void invocationFinally() {
if (keys.get() != null) {
keys.get().clear();
}
keys.remove();
Validation.current.remove();
}
// ~~~~~~
static class Validator extends Guard {
public List<ConstraintViolation> validateAction(Method actionMethod) throws Exception {
List<ConstraintViolation> violations = new ArrayList<>();
Object instance = null;
// Patch for scala defaults
if (!Modifier.isStatic(actionMethod.getModifiers()) && actionMethod.getDeclaringClass().getSimpleName().endsWith("$")) {
try {
instance = actionMethod.getDeclaringClass().getDeclaredField("MODULE$").get(null);
} catch (Exception e) {
throw new ActionNotFoundException(Http.Request.current().action, e);
}
}
Object[] rArgs = ActionInvoker.getActionMethodArgs(actionMethod, instance);
validateMethodParameters(null, actionMethod, rArgs, violations);
validateMethodPre(null, actionMethod, rArgs, violations);
return violations;
}
}
static Pattern errorsParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000");
static Validation restore() {
try {
Validation validation = new Validation();
Http.Cookie cookie = Http.Request.current().cookies.get(Scope.COOKIE_PREFIX + "_ERRORS");
if (cookie != null) {
String errorsData = URLDecoder.decode(cookie.value, "utf-8");
Matcher matcher = errorsParser.matcher(errorsData);
while (matcher.find()) {
String[] g2 = matcher.group(2).split("\u0001", -1);
String message = g2[0];
String[] args = new String[g2.length - 1];
System.arraycopy(g2, 1, args, 0, args.length);
validation.errors.add(new Error(matcher.group(1), message, args));
}
}
return validation;
} catch (Exception e) {
return new Validation();
}
}
static void save() {
if (Http.Response.current() == null) {
// Some request like WebSocket don't have any response
return;
}
if (Validation.errors().isEmpty()) {
// Only send "delete cookie" header when the cookie was present in the request
if(Http.Request.current().cookies.containsKey(Scope.COOKIE_PREFIX + "_ERRORS") || !Scope.SESSION_SEND_ONLY_IF_CHANGED) {
Http.Response.current().setCookie(Scope.COOKIE_PREFIX + "_ERRORS", "", null, "/", 0, Scope.COOKIE_SECURE, Scope.SESSION_HTTPONLY, null);
}
return;
}
try {
StringBuilder errors = new StringBuilder();
if (Validation.current() != null && Validation.current().keep) {
for (Error error : Validation.errors()) {
errors.append("\u0000");
errors.append(error.key);
errors.append(":");
errors.append(error.message);
for (String variable : error.variables) {
errors.append("\u0001");
errors.append(variable);
}
errors.append("\u0000");
}
}
String errorsData = URLEncoder.encode(errors.toString(), "utf-8");
Http.Response.current().setCookie(Scope.COOKIE_PREFIX + "_ERRORS", errorsData, null, "/", null, Scope.COOKIE_SECURE, Scope.SESSION_HTTPONLY, null);
} catch (Exception e) {
throw new UnexpectedException("Errors serializationProblem", e);
}
}
static void clear() {
try {
if (Http.Response.current() != null && Http.Response.current().cookies != null) {
Cookie cookie = new Cookie();
cookie.name = Scope.COOKIE_PREFIX + "_ERRORS";
cookie.value = "";
cookie.sendOnError = true;
Http.Response.current().cookies.put(cookie.name, cookie);
}
} catch (Exception e) {
throw new UnexpectedException("Errors serializationProblem", e);
}
}
}