63d426937ac5eb5eee792faff7ac8d8856adc5d0
[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 org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.encodeAngleBrackets
11
12 import com.google.common.base.CharMatcher
13 import com.google.common.base.MoreObjects
14 import com.google.common.base.Splitter
15 import com.google.common.collect.Iterables
16 import java.util.Collection
17 import java.util.List
18 import java.util.StringTokenizer
19 import java.util.regex.Pattern
20 import org.opendaylight.mdsal.binding.model.api.ConcreteType
21 import org.opendaylight.mdsal.binding.model.api.Constant
22 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
23 import org.opendaylight.mdsal.binding.model.api.GeneratedType
24 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
25 import org.opendaylight.mdsal.binding.model.api.MethodSignature
26 import org.opendaylight.mdsal.binding.model.api.Restrictions
27 import org.opendaylight.mdsal.binding.model.api.Type
28 import org.opendaylight.mdsal.binding.model.api.TypeMember
29 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single
30 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple
31 import org.opendaylight.mdsal.binding.model.util.Types
32 import org.opendaylight.yangtools.yang.binding.CodeHelpers
33 import org.opendaylight.yangtools.yang.common.QName
34 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
35 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
36 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition
37 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
38 import org.opendaylight.yangtools.yang.model.api.SchemaNode
39 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping
40 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement
41 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement
42 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement
43 import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter
44
45 abstract class BaseTemplate extends JavaFileTemplate {
46     private static final char NEW_LINE = '\n'
47     private static val AMP_MATCHER = CharMatcher.is('&')
48     private static val NL_MATCHER = CharMatcher.is(NEW_LINE)
49     private static val TAB_MATCHER = CharMatcher.is('\t')
50     private static val SPACES_PATTERN = Pattern.compile(" +")
51     private static val NL_SPLITTER = Splitter.on(NL_MATCHER)
52     private static val TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
53     private static val YANG_FORMATTER = DeclaredStatementFormatter.builder()
54         .addIgnoredStatement(YangStmtMapping.CONTACT)
55         .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
56         .addIgnoredStatement(YangStmtMapping.REFERENCE)
57         .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
58         .build();
59
60     new(GeneratedType type) {
61         super(type)
62     }
63
64     final public def generate() {
65         val _body = body()
66         '''
67             package «type.packageName»;
68             «generateImportBlock»
69
70             «_body»
71         '''.toString
72     }
73
74     protected abstract def CharSequence body();
75
76     // Helper patterns
77     final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
78
79     final protected def propertyNameFromGetter(MethodSignature getter) {
80         var int prefix;
81         if (getter.name.startsWith("is")) {
82             prefix = 2
83         } else if (getter.name.startsWith("get")) {
84             prefix = 3
85         } else {
86             throw new IllegalArgumentException("Not a getter")
87         }
88         return getter.name.substring(prefix).toFirstLower;
89     }
90
91     final protected def isAccessor(MethodSignature maybeGetter) {
92         return maybeGetter.name.startsWith("is") || maybeGetter.name.startsWith("get");
93     }
94
95     /**
96      * Template method which generates the getter method for <code>field</code>
97      *
98      * @param field
99      * generated property with data about field which is generated as the getter method
100      * @return string with the getter method source code in JAVA format
101      */
102     protected def getterMethod(GeneratedProperty field) {
103         '''
104             public «field.returnType.importedName» «field.getterMethodName»() {
105                 «IF field.returnType.importedName.contains("[]")»
106                 return «field.fieldName» == null ? null : «field.fieldName».clone();
107                 «ELSE»
108                 return «field.fieldName»;
109                 «ENDIF»
110             }
111         '''
112     }
113
114     final protected def getterMethodName(GeneratedProperty field) {
115         val prefix = if(field.returnType.equals(Types.BOOLEAN)) "is" else "get"
116         return '''«prefix»«field.name.toFirstUpper»'''
117     }
118
119     /**
120      * Template method which generates the setter method for <code>field</code>
121      *
122      * @param field
123      * generated property with data about field which is generated as the setter method
124      * @return string with the setter method source code in JAVA format
125      */
126     final protected def setterMethod(GeneratedProperty field) '''
127         «val returnType = field.returnType.importedName»
128         public «type.name» set«field.name.toFirstUpper»(«returnType» value) {
129             this.«field.fieldName» = value;
130             return this;
131         }
132     '''
133
134     /**
135      * Template method which generates method parameters with their types from <code>parameters</code>.
136      *
137      * @param parameters
138      * group of generated property instances which are transformed to the method parameters
139      * @return string with the list of the method parameters with their types in JAVA format
140      */
141     def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
142         returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
143
144     /**
145      * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
146      *
147      * @param parameters
148      * group of generated property instances which are transformed to the sequence of parameter names
149      * @return string with the list of the parameter names of the <code>parameters</code>
150      */
151     def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
152         fieldName»«ENDFOR»«ENDIF»'''
153
154     /**
155      * Template method which generates JAVA comments.
156      *
157      * @param comment string with the comment for whole JAVA class
158      * @return string with comment in JAVA format
159      */
160     def protected CharSequence asJavadoc(String comment) {
161         if(comment === null) return ''
162         var txt = comment
163
164         txt = comment.trim
165         txt = formatToParagraph(txt)
166
167         return '''
168             «wrapToDocumentation(txt)»
169         '''
170     }
171
172     def String wrapToDocumentation(String text) {
173         if (text.empty)
174             return ""
175
176         val StringBuilder sb = new StringBuilder().append("/**\n")
177         for (String t : NL_SPLITTER.split(text)) {
178             sb.append(" *")
179             if (!t.isEmpty()) {
180                 sb.append(' ');
181                 sb.append(t)
182             }
183             sb.append(NEW_LINE)
184         }
185         sb.append(" */")
186
187         return sb.toString
188     }
189
190     def protected String formatDataForJavaDoc(GeneratedType type) {
191         val sb = new StringBuilder()
192         val comment = type.comment
193         if (comment !== null) {
194             sb.append(comment.javadoc)
195         }
196
197         appendSnippet(sb, type)
198
199         return '''
200             «IF sb.length != 0»
201             «sb.toString»
202             «ENDIF»
203         '''.toString
204     }
205
206     def static encodeJavadocSymbols(String description) {
207         if (description.nullOrEmpty) {
208             return description;
209         }
210
211         return TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&amp;")).replaceAll("&#42;&#47;")
212     }
213
214     def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) {
215         val comment = type.comment
216         if (comment === null) {
217             return '''
218                 «additionalComment»
219             '''
220         }
221
222         val sb = new StringBuilder().append(comment.javadoc)
223         appendSnippet(sb, type)
224
225         sb.append(NEW_LINE)
226         .append(NEW_LINE)
227         .append(NEW_LINE)
228         .append(additionalComment)
229
230         return '''
231             «sb.toString»
232         '''
233     }
234
235     def private static void appendSnippet(StringBuilder sb, GeneratedType type) {
236         val optDef = type.yangSourceDefinition
237         if (optDef.present) {
238             val def = optDef.get
239             sb.append(NEW_LINE)
240
241             if (def instanceof Single) {
242                 val node = def.node
243                 sb.append("<p>\n")
244                 .append("This class represents the following YANG schema fragment defined in module <b>")
245                 .append(def.module.argument).append("</b>\n")
246                 .append("<pre>\n")
247                 appendYangSnippet(sb, def.module, (node as EffectiveStatement<?, ?>).declared)
248                 sb.append("</pre>")
249
250                 if (node instanceof SchemaNode) {
251                     sb.append("The schema path to identify an instance is\n")
252                     .append("<i>")
253                     .append(formatSchemaPath(def.module.argument, node.path.pathFromRoot))
254                     .append("</i>\n")
255
256                     if (hasBuilderClass(node)) {
257                         val builderName = type.name + "Builder";
258
259                         sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
260                         .append("}.\n")
261                         .append("@see ").append(builderName).append('\n')
262                         if (node instanceof ListSchemaNode) {
263                             val keyDef = node.keyDefinition
264                             if (keyDef !== null && !keyDef.empty) {
265                                 sb.append("@see ").append(type.name).append("Key")
266                             }
267                             sb.append('\n');
268                         }
269                     }
270                 }
271             } else if (def instanceof Multiple) {
272                 sb.append("<pre>\n")
273                 for (SchemaNode node : def.nodes) {
274                     appendYangSnippet(sb, def.module, (node as EffectiveStatement<?, ?>).declared)
275                 }
276                 sb.append("</pre>\n")
277             }
278         }
279     }
280
281     def private static void appendYangSnippet(StringBuilder sb, ModuleEffectiveStatement module,
282             DeclaredStatement<?> stmt) {
283         for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
284             sb.append(encodeAngleBrackets(encodeJavadocSymbols(str)))
285         }
286     }
287
288     def private static boolean hasBuilderClass(SchemaNode schemaNode) {
289         return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
290                 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
291     }
292
293     def private static String formatSchemaPath(String moduleName, Iterable<QName> schemaPath) {
294         val sb = new StringBuilder().append(moduleName);
295
296         var currentElement = Iterables.getFirst(schemaPath, null);
297         for (QName pathElement : schemaPath) {
298             sb.append('/')
299             if (!currentElement.namespace.equals(pathElement.namespace)) {
300                 currentElement = pathElement
301                 sb.append(pathElement)
302             } else {
303                 sb.append(pathElement.getLocalName())
304             }
305         }
306         return sb.toString();
307     }
308
309     def protected String formatDataForJavaDoc(TypeMember type, String additionalComment) {
310         val StringBuilder typeDescriptionBuilder = new StringBuilder();
311         if (!type.comment.nullOrEmpty) {
312             typeDescriptionBuilder.append(formatToParagraph(type.comment))
313             typeDescriptionBuilder.append(NEW_LINE)
314             typeDescriptionBuilder.append(NEW_LINE)
315             typeDescriptionBuilder.append(NEW_LINE)
316         }
317         typeDescriptionBuilder.append(additionalComment)
318         var typeDescription = wrapToDocumentation(typeDescriptionBuilder.toString)
319         return '''
320             «typeDescription»
321         '''.toString
322     }
323
324     def asCode(String text) {
325         return "<code>" + text + "</code>"
326     }
327
328     def asLink(String text) {
329         val StringBuilder sb = new StringBuilder()
330         var tempText = text
331         var char lastChar = ' '
332         var boolean badEnding = false
333
334         if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
335             tempText = text.substring(0, text.length - 1)
336             lastChar = text.charAt(text.length - 1)
337             badEnding = true
338         }
339         sb.append("<a href = \"")
340         sb.append(tempText)
341         sb.append("\">")
342         sb.append(tempText)
343         sb.append("</a>")
344
345         if(badEnding)
346             sb.append(lastChar)
347
348         return sb.toString
349     }
350
351     protected def formatToParagraph(String text) {
352         if(text === null || text.isEmpty)
353             return text
354
355         var formattedText = text
356         val StringBuilder sb = new StringBuilder();
357         var StringBuilder lineBuilder = new StringBuilder();
358         var boolean isFirstElementOnNewLineEmptyChar = false;
359
360         formattedText = encodeJavadocSymbols(formattedText)
361         formattedText = NL_MATCHER.removeFrom(formattedText)
362         formattedText = TAB_MATCHER.removeFrom(formattedText)
363         formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
364
365         val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
366
367         while (tokenizer.hasMoreElements) {
368             val nextElement = tokenizer.nextElement.toString
369
370             if (lineBuilder.length != 0 && lineBuilder.length + nextElement.length > 80) {
371                 if (lineBuilder.charAt(lineBuilder.length - 1) == ' ') {
372                     lineBuilder.setLength(0)
373                     lineBuilder.append(lineBuilder.substring(0, lineBuilder.length - 1))
374                 }
375                 if (lineBuilder.charAt(0) == ' ') {
376                     lineBuilder.setLength(0)
377                     lineBuilder.append(lineBuilder.substring(1))
378                 }
379
380                 sb.append(lineBuilder);
381                 lineBuilder.setLength(0)
382                 sb.append(NEW_LINE)
383
384                 if(nextElement.toString == ' ') {
385                     isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
386                 }
387             }
388
389             if (isFirstElementOnNewLineEmptyChar) {
390                 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
391             }
392
393             else {
394                 lineBuilder.append(nextElement)
395             }
396         }
397         sb.append(lineBuilder)
398         sb.append(NEW_LINE)
399
400         return sb.toString
401     }
402
403     def protected generateToString(Collection<GeneratedProperty> properties) '''
404         «IF !properties.empty»
405             @Override
406             public «String.importedName» toString() {
407                 final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper(«type.importedName».class);
408                 «FOR property : properties»
409                     «CodeHelpers.importedName».appendValue(helper, "«property.fieldName»", «property.fieldName»);
410                 «ENDFOR»
411                 return helper.toString();
412             }
413         «ENDIF»
414     '''
415
416     /**
417      * Template method which generates method parameters with their types from <code>parameters</code>.
418      *
419      * @param parameters
420      * list of parameter instances which are transformed to the method parameters
421      * @return string with the list of the method parameters with their types in JAVA format
422      */
423     def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
424         IF !parameters.empty»«
425             FOR parameter : parameters SEPARATOR ", "»«
426                 parameter.type.importedName» «parameter.name»«
427             ENDFOR»«
428         ENDIF
429     »'''
430
431     def protected emitConstant(Constant c) '''
432         «IF c.value instanceof QName»
433             «val qname = c.value as QName»
434             «val rev = qname.revision»
435             public static final «c.type.importedName» «c.name» = «QName.name».create("«qname.namespace.toString»",
436                 «IF rev.isPresent»"«rev.get»", «ENDIF»"«qname.localName»").intern();
437         «ELSE»
438             public static final «c.type.importedName» «c.name» = «c.value»;
439         «ENDIF»
440     '''
441
442     def static Restrictions getRestrictions(Type type) {
443         if (type instanceof ConcreteType) {
444             return type.restrictions
445         }
446         if (type instanceof GeneratedTransferObject) {
447             return type.restrictions
448         }
449         return null
450     }
451 }