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 static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.encodeAngleBrackets
12 import com.google.common.base.CharMatcher
13 import com.google.common.base.Splitter
14 import com.google.common.collect.Iterables
15 import java.util.Arrays
16 import java.util.Collection
17 import java.util.HashMap
20 import java.util.StringTokenizer
21 import java.util.regex.Pattern
22 import org.opendaylight.mdsal.binding.model.api.ConcreteType
23 import org.opendaylight.mdsal.binding.model.api.Constant
24 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
25 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
26 import org.opendaylight.mdsal.binding.model.api.GeneratedType
27 import org.opendaylight.mdsal.binding.model.api.MethodSignature
28 import org.opendaylight.mdsal.binding.model.api.Restrictions
29 import org.opendaylight.mdsal.binding.model.api.Type
30 import org.opendaylight.mdsal.binding.model.api.TypeMember
31 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single
32 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple
33 import org.opendaylight.mdsal.binding.model.util.Types
34 import org.opendaylight.yangtools.yang.common.QName
35 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
36 import org.opendaylight.yangtools.yang.model.api.DocumentedNode
37 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
38 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition
39 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode
42 abstract class BaseTemplate {
43 protected val GeneratedType type;
44 protected val Map<String, String> importMap;
46 private static final char NEW_LINE = '\n'
47 private static final CharMatcher NL_MATCHER = CharMatcher.is(NEW_LINE)
48 private static final CharMatcher TAB_MATCHER = CharMatcher.is('\t')
49 private static final Pattern SPACES_PATTERN = Pattern.compile(" +")
50 private static final Splitter NL_SPLITTER = Splitter.on(NL_MATCHER)
51 private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
53 new(GeneratedType _type) {
55 throw new IllegalArgumentException("Generated type reference cannot be NULL!")
58 this.importMap = new HashMap<String,String>()
61 def packageDefinition() '''package «type.packageName»;'''
63 final public def generate() {
73 protected def imports() '''
74 «FOR entry : importMap.entrySet»
75 «IF !hasSamePackage(entry.value) && !isLocalInnerClass(entry.value)»
76 import «entry.value».«entry.key»;
82 * Checks if packages of generated type and imported type is the same
84 * @param importedTypePackageName the package name of imported type
85 * @return true if the packages are the same false otherwise
87 final private def boolean hasSamePackage(String importedTypePackageName) {
88 return type.packageName.equals(importedTypePackageName);
91 def isLocalInnerClass(String importedTypePackageName) {
92 return type.fullyQualifiedName.equals(importedTypePackageName);
95 protected abstract def CharSequence body();
98 final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
100 final protected def propertyNameFromGetter(MethodSignature getter) {
102 if (getter.name.startsWith("is")) {
104 } else if (getter.name.startsWith("get")) {
107 throw new IllegalArgumentException("Not a getter")
109 return getter.name.substring(prefix).toFirstLower;
112 final protected def isAccessor(MethodSignature maybeGetter) {
113 return maybeGetter.name.startsWith("is") || maybeGetter.name.startsWith("get");
117 * Template method which generates the getter method for <code>field</code>
120 * generated property with data about field which is generated as the getter method
121 * @return string with the getter method source code in JAVA format
123 protected def getterMethod(GeneratedProperty field) {
125 public «field.returnType.importedName» «field.getterMethodName»() {
126 «IF field.returnType.importedName.contains("[]")»
127 return «field.fieldName» == null ? null : «field.fieldName».clone();
129 return «field.fieldName»;
135 final protected def getterMethodName(GeneratedProperty field) {
136 val prefix = if(field.returnType.equals(Types.BOOLEAN)) "is" else "get"
137 return '''«prefix»«field.name.toFirstUpper»'''
141 * Template method which generates the setter method for <code>field</code>
144 * generated property with data about field which is generated as the setter method
145 * @return string with the setter method source code in JAVA format
147 final protected def setterMethod(GeneratedProperty field) '''
148 «val returnType = field.returnType.importedName»
149 public «type.name» set«field.name.toFirstUpper»(«returnType» value) {
150 this.«field.fieldName» = value;
155 final protected def importedName(Type intype) {
156 GeneratorUtil.putTypeIntoImports(type, intype, importMap);
157 GeneratorUtil.getExplicitType(type, intype, importMap)
160 final protected def importedName(Class<?> cls) {
161 importedName(Types.typeForClass(cls))
165 * Template method which generates method parameters with their types from <code>parameters</code>.
168 * group of generated property instances which are transformed to the method parameters
169 * @return string with the list of the method parameters with their types in JAVA format
171 def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
172 returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
175 * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
178 * group of generated property instances which are transformed to the sequence of parameter names
179 * @return string with the list of the parameter names of the <code>parameters</code>
181 def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
182 fieldName»«ENDFOR»«ENDIF»'''
185 * Template method which generates JAVA comments.
187 * @param comment string with the comment for whole JAVA class
188 * @return string with comment in JAVA format
190 def protected CharSequence asJavadoc(String comment) {
191 if(comment === null) return ''
195 txt = formatToParagraph(txt)
198 «wrapToDocumentation(txt)»
202 def String wrapToDocumentation(String text) {
206 val StringBuilder sb = new StringBuilder("/**")
209 for (String t : NL_SPLITTER.split(text)) {
222 def protected String formatDataForJavaDoc(GeneratedType type) {
223 val sb = new StringBuilder()
224 val comment = type.comment
225 if (comment !== null) {
226 sb.append(comment.javadoc)
229 appendSnippet(sb, type)
238 private static val AMP_MATCHER = CharMatcher.is('&')
240 def static encodeJavadocSymbols(String description) {
241 if (description.nullOrEmpty) {
245 return TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&")).replaceAll("*/")
248 def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) {
249 val comment = type.comment
250 if (comment === null) {
256 val sb = new StringBuilder().append(comment.javadoc)
257 appendSnippet(sb, type)
262 .append(additionalComment)
269 def private static void appendSnippet(StringBuilder sb, GeneratedType type) {
270 val optDef = type.yangSourceDefinition
271 if (optDef.present) {
275 if (def instanceof Single) {
278 .append("This class represents the following YANG schema fragment defined in module <b>")
279 .append(def.module.name).append("</b>\n")
281 .append(encodeAngleBrackets(encodeJavadocSymbols(YangTemplate.generateYangSnippet(node))))
284 if (node instanceof SchemaNode) {
285 sb.append("The schema path to identify an instance is\n")
287 .append(formatSchemaPath(def.module.name, node.path.pathFromRoot))
290 if (hasBuilderClass(node)) {
291 val builderName = type.name + "Builder";
293 sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
295 .append("@see ").append(builderName).append('\n')
296 if (node instanceof ListSchemaNode) {
297 val keyDef = node.keyDefinition
298 if (keyDef !== null && !keyDef.empty) {
299 sb.append("@see ").append(type.name).append("Key")
305 } else if (def instanceof Multiple) {
307 for (DocumentedNode schemaNode : def.nodes) {
308 sb.append(encodeAngleBrackets(encodeJavadocSymbols(YangTemplate.generateYangSnippet(schemaNode))))
310 sb.append("</pre>\n")
315 def private static boolean hasBuilderClass(SchemaNode schemaNode) {
316 return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
317 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
320 def private static String formatSchemaPath(String moduleName, Iterable<QName> schemaPath) {
321 val sb = new StringBuilder().append(moduleName);
323 var currentElement = Iterables.getFirst(schemaPath, null);
324 for (QName pathElement : schemaPath) {
326 if (!currentElement.namespace.equals(pathElement.namespace)) {
327 currentElement = pathElement
328 sb.append(pathElement)
330 sb.append(pathElement.getLocalName())
333 return sb.toString();
336 def protected String formatDataForJavaDoc(TypeMember type, String additionalComment) {
337 val StringBuilder typeDescriptionBuilder = new StringBuilder();
338 if (!type.comment.nullOrEmpty) {
339 typeDescriptionBuilder.append(formatToParagraph(type.comment))
340 typeDescriptionBuilder.append(NEW_LINE)
341 typeDescriptionBuilder.append(NEW_LINE)
342 typeDescriptionBuilder.append(NEW_LINE)
344 typeDescriptionBuilder.append(additionalComment)
345 var typeDescription = wrapToDocumentation(typeDescriptionBuilder.toString)
351 def asCode(String text) {
352 return "<code>" + text + "</code>"
355 def asLink(String text) {
356 val StringBuilder sb = new StringBuilder()
358 var char lastChar = ' '
359 var boolean badEnding = false
361 if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
362 tempText = text.substring(0, text.length - 1)
363 lastChar = text.charAt(text.length - 1)
366 sb.append("<a href = \"")
378 protected def formatToParagraph(String text) {
379 if(text === null || text.isEmpty)
382 var formattedText = text
383 val StringBuilder sb = new StringBuilder();
384 var StringBuilder lineBuilder = new StringBuilder();
385 var boolean isFirstElementOnNewLineEmptyChar = false;
387 formattedText = encodeJavadocSymbols(formattedText)
388 formattedText = NL_MATCHER.removeFrom(formattedText)
389 formattedText = TAB_MATCHER.removeFrom(formattedText)
390 formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
392 val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
394 while (tokenizer.hasMoreElements) {
395 val nextElement = tokenizer.nextElement.toString
397 if (lineBuilder.length != 0 && lineBuilder.length + nextElement.length > 80) {
398 if (lineBuilder.charAt(lineBuilder.length - 1) == ' ') {
399 lineBuilder.setLength(0)
400 lineBuilder.append(lineBuilder.substring(0, lineBuilder.length - 1))
402 if (lineBuilder.charAt(0) == ' ') {
403 lineBuilder.setLength(0)
404 lineBuilder.append(lineBuilder.substring(1))
407 sb.append(lineBuilder);
408 lineBuilder.setLength(0)
411 if(nextElement.toString == ' ') {
412 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
416 if (isFirstElementOnNewLineEmptyChar) {
417 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
421 lineBuilder.append(nextElement)
424 sb.append(lineBuilder)
430 def protected generateToString(Collection<GeneratedProperty> properties) '''
431 «IF !properties.empty»
433 public «String.importedName» toString() {
434 «StringBuilder.importedName» builder = new «StringBuilder.importedName»(«type.importedName».class.getSimpleName()).append(" [");
435 boolean first = true;
437 «FOR property : properties»
438 if («property.fieldName» != null) {
442 builder.append(", ");
444 builder.append("«property.fieldName»=");
445 «IF property.returnType.name.contains("[")»
446 builder.append(«Arrays.importedName».toString(«property.fieldName»));
448 builder.append(«property.fieldName»);
452 return builder.append(']').toString();
457 def getRestrictions(Type type) {
458 var Restrictions restrictions = null
459 if (type instanceof ConcreteType) {
460 restrictions = type.restrictions
461 } else if (type instanceof GeneratedTransferObject) {
462 restrictions = type.restrictions
468 * Template method which generates method parameters with their types from <code>parameters</code>.
471 * list of parameter instances which are transformed to the method parameters
472 * @return string with the list of the method parameters with their types in JAVA format
474 def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
475 IF !parameters.empty»«
476 FOR parameter : parameters SEPARATOR ", "»«
477 parameter.type.importedName» «parameter.name»«
482 def protected GeneratedProperty findProperty(GeneratedTransferObject gto, String name) {
483 val props = gto.properties
485 if (prop.name.equals(name)) {
489 val GeneratedTransferObject parent = gto.superType
490 if (parent !== null) {
491 return findProperty(parent, name)
496 def protected emitConstant(Constant c) '''
497 «IF c.value instanceof QName»
498 «val qname = c.value as QName»
499 «val rev = qname.revision»
500 public static final «c.type.importedName» «c.name» = «QName.name».create("«qname.namespace.toString»",
501 «IF rev.isPresent»"«rev.get»", «ENDIF»"«qname.localName»").intern();
503 public static final «c.type.importedName» «c.name» = «c.value»;