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