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