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 final Iterable<String> lineSplitText = NL_SPLITTER.split(text);
75 for (final String t : lineSplitText) {
89 * Returns formatted Javadoc, based on type
91 * @return formatted Javadoc, based on type
93 public static String formatDataForJavaDocBuilder(final String typeName) {
94 final StringBuilder stringBuilder = new StringBuilder();
95 stringBuilder.append("Class that builds {@link ")
97 .append("} instances.")
101 return stringBuilder.toString();
105 * Returns formatted Javadoc with possible additional comment, based on type
107 * @param additionalComment
108 * @return formatted Javadoc with possible additional comment, based on type
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())
118 javaDoc.append(additionalComment);
119 return javaDoc.toString();
123 * Returns properties names in formatted string
125 * @return properties names in formatted string
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));
133 * Returns formatted type description
135 * @return formatted type description
137 public static String formatDataForJavaDoc(final GeneratedType type) {
138 return type.getDescription().map(TextTemplateUtil::encodeJavadocSymbols).orElse("");
142 * Returns parameter name, based on given Type
145 * @return parameter name, based on given Type
147 public static String paramValue(final Type returnType, final String paramName) {
148 if (returnType instanceof ConcreteType) {
151 return paramName + ".getValue()";
156 * Template method which generates JAVA comments. InterfaceTemplate
158 * @param comment comment string with the comment for whole JAVA class
159 * @return string with comment in JAVA format
161 public static String asJavadoc(final String comment) {
162 if (comment == null) {
165 return wrapToDocumentation(formatToParagraph(comment.trim(), 0));
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))
176 javaDoc.append(additionalComment);
177 return wrapToDocumentation(javaDoc.toString());
181 * Returns related Javadoc
182 * @param methodSignature
183 * @return related Javadoc
185 public static String getJavaDocForInterface(final MethodSignature methodSignature) {
186 if (methodSignature.getReturnType() == Types.VOID) {
189 final StringBuilder javaDoc = new StringBuilder();
190 javaDoc.append("@return ")
191 .append(asCode(methodSignature.getReturnType().getFullyQualifiedName()))
193 .append(asCode(propertyNameFromGetter(methodSignature)))
195 .append(asCode("null"))
196 .append(" if not present");
197 return formatDataForJavaDoc(methodSignature, javaDoc.toString());
200 private static String asCode(final String text) {
201 return "<code>" + text + "</code>";
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
209 public static String encodeAngleBrackets(String description) {
210 if (description != null) {
211 description = LT_MATCHER.replaceFrom(description, "<");
212 description = GT_MATCHER.replaceFrom(description, ">");
218 * Returns collection of properties as formatted String
220 * @return generated properties as formatted String
222 public static String propsAsArgs(final Iterable<GeneratedProperty> properties) {
223 return String.join(",", Iterables.transform(properties, prop -> "\"" + prop.getName() + "\""));
227 * Returns properties as formatted String
230 * @return Properties as formatted String
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"));
238 * Extracts available restrictions from given type
240 * @return restrictions from given type
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();
253 * sets fieldname according to property for return type
254 * method(type fieldname)
256 * @param property type from getter
258 public static String fieldName(final GeneratedProperty property) {
259 final String name = Preconditions.checkNotNull(property.getName());
260 return UNDERSCORE.concat(name);
264 * Template method which generates sequence of the names of the class attributes
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
269 public static String asArguments(final List<GeneratedProperty> parameters) {
270 return String.join(", ", Lists.transform(parameters, TextTemplateUtil::fieldName));
274 * Helper method for building getter
276 * @param field property name
277 * @return getter for propery
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));
287 * Returns built setter method body
290 * @param returnTypeName
291 * @return built setter method body
293 public static String setterMethod(final GeneratedProperty field, final String typeName, final String returnTypeName) {
294 final StringBuilder stringBuilder = new StringBuilder();
295 stringBuilder.append("public ")
298 .append(toFirstUpper(field.getName()))
300 .append(returnTypeName)
301 .append(" value) {\n this.")
302 .append(fieldName(field))
303 .append(" = value;\n return this;\n}\n");
304 return stringBuilder.toString();
308 * Returns simple name of underlying class
309 * @return Simple name of underlying class
311 public static String getSimpleNameForBuilder() {
312 return Builder.class.getSimpleName();
316 * Makes start of getter name uppercase
318 * @param s getter name without prefix
319 * @return getter name starting in uppercase
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;
327 * Cuts prefix from getter name
329 * @param getter getter name
330 * @return getter name without prefix
332 public static String propertyNameFromGetter(final MethodSignature getter) {
333 final String name = Preconditions.checkNotNull(getter.getName());
335 if (name.startsWith("is")) {
337 } else if (name.startsWith("get")) {
342 return toFirstLower(name.substring(prefix));
346 * Returns list of properties as formatted String
348 * @return formatted property list as String
350 public static String getPropertyList(final List<GeneratedProperty> properties) {
351 return String.join(", ", Lists.transform(properties, prop -> "base." + getterMethodName(prop) + "()"));
355 * util method for unionTemplateBuilderTemplate
356 * @return string with clarification for javadoc
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")
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")
367 return clarification.toString();
371 * Returns source path as String
373 * @return formatted String source path
375 public static String getSourcePath(final Module module) {
376 return "/".concat(module.getModuleSourcePath().replace(java.io.File.separatorChar, '/'));
380 * util method for unionTemplateBuilderTemplate
381 * @return needed access modifier
383 public static String getAccessModifier(final AccessModifier modifier) {
385 case PUBLIC: return "public ";
386 case PROTECTED: return "protected ";
387 case PRIVATE: return "private ";
393 * @param text Content of tag description
394 * @param nextLineIndent Number of spaces from left side default is 12
395 * @return formatted description
397 private static String formatToParagraph(final String text, final int nextLineIndent) {
398 if (Strings.isNullOrEmpty(text)) {
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);
409 while (tokenizer.hasMoreElements()) {
410 final String nextElement = tokenizer.nextElement().toString();
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);
417 // Trim leading whitespace
418 while (lineBuilder.charAt(0) == ' ') {
419 lineBuilder.deleteCharAt(0);
421 sb.append(lineBuilder).append('\n');
422 lineBuilder.setLength(0);
424 if (nextLineIndent > 0) {
425 sb.append(lineIndent);
428 if (" ".equals(nextElement)) {
429 isFirstElementOnNewLineEmptyChar = true;
432 if (isFirstElementOnNewLineEmptyChar) {
433 isFirstElementOnNewLineEmptyChar = false;
435 lineBuilder.append(nextElement);
438 return sb.append(lineBuilder).append('\n').toString();
441 private static String encodeJavadocSymbols(final String description) {
442 if (description == null || description.isEmpty()) {
445 final String ret = description.replace("*/", "*/");
446 return AMP_MATCHER.replaceFrom(ret, "&");