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