1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.adservices.service.common; 18 19 import com.google.common.collect.ImmutableCollection; 20 import com.google.common.collect.ImmutableList; 21 22 import java.util.Collection; 23 24 /** 25 * This Interface generates a validator. 26 * 27 * @param <T> is the type name of the object instance to be validated. 28 */ 29 public interface Validator<T> { 30 String EXCEPTION_MESSAGE_FORMAT = "Invalid object of type %s. The violations are: %s"; 31 32 /** 33 * Validate the object instance of type T. 34 * 35 * @param object is the Object instance to be validated. 36 * @throws IllegalArgumentException with all the validation violations presented in a list of 37 * strings in the messages and return nothing is the object is valid. 38 */ validate(T object)39 default void validate(T object) throws IllegalArgumentException { 40 Collection<String> violations = getValidationViolations(object); 41 if (!violations.isEmpty()) { 42 throw new IllegalArgumentException( 43 String.format( 44 EXCEPTION_MESSAGE_FORMAT, object.getClass().getName(), violations)); 45 } 46 } 47 48 /** 49 * Validates the object and returns a collection of violations if any. 50 * 51 * @param object is the Object instance to be validated. 52 * @return an empty collection if the object is valid or a collection of strings describing all 53 * the encountered violations. 54 */ getValidationViolations(T object)55 default Collection<String> getValidationViolations(T object) { 56 ImmutableCollection.Builder<String> violations = new ImmutableList.Builder<>(); 57 addValidation(object, violations); 58 return violations.build(); 59 } 60 61 /** Validates the object and populate the violations. */ addValidation(T object, ImmutableCollection.Builder<String> violations)62 void addValidation(T object, ImmutableCollection.Builder<String> violations); 63 } 64