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