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.spec.naming.BindingMapping.AUGMENTATION_FIELD
13 import com.google.common.collect.ImmutableList
14 import java.util.ArrayList
15 import java.util.Collection
16 import java.util.HashMap
17 import java.util.HashSet
21 import java.util.regex.Pattern
22 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
23 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
24 import org.opendaylight.mdsal.binding.model.api.GeneratedType
25 import org.opendaylight.mdsal.binding.model.api.JavaTypeName
26 import org.opendaylight.mdsal.binding.model.api.ParameterizedType
27 import org.opendaylight.mdsal.binding.model.api.Type
28 import org.opendaylight.mdsal.binding.model.util.TypeConstants
29 import org.opendaylight.mdsal.binding.model.util.Types
30 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping
31 import org.opendaylight.yangtools.concepts.Builder
32 import org.opendaylight.yangtools.yang.binding.AugmentationHolder
33 import org.opendaylight.yangtools.yang.binding.CodeHelpers
34 import org.opendaylight.yangtools.yang.binding.DataObject
37 * Template for generating JAVA builder classes.
39 class BuilderTemplate extends AbstractBuilderTemplate {
41 * Constant used as suffix for builder name.
43 public static val BUILDER = "Builder";
46 * Constructs new instance of this class.
47 * @throws IllegalArgumentException if <code>genType</code> equals <code>null</code>
49 new(GeneratedType genType, GeneratedType targetType, Set<GeneratedProperty> properties, Type augmentType,
51 super(genType, targetType, properties, augmentType, keyType)
54 override isLocalInnerClass(JavaTypeName name) {
55 // Builders do not have inner types
60 * Template method which generates JAVA class body for builder class and for IMPL class.
62 * @return string with JAVA source code
65 «wrapToDocumentation(formatDataForJavaDoc(type))»
66 public class «type.name» implements «Builder.importedName»<«targetType.importedName»> {
68 «generateFields(false)»
70 «constantsDeclarations()»
72 «IF augmentType !== null»
73 «generateAugmentField()»
76 «generateConstructorsFromIfcs()»
78 public «generateCopyConstructor(targetType, type.enclosedTypes.get(0))»
80 «generateMethodFieldsFrom()»
82 «generateGetters(false)»
86 @«Override.importedName»
87 public «targetType.name» build() {
88 return new «type.enclosedTypes.get(0).importedName»(this);
91 «new BuilderImplTemplate(this, type.enclosedTypes.get(0)).body»
96 * Generate default constructor and constructor for every implemented interface from uses statements.
98 def private generateConstructorsFromIfcs() '''
99 public «type.name»() {
101 «IF (!(targetType instanceof GeneratedTransferObject))»
102 «FOR impl : targetType.implements»
103 «generateConstructorFromIfc(impl)»
109 * Generate constructor with argument of given type.
111 def private Object generateConstructorFromIfc(Type impl) '''
112 «IF (impl instanceof GeneratedType)»
113 «IF impl.hasNonDefaultMethods»
114 public «type.name»(«impl.fullyQualifiedName» arg) {
115 «printConstructorPropertySetter(impl)»
118 «FOR implTypeImplement : impl.implements»
119 «generateConstructorFromIfc(implTypeImplement)»
124 def private Object printConstructorPropertySetter(Type implementedIfc) '''
125 «IF (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))»
126 «val ifc = implementedIfc as GeneratedType»
127 «FOR getter : ifc.nonDefaultMethods»
128 «IF BindingMapping.isGetterMethodName(getter.name)»
129 this._«getter.propertyNameFromGetter» = arg.«getter.name»();
132 «FOR impl : ifc.implements»
133 «printConstructorPropertySetter(impl)»
139 * Generate 'fieldsFrom' method to set builder properties based on type of given argument.
141 def private generateMethodFieldsFrom() '''
142 «IF (!(targetType instanceof GeneratedTransferObject))»
143 «IF targetType.hasImplementsFromUses»
144 «val List<Type> done = targetType.getBaseIfcs»
145 «generateMethodFieldsFromComment(targetType)»
146 public void fieldsFrom(«DataObject.importedName» arg) {
147 boolean isValidArg = false;
148 «FOR impl : targetType.getAllIfcs»
149 «generateIfCheck(impl, done)»
151 «CodeHelpers.importedName».validValue(isValidArg, arg, "«targetType.getAllIfcs.toListOfNames»");
157 def private generateMethodFieldsFromComment(GeneratedType type) '''
159 * Set fields from given grouping argument. Valid argument is instance of one of following types:
161 «FOR impl : type.getAllIfcs»
162 * <li>«impl.fullyQualifiedName»</li>
166 * @param arg grouping object
167 * @throws IllegalArgumentException if given argument is none of valid types
172 * Method is used to find out if given type implements any interface from uses.
174 def boolean hasImplementsFromUses(GeneratedType type) {
176 for (impl : type.getAllIfcs) {
177 if (impl instanceof GeneratedType && (impl as GeneratedType).hasNonDefaultMethods) {
184 def private generateIfCheck(Type impl, List<Type> done) '''
185 «IF (impl instanceof GeneratedType && (impl as GeneratedType).hasNonDefaultMethods)»
186 «val implType = impl as GeneratedType»
187 if (arg instanceof «implType.fullyQualifiedName») {
188 «printPropertySetter(implType)»
194 def private printPropertySetter(Type implementedIfc) '''
195 «IF (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))»
196 «val ifc = implementedIfc as GeneratedType»
197 «FOR getter : ifc.nonDefaultMethods»
198 «IF BindingMapping.isGetterMethodName(getter.name)»
199 this._«getter.propertyNameFromGetter» = ((«implementedIfc.fullyQualifiedName»)arg).«getter.name»();
205 private def List<Type> getBaseIfcs(GeneratedType type) {
206 val List<Type> baseIfcs = new ArrayList();
207 for (ifc : type.implements) {
208 if (ifc instanceof GeneratedType && (ifc as GeneratedType).hasNonDefaultMethods) {
215 private def Set<Type> getAllIfcs(Type type) {
216 val Set<Type> baseIfcs = new HashSet()
217 if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
218 val ifc = type as GeneratedType
219 for (impl : ifc.implements) {
220 if (impl instanceof GeneratedType && (impl as GeneratedType).hasNonDefaultMethods) {
223 baseIfcs.addAll(impl.getAllIfcs)
229 private def List<String> toListOfNames(Collection<Type> types) {
230 val List<String> names = new ArrayList
232 names.add(type.fullyQualifiedName)
237 def private constantsDeclarations() '''
238 «FOR c : type.getConstantDefinitions»
239 «IF c.getName.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)»
240 «val cValue = c.value as Map<String, String>»
241 «val String fieldSuffix = c.getName.substring(TypeConstants.PATTERN_CONSTANT_NAME.length)»
242 «IF cValue.size == 1»
243 private static final «Pattern.importedName» «Constants.MEMBER_PATTERN_LIST»«fieldSuffix» = «Pattern.importedName».compile("«cValue.keySet.get(0).escapeJava»");
244 private static final String «Constants.MEMBER_REGEX_LIST»«fieldSuffix» = "«cValue.values.get(0).escapeJava»";
246 private static final «Pattern.importedName»[] «Constants.MEMBER_PATTERN_LIST»«fieldSuffix» = «CodeHelpers.importedName».compilePatterns(«ImmutableList.importedName».of(
247 «FOR v : cValue.keySet SEPARATOR ", "»"«v.escapeJava»"«ENDFOR»));
248 private static final String[] «Constants.MEMBER_REGEX_LIST»«fieldSuffix» = { «
249 FOR v : cValue.values SEPARATOR ", "»"«v.escapeJava»"«ENDFOR» };
257 def private generateListSetter(GeneratedProperty field, Type actualType) '''
258 «val restrictions = restrictionsForSetter(actualType)»
259 «IF restrictions !== null»
260 «generateCheckers(field, restrictions, actualType)»
262 public «type.getName» set«field.getName.toFirstUpper»(final «field.returnType.importedName» values) {
263 «IF restrictions !== null»
264 if (values != null) {
265 for («actualType.getFullyQualifiedName» value : values) {
266 «checkArgument(field, restrictions, actualType, "value")»
270 this.«field.fieldName.toString» = values;
276 def private generateSetter(GeneratedProperty field, Type actualType) '''
277 «val restrictions = restrictionsForSetter(actualType)»
278 «IF restrictions !== null»
279 «generateCheckers(field, restrictions, actualType)»
282 public «type.getName» set«field.getName.toFirstUpper»(final «field.returnType.importedName» value) {
283 «IF restrictions !== null»
285 «checkArgument(field, restrictions, actualType, "value")»
288 this.«field.fieldName.toString» = value;
293 private def Type getActualType(ParameterizedType ptype) {
294 return ptype.getActualTypeArguments.get(0)
298 * Template method which generates setter methods
300 * @return string with the setter methods
302 def private generateSetters() '''
303 «IF keyType !== null»
304 public «type.getName» withKey(final «keyType.importedName» key) {
309 «FOR property : properties»
310 «IF property.returnType instanceof ParameterizedType && Types.isListType(property.returnType)»
311 «generateListSetter(property, getActualType(property.returnType as ParameterizedType))»
313 «generateSetter(property, property.returnType)»
317 «IF augmentType !== null»
318 public «type.name» add«AUGMENTATION_FIELD.toFirstUpper»(«Class.importedName»<? extends «augmentType.importedName»> augmentationType, «augmentType.importedName» augmentationValue) {
319 if (augmentationValue == null) {
320 return remove«AUGMENTATION_FIELD.toFirstUpper»(augmentationType);
323 if (!(this.«AUGMENTATION_FIELD» instanceof «HashMap.importedName»)) {
324 this.«AUGMENTATION_FIELD» = new «HashMap.importedName»<>();
327 this.«AUGMENTATION_FIELD».put(augmentationType, augmentationValue);
331 public «type.name» remove«AUGMENTATION_FIELD.toFirstUpper»(«Class.importedName»<? extends «augmentType.importedName»> augmentationType) {
332 if (this.«AUGMENTATION_FIELD» instanceof «HashMap.importedName») {
333 this.«AUGMENTATION_FIELD».remove(augmentationType);
340 private def createDescription(GeneratedType type) {
342 Class that builds {@link «type.importedName»} instances.
344 @see «type.importedName»
348 override protected String formatDataForJavaDoc(GeneratedType type) {
349 val typeDescription = createDescription(type)
352 «IF !typeDescription.nullOrEmpty»
358 override protected generateCopyKeys(List<GeneratedProperty> keyProps) '''
359 this.key = base.«BindingMapping.IDENTIFIABLE_KEY_NAME»();
360 «FOR field : keyProps»
361 this.«field.fieldName» = base.«field.getterMethodName»();
365 override protected generateCopyAugmentation(Type implType) {
366 val implTypeRef = implType.importedName
367 val augmentationHolderRef = AugmentationHolder.importedName
368 val typeRef = targetType.importedName
369 val hashMapRef = HashMap.importedName
370 val augmentTypeRef = augmentType.importedName
372 if (base instanceof «implTypeRef») {
373 «implTypeRef» impl = («implTypeRef») base;
374 if (!impl.«AUGMENTATION_FIELD».isEmpty()) {
375 this.«AUGMENTATION_FIELD» = new «hashMapRef»<>(impl.«AUGMENTATION_FIELD»);
377 } else if (base instanceof «augmentationHolderRef») {
378 @SuppressWarnings("unchecked")
379 «Map.importedName»<«Class.importedName»<? extends «augmentTypeRef»>, «augmentTypeRef»> aug =((«augmentationHolderRef»<«typeRef»>) base).augmentations();
380 if (!aug.isEmpty()) {
381 this.«AUGMENTATION_FIELD» = new «hashMapRef»<>(aug);
387 private static def hasNonDefaultMethods(GeneratedType type) {
388 !type.methodDefinitions.isEmpty && type.methodDefinitions.exists([def | !def.isDefault])
391 private static def nonDefaultMethods(GeneratedType type) {
392 type.methodDefinitions.filter([def | !def.isDefault])