Remove getter @Nullable annotations for non-List/Map types
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / InterfaceTemplate.xtend
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.mdsal.binding.java.api.generator
9
10 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.getGetterMethodForNonnull
11 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.isGetterMethodName
12 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.isNonnullMethodName
13 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
14 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTATION_FIELD
15 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.BINDING_EQUALS_NAME
16 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.BINDING_HASHCODE_NAME
17 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.BINDING_TO_STRING_NAME
18 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME
19
20 import com.google.common.annotations.VisibleForTesting;
21 import com.google.common.base.MoreObjects
22 import java.util.List
23 import java.util.Map.Entry
24 import java.util.Set
25 import org.gaul.modernizer_maven_annotations.SuppressModernizer
26 import org.opendaylight.mdsal.binding.model.api.AnnotationType
27 import org.opendaylight.mdsal.binding.model.api.Constant
28 import org.opendaylight.mdsal.binding.model.api.Enumeration
29 import org.opendaylight.mdsal.binding.model.api.GeneratedType
30 import org.opendaylight.mdsal.binding.model.api.MethodSignature
31 import org.opendaylight.mdsal.binding.model.api.Type
32 import org.opendaylight.mdsal.binding.model.util.Types
33 import org.opendaylight.mdsal.binding.model.util.TypeConstants
34
35 /**
36  * Template for generating JAVA interfaces.
37  */
38  @SuppressModernizer
39 class InterfaceTemplate extends BaseTemplate {
40     /**
41      * List of constant instances which are generated as JAVA public static final attributes.
42      */
43     val List<Constant> consts
44
45     /**
46      * List of method signatures which are generated as method declarations.
47      */
48     val List<MethodSignature> methods
49
50     /**
51      * List of enumeration which are generated as JAVA enum type.
52      */
53     val List<Enumeration> enums
54
55     /**
56      * List of generated types which are enclosed inside <code>genType</code>
57      */
58     val List<GeneratedType> enclosedGeneratedTypes
59
60     var Entry<Type, Set<BuilderGeneratedProperty>> typeAnalysis
61
62     /**
63      * Creates the instance of this class which is used for generating the interface file source
64      * code from <code>genType</code>.
65      *
66      * @throws NullPointerException if <code>genType</code> is <code>null</code>
67      */
68     new(GeneratedType genType) {
69         super(genType)
70         consts = genType.constantDefinitions
71         methods = genType.methodDefinitions
72         enums = genType.enumerations
73         enclosedGeneratedTypes = genType.enclosedTypes
74     }
75
76     /**
77      * Template method which generate the whole body of the interface.
78      *
79      * @return string with code for interface body in JAVA format
80      */
81     override body() '''
82         «type.formatDataForJavaDoc.wrapToDocumentation»
83         «type.annotations.generateAnnotations»
84         public interface «type.name»
85             «superInterfaces»
86         {
87
88             «generateInnerClasses»
89
90             «generateEnums»
91
92             «generateConstants»
93
94             «generateMethods»
95
96         }
97
98     '''
99
100     def private generateAnnotations(List<AnnotationType> annotations) '''
101         «IF annotations !== null && !annotations.empty»
102             «FOR annotation : annotations»
103                 «annotation.generateAnnotation»
104             «ENDFOR»
105         «ENDIF»
106     '''
107
108     /**
109      * Template method which generates the interface name declaration.
110      *
111      * @return string with the code for the interface declaration in JAVA format
112      */
113     def private superInterfaces()
114     '''
115     «IF (!type.implements.empty)»
116          extends
117          «FOR type : type.implements SEPARATOR ","»
118              «type.importedName»
119          «ENDFOR»
120      « ENDIF»
121      '''
122
123     /**
124      * Template method which generates inner classes inside this interface.
125      *
126      * @return string with the source code for inner classes in JAVA format
127      */
128     def private generateInnerClasses() '''
129         «IF !enclosedGeneratedTypes.empty»
130             «FOR innerClass : enclosedGeneratedTypes SEPARATOR "\n"»
131                 «generateInnerClass(innerClass)»
132             «ENDFOR»
133         «ENDIF»
134     '''
135
136     /**
137      * Template method which generates JAVA enum type.
138      *
139      * @return string with inner enum source code in JAVA format
140      */
141     def private generateEnums() '''
142         «IF !enums.empty»
143             «FOR e : enums SEPARATOR "\n"»
144                 «val enumTemplate = new EnumTemplate(javaType.getEnclosedType(e.identifier), e)»
145                 «enumTemplate.generateAsInnerClass»
146             «ENDFOR»
147         «ENDIF»
148     '''
149
150     /**
151      * Template method wich generates JAVA constants.
152      *
153      * @return string with constants in JAVA format
154      */
155     def private generateConstants() '''
156         «IF !consts.empty»
157             «FOR c : consts»
158                 «IF !c.name.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)»
159                     «emitConstant(c)»
160                 «ENDIF»
161             «ENDFOR»
162         «ENDIF»
163     '''
164
165     /**
166      * Template method which generates the declaration of the methods.
167      *
168      * @return string with the declaration of methods source code in JAVA format
169      */
170     def private generateMethods() '''
171         «IF !methods.empty»
172             «FOR m : methods SEPARATOR "\n"»
173                 «IF m.isDefault»
174                     «generateDefaultMethod(m)»
175                 «ELSEIF m.isStatic»
176                     «generateStaticMethod(m)»
177                 «ELSEIF m.parameters.empty && m.name.isGetterMethodName»
178                     «generateAccessorMethod(m)»
179                 «ELSE»
180                     «generateMethod(m)»
181                 «ENDIF»
182             «ENDFOR»
183         «ENDIF»
184     '''
185
186     def private generateDefaultMethod(MethodSignature method) {
187         if (method.name.isNonnullMethodName) {
188             generateNonnullMethod(method)
189         } else {
190             switch method.name {
191                 case DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME : generateDefaultImplementedInterface
192                 default :
193                     if (VOID == method.returnType.identifier) {
194                         generateNoopVoidInterfaceMethod(method)
195                     }
196             }
197         }
198     }
199
200     def private generateStaticMethod(MethodSignature method) {
201         switch method.name {
202             case BINDING_EQUALS_NAME : generateBindingEquals
203             case BINDING_HASHCODE_NAME : generateBindingHashCode
204             case BINDING_TO_STRING_NAME : generateBindingToString
205         }
206     }
207
208     def private generateMethod(MethodSignature method) '''
209         «method.comment.asJavadoc»
210         «method.annotations.generateAnnotations»
211         «method.returnType.importedName» «method.name»(«method.parameters.generateParameters»);
212     '''
213
214     def private generateNoopVoidInterfaceMethod(MethodSignature method) '''
215         «method.comment.asJavadoc»
216         «method.annotations.generateAnnotations»
217         default «VOID.importedName» «method.name»(«method.parameters.generateParameters») {
218             // No-op
219         }
220     '''
221
222     def private static accessorJavadoc(MethodSignature method, String orString) {
223         val reference = method.comment?.referenceDescription
224         val propReturn = method.propertyNameFromGetter + ", or " + orString + " if it is not present."
225
226         return wrapToDocumentation('''
227             Return «propReturn».
228
229             «reference.formatReference»
230             @return {@code «method.returnType.fullyQualifiedName»} «propReturn»
231         ''')
232     }
233
234     def private generateAccessorMethod(MethodSignature method) {
235         return '''
236             «accessorJavadoc(method, "{@code null}")»
237             «method.annotations.generateAnnotations»
238             «method.returnType.nullableType» «method.name»();
239         '''
240     }
241
242     def private generateDefaultImplementedInterface() '''
243         @«OVERRIDE.importedName»
244         default «CLASS.importedName»<«type.fullyQualifiedName»> «DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME»() {
245             return «type.fullyQualifiedName».class;
246         }
247     '''
248
249     @VisibleForTesting
250     def generateBindingHashCode() '''
251         «val augmentable = analyzeType»
252         «IF augmentable || !typeAnalysis.value.empty»
253             /**
254              * Default implementation of {@link «Object.importedName»#hashCode()} contract for this interface.
255              * Implementations of this interface are encouraged to defer to this method to get consistent hashing
256              * results across all implementations.
257              *
258              * @param obj Object for which to generate hashCode() result.
259              * @return Hash code value of data modeled by this interface.
260              * @throws «NPE.importedName» if {@code obj} is null
261              */
262             static int «BINDING_HASHCODE_NAME»(final «type.fullyQualifiedNonNull» obj) {
263                 final int prime = 31;
264                 int result = 1;
265                 «FOR property : typeAnalysis.value»
266                     result = prime * result + «property.importedUtilClass».hashCode(obj.«property.getterMethodName»());
267                 «ENDFOR»
268                 «IF augmentable»
269                     result = prime * result + obj.augmentations().hashCode();
270                 «ENDIF»
271                 return result;
272             }
273         «ENDIF»
274     '''
275
276     def private generateBindingEquals() '''
277         «val augmentable = analyzeType»
278         «IF augmentable || !typeAnalysis.value.isEmpty»
279             /**
280              * Default implementation of {@link «Object.importedName»#equals(«Object.importedName»)} contract for this interface.
281              * Implementations of this interface are encouraged to defer to this method to get consistent equality
282              * results across all implementations.
283              *
284              * @param thisObj Object acting as the receiver of equals invocation
285              * @param obj Object acting as argument to equals invocation
286              * @return True if thisObj and obj are considered equal
287              * @throws «NPE.importedName» if {@code thisObj} is null
288              */
289             static boolean «BINDING_EQUALS_NAME»(final «type.fullyQualifiedNonNull» thisObj, final «Types.objectType().importedName» obj) {
290                 if (thisObj == obj) {
291                     return true;
292                 }
293                 final «type.fullyQualifiedName» other = «CODEHELPERS.importedName».checkCast(«type.fullyQualifiedName».class, obj);
294                 if (other == null) {
295                     return false;
296                 }
297                 «FOR property : ByTypeMemberComparator.sort(typeAnalysis.value)»
298                     if (!«property.importedUtilClass».equals(thisObj.«property.getterName»(), other.«property.getterName»())) {
299                         return false;
300                     }
301                 «ENDFOR»
302                 return «IF augmentable»thisObj.augmentations().equals(other.augmentations())«ELSE»true«ENDIF»;
303             }
304         «ENDIF»
305     '''
306
307     def generateBindingToString() '''
308         «val augmentable = analyzeType»
309         /**
310          * Default implementation of {@link «Object.importedName»#toString()} contract for this interface.
311          * Implementations of this interface are encouraged to defer to this method to get consistent string
312          * representations across all implementations.
313          *
314          * @param obj Object for which to generate toString() result.
315          * @return {@link «STRING.importedName»} value of data modeled by this interface.
316          * @throws «NPE.importedName» if {@code obj} is null
317          */
318         static «STRING.importedName» «BINDING_TO_STRING_NAME»(final «type.fullyQualifiedNonNull» obj) {
319             final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper("«type.name»");
320             «FOR property : typeAnalysis.value»
321                 «CODEHELPERS.importedName».appendValue(helper, "«property.name»", obj.«property.getterName»());
322             «ENDFOR»
323             «IF augmentable»
324                 «CODEHELPERS.importedName».appendValue(helper, "«AUGMENTATION_FIELD»", obj.augmentations().values());
325             «ENDIF»
326             return helper.toString();
327         }
328     '''
329
330     def private generateNonnullMethod(MethodSignature method) '''
331         «val ret = method.returnType»
332         «val name = method.name»
333         «accessorJavadoc(method, "an empty list")»
334         «method.annotations.generateAnnotations»
335         default «ret.importedNonNull» «name»() {
336             return «CODEHELPERS.importedName».nonnull(«name.getGetterMethodForNonnull»());
337         }
338     '''
339
340     def private String nullableType(Type type) {
341         if (type.isObject && (Types.isMapType(type) || Types.isListType(type))) {
342             return type.importedNullable
343         }
344         return type.importedName
345     }
346
347     def private static boolean isObject(Type type) {
348         // The return type has a package, so it's not a primitive type
349         return !type.getPackageName().isEmpty()
350     }
351
352     private def boolean analyzeType() {
353         if (typeAnalysis === null) {
354             typeAnalysis = analyzeTypeHierarchy(type)
355         }
356         typeAnalysis.key !== null
357     }
358 }