2 * Copyright (c) 2015 CableLabs and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.packetcable.provider.validation.impl.validators;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import javax.annotation.concurrent.NotThreadSafe;
14 import org.opendaylight.controller.packetcable.provider.validation.ValidationException;
15 import org.opendaylight.controller.packetcable.provider.validation.Validator;
18 * Helper class to help support lazy initialization of error message array.<br>
19 * This delays array creation until bad data is found.
21 * <strong>Subclasses must call {@link #throwErrorsIfNeeded()} at the end of validate()</strong>
26 public abstract class AbstractValidator<T> implements Validator<T> {
28 private ArrayList<String> errorMessages = null;
31 * If any error messages have been added to the list returned by {@link #getErrorMessages()}
32 * then a ValidationException will be thrown with those error messages.
34 * @throws ValidationException
36 protected void throwErrorsIfNeeded() throws ValidationException {
37 if (errorMessages != null && !errorMessages.isEmpty()) {
38 ValidationException exception = new ValidationException(errorMessages);
45 * sets the error message list to null.
47 protected void resetErrorMessages() {
52 * Checks if the passed in object is null. If it is, then an error message will be
53 * appended to the current list of errors.
56 * The object that must not be null.
58 * The name of the object (will be used in the error message).
60 protected void mustExist(Object obj, String name) {
62 getErrorMessages().add(name + " must exist");
67 * Lazy initalizer of an array list of error messages.
69 * @return The array list of error messages
71 protected ArrayList<String> getErrorMessages() {
72 if (errorMessages == null) {
73 errorMessages = new ArrayList<>(2);
79 * Checks if the passed in collection is null or empty. If it is then an error
80 * will be appended to the current list of errors.
83 * The collection to test
85 * The name of the object (will be used in the error message)
87 protected void mustExistAndNotBeEmpty(Collection<?> collection, String name) {
88 if (collection == null) {
89 getErrorMessages().add(name + " must exist");
90 } else if (collection.isEmpty()) {
91 getErrorMessages().add(name + " must not be empty");
95 protected <C> void validateChild(Validator<C> validator, C child) {
97 validator.validate(child, Extent.NODE_AND_SUBTREE);
98 } catch (ValidationException e) {
99 getErrorMessages().addAll(e.getErrorMessages());