-
Notifications
You must be signed in to change notification settings - Fork 544
/
RestLiDataValidator.java
813 lines (759 loc) · 32.8 KB
/
RestLiDataValidator.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
/*
Copyright (c) 2015 LinkedIn Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.linkedin.restli.common.validation;
import com.linkedin.data.DataMap;
import com.linkedin.data.element.DataElement;
import com.linkedin.data.element.DataElementUtil;
import com.linkedin.data.element.SimpleDataElement;
import com.linkedin.data.it.PathMatchesPatternPredicate;
import com.linkedin.data.it.Predicate;
import com.linkedin.data.it.Predicates;
import com.linkedin.data.it.Wildcard;
import com.linkedin.data.message.Message;
import com.linkedin.data.message.MessageList;
import com.linkedin.data.schema.ArrayDataSchema;
import com.linkedin.data.schema.DataSchema;
import com.linkedin.data.schema.DataSchemaUtil;
import com.linkedin.data.schema.MapDataSchema;
import com.linkedin.data.schema.Name;
import com.linkedin.data.schema.PathSpec;
import com.linkedin.data.schema.RecordDataSchema;
import com.linkedin.data.schema.TyperefDataSchema;
import com.linkedin.data.schema.UnionDataSchema;
import com.linkedin.data.schema.validation.RequiredMode;
import com.linkedin.data.schema.validation.ValidateDataAgainstSchema;
import com.linkedin.data.schema.validation.ValidationOptions;
import com.linkedin.data.schema.validation.ValidationResult;
import com.linkedin.data.schema.validator.DataSchemaAnnotationValidator;
import com.linkedin.data.schema.validator.Validator;
import com.linkedin.data.schema.validator.ValidatorContext;
import com.linkedin.data.template.DataTemplate;
import com.linkedin.data.template.DataTemplateUtil;
import com.linkedin.data.template.RecordTemplate;
import com.linkedin.data.template.TemplateRuntimeException;
import com.linkedin.data.transform.DataComplexProcessor;
import com.linkedin.data.transform.DataProcessingException;
import com.linkedin.data.transform.filter.FilterConstants;
import com.linkedin.data.transform.filter.request.MaskOperation;
import com.linkedin.data.transform.filter.request.MaskTree;
import com.linkedin.data.transform.patch.Patch;
import com.linkedin.data.transform.patch.PatchConstants;
import com.linkedin.restli.common.PatchRequest;
import com.linkedin.restli.common.ResourceMethod;
import com.linkedin.restli.restspec.RestSpecAnnotation;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* The Rest.li data validator validates Rest.li data using information from the data schema
* as well as additional Rest.li context such as method types.<p>
*
* This validator uses 3 types of rules:
* <ol>
* <li> Whether a field is optional or required (the validator uses {@link RequiredMode#CAN_BE_ABSENT_IF_HAS_DEFAULT},
* so it is okay for a required field to be missing if it has a default value).
* <li> Data schema annotations specified with the "validate" property (see {@link DataSchemaAnnotationValidator}).
* <li> (From Rest.li resource) Rest.li annotations such as {@link CreateOnly} and {@link ReadOnly}.
* </ol>
* <p>
* Rest.li annotations should be used on top of the resource and should specify paths in the same format as
* calling .toString() on the field's {@link com.linkedin.data.schema.PathSpec}.
* Because full paths are listed, different rules can be specified for records that have the same schema.
* For example, if the schema contains two Photos, you can make the id of photo1 ReadOnly and id of photo2 non-ReadOnly.
* This is different from the optional/required distinction where if the id of photo1 is required, the id of photo2 will also be required.
* <p>
* To use the validator from the server side, there are two options:
* <ol>
* <li> Inject the validator as a parameter of the resource method.<br>
* e.g. <code>public CreateResponse create(final ValidationDemo entity, @ValidatorParam RestLiDataValidator validator)</code><br>
* Call the validate() method with the entity or the patch.
* For batch requests or responses, the validate() method has to be called for each entity/patch.
* <li> Use the Rest.li input / output validation filters. The filter(s) will throw up on invalid requests / responses.
* </ol>
* From the client side, Rest.li validation is only supported for inputs (requests).<br>
* Request builders for CRUD methods with write operations have the validateInput() method.<br>
* e.g. <code>ValidationResult result = new PhotosRequestBuilders().create().validateInput(photo);</code><br>
* Clients have to use the pegasus data validator ({@link ValidateDataAgainstSchema}) if they want to validate responses.
* @author Soojung Ha
*/
public class RestLiDataValidator
{
// ReadOnly fields should not be specified for these types of requests
private static final Set<ResourceMethod> readOnlyRestrictedMethods = new HashSet<ResourceMethod>(
Arrays.asList(ResourceMethod.CREATE, ResourceMethod.PARTIAL_UPDATE, ResourceMethod.BATCH_CREATE, ResourceMethod.BATCH_PARTIAL_UPDATE));
// CreateOnly fields should not be specified for these types of requests
private static final Set<ResourceMethod> createOnlyRestrictedMethods = new HashSet<ResourceMethod>(
Arrays.asList(ResourceMethod.PARTIAL_UPDATE, ResourceMethod.BATCH_PARTIAL_UPDATE));
// ReadOnly fields are treated as optional for these types of requests
private static final Set<ResourceMethod> readOnlyOptional = new HashSet<ResourceMethod>(
Arrays.asList(ResourceMethod.CREATE, ResourceMethod.BATCH_CREATE));
// A path is ReadOnly if it satisfies this predicate
private final Predicate _readOnlyPredicate;
// A path is CreateOnly if it satisfies this predicate
private final Predicate _createOnlyPredicate;
// A path is a descendant of a ReadOnly field if it satisfies this predicate
private final Predicate _readOnlyDescendantPredicate;
// A path is a descendant of a CreateOnly field if it satisfies this predicate
private final Predicate _createOnlyDescendantPredicate;
private final Class<? extends RecordTemplate> _valueClass;
private final ResourceMethod _resourceMethod;
// To be passed into DataSchemaAnnotationValidator.
private final Map<String, Class<? extends Validator>> _validatorClassMap;
private static final String INSTANTIATION_ERROR = "InstantiationException while trying to instantiate the record template class";
private static final String ILLEGAL_ACCESS_ERROR = "IllegalAccessException while trying to instantiate the record template class";
private static final String TEMPLATE_RUNTIME_ERROR = "TemplateRuntimeException while trying to find the schema class";
private static PathMatchesPatternPredicate stringToPredicate(String path, boolean includeDescendants)
{
// Discard the initial / character if present
if (path.length() > 0 && path.charAt(0) == DataElement.SEPARATOR)
{
path = path.substring(1);
}
String[] components = path.split(DataElement.SEPARATOR.toString());
int length = components.length + (includeDescendants ? 1 : 0);
Object[] componentsWithWildcards = new Object[length];
int i = 0;
for (String component : components)
{
if (component.equals(PathSpec.WILDCARD)) // Treat * as wildcard even if it's not the same object as WILDCARD
{
componentsWithWildcards[i++] = Wildcard.ANY_ONE;
}
else
{
componentsWithWildcards[i++] = component;
}
}
if (includeDescendants)
{
componentsWithWildcards[components.length] = Wildcard.ANY_ZERO_OR_MORE;
}
return new PathMatchesPatternPredicate(componentsWithWildcards);
}
private static Map<String, List<String>> annotationsToMap(Annotation[] annotations)
{
Map<String, List<String>> annotationMap = new HashMap<String, List<String>>();
if (annotations != null)
{
for (Annotation annotation : annotations)
{
if (annotation.annotationType() == ReadOnly.class)
{
annotationMap.put(ReadOnly.class.getAnnotation(RestSpecAnnotation.class).name(),
Arrays.asList(((ReadOnly) annotation).value()));
}
else if (annotation.annotationType() == CreateOnly.class)
{
annotationMap.put(CreateOnly.class.getAnnotation(RestSpecAnnotation.class).name(),
Arrays.asList(((CreateOnly) annotation).value()));
}
}
}
return annotationMap;
}
/**
* Constructor.
*
* @param annotations annotations on the resource class
* @param valueClass class of the record template
* @param resourceMethod resource method type
*/
public RestLiDataValidator(Annotation[] annotations, Class<? extends RecordTemplate> valueClass, ResourceMethod resourceMethod)
{
this(annotations, valueClass, resourceMethod, Collections.emptyMap());
}
/**
* Constructor.
*
* @param annotations annotations on the resource class
* @param valueClass class of the record template
* @param resourceMethod resource method type
* @param validatorClassMap custom validator class map (see {@link #RestLiDataValidator(Map, Class, ResourceMethod, Map)} for explanation)
*/
public RestLiDataValidator(Annotation[] annotations,
Class<? extends RecordTemplate> valueClass,
ResourceMethod resourceMethod,
Map<String, Class<? extends Validator>> validatorClassMap)
{
this(annotationsToMap(annotations), valueClass, resourceMethod, validatorClassMap);
}
/**
* Constructor.
*
* @param annotations map from annotation name to annotation values
* @param valueClass class of the record template
* @param resourceMethod resource method type
*/
public RestLiDataValidator(Map<String, List<String>> annotations,
Class<? extends RecordTemplate> valueClass,
ResourceMethod resourceMethod)
{
this(annotations, valueClass, resourceMethod, Collections.emptyMap());
}
/**
* Constructor.
*
* @param annotations map from annotation name to annotation values
* @param valueClass class of the record template
* @param resourceMethod resource method type
* @param validatorClassMap custom validator class map, with keys as "validate" property keys
* (See {@link DataSchemaAnnotationValidator}) and values as validator class types
* (e.g. "strlen" as key and StrlenValidator.class as value)
*/
public RestLiDataValidator(Map<String, List<String>> annotations,
Class<? extends RecordTemplate> valueClass,
ResourceMethod resourceMethod,
Map<String, Class<? extends Validator>> validatorClassMap)
{
List<Predicate> readOnly = new ArrayList<Predicate>();
List<Predicate> createOnly = new ArrayList<Predicate>();
List<Predicate> readOnlyDescendant = new ArrayList<Predicate>();
List<Predicate> createOnlyDescendant = new ArrayList<Predicate>();
if (annotations != null)
{
for (Map.Entry<String, List<String>> entry : annotations.entrySet())
{
String annotationName = entry.getKey();
if (annotationName.equals(ReadOnly.class.getAnnotation(RestSpecAnnotation.class).name())
&& readOnlyRestrictedMethods.contains(resourceMethod))
{
for (String path : entry.getValue())
{
readOnly.add(stringToPredicate(path, false));
readOnlyDescendant.add(stringToPredicate(path, true));
}
}
else if (annotationName.equals(CreateOnly.class.getAnnotation(RestSpecAnnotation.class).name())
&& createOnlyRestrictedMethods.contains(resourceMethod))
{
for (String path : entry.getValue())
{
createOnly.add(stringToPredicate(path, false));
createOnlyDescendant.add(stringToPredicate(path, true));
}
}
}
}
_readOnlyPredicate = Predicates.or(readOnly);
_createOnlyPredicate = Predicates.or(createOnly);
_readOnlyDescendantPredicate = Predicates.or(readOnlyDescendant);
_createOnlyDescendantPredicate = Predicates.or(createOnlyDescendant);
_valueClass = valueClass;
_resourceMethod = resourceMethod;
_validatorClassMap = Collections.unmodifiableMap(validatorClassMap);
}
private class DataValidator extends DataSchemaAnnotationValidator
{
private DataValidator(DataSchema schema)
{
super(schema, _validatorClassMap);
}
@Override
public void validate(ValidatorContext context)
{
super.validate(context);
DataElement element = context.dataElement();
if (_readOnlyPredicate.evaluate(element))
{
context.addResult(new Message(element.path(), "ReadOnly field present in a %s request", _resourceMethod.toString()));
}
if (_createOnlyPredicate.evaluate(element))
{
context.addResult(new Message(element.path(), "CreateOnly field present in a %s request", _resourceMethod.toString()));
}
}
}
/**
* Validate Rest.li data (single entity or patch).
* Does not accept batch data.
*
* @deprecated This method only validates the input for create / batch create methods.
* Use {@link #validateInput(RecordTemplate)}, {@link #validateInput(PatchRequest)} or {@link #validateOutput(RecordTemplate)} instead.
* @param dataTemplate data to validate
* @return validation result
*/
@Deprecated
public ValidationResult validate(DataTemplate<?> dataTemplate)
{
switch (_resourceMethod)
{
case PARTIAL_UPDATE:
case BATCH_PARTIAL_UPDATE:
return validatePatch((PatchRequest) dataTemplate);
case CREATE:
case BATCH_CREATE:
case UPDATE:
case BATCH_UPDATE:
return validateInputEntity((RecordTemplate) dataTemplate);
case GET:
case BATCH_GET:
case FINDER:
case GET_ALL:
return validateOutputEntity((RecordTemplate) dataTemplate, null);
default:
throw new IllegalArgumentException("Cannot perform Rest.li validation for " + _resourceMethod.toString());
}
}
/**
* Validate Rest.li input data (single entity).
*
* @param dataTemplate data to validate
* @return validation result
*/
public ValidationResult validateInput(RecordTemplate dataTemplate)
{
if (dataTemplate == null)
{
throw new IllegalArgumentException("Record template is null.");
}
if (dataTemplate.data() == null)
{
throw new IllegalArgumentException("Record template does not have data.");
}
if (dataTemplate.schema() == null)
{
throw new IllegalArgumentException("Record template does not have a schema.");
}
switch (_resourceMethod)
{
case CREATE:
case BATCH_CREATE:
case UPDATE:
case BATCH_UPDATE:
return validateInputEntity(dataTemplate);
default:
throw new IllegalArgumentException("Cannot perform Rest.li input (entity) validation for " + _resourceMethod.toString());
}
}
/**
* Validate Rest.li input data (single patch).
*
* @param patchRequest patch to validate
* @return validation result
*/
public ValidationResult validateInput(PatchRequest<?> patchRequest)
{
if (patchRequest == null)
{
throw new IllegalArgumentException("Patch request is null.");
}
if (patchRequest.getPatchDocument() == null)
{
throw new IllegalArgumentException("Patch request does not have a patch document.");
}
switch (_resourceMethod)
{
case PARTIAL_UPDATE:
case BATCH_PARTIAL_UPDATE:
return validatePatch(patchRequest);
default:
throw new IllegalArgumentException("Cannot perform Rest.li input (patch) validation for " + _resourceMethod.toString());
}
}
/**
* Validate Rest.li output data (single entity).
*
* @param dataTemplate data to validate
* @return validation result
*/
public ValidationResult validateOutput(RecordTemplate dataTemplate)
{
return validateOutput(dataTemplate, null);
}
public ValidationResult validateOutput(RecordTemplate dataTemplate, MaskTree projectionMask)
{
if (dataTemplate == null)
{
throw new IllegalArgumentException("Record template is null.");
}
if (dataTemplate.data() == null)
{
throw new IllegalArgumentException("Record template does not have data.");
}
switch (_resourceMethod)
{
case CREATE:
case BATCH_CREATE:
case GET:
case BATCH_GET:
case FINDER:
case GET_ALL:
return validateOutputEntity(dataTemplate, projectionMask);
default:
throw new IllegalArgumentException("Cannot perform Rest.li output validation for " + _resourceMethod.toString());
}
}
/**
* Checks that if the patch is applied to a valid entity, the modified entity will also be valid.
* This method
* (1) Checks that required/ReadOnly/CreateOnly fields are not deleted.
* (2) Checks that new values for record templates contain all required fields.
* (3) Applies the patch to an empty entity and validates the entity for custom validation rules
* and Rest.li annotations (Allows required fields to be absent by using {@link RequiredMode#IGNORE},
* because a patch does not necessarily contain all fields).
*
* NOTE: Updating a part of an array is not supported. So if the array contains a required field that is
* readonly or createonly, the field cannot be present (no partial updates on readonly/createonly)
* but cannot be absent either (no missing required fields). This means the array cannot be changed by a
* partial update request. This is something that should be fixed.
*
* @param patchRequest the patch
* @return the final validation result
*/
private ValidationResult validatePatch(PatchRequest<?> patchRequest)
{
// Instantiate an empty entity.
RecordTemplate entity;
try
{
entity = _valueClass.newInstance();
}
catch (InstantiationException e)
{
return validationResultWithErrorMessage(INSTANTIATION_ERROR);
}
catch (IllegalAccessException e)
{
return validationResultWithErrorMessage(ILLEGAL_ACCESS_ERROR);
}
// Apply the patch to the entity and get paths that $set and $delete operations were performed on.
@SuppressWarnings("unchecked")
PatchRequest<RecordTemplate> patch = (PatchRequest<RecordTemplate>) patchRequest;
DataComplexProcessor processor =
new DataComplexProcessor(new Patch(true), patch.getPatchDocument(), entity.data());
MessageList<Message> messages;
try
{
messages = processor.runDataProcessing(false);
}
catch (DataProcessingException e)
{
return validationResultWithErrorMessage("Error while applying patch: " + e.getMessage());
}
ValidationErrorResult checkDeleteResult = new ValidationErrorResult();
checkDeletesAreValid(entity.schema(), messages, checkDeleteResult);
if (!checkDeleteResult.isValid())
{
return checkDeleteResult;
}
ValidationResult checkSetResult = checkNewRecordsAreNotMissingFields(entity, messages);
if (checkSetResult != null)
{
return checkSetResult;
}
// Custom validation rules and Rest.li annotations for set operations are checked here.
// It's okay if required fields are absent in a partial update request, so use ignore mode.
return ValidateDataAgainstSchema.validate(new SimpleDataElement(entity.data(), entity.schema()),
new ValidationOptions(RequiredMode.IGNORE), new DataValidator(entity.schema()));
}
private ValidationResult checkNewRecordsAreNotMissingFields(RecordTemplate entity, MessageList<Message> messages)
{
for (Message message : messages)
{
Object[] path = message.getPath();
if (path[path.length - 1].toString().equals(PatchConstants.SET_COMMAND))
{
// Replace $set with the field name to get the full path
path[path.length - 1] = message.getFormat();
DataElement element = DataElementUtil.element(new SimpleDataElement(entity.data(), entity.schema()), path);
ValidationResult result = ValidateDataAgainstSchema.validate(element, new ValidationOptions());
if (!result.isValid())
{
return result;
}
}
}
return null;
}
/**
* Create a hollow data element in which only getName() and getParent() work correctly.
* This method is used to test $delete partial update paths against {@link PathMatchesPatternPredicate}.
*
* @param path the path from the root to the element, including the name of the element
* @return a hollow data element
*/
private static DataElement hollowElementFromPath(Object[] path)
{
DataElement root = new SimpleDataElement(null, null);
DataElement current = root;
for (Object component : path)
{
DataElement child = new SimpleDataElement(null, component.toString(), null, current);
current = child;
}
return current;
}
private void checkDeletesAreValid(DataSchema schema, MessageList<Message> messages, ValidationErrorResult result)
{
for (Message message : messages)
{
Object[] path = message.getPath();
if (path[path.length - 1].toString().equals(PatchConstants.DELETE_COMMAND))
{
// Replace $delete with the field name to get the full path
path[path.length - 1] = message.getFormat();
RecordDataSchema.Field field = DataSchemaUtil.getField(schema, path);
if (field != null && !field.getOptional() && field.getDefault() == null)
{
result.addMessage(new Message(path, "cannot delete a required field"));
}
DataElement fakeElement = hollowElementFromPath(path);
if (_readOnlyDescendantPredicate.evaluate(fakeElement))
{
result.addMessage(new Message(path, "cannot delete a ReadOnly field or its descendants"));
}
else if (_createOnlyDescendantPredicate.evaluate(fakeElement))
{
result.addMessage(new Message(path, "cannot delete a CreateOnly field or its descendants"));
}
}
}
}
private ValidationResult validateInputEntity(RecordTemplate entity)
{
ValidationOptions validationOptions = new ValidationOptions();
if (readOnlyOptional.contains(_resourceMethod))
{
// Even if ReadOnly fields are non-optional, the client cannot supply them in a create request, so they should be treated as optional.
validationOptions.setTreatOptional(_readOnlyPredicate);
}
ValidationResult result = ValidateDataAgainstSchema.validate(entity, validationOptions, new DataValidator(entity.schema()));
return result;
}
private ValidationResult validateOutputEntity(RecordTemplate entity, MaskTree projectionMask)
{
try
{
// Value class from resource model is the only source of truth for record schema.
// Schema from the record template itself should not be used.
DataSchema originalSchema = DataTemplateUtil.getSchema(_valueClass);
// When a projection is defined, we only need to validate the projected fields.
DataSchema validatingSchema = (projectionMask != null) ?
buildSchemaByProjection(originalSchema, projectionMask.getDataMap()) : originalSchema;
DataSchemaAnnotationValidator validator = new DataSchemaAnnotationValidator(validatingSchema);
return ValidateDataAgainstSchema.validate(entity.data(), validatingSchema, new ValidationOptions(), validator);
}
catch (TemplateRuntimeException e)
{
return validationResultWithErrorMessage(TEMPLATE_RUNTIME_ERROR);
}
}
/**
* Build a new schema that contains only the projected fields from the original schema recursively.
* @param schema schema to build from
* @param maskMap projection mask data map
* @return new schema containing only projected fields
*/
private static DataSchema buildSchemaByProjection(DataSchema schema, DataMap maskMap) {
if (maskMap == null || maskMap.isEmpty()) {
throw new IllegalArgumentException("Invalid projection masks.");
}
if (schema instanceof RecordDataSchema) {
return buildRecordDataSchemaByProjection((RecordDataSchema) schema, maskMap);
} else if (schema instanceof UnionDataSchema) {
return buildUnionDataSchemaByProjection((UnionDataSchema) schema, maskMap);
} else if (schema instanceof ArrayDataSchema) {
return buildArrayDataSchemaByProjection((ArrayDataSchema) schema, maskMap);
} else if (schema instanceof MapDataSchema) {
return buildMapDataSchemaByProjection((MapDataSchema) schema, maskMap);
} else if (schema instanceof TyperefDataSchema) {
return buildTyperefDataSchemaByProjection((TyperefDataSchema) schema, maskMap);
}
throw new IllegalArgumentException("Unexpected data schema type: " + schema);
}
/**
* Build a new {@link TyperefDataSchema} schema that contains only the masked fields.
*/
private static TyperefDataSchema buildTyperefDataSchemaByProjection(TyperefDataSchema originalSchema, DataMap maskMap) {
TyperefDataSchema newSchema = new TyperefDataSchema(new Name(originalSchema.getFullName()));
if (originalSchema.getProperties() != null) {
newSchema.setProperties(originalSchema.getProperties());
}
if (originalSchema.getDoc() != null) {
newSchema.setDoc(originalSchema.getDoc());
}
if (originalSchema.getAliases() != null) {
newSchema.setAliases(originalSchema.getAliases());
}
DataSchema newRefSchema = buildSchemaByProjection(originalSchema.getRef(), maskMap);
newSchema.setReferencedType(newRefSchema);
return newSchema;
}
/**
* Build a new {@link MapDataSchema} schema that contains only the masked fields.
*/
private static MapDataSchema buildMapDataSchemaByProjection(MapDataSchema originalSchema, DataMap maskMap) {
if (maskMap.containsKey(FilterConstants.WILDCARD)) {
DataSchema newValuesSchema = reuseOrBuildDataSchema(originalSchema.getValues(), maskMap.get(FilterConstants.WILDCARD));
MapDataSchema newSchema = new MapDataSchema(newValuesSchema);
if (originalSchema.getProperties() != null) {
newSchema.setProperties(originalSchema.getProperties());
}
return newSchema;
}
throw new IllegalArgumentException("Missing wildcard key in projection mask: " + maskMap.keySet());
}
/**
* Build a new {@link ArrayDataSchema} schema that contains only the masked fields.
*/
private static ArrayDataSchema buildArrayDataSchemaByProjection(ArrayDataSchema originalSchema, DataMap maskMap) {
if (maskMap.containsKey(FilterConstants.WILDCARD)) {
DataSchema newItemsSchema = reuseOrBuildDataSchema(originalSchema.getItems(), maskMap.get(FilterConstants.WILDCARD));
ArrayDataSchema newSchema = new ArrayDataSchema(newItemsSchema);
if (originalSchema.getProperties() != null) {
newSchema.setProperties(originalSchema.getProperties());
}
return newSchema;
}
throw new IllegalArgumentException("Missing wildcard key in projection mask: " + maskMap.keySet());
}
/**
* Build a new {@link UnionDataSchema} schema that contains only the masked fields.
*/
private static UnionDataSchema buildUnionDataSchemaByProjection(UnionDataSchema originalSchema, DataMap maskMap) {
List<DataSchema> newUnionTypeSchemas = new ArrayList<>();
for (Map.Entry<String, Object> maskEntry : maskMap.entrySet()) {
DataSchema originalTypeSchema = originalSchema.getType(maskEntry.getKey());
DataSchema typeSchemaToUse = reuseOrBuildDataSchema(originalTypeSchema, maskEntry.getValue());
newUnionTypeSchemas.add(typeSchemaToUse);
}
UnionDataSchema newSchema = new UnionDataSchema();
// No errors are expected here, as the new schema is merely subset of the orignal
newSchema.setTypes(newUnionTypeSchemas, new StringBuilder());
if (originalSchema.getProperties() != null) {
newSchema.setProperties(originalSchema.getProperties());
}
return newSchema;
}
/**
* Build a new {@link RecordDataSchema} schema that contains only the masked fields.
*/
private static RecordDataSchema buildRecordDataSchemaByProjection(RecordDataSchema originalSchema, DataMap maskMap) {
RecordDataSchema newRecordSchema = new RecordDataSchema(new Name(originalSchema.getFullName()), RecordDataSchema.RecordType.RECORD);
List<RecordDataSchema.Field> newFields = new ArrayList<RecordDataSchema.Field>();
for (Map.Entry<String, Object> maskEntry : maskMap.entrySet()) {
RecordDataSchema.Field originalField = originalSchema.getField(maskEntry.getKey());
DataSchema fieldSchemaToUse = reuseOrBuildDataSchema(originalField.getType(), maskEntry.getValue());
RecordDataSchema.Field newField = buildRecordField(originalField, fieldSchemaToUse, newRecordSchema);
newFields.add(newField);
}
// Fields from 'include' are no difference from other fields from original schema,
// therefore, we are not calling newRecordSchema.setInclude() here.
newRecordSchema.setFields(newFields, new StringBuilder()); // No errors are expected here, as the new schema is merely subset of the original
if (originalSchema.getAliases() != null) {
newRecordSchema.setAliases(originalSchema.getAliases());
}
if (originalSchema.getDoc() != null) {
newRecordSchema.setDoc(originalSchema.getDoc());
}
if (originalSchema.getProperties() != null) {
newRecordSchema.setProperties(originalSchema.getProperties());
}
return newRecordSchema;
}
/**
* The maskValue from a rest.li projection mask is expected to be either:
* 1) Integer that has value 1, which means all fields in the original schema are projected (negative projection not supported)
* 2) DataMap, which means only selected fields in the original schema are projected
*/
private static DataSchema reuseOrBuildDataSchema(DataSchema originalSchema, Object maskValue) {
if (maskValue instanceof Integer && maskValue.equals(FilterConstants.POSITIVE)) {
return originalSchema;
} else if (maskValue instanceof DataMap) {
return buildSchemaByProjection(originalSchema, (DataMap) maskValue);
}
throw new IllegalArgumentException("Expected mask value to be either positive mask op or DataMap: " + maskValue);
}
/**
* Build a new record field with a new projected field schema.
* All other properties are copied over from the originalField.
*/
private static RecordDataSchema.Field buildRecordField(RecordDataSchema.Field originalField,
DataSchema fieldSchemaToReplace,
RecordDataSchema recordSchemaToReplace) {
RecordDataSchema.Field newField = new RecordDataSchema.Field(fieldSchemaToReplace);
if (originalField.getAliases() != null) {
// No errors are expected here, as the new schema is merely subset of the original
newField.setAliases(originalField.getAliases(), new StringBuilder());
}
if (originalField.getDefault() != null) {
newField.setDefault(originalField.getDefault());
}
if (originalField.getDoc() != null) {
newField.setDoc(originalField.getDoc());
}
if (originalField.getName() != null) {
// No errors are expected here, as the new schema is merely subset of the original
newField.setName(originalField.getName(), new StringBuilder());
}
if (originalField.getOrder() != null) {
newField.setOrder(originalField.getOrder());
}
if (originalField.getProperties() != null) {
newField.setProperties(originalField.getProperties());
}
newField.setRecord(recordSchemaToReplace);
newField.setOptional(originalField.getOptional());
return newField;
}
private static ValidationErrorResult validationResultWithErrorMessage(String errorMessage)
{
ValidationErrorResult result = new ValidationErrorResult();
result.addMessage(new Message(new Object[]{}, errorMessage));
return result;
}
private static class ValidationErrorResult implements ValidationResult
{
private MessageList<Message> _messages;
private ValidationErrorResult()
{
_messages = new MessageList<Message>();
}
@Override
public boolean hasFix()
{
return false;
}
@Override
public boolean hasFixupReadOnlyError()
{
return false;
}
@Override
public Object getFixed()
{
return null;
}
@Override
public boolean isValid()
{
return _messages.isEmpty();
}
public void addMessage(Message message)
{
_messages.add(message);
}
@Override
public Collection<Message> getMessages()
{
return _messages;
}
}
}