JavaIdentifierNormalizer ThreadSafe/Memory leak 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.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     /**
127      * Returns an instance of {@link ParameterizedType} describing the typed
128      * {@link Map}&lt;K,V&gt;
129      *
130      * @param keyType
131      *            Key Type
132      * @param valueType
133      *            Value Type
134      * @return Description of generic type instance
135      */
136     public static ParameterizedType mapTypeFor(final Type keyType, final Type valueType) {
137         return parameterizedTypeFor(MAP_TYPE, keyType, valueType);
138     }
139
140     /**
141      * Returns an instance of {@link ParameterizedType} describing the typed
142      * {@link Set}&lt;V&gt; with concrete type of value.
143      *
144      * @param valueType
145      *            Value Type
146      * @return Description of generic type instance of Set
147      */
148     public static ParameterizedType setTypeFor(final Type valueType) {
149         return parameterizedTypeFor(SET_TYPE, valueType);
150     }
151
152     /**
153      * Returns an instance of {@link ParameterizedType} describing the typed
154      * {@link List}&lt;V&gt; with concrete type of value.
155      *
156      * @param valueType
157      *            Value Type
158      * @return Description of type instance of List
159      */
160     public static ParameterizedType listTypeFor(final Type valueType) {
161         return parameterizedTypeFor(LIST_TYPE, valueType);
162     }
163
164     /**
165      * Creates instance of type
166      * {@link ParameterizedType
167      * ParameterizedType}
168      *
169      * @param type
170      *            JAVA <code>Type</code> for raw type
171      * @param parameters
172      *            JAVA <code>Type</code>s for actual parameter types
173      * @return <code>ParametrizedType</code> reprezentation of <code>type</code>
174      *         and its parameters <code>parameters</code>
175      */
176     public static ParameterizedType parameterizedTypeFor(final Type type, final Type... parameters) {
177         return new ParameterizedTypeImpl(type, parameters);
178     }
179
180     /**
181      * Creates instance of type
182      * {@link WildcardType
183      * WildcardType}
184      *
185      * @param packageName
186      *            string with the package name
187      * @param typeName
188      *            string with the type name
189      * @return <code>WildcardType</code> representation of
190      *         <code>packageName</code> and <code>typeName</code>
191      */
192     public static WildcardType wildcardTypeFor(final String packageName, final String typeName) {
193         return new WildcardTypeImpl(packageName, typeName);
194     }
195
196     /**
197      * Creates instance of type
198      * {@link WildcardType
199      * WildcardType}
200      *
201      * @param packageName
202      *            string with the package name
203      * @param typeName
204      *            string with the type name
205      * @param isPkNameNormalized
206      *            if the package name has been normalized
207      * @param isTypeNormalized
208      *            if the type name has been normalized
209      * @return <code>WildcardType</code> representation of
210      *         <code>packageName</code> and <code>typeName</code>
211      */
212     public static WildcardType wildcardTypeFor(final String packageName, final String typeName,
213             final boolean isPkNameNormalized, final boolean isTypeNormalized, ModuleContext context) {
214         return new WildcardTypeImpl(packageName, typeName, isPkNameNormalized, isTypeNormalized, context);
215     }
216
217     /**
218      * Creates instance of
219      * {@link ParameterizedType
220      * ParameterizedType} where raw type is
221      * {@link Augmentable} and actual
222      * parameter is <code>valueType</code>.
223      *
224      * @param valueType
225      *            JAVA <code>Type</code> with actual parameter
226      * @return <code>ParametrizedType</code> representation of raw type
227      *         <code>Augmentable</code> with actual parameter
228      *         <code>valueType</code>
229      */
230     public static ParameterizedType augmentableTypeFor(final Type valueType) {
231         final Type augmentable = typeForClass(Augmentable.class);
232         return parameterizedTypeFor(augmentable, valueType);
233     }
234
235     /**
236      * Creates instance of
237      * {@link ParameterizedType
238      * ParameterizedType} where raw type is
239      * {@link Augmentation} and actual
240      * parameter is <code>valueType</code>.
241      *
242      * @param valueType
243      *            JAVA <code>Type</code> with actual parameter
244      * @return <code>ParametrizedType</code> reprezentation of raw type
245      *         <code>Augmentation</code> with actual parameter
246      *         <code>valueType</code>
247      */
248     public static ParameterizedType augmentationTypeFor(final Type valueType) {
249         final Type augmentation = typeForClass(Augmentation.class);
250         return parameterizedTypeFor(augmentation, valueType);
251     }
252
253     @Nullable
254     public static String getOuterClassName(final Type valueType) {
255         final String pkgName = valueType.getPackageName();
256         final int index = CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName);
257         if (index >= 0) {
258             // It is inner class.
259             return Iterables.getFirst(DOT_SPLITTER.split(pkgName.substring(index)), null);
260         }
261         return null;
262     }
263
264     @Nullable
265     public static String getOuterClassPackageName(final Type valueType) {
266         final String pkgName = valueType.getPackageName();
267         final int index = CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName);
268         if (index >= 1) {
269             return pkgName.substring(0, index - 1);
270         }
271         return pkgName;
272     }
273
274     /**
275      *
276      * Represents concrete JAVA type.
277      *
278      */
279     private static final class ConcreteTypeImpl extends AbstractBaseType implements ConcreteType {
280
281         private final Restrictions restrictions;
282
283         /**
284          * Creates instance of this class with package <code>pkName</code> and
285          * with the type name <code>name</code>.
286          *
287          * @param pkName
288          *            string with package name
289          * @param name
290          *            string with the name of the type
291          */
292         private ConcreteTypeImpl(final String pkName, final String name, final Restrictions restrictions) {
293             super(pkName, name, true,null);
294             this.restrictions = restrictions;
295         }
296
297         @Override
298         public Restrictions getRestrictions() {
299             return this.restrictions;
300         }
301     }
302
303     /**
304      *
305      * Represents concrete JAVA type with changed restriction values.
306      *
307      */
308     private static final class BaseTypeWithRestrictionsImpl extends AbstractBaseType implements BaseTypeWithRestrictions {
309         private final Restrictions restrictions;
310
311         /**
312          * Creates instance of this class with package <code>pkName</code> and
313          * with the type name <code>name</code>.
314          *
315          * @param pkName
316          *            string with package name
317          * @param name
318          *            string with the name of the type
319          */
320         private BaseTypeWithRestrictionsImpl(final String pkName, final String name, final Restrictions restrictions) {
321             super(pkName, name, null);
322             this.restrictions = Preconditions.checkNotNull(restrictions);
323         }
324
325         @Override
326         public Restrictions getRestrictions() {
327             return this.restrictions;
328         }
329     }
330
331     /**
332      *
333      * Represents parametrized JAVA type.
334      *
335      */
336     private static class ParameterizedTypeImpl extends AbstractBaseType implements ParameterizedType {
337         /**
338          * Array of JAVA actual type parameters.
339          */
340         private final Type[] actualTypes;
341
342         /**
343          * JAVA raw type (like List, Set, Map...)
344          */
345         private final Type rawType;
346
347         /**
348          * Creates instance of this class with concrete rawType and array of
349          * actual parameters.
350          *
351          * @param rawType
352          *            JAVA <code>Type</code> for raw type
353          * @param actTypes
354          *            array of actual parameters
355          */
356         public ParameterizedTypeImpl(final Type rawType, final Type[] actTypes) {
357             super(rawType.getPackageName(), rawType.getName(), true, null);
358             this.rawType = rawType;
359             this.actualTypes = actTypes.clone();
360         }
361
362         @Override
363         public Type[] getActualTypeArguments() {
364
365             return this.actualTypes;
366         }
367
368         @Override
369         public Type getRawType() {
370             return this.rawType;
371         }
372     }
373
374     /**
375      *
376      * Represents JAVA bounded wildcard type.
377      *
378      */
379     private static class WildcardTypeImpl extends AbstractBaseType implements WildcardType {
380         /**
381          * Creates instance of this class with concrete package and type name.
382          *
383          * @param packageName
384          *            string with the package name
385          * @param typeName
386          *            string with the name of type
387          */
388         //FIXME: doesn't seem to be called at all
389         public WildcardTypeImpl(final String packageName, final String typeName) {
390             super(packageName, typeName, null);
391         }
392
393         /**
394          * Creates instance of this class with concrete package and type name.
395          *
396          * @param packageName
397          *            string with the package name
398          * @param typeName
399          *            string with the name of type
400          * @param isPkNameNormalized
401          *            if the package name has been normalized
402          * @param isTypeNormalized
403          *            if the type name has been normalized
404          */
405         public WildcardTypeImpl(final String packageName, final String typeName, final boolean isPkNameNormalized,
406                 final boolean isTypeNormalized, ModuleContext context) {
407             super(packageName, typeName, isPkNameNormalized, isTypeNormalized, context);
408         }
409     }
410
411     public static <T extends Number> DefaultRestrictions<T> getDefaultRestrictions(final T min, final T max) {
412         return new DefaultRestrictions<>(min, max);
413     }
414
415     private static final class DefaultRestrictions<T extends Number> implements Restrictions {
416         private final List<RangeConstraint> rangeConstraints;
417
418         private DefaultRestrictions(final T min, final T max) {
419             Preconditions.checkNotNull(min);
420             Preconditions.checkNotNull(max);
421             this.rangeConstraints = Collections.singletonList(BaseConstraints.newRangeConstraint(min, max, Optional
422                     .absent(), Optional.absent()));
423         }
424
425         @Override
426         public boolean isEmpty() {
427             return false;
428         }
429
430         @Override
431         public List<RangeConstraint> getRangeConstraints() {
432             return this.rangeConstraints;
433         }
434
435         @Override
436         public List<PatternConstraint> getPatternConstraints() {
437             return ImmutableList.of();
438         }
439
440         @Override
441         public List<LengthConstraint> getLengthConstraints() {
442             return ImmutableList.of();
443         }
444     }
445 }