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)
40 private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
42 new(GeneratedType _type) {
44 throw new IllegalArgumentException("Generated type reference cannot be NULL!")
47 this.importMap = new HashMap<String,String>()
50 def packageDefinition() '''package «type.packageName»;'''
52 final public def generate() {
62 protected def imports() '''
63 «FOR entry : importMap.entrySet»
64 «IF !hasSamePackage(entry.value) && !isLocalInnerClass(entry.value)»
65 import «entry.value».«entry.key»;
71 * Checks if packages of generated type and imported type is the same
73 * @param importedTypePackageName the package name of imported type
74 * @return true if the packages are the same false otherwise
76 final private def boolean hasSamePackage(String importedTypePackageName) {
77 return type.packageName.equals(importedTypePackageName);
80 def isLocalInnerClass(String importedTypePackageName) {
81 return type.fullyQualifiedName.equals(importedTypePackageName);
84 protected abstract def CharSequence body();
87 final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
89 final protected def propertyNameFromGetter(MethodSignature getter) {
91 if (getter.name.startsWith("is")) {
93 } else if (getter.name.startsWith("get")) {
96 throw new IllegalArgumentException("Not a getter")
98 return getter.name.substring(prefix).toFirstLower;
101 final protected def isAccessor(MethodSignature maybeGetter) {
102 return maybeGetter.name.startsWith("is") || maybeGetter.name.startsWith("get");
106 * Template method which generates the getter method for <code>field</code>
109 * generated property with data about field which is generated as the getter method
110 * @return string with the getter method source code in JAVA format
112 protected def getterMethod(GeneratedProperty field) {
114 public «field.returnType.importedName» «field.getterMethodName»() {
115 «IF field.returnType.importedName.contains("[]")»
116 return «field.fieldName» == null ? null : «field.fieldName».clone();
118 return «field.fieldName»;
124 final protected def getterMethodName(GeneratedProperty field) {
125 val prefix = if(field.returnType.equals(Types.BOOLEAN)) "is" else "get"
126 return '''«prefix»«field.name.toFirstUpper»'''
130 * Template method which generates the setter method for <code>field</code>
133 * generated property with data about field which is generated as the setter method
134 * @return string with the setter method source code in JAVA format
136 final protected def setterMethod(GeneratedProperty field) '''
137 «val returnType = field.returnType.importedName»
138 public «type.name» set«field.name.toFirstUpper»(«returnType» value) {
139 this.«field.fieldName» = value;
144 final protected def importedName(Type intype) {
145 GeneratorUtil.putTypeIntoImports(type, intype, importMap);
146 GeneratorUtil.getExplicitType(type, intype, importMap)
149 final protected def importedName(Class<?> cls) {
150 importedName(Types.typeForClass(cls))
154 * Template method which generates method parameters with their types from <code>parameters</code>.
157 * group of generated property instances which are transformed to the method parameters
158 * @return string with the list of the method parameters with their types in JAVA format
160 def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
161 returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
164 * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
167 * group of generated property instances which are transformed to the sequence of parameter names
168 * @return string with the list of the parameter names of the <code>parameters</code>
170 def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
171 fieldName»«ENDFOR»«ENDIF»'''
174 * Template method which generates JAVA comments.
176 * @param comment string with the comment for whole JAVA class
177 * @return string with comment in JAVA format
179 def protected CharSequence asJavadoc(String comment) {
180 if(comment === null) return ''
184 txt = formatToParagraph(txt)
187 «wrapToDocumentation(txt)»
191 def String wrapToDocumentation(String text) {
195 val StringBuilder sb = new StringBuilder("/**")
198 for (String t : NL_SPLITTER.split(text)) {
211 def protected String formatDataForJavaDoc(GeneratedType type) {
212 val typeDescription = type.getDescription().encodeJavadocSymbols;
215 «IF !typeDescription.nullOrEmpty»
221 private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
223 def encodeJavadocSymbols(String description) {
224 if (description.nullOrEmpty) {
228 return AMP_MATCHER.replaceFrom(TAIL_COMMENT_PATTERN.matcher(description).replaceAll("*/"), "&");
231 def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) {
232 val StringBuilder typeDescription = new StringBuilder();
233 if (!type.description.nullOrEmpty) {
234 typeDescription.append(type.description)
235 typeDescription.append(NEW_LINE)
236 typeDescription.append(NEW_LINE)
237 typeDescription.append(NEW_LINE)
238 typeDescription.append(additionalComment)
240 typeDescription.append(additionalComment)
244 «typeDescription.toString»
248 def protected String formatDataForJavaDoc(TypeMember type, String additionalComment) {
249 val StringBuilder typeDescriptionBuilder = new StringBuilder();
250 if (!type.comment.nullOrEmpty) {
251 typeDescriptionBuilder.append(formatToParagraph(type.comment))
252 typeDescriptionBuilder.append(NEW_LINE)
253 typeDescriptionBuilder.append(NEW_LINE)
254 typeDescriptionBuilder.append(NEW_LINE)
256 typeDescriptionBuilder.append(additionalComment)
257 var typeDescription = wrapToDocumentation(typeDescriptionBuilder.toString)
263 def asCode(String text) {
264 return "<code>" + text + "</code>"
267 def asLink(String text) {
268 val StringBuilder sb = new StringBuilder()
270 var char lastChar = ' '
271 var boolean badEnding = false
273 if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
274 tempText = text.substring(0, text.length - 1)
275 lastChar = text.charAt(text.length - 1)
278 sb.append("<a href = \"")
290 protected def formatToParagraph(String text) {
291 if(text === null || text.isEmpty)
294 var formattedText = text
295 val StringBuilder sb = new StringBuilder();
296 var StringBuilder lineBuilder = new StringBuilder();
297 var boolean isFirstElementOnNewLineEmptyChar = false;
299 formattedText = encodeJavadocSymbols(formattedText)
300 formattedText = NL_MATCHER.removeFrom(formattedText)
301 formattedText = TAB_MATCHER.removeFrom(formattedText)
302 formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
304 val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
306 while (tokenizer.hasMoreElements) {
307 val nextElement = tokenizer.nextElement.toString
309 if (lineBuilder.length != 0 && lineBuilder.length + nextElement.length > 80) {
310 if (lineBuilder.charAt(lineBuilder.length - 1) == ' ') {
311 lineBuilder.setLength(0)
312 lineBuilder.append(lineBuilder.substring(0, lineBuilder.length - 1))
314 if (lineBuilder.charAt(0) == ' ') {
315 lineBuilder.setLength(0)
316 lineBuilder.append(lineBuilder.substring(1))
319 sb.append(lineBuilder);
320 lineBuilder.setLength(0)
323 if(nextElement.toString == ' ') {
324 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
328 if (isFirstElementOnNewLineEmptyChar) {
329 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
333 lineBuilder.append(nextElement)
336 sb.append(lineBuilder)
342 def protected generateToString(Collection<GeneratedProperty> properties) '''
343 «IF !properties.empty»
345 public «String.importedName» toString() {
346 «StringBuilder.importedName» builder = new «StringBuilder.importedName»(«type.importedName».class.getSimpleName()).append(" [");
347 boolean first = true;
349 «FOR property : properties»
350 if («property.fieldName» != null) {
354 builder.append(", ");
356 builder.append("«property.fieldName»=");
357 «IF property.returnType.name.contains("[")»
358 builder.append(«Arrays.importedName».toString(«property.fieldName»));
360 builder.append(«property.fieldName»);
364 return builder.append(']').toString();
369 def getRestrictions(Type type) {
370 var Restrictions restrictions = null
371 if (type instanceof ConcreteType) {
372 restrictions = type.restrictions
373 } else if (type instanceof GeneratedTransferObject) {
374 restrictions = type.restrictions
380 * Template method which generates method parameters with their types from <code>parameters</code>.
383 * list of parameter instances which are transformed to the method parameters
384 * @return string with the list of the method parameters with their types in JAVA format
386 def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
387 IF !parameters.empty»«
388 FOR parameter : parameters SEPARATOR ", "»«
389 parameter.type.importedName» «parameter.name»«
394 def protected GeneratedProperty findProperty(GeneratedTransferObject gto, String name) {
395 val props = gto.properties
397 if (prop.name.equals(name)) {
401 val GeneratedTransferObject parent = gto.superType
402 if (parent !== null) {
403 return findProperty(parent, name)
408 def protected emitConstant(Constant c) '''
409 «IF c.value instanceof QName»
410 «val qname = c.value as QName»
411 public static final «c.type.importedName» «c.name» = «QName.name».create("«qname.namespace.toString»",
412 "«qname.formattedRevision»", "«qname.localName»").intern();
414 public static final «c.type.importedName» «c.name» = «c.value»;