Add yang.common.DerivedString class
[yangtools.git] / yang / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / AbstractDerivedStringSupport.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.common;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import java.lang.reflect.Modifier;
15 import javax.annotation.concurrent.ThreadSafe;
16 import org.eclipse.jdt.annotation.NonNullByDefault;
17 import org.eclipse.jdt.annotation.Nullable;
18
19 /**
20  * Base implementation of {@link DerivedStringSupport}. This class should be used as superclass to all implementations
21  * of {@link DerivedStringSupport}, as doing so provides a simpler base and enforces some aspects of the subclass.
22  *
23  * @param <T> derived string type
24  * @author Robert Varga
25  */
26 @Beta
27 @NonNullByDefault
28 @ThreadSafe
29 public abstract class AbstractDerivedStringSupport<T extends DerivedString<T>> implements DerivedStringSupport<T> {
30     private static final ClassValue<Boolean> VALIDATED_INSTANCES = new ClassValue<Boolean>() {
31         @Override
32         protected Boolean computeValue(final @Nullable Class<?> type) {
33             // Every DerivedStringSupport representation class must:
34             checkArgument(DerivedStringSupport.class.isAssignableFrom(type), "%s is not a DerivedStringSupport", type);
35
36             // be final
37             final int modifiers = type.getModifiers();
38             checkArgument(Modifier.isFinal(modifiers), "%s must be final", type);
39
40             return Boolean.TRUE;
41         }
42     };
43
44     private final Class<T> representationClass;
45
46     protected AbstractDerivedStringSupport(final Class<T> representationClass) {
47         this.representationClass = DerivedString.validateRepresentationClass(representationClass);
48         VALIDATED_INSTANCES.get(getClass());
49     }
50
51     @Override
52     public final Class<T> getRepresentationClass() {
53         return representationClass;
54     }
55
56     @Override
57     public final Class<T> getValidatedRepresentationClass() {
58         return representationClass;
59     }
60
61     @Override
62     public final T validateRepresentation(final T value) {
63         return requireNonNull(value);
64     }
65
66     @Override
67     public final T validateRepresentation(final T value, final String canonicalString) {
68         return requireNonNull(value);
69     }
70 }