fac6cf25c5aed0a114667df8fd07314f01508bbb
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / ClassTemplate.xtend
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.binding.java.api.generator
9
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
28
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
37 import java.util.List
38 import java.util.Map
39 import java.util.Set
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
53
54 /**
55  * Template for generating JAVA class.
56  */
57 @SuppressModernizer
58 class ClassTemplate extends BaseTemplate {
59     static val Comparator<GeneratedProperty> PROP_COMPARATOR = Comparator.comparing([prop | prop.name])
60     static val VALUEOF_TYPES = Set.of(
61         BOOLEAN_TYPE,
62         INT8_TYPE,
63         INT16_TYPE,
64         INT32_TYPE,
65         INT64_TYPE,
66         UINT8_TYPE,
67         UINT16_TYPE,
68         UINT32_TYPE,
69         UINT64_TYPE)
70
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
76
77     /**
78      * List of enumeration which are generated as JAVA enum type.
79      */
80     protected val List<Enumeration> enums
81
82     /**
83      * List of constant instances which are generated as JAVA public static final attributes.
84      */
85     protected val List<Constant> consts
86
87     protected val GeneratedTransferObject genTO
88
89     val AbstractRangeGenerator<?> rangeGenerator
90
91     /**
92      * Creates instance of this class with concrete <code>genType</code>.
93      *
94      * @param genType generated transfer object which will be transformed to JAVA class source code
95      */
96     new(GeneratedTransferObject genType) {
97         this(new TopLevelJavaGeneratedType(genType), genType)
98     }
99
100     /**
101      * Creates instance of this class with concrete <code>genType</code>.
102      *
103      * @param genType generated transfer object which will be transformed to JAVA class source code
104      */
105     new(AbstractJavaGeneratedType javaType, GeneratedTransferObject genType) {
106         super(javaType, genType)
107         this.genTO = genType
108         this.properties = genType.properties
109         this.finalProperties = GeneratorUtil.resolveReadOnlyPropertiesFromTO(genTO.properties)
110         this.parentProperties = GeneratorUtil.getPropertiesOfAllParents(genTO)
111         this.restrictions = genType.restrictions
112
113         val sorted = new ArrayList();
114         sorted.addAll(properties);
115         sorted.addAll(parentProperties);
116         sorted.sort(PROP_COMPARATOR);
117
118         this.allProperties = sorted
119         this.enums = genType.enumerations
120         this.consts = genType.constantDefinitions
121
122         if (restrictions !== null && restrictions.rangeConstraint.present) {
123             rangeGenerator = requireNonNull(AbstractRangeGenerator.forType(TypeUtils.encapsulatedValueType(genType)))
124         } else {
125             rangeGenerator = null
126         }
127     }
128
129     /**
130      * Generates JAVA class source code (class body only).
131      *
132      * @return string with JAVA class body source code
133      */
134     def CharSequence generateAsInnerClass() {
135         return generateBody(true)
136     }
137
138     override protected body() {
139         generateBody(false);
140     }
141
142     /**
143      * Template method which generates class body.
144      *
145      * @param isInnerClass boolean value which specify if generated class is|isn't inner
146      * @return string with class source code in JAVA format
147      */
148     def protected generateBody(boolean isInnerClass) '''
149         «wrapToDocumentation(formatDataForJavaDoc(type))»
150         «annotationDeclaration»
151         «generateClassDeclaration(isInnerClass)» {
152             «suidDeclaration»
153             «innerClassesDeclarations»
154             «enumDeclarations»
155             «constantsDeclarations»
156             «generateFields»
157
158             «IF restrictions !== null»
159                 «IF restrictions.lengthConstraint.present»
160                     «LengthGenerator.generateLengthChecker("_value", TypeUtils.encapsulatedValueType(genTO),
161                         restrictions.lengthConstraint.get, this)»
162                 «ENDIF»
163                 «IF restrictions.rangeConstraint.present»
164                     «rangeGenerator.generateRangeChecker("_value", restrictions.rangeConstraint.get, this)»
165                 «ENDIF»
166             «ENDIF»
167
168             «constructors»
169
170             «defaultInstance»
171
172             «propertyMethods»
173
174             «IF (genTO.isTypedef() && genTO.getBaseType instanceof BitsTypeDefinition)»
175                 «generateGetValueForBitsTypeDef»
176             «ENDIF»
177
178             «generateHashCode»
179
180             «generateEquals»
181
182             «generateToString(genTO.toStringIdentifiers)»
183         }
184
185     '''
186
187     def private propertyMethods() {
188         if (properties.empty) {
189             return ""
190         }
191         isScalarTypeObject ? scalarTypeObjectValue(properties.get(0)) : defaultProperties
192     }
193
194     def private isScalarTypeObject() {
195         for (impl : genTO.implements) {
196             if (SCALAR_TYPE_OBJECT.identifier.equals(impl.identifier)) {
197                 return true
198             }
199         }
200         return false
201     }
202
203     def private defaultProperties() '''
204         «FOR field : properties SEPARATOR "\n"»
205             «field.getterMethod»
206             «IF !field.readOnly»
207                 «field.setterMethod»
208             «ENDIF»
209         «ENDFOR»
210     '''
211
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»;
216         }
217     '''
218
219     /**
220      * Template method which generates the method <code>getValue()</code> for typedef,
221      * which base type is BitsDefinition.
222      *
223      * @return string with the <code>getValue()</code> method definition in JAVA format
224      */
225     def protected generateGetValueForBitsTypeDef() '''
226
227         public boolean[] getValue() {
228             return new boolean[]{
229             «FOR property: genTO.properties SEPARATOR ','»
230                  «property.fieldName»
231             «ENDFOR»
232             };
233         }
234     '''
235
236     /**
237      * Template method which generates inner classes inside this interface.
238      *
239      * @return string with the source code for inner classes in JAVA format
240      */
241     def protected innerClassesDeclarations() '''
242         «IF !type.enclosedTypes.empty»
243             «FOR innerClass : type.enclosedTypes SEPARATOR "\n"»
244                 «generateInnerClass(innerClass)»
245             «ENDFOR»
246         «ENDIF»
247     '''
248
249     def protected constructors() '''
250         «IF genTO.unionType»
251             «genUnionConstructor»
252         «ELSEIF genTO.typedef && allProperties.size == 1 && allProperties.get(0).name.equals(TypeConstants.VALUE_PROP)»
253             «typedefConstructor»
254         «ELSE»
255             «allValuesConstructor»
256         «ENDIF»
257
258         «IF !allProperties.empty»
259             «copyConstructor»
260         «ENDIF»
261         «IF properties.empty && !parentProperties.empty »
262             «parentConstructor»
263         «ENDIF»
264     '''
265
266     def private allValuesConstructor() '''
267     public «type.name»(«allProperties.asArgumentsDeclaration») {
268         «IF !parentProperties.empty»
269             super(«parentProperties.asArguments»);
270         «ENDIF»
271         «FOR p : allProperties»
272             «generateRestrictions(type, p.fieldName, p.returnType)»
273         «ENDFOR»
274
275         «FOR p : properties»
276             «val fieldName = p.fieldName»
277             «IF p.returnType.name.endsWith("[]")»
278                 this.«fieldName» = «fieldName» == null ? null : «fieldName».clone();
279             «ELSE»
280                 this.«fieldName» = «fieldName»;
281             «ENDIF»
282         «ENDFOR»
283     }
284     '''
285
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»);
292         «ENDIF»
293         «FOR p : allProperties»
294             «generateRestrictions(type, p.fieldName, p.returnType)»
295         «ENDFOR»
296         «/*
297          * If we have patterns, we need to apply them to the value field. This is a sad consequence of how this code is
298          * structured.
299          */»
300         «CODEHELPERS.importedName».requireValue(_value);
301         «genPatternEnforcer("_value")»
302
303         «FOR p : properties»
304             «val fieldName = p.fieldName»
305             «IF p.returnType.name.endsWith("[]")»
306                 this.«fieldName» = «fieldName».clone();
307             «ELSE»
308                 this.«fieldName» = «fieldName»;
309             «ENDIF»
310         «ENDFOR»
311     }
312     '''
313
314     def protected genUnionConstructor() '''
315     «FOR p : allProperties»
316         «val List<GeneratedProperty> other = new ArrayList(properties)»
317         «IF other.remove(p)»
318             «genConstructor(p, other)»
319         «ENDIF»
320     «ENDFOR»
321     '''
322
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»);
327         «ENDIF»
328
329         «val fieldName = property.fieldName»
330         «generateRestrictions(type, fieldName, property.returnType)»
331
332         this.«fieldName» = «property.name»;
333         «FOR p : other»
334             this.«p.fieldName» = null;
335         «ENDFOR»
336     }
337     '''
338
339     def private genPatternEnforcer(String ref) '''
340         «FOR c : consts»
341             «IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
342             «CODEHELPERS.importedName».checkPattern(«ref», «Constants.MEMBER_PATTERN_LIST», «Constants.MEMBER_REGEX_LIST»);
343             «ENDIF»
344         «ENDFOR»
345     '''
346
347     def private static paramValue(Type returnType, String paramName) {
348         if (returnType instanceof ConcreteType) {
349             return paramName
350         } else {
351             return paramName + ".getValue()"
352         }
353     }
354
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))»
362                 «ENDIF»
363                 «IF restrictions.rangeConstraint.present»
364                     «rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))»
365                 «ENDIF»
366             }
367             «ENDIF»
368         «ENDIF»
369     '''
370
371     def protected copyConstructor() '''
372     /**
373      * Creates a copy from Source Object.
374      *
375      * @param source Source object
376      */
377     public «type.name»(«type.name» source) {
378         «IF !parentProperties.empty»
379             super(source);
380         «ENDIF»
381         «FOR p : properties»
382             «val fieldName = p.fieldName»
383             this.«fieldName» = source.«fieldName»;
384         «ENDFOR»
385     }
386     '''
387
388     def protected parentConstructor() '''
389     /**
390      * Creates a new instance from «genTO.superType.importedName»
391      *
392      * @param source Source object
393      */
394     public «type.name»(«genTO.superType.importedName» source) {
395         super(source);
396         «genPatternEnforcer("getValue()")»
397     }
398     '''
399
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»
407                     «bitsArgs»
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());
417                 «ELSE»
418                     return new «genTO.name»(new «propType.importedName»(defaultValue));
419                 «ENDIF»
420             }
421             «ENDIF»
422         «ENDIF»
423     '''
424
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");
430         }
431         int i = 0;
432         return new «genTO.name»(
433         «FOR prop : allProperties SEPARATOR ","»
434             properties.get(i++).equals(defaultValue) ? «BOOLEAN.importedName».TRUE : null
435         «ENDFOR»
436         );
437     '''
438
439     def protected propsAsArgs(Iterable<GeneratedProperty> properties) '''
440         «FOR prop : properties SEPARATOR ","»
441             "«prop.name»"
442         «ENDFOR»
443     '''
444
445     /**
446      * Template method which generates JAVA class declaration.
447      *
448      * @param isInnerClass boolean value which specify if generated class is|isn't inner
449      * @return string with class declaration in JAVA format
450      */
451     def protected generateClassDeclaration(boolean isInnerClass) '''
452         public«
453         IF (isInnerClass)»«
454             " static final "»«
455         ELSEIF (type.abstract)»«
456             " abstract "»«
457         ELSE»«
458             " "»«
459         ENDIF»class «type.name»«
460         IF (genTO.superType !== null)»«
461             " extends "»«genTO.superType.importedName»«
462         ENDIF»
463         «IF (!type.implements.empty)»«
464             " implements "»«
465             FOR type : type.implements SEPARATOR ", "»«
466                 type.importedName»«
467             ENDFOR»«
468         ENDIF
469     »'''
470
471     /**
472      * Template method which generates JAVA enum type.
473      *
474      * @return string with inner enum source code in JAVA format
475      */
476     def protected enumDeclarations() '''
477         «IF !enums.empty»
478             «FOR e : enums SEPARATOR "\n"»
479                 «new EnumTemplate(javaType.getEnclosedType(e.identifier), e).generateAsInnerClass»
480             «ENDFOR»
481         «ENDIF»
482     '''
483
484     def protected suidDeclaration() '''
485         «IF genTO.SUID !== null»
486             private static final long serialVersionUID = «genTO.SUID.value»L;
487         «ENDIF»
488     '''
489
490     def protected annotationDeclaration() '''
491         «IF genTO.getAnnotations !== null»
492             «FOR e : genTO.getAnnotations»
493                 @«e.getName»
494             «ENDFOR»
495         «ENDIF»
496     '''
497
498     /**
499      * Template method which generates JAVA constants.
500      *
501      * @return string with constants in JAVA format
502      */
503     def protected constantsDeclarations() '''
504         «IF !consts.empty»
505             «FOR c : consts»
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»";
514                     «ELSE»
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» };
518                     «ENDIF»
519                 «ELSE»
520                     «emitConstant(c)»
521                 «ENDIF»
522             «ENDFOR»
523         «ENDIF»
524     '''
525
526     /**
527      * Template method which generates JAVA class attributes.
528      *
529      * @return string with the class attributes in JAVA format
530      */
531     def protected generateFields() '''
532         «IF !properties.empty»
533             «FOR f : properties»
534                 private«IF isReadOnly(f)» final«ENDIF» «f.returnType.importedName» «f.fieldName»;
535             «ENDFOR»
536         «ENDIF»
537     '''
538
539     protected def isReadOnly(GeneratedProperty field) {
540         return field.readOnly
541     }
542
543     /**
544      * Template method which generates the method <code>hashCode()</code>.
545      *
546      * @return string with the <code>hashCode()</code> method definition in JAVA format
547      */
548     def protected generateHashCode() {
549         val size = genTO.hashCodeIdentifiers.size
550         if (size == 0) {
551             return ""
552         }
553         return '''
554             @«OVERRIDE.importedName»
555             public int hashCode() {
556                 «IF size != 1»
557                     «hashCodeResult(genTO.hashCodeIdentifiers)»
558                     return result;
559                 «ELSE»
560                     return «CODEHELPERS.importedName».wrapperHashCode(«genTO.hashCodeIdentifiers.get(0).fieldName»);
561                 «ENDIF»
562             }
563         '''
564     }
565
566     /**
567      * Template method which generates the method <code>equals()</code>.
568      *
569      * @return string with the <code>equals()</code> method definition in JAVA format
570      */
571     def private generateEquals() '''
572         «IF !genTO.equalsIdentifiers.empty»
573             @«OVERRIDE.importedName»
574             public final boolean equals(java.lang.Object obj) {
575                 if (this == obj) {
576                     return true;
577                 }
578                 if (!(obj instanceof «type.name»)) {
579                     return false;
580                 }
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»)) {
585                         return false;
586                     }
587                 «ENDFOR»
588                 return true;
589             }
590         «ENDIF»
591     '''
592
593     def GeneratedProperty getPropByName(String name) {
594         for (GeneratedProperty prop : allProperties) {
595             if (prop.name.equals(name)) {
596                 return prop;
597             }
598         }
599         return null
600     }
601 }