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 java.util.Objects.requireNonNull
11 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
12 import static org.opendaylight.mdsal.binding.model.util.Types.BYTE_ARRAY;
13 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
14 import static extension org.apache.commons.text.StringEscapeUtils.escapeJava
16 import com.google.common.base.Preconditions
17 import com.google.common.collect.ImmutableList
18 import com.google.common.collect.Lists
19 import java.beans.ConstructorProperties
20 import java.util.ArrayList
21 import java.util.Base64;
22 import java.util.Collections
25 import java.util.Objects
26 import java.util.regex.Pattern
27 import org.opendaylight.mdsal.binding.model.api.ConcreteType
28 import org.opendaylight.mdsal.binding.model.api.Constant
29 import org.opendaylight.mdsal.binding.model.api.Enumeration
30 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
31 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
32 import org.opendaylight.mdsal.binding.model.api.Restrictions
33 import org.opendaylight.mdsal.binding.model.api.Type
34 import org.opendaylight.mdsal.binding.model.util.TypeConstants
35 import org.opendaylight.yangtools.yang.binding.CodeHelpers
36 import org.opendaylight.yangtools.yang.common.Empty
37 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
40 * Template for generating JAVA class.
42 class ClassTemplate extends BaseTemplate {
44 protected val List<GeneratedProperty> properties
45 protected val List<GeneratedProperty> finalProperties
46 protected val List<GeneratedProperty> parentProperties
47 protected val Iterable<GeneratedProperty> allProperties
48 protected val Restrictions restrictions
51 * List of enumeration which are generated as JAVA enum type.
53 protected val List<Enumeration> enums
56 * List of constant instances which are generated as JAVA public static final attributes.
58 protected val List<Constant> consts
60 protected val GeneratedTransferObject genTO
62 val AbstractRangeGenerator<?> rangeGenerator
65 * Creates instance of this class with concrete <code>genType</code>.
67 * @param genType generated transfer object which will be transformed to JAVA class source code
69 new(GeneratedTransferObject genType) {
70 this(new TopLevelJavaGeneratedType(genType), genType)
74 * Creates instance of this class with concrete <code>genType</code>.
76 * @param genType generated transfer object which will be transformed to JAVA class source code
78 new(AbstractJavaGeneratedType javaType, GeneratedTransferObject genType) {
79 super(javaType, genType)
81 this.properties = genType.properties
82 this.finalProperties = GeneratorUtil.resolveReadOnlyPropertiesFromTO(genTO.properties)
83 this.parentProperties = GeneratorUtil.getPropertiesOfAllParents(genTO)
84 this.restrictions = genType.restrictions
86 var List<GeneratedProperty> sorted = new ArrayList<GeneratedProperty>();
87 sorted.addAll(properties);
88 sorted.addAll(parentProperties);
89 Collections.sort(sorted, [p1, p2|
90 p1.name.compareTo(p2.name)
93 this.allProperties = sorted
94 this.enums = genType.enumerations
95 this.consts = genType.constantDefinitions
97 if (restrictions !== null && restrictions.rangeConstraint.present) {
98 rangeGenerator = requireNonNull(AbstractRangeGenerator.forType(findProperty(genType, "value").returnType))
100 rangeGenerator = null
105 * Generates JAVA class source code (class body only).
107 * @return string with JAVA class body source code
109 def CharSequence generateAsInnerClass() {
110 return generateBody(true)
113 override protected body() {
118 * Template method which generates class body.
120 * @param isInnerClass boolean value which specify if generated class is|isn't inner
121 * @return string with class source code in JAVA format
123 def protected generateBody(boolean isInnerClass) '''
124 «wrapToDocumentation(formatDataForJavaDoc(type))»
125 «annotationDeclaration»
126 «generateClassDeclaration(isInnerClass)» {
128 «innerClassesDeclarations»
130 «constantsDeclarations»
133 «IF restrictions !== null»
134 «IF restrictions.lengthConstraint.present»
135 «LengthGenerator.generateLengthChecker("_value", findProperty(genTO, "value").returnType, restrictions.lengthConstraint.get, this)»
137 «IF restrictions.rangeConstraint.present»
138 «rangeGenerator.generateRangeChecker("_value", restrictions.rangeConstraint.get, this)»
146 «FOR field : properties SEPARATOR "\n"»
153 «IF (genTO.isTypedef() && genTO.getBaseType instanceof BitsTypeDefinition)»
154 «generateGetValueForBitsTypeDef»
161 «generateToString(genTO.toStringIdentifiers)»
167 * Template method which generates the method <code>getValue()</code> for typedef,
168 * which base type is BitsDefinition.
170 * @return string with the <code>getValue()</code> method definition in JAVA format
172 def protected generateGetValueForBitsTypeDef() '''
174 public boolean[] getValue() {
175 return new boolean[]{
176 «FOR property: genTO.properties SEPARATOR ','»
184 * Template method which generates inner classes inside this interface.
186 * @return string with the source code for inner classes in JAVA format
188 def protected innerClassesDeclarations() '''
189 «IF !type.enclosedTypes.empty»
190 «FOR innerClass : type.enclosedTypes SEPARATOR "\n"»
191 «generateInnerClass(innerClass)»
196 def protected constructors() '''
198 «genUnionConstructor»
200 «allValuesConstructor»
202 «IF !allProperties.empty»
205 «IF properties.empty && !parentProperties.empty »
210 def protected allValuesConstructor() '''
211 «IF genTO.typedef && !allProperties.empty && allProperties.size == 1 && allProperties.get(0).name.equals("value")»
212 @«ConstructorProperties.importedName»("value")
214 public «type.name»(«allProperties.asArgumentsDeclaration») {
215 «IF false == parentProperties.empty»
216 super(«parentProperties.asArguments»);
218 «FOR p : allProperties»
219 «generateRestrictions(type, p.fieldName.toString, p.returnType)»
223 * If we have patterns, we need to apply them to the value field. This is a sad
224 * consequence of how this code is structured.
226 IF genTO.typedef && !allProperties.empty && allProperties.size == 1 && allProperties.get(0).name.equals("value")»
227 «Objects.importedName».requireNonNull(_value, "Supplied value may not be null");
228 «genPatternEnforcer("_value")»
232 «IF p.returnType.importedName.contains("[]")»
233 «IF genTO.typedef && !allProperties.empty && allProperties.size == 1 && allProperties.get(0).name
235 this.«p.fieldName» = «p.fieldName».clone();
237 this.«p.fieldName» = «p.fieldName» == null ? null : «p.fieldName».clone();
240 this.«p.fieldName» = «p.fieldName»;
247 def protected genUnionConstructor() '''
248 «FOR p : allProperties»
249 «val List<GeneratedProperty> other = new ArrayList(properties)»
251 «genConstructor(p, other)»
257 def protected genConstructor(GeneratedProperty property, GeneratedProperty... other) '''
258 public «type.name»(«property.returnType.importedName + " " + property.name») {
259 «IF false == parentProperties.empty»
260 super(«parentProperties.asArguments»);
263 «generateRestrictions(type, property.fieldName.toString, property.returnType)»
265 this.«property.fieldName» = «property.name»;
267 this.«p.fieldName» = null;
272 def private genPatternEnforcer(String ref) '''
274 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
275 «CodeHelpers.importedName».checkPattern(«ref», «Constants.MEMBER_PATTERN_LIST», «Constants.MEMBER_REGEX_LIST»);
280 def private static paramValue(Type returnType, String paramName) {
281 if (returnType instanceof ConcreteType) {
284 return paramName + ".getValue()"
288 def private generateRestrictions(Type type, String paramName, Type returnType) '''
289 «val restrictions = type.restrictions»
290 «IF restrictions !== null»
291 «IF restrictions.lengthConstraint.present || restrictions.rangeConstraint.present»
292 if («paramName» != null) {
293 «IF restrictions.lengthConstraint.present»
294 «LengthGenerator.generateLengthCheckerCall(paramName, paramValue(returnType, paramName))»
296 «IF restrictions.rangeConstraint.present»
297 «rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))»
304 def protected copyConstructor() '''
306 * Creates a copy from Source Object.
308 * @param source Source object
310 public «type.name»(«type.name» source) {
311 «IF false == parentProperties.empty»
315 this.«p.fieldName» = source.«p.fieldName»;
320 def protected parentConstructor() '''
322 * Creates a new instance from «genTO.superType.importedName»
324 * @param source Source object
326 public «type.name»(«genTO.superType.importedName» source) {
328 «genPatternEnforcer("getValue()")»
332 def protected defaultInstance() '''
333 «IF genTO.typedef && !allProperties.empty && !genTO.unionType»
334 «val prop = allProperties.get(0)»
335 «IF !("org.opendaylight.yangtools.yang.binding.InstanceIdentifier".equals(prop.returnType.fullyQualifiedName))»
336 public static «genTO.name» getDefaultInstance(String defaultValue) {
337 «IF BYTE_ARRAY.equals(prop.returnType)»
338 return new «genTO.name»(«Base64.importedName».getDecoder().decode(defaultValue));
339 «ELSEIF STRING.equals(prop.returnType)»
340 return new «genTO.name»(defaultValue);
341 «ELSEIF Constants.EMPTY.equals(prop.returnType)»
342 «Preconditions.importedName».checkArgument(defaultValue.isEmpty(), "Invalid value %s", defaultValue);
343 return new «genTO.name»(«Empty.importedName».getInstance());
344 «ELSEIF allProperties.size > 1»
346 «ELSEIF BOOLEAN.equals(prop.returnType)»
347 return new «genTO.name»(«Boolean.importedName».valueOf(defaultValue));
348 «ELSEIF "java.lang.Byte".equals(prop.returnType.fullyQualifiedName)»
349 return new «genTO.name»(«Byte.importedName».valueOf(defaultValue));
350 «ELSEIF "java.lang.Short".equals(prop.returnType.fullyQualifiedName)»
351 return new «genTO.name»(«Short.importedName».valueOf(defaultValue));
352 «ELSEIF "java.lang.Integer".equals(prop.returnType.fullyQualifiedName)»
353 return new «genTO.name»(«Integer.importedName».valueOf(defaultValue));
354 «ELSEIF "java.lang.Long".equals(prop.returnType.fullyQualifiedName)»
355 return new «genTO.name»(«Long.importedName».valueOf(defaultValue));
357 return new «genTO.name»(new «prop.returnType.importedName»(defaultValue));
364 def protected bitsArgs() '''
365 «List.importedName»<«String.importedName»> properties = «Lists.importedName».newArrayList(«allProperties.propsAsArgs»);
366 if (!properties.contains(defaultValue)) {
367 throw new «IllegalArgumentException.importedName»("invalid default parameter");
370 return new «genTO.name»(
371 «FOR prop : allProperties SEPARATOR ","»
372 properties.get(i++).equals(defaultValue) ? «Boolean.importedName».TRUE : null
377 def protected propsAsArgs(Iterable<GeneratedProperty> properties) '''
378 «FOR prop : properties SEPARATOR ","»
384 * Template method which generates JAVA class declaration.
386 * @param isInnerClass boolean value which specify if generated class is|isn't inner
387 * @return string with class declaration in JAVA format
389 def protected generateClassDeclaration(boolean isInnerClass) '''
393 ELSEIF (type.abstract)»«
397 ENDIF»class «type.name»«
398 IF (genTO.superType !== null)»«
399 " extends "»«genTO.superType.importedName»«
401 «IF (!type.implements.empty)»«
403 FOR type : type.implements SEPARATOR ", "»«
410 * Template method which generates JAVA enum type.
412 * @return string with inner enum source code in JAVA format
414 def protected enumDeclarations() '''
416 «FOR e : enums SEPARATOR "\n"»
417 «new EnumTemplate(javaType.getEnclosedType(e.identifier), e).generateAsInnerClass»
422 def protected suidDeclaration() '''
423 «IF genTO.SUID !== null»
424 private static final long serialVersionUID = «genTO.SUID.value»L;
428 def protected annotationDeclaration() '''
429 «IF genTO.getAnnotations !== null»
430 «FOR e : genTO.getAnnotations»
437 * Template method which generates JAVA constants.
439 * @return string with constants in JAVA format
441 def protected constantsDeclarations() '''
444 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
445 «val cValue = c.value as Map<String, String>»
446 public static final «List.importedName»<String> «TypeConstants.PATTERN_CONSTANT_NAME» = «ImmutableList.importedName».of(«
447 FOR v : cValue.keySet SEPARATOR ", "»"«v.escapeJava»"«ENDFOR»);
448 «IF cValue.size == 1»
449 private static final «Pattern.importedName» «Constants.MEMBER_PATTERN_LIST» = «Pattern.importedName».compile(«TypeConstants.PATTERN_CONSTANT_NAME».get(0));
450 private static final String «Constants.MEMBER_REGEX_LIST» = "«cValue.values.get(0).escapeJava»";
452 private static final «Pattern.importedName»[] «Constants.MEMBER_PATTERN_LIST» = «CodeHelpers.importedName».compilePatterns(«TypeConstants.PATTERN_CONSTANT_NAME»);
453 private static final String[] «Constants.MEMBER_REGEX_LIST» = { «
454 FOR v : cValue.values SEPARATOR ", "»"«v.escapeJava»"«ENDFOR» };
464 * Template method which generates JAVA class attributes.
466 * @return string with the class attributes in JAVA format
468 def protected generateFields() '''
469 «IF !properties.empty»
471 private«IF isReadOnly(f)» final«ENDIF» «f.returnType.importedName» «f.fieldName»;
476 protected def isReadOnly(GeneratedProperty field) {
477 return field.readOnly
481 * Template method which generates the method <code>hashCode()</code>.
483 * @return string with the <code>hashCode()</code> method definition in JAVA format
485 def protected generateHashCode() {
486 val size = genTO.hashCodeIdentifiers.size
491 @«Override.importedName»
492 public int hashCode() {
494 «hashCodeResult(genTO.hashCodeIdentifiers)»
497 return «CodeHelpers.importedName».wrapperHashCode(«genTO.hashCodeIdentifiers.get(0).fieldName»);
504 * Template method which generates the method <code>equals()</code>.
506 * @return string with the <code>equals()</code> method definition in JAVA format
508 def protected generateEquals() '''
509 «IF !genTO.equalsIdentifiers.empty»
510 @«Override.importedName»
511 public boolean equals(java.lang.Object obj) {
518 if (getClass() != obj.getClass()) {
521 «type.name» other = («type.name») obj;
522 «FOR property : genTO.equalsIdentifiers»
523 «val fieldName = property.fieldName»
524 if (!«property.importedUtilClass».equals(«fieldName», other.«fieldName»)) {
533 def GeneratedProperty getPropByName(String name) {
534 for (GeneratedProperty prop : allProperties) {
535 if (prop.name.equals(name)) {