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.MoreObjects
30 import com.google.common.base.Preconditions
31 import com.google.common.collect.ImmutableList
32 import com.google.common.collect.Lists
33 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
34 import java.beans.ConstructorProperties
35 import java.util.ArrayList
36 import java.util.Base64;
37 import java.util.Collection
38 import java.util.Comparator
42 import javax.management.ConstructorParameters
43 import org.gaul.modernizer_maven_annotations.SuppressModernizer
44 import org.opendaylight.mdsal.binding.model.api.ConcreteType
45 import org.opendaylight.mdsal.binding.model.api.Constant
46 import org.opendaylight.mdsal.binding.model.api.Enumeration
47 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
48 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
49 import org.opendaylight.mdsal.binding.model.api.Restrictions
50 import org.opendaylight.mdsal.binding.model.api.Type
51 import org.opendaylight.mdsal.binding.model.util.TypeConstants
52 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping
53 import org.opendaylight.yangtools.yang.common.Empty
54 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
57 * Template for generating JAVA class.
60 class ClassTemplate extends BaseTemplate {
61 static val Comparator<GeneratedProperty> PROP_COMPARATOR = Comparator.comparing([prop | prop.name])
62 static val VALUEOF_TYPES = Set.of(
73 protected val List<GeneratedProperty> properties
74 protected val List<GeneratedProperty> finalProperties
75 protected val List<GeneratedProperty> parentProperties
76 protected val List<GeneratedProperty> allProperties
77 protected val Restrictions restrictions
80 * List of enumeration which are generated as JAVA enum type.
82 protected val List<Enumeration> enums
85 * List of constant instances which are generated as JAVA public static final attributes.
87 protected val List<Constant> consts
89 protected val GeneratedTransferObject genTO
91 val AbstractRangeGenerator<?> rangeGenerator
94 * Creates instance of this class with concrete <code>genType</code>.
96 * @param genType generated transfer object which will be transformed to JAVA class source code
98 new(GeneratedTransferObject genType) {
99 this(new TopLevelJavaGeneratedType(genType), genType)
103 * Creates instance of this class with concrete <code>genType</code>.
105 * @param genType generated transfer object which will be transformed to JAVA class source code
107 new(AbstractJavaGeneratedType javaType, GeneratedTransferObject genType) {
108 super(javaType, genType)
110 this.properties = genType.properties
111 this.finalProperties = GeneratorUtil.resolveReadOnlyPropertiesFromTO(genTO.properties)
112 this.parentProperties = GeneratorUtil.getPropertiesOfAllParents(genTO)
113 this.restrictions = genType.restrictions
115 val sorted = new ArrayList();
116 sorted.addAll(properties);
117 sorted.addAll(parentProperties);
118 sorted.sort(PROP_COMPARATOR);
120 this.allProperties = sorted
121 this.enums = genType.enumerations
122 this.consts = genType.constantDefinitions
124 if (restrictions !== null && restrictions.rangeConstraint.present) {
125 rangeGenerator = requireNonNull(AbstractRangeGenerator.forType(TypeUtils.encapsulatedValueType(genType)))
127 rangeGenerator = null
132 * Generates JAVA class source code (class body only).
134 * @return string with JAVA class body source code
136 def CharSequence generateAsInnerClass() {
137 return generateBody(true)
140 override protected body() {
145 * Template method which generates class body.
147 * @param isInnerClass boolean value which specify if generated class is|isn't inner
148 * @return string with class source code in JAVA format
150 def protected generateBody(boolean isInnerClass) '''
151 «type.formatDataForJavaDoc.wrapToDocumentation»
152 «annotationDeclaration»
154 «generatedAnnotation»
156 «generateClassDeclaration(isInnerClass)» {
158 «innerClassesDeclarations»
160 «constantsDeclarations»
163 «IF restrictions !== null»
164 «IF restrictions.lengthConstraint.present»
165 «LengthGenerator.generateLengthChecker("_value", TypeUtils.encapsulatedValueType(genTO),
166 restrictions.lengthConstraint.get, this)»
168 «IF restrictions.rangeConstraint.present»
169 «rangeGenerator.generateRangeChecker("_value", restrictions.rangeConstraint.get, this)»
179 «IF (genTO.isTypedef() && genTO.getBaseType instanceof BitsTypeDefinition)»
180 «generateGetValueForBitsTypeDef»
187 «generateToString(genTO.toStringIdentifiers)»
192 def private propertyMethods() {
193 if (properties.empty) {
196 isScalarTypeObject ? scalarTypeObjectValue(properties.get(0)) : defaultProperties
199 def private isScalarTypeObject() {
200 for (impl : genTO.implements) {
201 if (SCALAR_TYPE_OBJECT.identifier.equals(impl.identifier)) {
208 def private defaultProperties() '''
209 «FOR field : properties SEPARATOR "\n"»
217 def private scalarTypeObjectValue(GeneratedProperty field) '''
218 @«OVERRIDE.importedName»
219 public «field.returnType.importedName» «BindingMapping.SCALAR_TYPE_OBJECT_GET_VALUE_NAME»() {
220 return «field.fieldName»«field.cloneCall»;
225 * Template method which generates the method <code>getValue()</code> for typedef,
226 * which base type is BitsDefinition.
228 * @return string with the <code>getValue()</code> method definition in JAVA format
230 def protected generateGetValueForBitsTypeDef() '''
232 public boolean[] getValue() {
233 return new boolean[]{
234 «FOR property: genTO.properties SEPARATOR ','»
242 * Template method which generates inner classes inside this interface.
244 * @return string with the source code for inner classes in JAVA format
246 def protected innerClassesDeclarations() '''
247 «IF !type.enclosedTypes.empty»
248 «FOR innerClass : type.enclosedTypes SEPARATOR "\n"»
249 «generateInnerClass(innerClass)»
254 def protected constructors() '''
256 «genUnionConstructor»
257 «ELSEIF genTO.typedef && allProperties.size == 1 && allProperties.get(0).name.equals(TypeConstants.VALUE_PROP)»
261 «allValuesConstructor»
265 «IF !allProperties.empty»
268 «IF properties.empty && !parentProperties.empty »
273 def allValuesConstructor() '''
274 public «type.name»(«allProperties.asArgumentsDeclaration») {
275 «IF !parentProperties.empty»
276 super(«parentProperties.asArguments»);
278 «FOR p : allProperties»
279 «generateRestrictions(type, p.fieldName, p.returnType)»
283 «val fieldName = p.fieldName»
284 «IF p.returnType.name.endsWith("[]")»
285 this.«fieldName» = «fieldName» == null ? null : «fieldName».clone();
287 this.«fieldName» = «fieldName»;
293 def private typedefConstructor() '''
294 @«ConstructorParameters.importedName»("«TypeConstants.VALUE_PROP»")
295 @«ConstructorProperties.importedName»("«TypeConstants.VALUE_PROP»")
296 public «type.name»(«allProperties.asArgumentsDeclaration») {
297 «IF !parentProperties.empty»
298 super(«parentProperties.asArguments»);
300 «FOR p : allProperties»
301 «generateRestrictions(type, p.fieldName, p.returnType)»
304 * If we have patterns, we need to apply them to the value field. This is a sad consequence of how this code is
307 «CODEHELPERS.importedName».requireValue(_value);
308 «genPatternEnforcer("_value")»
311 «val fieldName = p.fieldName»
312 this.«fieldName» = «fieldName»«p.cloneCall»;
317 def private legacyConstructor() {
318 if (!hasUintProperties) {
322 val compatUint = CODEHELPERS.importedName + ".compatUint("
326 * Utility migration constructor.
328 «FOR prop : allProperties»
329 * @param «prop.fieldName» «prop.name»«IF prop.isUintType» in legacy Java type«ENDIF»
331 * @deprecated Use {@link #«type.name»(«FOR prop : allProperties SEPARATOR ", "»«prop.returnType.importedJavadocName»«ENDFOR»)} instead.
333 @Deprecated(forRemoval = true)
334 public «type.getName»(«FOR prop : allProperties SEPARATOR ", "»«prop.legacyType.importedName» «prop.fieldName»«ENDFOR») {
335 this(«FOR prop : allProperties SEPARATOR ", "»«IF prop.isUintType»«compatUint»«prop.fieldName»)«ELSE»«prop.fieldName»«ENDIF»«ENDFOR»);
340 def protected genUnionConstructor() '''
341 «FOR p : allProperties»
342 «val List<GeneratedProperty> other = new ArrayList(properties)»
344 «genConstructor(p, other)»
349 def protected genConstructor(GeneratedProperty property, Iterable<GeneratedProperty> other) '''
350 public «type.name»(«property.returnType.importedName + " " + property.name») {
351 «IF !parentProperties.empty»
352 super(«parentProperties.asArguments»);
355 «val fieldName = property.fieldName»
356 «generateRestrictions(type, fieldName, property.returnType)»
358 this.«fieldName» = «property.name»;
360 this.«p.fieldName» = null;
365 def private genPatternEnforcer(String ref) '''
367 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
368 «CODEHELPERS.importedName».checkPattern(«ref», «Constants.MEMBER_PATTERN_LIST», «Constants.MEMBER_REGEX_LIST»);
373 def private static paramValue(Type returnType, String paramName) {
374 if (returnType instanceof ConcreteType) {
377 return paramName + ".getValue()"
381 def generateRestrictions(Type type, String paramName, Type returnType) '''
382 «val restrictions = type.restrictions»
383 «IF restrictions !== null»
384 «IF restrictions.lengthConstraint.present || restrictions.rangeConstraint.present»
385 if («paramName» != null) {
386 «IF restrictions.lengthConstraint.present»
387 «LengthGenerator.generateLengthCheckerCall(paramName, paramValue(returnType, paramName))»
389 «IF restrictions.rangeConstraint.present»
390 «rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))»
397 def protected copyConstructor() '''
399 * Creates a copy from Source Object.
401 * @param source Source object
403 public «type.name»(«type.name» source) {
404 «IF !parentProperties.empty»
408 «val fieldName = p.fieldName»
409 this.«fieldName» = source.«fieldName»;
414 def protected parentConstructor() '''
416 * Creates a new instance from «genTO.superType.importedName»
418 * @param source Source object
420 public «type.name»(«genTO.superType.importedName» source) {
422 «genPatternEnforcer("getValue()")»
426 def protected defaultInstance() '''
427 «IF genTO.typedef && !allProperties.empty && !genTO.unionType»
428 «val prop = allProperties.get(0)»
429 «val propType = prop.returnType»
430 «IF !(INSTANCE_IDENTIFIER.identifier.equals(propType.identifier))»
431 public static «genTO.name» getDefaultInstance(final String defaultValue) {
432 «IF allProperties.size > 1»
434 «ELSEIF VALUEOF_TYPES.contains(propType)»
435 return new «genTO.name»(«propType.importedName».valueOf(defaultValue));
436 «ELSEIF STRING_TYPE.equals(propType)»
437 return new «genTO.name»(defaultValue);
438 «ELSEIF BINARY_TYPE.equals(propType)»
439 return new «genTO.name»(«Base64.importedName».getDecoder().decode(defaultValue));
440 «ELSEIF EMPTY_TYPE.equals(propType)»
441 «Preconditions.importedName».checkArgument(defaultValue.isEmpty(), "Invalid value %s", defaultValue);
442 return new «genTO.name»(«Empty.importedName».getInstance());
444 return new «genTO.name»(new «propType.importedName»(defaultValue));
451 @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "FOR with SEPARATOR, not needing for value")
452 def protected bitsArgs() '''
453 «JU_LIST.importedName»<«STRING.importedName»> properties = «Lists.importedName».newArrayList(«allProperties.propsAsArgs»);
454 if (!properties.contains(defaultValue)) {
455 throw new «IllegalArgumentException.importedName»("invalid default parameter");
458 return new «genTO.name»(
459 «FOR prop : allProperties SEPARATOR ","»
460 properties.get(i++).equals(defaultValue) ? «BOOLEAN.importedName».TRUE : null
465 def protected propsAsArgs(Iterable<GeneratedProperty> properties) '''
466 «FOR prop : properties SEPARATOR ","»
472 * Template method which generates JAVA class declaration.
474 * @param isInnerClass boolean value which specify if generated class is|isn't inner
475 * @return string with class declaration in JAVA format
477 def protected generateClassDeclaration(boolean isInnerClass) '''
481 ELSEIF (type.abstract)»«
485 ENDIF»class «type.name»«
486 IF (genTO.superType !== null)»«
487 " extends "»«genTO.superType.importedName»«
489 «IF (!type.implements.empty)»«
491 FOR type : type.implements SEPARATOR ", "»«
498 * Template method which generates JAVA enum type.
500 * @return string with inner enum source code in JAVA format
502 def protected enumDeclarations() '''
504 «FOR e : enums SEPARATOR "\n"»
505 «new EnumTemplate(javaType.getEnclosedType(e.identifier), e).generateAsInnerClass»
510 def protected suidDeclaration() '''
511 «IF genTO.SUID !== null»
512 private static final long serialVersionUID = «genTO.SUID.value»L;
516 def protected annotationDeclaration() '''
517 «IF genTO.getAnnotations !== null»
518 «FOR e : genTO.getAnnotations»
525 * Template method which generates JAVA constants.
527 * @return string with constants in JAVA format
529 def protected constantsDeclarations() '''
532 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
533 «val cValue = c.value as Map<String, String>»
534 «val jurPatternRef = JUR_PATTERN.importedName»
535 public static final «JU_LIST.importedName»<String> «TypeConstants.PATTERN_CONSTANT_NAME» = «ImmutableList.importedName».of(«
536 FOR v : cValue.keySet SEPARATOR ", "»"«v.escapeJava»"«ENDFOR»);
537 «IF cValue.size == 1»
538 private static final «jurPatternRef» «Constants.MEMBER_PATTERN_LIST» = «jurPatternRef».compile(«TypeConstants.PATTERN_CONSTANT_NAME».get(0));
539 private static final String «Constants.MEMBER_REGEX_LIST» = "«cValue.values.iterator.next.escapeJava»";
541 private static final «jurPatternRef»[] «Constants.MEMBER_PATTERN_LIST» = «CODEHELPERS.importedName».compilePatterns(«TypeConstants.PATTERN_CONSTANT_NAME»);
542 private static final String[] «Constants.MEMBER_REGEX_LIST» = { «
543 FOR v : cValue.values SEPARATOR ", "»"«v.escapeJava»"«ENDFOR» };
553 * Template method which generates JAVA class attributes.
555 * @return string with the class attributes in JAVA format
557 def protected generateFields() '''
558 «IF !properties.empty»
560 private«IF isReadOnly(f)» final«ENDIF» «f.returnType.importedName» «f.fieldName»;
565 protected def isReadOnly(GeneratedProperty field) {
566 return field.readOnly
570 * Template method which generates the method <code>hashCode()</code>.
572 * @return string with the <code>hashCode()</code> method definition in JAVA format
574 def protected generateHashCode() {
575 val size = genTO.hashCodeIdentifiers.size
580 @«OVERRIDE.importedName»
581 public int hashCode() {
583 final int prime = 31;
585 «FOR property : genTO.hashCodeIdentifiers»
586 result = prime * result + «property.importedUtilClass».hashCode(«property.fieldName»);
590 return «CODEHELPERS.importedName».wrapperHashCode(«genTO.hashCodeIdentifiers.get(0).fieldName»);
597 * Template method which generates the method <code>equals()</code>.
599 * @return string with the <code>equals()</code> method definition in JAVA format
601 def private generateEquals() '''
602 «IF !genTO.equalsIdentifiers.empty»
603 @«OVERRIDE.importedName»
604 public final boolean equals(java.lang.Object obj) {
608 if (!(obj instanceof «type.name»)) {
611 final «type.name» other = («type.name») obj;
612 «FOR property : genTO.equalsIdentifiers»
613 «val fieldName = property.fieldName»
614 if (!«property.importedUtilClass».equals(«fieldName», other.«fieldName»)) {
623 def private generateToString(Collection<? extends GeneratedProperty> properties) '''
624 «IF !properties.empty»
625 @«OVERRIDE.importedName»
626 public «STRING.importedName» toString() {
627 final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper(«type.importedName».class);
628 «FOR property : properties»
629 «CODEHELPERS.importedName».appendValue(helper, "«property.fieldName»", «property.fieldName»);
631 return helper.toString();
636 def GeneratedProperty getPropByName(String name) {
637 for (GeneratedProperty prop : allProperties) {
638 if (prop.name.equals(name)) {
645 def private hasUintProperties() {
646 for (GeneratedProperty prop : allProperties) {
647 if (prop.isUintType) {
654 def private static isUintType(GeneratedProperty prop) {
655 UINT_TYPES.containsKey(prop.returnType)
658 def private static legacyType(GeneratedProperty prop) {
659 val type = prop.returnType
660 val uint = UINT_TYPES.get(type)