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