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