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