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