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)»
255 «allValuesConstructor»
258 «IF !allProperties.empty»
261 «IF properties.empty && !parentProperties.empty »
266 def private allValuesConstructor() '''
267 public «type.name»(«allProperties.asArgumentsDeclaration») {
268 «IF !parentProperties.empty»
269 super(«parentProperties.asArguments»);
271 «FOR p : allProperties»
272 «generateRestrictions(type, p.fieldName, p.returnType)»
276 «val fieldName = p.fieldName»
277 «IF p.returnType.name.endsWith("[]")»
278 this.«fieldName» = «fieldName» == null ? null : «fieldName».clone();
280 this.«fieldName» = «fieldName»;
286 def private typedefConstructor() '''
287 @«ConstructorParameters.importedName»("«TypeConstants.VALUE_PROP»")
288 @«ConstructorProperties.importedName»("«TypeConstants.VALUE_PROP»")
289 public «type.name»(«allProperties.asArgumentsDeclaration») {
290 «IF !parentProperties.empty»
291 super(«parentProperties.asArguments»);
293 «FOR p : allProperties»
294 «generateRestrictions(type, p.fieldName, p.returnType)»
297 * If we have patterns, we need to apply them to the value field. This is a sad consequence of how this code is
300 «CODEHELPERS.importedName».requireValue(_value);
301 «genPatternEnforcer("_value")»
304 «val fieldName = p.fieldName»
305 «IF p.returnType.name.endsWith("[]")»
306 this.«fieldName» = «fieldName».clone();
308 this.«fieldName» = «fieldName»;
314 def protected genUnionConstructor() '''
315 «FOR p : allProperties»
316 «val List<GeneratedProperty> other = new ArrayList(properties)»
318 «genConstructor(p, other)»
323 def protected genConstructor(GeneratedProperty property, Iterable<GeneratedProperty> other) '''
324 public «type.name»(«property.returnType.importedName + " " + property.name») {
325 «IF !parentProperties.empty»
326 super(«parentProperties.asArguments»);
329 «val fieldName = property.fieldName»
330 «generateRestrictions(type, fieldName, property.returnType)»
332 this.«fieldName» = «property.name»;
334 this.«p.fieldName» = null;
339 def private genPatternEnforcer(String ref) '''
341 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
342 «CODEHELPERS.importedName».checkPattern(«ref», «Constants.MEMBER_PATTERN_LIST», «Constants.MEMBER_REGEX_LIST»);
347 def private static paramValue(Type returnType, String paramName) {
348 if (returnType instanceof ConcreteType) {
351 return paramName + ".getValue()"
355 def private generateRestrictions(Type type, String paramName, Type returnType) '''
356 «val restrictions = type.restrictions»
357 «IF restrictions !== null»
358 «IF restrictions.lengthConstraint.present || restrictions.rangeConstraint.present»
359 if («paramName» != null) {
360 «IF restrictions.lengthConstraint.present»
361 «LengthGenerator.generateLengthCheckerCall(paramName, paramValue(returnType, paramName))»
363 «IF restrictions.rangeConstraint.present»
364 «rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))»
371 def protected copyConstructor() '''
373 * Creates a copy from Source Object.
375 * @param source Source object
377 public «type.name»(«type.name» source) {
378 «IF !parentProperties.empty»
382 «val fieldName = p.fieldName»
383 this.«fieldName» = source.«fieldName»;
388 def protected parentConstructor() '''
390 * Creates a new instance from «genTO.superType.importedName»
392 * @param source Source object
394 public «type.name»(«genTO.superType.importedName» source) {
396 «genPatternEnforcer("getValue()")»
400 def protected defaultInstance() '''
401 «IF genTO.typedef && !allProperties.empty && !genTO.unionType»
402 «val prop = allProperties.get(0)»
403 «val propType = prop.returnType»
404 «IF !(INSTANCE_IDENTIFIER.identifier.equals(propType.identifier))»
405 public static «genTO.name» getDefaultInstance(final String defaultValue) {
406 «IF allProperties.size > 1»
408 «ELSEIF VALUEOF_TYPES.contains(propType)»
409 return new «genTO.name»(«propType.importedName».valueOf(defaultValue));
410 «ELSEIF STRING_TYPE.equals(propType)»
411 return new «genTO.name»(defaultValue);
412 «ELSEIF BINARY_TYPE.equals(propType)»
413 return new «genTO.name»(«Base64.importedName».getDecoder().decode(defaultValue));
414 «ELSEIF EMPTY_TYPE.equals(propType)»
415 «Preconditions.importedName».checkArgument(defaultValue.isEmpty(), "Invalid value %s", defaultValue);
416 return new «genTO.name»(«Empty.importedName».getInstance());
418 return new «genTO.name»(new «propType.importedName»(defaultValue));
425 @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "FOR with SEPARATOR, not needing for value")
426 def protected bitsArgs() '''
427 «JU_LIST.importedName»<«STRING.importedName»> properties = «Lists.importedName».newArrayList(«allProperties.propsAsArgs»);
428 if (!properties.contains(defaultValue)) {
429 throw new «IllegalArgumentException.importedName»("invalid default parameter");
432 return new «genTO.name»(
433 «FOR prop : allProperties SEPARATOR ","»
434 properties.get(i++).equals(defaultValue) ? «BOOLEAN.importedName».TRUE : null
439 def protected propsAsArgs(Iterable<GeneratedProperty> properties) '''
440 «FOR prop : properties SEPARATOR ","»
446 * Template method which generates JAVA class declaration.
448 * @param isInnerClass boolean value which specify if generated class is|isn't inner
449 * @return string with class declaration in JAVA format
451 def protected generateClassDeclaration(boolean isInnerClass) '''
455 ELSEIF (type.abstract)»«
459 ENDIF»class «type.name»«
460 IF (genTO.superType !== null)»«
461 " extends "»«genTO.superType.importedName»«
463 «IF (!type.implements.empty)»«
465 FOR type : type.implements SEPARATOR ", "»«
472 * Template method which generates JAVA enum type.
474 * @return string with inner enum source code in JAVA format
476 def protected enumDeclarations() '''
478 «FOR e : enums SEPARATOR "\n"»
479 «new EnumTemplate(javaType.getEnclosedType(e.identifier), e).generateAsInnerClass»
484 def protected suidDeclaration() '''
485 «IF genTO.SUID !== null»
486 private static final long serialVersionUID = «genTO.SUID.value»L;
490 def protected annotationDeclaration() '''
491 «IF genTO.getAnnotations !== null»
492 «FOR e : genTO.getAnnotations»
499 * Template method which generates JAVA constants.
501 * @return string with constants in JAVA format
503 def protected constantsDeclarations() '''
506 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
507 «val cValue = c.value as Map<String, String>»
508 «val jurPatternRef = JUR_PATTERN.importedName»
509 public static final «JU_LIST.importedName»<String> «TypeConstants.PATTERN_CONSTANT_NAME» = «ImmutableList.importedName».of(«
510 FOR v : cValue.keySet SEPARATOR ", "»"«v.escapeJava»"«ENDFOR»);
511 «IF cValue.size == 1»
512 private static final «jurPatternRef» «Constants.MEMBER_PATTERN_LIST» = «jurPatternRef».compile(«TypeConstants.PATTERN_CONSTANT_NAME».get(0));
513 private static final String «Constants.MEMBER_REGEX_LIST» = "«cValue.values.iterator.next.escapeJava»";
515 private static final «jurPatternRef»[] «Constants.MEMBER_PATTERN_LIST» = «CODEHELPERS.importedName».compilePatterns(«TypeConstants.PATTERN_CONSTANT_NAME»);
516 private static final String[] «Constants.MEMBER_REGEX_LIST» = { «
517 FOR v : cValue.values SEPARATOR ", "»"«v.escapeJava»"«ENDFOR» };
527 * Template method which generates JAVA class attributes.
529 * @return string with the class attributes in JAVA format
531 def protected generateFields() '''
532 «IF !properties.empty»
534 private«IF isReadOnly(f)» final«ENDIF» «f.returnType.importedName» «f.fieldName»;
539 protected def isReadOnly(GeneratedProperty field) {
540 return field.readOnly
544 * Template method which generates the method <code>hashCode()</code>.
546 * @return string with the <code>hashCode()</code> method definition in JAVA format
548 def protected generateHashCode() {
549 val size = genTO.hashCodeIdentifiers.size
554 @«OVERRIDE.importedName»
555 public int hashCode() {
557 «hashCodeResult(genTO.hashCodeIdentifiers)»
560 return «CODEHELPERS.importedName».wrapperHashCode(«genTO.hashCodeIdentifiers.get(0).fieldName»);
567 * Template method which generates the method <code>equals()</code>.
569 * @return string with the <code>equals()</code> method definition in JAVA format
571 def private generateEquals() '''
572 «IF !genTO.equalsIdentifiers.empty»
573 @«OVERRIDE.importedName»
574 public final boolean equals(java.lang.Object obj) {
578 if (!(obj instanceof «type.name»)) {
581 final «type.name» other = («type.name») obj;
582 «FOR property : genTO.equalsIdentifiers»
583 «val fieldName = property.fieldName»
584 if (!«property.importedUtilClass».equals(«fieldName», other.«fieldName»)) {
593 def GeneratedProperty getPropByName(String name) {
594 for (GeneratedProperty prop : allProperties) {
595 if (prop.name.equals(name)) {