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