2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.java.api.generator
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
17 import java.util.StringTokenizer
18 import java.util.regex.Pattern
19 import org.opendaylight.mdsal.binding.model.api.ConcreteType
20 import org.opendaylight.mdsal.binding.model.api.Constant
21 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
22 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
23 import org.opendaylight.mdsal.binding.model.api.GeneratedType
24 import org.opendaylight.mdsal.binding.model.api.MethodSignature
25 import org.opendaylight.mdsal.binding.model.api.Restrictions
26 import org.opendaylight.mdsal.binding.model.api.Type
27 import org.opendaylight.mdsal.binding.model.api.TypeMember
28 import org.opendaylight.mdsal.binding.model.util.Types
29 import org.opendaylight.yangtools.yang.common.QName
31 abstract class BaseTemplate {
32 protected val GeneratedType type;
33 protected val Map<String, String> importMap;
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)
41 new(GeneratedType _type) {
43 throw new IllegalArgumentException("Generated type reference cannot be NULL!")
46 this.importMap = new HashMap<String,String>()
49 def packageDefinition() '''package «type.packageName»;'''
51 final public def generate() {
61 protected def imports() '''
63 «FOR entry : importMap.entrySet»
64 «IF !hasSamePackage(entry.value)»
65 import «entry.value».«entry.key»;
73 * Checks if packages of generated type and imported type is the same
75 * @param importedTypePackageNam
76 * the package name of imported type
77 * @return true if the packages are the same false otherwise
79 final private def boolean hasSamePackage(String importedTypePackageName) {
80 return type.packageName.equals(importedTypePackageName);
83 protected abstract def CharSequence body();
86 final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
88 final protected def propertyNameFromGetter(MethodSignature getter) {
90 if (getter.name.startsWith("is")) {
92 } else if (getter.name.startsWith("get")) {
95 throw new IllegalArgumentException("Not a getter")
97 return getter.name.substring(prefix).toFirstLower;
100 final protected def isAccessor(MethodSignature maybeGetter) {
101 return maybeGetter.name.startsWith("is") || maybeGetter.name.startsWith("get");
105 * Template method which generates the getter method for <code>field</code>
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
111 protected def getterMethod(GeneratedProperty field) {
113 public «field.returnType.importedName» «field.getterMethodName»() {
114 «IF field.returnType.importedName.contains("[]")»
115 return «field.fieldName» == null ? null : «field.fieldName».clone();
117 return «field.fieldName»;
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»'''
129 * Template method which generates the setter method for <code>field</code>
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
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;
143 final protected def importedName(Type intype) {
144 GeneratorUtil.putTypeIntoImports(type, intype, importMap);
145 GeneratorUtil.getExplicitType(type, intype, importMap)
148 final protected def importedName(Class<?> cls) {
149 importedName(Types.typeForClass(cls))
153 * Template method which generates method parameters with their types from <code>parameters</code>.
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
159 def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
160 returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
163 * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
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>
169 def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
170 fieldName»«ENDFOR»«ENDIF»'''
173 * Template method which generates JAVA comments.
175 * @param comment string with the comment for whole JAVA class
176 * @return string with comment in JAVA format
178 def protected CharSequence asJavadoc(String comment) {
179 if(comment === null) return ''
183 txt = formatToParagraph(txt)
186 «wrapToDocumentation(txt)»
190 def String wrapToDocumentation(String text) {
194 val StringBuilder sb = new StringBuilder("/**")
197 for (String t : NL_SPLITTER.split(text)) {
210 def protected String formatDataForJavaDoc(GeneratedType type) {
211 val typeDescription = type.getDescription().encodeJavadocSymbols;
214 «IF !typeDescription.nullOrEmpty»
220 private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
222 def encodeJavadocSymbols(String description) {
223 if (description.nullOrEmpty) {
227 var ret = description.replace("*/", "*/");
228 ret = AMP_MATCHER.replaceFrom(ret, "&");
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)
242 typeDescription.append(additionalComment)
246 «typeDescription.toString»
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)
258 typeDescriptionBuilder.append(additionalComment)
259 var typeDescription = wrapToDocumentation(typeDescriptionBuilder.toString)
265 def asCode(String text) {
266 return "<code>" + text + "</code>"
269 def asLink(String text) {
270 val StringBuilder sb = new StringBuilder()
272 var char lastChar = ' '
273 var boolean badEnding = false
275 if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
276 tempText = text.substring(0, text.length - 1)
277 lastChar = text.charAt(text.length - 1)
280 sb.append("<a href = \"")
292 protected def formatToParagraph(String text) {
293 if(text === null || text.isEmpty)
296 var formattedText = text
297 val StringBuilder sb = new StringBuilder();
298 var StringBuilder lineBuilder = new StringBuilder();
299 var boolean isFirstElementOnNewLineEmptyChar = false;
301 formattedText = encodeJavadocSymbols(formattedText)
302 formattedText = NL_MATCHER.removeFrom(formattedText)
303 formattedText = TAB_MATCHER.removeFrom(formattedText)
304 formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
306 val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
308 while (tokenizer.hasMoreElements) {
309 val nextElement = tokenizer.nextElement.toString
311 if (lineBuilder.length != 0 && 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))
316 if (lineBuilder.charAt(0) == ' ') {
317 lineBuilder.setLength(0)
318 lineBuilder.append(lineBuilder.substring(1))
321 sb.append(lineBuilder);
322 lineBuilder.setLength(0)
325 if(nextElement.toString == ' ') {
326 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
330 if (isFirstElementOnNewLineEmptyChar) {
331 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
335 lineBuilder.append(nextElement)
338 sb.append(lineBuilder)
344 def protected generateToString(Collection<GeneratedProperty> properties) '''
345 «IF !properties.empty»
347 public «String.importedName» toString() {
348 «StringBuilder.importedName» builder = new «StringBuilder.importedName»(«type.importedName».class.getSimpleName()).append(" [");
349 boolean first = true;
351 «FOR property : properties»
352 if («property.fieldName» != null) {
356 builder.append(", ");
358 builder.append("«property.fieldName»=");
359 «IF property.returnType.name.contains("[")»
360 builder.append(«Arrays.importedName».toString(«property.fieldName»));
362 builder.append(«property.fieldName»);
366 return builder.append(']').toString();
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
382 * Template method which generates method parameters with their types from <code>parameters</code>.
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
388 def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
389 IF !parameters.empty»«
390 FOR parameter : parameters SEPARATOR ", "»«
391 parameter.type.importedName» «parameter.name»«
396 def protected GeneratedProperty findProperty(GeneratedTransferObject gto, String name) {
397 val props = gto.properties
399 if (prop.name.equals(name)) {
403 val GeneratedTransferObject parent = gto.superType
404 if (parent !== null) {
405 return findProperty(parent, name)
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();
416 public static final «c.type.importedName» «c.name» = «c.value»;