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