Adopt yangtools-11.0.0-SNAPSHOT
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / BaseTemplate.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 extension org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil.encodeAngleBrackets
11 import static org.opendaylight.mdsal.binding.model.ri.Types.STRING;
12 import static org.opendaylight.mdsal.binding.model.ri.Types.objectType;
13
14 import com.google.common.base.CharMatcher
15 import com.google.common.base.Splitter
16 import java.util.Collection
17 import java.util.List
18 import java.util.Locale
19 import java.util.Map.Entry
20 import java.util.StringTokenizer
21 import java.util.regex.Pattern
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.mdsal.binding.model.api.AnnotationType
24 import org.opendaylight.mdsal.binding.model.api.ConcreteType
25 import org.opendaylight.mdsal.binding.model.api.Constant
26 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
27 import org.opendaylight.mdsal.binding.model.api.GeneratedType
28 import org.opendaylight.mdsal.binding.model.api.JavaTypeName
29 import org.opendaylight.mdsal.binding.model.api.MethodSignature
30 import org.opendaylight.mdsal.binding.model.api.Restrictions
31 import org.opendaylight.mdsal.binding.model.api.Type
32 import org.opendaylight.mdsal.binding.model.api.TypeMemberComment
33 import org.opendaylight.mdsal.binding.model.ri.TypeConstants
34 import org.opendaylight.yangtools.yang.binding.BaseIdentity
35 import org.opendaylight.yangtools.yang.binding.contract.Naming
36 import org.opendaylight.yangtools.yang.common.YangDataName
37
38 abstract class BaseTemplate extends JavaFileTemplate {
39     static final char NEW_LINE = '\n'
40     static final char SPACE = ' '
41     static val WS_MATCHER = CharMatcher.anyOf("\n\t")
42     static val SPACES_PATTERN = Pattern.compile(" +")
43     static val NL_SPLITTER = Splitter.on(NEW_LINE)
44
45     new(GeneratedType type) {
46         super(type)
47     }
48
49     new(AbstractJavaGeneratedType javaType, GeneratedType type) {
50         super(javaType, type)
51     }
52
53     final def generate() {
54         val _body = body()
55         '''
56             package «type.packageName»;
57             «generateImportBlock»
58
59             «_body»
60         '''.toString
61     }
62
63     protected abstract def CharSequence body();
64
65     // Helper patterns
66     final protected def fieldName(GeneratedProperty property) {
67         "_" + property.name
68     }
69
70     /**
71      * Template method which generates the getter method for <code>field</code>
72      *
73      * @param field
74      * generated property with data about field which is generated as the getter method
75      * @return string with the getter method source code in JAVA format
76      */
77     protected def getterMethod(GeneratedProperty field) '''
78         «val methodName = field.getterMethodName»
79         public «field.returnType.importedName» «methodName»() {
80             «val fieldName = field.fieldName»
81             «IF field.returnType.name.endsWith("[]")»
82             return «fieldName» == null ? null : «fieldName».clone();
83             «ELSE»
84             return «fieldName»;
85             «ENDIF»
86         }
87     '''
88
89     final protected def getterMethodName(GeneratedProperty field) {
90         return field.name.getterMethodName
91     }
92
93     final protected def getterMethodName(String propName) {
94         return '''«Naming.GETTER_PREFIX»«propName.toFirstUpper»'''
95     }
96
97     /**
98      * Template method which generates the setter method for <code>field</code>
99      *
100      * @param field
101      * generated property with data about field which is generated as the setter method
102      * @return string with the setter method source code in JAVA format
103      */
104     final protected def setterMethod(GeneratedProperty field) '''
105         «val returnType = field.returnType.importedName»
106         public «type.name» set«field.name.toFirstUpper»(«returnType» value) {
107             this.«field.fieldName» = value;
108             return this;
109         }
110     '''
111
112     /**
113      * Template method which generates method parameters with their types from <code>parameters</code>.
114      *
115      * @param parameters
116      * group of generated property instances which are transformed to the method parameters
117      * @return string with the list of the method parameters with their types in JAVA format
118      */
119     def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
120         returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
121
122     /**
123      * Template method which generates method parameters with their types from <code>parameters</code>, annotating them
124      * with {@link NonNull}.
125      *
126      * @param parameters group of generated property instances which are transformed to the method parameters
127      * @return string with the list of the method parameters with their types in JAVA format
128      */
129     def final protected asNonNullArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»
130         «FOR parameter : parameters SEPARATOR ", "»«parameter.returnType.importedNonNull» «parameter
131         .fieldName»«ENDFOR»«ENDIF»'''
132
133     /**
134      * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
135      *
136      * @param parameters
137      * group of generated property instances which are transformed to the sequence of parameter names
138      * @return string with the list of the parameter names of the <code>parameters</code>
139      */
140     def final protected asArguments(Collection<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
141         fieldName»«ENDFOR»«ENDIF»'''
142
143     /**
144      * Template method which generates JAVA comments.
145      *
146      * @param comment string with the comment for whole JAVA class
147      * @return string with comment in JAVA format
148      */
149     def final protected asJavadoc(TypeMemberComment comment) {
150         if (comment === null) {
151             return ''
152         }
153         return wrapToDocumentation('''
154            «comment.contractDescription»
155
156            «comment.referenceDescription.formatReference»
157
158            «comment.typeSignature»
159         ''')
160     }
161
162     def static String wrapToDocumentation(String text) {
163         if (text.empty)
164             return ""
165
166         val StringBuilder sb = new StringBuilder().append("/**\n")
167         for (String t : NL_SPLITTER.split(text)) {
168             sb.append(" *")
169             if (!t.isEmpty()) {
170                 sb.append(SPACE).append(t)
171             }
172             sb.append(NEW_LINE)
173         }
174         sb.append(" */")
175
176         return sb.toString
177     }
178
179     def protected String formatDataForJavaDoc(GeneratedType type) {
180         val sb = new StringBuilder()
181         val comment = type.comment
182         if (comment !== null) {
183             sb.append(comment.javadoc)
184         }
185
186         appendSnippet(sb, type)
187
188         return '''
189             «IF sb.length != 0»
190             «sb.toString»
191             «ENDIF»
192         '''.toString
193     }
194
195     def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) {
196         val comment = type.comment
197         if (comment === null) {
198             return '''
199                 «additionalComment»
200             '''
201         }
202
203         val sb = new StringBuilder().append(comment.javadoc)
204         appendSnippet(sb, type)
205
206         sb.append(NEW_LINE)
207         .append(NEW_LINE)
208         .append(NEW_LINE)
209         .append(additionalComment)
210
211         return '''
212             «sb.toString»
213         '''
214     }
215
216     def static formatReference(String reference) '''
217         «IF reference !== null»
218             <pre>
219                 <code>
220                     «reference.encodeAngleBrackets.formatToParagraph»
221                 </code>
222             </pre>
223
224         «ENDIF»
225     '''
226
227     def asLink(String text) {
228         val StringBuilder sb = new StringBuilder()
229         var tempText = text
230         var char lastChar = SPACE
231         var boolean badEnding = false
232
233         if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
234             tempText = text.substring(0, text.length - 1)
235             lastChar = text.charAt(text.length - 1)
236             badEnding = true
237         }
238         sb.append("<a href = \"").append(tempText).append("\">").append(tempText).append("</a>")
239
240         if (badEnding)
241             sb.append(lastChar)
242
243         return sb.toString
244     }
245
246     protected static def formatToParagraph(String inputText) {
247         val StringBuilder sb = new StringBuilder();
248         var StringBuilder lineBuilder = new StringBuilder();
249         var boolean isFirstElementOnNewLineEmptyChar = false;
250
251         var formattedText = WS_MATCHER.replaceFrom(inputText.encodeJavadocSymbols, SPACE)
252         formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
253
254         val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true)
255         while (tokenizer.hasMoreTokens) {
256             val nextElement = tokenizer.nextToken
257
258             if (lineBuilder.length != 0 && lineBuilder.length + nextElement.length > 80) {
259                 if (lineBuilder.charAt(lineBuilder.length - 1) == SPACE) {
260                     lineBuilder.setLength(lineBuilder.length - 1)
261                 }
262                 if (lineBuilder.length != 0 && lineBuilder.charAt(0) == SPACE) {
263                     lineBuilder.deleteCharAt(0)
264                 }
265
266                 sb.append(lineBuilder).append(NEW_LINE)
267                 lineBuilder.setLength(0)
268
269                 if (" ".equals(nextElement)) {
270                     isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
271                 }
272             }
273             if (isFirstElementOnNewLineEmptyChar) {
274                 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
275             } else {
276                 lineBuilder.append(nextElement)
277             }
278         }
279
280         return sb.append(lineBuilder).append(NEW_LINE).toString
281     }
282
283     /**
284      * Template method which generates method parameters with their types from <code>parameters</code>.
285      *
286      * @param parameters
287      * list of parameter instances which are transformed to the method parameters
288      * @return string with the list of the method parameters with their types in JAVA format
289      */
290     def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
291         IF !parameters.empty»«
292             FOR parameter : parameters SEPARATOR ", "»«
293                 parameter.type.importedName» «parameter.name»«
294             ENDFOR»«
295         ENDIF
296     »'''
297
298     def protected emitConstant(Constant c) '''
299         «IF Naming.QNAME_STATIC_FIELD_NAME.equals(c.name)»
300             «val entry = c.value as Entry<JavaTypeName, String>»
301             /**
302              * YANG identifier of the statement represented by this class.
303              */
304             public static final «c.type.importedNonNull» «c.name» = «entry.key.importedName».«Naming.MODULE_INFO_QNAMEOF_METHOD_NAME»("«entry.value»");
305         «ELSEIF Naming.NAME_STATIC_FIELD_NAME.equals(c.name)»
306             «val entry = c.value as Entry<JavaTypeName, YangDataName>»
307             /**
308              * Yang Data template name of the statement represented by this class.
309              */
310             public static final «c.type.importedNonNull» «c.name» = «entry.key.importedName».«Naming.MODULE_INFO_YANGDATANAMEOF_METHOD_NAME»("«entry.value.name»");
311         «ELSEIF Naming.VALUE_STATIC_FIELD_NAME.equals(c.name) && BaseIdentity.equals(c.value)»
312             «val typeName = c.type.importedName»
313             «val override = OVERRIDE.importedName»
314             /**
315              * Singleton value representing the {@link «typeName»} identity.
316              */
317             public static final «c.type.importedNonNull» «c.name» = new «typeName»() {
318                 @«override»
319                 public «CLASS.importedName»<«typeName»> «Naming.BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME»() {
320                     return «typeName».class;
321                 }
322
323                 @«override»
324                 public int hashCode() {
325                     return «typeName».class.hashCode();
326                 }
327
328                 @«override»
329                 public boolean equals(final «objectType.importedName» obj) {
330                     return obj == this || obj instanceof «typeName» other
331                         && «typeName».class.equals(other.«Naming.BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME»());
332                 }
333
334                 @«override»
335                 public «STRING.importedName» toString() {
336                     return «MOREOBJECTS.importedName».toStringHelper("«c.type.name»").add("qname", QNAME).toString();
337                 }
338             };
339         «ELSE»
340             public static final «c.type.importedName» «c.name» = «c.value»;
341         «ENDIF»
342     '''
343
344     def protected generateCheckers(GeneratedProperty field, Restrictions restrictions, Type actualType) '''
345        «IF restrictions.rangeConstraint.present»
346            «AbstractRangeGenerator.forType(actualType).generateRangeChecker(field.name.toFirstUpper,
347                restrictions.rangeConstraint.orElseThrow, this)»
348        «ENDIF»
349        «IF restrictions.lengthConstraint.present»
350            «LengthGenerator.generateLengthChecker(field.fieldName, actualType, restrictions.lengthConstraint.orElseThrow, this)»
351        «ENDIF»
352     '''
353
354     def protected checkArgument(GeneratedProperty property, Restrictions restrictions, Type actualType, String value) '''
355        «IF restrictions.getRangeConstraint.isPresent»
356            «IF actualType instanceof ConcreteType»
357                «AbstractRangeGenerator.forType(actualType).generateRangeCheckerCall(property.getName.toFirstUpper, value)»
358            «ELSE»
359                «AbstractRangeGenerator.forType(actualType).generateRangeCheckerCall(property.getName.toFirstUpper, value + ".getValue()")»
360            «ENDIF»
361        «ENDIF»
362        «val fieldName = property.fieldName»
363        «IF restrictions.getLengthConstraint.isPresent»
364            «IF actualType instanceof ConcreteType»
365                «LengthGenerator.generateLengthCheckerCall(fieldName, value)»
366            «ELSE»
367                «LengthGenerator.generateLengthCheckerCall(fieldName, value + ".getValue()")»
368            «ENDIF»
369        «ENDIF»
370
371        «val fieldUpperCase = fieldName.toUpperCase(Locale.ENGLISH)»
372        «FOR currentConstant : type.getConstantDefinitions»
373            «IF currentConstant.getName.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)
374                && fieldUpperCase.equals(currentConstant.getName.substring(TypeConstants.PATTERN_CONSTANT_NAME.length))»
375            «CODEHELPERS.importedName».checkPattern(value, «Constants.MEMBER_PATTERN_LIST»«fieldName», «Constants.MEMBER_REGEX_LIST»«fieldName»);
376            «ENDIF»
377        «ENDFOR»
378     '''
379
380     def protected final generateAnnotation(AnnotationType annotation) '''
381         @«annotation.importedName»
382         «IF annotation.parameters !== null && !annotation.parameters.empty»
383         (
384         «FOR param : annotation.parameters SEPARATOR ","»
385             «param.name»=«param.value»
386         «ENDFOR»
387         )
388         «ENDIF»
389     '''
390 }