5c11b7ca97288c8b0353e2f3df679764295f8024
[mdsal.git] / binding2 / mdsal-binding2-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / javav2 / java / api / generator / util / TextTemplateUtil.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.mdsal.binding.javav2.java.api.generator.util;
10
11 import com.google.common.base.CharMatcher;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.Iterables;
16 import com.google.common.collect.Lists;
17 import java.util.List;
18 import java.util.StringTokenizer;
19 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
20 import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier;
21 import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType;
22 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty;
23 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject;
24 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType;
25 import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature;
26 import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions;
27 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
28 import org.opendaylight.mdsal.binding.javav2.model.api.TypeMember;
29 import org.opendaylight.yangtools.concepts.Builder;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31
32 public final class TextTemplateUtil {
33
34     public static final String DOT = ".";
35     public static final String PATTERN_CONSTANT_NAME = "PATTERN_CONSTANTS";
36
37     private static final char NEW_LINE = '\n';
38     private static final String UNDERSCORE = "_";
39     private static final CharMatcher NEWLINE_OR_TAB = CharMatcher.anyOf("\n\t");
40     private static final CharMatcher NL_MATCHER = CharMatcher.is(NEW_LINE);
41     private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
42     private static final CharMatcher GT_MATCHER = CharMatcher.is('>');
43     private static final CharMatcher LT_MATCHER = CharMatcher.is('<');
44     private static final Splitter NL_SPLITTER = Splitter.on(NL_MATCHER);
45
46     private TextTemplateUtil() {
47         throw new UnsupportedOperationException("Util class");
48     }
49
50     /**
51      * Makes start of getter name LowerCase
52      *
53      * @param s getter name without prefix
54      * @return getter name starting in LowerCase
55      */
56     public static String toFirstLower(final String s) {
57         return s != null && s.length() != 0 ? Character.isLowerCase(s.charAt(0)) ? s : s.length() == 1 ?
58                 s.toLowerCase() : s.substring(0, 1).toLowerCase() + s.substring(1) : s;
59     }
60
61     /**
62      * Wraps text as documentation, used in enum description
63      *
64      * @param text text for wrapping
65      * @return wrapped text
66      */
67     public static String wrapToDocumentation(final String text) {
68         if (text.isEmpty()) {
69             return "";
70         }
71         final StringBuilder sb = new StringBuilder(NEW_LINE);
72         sb.append("/**");
73         sb.append(NEW_LINE);
74         for (final String t : NL_SPLITTER.split(text)) {
75             if (!t.isEmpty()) {
76                 sb.append(" * ");
77                 sb.append(t);
78                 sb.append(NEW_LINE);
79             }
80         }
81         sb.append(" */");
82         sb.append(NEW_LINE);
83         return sb.toString();
84     }
85
86     /**
87      * Returns formatted Javadoc, based on type
88      * @param typeName
89      * @return formatted Javadoc, based on type
90      */
91     public static String formatDataForJavaDocBuilder(final String typeName) {
92         final StringBuilder stringBuilder = new StringBuilder();
93         stringBuilder.append("Class that builds {@link ")
94                 .append(typeName)
95                 .append("} instances.")
96                 .append(NEW_LINE)
97                 .append("@see ")
98                 .append(typeName);
99         return stringBuilder.toString();
100     }
101
102     /**
103      * Returns formatted Javadoc with possible additional comment, based on type
104      * @param type
105      * @param additionalComment
106      * @return formatted Javadoc with possible additional comment, based on type
107      */
108     public static String formatDataForJavaDoc(final GeneratedType type, final String additionalComment) {
109         final StringBuilder javaDoc = new StringBuilder();
110         if (type.getDescription().isPresent()) {
111             javaDoc.append(type.getDescription())
112                     .append(NEW_LINE)
113                     .append(NEW_LINE)
114                     .append(NEW_LINE);
115         }
116         javaDoc.append(additionalComment);
117         return javaDoc.toString();
118     }
119
120     /**
121      * Returns properties names in formatted string
122      * @param properties
123      * @return properties names in formatted string
124      */
125     //FIXME: this needs further clarification in future patch
126     public static String valueForBits(final List<GeneratedProperty> properties) {
127         return String.join(",", Lists.transform(properties, TextTemplateUtil::fieldName));
128     }
129
130     /**
131      * Returns formatted type description
132      * @param type
133      * @return formatted type description
134      */
135     public static String formatDataForJavaDoc(final GeneratedType type) {
136         return type.getDescription().map(TextTemplateUtil::encodeJavadocSymbols).orElse("");
137     }
138
139     /**
140      * Returns parameter name, based on given Type
141      * @param returnType
142      * @param paramName
143      * @return parameter name, based on given Type
144      */
145     public static String paramValue(final Type returnType, final String paramName) {
146         if (returnType instanceof ConcreteType) {
147             return paramName;
148         } else {
149             return paramName + ".getValue()";
150         }
151     }
152
153     /**
154      * Template method which generates JAVA comments. InterfaceTemplate
155      *
156      * @param comment comment string with the comment for whole JAVA class
157      * @return string with comment in JAVA format
158      */
159     public static String asJavadoc(final String comment) {
160         if (comment == null) {
161             return "";
162         }
163         return wrapToDocumentation(formatToParagraph(comment.trim(), 0));
164     }
165
166     private static String formatDataForJavaDoc(final TypeMember type, final String additionalComment) {
167         final StringBuilder javaDoc = new StringBuilder();
168         if (type.getComment() != null && !type.getComment().isEmpty()) {
169             javaDoc.append(formatToParagraph(type.getComment(), 0))
170                     .append(NEW_LINE)
171                     .append(NEW_LINE)
172                     .append(NEW_LINE);
173         }
174         javaDoc.append(additionalComment);
175         return wrapToDocumentation(javaDoc.toString());
176     }
177
178     /**
179      * Returns related Javadoc
180      * @param methodSignature
181      * @return related Javadoc
182      */
183     public static String getJavaDocForInterface(final MethodSignature methodSignature) {
184         if (methodSignature.getReturnType() == Types.VOID) {
185             return "";
186         }
187         final StringBuilder javaDoc = new StringBuilder();
188         javaDoc.append("@return ")
189                 .append(asCode(methodSignature.getReturnType().getFullyQualifiedName()))
190                 .append(" ")
191                 .append(asCode(propertyNameFromGetter(methodSignature)))
192                 .append(", or ")
193                 .append(asCode("null"))
194                 .append(" if not present");
195         return formatDataForJavaDoc(methodSignature, javaDoc.toString());
196     }
197
198     private static String asCode(final String text) {
199         return "<code>" + text + "</code>";
200     }
201
202     /**
203      * Encodes angle brackets in yang statement description
204      * @param description description of a yang statement which is used to generate javadoc comments
205      * @return string with encoded angle brackets
206      */
207     public static String encodeAngleBrackets(String description) {
208         if (description != null) {
209             description = LT_MATCHER.replaceFrom(description, "&lt;");
210             description = GT_MATCHER.replaceFrom(description, "&gt;");
211         }
212         return description;
213     }
214
215     /**
216      * Returns collection of properties as formatted String
217      * @param properties
218      * @return generated properties as formatted String
219      */
220     public static String propsAsArgs(final Iterable<GeneratedProperty> properties) {
221         return String.join(",", Iterables.transform(properties, prop -> "\"" + prop.getName() + "\""));
222     }
223
224     /**
225      * Returns properties as formatted String
226      * @param properties
227      * @param booleanName
228      * @return Properties as formatted String
229      */
230     public static String propsAsList(final Iterable<GeneratedProperty> properties, final String booleanName) {
231         return String.join(",", Iterables.transform(properties,
232             prop -> "properties.get(i++).equals(defaultValue) ? " + booleanName + ".TRUE : null"));
233     }
234
235     /**
236      * Extracts available restrictions from given type
237      * @param currentType
238      * @return restrictions from given type
239      */
240     public static Restrictions getRestrictions(final Type currentType) {
241         Restrictions restrictions = null;
242         if (currentType instanceof ConcreteType) {
243             restrictions = ((ConcreteType) currentType).getRestrictions();
244         } else if (currentType instanceof GeneratedTransferObject) {
245             restrictions = ((GeneratedTransferObject) currentType).getRestrictions();
246         }
247         return restrictions;
248     }
249
250     /**
251      * sets fieldname according to property for return type
252      * method(type fieldname)
253      *
254      * @param property type from getter
255      */
256     public static String fieldName(final GeneratedProperty property) {
257         final String name = Preconditions.checkNotNull(property.getName());
258         return UNDERSCORE.concat(name);
259     }
260
261     /**
262      * Template method which generates sequence of the names of the class attributes
263      *
264      * @param parameters group of generated property instances which are transformed to the sequence of parameter names
265      * @return string with the list of the parameter names
266      */
267     public static String asArguments(final List<GeneratedProperty> parameters) {
268         return String.join(", ", Lists.transform(parameters, TextTemplateUtil::fieldName));
269     }
270
271     /**
272      * Helper method for building getter
273      *
274      * @param field property name
275      * @return getter for propery
276      */
277     public static String getterMethodName(final GeneratedProperty field) {
278         final Type type = Preconditions.checkNotNull(field.getReturnType());
279         final String name = Preconditions.checkNotNull(field.getName());
280         final String prefix = Types.BOOLEAN.equals(type) ? "is" : "get";
281         return prefix.concat(toFirstUpper(name));
282     }
283
284     /**
285      * Returns built setter method body
286      * @param field
287      * @param typeName
288      * @param returnTypeName
289      * @return built setter method body
290      */
291     public static String setterMethod(final GeneratedProperty field, final String typeName, final String returnTypeName) {
292         final StringBuilder stringBuilder = new StringBuilder();
293         stringBuilder.append("public ")
294                 .append(typeName)
295                 .append(" set")
296                 .append(toFirstUpper(field.getName()))
297                 .append("(")
298                 .append(returnTypeName)
299                 .append(" value) {\n    this.")
300                 .append(fieldName(field))
301                 .append(" = value;\n    return this;\n}\n");
302         return stringBuilder.toString();
303     }
304
305     /**
306      * Returns simple name of underlying class
307      * @return Simple name of underlying class
308      */
309     public static String getSimpleNameForBuilder() {
310         return Builder.class.getSimpleName();
311     }
312
313     /**
314      * Makes start of getter name uppercase
315      *
316      * @param s getter name without prefix
317      * @return getter name starting in uppercase
318      */
319     public static String toFirstUpper(final String s) {
320         return s != null && s.length() != 0 ? Character.isUpperCase(s.charAt(0)) ? s : s.length() == 1 ?
321                 s.toUpperCase() : s.substring(0, 1).toUpperCase() + s.substring(1) : s;
322     }
323
324     /**
325      * Cuts prefix from getter name
326      *
327      * @param getter getter name
328      * @return getter name without prefix
329      */
330     public static String propertyNameFromGetter(final MethodSignature getter) {
331         final String name = Preconditions.checkNotNull(getter.getName());
332         int prefix;
333         if (name.startsWith("is")) {
334             prefix = 2;
335         } else if (name.startsWith("get")) {
336             prefix = 3;
337         } else {
338             prefix = 0;
339         }
340         return toFirstLower(name.substring(prefix));
341     }
342
343     /**
344      * Returns list of properties as formatted String
345      * @param properties
346      * @return formatted property list as String
347      */
348     public static String getPropertyList(final List<GeneratedProperty> properties) {
349         return String.join(", ", Lists.transform(properties, prop -> "base." + getterMethodName(prop) + "()"));
350     }
351
352     /**
353      * util method for unionTemplateBuilderTemplate
354      * @return string with clarification for javadoc
355      */
356     public static String getClarification() {
357         final StringBuilder clarification = new StringBuilder();
358         clarification.append("The purpose of generated class in src/main/java for Union types is to create new instances of unions from a string representation.\n")
359                 .append("In some cases it is very difficult to automate it since there can be unions such as (uint32 - uint16), or (string - uint32).\n")
360                 .append("\n")
361                 .append("The reason behind putting it under src/main/java is:\n")
362                 .append("This class is generated in form of a stub and needs to be finished by the user. This class is generated only once to prevent\n")
363                 .append("loss of user code.\n")
364                 .append("\n");
365         return clarification.toString();
366     }
367
368     /**
369      * Returns source path as String
370      * @param module
371      * @return formatted String source path
372      */
373     public static String getSourcePath(final Module module) {
374         return "/".concat(module.getModuleSourcePath().replace(java.io.File.separatorChar, '/'));
375     }
376
377     /**
378      * util method for unionTemplateBuilderTemplate
379      * @return needed access modifier
380      */
381     public static String getAccessModifier(final AccessModifier modifier) {
382         switch (modifier) {
383             case PUBLIC: return "public ";
384             case PROTECTED: return "protected ";
385             case PRIVATE: return "private ";
386             default: return "";
387         }
388     }
389
390     /**
391      * @param text Content of tag description
392      * @param nextLineIndent Number of spaces from left side default is 12
393      * @return formatted description
394      */
395     private static String formatToParagraph(final String text, final int nextLineIndent) {
396         if (Strings.isNullOrEmpty(text)) {
397             return "";
398         }
399         boolean isFirstElementOnNewLineEmptyChar = false;
400         final StringBuilder sb = new StringBuilder();
401         final StringBuilder lineBuilder = new StringBuilder();
402         final String lineIndent = Strings.repeat(" ", nextLineIndent);
403         final String textToFormat = NEWLINE_OR_TAB.removeFrom(encodeJavadocSymbols(text));
404         final String formattedText = textToFormat.replaceAll(" +", " ");
405         final StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
406
407         while (tokenizer.hasMoreElements()) {
408             final String nextElement = tokenizer.nextElement().toString();
409
410             if (lineBuilder.length() + nextElement.length() > 80) {
411                 // Trim trailing whitespace
412                 for (int i = lineBuilder.length() - 1; i >= 0 && lineBuilder.charAt(i) != ' '; --i) {
413                     lineBuilder.setLength(i);
414                 }
415                 // Trim leading whitespace
416                 while (lineBuilder.charAt(0) == ' ') {
417                     lineBuilder.deleteCharAt(0);
418                 }
419                 sb.append(lineBuilder).append('\n');
420                 lineBuilder.setLength(0);
421
422                 if (nextLineIndent > 0) {
423                     sb.append(lineIndent);
424                 }
425
426                 if (" ".equals(nextElement)) {
427                     isFirstElementOnNewLineEmptyChar = true;
428                 }
429             }
430             if (isFirstElementOnNewLineEmptyChar) {
431                 isFirstElementOnNewLineEmptyChar = false;
432             } else {
433                 lineBuilder.append(nextElement);
434             }
435         }
436         return sb.append(lineBuilder).append('\n').toString();
437     }
438
439     private static String encodeJavadocSymbols(final String description) {
440         if (description == null || description.isEmpty()) {
441             return description;
442         }
443         final String ret = description.replace("*/", "&#42;&#47;");
444         return AMP_MATCHER.replaceFrom(ret, "&amp;");
445     }
446 }