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.MoreObjects
14 import com.google.common.base.Splitter
15 import com.google.common.collect.Iterables
16 import java.util.Collection
18 import java.util.StringTokenizer
19 import java.util.regex.Pattern
20 import org.opendaylight.mdsal.binding.model.api.ConcreteType
21 import org.opendaylight.mdsal.binding.model.api.Constant
22 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
23 import org.opendaylight.mdsal.binding.model.api.GeneratedType
24 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
25 import org.opendaylight.mdsal.binding.model.api.MethodSignature
26 import org.opendaylight.mdsal.binding.model.api.Restrictions
27 import org.opendaylight.mdsal.binding.model.api.Type
28 import org.opendaylight.mdsal.binding.model.api.TypeMember
29 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single
30 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple
31 import org.opendaylight.mdsal.binding.model.util.Types
32 import org.opendaylight.yangtools.yang.binding.CodeHelpers
33 import org.opendaylight.yangtools.yang.common.QName
34 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
35 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
36 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition
37 import org.opendaylight.yangtools.yang.model.api.RpcDefinition
38 import org.opendaylight.yangtools.yang.model.api.SchemaNode
39 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping
40 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement
41 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement
42 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement
43 import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter
45 abstract class BaseTemplate extends JavaFileTemplate {
46 private static final char NEW_LINE = '\n'
47 private static val AMP_MATCHER = CharMatcher.is('&')
48 private static val NL_MATCHER = CharMatcher.is(NEW_LINE)
49 private static val TAB_MATCHER = CharMatcher.is('\t')
50 private static val SPACES_PATTERN = Pattern.compile(" +")
51 private static val NL_SPLITTER = Splitter.on(NL_MATCHER)
52 private static val TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
53 private static val YANG_FORMATTER = DeclaredStatementFormatter.builder()
54 .addIgnoredStatement(YangStmtMapping.CONTACT)
55 .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
56 .addIgnoredStatement(YangStmtMapping.REFERENCE)
57 .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
60 new(GeneratedType type) {
64 new(AbstractJavaGeneratedType javaType, GeneratedType type) {
68 final public def generate() {
71 package «type.packageName»;
78 protected abstract def CharSequence body();
81 final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
83 final protected def propertyNameFromGetter(MethodSignature getter) {
85 if (getter.name.startsWith("is")) {
87 } else if (getter.name.startsWith("get")) {
90 throw new IllegalArgumentException("Not a getter")
92 return getter.name.substring(prefix).toFirstLower;
95 final protected def isAccessor(MethodSignature maybeGetter) {
96 return maybeGetter.name.startsWith("is") || maybeGetter.name.startsWith("get");
100 * Template method which generates the getter method for <code>field</code>
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
106 protected def getterMethod(GeneratedProperty field) {
108 public «field.returnType.importedName» «field.getterMethodName»() {
109 «IF field.returnType.importedName.contains("[]")»
110 return «field.fieldName» == null ? null : «field.fieldName».clone();
112 return «field.fieldName»;
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»'''
124 * Template method which generates the setter method for <code>field</code>
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
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;
139 * Template method which generates method parameters with their types from <code>parameters</code>.
142 * group of generated property instances which are transformed to the method parameters
143 * @return string with the list of the method parameters with their types in JAVA format
145 def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
146 returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
149 * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
152 * group of generated property instances which are transformed to the sequence of parameter names
153 * @return string with the list of the parameter names of the <code>parameters</code>
155 def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
156 fieldName»«ENDFOR»«ENDIF»'''
159 * Template method which generates JAVA comments.
161 * @param comment string with the comment for whole JAVA class
162 * @return string with comment in JAVA format
164 def protected CharSequence asJavadoc(String comment) {
165 if(comment === null) return ''
169 txt = formatToParagraph(txt)
172 «wrapToDocumentation(txt)»
176 def String wrapToDocumentation(String text) {
180 val StringBuilder sb = new StringBuilder().append("/**\n")
181 for (String t : NL_SPLITTER.split(text)) {
194 def protected String formatDataForJavaDoc(GeneratedType type) {
195 val sb = new StringBuilder()
196 val comment = type.comment
197 if (comment !== null) {
198 sb.append(comment.javadoc)
201 appendSnippet(sb, type)
210 def static encodeJavadocSymbols(String description) {
211 if (description.nullOrEmpty) {
215 return TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&")).replaceAll("*/")
218 def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) {
219 val comment = type.comment
220 if (comment === null) {
226 val sb = new StringBuilder().append(comment.javadoc)
227 appendSnippet(sb, type)
232 .append(additionalComment)
239 def private static void appendSnippet(StringBuilder sb, GeneratedType type) {
240 val optDef = type.yangSourceDefinition
241 if (optDef.present) {
245 if (def instanceof Single) {
248 .append("This class represents the following YANG schema fragment defined in module <b>")
249 .append(def.module.argument).append("</b>\n")
251 appendYangSnippet(sb, def.module, (node as EffectiveStatement<?, ?>).declared)
254 if (node instanceof SchemaNode) {
255 sb.append("The schema path to identify an instance is\n")
257 .append(formatSchemaPath(def.module.argument, node.path.pathFromRoot))
260 if (hasBuilderClass(node)) {
261 val builderName = type.name + "Builder";
263 sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
265 .append("@see ").append(builderName).append('\n')
266 if (node instanceof ListSchemaNode) {
267 val keyDef = node.keyDefinition
268 if (keyDef !== null && !keyDef.empty) {
269 sb.append("@see ").append(type.name).append("Key")
275 } else if (def instanceof Multiple) {
277 for (SchemaNode node : def.nodes) {
278 appendYangSnippet(sb, def.module, (node as EffectiveStatement<?, ?>).declared)
280 sb.append("</pre>\n")
285 def private static void appendYangSnippet(StringBuilder sb, ModuleEffectiveStatement module,
286 DeclaredStatement<?> stmt) {
287 for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
288 sb.append(encodeAngleBrackets(encodeJavadocSymbols(str)))
292 def private static boolean hasBuilderClass(SchemaNode schemaNode) {
293 return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
294 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
297 def private static String formatSchemaPath(String moduleName, Iterable<QName> schemaPath) {
298 val sb = new StringBuilder().append(moduleName);
300 var currentElement = Iterables.getFirst(schemaPath, null);
301 for (QName pathElement : schemaPath) {
303 if (!currentElement.namespace.equals(pathElement.namespace)) {
304 currentElement = pathElement
305 sb.append(pathElement)
307 sb.append(pathElement.getLocalName())
310 return sb.toString();
313 def protected String formatDataForJavaDoc(TypeMember type, String additionalComment) {
314 val StringBuilder typeDescriptionBuilder = new StringBuilder();
315 if (!type.comment.nullOrEmpty) {
316 typeDescriptionBuilder.append(formatToParagraph(type.comment))
317 typeDescriptionBuilder.append(NEW_LINE)
318 typeDescriptionBuilder.append(NEW_LINE)
319 typeDescriptionBuilder.append(NEW_LINE)
321 typeDescriptionBuilder.append(additionalComment)
322 var typeDescription = wrapToDocumentation(typeDescriptionBuilder.toString)
328 def asCode(String text) {
329 return "<code>" + text + "</code>"
332 def asLink(String text) {
333 val StringBuilder sb = new StringBuilder()
335 var char lastChar = ' '
336 var boolean badEnding = false
338 if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
339 tempText = text.substring(0, text.length - 1)
340 lastChar = text.charAt(text.length - 1)
343 sb.append("<a href = \"")
355 protected def formatToParagraph(String text) {
356 if(text === null || text.isEmpty)
359 var formattedText = text
360 val StringBuilder sb = new StringBuilder();
361 var StringBuilder lineBuilder = new StringBuilder();
362 var boolean isFirstElementOnNewLineEmptyChar = false;
364 formattedText = encodeJavadocSymbols(formattedText)
365 formattedText = NL_MATCHER.removeFrom(formattedText)
366 formattedText = TAB_MATCHER.removeFrom(formattedText)
367 formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
369 val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
371 while (tokenizer.hasMoreElements) {
372 val nextElement = tokenizer.nextElement.toString
374 if (lineBuilder.length != 0 && lineBuilder.length + nextElement.length > 80) {
375 if (lineBuilder.charAt(lineBuilder.length - 1) == ' ') {
376 lineBuilder.setLength(0)
377 lineBuilder.append(lineBuilder.substring(0, lineBuilder.length - 1))
379 if (lineBuilder.charAt(0) == ' ') {
380 lineBuilder.setLength(0)
381 lineBuilder.append(lineBuilder.substring(1))
384 sb.append(lineBuilder);
385 lineBuilder.setLength(0)
388 if(nextElement.toString == ' ') {
389 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
393 if (isFirstElementOnNewLineEmptyChar) {
394 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
398 lineBuilder.append(nextElement)
401 sb.append(lineBuilder)
407 def protected generateToString(Collection<GeneratedProperty> properties) '''
408 «IF !properties.empty»
410 public «String.importedName» toString() {
411 final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper(«type.importedName».class);
412 «FOR property : properties»
413 «CodeHelpers.importedName».appendValue(helper, "«property.fieldName»", «property.fieldName»);
415 return helper.toString();
421 * Template method which generates method parameters with their types from <code>parameters</code>.
424 * list of parameter instances which are transformed to the method parameters
425 * @return string with the list of the method parameters with their types in JAVA format
427 def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
428 IF !parameters.empty»«
429 FOR parameter : parameters SEPARATOR ", "»«
430 parameter.type.importedName» «parameter.name»«
435 def protected emitConstant(Constant c) '''
436 «IF c.value instanceof QName»
437 «val qname = c.value as QName»
438 «val rev = qname.revision»
439 public static final «c.type.importedName» «c.name» = «QName.name».create("«qname.namespace.toString»",
440 «IF rev.isPresent»"«rev.get»", «ENDIF»"«qname.localName»").intern();
442 public static final «c.type.importedName» «c.name» = «c.value»;
446 def static Restrictions getRestrictions(Type type) {
447 if (type instanceof ConcreteType) {
448 return type.restrictions
450 if (type instanceof GeneratedTransferObject) {
451 return type.restrictions