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