226b3295a959254d2f53c9323f7ba749f27f3696
[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.yang.binding.Augmentable;
37 import org.opendaylight.yangtools.yang.binding.Augmentation;
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 =
44             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     public static final ConcreteType CHAR_ARRAY = typeForClass(char[].class);
59
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      * Creates instance of type
202      * {@link org.opendaylight.mdsal.binding.model.api.ParameterizedType
203      * ParameterizedType}
204      *
205      * @param type
206      *            JAVA <code>Type</code> for raw type
207      * @param parameters
208      *            JAVA <code>Type</code>s for actual parameter types
209      * @return <code>ParametrizedType</code> representation of <code>type</code>
210      *         and its parameters <code>parameters</code>
211      * @throws NullPointerException if any argument or any member of {@code parameters} is null
212      */
213     public static ParameterizedType parameterizedTypeFor(final Type type, final Type... parameters) {
214         return new ParametrizedTypeImpl(type, parameters);
215     }
216
217     /**
218      * Creates instance of type {@link org.opendaylight.mdsal.binding.model.api.WildcardType}.
219      *
220      * @param identifier JavaTypeName of the type
221      * @return <code>WildcardType</code> representation of specified identifier
222      */
223     public static WildcardType wildcardTypeFor(final JavaTypeName identifier) {
224         return new WildcardTypeImpl(identifier);
225     }
226
227     /**
228      * Creates instance of
229      * {@link org.opendaylight.mdsal.binding.model.api.ParameterizedType
230      * ParameterizedType} where raw type is
231      * {@link org.opendaylight.yangtools.yang.binding.Augmentable} and actual
232      * parameter is <code>valueType</code>.
233      *
234      * @param valueType
235      *            JAVA <code>Type</code> with actual parameter
236      * @return <code>ParametrizedType</code> representation of raw type
237      *         <code>Augmentable</code> with actual parameter
238      *         <code>valueType</code>
239      */
240     public static ParameterizedType augmentableTypeFor(final Type valueType) {
241         final Type augmentable = typeForClass(Augmentable.class);
242         return parameterizedTypeFor(augmentable, valueType);
243     }
244
245     /**
246      * Creates instance of
247      * {@link org.opendaylight.mdsal.binding.model.api.ParameterizedType
248      * ParameterizedType} where raw type is
249      * {@link org.opendaylight.yangtools.yang.binding.Augmentation} and actual
250      * parameter is <code>valueType</code>.
251      *
252      * @param valueType
253      *            JAVA <code>Type</code> with actual parameter
254      * @return <code>ParametrizedType</code> reprezentation of raw type
255      *         <code>Augmentation</code> with actual parameter
256      *         <code>valueType</code>
257      */
258     public static ParameterizedType augmentationTypeFor(final Type valueType) {
259         final Type augmentation = typeForClass(Augmentation.class);
260         return parameterizedTypeFor(augmentation, valueType);
261     }
262
263     public static @Nullable String getOuterClassName(final Type valueType) {
264         return valueType.getIdentifier().immediatelyEnclosingClass().map(Object::toString).orElse(null);
265     }
266
267     /**
268      *
269      * Represents concrete JAVA type.
270      *
271      */
272     private static final class ConcreteTypeImpl extends AbstractBaseType implements ConcreteType {
273         private final Restrictions restrictions;
274
275         /**
276          * Creates instance of this class with package <code>pkName</code> and
277          * with the type name <code>name</code>.
278          *
279          * @param pkName
280          *            string with package name
281          * @param name
282          *            string with the name of the type
283          */
284         ConcreteTypeImpl(final JavaTypeName identifier, final Restrictions restrictions) {
285             super(identifier);
286             this.restrictions = restrictions;
287         }
288
289         @Override
290         public Restrictions getRestrictions() {
291             return this.restrictions;
292         }
293     }
294
295     /**
296      * Represents concrete JAVA type with changed restriction values.
297      */
298     private static final class BaseTypeWithRestrictionsImpl extends AbstractBaseType implements BaseTypeWithRestrictions {
299         private final Restrictions restrictions;
300
301         /**
302          * Creates instance of this class with package <code>pkName</code> and
303          * with the type name <code>name</code>.
304          *
305          * @param pkName
306          *            string with package name
307          * @param name
308          *            string with the name of the type
309          */
310         BaseTypeWithRestrictionsImpl(final JavaTypeName identifier, final Restrictions restrictions) {
311             super(identifier);
312             this.restrictions = Preconditions.checkNotNull(restrictions);
313         }
314
315         @Override
316         public Restrictions getRestrictions() {
317             return this.restrictions;
318         }
319     }
320
321     /**
322      * Represents parametrized JAVA type.
323      */
324     private static class ParametrizedTypeImpl extends AbstractBaseType implements ParameterizedType {
325         /**
326          * Array of JAVA actual type parameters.
327          */
328         private final Type[] actualTypes;
329
330         /**
331          * JAVA raw type (like List, Set, Map...)
332          */
333         private final Type rawType;
334
335         @Override
336         public Type[] getActualTypeArguments() {
337
338             return this.actualTypes;
339         }
340
341         @Override
342         public Type getRawType() {
343             return this.rawType;
344         }
345
346         /**
347          * Creates instance of this class with concrete rawType and array of
348          * actual parameters.
349          *
350          * @param rawType
351          *            JAVA <code>Type</code> for raw type
352          * @param actTypes
353          *            array of actual parameters
354          */
355         public ParametrizedTypeImpl(final Type rawType, final Type[] actTypes) {
356             super(rawType.getIdentifier());
357             this.rawType = requireNonNull(rawType);
358             actualTypes = actTypes.clone();
359             if (Arrays.stream(actualTypes).anyMatch(Objects::isNull)) {
360                 throw new NullPointerException("actTypes contains a null");
361             }
362         }
363     }
364
365     /**
366      * Represents JAVA bounded wildcard type.
367      */
368     private static class WildcardTypeImpl extends AbstractBaseType implements WildcardType {
369         /**
370          * Creates instance of this class with concrete package and type name.
371          *
372          * @param packageName
373          *            string with the package name
374          * @param typeName
375          *            string with the name of type
376          */
377         WildcardTypeImpl(final JavaTypeName identifier) {
378             super(identifier);
379         }
380     }
381
382     public static <T extends Number& Comparable<T>> DefaultRestrictions<T> getDefaultRestrictions(final T min,
383             final T max) {
384         return new DefaultRestrictions<>(min, max);
385     }
386
387     private static final class DefaultRestrictions<T extends Number & Comparable<T>> implements Restrictions {
388         private final T min;
389         private final T max;
390         private final RangeConstraint<?> rangeConstraint;
391
392         private DefaultRestrictions(final T min, final T max) {
393             this.min = Preconditions.checkNotNull(min);
394             this.max = Preconditions.checkNotNull(max);
395
396             this.rangeConstraint = new RangeConstraint<T>() {
397
398                 @Override
399                 public Optional<String> getErrorAppTag() {
400                     return Optional.empty();
401                 }
402
403                 @Override
404                 public Optional<String> getErrorMessage() {
405                     return Optional.empty();
406                 }
407
408                 @Override
409                 public Optional<String> getDescription() {
410                     return Optional.empty();
411                 }
412
413                 @Override
414                 public Optional<String> getReference() {
415                     return Optional.empty();
416                 }
417
418                 @Override
419                 public RangeSet<T> getAllowedRanges() {
420                     return ImmutableRangeSet.of(Range.closed(min, max));
421                 }
422             };
423         }
424
425         @Override
426         public boolean isEmpty() {
427             return false;
428         }
429
430         @Override
431         public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
432             return Optional.of(rangeConstraint);
433         }
434
435         @Override
436         public List<PatternConstraint> getPatternConstraints() {
437             return Collections.emptyList();
438         }
439
440         @Override
441         public Optional<LengthConstraint> getLengthConstraint() {
442             return Optional.empty();
443         }
444     }
445 }