7780cbd510f5a290d4dba1ef9863bd0061ba111e
[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         «wrapToDocumentation(formatDataForJavaDoc(type))»
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             }
193         }
194     }
195
196     def private generateStaticMethod(MethodSignature method) {
197         switch method.name {
198             case BINDING_EQUALS_NAME : generateBindingEquals
199             case BINDING_HASHCODE_NAME : generateBindingHashCode
200             case BINDING_TO_STRING_NAME : generateBindingToString
201         }
202     }
203
204     def private generateMethod(MethodSignature method) '''
205         «method.comment.asJavadoc»
206         «method.annotations.generateAnnotations»
207         «method.returnType.importedName» «method.name»(«method.parameters.generateParameters»);
208     '''
209
210     def private generateAccessorMethod(MethodSignature method) '''
211         «val ret = method.returnType»
212         «formatDataForJavaDoc(method, "@return " + asCode(ret.fullyQualifiedName) + " " + asCode(propertyNameFromGetter(method)) + ", or " + asCode("null") + " if not present")»
213         «method.annotations.generateAnnotations»
214         «nullableType(ret)» «method.name»();
215     '''
216
217     def private generateDefaultImplementedInterface() '''
218         @«OVERRIDE.importedName»
219         default «CLASS.importedName»<«type.fullyQualifiedName»> «DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME»() {
220             return «type.fullyQualifiedName».class;
221         }
222     '''
223
224     @VisibleForTesting
225     def generateBindingHashCode() '''
226         «val augmentable = analyzeType»
227         «IF augmentable || !typeAnalysis.value.empty»
228             /**
229              * Default implementation of {@link «Object.importedName»#hashCode()} contract for this interface.
230              * Implementations of this interface are encouraged to defer to this method to get consistent hashing
231              * results across all implementations.
232              *
233              * @param obj Object for which to generate hashCode() result.
234              * @return Hash code value of data modeled by this interface.
235              * @throws «NPE.importedName» if {@code obj} is null
236              */
237             static int «BINDING_HASHCODE_NAME»(final «type.fullyQualifiedNonNull» obj) {
238                 final int prime = 31;
239                 int result = 1;
240                 «FOR property : typeAnalysis.value»
241                     result = prime * result + «property.importedUtilClass».hashCode(obj.«property.getterMethodName»());
242                 «ENDFOR»
243                 «IF augmentable»
244                     result = prime * result + obj.augmentations().hashCode();
245                 «ENDIF»
246                 return result;
247             }
248         «ENDIF»
249     '''
250
251     def private generateBindingEquals() '''
252         «val augmentable = analyzeType»
253         «IF augmentable || !typeAnalysis.value.isEmpty»
254             /**
255              * Default implementation of {@link «Object.importedName»#equals(«Object.importedName»)} contract for this interface.
256              * Implementations of this interface are encouraged to defer to this method to get consistent equality
257              * results across all implementations.
258              *
259              * @param thisObj Object acting as the receiver of equals invocation
260              * @param obj Object acting as argument to equals invocation
261              * @return True if thisObj and obj are considered equal
262              * @throws «NPE.importedName» if {@code thisObj} is null
263              */
264             static boolean «BINDING_EQUALS_NAME»(final «type.fullyQualifiedNonNull» thisObj, final «Types.objectType().importedName» obj) {
265                 if (thisObj == obj) {
266                     return true;
267                 }
268                 final «type.fullyQualifiedName» other = «CODEHELPERS.importedName».checkCast(«type.fullyQualifiedName».class, obj);
269                 if (other == null) {
270                     return false;
271                 }
272                 «FOR property : ByTypeMemberComparator.sort(typeAnalysis.value)»
273                     if (!«property.importedUtilClass».equals(thisObj.«property.getterName»(), other.«property.getterName»())) {
274                         return false;
275                     }
276                 «ENDFOR»
277                 return «IF augmentable»thisObj.augmentations().equals(other.augmentations())«ELSE»true«ENDIF»;
278             }
279         «ENDIF»
280     '''
281
282     def generateBindingToString() '''
283         «val augmentable = analyzeType»
284         /**
285          * Default implementation of {@link «Object.importedName»#toString()} contract for this interface.
286          * Implementations of this interface are encouraged to defer to this method to get consistent string
287          * representations across all implementations.
288          *
289          * @param obj Object for which to generate toString() result.
290          * @return {@link «STRING.importedName»} value of data modeled by this interface.
291          * @throws «NPE.importedName» if {@code obj} is null
292          */
293         static «STRING.importedName» «BINDING_TO_STRING_NAME»(final «type.fullyQualifiedNonNull» obj) {
294             final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper("«type.name»");
295             «FOR property : typeAnalysis.value»
296                 «CODEHELPERS.importedName».appendValue(helper, "«property.name»", obj.«property.getterName»());
297             «ENDFOR»
298             «IF augmentable»
299                 «CODEHELPERS.importedName».appendValue(helper, "«AUGMENTATION_FIELD»", obj.augmentations().values());
300             «ENDIF»
301             return helper.toString();
302         }
303     '''
304
305     def private generateNonnullMethod(MethodSignature method) '''
306         «val ret = method.returnType»
307         «val name = method.name»
308         «formatDataForJavaDoc(method, "@return " + asCode(ret.fullyQualifiedName) + " " + asCode(propertyNameFromGetter(method)) + ", or an empty list if it is not present")»
309         «method.annotations.generateAnnotations»
310         default «ret.importedNonNull» «name»() {
311             return «CODEHELPERS.importedName».nonnull(«name.getGetterMethodForNonnull»());
312         }
313     '''
314
315     def private String nullableType(Type type) {
316         if (type.isObject) {
317             return type.importedNullable
318         }
319         return type.importedName
320     }
321
322     def private static boolean isObject(Type type) {
323         // The return type has a package, so it's not a primitive type
324         return !type.getPackageName().isEmpty()
325     }
326
327     private def boolean analyzeType() {
328         if (typeAnalysis === null) {
329             typeAnalysis = analyzeTypeHierarchy(type)
330         }
331         typeAnalysis.key !== null
332     }
333 }