X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=blobdiff_plain;f=binding%2Fmdsal-binding-java-api-generator%2Fsrc%2Fmain%2Fjava%2Forg%2Fopendaylight%2Fmdsal%2Fbinding%2Fjava%2Fapi%2Fgenerator%2FBaseTemplate.xtend;h=ea60bba40f39ccba8a267d537e06bb6a7c31443a;hb=56029dd8a38725d8c5149646a9348e58e769583a;hp=fae62150fd5c81caf66773946027bb4fefff4ed3;hpb=6c5442b6f9b659f296c468f162e6253db00ce53e;p=mdsal.git diff --git a/binding/mdsal-binding-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/java/api/generator/BaseTemplate.xtend b/binding/mdsal-binding-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/java/api/generator/BaseTemplate.xtend index fae62150fd..ea60bba40f 100644 --- a/binding/mdsal-binding-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/java/api/generator/BaseTemplate.xtend +++ b/binding/mdsal-binding-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/java/api/generator/BaseTemplate.xtend @@ -7,18 +7,19 @@ */ package org.opendaylight.mdsal.binding.java.api.generator -import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.encodeAngleBrackets +import static extension org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil.encodeAngleBrackets import com.google.common.base.CharMatcher -import com.google.common.base.MoreObjects import com.google.common.base.Splitter -import com.google.common.collect.Iterables import java.util.Collection import java.util.List import java.util.Locale import java.util.Map.Entry import java.util.StringTokenizer import java.util.regex.Pattern +import org.eclipse.jdt.annotation.NonNull; +import org.gaul.modernizer_maven_annotations.SuppressModernizer +import org.opendaylight.mdsal.binding.model.api.AnnotationType import org.opendaylight.mdsal.binding.model.api.ConcreteType import org.opendaylight.mdsal.binding.model.api.Constant import org.opendaylight.mdsal.binding.model.api.GeneratedProperty @@ -27,39 +28,17 @@ import org.opendaylight.mdsal.binding.model.api.JavaTypeName import org.opendaylight.mdsal.binding.model.api.MethodSignature import org.opendaylight.mdsal.binding.model.api.Restrictions import org.opendaylight.mdsal.binding.model.api.Type -import org.opendaylight.mdsal.binding.model.api.TypeMember -import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single -import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple -import org.opendaylight.mdsal.binding.model.util.TypeConstants -import org.opendaylight.mdsal.binding.model.util.Types +import org.opendaylight.mdsal.binding.model.api.TypeMemberComment +import org.opendaylight.mdsal.binding.model.ri.TypeConstants import org.opendaylight.mdsal.binding.spec.naming.BindingMapping -import org.opendaylight.yangtools.yang.binding.CodeHelpers -import org.opendaylight.yangtools.yang.common.QName -import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode -import org.opendaylight.yangtools.yang.model.api.NotificationDefinition -import org.opendaylight.yangtools.yang.model.api.RpcDefinition -import org.opendaylight.yangtools.yang.model.api.SchemaNode -import org.opendaylight.yangtools.yang.model.api.YangStmtMapping -import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement -import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement -import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement -import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter +@SuppressModernizer abstract class BaseTemplate extends JavaFileTemplate { static final char NEW_LINE = '\n' static final char SPACE = ' ' - static val AMP_MATCHER = CharMatcher.is('&') static val WS_MATCHER = CharMatcher.anyOf("\n\t") static val SPACES_PATTERN = Pattern.compile(" +") static val NL_SPLITTER = Splitter.on(NEW_LINE) - static val TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL); - static val YANG_FORMATTER = DeclaredStatementFormatter.builder() - .addIgnoredStatement(YangStmtMapping.CONTACT) - .addIgnoredStatement(YangStmtMapping.DESCRIPTION) - .addIgnoredStatement(YangStmtMapping.REFERENCE) - .addIgnoredStatement(YangStmtMapping.ORGANIZATION) - .build(); new(GeneratedType type) { super(type) @@ -82,20 +61,8 @@ abstract class BaseTemplate extends JavaFileTemplate { protected abstract def CharSequence body(); // Helper patterns - final protected def fieldName(GeneratedProperty property) '''_«property.name»''' - - final protected def propertyNameFromGetter(MethodSignature getter) { - var String prefix; - if (getter.name.startsWith(BindingMapping.BOOLEAN_GETTER_PREFIX)) { - prefix = BindingMapping.BOOLEAN_GETTER_PREFIX - } else if (getter.name.startsWith(BindingMapping.GETTER_PREFIX)) { - prefix = BindingMapping.GETTER_PREFIX - } else if (getter.name.startsWith(BindingMapping.NONNULL_PREFIX)) { - prefix = BindingMapping.NONNULL_PREFIX - } else { - throw new IllegalArgumentException(getter + " is not a getter") - } - return getter.name.substring(prefix.length).toFirstLower; + final protected def fieldName(GeneratedProperty property) { + "_" + property.name } /** @@ -105,21 +72,20 @@ abstract class BaseTemplate extends JavaFileTemplate { * generated property with data about field which is generated as the getter method * @return string with the getter method source code in JAVA format */ - protected def getterMethod(GeneratedProperty field) { - ''' - public «field.returnType.importedName» «field.getterMethodName»() { - «IF field.returnType.importedName.contains("[]")» - return «field.fieldName» == null ? null : «field.fieldName».clone(); - «ELSE» - return «field.fieldName»; - «ENDIF» - } - ''' - } + protected def getterMethod(GeneratedProperty field) ''' + «val methodName = field.getterMethodName» + public «field.returnType.importedName» «methodName»() { + «val fieldName = field.fieldName» + «IF field.returnType.name.endsWith("[]")» + return «fieldName» == null ? null : «fieldName».clone(); + «ELSE» + return «fieldName»; + «ENDIF» + } + ''' final protected def getterMethodName(GeneratedProperty field) { - val prefix = if(field.returnType.equals(Types.BOOLEAN)) "is" else "get" - return '''«prefix»«field.name.toFirstUpper»''' + return '''«BindingMapping.GETTER_PREFIX»«field.name.toFirstUpper»''' } /** @@ -147,6 +113,17 @@ abstract class BaseTemplate extends JavaFileTemplate { def final protected asArgumentsDeclaration(Iterable parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter. returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»''' + /** + * Template method which generates method parameters with their types from parameters, annotating them + * with {@link NonNull}. + * + * @param parameters group of generated property instances which are transformed to the method parameters + * @return string with the list of the method parameters with their types in JAVA format + */ + def final protected asNonNullArgumentsDeclaration(Iterable parameters) '''«IF !parameters.empty» + «FOR parameter : parameters SEPARATOR ", "»«parameter.returnType.importedNonNull» «parameter + .fieldName»«ENDFOR»«ENDIF»''' + /** * Template method which generates sequence of the names of the class attributes from parameters. * @@ -154,7 +131,7 @@ abstract class BaseTemplate extends JavaFileTemplate { * group of generated property instances which are transformed to the sequence of parameter names * @return string with the list of the parameter names of the parameters */ - def final protected asArguments(Iterable parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter. + def final protected asArguments(Collection parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter. fieldName»«ENDFOR»«ENDIF»''' /** @@ -163,16 +140,17 @@ abstract class BaseTemplate extends JavaFileTemplate { * @param comment string with the comment for whole JAVA class * @return string with comment in JAVA format */ - def protected CharSequence asJavadoc(String comment) { - if(comment === null) return '' - var txt = comment + def final protected asJavadoc(TypeMemberComment comment) { + if (comment === null) { + return '' + } + return wrapToDocumentation(''' + «comment.contractDescription» - txt = comment.trim - txt = formatToParagraph(txt) + «comment.referenceDescription.formatReference» - return ''' - «wrapToDocumentation(txt)» - ''' + «comment.typeSignature» + ''') } def static String wrapToDocumentation(String text) { @@ -208,14 +186,6 @@ abstract class BaseTemplate extends JavaFileTemplate { '''.toString } - def static encodeJavadocSymbols(String description) { - if (description.nullOrEmpty) { - return description; - } - - return TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&")).replaceAll("*/") - } - def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) { val comment = type.comment if (comment === null) { @@ -237,98 +207,16 @@ abstract class BaseTemplate extends JavaFileTemplate { ''' } - def private static void appendSnippet(StringBuilder sb, GeneratedType type) { - val optDef = type.yangSourceDefinition - if (optDef.present) { - val def = optDef.get - sb.append(NEW_LINE) - - if (def instanceof Single) { - val node = def.node - sb.append("

\n") - .append("This class represents the following YANG schema fragment defined in module ") - .append(def.module.argument).append("\n") - .append("

\n")
-                appendYangSnippet(sb, def.module, (node as EffectiveStatement).declared)
-                sb.append("
") - - if (node instanceof SchemaNode) { - sb.append("The schema path to identify an instance is\n") - .append("") - .append(formatSchemaPath(def.module.argument, node.path.pathFromRoot)) - .append("\n") - - if (hasBuilderClass(node)) { - val builderName = type.name + "Builder"; - - sb.append("\n

To create instances of this class use {@link ").append(builderName) - .append("}.\n") - .append("@see ").append(builderName).append('\n') - if (node instanceof ListSchemaNode) { - val keyDef = node.keyDefinition - if (keyDef !== null && !keyDef.empty) { - sb.append("@see ").append(type.name).append("Key") - } - sb.append('\n'); - } - } - } - } else if (def instanceof Multiple) { - sb.append("

\n")
-                for (SchemaNode node : def.nodes) {
-                    appendYangSnippet(sb, def.module, (node as EffectiveStatement).declared)
-                }
-                sb.append("
\n") - } - } - } - - def private static void appendYangSnippet(StringBuilder sb, ModuleEffectiveStatement module, - DeclaredStatement stmt) { - for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) { - sb.append(encodeAngleBrackets(encodeJavadocSymbols(str))) - } - } - - def private static boolean hasBuilderClass(SchemaNode schemaNode) { - return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode - || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition; - } - - def private static String formatSchemaPath(String moduleName, Iterable schemaPath) { - val sb = new StringBuilder().append(moduleName); - - var currentElement = Iterables.getFirst(schemaPath, null); - for (QName pathElement : schemaPath) { - sb.append('/') - if (!currentElement.namespace.equals(pathElement.namespace)) { - currentElement = pathElement - sb.append(pathElement) - } else { - sb.append(pathElement.getLocalName()) - } - } - return sb.toString(); - } - - def protected static String formatDataForJavaDoc(TypeMember type, String additionalComment) { - val StringBuilder typeDescriptionBuilder = new StringBuilder(); - if (!type.comment.nullOrEmpty) { - typeDescriptionBuilder.append(formatToParagraph(type.comment)) - typeDescriptionBuilder.append(NEW_LINE) - typeDescriptionBuilder.append(NEW_LINE) - typeDescriptionBuilder.append(NEW_LINE) - } - typeDescriptionBuilder.append(additionalComment) - var typeDescription = wrapToDocumentation(typeDescriptionBuilder.toString) - return ''' - «typeDescription» - '''.toString - } + def static formatReference(String reference) ''' + «IF reference !== null» +
+                
+                    «reference.encodeAngleBrackets.formatToParagraph»
+                
+            
- def asCode(String text) { - return "" + text + "" - } + «ENDIF» + ''' def asLink(String text) { val StringBuilder sb = new StringBuilder() @@ -341,56 +229,41 @@ abstract class BaseTemplate extends JavaFileTemplate { lastChar = text.charAt(text.length - 1) badEnding = true } - sb.append("") - sb.append(tempText) - sb.append("") + sb.append("").append(tempText).append("") - if(badEnding) + if (badEnding) sb.append(lastChar) return sb.toString } - protected static def formatToParagraph(String text) { - if(text === null || text.isEmpty) - return text - - var formattedText = text + protected static def formatToParagraph(String inputText) { val StringBuilder sb = new StringBuilder(); var StringBuilder lineBuilder = new StringBuilder(); var boolean isFirstElementOnNewLineEmptyChar = false; - formattedText = encodeJavadocSymbols(formattedText) - formattedText = WS_MATCHER.replaceFrom(formattedText, SPACE) + var formattedText = WS_MATCHER.replaceFrom(inputText.encodeJavadocSymbols, SPACE) formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ") - val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true); - - while (tokenizer.hasMoreElements) { - val nextElement = tokenizer.nextElement.toString + val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true) + while (tokenizer.hasMoreTokens) { + val nextElement = tokenizer.nextToken if (lineBuilder.length != 0 && lineBuilder.length + nextElement.length > 80) { - // FIXME: what tricks are we playing here? Equality probably does not trigger ever - // and then the setLength()/append() combo does not work, either - if (lineBuilder.charAt(lineBuilder.length - 1) == ' ') { - lineBuilder.setLength(0) - lineBuilder.append(lineBuilder.substring(0, lineBuilder.length - 1)) + if (lineBuilder.charAt(lineBuilder.length - 1) == SPACE) { + lineBuilder.setLength(lineBuilder.length - 1) } - if (lineBuilder.charAt(0) == ' ') { - lineBuilder.setLength(0) - lineBuilder.append(lineBuilder.substring(1)) + if (lineBuilder.length != 0 && lineBuilder.charAt(0) == SPACE) { + lineBuilder.deleteCharAt(0) } sb.append(lineBuilder).append(NEW_LINE) lineBuilder.setLength(0) - if (nextElement.toString == ' ') { + if (nextElement == " ") { isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar; } } - if (isFirstElementOnNewLineEmptyChar) { isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar } else { @@ -401,19 +274,6 @@ abstract class BaseTemplate extends JavaFileTemplate { return sb.append(lineBuilder).append(NEW_LINE).toString } - def protected generateToString(Collection properties) ''' - «IF !properties.empty» - @«Override.importedName» - public «String.importedName» toString() { - final «MoreObjects.importedName».ToStringHelper helper = «MoreObjects.importedName».toStringHelper(«type.importedName».class); - «FOR property : properties» - «CodeHelpers.importedName».appendValue(helper, "«property.fieldName»", «property.fieldName»); - «ENDFOR» - return helper.toString(); - } - «ENDIF» - ''' - /** * Template method which generates method parameters with their types from parameters. * @@ -444,7 +304,7 @@ abstract class BaseTemplate extends JavaFileTemplate { restrictions.rangeConstraint.get, this)» «ENDIF» «IF restrictions.lengthConstraint.present» - «LengthGenerator.generateLengthChecker(field.fieldName.toString, actualType, restrictions.lengthConstraint.get, this)» + «LengthGenerator.generateLengthChecker(field.fieldName, actualType, restrictions.lengthConstraint.get, this)» «ENDIF» ''' @@ -456,28 +316,40 @@ abstract class BaseTemplate extends JavaFileTemplate { «AbstractRangeGenerator.forType(actualType).generateRangeCheckerCall(property.getName.toFirstUpper, value + ".getValue()")» «ENDIF» «ENDIF» + «val fieldName = property.fieldName» «IF restrictions.getLengthConstraint.isPresent» «IF actualType instanceof ConcreteType» - «LengthGenerator.generateLengthCheckerCall(property.fieldName.toString, value)» + «LengthGenerator.generateLengthCheckerCall(fieldName, value)» «ELSE» - «LengthGenerator.generateLengthCheckerCall(property.fieldName.toString, value + ".getValue()")» + «LengthGenerator.generateLengthCheckerCall(fieldName, value + ".getValue()")» «ENDIF» «ENDIF» - «val fieldUpperCase = property.fieldName.toString.toUpperCase(Locale.ENGLISH)» + «val fieldUpperCase = fieldName.toUpperCase(Locale.ENGLISH)» «FOR currentConstant : type.getConstantDefinitions» «IF currentConstant.getName.startsWith(TypeConstants.PATTERN_CONSTANT_NAME) && fieldUpperCase.equals(currentConstant.getName.substring(TypeConstants.PATTERN_CONSTANT_NAME.length))» - «CodeHelpers.importedName».checkPattern(value, «Constants.MEMBER_PATTERN_LIST»«property.fieldName», «Constants.MEMBER_REGEX_LIST»«property.fieldName»); + «CODEHELPERS.importedName».checkPattern(value, «Constants.MEMBER_PATTERN_LIST»«fieldName», «Constants.MEMBER_REGEX_LIST»«fieldName»); «ENDIF» «ENDFOR» ''' - def protected hashCodeResult(Collection properties) ''' + def protected hashCodeResult(Collection properties) ''' final int prime = 31; int result = 1; «FOR property : properties» result = prime * result + «property.importedUtilClass».hashCode(«property.fieldName»); «ENDFOR» ''' + + def protected final generateAnnotation(AnnotationType annotation) ''' + @«annotation.importedName» + «IF annotation.parameters !== null && !annotation.parameters.empty» + ( + «FOR param : annotation.parameters SEPARATOR ","» + «param.name»=«param.value» + «ENDFOR» + ) + «ENDIF» + ''' }