2 * Copyright (c) 2013, 2015 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.controller.config.yangjmxgenerator.plugin.util;
11 import com.google.common.base.Joiner;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import java.util.List;
16 import java.util.regex.Pattern;
17 import org.apache.commons.lang3.StringUtils;
18 import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 public class StringUtil {
23 private static final Logger LOG = LoggerFactory.getLogger(StringUtil.class);
26 * @param list of strings to be joined by ','
27 * @param prefix e.g. 'extends' or 'implements'
29 public static String prefixAndJoin(List<FullyQualifiedName> list, String prefix) {
33 Joiner joiner = Joiner.on(",");
34 return " " + prefix + " " + joiner.join(list);
37 public static String addAsterixAtEachLineStart(String input) {
38 String s = Pattern.compile("^", Pattern.MULTILINE).matcher(input).replaceAll("* ");
39 // remove trailing spaces
40 s = Pattern.compile("\\s+$", Pattern.MULTILINE).matcher(s).replaceAll("");
41 s = ensureEndsWithSingleNewLine(s);
45 private static String ensureEndsWithSingleNewLine(String s) {
46 // .split Only trailing empty strings are skipped.
47 String[] split = s.split("\n");
48 s = Joiner.on("\n").join(split);
53 public static String writeComment(String input, boolean isJavadoc) {
54 StringBuilder content = new StringBuilder();
61 content.append(addAsterixAtEachLineStart(input));
62 content.append("*/\n");
63 return content.toString();
67 public static Optional<String> loadCopyright() {
69 * FIXME: BUG-980: this is a nice feature, but the copyright needs to come
70 * from the project being processed, not this one.
71 try (InputStream in = StringUtil.class.getResourceAsStream("/copyright.txt")) {
73 return Optional.of(IOUtils.toString(in));
75 } catch (IOException e) {
76 LOG.warn("Cannot load copyright.txt", e);
80 return Optional.absent();
83 public static String formatJavaSource(String input) {
84 Iterable<String> split = Splitter.on("\n").trimResults().split(input);
87 StringBuilder sb = new StringBuilder();
88 int intends = 0, empty = 0;
89 for (String line : split) {
90 intends -= StringUtils.countMatches(line, "}");
94 if (line.isEmpty() == false) {
95 sb.append(Strings.repeat(" ", basicIndent * intends));
100 empty++; // one empty line is allowed
105 intends += StringUtils.countMatches(line, "{");
107 return ensureEndsWithSingleNewLine(sb.toString());