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