Fix YANG snippet escaping
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / BaseTemplate.xtend
index 403f5ebfefde246f64a92e18760d20cea5c360bd..71005ca2ac6b1c9fb8b45c0911573bb7328251b5 100644 (file)
@@ -15,14 +15,15 @@ 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.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
 import org.opendaylight.mdsal.binding.model.api.GeneratedType
-import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject
 import org.opendaylight.mdsal.binding.model.api.JavaTypeName
 import org.opendaylight.mdsal.binding.model.api.MethodSignature
 import org.opendaylight.mdsal.binding.model.api.Restrictions
@@ -30,6 +31,7 @@ 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.BindingGeneratorUtil
 import org.opendaylight.mdsal.binding.model.util.TypeConstants
 import org.opendaylight.mdsal.binding.model.util.Types
 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping
@@ -48,11 +50,11 @@ import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter
 
 abstract class BaseTemplate extends JavaFileTemplate {
     static final char NEW_LINE = '\n'
+    static final char SPACE = ' '
     static val AMP_MATCHER = CharMatcher.is('&')
-    static val NL_MATCHER = CharMatcher.is(NEW_LINE)
-    static val TAB_MATCHER = CharMatcher.is('\t')
+    static val WS_MATCHER = CharMatcher.anyOf("\n\t")
     static val SPACES_PATTERN = Pattern.compile(" +")
-    static val NL_SPLITTER = Splitter.on(NL_MATCHER)
+    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)
@@ -85,19 +87,17 @@ abstract class BaseTemplate extends JavaFileTemplate {
     final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
 
     final protected def propertyNameFromGetter(MethodSignature getter) {
-        var int prefix;
-        if (getter.name.startsWith("is")) {
-            prefix = 2
-        } else if (getter.name.startsWith("get")) {
-            prefix = 3
+        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("Not a getter")
+            throw new IllegalArgumentException(getter + " is not a getter")
         }
-        return getter.name.substring(prefix).toFirstLower;
-    }
-
-    final protected def isAccessor(MethodSignature maybeGetter) {
-        return maybeGetter.name.startsWith("is") || maybeGetter.name.startsWith("get");
+        return getter.name.substring(prefix.length).toFirstLower;
     }
 
     /**
@@ -110,10 +110,11 @@ abstract class BaseTemplate extends JavaFileTemplate {
     protected def getterMethod(GeneratedProperty field) {
         '''
             public «field.returnType.importedName» «field.getterMethodName»() {
-                «IF field.returnType.importedName.contains("[]")»
-                return «field.fieldName» == null ? null : «field.fieldName».clone();
+                «val fieldName = field.fieldName»
+                «IF field.returnType.name.endsWith("[]")»
+                return «fieldName» == null ? null : «fieldName».clone();
                 «ELSE»
-                return «field.fieldName»;
+                return «fieldName»;
                 «ENDIF»
             }
         '''
@@ -156,7 +157,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 <code>parameters</code>
      */
-    def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
+    def final protected asArguments(Collection<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
         fieldName»«ENDFOR»«ENDIF»'''
 
     /**
@@ -166,18 +167,15 @@ abstract class BaseTemplate extends JavaFileTemplate {
      * @return string with comment in JAVA format
      */
     def protected CharSequence asJavadoc(String comment) {
-        if(comment === null) return ''
-        var txt = comment
-
-        txt = comment.trim
-        txt = formatToParagraph(txt)
-
+        if (comment === null) {
+            return ''
+        }
         return '''
-            «wrapToDocumentation(txt
+            «wrapToDocumentation(formatToParagraph(comment.trim)
         '''
     }
 
-    def String wrapToDocumentation(String text) {
+    def static String wrapToDocumentation(String text) {
         if (text.empty)
             return ""
 
@@ -185,8 +183,7 @@ abstract class BaseTemplate extends JavaFileTemplate {
         for (String t : NL_SPLITTER.split(text)) {
             sb.append(" *")
             if (!t.isEmpty()) {
-                sb.append(' ');
-                sb.append(t)
+                sb.append(SPACE).append(t)
             }
             sb.append(NEW_LINE)
         }
@@ -289,7 +286,7 @@ abstract class BaseTemplate extends JavaFileTemplate {
     def private static void appendYangSnippet(StringBuilder sb, ModuleEffectiveStatement module,
             DeclaredStatement<?> stmt) {
         for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
-            sb.append(encodeAngleBrackets(encodeJavadocSymbols(str)))
+            sb.append(BindingGeneratorUtil.replaceAllIllegalChars(encodeAngleBrackets(encodeJavadocSymbols(str))))
         }
     }
 
@@ -314,7 +311,7 @@ abstract class BaseTemplate extends JavaFileTemplate {
         return sb.toString();
     }
 
-    def protected String formatDataForJavaDoc(TypeMember type, String additionalComment) {
+    def protected static String formatDataForJavaDoc(TypeMember type, String additionalComment) {
         val StringBuilder typeDescriptionBuilder = new StringBuilder();
         if (!type.comment.nullOrEmpty) {
             typeDescriptionBuilder.append(formatToParagraph(type.comment))
@@ -336,7 +333,7 @@ abstract class BaseTemplate extends JavaFileTemplate {
     def asLink(String text) {
         val StringBuilder sb = new StringBuilder()
         var tempText = text
-        var char lastChar = ' '
+        var char lastChar = SPACE
         var boolean badEnding = false
 
         if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
@@ -356,7 +353,7 @@ abstract class BaseTemplate extends JavaFileTemplate {
         return sb.toString
     }
 
-    protected def formatToParagraph(String text) {
+    protected static def formatToParagraph(String text) {
         if(text === null || text.isEmpty)
             return text
 
@@ -366,46 +363,38 @@ abstract class BaseTemplate extends JavaFileTemplate {
         var boolean isFirstElementOnNewLineEmptyChar = false;
 
         formattedText = encodeJavadocSymbols(formattedText)
-        formattedText = NL_MATCHER.removeFrom(formattedText)
-        formattedText = TAB_MATCHER.removeFrom(formattedText)
+        formattedText = WS_MATCHER.replaceFrom(formattedText, SPACE)
         formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
 
         val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
 
-        while (tokenizer.hasMoreElements) {
-            val nextElement = tokenizer.nextElement.toString
+        while (tokenizer.hasMoreTokens) {
+            val nextElement = tokenizer.nextToken
 
             if (lineBuilder.length != 0 && lineBuilder.length + nextElement.length > 80) {
-                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);
+                sb.append(lineBuilder).append(NEW_LINE)
                 lineBuilder.setLength(0)
-                sb.append(NEW_LINE)
 
-                if(nextElement.toString == ' ') {
+                if (nextElement == " ") {
                     isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
                 }
             }
 
             if (isFirstElementOnNewLineEmptyChar) {
                 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
-            }
-
-            else {
+            } else {
                 lineBuilder.append(nextElement)
             }
         }
-        sb.append(lineBuilder)
-        sb.append(NEW_LINE)
 
-        return sb.toString
+        return sb.append(lineBuilder).append(NEW_LINE).toString
     }
 
     def protected generateToString(Collection<GeneratedProperty> properties) '''
@@ -439,7 +428,7 @@ abstract class BaseTemplate extends JavaFileTemplate {
     def protected emitConstant(Constant c) '''
         «IF BindingMapping.QNAME_STATIC_FIELD_NAME.equals(c.name)»
             «val entry = c.value as Entry<JavaTypeName, String>»
-            public static final «c.type.importedName» «c.name» = «entry.key.importedName».«BindingMapping.MODULE_INFO_QNAMEOF_METHOD_NAME»("«entry.value»");
+            public static final «c.type.importedNonNull» «c.name» = «entry.key.importedName».«BindingMapping.MODULE_INFO_QNAMEOF_METHOD_NAME»("«entry.value»");
         «ELSE»
             public static final «c.type.importedName» «c.name» = «c.value»;
         «ENDIF»
@@ -463,37 +452,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.toString, value)»
            «ELSE»
-               «LengthGenerator.generateLengthCheckerCall(property.fieldName.toString, value + ".getValue()")»
+               «LengthGenerator.generateLengthCheckerCall(fieldName.toString, value + ".getValue()")»
            «ENDIF»
        «ENDIF»
 
-       «val fieldUpperCase = property.fieldName.toString.toUpperCase(
+       «val fieldUpperCase = fieldName.toString.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 Restrictions restrictionsForSetter(Type actualType) {
-        if (actualType instanceof GeneratedType) {
-            return null;
-        }
-        return actualType.restrictions;
-    }
+    def protected hashCodeResult(Collection<GeneratedProperty> properties) '''
+        final int prime = 31;
+        int result = 1;
+        «FOR property : properties»
+            result = prime * result + «property.importedUtilClass».hashCode(«property.fieldName»);
+        «ENDFOR»
+    '''
 
-    def static Restrictions getRestrictions(Type type) {
-        if (type instanceof ConcreteType) {
-            return type.restrictions
-        }
-        if (type instanceof GeneratedTransferObject) {
-            return type.restrictions
-        }
-        return null
-    }
+    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»
+    '''
 }