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.ri.BaseYangTypes.BINARY_TYPE
12 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.BOOLEAN_TYPE
13 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.DECIMAL64_TYPE
14 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.EMPTY_TYPE
15 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.INSTANCE_IDENTIFIER
16 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.INT16_TYPE
17 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.INT32_TYPE
18 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.INT64_TYPE
19 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.INT8_TYPE
20 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.STRING_TYPE
21 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.UINT16_TYPE
22 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.UINT32_TYPE
23 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.UINT64_TYPE
24 import static org.opendaylight.mdsal.binding.model.ri.BaseYangTypes.UINT8_TYPE
25 import static org.opendaylight.mdsal.binding.model.ri.BindingTypes.SCALAR_TYPE_OBJECT
26 import static org.opendaylight.mdsal.binding.model.ri.Types.BOOLEAN
27 import static org.opendaylight.mdsal.binding.model.ri.Types.STRING;
28 import static extension org.apache.commons.text.StringEscapeUtils.escapeJava
30 import com.google.common.base.MoreObjects
31 import com.google.common.base.Preconditions
32 import com.google.common.collect.ImmutableList
33 import com.google.common.collect.Lists
34 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
35 import java.beans.ConstructorProperties
36 import java.util.ArrayList
37 import java.util.Base64;
38 import java.util.Collection
39 import java.util.Comparator
43 import javax.management.ConstructorParameters
44 import org.gaul.modernizer_maven_annotations.SuppressModernizer
45 import org.opendaylight.mdsal.binding.model.api.ConcreteType
46 import org.opendaylight.mdsal.binding.model.api.Constant
47 import org.opendaylight.mdsal.binding.model.api.Enumeration
48 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
49 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
50 import org.opendaylight.mdsal.binding.model.api.Restrictions
51 import org.opendaylight.mdsal.binding.model.api.Type
52 import org.opendaylight.mdsal.binding.model.ri.TypeConstants
53 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping
54 import org.opendaylight.yangtools.yang.common.Empty
55 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
58 * Template for generating JAVA class.
61 class ClassTemplate extends BaseTemplate {
62 static val Comparator<GeneratedProperty> PROP_COMPARATOR = Comparator.comparing([prop | prop.name])
63 static val VALUEOF_TYPES = Set.of(
75 protected val List<GeneratedProperty> properties
76 protected val List<GeneratedProperty> finalProperties
77 protected val List<GeneratedProperty> parentProperties
78 protected val List<GeneratedProperty> allProperties
79 protected val Restrictions restrictions
82 * List of enumeration which are generated as JAVA enum type.
84 protected val List<Enumeration> enums
87 * List of constant instances which are generated as JAVA public static final attributes.
89 protected val List<Constant> consts
91 protected val GeneratedTransferObject genTO
93 val AbstractRangeGenerator<?> rangeGenerator
96 * Creates instance of this class with concrete <code>genType</code>.
98 * @param genType generated transfer object which will be transformed to JAVA class source code
100 new(GeneratedTransferObject genType) {
101 this(new TopLevelJavaGeneratedType(genType), genType)
105 * Creates instance of this class with concrete <code>genType</code>.
107 * @param genType generated transfer object which will be transformed to JAVA class source code
109 new(AbstractJavaGeneratedType javaType, GeneratedTransferObject genType) {
110 super(javaType, genType)
112 this.properties = genType.properties
113 this.finalProperties = GeneratorUtil.resolveReadOnlyPropertiesFromTO(genTO.properties)
114 this.parentProperties = GeneratorUtil.getPropertiesOfAllParents(genTO)
115 this.restrictions = genType.restrictions
117 val sorted = new ArrayList();
118 sorted.addAll(properties);
119 sorted.addAll(parentProperties);
120 sorted.sort(PROP_COMPARATOR);
122 this.allProperties = sorted
123 this.enums = genType.enumerations
124 this.consts = genType.constantDefinitions
126 if (restrictions !== null && restrictions.rangeConstraint.present) {
127 rangeGenerator = requireNonNull(AbstractRangeGenerator.forType(TypeUtils.encapsulatedValueType(genType)))
129 rangeGenerator = null
134 * Generates JAVA class source code (class body only).
136 * @return string with JAVA class body source code
138 def CharSequence generateAsInnerClass() {
139 return generateBody(true)
142 override protected body() {
147 * Template method which generates class body.
149 * @param isInnerClass boolean value which specify if generated class is|isn't inner
150 * @return string with class source code in JAVA format
152 def protected generateBody(boolean isInnerClass) '''
153 «type.formatDataForJavaDoc.wrapToDocumentation»
154 «annotationDeclaration»
156 «generatedAnnotation»
158 «generateClassDeclaration(isInnerClass)» {
160 «innerClassesDeclarations»
162 «constantsDeclarations»
165 «IF restrictions !== null»
166 «IF restrictions.lengthConstraint.present»
167 «LengthGenerator.generateLengthChecker("_value", TypeUtils.encapsulatedValueType(genTO),
168 restrictions.lengthConstraint.get, this)»
170 «IF restrictions.rangeConstraint.present»
171 «rangeGenerator.generateRangeChecker("_value", restrictions.rangeConstraint.get, this)»
181 «IF (genTO.isTypedef() && genTO.getBaseType instanceof BitsTypeDefinition)»
182 «generateGetValueForBitsTypeDef»
189 «generateToString(genTO.toStringIdentifiers)»
194 def private propertyMethods() {
195 if (properties.empty) {
198 isScalarTypeObject ? scalarTypeObjectValue(properties.get(0)) : defaultProperties
201 def private isScalarTypeObject() {
202 for (impl : genTO.implements) {
203 if (SCALAR_TYPE_OBJECT.identifier.equals(impl.identifier)) {
210 def private defaultProperties() '''
211 «FOR field : properties SEPARATOR "\n"»
219 def private scalarTypeObjectValue(GeneratedProperty field) '''
220 @«OVERRIDE.importedName»
221 public «field.returnType.importedName» «BindingMapping.SCALAR_TYPE_OBJECT_GET_VALUE_NAME»() {
222 return «field.fieldName»«field.cloneCall»;
227 * Template method which generates the method <code>getValue()</code> for typedef,
228 * which base type is BitsDefinition.
230 * @return string with the <code>getValue()</code> method definition in JAVA format
232 def protected generateGetValueForBitsTypeDef() '''
234 public boolean[] getValue() {
235 return new boolean[]{
236 «FOR property: genTO.properties SEPARATOR ','»
244 * Template method which generates inner classes inside this interface.
246 * @return string with the source code for inner classes in JAVA format
248 def protected innerClassesDeclarations() '''
249 «IF !type.enclosedTypes.empty»
250 «FOR innerClass : type.enclosedTypes SEPARATOR "\n"»
251 «generateInnerClass(innerClass)»
256 def protected constructors() '''
258 «genUnionConstructor»
259 «ELSEIF genTO.typedef && allProperties.size == 1 && allProperties.get(0).name.equals(TypeConstants.VALUE_PROP)»
262 «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 protected genUnionConstructor() '''
318 «FOR p : allProperties»
319 «val List<GeneratedProperty> other = new ArrayList(properties)»
321 «genConstructor(p, other)»
326 def protected genConstructor(GeneratedProperty property, Iterable<GeneratedProperty> other) '''
327 public «type.name»(«property.returnType.importedName + " " + property.name») {
328 «IF !parentProperties.empty»
329 super(«parentProperties.asArguments»);
332 «val fieldName = property.fieldName»
333 «generateRestrictions(type, fieldName, property.returnType)»
335 this.«fieldName» = «property.name»;
337 this.«p.fieldName» = null;
342 def private genPatternEnforcer(String ref) '''
344 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
345 «CODEHELPERS.importedName».checkPattern(«ref», «Constants.MEMBER_PATTERN_LIST», «Constants.MEMBER_REGEX_LIST»);
350 def private static paramValue(Type returnType, String paramName) {
351 if (returnType instanceof ConcreteType) {
354 return paramName + ".getValue()"
358 def generateRestrictions(Type type, String paramName, Type returnType) '''
359 «val restrictions = type.restrictions»
360 «IF restrictions !== null»
361 «IF restrictions.lengthConstraint.present || restrictions.rangeConstraint.present»
362 if («paramName» != null) {
363 «IF restrictions.lengthConstraint.present»
364 «LengthGenerator.generateLengthCheckerCall(paramName, paramValue(returnType, paramName))»
366 «IF restrictions.rangeConstraint.present»
367 «rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))»
374 def protected copyConstructor() '''
376 * Creates a copy from Source Object.
378 * @param source Source object
380 public «type.name»(«type.name» source) {
381 «IF !parentProperties.empty»
385 «val fieldName = p.fieldName»
386 this.«fieldName» = source.«fieldName»;
391 def protected parentConstructor() '''
393 * Creates a new instance from «genTO.superType.importedName»
395 * @param source Source object
397 public «type.name»(«genTO.superType.importedName» source) {
399 «genPatternEnforcer("getValue()")»
403 def protected defaultInstance() '''
404 «IF genTO.typedef && !allProperties.empty && !genTO.unionType»
405 «val prop = allProperties.get(0)»
406 «val propType = prop.returnType»
407 «IF !(INSTANCE_IDENTIFIER.identifier.equals(propType.identifier))»
408 public static «genTO.name» getDefaultInstance(final String defaultValue) {
409 «IF allProperties.size > 1»
411 «ELSEIF VALUEOF_TYPES.contains(propType)»
412 return new «genTO.name»(«propType.importedName».valueOf(defaultValue));
413 «ELSEIF STRING_TYPE.equals(propType)»
414 return new «genTO.name»(defaultValue);
415 «ELSEIF BINARY_TYPE.equals(propType)»
416 return new «genTO.name»(«Base64.importedName».getDecoder().decode(defaultValue));
417 «ELSEIF EMPTY_TYPE.equals(propType)»
418 «Preconditions.importedName».checkArgument(defaultValue.isEmpty(), "Invalid value %s", defaultValue);
419 return new «genTO.name»(«Empty.importedName».value());
421 return new «genTO.name»(new «propType.importedName»(defaultValue));
428 @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "FOR with SEPARATOR, not needing for value")
429 def protected bitsArgs() '''
430 «JU_LIST.importedName»<«STRING.importedName»> properties = «Lists.importedName».newArrayList(«allProperties.propsAsArgs»);
431 if (!properties.contains(defaultValue)) {
432 throw new «IllegalArgumentException.importedName»("invalid default parameter");
435 return new «genTO.name»(
436 «FOR prop : allProperties SEPARATOR ","»
437 properties.get(i++).equals(defaultValue) ? «BOOLEAN.importedName».TRUE : null
442 def protected propsAsArgs(Iterable<GeneratedProperty> properties) '''
443 «FOR prop : properties SEPARATOR ","»
449 * Template method which generates JAVA class declaration.
451 * @param isInnerClass boolean value which specify if generated class is|isn't inner
452 * @return string with class declaration in JAVA format
454 def protected generateClassDeclaration(boolean isInnerClass) '''
458 ELSEIF (type.abstract)»«
462 ENDIF»class «type.name»«
463 IF (genTO.superType !== null)»«
464 " extends "»«genTO.superType.importedName»«
466 «IF (!type.implements.empty)»«
468 FOR type : type.implements SEPARATOR ", "»«
475 * Template method which generates JAVA enum type.
477 * @return string with inner enum source code in JAVA format
479 def protected enumDeclarations() '''
481 «FOR e : enums SEPARATOR "\n"»
482 «new EnumTemplate(javaType.getEnclosedType(e.identifier), e).generateAsInnerClass»
487 def protected suidDeclaration() '''
488 «IF genTO.SUID !== null»
489 private static final long serialVersionUID = «genTO.SUID.value»L;
493 def protected annotationDeclaration() '''
494 «IF genTO.getAnnotations !== null»
495 «FOR e : genTO.getAnnotations»
502 * Template method which generates JAVA constants.
504 * @return string with constants in JAVA format
506 def protected constantsDeclarations() '''
509 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
510 «val cValue = c.value as Map<String, String>»
511 «val jurPatternRef = JUR_PATTERN.importedName»
512 public static final «JU_LIST.importedName»<String> «TypeConstants.PATTERN_CONSTANT_NAME» = «ImmutableList.importedName».of(«
513 FOR v : cValue.keySet SEPARATOR ", "»"«v.escapeJava»"«ENDFOR»);
514 «IF cValue.size == 1»
515 private static final «jurPatternRef» «Constants.MEMBER_PATTERN_LIST» = «jurPatternRef».compile(«TypeConstants.PATTERN_CONSTANT_NAME».get(0));
516 private static final String «Constants.MEMBER_REGEX_LIST» = "«cValue.values.iterator.next.escapeJava»";
518 private static final «jurPatternRef»[] «Constants.MEMBER_PATTERN_LIST» = «CODEHELPERS.importedName».compilePatterns(«TypeConstants.PATTERN_CONSTANT_NAME»);
519 private static final String[] «Constants.MEMBER_REGEX_LIST» = { «
520 FOR v : cValue.values SEPARATOR ", "»"«v.escapeJava»"«ENDFOR» };
530 * Template method which generates JAVA class attributes.
532 * @return string with the class attributes in JAVA format
534 def protected generateFields() '''
535 «IF !properties.empty»
537 private«IF isReadOnly(f)» final«ENDIF» «f.returnType.importedName» «f.fieldName»;
542 protected def isReadOnly(GeneratedProperty field) {
543 return field.readOnly
547 * Template method which generates the method <code>hashCode()</code>.
549 * @return string with the <code>hashCode()</code> method definition in JAVA format
551 def protected generateHashCode() {
552 val size = genTO.hashCodeIdentifiers.size
557 @«OVERRIDE.importedName»
558 public int hashCode() {
560 final int prime = 31;
562 «FOR property : genTO.hashCodeIdentifiers»
563 result = prime * result + «property.importedUtilClass».hashCode(«property.fieldName»);
567 return «CODEHELPERS.importedName».wrapperHashCode(«genTO.hashCodeIdentifiers.get(0).fieldName»);
574 * Template method which generates the method <code>equals()</code>.
576 * @return string with the <code>equals()</code> method definition in JAVA format
578 def private generateEquals() '''
579 «IF !genTO.equalsIdentifiers.empty»
580 @«OVERRIDE.importedName»
581 public final boolean equals(java.lang.Object obj) {
585 if (!(obj instanceof «type.name»)) {
588 final «type.name» other = («type.name») obj;
589 «FOR property : genTO.equalsIdentifiers»
590 «val fieldName = property.fieldName»
591 if (!«property.importedUtilClass».equals(«fieldName», other.«fieldName»)) {
600 def private generateToString(Collection<? extends GeneratedProperty> properties) '''
601 «IF !properties.empty»
602 @«OVERRIDE.importedName»
603 public «STRING.importedName» toString() {
604 final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper(«type.importedName».class);
605 «FOR property : properties»
606 «CODEHELPERS.importedName».appendValue(helper, "«property.fieldName»", «property.fieldName»);
608 return helper.toString();
613 def GeneratedProperty getPropByName(String name) {
614 for (GeneratedProperty prop : allProperties) {
615 if (prop.name.equals(name)) {