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