Generate bindingHashCode() and use it in generated implementations
[mdsal.git] / binding / mdsal-binding-generator-util / src / main / java / org / opendaylight / mdsal / binding / model / util / Types.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. 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.mdsal.binding.model.util;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.cache.CacheBuilder;
14 import com.google.common.cache.CacheLoader;
15 import com.google.common.cache.LoadingCache;
16 import com.google.common.collect.ImmutableRangeSet;
17 import com.google.common.collect.Range;
18 import com.google.common.collect.RangeSet;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import java.io.Serializable;
21 import java.util.Arrays;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Objects;
26 import java.util.Optional;
27 import java.util.Set;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.mdsal.binding.model.api.AbstractBaseType;
31 import org.opendaylight.mdsal.binding.model.api.BaseTypeWithRestrictions;
32 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
33 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
34 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
35 import org.opendaylight.mdsal.binding.model.api.Restrictions;
36 import org.opendaylight.mdsal.binding.model.api.Type;
37 import org.opendaylight.mdsal.binding.model.api.WildcardType;
38 import org.opendaylight.yangtools.concepts.Builder;
39 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
40 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
41 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
42
43 public final class Types {
44     private static final CacheLoader<Class<?>, ConcreteType> TYPE_LOADER = new CacheLoader<>() {
45         @Override
46         public ConcreteType load(final Class<?> key) {
47             return new ConcreteTypeImpl(JavaTypeName.create(key), null);
48         }
49     };
50     private static final LoadingCache<Class<?>, ConcreteType> TYPE_CACHE =
51             CacheBuilder.newBuilder().weakKeys().build(TYPE_LOADER);
52
53     public static final @NonNull ConcreteType BOOLEAN = typeForClass(Boolean.class);
54     public static final @NonNull ConcreteType STRING = typeForClass(String.class);
55     public static final @NonNull ConcreteType VOID = typeForClass(Void.class);
56     public static final @NonNull ConcreteType BYTE_ARRAY = typeForClass(byte[].class);
57
58     private static final @NonNull ConcreteType BUILDER = typeForClass(Builder.class);
59     private static final @NonNull ConcreteType CLASS = typeForClass(Class.class);
60     private static final @NonNull ConcreteType LIST_TYPE = typeForClass(List.class);
61     private static final @NonNull ConcreteType LISTENABLE_FUTURE = typeForClass(ListenableFuture.class);
62     private static final @NonNull ConcreteType MAP_TYPE = typeForClass(Map.class);
63     private static final @NonNull ConcreteType OBJECT = typeForClass(Object.class);
64     private static final @NonNull ConcreteType PRIMITIVE_INT = typeForClass(int.class);
65     private static final @NonNull ConcreteType PRIMITIVE_VOID = typeForClass(void.class);
66     private static final @NonNull ConcreteType SERIALIZABLE = typeForClass(Serializable.class);
67     private static final @NonNull ConcreteType SET_TYPE = typeForClass(Set.class);
68
69     /**
70      * It is not desirable to create instance of this class.
71      */
72     private Types() {
73     }
74
75     /**
76      * Returns an instance of {@link ParameterizedType} which represents JAVA <code>java.lang.Class</code> type
77      * specialized to specified type.
78      *
79      * @param type Type for which to specialize
80      * @return A parameterized type corresponding to {@code Class<Type>}
81      * @throws NullPointerException if {@code type} is null
82      */
83     public static @NonNull ParameterizedType classType(final Type type) {
84         return parameterizedTypeFor(CLASS, type);
85     }
86
87     /**
88      * Returns an instance of {@link ConcreteType} which represents JAVA <code>java.lang.Void</code> type.
89      *
90      * @return <code>ConcreteType</code> instance which represents JAVA <code>java.lang.Void</code>
91      */
92     public static @NonNull ConcreteType voidType() {
93         return VOID;
94     }
95
96     /**
97      * Returns an instance of {@link ConcreteType} which represents {@link Object} type.
98      *
99      * @return <code>ConcreteType</code> instance which represents {@link Object}
100      */
101     public static @NonNull ConcreteType objectType() {
102         return OBJECT;
103     }
104
105     /**
106      * Returns an instance of {@link ConcreteType} which represents JAVA <code>int</code> type.
107      *
108      * @return <code>ConcreteType</code> instance which represents JAVA <code>int</code>
109      */
110     public static @NonNull ConcreteType primitiveIntType() {
111         return PRIMITIVE_INT;
112     }
113
114     /**
115      * Returns an instance of {@link ConcreteType} which represents JAVA <code>void</code> type.
116      *
117      * @return <code>ConcreteType</code> instance which represents JAVA <code>void</code>
118      */
119     public static @NonNull ConcreteType primitiveVoidType() {
120         return PRIMITIVE_VOID;
121     }
122
123     /**
124      * Returns an instance of {@link ConcreteType} which represents {@link Serializable} type.
125      *
126      * @return <code>ConcreteType</code> instance which represents JAVA <code>{@link Serializable}</code>
127      */
128     public static @NonNull ConcreteType serializableType() {
129         return SERIALIZABLE;
130     }
131
132     /**
133      * Returns an instance of {@link ConcreteType} describing the class.
134      *
135      * @param cls Class to describe
136      * @return Description of class
137      */
138     public static @NonNull ConcreteType typeForClass(final @NonNull Class<?> cls) {
139         return TYPE_CACHE.getUnchecked(cls);
140     }
141
142     public static @NonNull ConcreteType typeForClass(final @NonNull Class<?> cls,
143             final @Nullable Restrictions restrictions) {
144         return restrictions == null ? typeForClass(cls) : restrictedType(JavaTypeName.create(cls), restrictions);
145     }
146
147     @Beta
148     public static @NonNull ConcreteType restrictedType(final Type type, final @NonNull Restrictions restrictions) {
149         return restrictedType(type.getIdentifier(), restrictions);
150     }
151
152     private static @NonNull ConcreteType restrictedType(final JavaTypeName identifier,
153             final @NonNull Restrictions restrictions) {
154         return restrictions instanceof DefaultRestrictions ? new ConcreteTypeImpl(identifier, restrictions)
155                 : new BaseTypeWithRestrictionsImpl(identifier, restrictions);
156     }
157
158     /**
159      * Returns an instance of {@link ParameterizedType} describing the typed {@link Map}&lt;K,V&gt;.
160      *
161      * @param keyType Key Type
162      * @param valueType Value Type
163      * @return Description of generic type instance
164      */
165     public static @NonNull ParameterizedType mapTypeFor(final Type keyType, final Type valueType) {
166         return parameterizedTypeFor(MAP_TYPE, keyType, valueType);
167     }
168
169     public static boolean isMapType(final ParameterizedType type) {
170         return MAP_TYPE.equals(type.getRawType());
171     }
172
173     public static boolean isMapType(final Type type) {
174         return type instanceof ParameterizedType && isMapType((ParameterizedType) type);
175     }
176
177     /**
178      * Returns an instance of {@link ParameterizedType} describing the typed {@link Set}&lt;V&gt; with concrete type
179      * of value.
180      *
181      * @param valueType Value Type
182      * @return Description of generic type instance of Set
183      */
184     public static @NonNull ParameterizedType setTypeFor(final Type valueType) {
185         return parameterizedTypeFor(SET_TYPE, valueType);
186     }
187
188     /**
189      * Returns an instance of {@link ParameterizedType} describing the typed {@link List}&lt;V&gt; with concrete type
190      * of value.
191      *
192      * @param valueType Value Type
193      * @return Description of type instance of List
194      */
195     public static @NonNull ParameterizedType listTypeFor(final Type valueType) {
196         return parameterizedTypeFor(LIST_TYPE, valueType);
197     }
198
199     public static boolean isListType(final ParameterizedType type) {
200         return LIST_TYPE.equals(type.getRawType());
201     }
202
203     public static boolean isListType(final Type type) {
204         return type instanceof ParameterizedType && isListType((ParameterizedType) type);
205     }
206
207     /**
208      * Returns an instance of {@link ParameterizedType} describing the typed {@link ListenableFuture}&lt;V&gt;
209      * with concrete type of value.
210      *
211      * @param valueType Value Type
212      * @return Description of type instance of ListenableFuture
213      */
214     public static @NonNull ParameterizedType listenableFutureTypeFor(final Type valueType) {
215         return parameterizedTypeFor(LISTENABLE_FUTURE, valueType);
216     }
217
218     /**
219      * Returns an instance of {@link ParameterizedType} describing the typed
220      * {@link Builder}&lt;V&gt; with concrete type of value.
221      *
222      * @param valueType Value Type
223      * @return Description of type instance of Builder
224      */
225     public static @NonNull ParameterizedType builderTypeFor(final Type valueType) {
226         return parameterizedTypeFor(BUILDER, valueType);
227     }
228
229     /**
230      * Creates instance of type {@link org.opendaylight.mdsal.binding.model.api.ParameterizedType ParameterizedType}.
231      *
232      * @param type JAVA <code>Type</code> for raw type
233      * @param parameters JAVA <code>Type</code>s for actual parameter types
234      * @return <code>ParametrizedType</code> representation of <code>type</code> and its <code>parameters</code>
235      * @throws NullPointerException if any argument or any member of {@code parameters} is null
236      */
237     public static @NonNull ParameterizedType parameterizedTypeFor(final Type type, final Type... parameters) {
238         return new ParametrizedTypeImpl(type, parameters);
239     }
240
241     /**
242      * Creates instance of type {@link org.opendaylight.mdsal.binding.model.api.WildcardType}.
243      *
244      * @param identifier JavaTypeName of the type
245      * @return <code>WildcardType</code> representation of specified identifier
246      */
247     public static WildcardType wildcardTypeFor(final JavaTypeName identifier) {
248         return new WildcardTypeImpl(identifier);
249     }
250
251     public static @Nullable String getOuterClassName(final Type valueType) {
252         return valueType.getIdentifier().immediatelyEnclosingClass().map(Object::toString).orElse(null);
253     }
254
255     /**
256      * Represents concrete JAVA type.
257      */
258     private static final class ConcreteTypeImpl extends AbstractBaseType implements ConcreteType {
259         private final Restrictions restrictions;
260
261         /**
262          * Creates instance of this class with package <code>pkName</code> and with the type name <code>name</code>.
263          *
264          * @param pkName string with package name
265          * @param name string with the name of the type
266          */
267         ConcreteTypeImpl(final JavaTypeName identifier, final Restrictions restrictions) {
268             super(identifier);
269             this.restrictions = restrictions;
270         }
271
272         @Override
273         public Restrictions getRestrictions() {
274             return this.restrictions;
275         }
276     }
277
278     /**
279      * Represents concrete JAVA type with changed restriction values.
280      */
281     private static final class BaseTypeWithRestrictionsImpl extends AbstractBaseType implements
282             BaseTypeWithRestrictions {
283         private final Restrictions restrictions;
284
285         /**
286          * Creates instance of this class with package <code>pkName</code> and with the type name <code>name</code>.
287          *
288          * @param pkName string with package name
289          * @param name string with the name of the type
290          */
291         BaseTypeWithRestrictionsImpl(final JavaTypeName identifier, final Restrictions restrictions) {
292             super(identifier);
293             this.restrictions = requireNonNull(restrictions);
294         }
295
296         @Override
297         public Restrictions getRestrictions() {
298             return this.restrictions;
299         }
300     }
301
302     /**
303      * Represents parametrized JAVA type.
304      */
305     private static class ParametrizedTypeImpl extends AbstractBaseType implements ParameterizedType {
306         /**
307          * Array of JAVA actual type parameters.
308          */
309         private final Type[] actualTypes;
310
311         /**
312          * JAVA raw type (like List, Set, Map...).
313          */
314         private final Type rawType;
315
316         /**
317          * Creates instance of this class with concrete rawType and array of actual parameters.
318          *
319          * @param rawType JAVA <code>Type</code> for raw type
320          * @param actTypes array of actual parameters
321          */
322         ParametrizedTypeImpl(final Type rawType, final Type[] actTypes) {
323             super(rawType.getIdentifier());
324             this.rawType = requireNonNull(rawType);
325             actualTypes = actTypes.clone();
326             if (Arrays.stream(actualTypes).anyMatch(Objects::isNull)) {
327                 throw new NullPointerException("actTypes contains a null");
328             }
329         }
330
331         @Override
332         public Type[] getActualTypeArguments() {
333
334             return this.actualTypes;
335         }
336
337         @Override
338         public Type getRawType() {
339             return this.rawType;
340         }
341     }
342
343     /**
344      * Represents JAVA bounded wildcard type.
345      */
346     private static class WildcardTypeImpl extends AbstractBaseType implements WildcardType {
347         /**
348          * Creates instance of this class with concrete package and type name.
349          *
350          * @param packageName string with the package name
351          * @param typeName string with the name of type
352          */
353         WildcardTypeImpl(final JavaTypeName identifier) {
354             super(identifier);
355         }
356     }
357
358     public static <T extends Number & Comparable<T>> DefaultRestrictions<T> getDefaultRestrictions(final T min,
359             final T max) {
360         return new DefaultRestrictions<>(min, max);
361     }
362
363     private static final class DefaultRestrictions<T extends Number & Comparable<T>> implements Restrictions {
364         private final RangeConstraint<?> rangeConstraint;
365
366         DefaultRestrictions(final T min, final T max) {
367             this.rangeConstraint = new DefaultRangeConstraint<>(min, max);
368         }
369
370         @Override
371         public boolean isEmpty() {
372             return false;
373         }
374
375         @Override
376         public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
377             return Optional.of(rangeConstraint);
378         }
379
380         @Override
381         public List<PatternConstraint> getPatternConstraints() {
382             return Collections.emptyList();
383         }
384
385         @Override
386         public Optional<LengthConstraint> getLengthConstraint() {
387             return Optional.empty();
388         }
389     }
390
391     private static final class DefaultRangeConstraint<T extends Number & Comparable<T>> implements RangeConstraint<T> {
392         private final T min;
393         private final T max;
394
395         DefaultRangeConstraint(final T min, final T max) {
396             this.min = requireNonNull(min);
397             this.max = requireNonNull(max);
398         }
399
400         @Override
401         public Optional<String> getErrorAppTag() {
402             return Optional.empty();
403         }
404
405         @Override
406         public Optional<String> getErrorMessage() {
407             return Optional.empty();
408         }
409
410         @Override
411         public Optional<String> getDescription() {
412             return Optional.empty();
413         }
414
415         @Override
416         public Optional<String> getReference() {
417             return Optional.empty();
418         }
419
420         @Override
421         public RangeSet<T> getAllowedRanges() {
422             return ImmutableRangeSet.of(Range.closed(min, max));
423         }
424     }
425 }