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