bef1e9edd9efdc7be5d8bb36d430d44ce1d09f2d
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / JavaFileTemplate.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o. 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 package org.opendaylight.mdsal.binding.java.api.generator;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTABLE_AUGMENTATION_NAME;
14 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.GETTER_PREFIX;
15
16 import com.google.common.collect.ImmutableSortedSet;
17 import java.lang.reflect.Method;
18 import java.util.AbstractMap;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Comparator;
23 import java.util.HashMap;
24 import java.util.LinkedHashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.regex.Pattern;
31 import java.util.stream.Collectors;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.eclipse.xtext.xbase.lib.StringExtensions;
34 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
35 import org.opendaylight.mdsal.binding.model.api.DefaultType;
36 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
37 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
38 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
39 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
40 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
41 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
42 import org.opendaylight.mdsal.binding.model.api.Restrictions;
43 import org.opendaylight.mdsal.binding.model.api.Type;
44 import org.opendaylight.mdsal.binding.model.util.Types;
45 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
46 import org.opendaylight.yangtools.yang.binding.Augmentable;
47 import org.opendaylight.yangtools.yang.binding.CodeHelpers;
48
49 /**
50  * Base Java file template. Contains a non-null type and imports which the generated code refers to.
51  */
52 class JavaFileTemplate {
53     /**
54      * {@code java.lang.Class} as a JavaTypeName.
55      */
56     static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
57     /**
58      * {@code java.lang.Deprecated} as a JavaTypeName.
59      */
60     static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
61     /**
62      * {@code java.lang.NullPointerException} as a JavaTypeName.
63      */
64     static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
65     /**
66      * {@code java.lang.Override} as a JavaTypeName.
67      */
68     static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
69     /**
70      * {@code java.lang.void} as a JavaTypeName.
71      */
72     static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
73     /**
74      * {@code java.lang.SuppressWarnings} as a JavaTypeName.
75      */
76     static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
77
78     /**
79      * {@code java.util.Arrays} as a JavaTypeName.
80      */
81     static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
82     /**
83      * {@code java.util.HashMap} as a JavaTypeName.
84      */
85     static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
86     /**
87      * {@code java.util.List} as a JavaTypeName.
88      */
89     static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
90     /**
91      * {@code java.util.Map} as a JavaTypeName.
92      */
93     static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
94     /**
95      * {@code java.util.Objects} as a JavaTypeName.
96      */
97     static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
98     /**
99      * {@code java.util.regex.Pattern} as a JavaTypeName.
100      */
101     static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
102
103     /**
104      * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
105      */
106     static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
107     /**
108      * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
109      */
110     static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
111
112     /**
113      * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
114      */
115     static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
116
117     private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
118     private static final Type AUGMENTATION_RET_TYPE;
119
120     static {
121         final Method m;
122         try {
123             m = Augmentable.class.getDeclaredMethod(AUGMENTABLE_AUGMENTATION_NAME, Class.class);
124         } catch (NoSuchMethodException e) {
125             throw new ExceptionInInitializerError(e);
126         }
127
128         AUGMENTATION_RET_TYPE = DefaultType.of(JavaTypeName.create(m.getReturnType()));
129     }
130
131     private final AbstractJavaGeneratedType javaType;
132     private final GeneratedType type;
133
134     JavaFileTemplate(final @NonNull GeneratedType type) {
135         this(new TopLevelJavaGeneratedType(type), type);
136     }
137
138     JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
139         this.javaType = requireNonNull(javaType);
140         this.type = requireNonNull(type);
141     }
142
143     final AbstractJavaGeneratedType javaType() {
144         return javaType;
145     }
146
147     final GeneratedType type() {
148         return type;
149     }
150
151     final String generateImportBlock() {
152         verify(javaType instanceof TopLevelJavaGeneratedType);
153         return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
154                 .collect(Collectors.joining());
155     }
156
157     final @NonNull String importedJavadocName(final @NonNull Type intype) {
158         return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
159     }
160
161     final @NonNull String importedName(final @NonNull Type intype) {
162         return javaType.getReferenceString(intype);
163     }
164
165     final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
166         return javaType.getReferenceString(intype, annotation);
167     }
168
169     final @NonNull String importedName(final Class<?> cls) {
170         return importedName(Types.typeForClass(cls));
171     }
172
173     final @NonNull String importedName(final @NonNull JavaTypeName intype) {
174         return javaType.getReferenceString(intype);
175     }
176
177     final @NonNull String importedNonNull(final @NonNull Type intype) {
178         return importedName(intype, importedName(NONNULL));
179     }
180
181     final @NonNull String importedNullable(final @NonNull Type intype) {
182         return importedName(intype, importedName(NULLABLE));
183     }
184
185     final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
186         return fullyQualifiedName(intype, importedName(NONNULL));
187     }
188
189     final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
190         return javaType.getFullyQualifiedReference(intype, annotation);
191     }
192
193     // Exposed for BuilderTemplate
194     boolean isLocalInnerClass(final JavaTypeName name) {
195         final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
196         return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
197     }
198
199     final CharSequence generateInnerClass(final GeneratedType innerClass) {
200         if (!(innerClass instanceof GeneratedTransferObject)) {
201             return "";
202         }
203
204         final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
205         final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
206         return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
207                 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
208     }
209
210     /**
211      * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
212      * {@link Arrays} if the property is an array, {@link Objects} otherwise.
213      *
214      * @param property Generated property
215      * @return Imported class name
216      */
217     final String importedUtilClass(final GeneratedProperty property) {
218         return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
219     }
220
221     /**
222      * Run type analysis, which results in identification of the augmentable type, as well as all methods available
223      * to the type, expressed as properties.
224      */
225     static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
226         final Set<MethodSignature> methods = new LinkedHashSet<>();
227         final Type augmentType = createMethods(type, methods);
228         final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
229                 .build();
230
231         return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
232     }
233
234     static final Restrictions restrictionsForSetter(final Type actualType) {
235         return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
236     }
237
238     static final Restrictions getRestrictions(final Type type) {
239         if (type instanceof ConcreteType) {
240             return ((ConcreteType) type).getRestrictions();
241         }
242         if (type instanceof GeneratedTransferObject) {
243             return ((GeneratedTransferObject) type).getRestrictions();
244         }
245         return null;
246     }
247
248     /**
249      * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
250      *
251      * @param property Generated property
252      * @return The string used to clone the property, or an empty string
253      */
254     static final String cloneCall(final GeneratedProperty property) {
255         return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
256     }
257
258     /**
259      * Returns set of method signature instances which contains all the methods of the <code>genType</code>
260      * and all the methods of the implemented interfaces.
261      *
262      * @returns set of method signature instances
263      */
264     private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
265         methods.addAll(type.getMethodDefinitions());
266         return collectImplementedMethods(type, methods, type.getImplements());
267     }
268
269     /**
270      * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
271      * and recursively their implemented interfaces.
272      *
273      * @param methods set of method signatures
274      * @param implementedIfcs list of implemented interfaces
275      */
276     private static ParameterizedType collectImplementedMethods(final GeneratedType type,
277             final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
278         if (implementedIfcs == null || implementedIfcs.isEmpty()) {
279             return null;
280         }
281
282         ParameterizedType augmentType = null;
283         for (Type implementedIfc : implementedIfcs) {
284             if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
285                 final GeneratedType ifc = (GeneratedType) implementedIfc;
286                 methods.addAll(ifc.getMethodDefinitions());
287
288                 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
289                 if (t != null && augmentType == null) {
290                     augmentType = t;
291                 }
292             } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
293                 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, DefaultType.of(type.getIdentifier()));
294             }
295         }
296
297         return augmentType;
298     }
299
300     /**
301      * Creates set of generated property instances from getter <code>methods</code>.
302      *
303      * @param methods set of method signature instances which should be transformed to list of properties
304      * @return set of generated property instances which represents the getter <code>methods</code>
305      */
306     private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
307         if (methods == null || methods.isEmpty()) {
308             return Collections.emptySet();
309         }
310         final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
311         for (MethodSignature m : methods) {
312             final BuilderGeneratedProperty createdField = propertyFromGetter(m);
313             if (createdField != null) {
314                 result.add(createdField);
315             }
316         }
317         return result;
318     }
319
320     /**
321      * Creates generated property instance from the getter <code>method</code> name and return type.
322      *
323      * @param method method signature from which is the method name and return type obtained
324      * @return generated property instance for the getter <code>method</code>
325      * @throws IllegalArgumentException <ul>
326      *  <li>if the <code>method</code> equals <code>null</code></li>
327      *  <li>if the name of the <code>method</code> equals <code>null</code></li>
328      *  <li>if the name of the <code>method</code> is empty</li>
329      *  <li>if the return type of the <code>method</code> equals <code>null</code></li>
330      * </ul>
331      */
332     private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
333         checkArgument(method != null);
334         checkArgument(method.getReturnType() != null);
335         checkArgument(method.getName() != null);
336         checkArgument(!method.getName().isEmpty());
337         if (method.isDefault()) {
338             return null;
339         }
340         if (!BindingMapping.isGetterMethodName(method.getName())) {
341             return null;
342         }
343
344         final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX.length()));
345         return new BuilderGeneratedProperty(fieldName, method);
346     }
347 }