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