Switch to Objects.requireNonNull
[mdsal.git] / binding2 / mdsal-binding2-generator-util / src / main / java / org / opendaylight / mdsal / binding / javav2 / generator / util / Types.java
1 /*
2  * Copyright (c) 2017 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
9 package org.opendaylight.mdsal.binding.javav2.generator.util;
10
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.CharMatcher;
15 import com.google.common.base.Splitter;
16 import com.google.common.cache.CacheBuilder;
17 import com.google.common.cache.CacheLoader;
18 import com.google.common.cache.LoadingCache;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableRangeSet;
21 import com.google.common.collect.Iterables;
22 import com.google.common.collect.Range;
23 import com.google.common.collect.RangeSet;
24
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import java.util.Set;
29 import javax.annotation.Nonnull;
30 import javax.annotation.Nullable;
31
32 import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext;
33 import org.opendaylight.mdsal.binding.javav2.model.api.BaseTypeWithRestrictions;
34 import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType;
35 import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType;
36 import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions;
37 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
38 import org.opendaylight.mdsal.binding.javav2.model.api.WildcardType;
39 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
40 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
41 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
42 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
43 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
44 import org.w3c.dom.Document;
45
46 @Beta
47 public final class Types {
48     private static final CacheLoader<Class<?>, ConcreteType> TYPE_LOADER =
49         new CacheLoader<Class<?>, ConcreteType>() {
50
51             @Override
52             public ConcreteType load(@Nonnull final Class<?> key) throws Exception {
53                 return new ConcreteTypeImpl(key.getPackage().getName(), key.getSimpleName(), null);
54             }
55         };
56
57     private static final LoadingCache<Class<?>, ConcreteType> TYPE_CACHE =
58             CacheBuilder.newBuilder().weakKeys().build(TYPE_LOADER);
59
60     public static final ConcreteType BOOLEAN = typeForClass(Boolean.class);
61     public static final ConcreteType CLASS = typeForClass(Class.class);
62     public static final ConcreteType STRING = typeForClass(String.class);
63     public static final ConcreteType VOID = typeForClass(Void.class);
64     public static final ConcreteType DOCUMENT = typeForClass(Document.class);
65
66     public static final ConcreteType BYTE_ARRAY = primitiveType("byte[]", null);
67     public static final ConcreteType CHAR_ARRAY = primitiveType("char[]", null);
68
69     private static final Splitter DOT_SPLITTER = Splitter.on('.');
70     private static final Type SET_TYPE = typeForClass(Set.class);
71     private static final Type LIST_TYPE = typeForClass(List.class);
72     private static final Type MAP_TYPE = typeForClass(Map.class);
73
74     private Types() {
75         throw new UnsupportedOperationException("Utility class");
76     }
77
78     /**
79      * Creates the instance of type
80      * {@link ConcreteType
81      * ConcreteType} which represents JAVA <code>void</code> type.
82      *
83      * @return <code>ConcreteType</code> instance which represents JAVA
84      * <code>void</code>
85      */
86     public static ConcreteType voidType() {
87         return VOID;
88     }
89
90     /**
91      * Creates the instance of type
92      * {@link ConcreteType
93      * ConcreteType} which represents primitive JAVA type for which package
94      * doesn't exist.
95      *
96      * @param primitiveType string containing programmatic construction based on
97      *                      primitive type (e.g byte[])
98      * @return <code>ConcreteType</code> instance which represents programmatic
99      *      construction with primitive JAVA type
100      */
101     public static ConcreteType primitiveType(final String primitiveType, final Restrictions restrictions) {
102         return new ConcreteTypeImpl("", primitiveType, restrictions);
103     }
104
105     /**
106      * Returns an instance of {@link ConcreteType} describing the class.
107      *
108      * @param cls Class to describe
109      * @return Description of class
110      */
111     public static ConcreteType typeForClass(final Class<?> cls) {
112         return TYPE_CACHE.getUnchecked(cls);
113     }
114
115
116     public static ConcreteType typeForClass(final Class<?> cls, final Restrictions restrictions) {
117         if (restrictions == null) {
118             return typeForClass(cls);
119         }
120         if (restrictions instanceof DefaultRestrictions) {
121             return new ConcreteTypeImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions);
122         } else {
123             return new BaseTypeWithRestrictionsImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions);
124         }
125     }
126
127     public static ConcreteType typeForClass(final Class<?> cls, final Restrictions restrictions,
128                                             final ModuleContext moduleContext) {
129         if (restrictions == null) {
130             return typeForClass(cls);
131         }
132         if (restrictions instanceof DefaultRestrictions) {
133             return new ConcreteTypeImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions);
134         } else {
135             return new BaseTypeWithRestrictionsImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions,
136                     moduleContext);
137         }
138     }
139
140     /**
141      * Returns an instance of {@link ParameterizedType} describing the typed.
142      * {@link Map}&lt;K,V&gt;
143      *
144      * @param keyType   Key Type
145      * @param valueType Value Type
146      * @return Description of generic type instance
147      */
148     public static ParameterizedType mapTypeFor(final Type keyType, final Type valueType) {
149         return parameterizedTypeFor(MAP_TYPE, keyType, valueType);
150     }
151
152     /**
153      * Returns an instance of {@link ParameterizedType} describing the typed
154      * {@link Set}&lt;V&gt; with concrete type of value.
155      *
156      * @param valueType Value Type
157      * @return Description of generic type instance of Set
158      */
159     public static ParameterizedType setTypeFor(final Type valueType) {
160         return parameterizedTypeFor(SET_TYPE, valueType);
161     }
162
163     /**
164      * Returns an instance of {@link ParameterizedType} describing the typed
165      * {@link List}&lt;V&gt; with concrete type of value.
166      *
167      * @param valueType Value Type
168      * @return Description of type instance of List
169      */
170     public static ParameterizedType listTypeFor(final Type valueType) {
171         return parameterizedTypeFor(LIST_TYPE, valueType);
172     }
173
174     /**
175      * Creates instance of type {@link ParameterizedType ParameterizedType}.
176      *
177      * @param type       JAVA <code>Type</code> for raw type
178      * @param parameters JAVA <code>Type</code>s for actual parameter types
179      * @return <code>ParametrizedType</code> reprezentation of <code>type</code>
180      *      and its parameters <code>parameters</code>
181      */
182     public static ParameterizedType parameterizedTypeFor(final Type type, final Type... parameters) {
183         return new ParameterizedTypeImpl(type, parameters);
184     }
185
186     /**
187      * Creates instance of type {@link WildcardType WildcardType}.
188      *
189      * @param packageName string with the package name
190      * @param typeName    string with the type name
191      * @return <code>WildcardType</code> representation of
192      * <code>packageName</code> and <code>typeName</code>
193      */
194     public static WildcardType wildcardTypeFor(final String packageName, final String typeName) {
195         return new WildcardTypeImpl(packageName, typeName);
196     }
197
198     /**
199      * Creates instance of type {@link WildcardType WildcardType}.
200      *
201      * @param packageName        string with the package name
202      * @param typeName           string with the type name
203      * @param isPkNameNormalized if the package name has been normalized
204      * @param isTypeNormalized   if the type name has been normalized
205      * @return <code>WildcardType</code> representation of
206      * <code>packageName</code> and <code>typeName</code>
207      */
208     public static WildcardType wildcardTypeFor(final String packageName, final String typeName,
209                                                final boolean isPkNameNormalized, final boolean isTypeNormalized,
210                                                final ModuleContext context) {
211         return new WildcardTypeImpl(packageName, typeName, isPkNameNormalized, isTypeNormalized, context);
212     }
213
214     /**
215      * Creates instance of
216      * {@link ParameterizedType
217      * ParameterizedType} where raw type is
218      * {@link Augmentable} and actual
219      * parameter is <code>valueType</code>.
220      *
221      * @param valueType JAVA <code>Type</code> with actual parameter
222      * @return <code>ParametrizedType</code> representation of raw type
223      * <code>Augmentable</code> with actual parameter
224      * <code>valueType</code>
225      */
226     public static ParameterizedType augmentableTypeFor(final Type valueType) {
227         final Type augmentable = typeForClass(Augmentable.class);
228         return parameterizedTypeFor(augmentable, valueType);
229     }
230
231     /**
232      * Creates instance of
233      * {@link ParameterizedType
234      * ParameterizedType} where raw type is
235      * {@link Augmentation} and actual
236      * parameter is <code>valueType</code>.
237      *
238      * @param valueType JAVA <code>Type</code> with actual parameter
239      * @return <code>ParametrizedType</code> reprezentation of raw type
240      * <code>Augmentation</code> with actual parameter
241      * <code>valueType</code>
242      */
243     public static ParameterizedType augmentationTypeFor(final Type valueType) {
244         final Type augmentation = typeForClass(Augmentation.class);
245         return parameterizedTypeFor(augmentation, valueType);
246     }
247
248     @Nullable
249     public static String getOuterClassName(final Type valueType) {
250         final String pkgName = valueType.getPackageName();
251         final int index = CharMatcher.javaUpperCase().indexIn(pkgName);
252         if (index >= 0) {
253             // It is inner class.
254             return Iterables.getFirst(DOT_SPLITTER.split(pkgName.substring(index)), null);
255         }
256         return null;
257     }
258
259     @Nullable
260     public static String getOuterClassPackageName(final Type valueType) {
261         final String pkgName = valueType.getPackageName();
262         final int index = CharMatcher.javaUpperCase().indexIn(pkgName);
263         if (index >= 1) {
264             return pkgName.substring(0, index - 1);
265         }
266         return pkgName;
267     }
268
269     /**
270      * Represents concrete JAVA type.
271      */
272     private static final class ConcreteTypeImpl extends AbstractBaseType implements ConcreteType {
273
274         private final Restrictions restrictions;
275
276         /**
277          * Creates instance of this class with package <code>pkName</code> and
278          * with the type name <code>name</code>.
279          *
280          * @param pkName string with package name
281          * @param name   string with the name of the type
282          */
283         private ConcreteTypeImpl(final String pkName, final String name, final Restrictions restrictions) {
284             super(pkName, name, true, null);
285             this.restrictions = restrictions;
286         }
287
288         @Override
289         public Restrictions getRestrictions() {
290             return this.restrictions;
291         }
292     }
293
294     /**
295      * Represents concrete JAVA type with changed restriction values.
296      */
297     private static final class BaseTypeWithRestrictionsImpl extends AbstractBaseType implements
298             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 string with package name
306          * @param name   string with the name of the type
307          */
308         private BaseTypeWithRestrictionsImpl(final String pkName, final String name, final Restrictions restrictions) {
309             super(pkName, name, null);
310             this.restrictions = requireNonNull(restrictions);
311         }
312
313         private BaseTypeWithRestrictionsImpl(final String pkName, final String name, final Restrictions restrictions,
314                                              final ModuleContext moduleContext) {
315             super(pkName, name, moduleContext);
316             this.restrictions = requireNonNull(restrictions);
317         }
318
319         @Override
320         public Restrictions getRestrictions() {
321             return this.restrictions;
322         }
323     }
324
325     /**
326      * Represents parametrized JAVA type.
327      */
328     private static class ParameterizedTypeImpl extends AbstractBaseType implements ParameterizedType {
329         /**
330          * Array of JAVA actual type parameters.
331          */
332         private final Type[] actualTypes;
333
334         /**
335          * JAVA raw type (like List, Set, Map...).
336          */
337         private final Type rawType;
338
339         /**
340          * Creates instance of this class with concrete rawType and array of
341          * actual parameters.
342          *
343          * @param rawType  JAVA <code>Type</code> for raw type
344          * @param actTypes array of actual parameters
345          */
346         ParameterizedTypeImpl(final Type rawType, final Type[] actTypes) {
347             super(rawType.getPackageName(), rawType.getName(), true, null);
348             this.rawType = rawType;
349             this.actualTypes = actTypes.clone();
350         }
351
352         @Override
353         public Type[] getActualTypeArguments() {
354
355             return this.actualTypes;
356         }
357
358         @Override
359         public Type getRawType() {
360             return this.rawType;
361         }
362     }
363
364     /**
365      * Represents JAVA bounded wildcard type.
366      */
367     private static class WildcardTypeImpl extends AbstractBaseType implements WildcardType {
368         /**
369          * Creates instance of this class with concrete package and type name.
370          *
371          * @param packageName string with the package name
372          * @param typeName    string with the name of type
373          */
374         //FIXME: doesn't seem to be called at all
375         WildcardTypeImpl(final String packageName, final String typeName) {
376             super(packageName, typeName, null);
377         }
378
379         /**
380          * Creates instance of this class with concrete package and type name.
381          *
382          * @param packageName        string with the package name
383          * @param typeName           string with the name of type
384          * @param isPkNameNormalized if the package name has been normalized
385          * @param isTypeNormalized   if the type name has been normalized
386          */
387         WildcardTypeImpl(final String packageName, final String typeName, final boolean isPkNameNormalized,
388                                 final boolean isTypeNormalized, final ModuleContext context) {
389             super(packageName, typeName, isPkNameNormalized, isTypeNormalized, context);
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 RangeConstraint<T> rangeConstraint;
400
401         private DefaultRestrictions(final T min, final T max) {
402             requireNonNull(min);
403             requireNonNull(max);
404             this.rangeConstraint = new RangeConstraint<T>() {
405
406                 @Override
407                 public Optional<String> getErrorAppTag() {
408                     return Optional.empty();
409                 }
410
411                 @Override
412                 public Optional<String> getErrorMessage() {
413                     return Optional.empty();
414                 }
415
416                 @Override
417                 public Optional<String> getDescription() {
418                     return Optional.empty();
419                 }
420
421                 @Override
422                 public Optional<String> getReference() {
423                     return Optional.empty();
424                 }
425
426                 @Override
427                 public RangeSet<T> getAllowedRanges() {
428                     return ImmutableRangeSet.of(Range.closed(min, max));
429                 }
430             };
431         }
432
433         @Override
434         public boolean isEmpty() {
435             return false;
436         }
437
438         @Override
439         public Optional<RangeConstraint<?>> getRangeConstraint() {
440             return Optional.ofNullable(rangeConstraint);
441         }
442
443         @Override
444         public List<PatternConstraint> getPatternConstraints() {
445             return ImmutableList.of();
446         }
447
448         @Override
449         public Optional<LengthConstraint> getLengthConstraint() {
450             return Optional.empty();
451         }
452     }
453 }