2 * Copyright (c) 2017 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
9 package org.opendaylight.mdsal.binding.javav2.java.api.generator.util;
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 java.util.regex.Pattern;
20 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
21 import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier;
22 import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType;
23 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty;
24 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject;
25 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType;
26 import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature;
27 import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions;
28 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
29 import org.opendaylight.mdsal.binding.javav2.model.api.TypeMember;
30 import org.opendaylight.yangtools.concepts.Builder;
31 import org.opendaylight.yangtools.yang.model.api.Module;
33 public final class TextTemplateUtil {
35 public static final String DOT = ".";
36 public static final String PATTERN_CONSTANT_NAME = "PATTERN_CONSTANTS";
38 private static final char NEW_LINE = '\n';
39 private static final String UNDERSCORE = "_";
40 private static final CharMatcher NEWLINE_OR_TAB = CharMatcher.anyOf("\n\t");
41 private static final CharMatcher NL_MATCHER = CharMatcher.is(NEW_LINE);
42 private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
43 private static final CharMatcher GT_MATCHER = CharMatcher.is('>');
44 private static final CharMatcher LT_MATCHER = CharMatcher.is('<');
45 private static final Splitter NL_SPLITTER = Splitter.on(NL_MATCHER);
47 private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
48 private static final Pattern MULTIPLE_SPACES_PATTERN = Pattern.compile(" +");
50 private TextTemplateUtil() {
51 throw new UnsupportedOperationException("Util class");
55 * Makes start of getter name LowerCase
57 * @param s getter name without prefix
58 * @return getter name starting in LowerCase
60 public static String toFirstLower(final String s) {
61 return s != null && s.length() != 0 ? Character.isLowerCase(s.charAt(0)) ? s : s.length() == 1 ?
62 s.toLowerCase() : s.substring(0, 1).toLowerCase() + s.substring(1) : s;
66 * Wraps text as documentation, used in enum description
68 * @param text text for wrapping
69 * @return wrapped text
71 public static String wrapToDocumentation(final String text) {
75 final StringBuilder sb = new StringBuilder(NEW_LINE);
78 for (final String t : NL_SPLITTER.split(text)) {
91 * Returns formatted Javadoc, based on type
93 * @return formatted Javadoc, based on type
95 public static String formatDataForJavaDocBuilder(final String typeName) {
96 final StringBuilder stringBuilder = new StringBuilder();
97 stringBuilder.append("Class that builds {@link ")
99 .append("} instances.")
103 return stringBuilder.toString();
107 * Returns formatted Javadoc with possible additional comment, based on type
109 * @param additionalComment
110 * @return formatted Javadoc with possible additional comment, based on type
112 public static String formatDataForJavaDoc(final GeneratedType type, final String additionalComment) {
113 final StringBuilder javaDoc = new StringBuilder();
114 if (type.getDescription().isPresent()) {
115 javaDoc.append(type.getDescription())
120 javaDoc.append(additionalComment);
121 return javaDoc.toString();
125 * Returns properties names in formatted string
127 * @return properties names in formatted string
129 //FIXME: this needs further clarification in future patch
130 public static String valueForBits(final List<GeneratedProperty> properties) {
131 return String.join(",", Lists.transform(properties, TextTemplateUtil::fieldName));
135 * Returns formatted type description
137 * @return formatted type description
139 public static String formatDataForJavaDoc(final GeneratedType type) {
140 return type.getDescription().map(TextTemplateUtil::encodeJavadocSymbols).orElse("");
144 * Returns parameter name, based on given Type
147 * @return parameter name, based on given Type
149 public static String paramValue(final Type returnType, final String paramName) {
150 return returnType instanceof ConcreteType ? paramName : paramName + ".getValue()";
154 * Template method which generates JAVA comments. InterfaceTemplate
156 * @param comment comment string with the comment for whole JAVA class
157 * @return string with comment in JAVA format
159 public static String asJavadoc(final String comment) {
160 return comment == null ? "" : wrapToDocumentation(formatToParagraph(comment.trim(), 0));
163 private static String formatDataForJavaDoc(final TypeMember type, final String additionalComment) {
164 final StringBuilder javaDoc = new StringBuilder();
165 if (type.getComment() != null && !type.getComment().isEmpty()) {
166 javaDoc.append(formatToParagraph(type.getComment(), 0))
171 javaDoc.append(additionalComment);
172 return wrapToDocumentation(javaDoc.toString());
176 * Returns related Javadoc
177 * @param methodSignature
178 * @return related Javadoc
180 public static String getJavaDocForInterface(final MethodSignature methodSignature) {
181 if (methodSignature.getReturnType() == Types.VOID) {
184 final StringBuilder javaDoc = new StringBuilder();
185 javaDoc.append("@return ")
186 .append(asCode(methodSignature.getReturnType().getFullyQualifiedName()))
188 .append(asCode(propertyNameFromGetter(methodSignature)))
190 .append(asCode("null"))
191 .append(" if not present");
192 return formatDataForJavaDoc(methodSignature, javaDoc.toString());
195 private static String asCode(final String text) {
196 return "<code>" + text + "</code>";
200 * Encodes angle brackets in yang statement description
201 * @param description description of a yang statement which is used to generate javadoc comments
202 * @return string with encoded angle brackets
204 public static String encodeAngleBrackets(String description) {
205 if (description != null) {
206 description = LT_MATCHER.replaceFrom(description, "<");
207 description = GT_MATCHER.replaceFrom(description, ">");
213 * Returns collection of properties as formatted String
215 * @return generated properties as formatted String
217 public static String propsAsArgs(final Iterable<GeneratedProperty> properties) {
218 return String.join(",", Iterables.transform(properties, prop -> "\"" + prop.getName() + "\""));
222 * Returns properties as formatted String
225 * @return Properties as formatted String
227 public static String propsAsList(final Iterable<GeneratedProperty> properties, final String booleanName) {
228 return String.join(",", Iterables.transform(properties,
229 prop -> "properties.get(i++).equals(defaultValue) ? " + booleanName + ".TRUE : null"));
233 * Extracts available restrictions from given type
235 * @return restrictions from given type
237 public static Restrictions getRestrictions(final Type currentType) {
238 Restrictions restrictions = null;
239 if (currentType instanceof ConcreteType) {
240 restrictions = ((ConcreteType) currentType).getRestrictions();
241 } else if (currentType instanceof GeneratedTransferObject) {
242 restrictions = ((GeneratedTransferObject) currentType).getRestrictions();
248 * sets fieldname according to property for return type
249 * method(type fieldname)
251 * @param property type from getter
253 public static String fieldName(final GeneratedProperty property) {
254 final String name = Preconditions.checkNotNull(property.getName());
255 return UNDERSCORE.concat(name);
259 * Template method which generates sequence of the names of the class attributes
261 * @param parameters group of generated property instances which are transformed to the sequence of parameter names
262 * @return string with the list of the parameter names
264 public static String asArguments(final List<GeneratedProperty> parameters) {
265 return String.join(", ", Lists.transform(parameters, TextTemplateUtil::fieldName));
269 * Helper method for building getter
271 * @param field property name
272 * @return getter for propery
274 public static String getterMethodName(final GeneratedProperty field) {
275 final Type type = Preconditions.checkNotNull(field.getReturnType());
276 final String name = Preconditions.checkNotNull(field.getName());
277 final String prefix = Types.BOOLEAN.equals(type) ? "is" : "get";
278 return prefix.concat(toFirstUpper(name));
282 * Returns built setter method body
285 * @param returnTypeName
286 * @return built setter method body
288 public static String setterMethod(final GeneratedProperty field, final String typeName, final String returnTypeName) {
289 final StringBuilder stringBuilder = new StringBuilder();
290 stringBuilder.append("public ")
293 .append(toFirstUpper(field.getName()))
295 .append(returnTypeName)
296 .append(" value) {\n this.")
297 .append(fieldName(field))
298 .append(" = value;\n return this;\n}\n");
299 return stringBuilder.toString();
303 * Returns simple name of underlying class
304 * @return Simple name of underlying class
306 public static String getSimpleNameForBuilder() {
307 return Builder.class.getSimpleName();
311 * Makes start of getter name uppercase
313 * @param s getter name without prefix
314 * @return getter name starting in uppercase
316 public static String toFirstUpper(final String s) {
317 return s != null && s.length() != 0 ? Character.isUpperCase(s.charAt(0)) ? s : s.length() == 1 ?
318 s.toUpperCase() : s.substring(0, 1).toUpperCase() + s.substring(1) : s;
322 * Cuts prefix from getter name
324 * @param getter getter name
325 * @return getter name without prefix
327 public static String propertyNameFromGetter(final MethodSignature getter) {
328 final String name = Preconditions.checkNotNull(getter.getName());
330 if (name.startsWith("is")) {
332 } else if (name.startsWith("get")) {
337 return toFirstLower(name.substring(prefix));
341 * Returns list of properties as formatted String
343 * @return formatted property list as String
345 public static String getPropertyList(final List<GeneratedProperty> properties) {
346 return String.join(", ", Lists.transform(properties, prop -> "base." + getterMethodName(prop) + "()"));
350 * util method for unionTemplateBuilderTemplate
351 * @return string with clarification for javadoc
353 public static String getClarification() {
354 final StringBuilder clarification = new StringBuilder();
355 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")
356 .append("In some cases it is very difficult to automate it since there can be unions such as (uint32 - uint16), or (string - uint32).\n")
358 .append("The reason behind putting it under src/main/java is:\n")
359 .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")
360 .append("loss of user code.\n")
362 return clarification.toString();
366 * Returns source path as String
368 * @return formatted String source path
370 public static String getSourcePath(final Module module) {
371 return "/".concat(module.getModuleSourcePath().replace(java.io.File.separatorChar, '/'));
375 * util method for unionTemplateBuilderTemplate
376 * @return needed access modifier
378 public static String getAccessModifier(final AccessModifier modifier) {
380 case PUBLIC: return "public ";
381 case PROTECTED: return "protected ";
382 case PRIVATE: return "private ";
388 * @param text Content of tag description
389 * @param nextLineIndent Number of spaces from left side default is 12
390 * @return formatted description
392 private static String formatToParagraph(final String text, final int nextLineIndent) {
393 if (Strings.isNullOrEmpty(text)) {
396 boolean isFirstElementOnNewLineEmptyChar = false;
397 final StringBuilder sb = new StringBuilder();
398 final StringBuilder lineBuilder = new StringBuilder();
399 final String lineIndent = Strings.repeat(" ", nextLineIndent);
400 final String textToFormat = NEWLINE_OR_TAB.removeFrom(encodeJavadocSymbols(text));
401 final String formattedText = MULTIPLE_SPACES_PATTERN.matcher(textToFormat).replaceAll(" ");
402 final StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
404 while (tokenizer.hasMoreElements()) {
405 final String nextElement = tokenizer.nextElement().toString();
407 if (lineBuilder.length() + nextElement.length() > 80) {
408 // Trim trailing whitespace
409 for (int i = lineBuilder.length() - 1; i >= 0 && lineBuilder.charAt(i) != ' '; --i) {
410 lineBuilder.setLength(i);
412 // Trim leading whitespace
413 while (lineBuilder.charAt(0) == ' ') {
414 lineBuilder.deleteCharAt(0);
416 sb.append(lineBuilder).append('\n');
417 lineBuilder.setLength(0);
419 if (nextLineIndent > 0) {
420 sb.append(lineIndent);
423 if (" ".equals(nextElement)) {
424 isFirstElementOnNewLineEmptyChar = true;
427 if (isFirstElementOnNewLineEmptyChar) {
428 isFirstElementOnNewLineEmptyChar = false;
430 lineBuilder.append(nextElement);
433 return sb.append(lineBuilder).append('\n').toString();
436 private static String encodeJavadocSymbols(final String description) {
437 return Strings.isNullOrEmpty(description) ? description
438 : AMP_MATCHER.replaceFrom(TAIL_COMMENT_PATTERN.matcher(description).replaceAll("*/"), "&");