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 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;
32 public final class TextTemplateUtil {
34 public static final String DOT = ".";
35 public static final String PATTERN_CONSTANT_NAME = "PATTERN_CONSTANTS";
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);
46 private TextTemplateUtil() {
47 throw new UnsupportedOperationException("Util class");
51 * Makes start of getter name LowerCase
53 * @param s getter name without prefix
54 * @return getter name starting in LowerCase
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;
62 * Wraps text as documentation, used in enum description
64 * @param text text for wrapping
65 * @return wrapped text
67 public static String wrapToDocumentation(final String text) {
71 final StringBuilder sb = new StringBuilder(NEW_LINE);
74 for (final String t : NL_SPLITTER.split(text)) {
87 * Returns formatted Javadoc, based on type
89 * @return formatted Javadoc, based on type
91 public static String formatDataForJavaDocBuilder(final String typeName) {
92 final StringBuilder stringBuilder = new StringBuilder();
93 stringBuilder.append("Class that builds {@link ")
95 .append("} instances.")
99 return stringBuilder.toString();
103 * Returns formatted Javadoc with possible additional comment, based on type
105 * @param additionalComment
106 * @return formatted Javadoc with possible additional comment, based on type
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())
116 javaDoc.append(additionalComment);
117 return javaDoc.toString();
121 * Returns properties names in formatted string
123 * @return properties names in formatted string
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));
131 * Returns formatted type description
133 * @return formatted type description
135 public static String formatDataForJavaDoc(final GeneratedType type) {
136 return type.getDescription().map(TextTemplateUtil::encodeJavadocSymbols).orElse("");
140 * Returns parameter name, based on given Type
143 * @return parameter name, based on given Type
145 public static String paramValue(final Type returnType, final String paramName) {
146 if (returnType instanceof ConcreteType) {
149 return 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 if (comment == null) {
163 return wrapToDocumentation(formatToParagraph(comment.trim(), 0));
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))
174 javaDoc.append(additionalComment);
175 return wrapToDocumentation(javaDoc.toString());
179 * Returns related Javadoc
180 * @param methodSignature
181 * @return related Javadoc
183 public static String getJavaDocForInterface(final MethodSignature methodSignature) {
184 if (methodSignature.getReturnType() == Types.VOID) {
187 final StringBuilder javaDoc = new StringBuilder();
188 javaDoc.append("@return ")
189 .append(asCode(methodSignature.getReturnType().getFullyQualifiedName()))
191 .append(asCode(propertyNameFromGetter(methodSignature)))
193 .append(asCode("null"))
194 .append(" if not present");
195 return formatDataForJavaDoc(methodSignature, javaDoc.toString());
198 private static String asCode(final String text) {
199 return "<code>" + text + "</code>";
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
207 public static String encodeAngleBrackets(String description) {
208 if (description != null) {
209 description = LT_MATCHER.replaceFrom(description, "<");
210 description = GT_MATCHER.replaceFrom(description, ">");
216 * Returns collection of properties as formatted String
218 * @return generated properties as formatted String
220 public static String propsAsArgs(final Iterable<GeneratedProperty> properties) {
221 return String.join(",", Iterables.transform(properties, prop -> "\"" + prop.getName() + "\""));
225 * Returns properties as formatted String
228 * @return Properties as formatted String
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"));
236 * Extracts available restrictions from given type
238 * @return restrictions from given type
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();
251 * sets fieldname according to property for return type
252 * method(type fieldname)
254 * @param property type from getter
256 public static String fieldName(final GeneratedProperty property) {
257 final String name = Preconditions.checkNotNull(property.getName());
258 return UNDERSCORE.concat(name);
262 * Template method which generates sequence of the names of the class attributes
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
267 public static String asArguments(final List<GeneratedProperty> parameters) {
268 return String.join(", ", Lists.transform(parameters, TextTemplateUtil::fieldName));
272 * Helper method for building getter
274 * @param field property name
275 * @return getter for propery
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));
285 * Returns built setter method body
288 * @param returnTypeName
289 * @return built setter method body
291 public static String setterMethod(final GeneratedProperty field, final String typeName, final String returnTypeName) {
292 final StringBuilder stringBuilder = new StringBuilder();
293 stringBuilder.append("public ")
296 .append(toFirstUpper(field.getName()))
298 .append(returnTypeName)
299 .append(" value) {\n this.")
300 .append(fieldName(field))
301 .append(" = value;\n return this;\n}\n");
302 return stringBuilder.toString();
306 * Returns simple name of underlying class
307 * @return Simple name of underlying class
309 public static String getSimpleNameForBuilder() {
310 return Builder.class.getSimpleName();
314 * Makes start of getter name uppercase
316 * @param s getter name without prefix
317 * @return getter name starting in uppercase
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;
325 * Cuts prefix from getter name
327 * @param getter getter name
328 * @return getter name without prefix
330 public static String propertyNameFromGetter(final MethodSignature getter) {
331 final String name = Preconditions.checkNotNull(getter.getName());
333 if (name.startsWith("is")) {
335 } else if (name.startsWith("get")) {
340 return toFirstLower(name.substring(prefix));
344 * Returns list of properties as formatted String
346 * @return formatted property list as String
348 public static String getPropertyList(final List<GeneratedProperty> properties) {
349 return String.join(", ", Lists.transform(properties, prop -> "base." + getterMethodName(prop) + "()"));
353 * util method for unionTemplateBuilderTemplate
354 * @return string with clarification for javadoc
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")
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")
365 return clarification.toString();
369 * Returns source path as String
371 * @return formatted String source path
373 public static String getSourcePath(final Module module) {
374 return "/".concat(module.getModuleSourcePath().replace(java.io.File.separatorChar, '/'));
378 * util method for unionTemplateBuilderTemplate
379 * @return needed access modifier
381 public static String getAccessModifier(final AccessModifier modifier) {
383 case PUBLIC: return "public ";
384 case PROTECTED: return "protected ";
385 case PRIVATE: return "private ";
391 * @param text Content of tag description
392 * @param nextLineIndent Number of spaces from left side default is 12
393 * @return formatted description
395 private static String formatToParagraph(final String text, final int nextLineIndent) {
396 if (Strings.isNullOrEmpty(text)) {
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);
407 while (tokenizer.hasMoreElements()) {
408 final String nextElement = tokenizer.nextElement().toString();
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);
415 // Trim leading whitespace
416 while (lineBuilder.charAt(0) == ' ') {
417 lineBuilder.deleteCharAt(0);
419 sb.append(lineBuilder).append('\n');
420 lineBuilder.setLength(0);
422 if (nextLineIndent > 0) {
423 sb.append(lineIndent);
426 if (" ".equals(nextElement)) {
427 isFirstElementOnNewLineEmptyChar = true;
430 if (isFirstElementOnNewLineEmptyChar) {
431 isFirstElementOnNewLineEmptyChar = false;
433 lineBuilder.append(nextElement);
436 return sb.append(lineBuilder).append('\n').toString();
439 private static String encodeJavadocSymbols(final String description) {
440 if (description == null || description.isEmpty()) {
443 final String ret = description.replace("*/", "*/");
444 return AMP_MATCHER.replaceFrom(ret, "&");