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 final public def generate() {
67 package «type.packageName»;
74 protected abstract def CharSequence body();
77 final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
79 final protected def propertyNameFromGetter(MethodSignature getter) {
81 if (getter.name.startsWith("is")) {
83 } else if (getter.name.startsWith("get")) {
86 throw new IllegalArgumentException("Not a getter")
88 return getter.name.substring(prefix).toFirstLower;
91 final protected def isAccessor(MethodSignature maybeGetter) {
92 return maybeGetter.name.startsWith("is") || maybeGetter.name.startsWith("get");
96 * Template method which generates the getter method for <code>field</code>
99 * generated property with data about field which is generated as the getter method
100 * @return string with the getter method source code in JAVA format
102 protected def getterMethod(GeneratedProperty field) {
104 public «field.returnType.importedName» «field.getterMethodName»() {
105 «IF field.returnType.importedName.contains("[]")»
106 return «field.fieldName» == null ? null : «field.fieldName».clone();
108 return «field.fieldName»;
114 final protected def getterMethodName(GeneratedProperty field) {
115 val prefix = if(field.returnType.equals(Types.BOOLEAN)) "is" else "get"
116 return '''«prefix»«field.name.toFirstUpper»'''
120 * Template method which generates the setter method for <code>field</code>
123 * generated property with data about field which is generated as the setter method
124 * @return string with the setter method source code in JAVA format
126 final protected def setterMethod(GeneratedProperty field) '''
127 «val returnType = field.returnType.importedName»
128 public «type.name» set«field.name.toFirstUpper»(«returnType» value) {
129 this.«field.fieldName» = value;
135 * Template method which generates method parameters with their types from <code>parameters</code>.
138 * group of generated property instances which are transformed to the method parameters
139 * @return string with the list of the method parameters with their types in JAVA format
141 def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
142 returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
145 * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
148 * group of generated property instances which are transformed to the sequence of parameter names
149 * @return string with the list of the parameter names of the <code>parameters</code>
151 def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
152 fieldName»«ENDFOR»«ENDIF»'''
155 * Template method which generates JAVA comments.
157 * @param comment string with the comment for whole JAVA class
158 * @return string with comment in JAVA format
160 def protected CharSequence asJavadoc(String comment) {
161 if(comment === null) return ''
165 txt = formatToParagraph(txt)
168 «wrapToDocumentation(txt)»
172 def String wrapToDocumentation(String text) {
176 val StringBuilder sb = new StringBuilder().append("/**\n")
177 for (String t : NL_SPLITTER.split(text)) {
190 def protected String formatDataForJavaDoc(GeneratedType type) {
191 val sb = new StringBuilder()
192 val comment = type.comment
193 if (comment !== null) {
194 sb.append(comment.javadoc)
197 appendSnippet(sb, type)
206 def static encodeJavadocSymbols(String description) {
207 if (description.nullOrEmpty) {
211 return TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&")).replaceAll("*/")
214 def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) {
215 val comment = type.comment
216 if (comment === null) {
222 val sb = new StringBuilder().append(comment.javadoc)
223 appendSnippet(sb, type)
228 .append(additionalComment)
235 def private static void appendSnippet(StringBuilder sb, GeneratedType type) {
236 val optDef = type.yangSourceDefinition
237 if (optDef.present) {
241 if (def instanceof Single) {
244 .append("This class represents the following YANG schema fragment defined in module <b>")
245 .append(def.module.argument).append("</b>\n")
247 appendYangSnippet(sb, def.module, (node as EffectiveStatement<?, ?>).declared)
250 if (node instanceof SchemaNode) {
251 sb.append("The schema path to identify an instance is\n")
253 .append(formatSchemaPath(def.module.argument, node.path.pathFromRoot))
256 if (hasBuilderClass(node)) {
257 val builderName = type.name + "Builder";
259 sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
261 .append("@see ").append(builderName).append('\n')
262 if (node instanceof ListSchemaNode) {
263 val keyDef = node.keyDefinition
264 if (keyDef !== null && !keyDef.empty) {
265 sb.append("@see ").append(type.name).append("Key")
271 } else if (def instanceof Multiple) {
273 for (SchemaNode node : def.nodes) {
274 appendYangSnippet(sb, def.module, (node as EffectiveStatement<?, ?>).declared)
276 sb.append("</pre>\n")
281 def private static void appendYangSnippet(StringBuilder sb, ModuleEffectiveStatement module,
282 DeclaredStatement<?> stmt) {
283 for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
284 sb.append(encodeAngleBrackets(encodeJavadocSymbols(str)))
288 def private static boolean hasBuilderClass(SchemaNode schemaNode) {
289 return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
290 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
293 def private static String formatSchemaPath(String moduleName, Iterable<QName> schemaPath) {
294 val sb = new StringBuilder().append(moduleName);
296 var currentElement = Iterables.getFirst(schemaPath, null);
297 for (QName pathElement : schemaPath) {
299 if (!currentElement.namespace.equals(pathElement.namespace)) {
300 currentElement = pathElement
301 sb.append(pathElement)
303 sb.append(pathElement.getLocalName())
306 return sb.toString();
309 def protected String formatDataForJavaDoc(TypeMember type, String additionalComment) {
310 val StringBuilder typeDescriptionBuilder = new StringBuilder();
311 if (!type.comment.nullOrEmpty) {
312 typeDescriptionBuilder.append(formatToParagraph(type.comment))
313 typeDescriptionBuilder.append(NEW_LINE)
314 typeDescriptionBuilder.append(NEW_LINE)
315 typeDescriptionBuilder.append(NEW_LINE)
317 typeDescriptionBuilder.append(additionalComment)
318 var typeDescription = wrapToDocumentation(typeDescriptionBuilder.toString)
324 def asCode(String text) {
325 return "<code>" + text + "</code>"
328 def asLink(String text) {
329 val StringBuilder sb = new StringBuilder()
331 var char lastChar = ' '
332 var boolean badEnding = false
334 if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
335 tempText = text.substring(0, text.length - 1)
336 lastChar = text.charAt(text.length - 1)
339 sb.append("<a href = \"")
351 protected def formatToParagraph(String text) {
352 if(text === null || text.isEmpty)
355 var formattedText = text
356 val StringBuilder sb = new StringBuilder();
357 var StringBuilder lineBuilder = new StringBuilder();
358 var boolean isFirstElementOnNewLineEmptyChar = false;
360 formattedText = encodeJavadocSymbols(formattedText)
361 formattedText = NL_MATCHER.removeFrom(formattedText)
362 formattedText = TAB_MATCHER.removeFrom(formattedText)
363 formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
365 val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
367 while (tokenizer.hasMoreElements) {
368 val nextElement = tokenizer.nextElement.toString
370 if (lineBuilder.length != 0 && lineBuilder.length + nextElement.length > 80) {
371 if (lineBuilder.charAt(lineBuilder.length - 1) == ' ') {
372 lineBuilder.setLength(0)
373 lineBuilder.append(lineBuilder.substring(0, lineBuilder.length - 1))
375 if (lineBuilder.charAt(0) == ' ') {
376 lineBuilder.setLength(0)
377 lineBuilder.append(lineBuilder.substring(1))
380 sb.append(lineBuilder);
381 lineBuilder.setLength(0)
384 if(nextElement.toString == ' ') {
385 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
389 if (isFirstElementOnNewLineEmptyChar) {
390 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
394 lineBuilder.append(nextElement)
397 sb.append(lineBuilder)
403 def protected generateToString(Collection<GeneratedProperty> properties) '''
404 «IF !properties.empty»
406 public «String.importedName» toString() {
407 final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper(«type.importedName».class);
408 «FOR property : properties»
409 «CodeHelpers.importedName».appendValue(helper, "«property.fieldName»", «property.fieldName»);
411 return helper.toString();
417 * Template method which generates method parameters with their types from <code>parameters</code>.
420 * list of parameter instances which are transformed to the method parameters
421 * @return string with the list of the method parameters with their types in JAVA format
423 def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
424 IF !parameters.empty»«
425 FOR parameter : parameters SEPARATOR ", "»«
426 parameter.type.importedName» «parameter.name»«
431 def protected emitConstant(Constant c) '''
432 «IF c.value instanceof QName»
433 «val qname = c.value as QName»
434 «val rev = qname.revision»
435 public static final «c.type.importedName» «c.name» = «QName.name».create("«qname.namespace.toString»",
436 «IF rev.isPresent»"«rev.get»", «ENDIF»"«qname.localName»").intern();
438 public static final «c.type.importedName» «c.name» = «c.value»;
442 def static Restrictions getRestrictions(Type type) {
443 if (type instanceof ConcreteType) {
444 return type.restrictions
446 if (type instanceof GeneratedTransferObject) {
447 return type.restrictions