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