409b1266c2c3b946b1bb9a8bd70456e775e06423
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / yangtools / sal / 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.yangtools.sal.java.api.generator
9
10 import com.google.common.base.CharMatcher
11 import com.google.common.base.Splitter
12 import java.util.Arrays
13 import java.util.Collection
14 import java.util.HashMap
15 import java.util.List
16 import java.util.Map
17 import java.util.StringTokenizer
18 import java.util.regex.Pattern
19 import org.opendaylight.yangtools.binding.generator.util.Types
20 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType
21 import org.opendaylight.yangtools.sal.binding.model.api.Constant
22 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty
23 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject
24 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
25 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature
26 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions
27 import org.opendaylight.yangtools.sal.binding.model.api.Type
28 import org.opendaylight.yangtools.sal.binding.model.api.TypeMember
29 import org.opendaylight.yangtools.yang.common.QName
30
31 abstract class BaseTemplate {
32     protected val GeneratedType type;
33     protected val Map<String, String> importMap;
34
35     private static final char NEW_LINE = '\n'
36     private static final CharMatcher NL_MATCHER = CharMatcher.is(NEW_LINE)
37     private static final CharMatcher TAB_MATCHER = CharMatcher.is('\t')
38     private static final Pattern SPACES_PATTERN = Pattern.compile(" +")
39     private static final Splitter NL_SPLITTER = Splitter.on(NL_MATCHER)
40
41     new(GeneratedType _type) {
42         if (_type == null) {
43             throw new IllegalArgumentException("Generated type reference cannot be NULL!")
44         }
45         this.type = _type;
46         this.importMap = new HashMap<String,String>()
47     }
48
49     def packageDefinition() '''package «type.packageName»;'''
50
51     final public def generate() {
52         val _body = body()
53         '''
54             «packageDefinition»
55             «imports»
56
57             «_body»
58         '''.toString
59     }
60
61     protected def imports() '''
62         «IF !importMap.empty»
63             «FOR entry : importMap.entrySet»
64                 «IF !hasSamePackage(entry.value)»
65                     import «entry.value».«entry.key»;
66                 «ENDIF»
67             «ENDFOR»
68         «ENDIF»
69
70     '''
71
72     /**
73      * Checks if packages of generated type and imported type is the same
74      *
75      * @param importedTypePackageNam
76      * the package name of imported type
77      * @return true if the packages are the same false otherwise
78      */
79     final private def boolean hasSamePackage(String importedTypePackageName) {
80         return type.packageName.equals(importedTypePackageName);
81     }
82
83     protected abstract def CharSequence body();
84
85     // Helper patterns
86     final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
87
88     final protected def propertyNameFromGetter(MethodSignature getter) {
89         var int prefix;
90         if (getter.name.startsWith("is")) {
91             prefix = 2
92         } else if (getter.name.startsWith("get")) {
93             prefix = 3
94         } else {
95             throw new IllegalArgumentException("Not a getter")
96         }
97         return getter.name.substring(prefix).toFirstLower;
98     }
99
100     final protected def isAccessor(MethodSignature maybeGetter) {
101         return maybeGetter.name.startsWith("is") || maybeGetter.name.startsWith("get");
102     }
103
104     /**
105      * Template method which generates the getter method for <code>field</code>
106      *
107      * @param field
108      * generated property with data about field which is generated as the getter method
109      * @return string with the getter method source code in JAVA format
110      */
111     protected def getterMethod(GeneratedProperty field) {
112         '''
113             public «field.returnType.importedName» «field.getterMethodName»() {
114                 «IF field.returnType.importedName.contains("[]")»
115                 return «field.fieldName» == null ? null : «field.fieldName».clone();
116                 «ELSE»
117                 return «field.fieldName»;
118                 «ENDIF»
119             }
120         '''
121     }
122
123     final protected def getterMethodName(GeneratedProperty field) {
124         val prefix = if(field.returnType.equals(Types.BOOLEAN)) "is" else "get"
125         return '''«prefix»«field.name.toFirstUpper»'''
126     }
127
128     /**
129      * Template method which generates the setter method for <code>field</code>
130      *
131      * @param field
132      * generated property with data about field which is generated as the setter method
133      * @return string with the setter method source code in JAVA format
134      */
135     final protected def setterMethod(GeneratedProperty field) '''
136         «val returnType = field.returnType.importedName»
137         public «type.name» set«field.name.toFirstUpper»(«returnType» value) {
138             this.«field.fieldName» = value;
139             return this;
140         }
141     '''
142
143     final protected def importedName(Type intype) {
144         GeneratorUtil.putTypeIntoImports(type, intype, importMap);
145         GeneratorUtil.getExplicitType(type, intype, importMap)
146     }
147
148     final protected def importedName(Class<?> cls) {
149         importedName(Types.typeForClass(cls))
150     }
151
152     /**
153      * Template method which generates method parameters with their types from <code>parameters</code>.
154      *
155      * @param parameters
156      * group of generated property instances which are transformed to the method parameters
157      * @return string with the list of the method parameters with their types in JAVA format
158      */
159     def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
160         returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
161
162     /**
163      * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
164      *
165      * @param parameters
166      * group of generated property instances which are transformed to the sequence of parameter names
167      * @return string with the list of the parameter names of the <code>parameters</code>
168      */
169     def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
170         fieldName»«ENDFOR»«ENDIF»'''
171
172     /**
173      * Template method which generates JAVA comments.
174      *
175      * @param comment string with the comment for whole JAVA class
176      * @return string with comment in JAVA format
177      */
178     def protected CharSequence asJavadoc(String comment) {
179         if(comment == null) return ''
180         var txt = comment
181
182         txt = comment.trim
183         txt = formatToParagraph(txt)
184
185         return '''
186             «wrapToDocumentation(txt)»
187         '''
188     }
189
190     def String wrapToDocumentation(String text) {
191         if (text.empty)
192             return ""
193
194         val StringBuilder sb = new StringBuilder("/**")
195         sb.append(NEW_LINE)
196
197         for (String t : NL_SPLITTER.split(text)) {
198             sb.append(" *")
199             if (!t.isEmpty()) {
200                 sb.append(' ');
201                 sb.append(t)
202             }
203             sb.append(NEW_LINE)
204         }
205         sb.append(" */")
206
207         return sb.toString
208     }
209
210     def protected String formatDataForJavaDoc(GeneratedType type) {
211         val typeDescription = type.getDescription().encodeJavadocSymbols;
212
213         return '''
214             «IF !typeDescription.nullOrEmpty»
215             «typeDescription»
216             «ENDIF»
217         '''.toString
218     }
219
220     private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
221
222     def encodeJavadocSymbols(String description) {
223         if (description.nullOrEmpty) {
224             return description;
225         }
226
227         var ret = description.replace("*/", "&#42;&#47;");
228         ret = AMP_MATCHER.replaceFrom(ret, "&amp;");
229
230         return ret;
231     }
232
233     def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) {
234         val StringBuilder typeDescription = new StringBuilder();
235         if (!type.description.nullOrEmpty) {
236             typeDescription.append(type.description)
237             typeDescription.append(NEW_LINE)
238             typeDescription.append(NEW_LINE)
239             typeDescription.append(NEW_LINE)
240             typeDescription.append(additionalComment)
241         } else {
242             typeDescription.append(additionalComment)
243         }
244
245         return '''
246             «typeDescription.toString»
247         '''.toString
248     }
249
250     def protected String formatDataForJavaDoc(TypeMember type, String additionalComment) {
251         val StringBuilder typeDescriptionBuilder = new StringBuilder();
252         if (!type.comment.nullOrEmpty) {
253             typeDescriptionBuilder.append(formatToParagraph(type.comment))
254             typeDescriptionBuilder.append(NEW_LINE)
255             typeDescriptionBuilder.append(NEW_LINE)
256             typeDescriptionBuilder.append(NEW_LINE)
257         }
258         typeDescriptionBuilder.append(additionalComment)
259         var typeDescription = wrapToDocumentation(typeDescriptionBuilder.toString)
260         return '''
261             «typeDescription»
262         '''.toString
263     }
264
265     def asCode(String text) {
266         return "<code>" + text + "</code>"
267     }
268
269     def asLink(String text) {
270         val StringBuilder sb = new StringBuilder()
271         var tempText = text
272         var char lastChar = ' '
273         var boolean badEnding = false
274
275         if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
276             tempText = text.substring(0, text.length - 1)
277             lastChar = text.charAt(text.length - 1)
278             badEnding = true
279         }
280         sb.append("<a href = \"")
281         sb.append(tempText)
282         sb.append("\">")
283         sb.append(tempText)
284         sb.append("</a>")
285
286         if(badEnding)
287             sb.append(lastChar)
288
289         return sb.toString
290     }
291
292     protected def formatToParagraph(String text) {
293         if(text == null || text.isEmpty)
294             return text
295
296         var formattedText = text
297         val StringBuilder sb = new StringBuilder();
298         var StringBuilder lineBuilder = new StringBuilder();
299         var boolean isFirstElementOnNewLineEmptyChar = false;
300
301         formattedText = encodeJavadocSymbols(formattedText)
302         formattedText = NL_MATCHER.removeFrom(formattedText)
303         formattedText = TAB_MATCHER.removeFrom(formattedText)
304         formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
305
306         val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
307
308         while(tokenizer.hasMoreElements) {
309             val nextElement = tokenizer.nextElement.toString
310
311             if(lineBuilder.length + nextElement.length > 80) {
312                 if (lineBuilder.charAt(lineBuilder.length - 1) == ' ') {
313                     lineBuilder.setLength(0)
314                     lineBuilder.append(lineBuilder.substring(0, lineBuilder.length - 1))
315                 }
316                 if (lineBuilder.charAt(0) == ' ') {
317                     lineBuilder.setLength(0)
318                     lineBuilder.append(lineBuilder.substring(1))
319                 }
320
321                 sb.append(lineBuilder);
322                 lineBuilder.setLength(0)
323                 sb.append(NEW_LINE)
324
325                 if(nextElement.toString == ' ') {
326                     isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
327                 }
328             }
329
330             if(isFirstElementOnNewLineEmptyChar) {
331                 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
332             }
333
334             else {
335                 lineBuilder.append(nextElement)
336             }
337         }
338         sb.append(lineBuilder)
339         sb.append(NEW_LINE)
340
341         return sb.toString
342     }
343
344     def protected generateToString(Collection<GeneratedProperty> properties) '''
345         «IF !properties.empty»
346             @Override
347             public «String.importedName» toString() {
348                 «StringBuilder.importedName» builder = new «StringBuilder.importedName»(«type.importedName».class.getSimpleName()).append(" [");
349                 boolean first = true;
350
351                 «FOR property : properties»
352                     if («property.fieldName» != null) {
353                         if (first) {
354                             first = false;
355                         } else {
356                             builder.append(", ");
357                         }
358                         builder.append("«property.fieldName»=");
359                         «IF property.returnType.name.contains("[")»
360                             builder.append(«Arrays.importedName».toString(«property.fieldName»));
361                         «ELSE»
362                             builder.append(«property.fieldName»);
363                         «ENDIF»
364                      }
365                 «ENDFOR»
366                 return builder.append(']').toString();
367             }
368         «ENDIF»
369     '''
370
371     def getRestrictions(Type type) {
372         var Restrictions restrictions = null
373         if (type instanceof ConcreteType) {
374             restrictions = type.restrictions
375         } else if (type instanceof GeneratedTransferObject) {
376             restrictions = type.restrictions
377         }
378         return restrictions
379     }
380
381     /**
382      * Template method which generates method parameters with their types from <code>parameters</code>.
383      *
384      * @param parameters
385      * list of parameter instances which are transformed to the method parameters
386      * @return string with the list of the method parameters with their types in JAVA format
387      */
388     def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
389         IF !parameters.empty»«
390             FOR parameter : parameters SEPARATOR ", "»«
391                 parameter.type.importedName» «parameter.name»«
392             ENDFOR»«
393         ENDIF
394     »'''
395
396     def protected GeneratedProperty findProperty(GeneratedTransferObject gto, String name) {
397         val props = gto.properties
398         for (prop : props) {
399             if (prop.name.equals(name)) {
400                 return prop
401             }
402         }
403         val GeneratedTransferObject parent = gto.superType
404         if (parent != null) {
405             return findProperty(parent, name)
406         }
407         return null
408     }
409
410     def protected emitConstant(Constant c) '''
411         «IF c.value instanceof QName»
412             «val qname = c.value as QName»
413             public static final «c.type.importedName» «c.name» = «QName.name».create("«qname.namespace.toString»",
414                 "«qname.formattedRevision»", "«qname.localName»").intern();
415         «ELSE»
416             public static final «c.type.importedName» «c.name» = «c.value»;
417         «ENDIF»
418     '''
419 }