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