6f55283cb13fc867b53b806d698cabef73737cdf
[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
197      * {@link ParameterizedType
198      * ParameterizedType} where raw type is
199      * {@link Augmentable} and actual
200      * parameter is <code>valueType</code>.
201      *
202      * @param valueType
203      *            JAVA <code>Type</code> with actual parameter
204      * @return <code>ParametrizedType</code> representation of raw type
205      *         <code>Augmentable</code> with actual parameter
206      *         <code>valueType</code>
207      */
208     public static ParameterizedType augmentableTypeFor(final Type valueType) {
209         final Type augmentable = typeForClass(Augmentable.class);
210         return parameterizedTypeFor(augmentable, valueType);
211     }
212
213     /**
214      * Creates instance of
215      * {@link ParameterizedType
216      * ParameterizedType} where raw type is
217      * {@link Augmentation} and actual
218      * parameter is <code>valueType</code>.
219      *
220      * @param valueType
221      *            JAVA <code>Type</code> with actual parameter
222      * @return <code>ParametrizedType</code> reprezentation of raw type
223      *         <code>Augmentation</code> with actual parameter
224      *         <code>valueType</code>
225      */
226     public static ParameterizedType augmentationTypeFor(final Type valueType) {
227         final Type augmentation = typeForClass(Augmentation.class);
228         return parameterizedTypeFor(augmentation, valueType);
229     }
230
231     @Nullable
232     public static String getOuterClassName(final Type valueType) {
233         final String pkgName = valueType.getPackageName();
234         final int index = CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName);
235         if (index >= 0) {
236             // It is inner class.
237             return Iterables.getFirst(DOT_SPLITTER.split(pkgName.substring(index)), null);
238         }
239         return null;
240     }
241
242     @Nullable
243     public static String getOuterClassPackageName(final Type valueType) {
244         final String pkgName = valueType.getPackageName();
245         final int index = CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName);
246         if (index >= 1) {
247             return pkgName.substring(0, index - 1);
248         }
249         return pkgName;
250     }
251
252     /**
253      *
254      * Represents concrete JAVA type.
255      *
256      */
257     private static final class ConcreteTypeImpl extends AbstractBaseType implements ConcreteType {
258
259         private final Restrictions restrictions;
260
261         /**
262          * Creates instance of this class with package <code>pkName</code> and
263          * with the type name <code>name</code>.
264          *
265          * @param pkName
266          *            string with package name
267          * @param name
268          *            string with the name of the type
269          */
270         private ConcreteTypeImpl(final String pkName, final String name, final Restrictions restrictions) {
271             super(pkName, name);
272             this.restrictions = restrictions;
273         }
274
275         @Override
276         public Restrictions getRestrictions() {
277             return this.restrictions;
278         }
279     }
280
281     /**
282      *
283      * Represents concrete JAVA type with changed restriction values.
284      *
285      */
286     private static final class BaseTypeWithRestrictionsImpl extends AbstractBaseType implements BaseTypeWithRestrictions {
287         private final Restrictions restrictions;
288
289         /**
290          * Creates instance of this class with package <code>pkName</code> and
291          * with the type name <code>name</code>.
292          *
293          * @param pkName
294          *            string with package name
295          * @param name
296          *            string with the name of the type
297          */
298         private BaseTypeWithRestrictionsImpl(final String pkName, final String name, final Restrictions restrictions) {
299             super(pkName, name);
300             this.restrictions = Preconditions.checkNotNull(restrictions);
301         }
302
303         @Override
304         public Restrictions getRestrictions() {
305             return this.restrictions;
306         }
307     }
308
309     /**
310      *
311      * Represents parametrized JAVA type.
312      *
313      */
314     private static class ParameterizedTypeImpl extends AbstractBaseType implements ParameterizedType {
315         /**
316          * Array of JAVA actual type parameters.
317          */
318         private final Type[] actualTypes;
319
320         /**
321          * JAVA raw type (like List, Set, Map...)
322          */
323         private final Type rawType;
324
325         /**
326          * Creates instance of this class with concrete rawType and array of
327          * actual parameters.
328          *
329          * @param rawType
330          *            JAVA <code>Type</code> for raw type
331          * @param actTypes
332          *            array of actual parameters
333          */
334         public ParameterizedTypeImpl(final Type rawType, final Type[] actTypes) {
335             super(rawType.getPackageName(), rawType.getName(), true);
336             this.rawType = rawType;
337             this.actualTypes = actTypes.clone();
338         }
339
340         @Override
341         public Type[] getActualTypeArguments() {
342
343             return this.actualTypes;
344         }
345
346         @Override
347         public Type getRawType() {
348             return this.rawType;
349         }
350     }
351
352     /**
353      *
354      * Represents JAVA bounded wildcard type.
355      *
356      */
357     private static class WildcardTypeImpl extends AbstractBaseType implements WildcardType {
358         /**
359          * Creates instance of this class with concrete package and type name.
360          *
361          * @param packageName
362          *            string with the package name
363          * @param typeName
364          *            string with the name of type
365          */
366         public WildcardTypeImpl(final String packageName, final String typeName) {
367             super(packageName, typeName);
368         }
369     }
370
371     public static <T extends Number> DefaultRestrictions<T> getDefaultRestrictions(final T min, final T max) {
372         return new DefaultRestrictions<>(min, max);
373     }
374
375     private static final class DefaultRestrictions<T extends Number> implements Restrictions {
376         private final List<RangeConstraint> rangeConstraints;
377
378         private DefaultRestrictions(final T min, final T max) {
379             Preconditions.checkNotNull(min);
380             Preconditions.checkNotNull(max);
381             this.rangeConstraints = Collections.singletonList(BaseConstraints.newRangeConstraint(min, max, Optional
382                     .absent(), Optional.absent()));
383         }
384
385         @Override
386         public boolean isEmpty() {
387             return false;
388         }
389
390         @Override
391         public List<RangeConstraint> getRangeConstraints() {
392             return this.rangeConstraints;
393         }
394
395         @Override
396         public List<PatternConstraint> getPatternConstraints() {
397             return ImmutableList.of();
398         }
399
400         @Override
401         public List<LengthConstraint> getLengthConstraints() {
402             return ImmutableList.of();
403         }
404     }
405 }