2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.java.api.generator
10 import static extension org.apache.commons.text.StringEscapeUtils.escapeJava
11 import static org.opendaylight.mdsal.binding.model.ri.BindingTypes.DATA_OBJECT
12 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTABLE_AUGMENTATION_NAME
13 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTATION_FIELD
14 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME
16 import com.google.common.collect.ImmutableList
17 import com.google.common.collect.ImmutableSet
18 import com.google.common.collect.Sets
19 import java.util.ArrayList
20 import java.util.Collection
21 import java.util.HashSet
25 import org.opendaylight.mdsal.binding.model.api.AnnotationType
26 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
27 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
28 import org.opendaylight.mdsal.binding.model.api.GeneratedType
29 import org.opendaylight.mdsal.binding.model.api.JavaTypeName
30 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
31 import org.opendaylight.mdsal.binding.model.api.ParameterizedType
32 import org.opendaylight.mdsal.binding.model.api.Type
33 import org.opendaylight.mdsal.binding.model.ri.TypeConstants
34 import org.opendaylight.mdsal.binding.model.ri.Types
35 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping
38 * Template for generating JAVA builder classes.
40 class BuilderTemplate extends AbstractBuilderTemplate {
41 val BuilderImplTemplate implTemplate
44 * Constructs new instance of this class.
45 * @throws IllegalArgumentException if <code>genType</code> equals <code>null</code>
47 new(GeneratedType genType, GeneratedType targetType, Type keyType) {
48 super(genType, targetType, keyType)
49 implTemplate = new BuilderImplTemplate(this, type.enclosedTypes.get(0))
52 override isLocalInnerClass(JavaTypeName name) {
53 // Builders do not have inner types
58 * Template method which generates JAVA class body for builder class and for IMPL class.
60 * @return string with JAVA source code
63 «wrapToDocumentation(formatDataForJavaDoc(targetType))»
64 «targetType.annotations.generateDeprecatedAnnotation»
66 public class «type.name» {
68 «generateFields(false)»
70 «constantsDeclarations()»
72 «IF augmentType !== null»
73 «generateAugmentField()»
77 * Construct an empty builder.
79 public «type.name»() {
83 «generateConstructorsFromIfcs()»
85 «val targetTypeName = targetType.importedName»
87 * Construct a builder initialized with state from specified {@link «targetTypeName»}.
89 * @param base «targetTypeName» from which the builder should be initialized
91 public «generateCopyConstructor(targetType, type.enclosedTypes.get(0))»
93 «generateMethodFieldsFrom()»
95 «generateGetters(false)»
96 «IF augmentType !== null»
98 «generateAugmentation()»
104 * A new {@link «targetTypeName»} instance.
106 * @return A new {@link «targetTypeName»} instance.
108 public «targetTypeName» build() {
109 return new «type.enclosedTypes.get(0).importedName»(this);
116 override generateDeprecatedAnnotation(AnnotationType ann) {
117 val forRemoval = ann.getParameter("forRemoval")
118 if (forRemoval !== null) {
119 return "@" + DEPRECATED.importedName + "(forRemoval = " + forRemoval.value + ")"
121 return "@" + SUPPRESS_WARNINGS.importedName + "(\"deprecation\")"
125 * Generate default constructor and constructor for every implemented interface from uses statements.
127 def private generateConstructorsFromIfcs() '''
128 «IF (!(targetType instanceof GeneratedTransferObject))»
129 «FOR impl : targetType.implements SEPARATOR "\n"»
130 «generateConstructorFromIfc(impl)»
136 * Generate constructor with argument of given type.
138 def private Object generateConstructorFromIfc(Type impl) '''
139 «IF (impl instanceof GeneratedType)»
140 «IF impl.hasNonDefaultMethods»
141 «val typeName = impl.importedName»
143 * Construct a new builder initialized from specified {@link «typeName»}.
145 * @param arg «typeName» from which the builder should be initialized
147 public «type.name»(«typeName» arg) {
148 «printConstructorPropertySetter(impl)»
152 «FOR implTypeImplement : impl.implements»
153 «generateConstructorFromIfc(implTypeImplement)»
158 def private Object printConstructorPropertySetter(Type implementedIfc) '''
159 «IF (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))»
160 «val ifc = implementedIfc as GeneratedType»
161 «FOR getter : ifc.nonDefaultMethods»
162 «IF BindingMapping.isGetterMethodName(getter.name)»
163 «val propertyName = getter.propertyNameFromGetter»
164 «printPropertySetter(getter, '''arg.«getter.name»()''', propertyName)»;
167 «FOR impl : ifc.implements»
168 «printConstructorPropertySetter(impl, getSpecifiedGetters(ifc))»
173 def private Object printConstructorPropertySetter(Type implementedIfc, Set<MethodSignature> alreadySetProperties) '''
174 «IF (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))»
175 «val ifc = implementedIfc as GeneratedType»
176 «FOR getter : ifc.nonDefaultMethods»
177 «IF BindingMapping.isGetterMethodName(getter.name) && getterByName(alreadySetProperties, getter.name).isEmpty»
178 «val propertyName = getter.propertyNameFromGetter»
179 «printPropertySetter(getter, '''arg.«getter.name»()''', propertyName)»;
182 «FOR descendant : ifc.implements»
183 «printConstructorPropertySetter(descendant, Sets.union(alreadySetProperties, getSpecifiedGetters(ifc)))»
188 def static Set<MethodSignature> getSpecifiedGetters(GeneratedType type) {
189 val ImmutableSet.Builder<MethodSignature> setBuilder = new ImmutableSet.Builder
190 for (MethodSignature method : type.getMethodDefinitions()) {
191 if (method.hasOverrideAnnotation) {
192 setBuilder.add(method)
195 return setBuilder.build()
199 * Generate 'fieldsFrom' method to set builder properties based on type of given argument.
201 def private generateMethodFieldsFrom() '''
202 «IF (!(targetType instanceof GeneratedTransferObject))»
203 «IF targetType.hasImplementsFromUses»
204 «val List<Type> done = targetType.getBaseIfcs»
205 «generateMethodFieldsFromComment(targetType)»
206 public void fieldsFrom(«DATA_OBJECT.importedName» arg) {
207 boolean isValidArg = false;
208 «FOR impl : targetType.getAllIfcs»
209 «generateIfCheck(impl, done)»
211 «CODEHELPERS.importedName».validValue(isValidArg, arg, "«targetType.getAllIfcs.toListOfNames»");
217 def private generateMethodFieldsFromComment(GeneratedType type) '''
219 * Set fields from given grouping argument. Valid argument is instance of one of following types:
221 «FOR impl : type.getAllIfcs»
222 * <li>{@link «impl.importedName»}</li>
226 * @param arg grouping object
227 * @throws IllegalArgumentException if given argument is none of valid types or has property with incompatible value
232 * Method is used to find out if given type implements any interface from uses.
234 def boolean hasImplementsFromUses(GeneratedType type) {
236 for (impl : type.getAllIfcs) {
237 if (impl instanceof GeneratedType && (impl as GeneratedType).hasNonDefaultMethods) {
244 def private generateIfCheck(Type impl, List<Type> done) '''
245 «IF (impl instanceof GeneratedType && (impl as GeneratedType).hasNonDefaultMethods)»
246 «val implType = impl as GeneratedType»
247 if (arg instanceof «implType.importedName») {
248 «printPropertySetter(implType)»
254 def private printPropertySetter(Type implementedIfc) '''
255 «IF (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))»
256 «val ifc = implementedIfc as GeneratedType»
257 «FOR getter : ifc.nonDefaultMethods»
258 «IF BindingMapping.isGetterMethodName(getter.name) && !hasOverrideAnnotation(getter)»
259 «printPropertySetter(getter, '''((«ifc.importedName»)arg).«getter.name»()''', getter.propertyNameFromGetter)»;
265 def private printPropertySetter(MethodSignature getter, String retrieveProperty, String propertyName) {
266 val ownGetter = implTemplate.findGetter(getter.name)
267 val ownGetterType = ownGetter.returnType
268 if (Types.strictTypeEquals(getter.returnType, ownGetterType)) {
269 return "this._" + propertyName + " = " + retrieveProperty
271 if (ownGetterType instanceof ParameterizedType) {
272 val itemType = ownGetterType.actualTypeArguments.get(0)
273 if (Types.isListType(ownGetterType)) {
274 return printPropertySetter(retrieveProperty, propertyName, "checkListFieldCast", itemType.importedName)
276 if (Types.isSetType(ownGetterType)) {
277 return printPropertySetter(retrieveProperty, propertyName, "checkSetFieldCast", itemType.importedName)
280 return printPropertySetter(retrieveProperty, propertyName, "checkFieldCast", ownGetterType.importedName)
283 def private printPropertySetter(String retrieveProperty, String propertyName, String checkerName, String className) '''
284 this._«propertyName» = «CODEHELPERS.importedName».«checkerName»(«className».class, "«propertyName»", «retrieveProperty»)'''
286 private def List<Type> getBaseIfcs(GeneratedType type) {
287 val List<Type> baseIfcs = new ArrayList();
288 for (ifc : type.implements) {
289 if (ifc instanceof GeneratedType && (ifc as GeneratedType).hasNonDefaultMethods) {
296 private def Set<Type> getAllIfcs(Type type) {
297 val Set<Type> baseIfcs = new HashSet()
298 if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
299 val ifc = type as GeneratedType
300 for (impl : ifc.implements) {
301 if (impl instanceof GeneratedType && (impl as GeneratedType).hasNonDefaultMethods) {
304 baseIfcs.addAll(impl.getAllIfcs)
310 private def List<String> toListOfNames(Collection<Type> types) {
311 val List<String> names = new ArrayList
313 names.add(type.importedName)
318 def private constantsDeclarations() '''
319 «FOR c : type.getConstantDefinitions»
320 «IF c.getName.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)»
321 «val cValue = c.value as Map<String, String>»
322 «val String fieldSuffix = c.getName.substring(TypeConstants.PATTERN_CONSTANT_NAME.length)»
323 «val jurPatternRef = JUR_PATTERN.importedName»
324 «IF cValue.size == 1»
325 «val firstEntry = cValue.entrySet.iterator.next»
326 private static final «jurPatternRef» «Constants.MEMBER_PATTERN_LIST»«fieldSuffix» = «jurPatternRef».compile("«firstEntry.key.escapeJava»");
327 private static final String «Constants.MEMBER_REGEX_LIST»«fieldSuffix» = "«firstEntry.value.escapeJava»";
329 private static final «jurPatternRef»[] «Constants.MEMBER_PATTERN_LIST»«fieldSuffix» = «CODEHELPERS.importedName».compilePatterns(«ImmutableList.importedName».of(
330 «FOR v : cValue.keySet SEPARATOR ", "»"«v.escapeJava»"«ENDFOR»));
331 private static final String[] «Constants.MEMBER_REGEX_LIST»«fieldSuffix» = { «
332 FOR v : cValue.values SEPARATOR ", "»"«v.escapeJava»"«ENDFOR» };
340 def private generateSetter(GeneratedProperty field) {
341 val returnType = field.returnType
342 if (returnType instanceof ParameterizedType) {
343 if (Types.isListType(returnType) || Types.isSetType(returnType)) {
344 val arguments = returnType.actualTypeArguments
345 if (arguments.isEmpty) {
346 return generateListSetter(field, Types.objectType)
348 return generateListSetter(field, arguments.get(0))
349 } else if (Types.isMapType(returnType)) {
350 return generateMapSetter(field, returnType.actualTypeArguments.get(1))
353 return generateSimpleSetter(field, returnType)
356 def private generateListSetter(GeneratedProperty field, Type actualType) '''
357 «val restrictions = restrictionsForSetter(actualType)»
358 «IF restrictions !== null»
359 «generateCheckers(field, restrictions, actualType)»
361 public «type.getName» set«field.getName.toFirstUpper»(final «field.returnType.importedName» values) {
362 «IF restrictions !== null»
363 if (values != null) {
364 for («actualType.importedName» value : values) {
365 «checkArgument(field, restrictions, actualType, "value")»
369 this.«field.fieldName» = values;
375 def private generateMapSetter(GeneratedProperty field, Type actualType) '''
376 «val restrictions = restrictionsForSetter(actualType)»
377 «IF restrictions !== null»
378 «generateCheckers(field, restrictions, actualType)»
380 public «type.getName» set«field.name.toFirstUpper»(final «field.returnType.importedName» values) {
381 «IF restrictions !== null»
382 if (values != null) {
383 for («actualType.importedName» value : values.values()) {
384 «checkArgument(field, restrictions, actualType, "value")»
388 this.«field.fieldName» = values;
393 def private generateSimpleSetter(GeneratedProperty field, Type actualType) '''
394 «val restrictions = restrictionsForSetter(actualType)»
395 «IF restrictions !== null»
397 «generateCheckers(field, restrictions, actualType)»
400 «val setterName = "set" + field.getName.toFirstUpper»
401 public «type.getName» «setterName»(final «field.returnType.importedName» value) {
402 «IF restrictions !== null»
404 «checkArgument(field, restrictions, actualType, "value")»
407 this.«field.fieldName» = value;
413 * Template method which generates setter methods
415 * @return string with the setter methods
417 def private generateSetters() '''
418 «IF keyType !== null»
419 public «type.getName» withKey(final «keyType.importedName» key) {
424 «FOR property : properties»
425 «generateSetter(property)»
428 «IF augmentType !== null»
429 «val augmentTypeRef = augmentType.importedName»
430 «val jlClassRef = CLASS.importedName»
431 «val hashMapRef = JU_HASHMAP.importedName»
433 * Add an augmentation to this builder's product.
435 * @param augmentation augmentation to be added
436 * @return this builder
437 * @throws NullPointerException if {@code augmentation} is null
439 public «type.name» addAugmentation(«augmentTypeRef» augmentation) {
440 «jlClassRef»<? extends «augmentTypeRef»> augmentationType = augmentation.«BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME»();
441 if (!(this.«AUGMENTATION_FIELD» instanceof «hashMapRef»)) {
442 this.«AUGMENTATION_FIELD» = new «hashMapRef»<>();
445 this.«AUGMENTATION_FIELD».put(augmentationType, augmentation);
450 * Remove an augmentation from this builder's product. If this builder does not track such an augmentation
451 * type, this method does nothing.
453 * @param augmentationType augmentation type to be removed
454 * @return this builder
456 public «type.name» removeAugmentation(«jlClassRef»<? extends «augmentTypeRef»> augmentationType) {
457 if (this.«AUGMENTATION_FIELD» instanceof «hashMapRef») {
458 this.«AUGMENTATION_FIELD».remove(augmentationType);
465 private def createDescription(GeneratedType targetType) {
466 val target = targetType.importedName
468 Class that builds {@link «target»} instances. Overall design of the class is that of a
469 <a href="https://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a>, where method chaining is used.
472 In general, this class is supposed to be used like this template:
475 «target» create«target»(int fooXyzzy, int barBaz) {
476 return new «target»Builder()
477 .setFoo(new FooBuilder().setXyzzy(fooXyzzy).build())
478 .setBar(new BarBuilder().setBaz(barBaz).build())
485 This pattern is supported by the immutable nature of «target», as instances can be freely passed around without
486 worrying about synchronization issues.
489 As a side note: method chaining results in:
491 <li>very efficient Java bytecode, as the method invocation result, in this case the Builder reference, is
492 on the stack, so further method invocations just need to fill method arguments for the next method
493 invocation, which is terminated by {@link #build()}, which is then returned from the method</li>
494 <li>better understanding by humans, as the scope of mutable state (the builder) is kept to a minimum and is
496 <li>better optimization opportunities, as the object scope is minimized in terms of invocation (rather than
497 method) stack, making <a href="https://en.wikipedia.org/wiki/Escape_analysis">escape analysis</a> a lot
498 easier. Given enough compiler (JIT/AOT) prowess, the cost of th builder object can be completely
506 override protected String formatDataForJavaDoc(GeneratedType type) {
507 val typeDescription = createDescription(type)
510 «IF !typeDescription.nullOrEmpty»
516 private def generateAugmentation() '''
517 @«SUPPRESS_WARNINGS.importedName»({ "unchecked", "checkstyle:methodTypeParameterName"})
518 public <E$$ extends «augmentType.importedName»> E$$ «AUGMENTABLE_AUGMENTATION_NAME»(«CLASS.importedName»<E$$> augmentationType) {
519 return (E$$) «AUGMENTATION_FIELD».get(«JU_OBJECTS.importedName».requireNonNull(augmentationType));
523 override protected generateCopyKeys(List<GeneratedProperty> keyProps) '''
524 this.key = base.«BindingMapping.IDENTIFIABLE_KEY_NAME»();
525 «FOR field : keyProps»
526 this.«field.fieldName» = base.«field.getterMethodName»();
530 override protected CharSequence generateCopyNonKeys(Collection<BuilderGeneratedProperty> props) '''
532 this.«field.fieldName» = base.«field.getterName»();
536 override protected generateCopyAugmentation(Type implType) {
537 val hashMapRef = JU_HASHMAP.importedName
538 val augmentTypeRef = augmentType.importedName
540 «JU_MAP.importedName»<«CLASS.importedName»<? extends «augmentTypeRef»>, «augmentTypeRef»> aug = base.augmentations();
541 if (!aug.isEmpty()) {
542 this.«AUGMENTATION_FIELD» = new «hashMapRef»<>(aug);