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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings
20 import java.beans.ConstructorProperties
21 import java.util.ArrayList
22 import java.util.Base64;
23 import java.util.Comparator
26 import javax.management.ConstructorParameters
27 import org.gaul.modernizer_maven_annotations.SuppressModernizer
28 import org.opendaylight.mdsal.binding.model.api.ConcreteType
29 import org.opendaylight.mdsal.binding.model.api.Constant
30 import org.opendaylight.mdsal.binding.model.api.Enumeration
31 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
32 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
33 import org.opendaylight.mdsal.binding.model.api.Restrictions
34 import org.opendaylight.mdsal.binding.model.api.Type
35 import org.opendaylight.mdsal.binding.model.util.TypeConstants
36 import org.opendaylight.yangtools.yang.common.Empty
37 import org.opendaylight.yangtools.yang.common.Uint16
38 import org.opendaylight.yangtools.yang.common.Uint32
39 import org.opendaylight.yangtools.yang.common.Uint64
40 import org.opendaylight.yangtools.yang.common.Uint8
41 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
44 * Template for generating JAVA class.
47 class ClassTemplate extends BaseTemplate {
48 static val Comparator<GeneratedProperty> PROP_COMPARATOR = Comparator.comparing([prop | prop.name])
50 protected val List<GeneratedProperty> properties
51 protected val List<GeneratedProperty> finalProperties
52 protected val List<GeneratedProperty> parentProperties
53 protected val List<GeneratedProperty> allProperties
54 protected val Restrictions restrictions
57 * List of enumeration which are generated as JAVA enum type.
59 protected val List<Enumeration> enums
62 * List of constant instances which are generated as JAVA public static final attributes.
64 protected val List<Constant> consts
66 protected val GeneratedTransferObject genTO
68 val AbstractRangeGenerator<?> rangeGenerator
71 * Creates instance of this class with concrete <code>genType</code>.
73 * @param genType generated transfer object which will be transformed to JAVA class source code
75 new(GeneratedTransferObject genType) {
76 this(new TopLevelJavaGeneratedType(genType), genType)
80 * Creates instance of this class with concrete <code>genType</code>.
82 * @param genType generated transfer object which will be transformed to JAVA class source code
84 new(AbstractJavaGeneratedType javaType, GeneratedTransferObject genType) {
85 super(javaType, genType)
87 this.properties = genType.properties
88 this.finalProperties = GeneratorUtil.resolveReadOnlyPropertiesFromTO(genTO.properties)
89 this.parentProperties = GeneratorUtil.getPropertiesOfAllParents(genTO)
90 this.restrictions = genType.restrictions
92 val sorted = new ArrayList();
93 sorted.addAll(properties);
94 sorted.addAll(parentProperties);
95 sorted.sort(PROP_COMPARATOR);
97 this.allProperties = sorted
98 this.enums = genType.enumerations
99 this.consts = genType.constantDefinitions
101 if (restrictions !== null && restrictions.rangeConstraint.present) {
102 rangeGenerator = requireNonNull(AbstractRangeGenerator.forType(TypeUtils.encapsulatedValueType(genType)))
104 rangeGenerator = null
109 * Generates JAVA class source code (class body only).
111 * @return string with JAVA class body source code
113 def CharSequence generateAsInnerClass() {
114 return generateBody(true)
117 override protected body() {
122 * Template method which generates class body.
124 * @param isInnerClass boolean value which specify if generated class is|isn't inner
125 * @return string with class source code in JAVA format
127 def protected generateBody(boolean isInnerClass) '''
128 «wrapToDocumentation(formatDataForJavaDoc(type))»
129 «annotationDeclaration»
130 «generateClassDeclaration(isInnerClass)» {
132 «innerClassesDeclarations»
134 «constantsDeclarations»
137 «IF restrictions !== null»
138 «IF restrictions.lengthConstraint.present»
139 «LengthGenerator.generateLengthChecker("_value", TypeUtils.encapsulatedValueType(genTO),
140 restrictions.lengthConstraint.get, this)»
142 «IF restrictions.rangeConstraint.present»
143 «rangeGenerator.generateRangeChecker("_value", restrictions.rangeConstraint.get, this)»
151 «FOR field : properties SEPARATOR "\n"»
158 «IF (genTO.isTypedef() && genTO.getBaseType instanceof BitsTypeDefinition)»
159 «generateGetValueForBitsTypeDef»
166 «generateToString(genTO.toStringIdentifiers)»
172 * Template method which generates the method <code>getValue()</code> for typedef,
173 * which base type is BitsDefinition.
175 * @return string with the <code>getValue()</code> method definition in JAVA format
177 def protected generateGetValueForBitsTypeDef() '''
179 public boolean[] getValue() {
180 return new boolean[]{
181 «FOR property: genTO.properties SEPARATOR ','»
189 * Template method which generates inner classes inside this interface.
191 * @return string with the source code for inner classes in JAVA format
193 def protected innerClassesDeclarations() '''
194 «IF !type.enclosedTypes.empty»
195 «FOR innerClass : type.enclosedTypes SEPARATOR "\n"»
196 «generateInnerClass(innerClass)»
201 def protected constructors() '''
203 «genUnionConstructor»
204 «ELSEIF genTO.typedef && allProperties.size == 1 && allProperties.get(0).name.equals(TypeConstants.VALUE_PROP)»
207 «allValuesConstructor»
210 «IF !allProperties.empty»
213 «IF properties.empty && !parentProperties.empty »
218 def private allValuesConstructor() '''
219 public «type.name»(«allProperties.asArgumentsDeclaration») {
220 «IF !parentProperties.empty»
221 super(«parentProperties.asArguments»);
223 «FOR p : allProperties»
224 «generateRestrictions(type, p.fieldName, p.returnType)»
228 «val fieldName = p.fieldName»
229 «IF p.returnType.name.endsWith("[]")»
230 this.«fieldName» = «fieldName» == null ? null : «fieldName».clone();
232 this.«fieldName» = «fieldName»;
238 def private typedefConstructor() '''
239 @«ConstructorParameters.importedName»("«TypeConstants.VALUE_PROP»")
240 @«ConstructorProperties.importedName»("«TypeConstants.VALUE_PROP»")
241 public «type.name»(«allProperties.asArgumentsDeclaration») {
242 «IF !parentProperties.empty»
243 super(«parentProperties.asArguments»);
245 «FOR p : allProperties»
246 «generateRestrictions(type, p.fieldName, p.returnType)»
249 * If we have patterns, we need to apply them to the value field. This is a sad consequence of how this code is
252 «CODEHELPERS.importedName».requireValue(_value);
253 «genPatternEnforcer("_value")»
256 «val fieldName = p.fieldName»
257 «IF p.returnType.name.endsWith("[]")»
258 this.«fieldName» = «fieldName».clone();
260 this.«fieldName» = «fieldName»;
266 def protected genUnionConstructor() '''
267 «FOR p : allProperties»
268 «val List<GeneratedProperty> other = new ArrayList(properties)»
270 «genConstructor(p, other)»
275 def protected genConstructor(GeneratedProperty property, Iterable<GeneratedProperty> other) '''
276 public «type.name»(«property.returnType.importedName + " " + property.name») {
277 «IF !parentProperties.empty»
278 super(«parentProperties.asArguments»);
281 «val fieldName = property.fieldName»
282 «generateRestrictions(type, fieldName, property.returnType)»
284 this.«fieldName» = «property.name»;
286 this.«p.fieldName» = null;
291 def private genPatternEnforcer(String ref) '''
293 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
294 «CODEHELPERS.importedName».checkPattern(«ref», «Constants.MEMBER_PATTERN_LIST», «Constants.MEMBER_REGEX_LIST»);
299 def private static paramValue(Type returnType, String paramName) {
300 if (returnType instanceof ConcreteType) {
303 return paramName + ".getValue()"
307 def private generateRestrictions(Type type, String paramName, Type returnType) '''
308 «val restrictions = type.restrictions»
309 «IF restrictions !== null»
310 «IF restrictions.lengthConstraint.present || restrictions.rangeConstraint.present»
311 if («paramName» != null) {
312 «IF restrictions.lengthConstraint.present»
313 «LengthGenerator.generateLengthCheckerCall(paramName, paramValue(returnType, paramName))»
315 «IF restrictions.rangeConstraint.present»
316 «rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))»
323 def protected copyConstructor() '''
325 * Creates a copy from Source Object.
327 * @param source Source object
329 public «type.name»(«type.name» source) {
330 «IF !parentProperties.empty»
334 «val fieldName = p.fieldName»
335 this.«fieldName» = source.«fieldName»;
340 def protected parentConstructor() '''
342 * Creates a new instance from «genTO.superType.importedName»
344 * @param source Source object
346 public «type.name»(«genTO.superType.importedName» source) {
348 «genPatternEnforcer("getValue()")»
352 def protected defaultInstance() '''
353 «IF genTO.typedef && !allProperties.empty && !genTO.unionType»
354 «val prop = allProperties.get(0)»
355 «IF !("org.opendaylight.yangtools.yang.binding.InstanceIdentifier".equals(prop.returnType.fullyQualifiedName))»
356 public static «genTO.name» getDefaultInstance(String defaultValue) {
357 «IF BYTE_ARRAY.equals(prop.returnType)»
358 return new «genTO.name»(«Base64.importedName».getDecoder().decode(defaultValue));
359 «ELSEIF STRING.equals(prop.returnType)»
360 return new «genTO.name»(defaultValue);
361 «ELSEIF Constants.EMPTY.equals(prop.returnType)»
362 «Preconditions.importedName».checkArgument(defaultValue.isEmpty(), "Invalid value %s", defaultValue);
363 return new «genTO.name»(«Empty.importedName».getInstance());
364 «ELSEIF allProperties.size > 1»
366 «ELSEIF BOOLEAN.equals(prop.returnType)»
367 return new «genTO.name»(«Boolean.importedName».valueOf(defaultValue));
368 «ELSEIF "java.lang.Byte".equals(prop.returnType.fullyQualifiedName)»
369 return new «genTO.name»(«Byte.importedName».valueOf(defaultValue));
370 «ELSEIF "java.lang.Short".equals(prop.returnType.fullyQualifiedName)»
371 return new «genTO.name»(«Short.importedName».valueOf(defaultValue));
372 «ELSEIF "java.lang.Integer".equals(prop.returnType.fullyQualifiedName)»
373 return new «genTO.name»(«Integer.importedName».valueOf(defaultValue));
374 «ELSEIF "java.lang.Long".equals(prop.returnType.fullyQualifiedName)»
375 return new «genTO.name»(«Long.importedName».valueOf(defaultValue));
376 «ELSEIF "org.opendaylight.yangtools.yang.common.Uint8".equals(prop.returnType.fullyQualifiedName)»
377 return new «genTO.name»(«Uint8.importedName».valueOf(defaultValue));
378 «ELSEIF "org.opendaylight.yangtools.yang.common.Uint16".equals(prop.returnType.fullyQualifiedName)»
379 return new «genTO.name»(«Uint16.importedName».valueOf(defaultValue));
380 «ELSEIF "org.opendaylight.yangtools.yang.common.Uint32".equals(prop.returnType.fullyQualifiedName)»
381 return new «genTO.name»(«Uint32.importedName».valueOf(defaultValue));
382 «ELSEIF "org.opendaylight.yangtools.yang.common.Uint64".equals(prop.returnType.fullyQualifiedName)»
383 return new «genTO.name»(«Uint64.importedName».valueOf(defaultValue));
385 return new «genTO.name»(new «prop.returnType.importedName»(defaultValue));
392 @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "FOR with SEPARATOR, not needing for value")
393 def protected bitsArgs() '''
394 «JU_LIST.importedName»<«STRING.importedName»> properties = «Lists.importedName».newArrayList(«allProperties.propsAsArgs»);
395 if (!properties.contains(defaultValue)) {
396 throw new «IllegalArgumentException.importedName»("invalid default parameter");
399 return new «genTO.name»(
400 «FOR prop : allProperties SEPARATOR ","»
401 properties.get(i++).equals(defaultValue) ? «Boolean.importedName».TRUE : null
406 def protected propsAsArgs(Iterable<GeneratedProperty> properties) '''
407 «FOR prop : properties SEPARATOR ","»
413 * Template method which generates JAVA class declaration.
415 * @param isInnerClass boolean value which specify if generated class is|isn't inner
416 * @return string with class declaration in JAVA format
418 def protected generateClassDeclaration(boolean isInnerClass) '''
422 ELSEIF (type.abstract)»«
426 ENDIF»class «type.name»«
427 IF (genTO.superType !== null)»«
428 " extends "»«genTO.superType.importedName»«
430 «IF (!type.implements.empty)»«
432 FOR type : type.implements SEPARATOR ", "»«
439 * Template method which generates JAVA enum type.
441 * @return string with inner enum source code in JAVA format
443 def protected enumDeclarations() '''
445 «FOR e : enums SEPARATOR "\n"»
446 «new EnumTemplate(javaType.getEnclosedType(e.identifier), e).generateAsInnerClass»
451 def protected suidDeclaration() '''
452 «IF genTO.SUID !== null»
453 private static final long serialVersionUID = «genTO.SUID.value»L;
457 def protected annotationDeclaration() '''
458 «IF genTO.getAnnotations !== null»
459 «FOR e : genTO.getAnnotations»
466 * Template method which generates JAVA constants.
468 * @return string with constants in JAVA format
470 def protected constantsDeclarations() '''
473 «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
474 «val cValue = c.value as Map<String, String>»
475 «val jurPatternRef = JUR_PATTERN.importedName»
476 public static final «JU_LIST.importedName»<String> «TypeConstants.PATTERN_CONSTANT_NAME» = «ImmutableList.importedName».of(«
477 FOR v : cValue.keySet SEPARATOR ", "»"«v.escapeJava»"«ENDFOR»);
478 «IF cValue.size == 1»
479 private static final «jurPatternRef» «Constants.MEMBER_PATTERN_LIST» = «jurPatternRef».compile(«TypeConstants.PATTERN_CONSTANT_NAME».get(0));
480 private static final String «Constants.MEMBER_REGEX_LIST» = "«cValue.values.iterator.next.escapeJava»";
482 private static final «jurPatternRef»[] «Constants.MEMBER_PATTERN_LIST» = «CODEHELPERS.importedName».compilePatterns(«TypeConstants.PATTERN_CONSTANT_NAME»);
483 private static final String[] «Constants.MEMBER_REGEX_LIST» = { «
484 FOR v : cValue.values SEPARATOR ", "»"«v.escapeJava»"«ENDFOR» };
494 * Template method which generates JAVA class attributes.
496 * @return string with the class attributes in JAVA format
498 def protected generateFields() '''
499 «IF !properties.empty»
501 private«IF isReadOnly(f)» final«ENDIF» «f.returnType.importedName» «f.fieldName»;
506 protected def isReadOnly(GeneratedProperty field) {
507 return field.readOnly
511 * Template method which generates the method <code>hashCode()</code>.
513 * @return string with the <code>hashCode()</code> method definition in JAVA format
515 def protected generateHashCode() {
516 val size = genTO.hashCodeIdentifiers.size
521 @«OVERRIDE.importedName»
522 public int hashCode() {
524 «hashCodeResult(genTO.hashCodeIdentifiers)»
527 return «CODEHELPERS.importedName».wrapperHashCode(«genTO.hashCodeIdentifiers.get(0).fieldName»);
534 * Template method which generates the method <code>equals()</code>.
536 * @return string with the <code>equals()</code> method definition in JAVA format
538 def private generateEquals() '''
539 «IF !genTO.equalsIdentifiers.empty»
540 @«OVERRIDE.importedName»
541 public final boolean equals(java.lang.Object obj) {
545 if (!(obj instanceof «type.name»)) {
548 final «type.name» other = («type.name») obj;
549 «FOR property : genTO.equalsIdentifiers»
550 «val fieldName = property.fieldName»
551 if (!«property.importedUtilClass».equals(«fieldName», other.«fieldName»)) {
560 def GeneratedProperty getPropByName(String name) {
561 for (GeneratedProperty prop : allProperties) {
562 if (prop.name.equals(name)) {