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;
11 import static com.google.common.base.Preconditions.checkNotNull;
13 import com.google.common.collect.Maps;
15 import java.util.NoSuchElementException;
16 import javax.annotation.Nonnull;
17 import org.opendaylight.controller.packetcable.provider.validation.ValidationException;
18 import org.opendaylight.controller.packetcable.provider.validation.Validator;
19 import org.opendaylight.controller.packetcable.provider.validation.ValidatorProvider;
20 import org.opendaylight.yangtools.yang.binding.DataObject;
28 public class ValidatorProviderImpl implements ValidatorProvider {
30 private final Map<Class<? extends DataObject>, Validator<? extends DataObject>> validatorMap;
32 public ValidatorProviderImpl() {
33 this.validatorMap = Maps.newHashMap();
40 public <T extends DataObject> void put(@Nonnull final Class<T> tClass, @Nonnull final Validator<T> validator) {
42 checkNotNull(validator);
43 validatorMap.put(tClass, validator);
50 public <T extends DataObject> void validate(@Nonnull final Class<T> tClass, @Nonnull final DataObject data,
51 @Nonnull final Validator.Extent extent) throws ValidationException {
52 if (!tClass.isAssignableFrom(data.getClass())) {
53 throw new IllegalArgumentException(
54 String.format("data must be the same type as tClass, got=%s : expected=%s",
55 data.getImplementedInterface(), tClass));
57 // We are checking the type of data above
58 @SuppressWarnings("unchecked") T tData = (T) data;
59 validatorFor(tClass).validate(tData, extent);
66 public <T extends DataObject> Validator<T> validatorFor(@Nonnull final Class<T> tClass) {
68 if (validatorMap.containsKey(tClass)) {
69 // validation is done via the put method all key/value pairs are for the same type T
70 @SuppressWarnings("unchecked") Validator<T> result = (Validator<T>) validatorMap.get(tClass);
73 throw new NoSuchElementException("Entry not found for key: " + tClass);