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