-
Notifications
You must be signed in to change notification settings - Fork 32
/
PropertiesValidatorFactory.java
305 lines (278 loc) · 12.5 KB
/
PropertiesValidatorFactory.java
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
* Copyright (c) 2011-2020 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.json.schema.common;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.pointer.JsonPointer;
import io.vertx.json.schema.Schema;
import io.vertx.json.schema.SchemaException;
import io.vertx.json.schema.ValidationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Stream;
import static io.vertx.json.schema.ValidationException.create;
import static io.vertx.json.schema.common.JsonUtil.unwrap;
public class PropertiesValidatorFactory implements ValidatorFactory {
private SchemaInternal parseAdditionalProperties(Object obj, JsonPointer scope, SchemaParserInternal parser, MutableStateValidator parent) {
try {
return parser.parse(obj, scope.copy().append("additionalProperties"), parent);
} catch (ClassCastException e) {
throw new SchemaException(obj, "Wrong type for additionalProperties keyword", e);
} catch (NullPointerException e) {
throw new SchemaException(obj, "Null additionalProperties keyword", e);
}
}
private Map<String, SchemaInternal> parseProperties(JsonObject obj, JsonPointer scope, SchemaParserInternal parser, MutableStateValidator parent) {
JsonPointer basePointer = scope.copy().append("properties");
Map<String, SchemaInternal> parsedSchemas = new HashMap<>();
for (Map.Entry<String, Object> entry : obj) {
try {
parsedSchemas.put(entry.getKey(), parser.parse(
entry.getValue(),
basePointer.copy().append(entry.getKey()),
parent
));
} catch (ClassCastException | NullPointerException e) {
throw new SchemaException(obj, "Property descriptor " + entry.getKey() + " should be a not null JsonObject", e);
}
}
return parsedSchemas;
}
private Map<Pattern, SchemaInternal> parsePatternProperties(JsonObject obj, JsonPointer scope, SchemaParserInternal parser, MutableStateValidator parent) {
JsonPointer basePointer = scope.copy().append("patternProperties");
Map<Pattern, SchemaInternal> parsedSchemas = new HashMap<>();
for (Map.Entry<String, Object> entry : obj) {
try {
parsedSchemas.put(Pattern.compile(entry.getKey()), parser.parse(
entry.getValue(),
basePointer.copy().append(entry.getKey()),
parent
));
} catch (PatternSyntaxException e) {
throw new SchemaException(obj, "Invalid pattern for pattern keyword", e);
} catch (ClassCastException | NullPointerException e) {
throw new SchemaException(obj, "Property descriptor " + entry.getKey() + " should be a not null JsonObject", e);
}
}
return parsedSchemas;
}
@Override
public Validator createValidator(JsonObject schema, JsonPointer scope, SchemaParserInternal parser, MutableStateValidator parent) {
try {
JsonObject properties = schema.getJsonObject("properties");
JsonObject patternProperties = schema.getJsonObject("patternProperties");
Object additionalProperties = schema.getValue("additionalProperties");
PropertiesValidator validator = new PropertiesValidator(parent);
Map<String, SchemaInternal> parsedProperties = (properties != null) ? parseProperties(properties, scope, parser, validator) : null;
Map<Pattern, SchemaInternal> parsedPatternProperties = (patternProperties != null) ? parsePatternProperties(patternProperties, scope, parser, validator) : null;
if (additionalProperties instanceof JsonObject) {
validator.configure(parsedProperties, parsedPatternProperties, parseAdditionalProperties(additionalProperties, scope, parser, validator));
} else if (additionalProperties instanceof Boolean) {
validator.configure(parsedProperties, parsedPatternProperties, (Boolean) additionalProperties);
} else {
validator.configure(parsedProperties, parsedPatternProperties, true);
}
return validator;
} catch (ClassCastException e) {
throw new SchemaException(schema, "Wrong type for properties/patternProperties keyword", e);
}
}
@Override
public boolean canConsumeSchema(JsonObject schema) {
return schema.containsKey("properties") || schema.containsKey("patternProperties") || schema.containsKey("additionalProperties");
}
private Future<Void> fillAdditionalPropertyException(Throwable t, Object in) {
return Future.failedFuture(ValidationException.create("additionalProperties schema should match", "additionalProperties", in, t));
}
class PropertiesValidator extends BaseMutableStateValidator implements DefaultApplier {
private Map<String, SchemaInternal> properties;
private Map<Pattern, SchemaInternal> patternProperties;
private boolean allowAdditionalProperties;
private SchemaInternal additionalPropertiesSchema;
public PropertiesValidator(MutableStateValidator parent) {
super(parent);
}
private void configure(Map<String, SchemaInternal> properties, Map<Pattern, SchemaInternal> patternProperties, boolean allowAdditionalProperties) {
this.properties = properties;
this.patternProperties = patternProperties;
this.allowAdditionalProperties = allowAdditionalProperties;
this.additionalPropertiesSchema = null;
initializeIsSync();
}
private void configure(Map<String, SchemaInternal> properties, Map<Pattern, SchemaInternal> patternProperties, SchemaInternal additionalPropertiesSchema) {
this.properties = properties;
this.patternProperties = patternProperties;
this.allowAdditionalProperties = true;
this.additionalPropertiesSchema = additionalPropertiesSchema;
initializeIsSync();
}
@Override
public boolean calculateIsSync() {
Stream<Boolean> props = (properties != null) ? properties.values().stream().map(Schema::isSync) : Stream.empty();
Stream<Boolean> patternProps = (patternProperties != null) ? patternProperties.values().stream().map(Schema::isSync) : Stream.empty();
Stream<Boolean> additionalProps = (additionalPropertiesSchema != null) ? Stream.of(additionalPropertiesSchema.isSync()) : Stream.empty();
return Stream.concat(
props,
Stream.concat(patternProps, additionalProps)
).reduce(true, Boolean::logicalAnd);
}
@Override
public Future<Void> validateAsync(ValidatorContext context, final Object in) throws ValidationException {
if (isSync()) return validateSyncAsAsync(context, in);
Object o = unwrap(in);
if (o instanceof Map<?, ?>) {
Map<String, ?> obj = (Map<String, ?>) o;
List<Future> futs = new ArrayList<>();
for (String key : obj.keySet()) {
boolean found = false;
if (properties != null && properties.containsKey(key)) {
SchemaInternal s = properties.get(key);
context.markEvaluatedProperty(key);
if (s.isSync()) {
try {
s.validateSync(context.lowerLevelContext(key), obj.get(key));
} catch (ValidationException e) {
return Future.failedFuture(e);
}
} else {
futs.add(s.validateAsync(context.lowerLevelContext(key), obj.get(key)));
}
found = true;
}
if (patternProperties != null) {
for (Map.Entry<Pattern, SchemaInternal> patternProperty : patternProperties.entrySet()) {
if (patternProperty.getKey().matcher(key).find()) {
SchemaInternal s = patternProperty.getValue();
context.markEvaluatedProperty(key);
if (s.isSync()) {
try {
s.validateSync(context.lowerLevelContext(key), obj.get(key));
} catch (ValidationException e) {
return Future.failedFuture(e);
}
} else {
futs.add(s.validateAsync(context.lowerLevelContext(key), obj.get(key)));
}
found = true;
}
}
}
if (!found) {
if (allowAdditionalProperties) {
if (additionalPropertiesSchema != null) {
context.markEvaluatedProperty(key);
if (additionalPropertiesSchema.isSync()) {
try {
additionalPropertiesSchema.validateSync(context.lowerLevelContext(key), obj.get(key));
} catch (ValidationException e) {
return fillAdditionalPropertyException(e, in);
}
} else {
futs.add(additionalPropertiesSchema
.validateAsync(context.lowerLevelContext(key), obj.get(key))
.recover(t -> fillAdditionalPropertyException(t, in))
);
}
}
} else {
return Future.failedFuture(create("Provided object contains unexpected additional property: " + key, "additionalProperties", in));
}
}
}
if (futs.isEmpty()) return Future.succeededFuture();
else return CompositeFuture.all(futs).compose(cf -> Future.succeededFuture());
} else return Future.succeededFuture();
}
@Override
public void validateSync(ValidatorContext context, final Object in) throws ValidationException {
this.checkSync();
Object o = unwrap(in);
if (o instanceof Map<?, ?>) {
Map<String, ?> obj = (Map<String, ?>) o;
for (String key : obj.keySet()) {
boolean found = false;
if (properties != null && properties.containsKey(key)) {
SchemaInternal s = properties.get(key);
context.markEvaluatedProperty(key);
s.validateSync(context.lowerLevelContext(key), obj.get(key));
found = true;
}
if (patternProperties != null) {
for (Map.Entry<Pattern, SchemaInternal> patternProperty : patternProperties.entrySet()) {
if (patternProperty.getKey().matcher(key).find()) {
SchemaInternal s = patternProperty.getValue();
context.markEvaluatedProperty(key);
s.validateSync(context.lowerLevelContext(key), obj.get(key));
found = true;
}
}
}
if (!found) {
if (allowAdditionalProperties) {
if (additionalPropertiesSchema != null) {
context.markEvaluatedProperty(key);
additionalPropertiesSchema.validateSync(context.lowerLevelContext(key), obj.get(key));
}
} else {
throw create("Provided object contains unexpected additional property: " + key, "additionalProperties", in);
}
}
}
}
}
@Override
public Future<Void> applyDefaultValue(Object value) {
value = unwrap(value);
if (!(value instanceof Map<?, ?> && properties != null)) {
return Future.succeededFuture();
}
List<Future> futs = new ArrayList<>();
Map<String, Object> obj = (Map<String, Object>) value;
for (Map.Entry<String, SchemaInternal> e : properties.entrySet()) {
final String key = e.getKey();
final SchemaInternal schema = e.getValue();
if (!obj.containsKey(key)) {
if (schema.isSync()) {
Object def = schema.getOrApplyDefaultSync(null);
if (def != null) {
obj.put(key, def);
}
} else {
futs.add(
schema.getOrApplyDefaultAsync(null).onSuccess(def -> {
if (def != null) {
obj.put(key, def);
}
})
);
}
} else {
if (schema.isSync()) {
schema.getOrApplyDefaultSync(obj.get(key));
} else {
futs.add(
schema.getOrApplyDefaultAsync(obj.get(key))
);
}
}
}
if (futs.isEmpty()) {
return Future.succeededFuture();
}
return CompositeFuture.all(futs).mapEmpty();
}
}
}