89c1ed186120b077ec41bbbd47ded2781122c125
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / BuilderTemplate.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.apache.commons.text.StringEscapeUtils.escapeJava
11 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTABLE_AUGMENTATION_NAME
12 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTATION_FIELD
13
14 import com.google.common.collect.ImmutableList
15 import java.util.ArrayList
16 import java.util.Collection
17 import java.util.HashMap
18 import java.util.HashSet
19 import java.util.List
20 import java.util.Map
21 import java.util.Set
22 import org.opendaylight.mdsal.binding.model.api.AnnotationType
23 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
24 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
25 import org.opendaylight.mdsal.binding.model.api.GeneratedType
26 import org.opendaylight.mdsal.binding.model.api.JavaTypeName
27 import org.opendaylight.mdsal.binding.model.api.ParameterizedType
28 import org.opendaylight.mdsal.binding.model.api.Type
29 import org.opendaylight.mdsal.binding.model.util.TypeConstants
30 import org.opendaylight.mdsal.binding.model.util.Types
31 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping
32 import org.opendaylight.yangtools.concepts.Builder
33 import org.opendaylight.yangtools.yang.binding.AugmentationHolder
34 import org.opendaylight.yangtools.yang.binding.DataObject
35
36 /**
37  * Template for generating JAVA builder classes.
38  */
39 class BuilderTemplate extends AbstractBuilderTemplate {
40     /**
41      * Constant used as suffix for builder name.
42      */
43     public static val BUILDER = "Builder";
44
45     static val AUGMENTATION_FIELD_UPPER = AUGMENTATION_FIELD.toFirstUpper
46
47     /**
48      * Constructs new instance of this class.
49      * @throws IllegalArgumentException if <code>genType</code> equals <code>null</code>
50      */
51     new(GeneratedType genType, GeneratedType targetType, Set<GeneratedProperty> properties, Type augmentType,
52             Type keyType) {
53         super(genType, targetType, properties, augmentType, keyType)
54     }
55
56     override isLocalInnerClass(JavaTypeName name) {
57         // Builders do not have inner types
58         return false;
59     }
60
61     /**
62      * Template method which generates JAVA class body for builder class and for IMPL class.
63      *
64      * @return string with JAVA source code
65      */
66     override body() '''
67         «wrapToDocumentation(formatDataForJavaDoc(targetType))»
68         «targetType.annotations.generateDeprecatedAnnotation»
69         public class «type.name» implements «Builder.importedName»<«targetType.importedName»> {
70
71             «generateFields(false)»
72
73             «constantsDeclarations()»
74
75             «IF augmentType !== null»
76                 «generateAugmentField()»
77             «ENDIF»
78
79             «generateConstructorsFromIfcs()»
80
81             public «generateCopyConstructor(targetType, type.enclosedTypes.get(0))»
82
83             «generateMethodFieldsFrom()»
84
85             «generateGetters(false)»
86             «IF augmentType !== null»
87
88                 «generateAugmentation()»
89             «ENDIF»
90
91             «generateSetters»
92
93             @«OVERRIDE.importedName»
94             public «targetType.name» build() {
95                 return new «type.enclosedTypes.get(0).importedName»(this);
96             }
97
98             «new BuilderImplTemplate(this, type.enclosedTypes.get(0)).body»
99         }
100     '''
101
102     override generateDeprecatedAnnotation(AnnotationType ann) {
103         val forRemoval = ann.getParameter("forRemoval")
104         if (forRemoval !== null) {
105             return "@" + DEPRECATED.importedName + "(forRemoval = " + forRemoval.value + ")"
106         }
107         return "@" + SUPPRESS_WARNINGS.importedName + "(\"deprecation\")"
108     }
109
110     /**
111      * Generate default constructor and constructor for every implemented interface from uses statements.
112      */
113     def private generateConstructorsFromIfcs() '''
114         public «type.name»() {
115         }
116         «IF (!(targetType instanceof GeneratedTransferObject))»
117             «FOR impl : targetType.implements»
118                 «generateConstructorFromIfc(impl)»
119             «ENDFOR»
120         «ENDIF»
121     '''
122
123     /**
124      * Generate constructor with argument of given type.
125      */
126     def private Object generateConstructorFromIfc(Type impl) '''
127         «IF (impl instanceof GeneratedType)»
128             «IF impl.hasNonDefaultMethods»
129                 public «type.name»(«impl.fullyQualifiedName» arg) {
130                     «printConstructorPropertySetter(impl)»
131                 }
132             «ENDIF»
133             «FOR implTypeImplement : impl.implements»
134                 «generateConstructorFromIfc(implTypeImplement)»
135             «ENDFOR»
136         «ENDIF»
137     '''
138
139     def private Object printConstructorPropertySetter(Type implementedIfc) '''
140         «IF (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))»
141             «val ifc = implementedIfc as GeneratedType»
142             «FOR getter : ifc.nonDefaultMethods»
143                 «IF BindingMapping.isGetterMethodName(getter.name)»
144                     this._«getter.propertyNameFromGetter» = arg.«getter.name»();
145                 «ENDIF»
146             «ENDFOR»
147             «FOR impl : ifc.implements»
148                 «printConstructorPropertySetter(impl)»
149             «ENDFOR»
150         «ENDIF»
151     '''
152
153     /**
154      * Generate 'fieldsFrom' method to set builder properties based on type of given argument.
155      */
156     def private generateMethodFieldsFrom() '''
157         «IF (!(targetType instanceof GeneratedTransferObject))»
158             «IF targetType.hasImplementsFromUses»
159                 «val List<Type> done = targetType.getBaseIfcs»
160                 «generateMethodFieldsFromComment(targetType)»
161                 public void fieldsFrom(«DataObject.importedName» arg) {
162                     boolean isValidArg = false;
163                     «FOR impl : targetType.getAllIfcs»
164                         «generateIfCheck(impl, done)»
165                     «ENDFOR»
166                     «CODEHELPERS.importedName».validValue(isValidArg, arg, "«targetType.getAllIfcs.toListOfNames»");
167                 }
168             «ENDIF»
169         «ENDIF»
170     '''
171
172     def private generateMethodFieldsFromComment(GeneratedType type) '''
173         /**
174          * Set fields from given grouping argument. Valid argument is instance of one of following types:
175          * <ul>
176          «FOR impl : type.getAllIfcs»
177          * <li>«impl.fullyQualifiedName»</li>
178          «ENDFOR»
179          * </ul>
180          *
181          * @param arg grouping object
182          * @throws IllegalArgumentException if given argument is none of valid types
183         */
184     '''
185
186     /**
187      * Method is used to find out if given type implements any interface from uses.
188      */
189     def boolean hasImplementsFromUses(GeneratedType type) {
190         var i = 0
191         for (impl : type.getAllIfcs) {
192             if (impl instanceof GeneratedType && (impl as GeneratedType).hasNonDefaultMethods) {
193                 i = i + 1
194             }
195         }
196         return i > 0
197     }
198
199     def private generateIfCheck(Type impl, List<Type> done) '''
200         «IF (impl instanceof GeneratedType && (impl as GeneratedType).hasNonDefaultMethods)»
201             «val implType = impl as GeneratedType»
202             if (arg instanceof «implType.fullyQualifiedName») {
203                 «printPropertySetter(implType)»
204                 isValidArg = true;
205             }
206         «ENDIF»
207     '''
208
209     def private printPropertySetter(Type implementedIfc) '''
210         «IF (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))»
211         «val ifc = implementedIfc as GeneratedType»
212         «FOR getter : ifc.nonDefaultMethods»
213             «IF BindingMapping.isGetterMethodName(getter.name)»
214                 this._«getter.propertyNameFromGetter» = ((«implementedIfc.fullyQualifiedName»)arg).«getter.name»();
215             «ENDIF»
216         «ENDFOR»
217         «ENDIF»
218     '''
219
220     private def List<Type> getBaseIfcs(GeneratedType type) {
221         val List<Type> baseIfcs = new ArrayList();
222         for (ifc : type.implements) {
223             if (ifc instanceof GeneratedType && (ifc as GeneratedType).hasNonDefaultMethods) {
224                 baseIfcs.add(ifc)
225             }
226         }
227         return baseIfcs
228     }
229
230     private def Set<Type> getAllIfcs(Type type) {
231         val Set<Type> baseIfcs = new HashSet()
232         if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
233             val ifc = type as GeneratedType
234             for (impl : ifc.implements) {
235                 if (impl instanceof GeneratedType && (impl as GeneratedType).hasNonDefaultMethods) {
236                     baseIfcs.add(impl)
237                 }
238                 baseIfcs.addAll(impl.getAllIfcs)
239             }
240         }
241         return baseIfcs
242     }
243
244     private def List<String> toListOfNames(Collection<Type> types) {
245         val List<String> names = new ArrayList
246         for (type : types) {
247             names.add(type.fullyQualifiedName)
248         }
249         return names
250     }
251
252     def private constantsDeclarations() '''
253         «FOR c : type.getConstantDefinitions»
254             «IF c.getName.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)»
255                 «val cValue = c.value as Map<String, String>»
256                 «val String fieldSuffix = c.getName.substring(TypeConstants.PATTERN_CONSTANT_NAME.length)»
257                 «val jurPatternRef = JUR_PATTERN.importedName»
258                 «IF cValue.size == 1»
259                    «val firstEntry = cValue.entrySet.iterator.next»
260                    private static final «jurPatternRef» «Constants.MEMBER_PATTERN_LIST»«fieldSuffix» = «jurPatternRef».compile("«firstEntry.key.escapeJava»");
261                    private static final String «Constants.MEMBER_REGEX_LIST»«fieldSuffix» = "«firstEntry.value.escapeJava»";
262                 «ELSE»
263                    private static final «jurPatternRef»[] «Constants.MEMBER_PATTERN_LIST»«fieldSuffix» = «CODEHELPERS.importedName».compilePatterns(«ImmutableList.importedName».of(
264                    «FOR v : cValue.keySet SEPARATOR ", "»"«v.escapeJava»"«ENDFOR»));
265                    private static final String[] «Constants.MEMBER_REGEX_LIST»«fieldSuffix» = { «
266                    FOR v : cValue.values SEPARATOR ", "»"«v.escapeJava»"«ENDFOR» };
267                 «ENDIF»
268             «ELSE»
269                 «emitConstant(c)»
270             «ENDIF»
271         «ENDFOR»
272     '''
273
274     def private generateListSetter(GeneratedProperty field, Type actualType) '''
275         «val restrictions = restrictionsForSetter(actualType)»
276         «IF restrictions !== null»
277             «generateCheckers(field, restrictions, actualType)»
278         «ENDIF»
279         public «type.getName» set«field.getName.toFirstUpper»(final «field.returnType.importedName» values) {
280         «IF restrictions !== null»
281             if (values != null) {
282                for («actualType.getFullyQualifiedName» value : values) {
283                    «checkArgument(field, restrictions, actualType, "value")»
284                }
285             }
286         «ENDIF»
287             this.«field.fieldName» = values;
288             return this;
289         }
290
291     '''
292
293     def private generateSetter(GeneratedProperty field, Type actualType) '''
294         «val restrictions = restrictionsForSetter(actualType)»
295         «IF restrictions !== null»
296
297             «generateCheckers(field, restrictions, actualType)»
298         «ENDIF»
299
300         «val setterName = "set" + field.getName.toFirstUpper»
301         public «type.getName» «setterName»(final «field.returnType.importedName» value) {
302             «IF restrictions !== null»
303                 if (value != null) {
304                     «checkArgument(field, restrictions, actualType, "value")»
305                 }
306             «ENDIF»
307             this.«field.fieldName» = value;
308             return this;
309         }
310         «val uintType = UINT_TYPES.get(field.returnType)»
311         «IF uintType !== null»
312
313             /**
314              * Utility migration setter.
315              *
316              * @param value field value in legacy type
317              * @return this builder
318              * @deprecated Use {#link «setterName»(«field.returnType.importedJavadocName»)} instead.
319              */
320             @Deprecated(forRemoval = true)
321             public «type.getName» «setterName»(final «uintType.importedName» value) {
322                 return «setterName»(«CODEHELPERS.importedName».compatUint(value));
323             }
324         «ENDIF»
325     '''
326
327     private def Type getActualType(ParameterizedType ptype) {
328         return ptype.getActualTypeArguments.get(0)
329     }
330
331     /**
332      * Template method which generates setter methods
333      *
334      * @return string with the setter methods
335      */
336     def private generateSetters() '''
337         «IF keyType !== null»
338             public «type.getName» withKey(final «keyType.importedName» key) {
339                 this.key = key;
340                 return this;
341             }
342         «ENDIF»
343         «FOR property : properties»
344             «IF property.returnType instanceof ParameterizedType && Types.isListType(property.returnType)»
345                 «generateListSetter(property, getActualType(property.returnType as ParameterizedType))»
346             «ELSE»
347                 «generateSetter(property, property.returnType)»
348             «ENDIF»
349         «ENDFOR»
350
351         «IF augmentType !== null»
352             «val augmentTypeRef = augmentType.importedName»
353             «val jlClassRef = CLASS.importedName»
354             public «type.name» add«AUGMENTATION_FIELD_UPPER»(«jlClassRef»<? extends «augmentTypeRef»> augmentationType, «augmentTypeRef» augmentationValue) {
355                 if (augmentationValue == null) {
356                     return remove«AUGMENTATION_FIELD_UPPER»(augmentationType);
357                 }
358
359                 if (!(this.«AUGMENTATION_FIELD» instanceof «HashMap.importedName»)) {
360                     this.«AUGMENTATION_FIELD» = new «HashMap.importedName»<>();
361                 }
362
363                 this.«AUGMENTATION_FIELD».put(augmentationType, augmentationValue);
364                 return this;
365             }
366
367             public «type.name» remove«AUGMENTATION_FIELD_UPPER»(«jlClassRef»<? extends «augmentTypeRef»> augmentationType) {
368                 if (this.«AUGMENTATION_FIELD» instanceof «HashMap.importedName») {
369                     this.«AUGMENTATION_FIELD».remove(augmentationType);
370                 }
371                 return this;
372             }
373         «ENDIF»
374     '''
375
376     private def createDescription(GeneratedType targetType) {
377         val target = type.importedName
378         return '''
379         Class that builds {@link «target»} instances. Overall design of the class is that of a
380         <a href="https://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a>, where method chaining is used.
381
382         <p>
383         In general, this class is supposed to be used like this template:
384         <pre>
385           <code>
386             «target» createTarget(int fooXyzzy, int barBaz) {
387                 return new «target»Builder()
388                     .setFoo(new FooBuilder().setXyzzy(fooXyzzy).build())
389                     .setBar(new BarBuilder().setBaz(barBaz).build())
390                     .build();
391             }
392           </code>
393         </pre>
394
395         <p>
396         This pattern is supported by the immutable nature of «target», as instances can be freely passed around without
397         worrying about synchronization issues.
398
399         <p>
400         As a side note: method chaining results in:
401         <ul>
402           <li>very efficient Java bytecode, as the method invocation result, in this case the Builder reference, is
403               on the stack, so further method invocations just need to fill method arguments for the next method
404               invocation, which is terminated by {@link #build()}, which is then returned from the method</li>
405           <li>better understanding by humans, as the scope of mutable state (the builder) is kept to a minimum and is
406               very localized</li>
407           <li>better optimization oportunities, as the object scope is minimized in terms of invocation (rather than
408               method) stack, making <a href="https://en.wikipedia.org/wiki/Escape_analysis">escape analysis</a> a lot
409               easier. Given enough compiler (JIT/AOT) prowess, the cost of th builder object can be completely
410               eliminated</li>
411         </ul>
412
413         @see «target»
414         @see «Builder.importedName»
415     '''
416     }
417
418     override protected String formatDataForJavaDoc(GeneratedType type) {
419         val typeDescription = createDescription(type)
420
421         return '''
422             «IF !typeDescription.nullOrEmpty»
423             «typeDescription»
424             «ENDIF»
425         '''.toString
426     }
427
428     private def generateAugmentation() '''
429         @«SUPPRESS_WARNINGS.importedName»({ "unchecked", "checkstyle:methodTypeParameterName"})
430         public <E$$ extends «augmentType.importedName»> E$$ «AUGMENTABLE_AUGMENTATION_NAME»(«CLASS.importedName»<E$$> augmentationType) {
431             return (E$$) «AUGMENTATION_FIELD».get(«CODEHELPERS.importedName».nonNullValue(augmentationType, "augmentationType"));
432         }
433     '''
434
435     override protected generateCopyKeys(List<GeneratedProperty> keyProps) '''
436         this.key = base.«BindingMapping.IDENTIFIABLE_KEY_NAME»();
437         «FOR field : keyProps»
438             this.«field.fieldName» = base.«field.getterMethodName»();
439         «ENDFOR»
440     '''
441
442     override protected generateCopyAugmentation(Type implType) {
443         val augmentationHolderRef = AugmentationHolder.importedName
444         val typeRef = targetType.importedName
445         val hashMapRef = HashMap.importedName
446         val augmentTypeRef = augmentType.importedName
447         return '''
448             if (base instanceof «augmentationHolderRef») {
449                 @SuppressWarnings("unchecked")
450                 «JU_MAP.importedName»<«CLASS.importedName»<? extends «augmentTypeRef»>, «augmentTypeRef»> aug =((«augmentationHolderRef»<«typeRef»>) base).augmentations();
451                 if (!aug.isEmpty()) {
452                     this.«AUGMENTATION_FIELD» = new «hashMapRef»<>(aug);
453                 }
454             }
455         '''
456     }
457
458     private static def hasNonDefaultMethods(GeneratedType type) {
459         !type.methodDefinitions.isEmpty && type.methodDefinitions.exists([def | !def.isDefault])
460     }
461
462     private static def nonDefaultMethods(GeneratedType type) {
463         type.methodDefinitions.filter([def | !def.isDefault])
464     }
465 }