Generate bindingToString() and use it in generated implementations
[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 org.opendaylight.mdsal.binding.model.util.Types.STRING;
11 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.getGetterMethodForNonnull
12 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.isGetterMethodName
13 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.isNonnullMethodName
14 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTATION_FIELD
15 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.BINDING_TO_STRING_NAME
16 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME
17
18 import com.google.common.base.MoreObjects
19 import java.util.List
20 import java.util.Map.Entry
21 import java.util.Set
22 import org.gaul.modernizer_maven_annotations.SuppressModernizer
23 import org.opendaylight.mdsal.binding.model.api.AnnotationType
24 import org.opendaylight.mdsal.binding.model.api.Constant
25 import org.opendaylight.mdsal.binding.model.api.Enumeration
26 import org.opendaylight.mdsal.binding.model.api.GeneratedType
27 import org.opendaylight.mdsal.binding.model.api.MethodSignature
28 import org.opendaylight.mdsal.binding.model.api.Type
29 import org.opendaylight.mdsal.binding.model.util.TypeConstants
30
31 /**
32  * Template for generating JAVA interfaces.
33  */
34  @SuppressModernizer
35 class InterfaceTemplate extends BaseTemplate {
36     /**
37      * List of constant instances which are generated as JAVA public static final attributes.
38      */
39     val List<Constant> consts
40
41     /**
42      * List of method signatures which are generated as method declarations.
43      */
44     val List<MethodSignature> methods
45
46     /**
47      * List of enumeration which are generated as JAVA enum type.
48      */
49     val List<Enumeration> enums
50
51     /**
52      * List of generated types which are enclosed inside <code>genType</code>
53      */
54     val List<GeneratedType> enclosedGeneratedTypes
55
56     var Entry<Type, Set<BuilderGeneratedProperty>> typeAnalysis
57
58     /**
59      * Creates the instance of this class which is used for generating the interface file source
60      * code from <code>genType</code>.
61      *
62      * @throws NullPointerException if <code>genType</code> is <code>null</code>
63      */
64     new(GeneratedType genType) {
65         super(genType)
66         consts = genType.constantDefinitions
67         methods = genType.methodDefinitions
68         enums = genType.enumerations
69         enclosedGeneratedTypes = genType.enclosedTypes
70     }
71
72     /**
73      * Template method which generate the whole body of the interface.
74      *
75      * @return string with code for interface body in JAVA format
76      */
77     override body() '''
78         «wrapToDocumentation(formatDataForJavaDoc(type))»
79         «type.annotations.generateAnnotations»
80         public interface «type.name»
81             «superInterfaces»
82         {
83
84             «generateInnerClasses»
85
86             «generateEnums»
87
88             «generateConstants»
89
90             «generateMethods»
91
92         }
93
94     '''
95
96     def private generateAnnotations(List<AnnotationType> annotations) '''
97         «IF annotations !== null && !annotations.empty»
98             «FOR annotation : annotations»
99                 «annotation.generateAnnotation»
100             «ENDFOR»
101         «ENDIF»
102     '''
103
104     /**
105      * Template method which generates the interface name declaration.
106      *
107      * @return string with the code for the interface declaration in JAVA format
108      */
109     def private superInterfaces()
110     '''
111     «IF (!type.implements.empty)»
112          extends
113          «FOR type : type.implements SEPARATOR ","»
114              «type.importedName»
115          «ENDFOR»
116      « ENDIF»
117      '''
118
119     /**
120      * Template method which generates inner classes inside this interface.
121      *
122      * @return string with the source code for inner classes in JAVA format
123      */
124     def private generateInnerClasses() '''
125         «IF !enclosedGeneratedTypes.empty»
126             «FOR innerClass : enclosedGeneratedTypes SEPARATOR "\n"»
127                 «generateInnerClass(innerClass)»
128             «ENDFOR»
129         «ENDIF»
130     '''
131
132     /**
133      * Template method which generates JAVA enum type.
134      *
135      * @return string with inner enum source code in JAVA format
136      */
137     def private generateEnums() '''
138         «IF !enums.empty»
139             «FOR e : enums SEPARATOR "\n"»
140                 «val enumTemplate = new EnumTemplate(javaType.getEnclosedType(e.identifier), e)»
141                 «enumTemplate.generateAsInnerClass»
142             «ENDFOR»
143         «ENDIF»
144     '''
145
146     /**
147      * Template method wich generates JAVA constants.
148      *
149      * @return string with constants in JAVA format
150      */
151     def private generateConstants() '''
152         «IF !consts.empty»
153             «FOR c : consts»
154                 «IF !c.name.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)»
155                     «emitConstant(c)»
156                 «ENDIF»
157             «ENDFOR»
158         «ENDIF»
159     '''
160
161     /**
162      * Template method which generates the declaration of the methods.
163      *
164      * @return string with the declaration of methods source code in JAVA format
165      */
166     def private generateMethods() '''
167         «IF !methods.empty»
168             «FOR m : methods SEPARATOR "\n"»
169                 «IF m.isDefault»
170                     «generateDefaultMethod(m)»
171                 «ELSEIF m.isStatic»
172                     «generateStaticMethod(m)»
173                 «ELSEIF m.parameters.empty && m.name.isGetterMethodName»
174                     «generateAccessorMethod(m)»
175                 «ELSE»
176                     «generateMethod(m)»
177                 «ENDIF»
178             «ENDFOR»
179         «ENDIF»
180     '''
181
182     def private generateDefaultMethod(MethodSignature method) {
183         if (method.name.isNonnullMethodName) {
184             generateNonnullMethod(method)
185         } else {
186             switch method.name {
187                 case DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME : generateDefaultImplementedInterface
188             }
189         }
190     }
191
192     def private generateStaticMethod(MethodSignature method) {
193         switch method.name {
194             case BINDING_TO_STRING_NAME : generateBindingToString
195         }
196     }
197
198     def private generateMethod(MethodSignature method) '''
199         «method.comment.asJavadoc»
200         «method.annotations.generateAnnotations»
201         «method.returnType.importedName» «method.name»(«method.parameters.generateParameters»);
202     '''
203
204     def private generateAccessorMethod(MethodSignature method) '''
205         «val ret = method.returnType»
206         «formatDataForJavaDoc(method, "@return " + asCode(ret.fullyQualifiedName) + " " + asCode(propertyNameFromGetter(method)) + ", or " + asCode("null") + " if not present")»
207         «method.annotations.generateAnnotations»
208         «nullableType(ret)» «method.name»();
209     '''
210
211     def private generateDefaultImplementedInterface() '''
212         @«OVERRIDE.importedName»
213         default «CLASS.importedName»<«type.fullyQualifiedName»> «DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME»() {
214             return «type.fullyQualifiedName».class;
215         }
216     '''
217
218     def generateBindingToString() '''
219         «val augmentable = analyzeType»
220         /**
221          * Default implementation of {@link «Object.importedName»#toString()} contract for this interface.
222          * Implementations of this interface are encouraged to defer to this method to get consistent string
223          * representations across all implementation.
224          *
225          «IF augmentable»
226          * <p>
227          * @param <T$$> implementation type, which has to also implement «AUGMENTATION_HOLDER.importedName» interface
228          *              contract.
229          «ENDIF»
230          * @param obj Object for which to generate toString() result.
231          * @return {@link «STRING.importedName»} value of data modeled by this interface.
232          * @throws «NPE.importedName» if {@code obj} is null
233          */
234         «IF augmentable»
235             static <T$$ extends «type.fullyQualifiedName» & «AUGMENTATION_HOLDER.importedName»<«type.fullyQualifiedName»>> «STRING.importedName» «BINDING_TO_STRING_NAME»(final @«NONNULL.importedName» T$$ obj) {
236         «ELSE»
237             static «STRING.importedName» «BINDING_TO_STRING_NAME»(final «type.fullyQualifiedName» obj) {
238         «ENDIF»
239             final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper("«type.name»");
240             «FOR property : typeAnalysis.value»
241                 «CODEHELPERS.importedName».appendValue(helper, "«property.name»", obj.«property.getterName»());
242             «ENDFOR»
243             «IF augmentable»
244                 «CODEHELPERS.importedName».appendValue(helper, "«AUGMENTATION_FIELD»", obj.augmentations().values());
245             «ENDIF»
246             return helper.toString();
247         }
248     '''
249
250     def private generateNonnullMethod(MethodSignature method) '''
251         «val ret = method.returnType»
252         «val name = method.name»
253         «formatDataForJavaDoc(method, "@return " + asCode(ret.fullyQualifiedName) + " " + asCode(propertyNameFromGetter(method)) + ", or an empty list if it is not present")»
254         «method.annotations.generateAnnotations»
255         default «ret.importedNonNull» «name»() {
256             return «CODEHELPERS.importedName».nonnull(«getGetterMethodForNonnull(name)»());
257         }
258     '''
259
260     def private String nullableType(Type type) {
261         if (type.isObject) {
262             return type.importedNullable
263         }
264         return type.importedName
265     }
266
267     def private static boolean isObject(Type type) {
268         // The return type has a package, so it's not a primitive type
269         return !type.getPackageName().isEmpty()
270     }
271
272     private def boolean analyzeType() {
273         if (typeAnalysis === null) {
274             typeAnalysis = analyzeTypeHierarchy(type)
275         }
276         typeAnalysis.key !== null
277     }
278 }