1 package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
3 import com.google.common.base.Joiner;
4 import com.google.common.base.Optional;
5 import com.google.common.base.Splitter;
6 import com.google.common.base.Strings;
7 import org.apache.commons.io.IOUtils;
8 import org.apache.commons.lang3.StringUtils;
9 import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
10 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.util.List;
16 import java.util.regex.Pattern;
18 public class StringUtil {
19 private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
22 * @param list of strings to be joined by ','
23 * @param prefix e.g. 'extends' or 'implements'
25 public static String prefixAndJoin(List<FullyQualifiedName> list, String prefix) {
29 Joiner joiner = Joiner.on(",");
30 return " " + prefix + " " + joiner.join(list);
33 public static String addAsterixAtEachLineStart(String input) {
34 String s = Pattern.compile("^", Pattern.MULTILINE).matcher(input).replaceAll("* ");
35 // remove trailing spaces
36 s = Pattern.compile("\\s+$", Pattern.MULTILINE).matcher(s).replaceAll("");
37 s = ensureEndsWithSingleNewLine(s);
41 private static String ensureEndsWithSingleNewLine(String s) {
42 // .split Only trailing empty strings are skipped.
43 String[] split = s.split("\n");
44 s = Joiner.on("\n").join(split);
49 public static String writeComment(String input, boolean isJavadoc) {
50 StringBuilder content = new StringBuilder();
57 content.append(addAsterixAtEachLineStart(input));
58 content.append("*/\n");
59 return content.toString();
63 public static Optional<String> loadCopyright() {
64 try (InputStream in = StringUtil.class.getResourceAsStream("/copyright.txt")) {
66 return Optional.of(IOUtils.toString(in));
68 } catch (IOException e) {
69 logger.warn("Cannot load copyright.txt", e);
71 return Optional.absent();
74 public static String formatJavaSource(String input) {
75 Iterable<String> split = Splitter.on("\n").trimResults().split(input);
78 StringBuilder sb = new StringBuilder();
79 int intends = 0, empty = 0;
80 for (String line : split) {
81 intends -= StringUtils.countMatches(line, "}");
85 if (line.isEmpty() == false) {
86 sb.append(Strings.repeat(" ", basicIndent * intends));
91 empty++; // one empty line is allowed
96 intends += StringUtils.countMatches(line, "{");
98 return ensureEndsWithSingleNewLine(sb.toString());