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