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.BaseYangTypes.BINARY_TYPE
12 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.BOOLEAN_TYPE
13 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.EMPTY_TYPE
14 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.INSTANCE_IDENTIFIER
15 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.INT16_TYPE
16 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.INT32_TYPE
17 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.INT64_TYPE
18 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.INT8_TYPE
19 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.STRING_TYPE
20 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.UINT16_TYPE
21 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.UINT32_TYPE
22 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.UINT64_TYPE
23 import static org.opendaylight.mdsal.binding.model.util.BaseYangTypes.UINT8_TYPE
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.SCALAR_TYPE_OBJECT
25 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN
26 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
27 import static extension org.apache.commons.text.StringEscapeUtils.escapeJava
29 import com.google.common.base.Preconditions
30 import com.google.common.collect.ImmutableList
31 import com.google.common.collect.Lists
32 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
33 import java.beans.ConstructorProperties
34 import java.util.ArrayList
35 import java.util.Base64;
36 import java.util.Comparator
40 import javax.management.ConstructorParameters
41 import org.gaul.modernizer_maven_annotations.SuppressModernizer
42 import org.opendaylight.mdsal.binding.model.api.ConcreteType
43 import org.opendaylight.mdsal.binding.model.api.Constant
44 import org.opendaylight.mdsal.binding.model.api.Enumeration
45 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
46 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
47 import org.opendaylight.mdsal.binding.model.api.Restrictions
48 import org.opendaylight.mdsal.binding.model.api.Type
49 import org.opendaylight.mdsal.binding.model.util.TypeConstants
50 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping
51 import org.opendaylight.yangtools.yang.common.Empty
52 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
55 * Template for generating JAVA class.
58 class ClassTemplate extends BaseTemplate {
59 static val Comparator<GeneratedProperty> PROP_COMPARATOR = Comparator.comparing([prop | prop.name])
60 static val VALUEOF_TYPES = Set.of(
71 protected val List<GeneratedProperty> properties
72 protected val List<GeneratedProperty> finalProperties
73 protected val List<GeneratedProperty> parentProperties
74 protected val List<GeneratedProperty> allProperties
75 protected val Restrictions restrictions
78 * List of enumeration which are generated as JAVA enum type.
80 protected val List<Enumeration> enums
83 * List of constant instances which are generated as JAVA public static final attributes.
85 protected val List<Constant> consts
87 protected val GeneratedTransferObject genTO
89 val AbstractRangeGenerator<?> rangeGenerator
92 * Creates instance of this class with concrete <code>genType</code>.
94 * @param genType generated transfer object which will be transformed to JAVA class source code
96 new(GeneratedTransferObject genType) {
97 this(new TopLevelJavaGeneratedType(genType), genType)
101 * Creates instance of this class with concrete <code>genType</code>.
103 * @param genType generated transfer object which will be transformed to JAVA class source code
105 new(AbstractJavaGeneratedType javaType, GeneratedTransferObject genType) {
106 super(javaType, genType)
108 this.properties = genType.properties
109 this.finalProperties = GeneratorUtil.resolveReadOnlyPropertiesFromTO(genTO.properties)
110 this.parentProperties = GeneratorUtil.getPropertiesOfAllParents(genTO)
111 this.restrictions = genType.restrictions
113 val sorted = new ArrayList();
114 sorted.addAll(properties);
115 sorted.addAll(parentProperties);
116 sorted.sort(PROP_COMPARATOR);
118 this.allProperties = sorted
119 this.enums = genType.enumerations
120 this.consts = genType.constantDefinitions
122 if (restrictions !== null && restrictions.rangeConstraint.present) {
123 rangeGenerator = requireNonNull(AbstractRangeGenerator.forType(TypeUtils.encapsulatedValueType(genType)))
125 rangeGenerator = null
130 * Generates JAVA class source code (class body only).
132 * @return string with JAVA class body source code
134 def CharSequence generateAsInnerClass() {
135 return generateBody(true)
138 override protected body() {
143 * Template method which generates class body.
145 * @param isInnerClass boolean value which specify if generated class is|isn't inner
146 * @return string with class source code in JAVA format
148 def protected generateBody(boolean isInnerClass) '''
149 «wrapToDocumentation(formatDataForJavaDoc(type))»
150 «annotationDeclaration»
151 «generateClassDeclaration(isInnerClass)» {
153 «innerClassesDeclarations»
155 «constantsDeclarations»
158 «IF restrictions !== null»
159 «IF restrictions.lengthConstraint.present»
160 «LengthGenerator.generateLengthChecker("_value", TypeUtils.encapsulatedValueType(genTO),
161 restrictions.lengthConstraint.get, this)»
163 «IF restrictions.rangeConstraint.present»
164 «rangeGenerator.generateRangeChecker("_value", restrictions.rangeConstraint.get, this)»
174 «IF (genTO.isTypedef() && genTO.getBaseType instanceof BitsTypeDefinition)»
175 «generateGetValueForBitsTypeDef»
182 «generateToString(genTO.toStringIdentifiers)»
187 def private propertyMethods() {
188 if (properties.empty) {
191 isScalarTypeObject ? scalarTypeObjectValue(properties.get(0)) : defaultProperties
194 def private isScalarTypeObject() {
195 for (impl : genTO.implements) {
196 if (SCALAR_TYPE_OBJECT.identifier.equals(impl.identifier)) {
203 def private defaultProperties() '''
204 «FOR field : properties SEPARATOR "\n"»
212 def private scalarTypeObjectValue(GeneratedProperty field) '''
213 @«OVERRIDE.importedName»
214 public «field.returnType.importedName» «BindingMapping.SCALAR_TYPE_OBJECT_GET_VALUE_NAME»() {
215 return «field.fieldName»«IF field.returnType.name.endsWith("[]")».clone()«ENDIF»;
220 * Template method which generates the method <code>getValue()</code> for typedef,
221 * which base type is BitsDefinition.
223 * @return string with the <code>getValue()</code> method definition in JAVA format
225 def protected generateGetValueForBitsTypeDef() '''
227 public boolean[] getValue() {
228 return new boolean[]{
229 «FOR property: genTO.properties SEPARATOR ','»
237 * Template method which generates inner classes inside this interface.
239 * @return string with the source code for inner classes in JAVA format
241 def protected innerClassesDeclarations() '''
242 «IF !type.enclosedTypes.empty»
243 «FOR innerClass : type.enclosedTypes SEPARATOR "\n"»
244 «generateInnerClass(innerClass)»
249 def protected constructors() '''
251 «genUnionConstructor»
252 «ELSEIF genTO.typedef && allProperties.size == 1 && allProperties.get(0).name.equals(TypeConstants.VALUE_PROP)»
256 «allValuesConstructor»
260 «IF !allProperties.empty»
263 «IF properties.empty && !parentProperties.empty »
268 def private allValuesConstructor() '''
269 public «type.name»(«allProperties.asArgumentsDeclaration») {
270 «IF !parentProperties.empty»
271 super(«parentProperties.asArguments»);
273 «FOR p : allProperties»
274 «generateRestrictions(type, p.fieldName, p.returnType)»
278 «val fieldName = p.fieldName»
279 «IF p.returnType.name.endsWith("[]")»
280 this.«fieldName» = «fieldName» == null ? null : «fieldName».clone();
282 this.«fieldName» = «fieldName»;
288 def private typedefConstructor() '''
289 @«ConstructorParameters.importedName»("«TypeConstants.VALUE_PROP»")
290 @«ConstructorProperties.importedName»("«TypeConstants.VALUE_PROP»")
291 public «type.name»(«allProperties.asArgumentsDeclaration») {
292 «IF !parentProperties.empty»
293 super(«parentProperties.asArguments»);
295 «FOR p : allProperties»
296 «generateRestrictions(type, p.fieldName, p.returnType)»
299 * If we have patterns, we need to apply them to the value field. This is a sad consequence of how this code is
302 «CODEHELPERS.importedName».requireValue(_value);
303 «genPatternEnforcer("_value")»
306 «val fieldName = p.fieldName»
307 «IF p.returnType.name.endsWith("[]")»
308 this.«fieldName» = «fieldName».clone();
310 this.«fieldName» = «fieldName»;
316 def private legacyConstructor() {
317 if (!hasUintProperties) {
321 val compatUint = CODEHELPERS.importedName + ".compatUint("
325 * Utility migration constructor.
327 «FOR prop : allProperties»
328 * @param «prop.fieldName» «prop.name»«IF prop.isUintType» in legacy Java type«ENDIF»
330 * @deprecated Use {#link «type.name»(«FOR prop : allProperties SEPARATOR ", "»«prop.returnType.importedJavadocName»«ENDFOR»)} instead.
332 @Deprecated(forRemoval = true)
333 public «type.getName»(«FOR prop : allProperties SEPARATOR ", "»«prop.legacyType.importedName» «prop.fieldName»«ENDFOR») {
334 this(«FOR prop : allProperties SEPARATOR ", "»«IF prop.isUintType»«compatUint»«prop.fieldName»)«ELSE»«prop.fieldName»«ENDIF»«ENDFOR»);
339 def protected genUnionConstructor() '''
340 «FOR p : allProperties»
341 «val List<GeneratedProperty> other = new ArrayList(properties)»
343 «genConstructor(p, other)»
348 def protected genConstructor(GeneratedProperty property, Iterable<GeneratedProperty> other) '''
349 public «type.name»(«property.returnType.importedName + " " + property.name») {
350 «IF !parentProperties.empty»
351 super(«parentProperties.asArguments»);
354 «val fieldName = property.fieldName»
355 «generateRestrictions(type, fieldName, property.returnType)»
357 this.«fieldName» = «property.name»;
359 this.«p.fieldName» = null;
364 def private genPatternEnforcer(String ref) '''
366 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
367 «CODEHELPERS.importedName».checkPattern(«ref», «Constants.MEMBER_PATTERN_LIST», «Constants.MEMBER_REGEX_LIST»);
372 def private static paramValue(Type returnType, String paramName) {
373 if (returnType instanceof ConcreteType) {
376 return paramName + ".getValue()"
380 def private generateRestrictions(Type type, String paramName, Type returnType) '''
381 «val restrictions = type.restrictions»
382 «IF restrictions !== null»
383 «IF restrictions.lengthConstraint.present || restrictions.rangeConstraint.present»
384 if («paramName» != null) {
385 «IF restrictions.lengthConstraint.present»
386 «LengthGenerator.generateLengthCheckerCall(paramName, paramValue(returnType, paramName))»
388 «IF restrictions.rangeConstraint.present»
389 «rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))»
396 def protected copyConstructor() '''
398 * Creates a copy from Source Object.
400 * @param source Source object
402 public «type.name»(«type.name» source) {
403 «IF !parentProperties.empty»
407 «val fieldName = p.fieldName»
408 this.«fieldName» = source.«fieldName»;
413 def protected parentConstructor() '''
415 * Creates a new instance from «genTO.superType.importedName»
417 * @param source Source object
419 public «type.name»(«genTO.superType.importedName» source) {
421 «genPatternEnforcer("getValue()")»
425 def protected defaultInstance() '''
426 «IF genTO.typedef && !allProperties.empty && !genTO.unionType»
427 «val prop = allProperties.get(0)»
428 «val propType = prop.returnType»
429 «IF !(INSTANCE_IDENTIFIER.identifier.equals(propType.identifier))»
430 public static «genTO.name» getDefaultInstance(final String defaultValue) {
431 «IF allProperties.size > 1»
433 «ELSEIF VALUEOF_TYPES.contains(propType)»
434 return new «genTO.name»(«propType.importedName».valueOf(defaultValue));
435 «ELSEIF STRING_TYPE.equals(propType)»
436 return new «genTO.name»(defaultValue);
437 «ELSEIF BINARY_TYPE.equals(propType)»
438 return new «genTO.name»(«Base64.importedName».getDecoder().decode(defaultValue));
439 «ELSEIF EMPTY_TYPE.equals(propType)»
440 «Preconditions.importedName».checkArgument(defaultValue.isEmpty(), "Invalid value %s", defaultValue);
441 return new «genTO.name»(«Empty.importedName».getInstance());
443 return new «genTO.name»(new «propType.importedName»(defaultValue));
450 @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "FOR with SEPARATOR, not needing for value")
451 def protected bitsArgs() '''
452 «JU_LIST.importedName»<«STRING.importedName»> properties = «Lists.importedName».newArrayList(«allProperties.propsAsArgs»);
453 if (!properties.contains(defaultValue)) {
454 throw new «IllegalArgumentException.importedName»("invalid default parameter");
457 return new «genTO.name»(
458 «FOR prop : allProperties SEPARATOR ","»
459 properties.get(i++).equals(defaultValue) ? «BOOLEAN.importedName».TRUE : null
464 def protected propsAsArgs(Iterable<GeneratedProperty> properties) '''
465 «FOR prop : properties SEPARATOR ","»
471 * Template method which generates JAVA class declaration.
473 * @param isInnerClass boolean value which specify if generated class is|isn't inner
474 * @return string with class declaration in JAVA format
476 def protected generateClassDeclaration(boolean isInnerClass) '''
480 ELSEIF (type.abstract)»«
484 ENDIF»class «type.name»«
485 IF (genTO.superType !== null)»«
486 " extends "»«genTO.superType.importedName»«
488 «IF (!type.implements.empty)»«
490 FOR type : type.implements SEPARATOR ", "»«
497 * Template method which generates JAVA enum type.
499 * @return string with inner enum source code in JAVA format
501 def protected enumDeclarations() '''
503 «FOR e : enums SEPARATOR "\n"»
504 «new EnumTemplate(javaType.getEnclosedType(e.identifier), e).generateAsInnerClass»
509 def protected suidDeclaration() '''
510 «IF genTO.SUID !== null»
511 private static final long serialVersionUID = «genTO.SUID.value»L;
515 def protected annotationDeclaration() '''
516 «IF genTO.getAnnotations !== null»
517 «FOR e : genTO.getAnnotations»
524 * Template method which generates JAVA constants.
526 * @return string with constants in JAVA format
528 def protected constantsDeclarations() '''
531 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
532 «val cValue = c.value as Map<String, String>»
533 «val jurPatternRef = JUR_PATTERN.importedName»
534 public static final «JU_LIST.importedName»<String> «TypeConstants.PATTERN_CONSTANT_NAME» = «ImmutableList.importedName».of(«
535 FOR v : cValue.keySet SEPARATOR ", "»"«v.escapeJava»"«ENDFOR»);
536 «IF cValue.size == 1»
537 private static final «jurPatternRef» «Constants.MEMBER_PATTERN_LIST» = «jurPatternRef».compile(«TypeConstants.PATTERN_CONSTANT_NAME».get(0));
538 private static final String «Constants.MEMBER_REGEX_LIST» = "«cValue.values.iterator.next.escapeJava»";
540 private static final «jurPatternRef»[] «Constants.MEMBER_PATTERN_LIST» = «CODEHELPERS.importedName».compilePatterns(«TypeConstants.PATTERN_CONSTANT_NAME»);
541 private static final String[] «Constants.MEMBER_REGEX_LIST» = { «
542 FOR v : cValue.values SEPARATOR ", "»"«v.escapeJava»"«ENDFOR» };
552 * Template method which generates JAVA class attributes.
554 * @return string with the class attributes in JAVA format
556 def protected generateFields() '''
557 «IF !properties.empty»
559 private«IF isReadOnly(f)» final«ENDIF» «f.returnType.importedName» «f.fieldName»;
564 protected def isReadOnly(GeneratedProperty field) {
565 return field.readOnly
569 * Template method which generates the method <code>hashCode()</code>.
571 * @return string with the <code>hashCode()</code> method definition in JAVA format
573 def protected generateHashCode() {
574 val size = genTO.hashCodeIdentifiers.size
579 @«OVERRIDE.importedName»
580 public int hashCode() {
582 «hashCodeResult(genTO.hashCodeIdentifiers)»
585 return «CODEHELPERS.importedName».wrapperHashCode(«genTO.hashCodeIdentifiers.get(0).fieldName»);
592 * Template method which generates the method <code>equals()</code>.
594 * @return string with the <code>equals()</code> method definition in JAVA format
596 def private generateEquals() '''
597 «IF !genTO.equalsIdentifiers.empty»
598 @«OVERRIDE.importedName»
599 public final boolean equals(java.lang.Object obj) {
603 if (!(obj instanceof «type.name»)) {
606 final «type.name» other = («type.name») obj;
607 «FOR property : genTO.equalsIdentifiers»
608 «val fieldName = property.fieldName»
609 if (!«property.importedUtilClass».equals(«fieldName», other.«fieldName»)) {
618 def GeneratedProperty getPropByName(String name) {
619 for (GeneratedProperty prop : allProperties) {
620 if (prop.name.equals(name)) {
627 def private hasUintProperties() {
628 for (GeneratedProperty prop : allProperties) {
629 if (prop.isUintType) {
636 def private static isUintType(GeneratedProperty prop) {
637 UINT_TYPES.containsKey(prop.returnType)
640 def private static legacyType(GeneratedProperty prop) {
641 val type = prop.returnType
642 val uint = UINT_TYPES.get(type)