Example usage for org.apache.commons.lang3 StringUtils chomp

List of usage examples for org.apache.commons.lang3 StringUtils chomp

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils chomp.

Prototype

public static String chomp(final String str) 

Source Link

Document

Removes one newline from end of a String if it's there, otherwise leave it alone.

Usage

From source file:com.gs.obevo.db.impl.core.reader.TextMarkupDocumentReaderOld.java

private ImmutableList<TextMarkupDocumentSection> parseString(String text, MutableList<String> elementsToCheck,
        boolean recurse, String elementPrefix) {
    MutableList<TextMarkupDocumentSection> sections = Lists.mutable.empty();
    while (true) {
        int earliestIndex = Integer.MAX_VALUE;

        for (String firstLevelElement : elementsToCheck) {
            int index = text.indexOf(elementPrefix + " " + firstLevelElement, 1);
            if (index != -1 && index < earliestIndex) {
                earliestIndex = index;/*  w w w  .  j a v a  2s. c o m*/
            }
        }

        if (earliestIndex == Integer.MAX_VALUE) {
            sections.add(new TextMarkupDocumentSection(null, text));
            break;
        } else {
            sections.add(new TextMarkupDocumentSection(null, text.substring(0, earliestIndex)));
            text = text.substring(earliestIndex);
        }
    }
    for (TextMarkupDocumentSection section : sections) {
        MutableMap<String, String> attrs = Maps.mutable.empty();
        MutableSet<String> toggles = Sets.mutable.empty();
        String content = StringUtils.chomp(section.getContent());

        String[] contents = content.split("\\r?\\n", 2);
        String firstLine = contents[0];

        for (String elementToCheck : elementsToCheck) {
            if (firstLine.startsWith(elementPrefix + " " + elementToCheck)) {
                section.setName(elementToCheck);
                String[] args = StringUtils.splitByWholeSeparator(firstLine, " ");
                for (String arg : args) {
                    if (arg.contains("=")) {
                        String[] attr = arg.split("=");
                        if (attr.length > 2) {
                            throw new IllegalArgumentException(
                                    "Cannot mark = multiple times in a parameter - " + firstLine);
                        }
                        String attrVal = attr[1];
                        if (attrVal.startsWith("\"") && attrVal.endsWith("\"")) {
                            attrVal = attrVal.substring(1, attrVal.length() - 1);
                        }
                        attrs.put(attr[0], attrVal);
                    } else {
                        toggles.add(arg);
                    }
                }
                if (contents.length > 1) {
                    content = contents[1];
                } else {
                    content = null;
                }
            }
        }
        section.setAttrs(attrs.toImmutable());
        section.setToggles(toggles.toImmutable());

        if (!recurse) {
            section.setContent(content);
        } else if (content != null) {
            ImmutableList<TextMarkupDocumentSection> subsections = this.parseString(content,
                    this.secondLevelElements, false, "//");
            if (subsections.size() == 1) {
                section.setContent(content);
            } else {
                section.setContent(subsections.get(0).getContent());
                section.setSubsections(subsections.subList(1, subsections.size()));
            }
        } else {
            section.setContent(null);
        }
    }

    return sections.toImmutable();
}

From source file:eu.project.ttc.engines.variant.VariantRuleYamlIO.java

private void parseRule(VariantRuleBuilder builder, String ruleName, Object valueStr) {
    Preconditions.checkArgument(valueStr instanceof CharSequence,
            String.format("Bad format for property rule (in rule %s). String expected. Got %s", ruleName,
                    valueStr.getClass().getName()));
    builder.rule(StringUtils.chomp((String) valueStr));
}

From source file:com.gs.obevo.impl.util.MultiLineStringSplitter.java

@Override
public MutableList<String> valueOf(String inputString) {
    inputString += "\n"; // add sentinel to facilitate line split

    MutableList<SqlToken> sqlTokens = this.tokenParser.parseTokens(inputString);
    sqlTokens = this.collapseWhiteSpaceAndTokens(sqlTokens);

    MutableList<String> finalSplitStrings = Lists.mutable.empty();
    String currentSql = "";

    for (SqlToken sqlToken : sqlTokens) {
        if (sqlToken.getTokenType() == SqlTokenType.COMMENT || sqlToken.getTokenType() == SqlTokenType.STRING) {
            currentSql += sqlToken.getText();
        } else {//w  w  w .  j  a va2s. c  o  m
            String pattern = splitOnWholeLine ? "(?i)^" + this.splitToken + "$" : this.splitToken;
            MutableList<String> splitStrings = Lists.mutable
                    .with(Pattern.compile(pattern, Pattern.MULTILINE).split(sqlToken.getText()));
            if (splitStrings.isEmpty()) {
                // means that we exactly match
                finalSplitStrings.add(currentSql);
                currentSql = "";
            } else if (splitStrings.size() == 1) {
                currentSql += sqlToken.getText();
            } else {
                splitStrings.set(0, currentSql + splitStrings.get(0));

                if (splitOnWholeLine) {
                    if (splitStrings.size() > 1) {
                        splitStrings.set(0, StringUtils.chomp(splitStrings.get(0)));
                        for (int i = 1; i < splitStrings.size(); i++) {
                            String newSql = splitStrings.get(i);
                            if (newSql.startsWith("\n")) {
                                newSql = newSql.replaceFirst("^\n", "");
                            } else if (newSql.startsWith("\r\n")) {
                                newSql = newSql.replaceFirst("^\r\n", "");
                            }

                            // Chomping the end of each sql due to the split of the GO statement
                            if (i < splitStrings.size() - 1) {
                                newSql = StringUtils.chomp(newSql);
                            }
                            splitStrings.set(i, newSql);
                        }
                    }
                }

                finalSplitStrings.addAll(splitStrings.subList(0, splitStrings.size() - 1));
                currentSql = splitStrings.getLast();
            }
        }
    }

    if (!currentSql.isEmpty()) {
        finalSplitStrings.add(currentSql);
    }

    // accounting for the sentinel
    if (finalSplitStrings.getLast().isEmpty()) {
        finalSplitStrings.remove(finalSplitStrings.size() - 1);
    } else {
        finalSplitStrings.set(finalSplitStrings.size() - 1, StringUtils.chomp(finalSplitStrings.getLast()));
    }

    return finalSplitStrings;
}

From source file:de.openali.odysseus.chart.ext.base.layer.TooltipFormatter.java

public String format() {
    final StringWriter out = new StringWriter();
    final PrintWriter pw = new PrintWriter(out);

    if (m_header != null) {
        pw.println(m_header);/*from   www.  ja v  a  2  s.co m*/
        pw.println();
    }

    for (final String[] texts : m_lines) {
        for (int i = 0; i < texts.length; i++) {
            final String alignedText = alignText(texts, i);
            pw.append(alignedText);

            /* one space between columns */
            if (i != texts.length - 1)
                pw.append(' ');
        }

        pw.println();
    }

    for (String footer : m_footer)
        pw.println(footer);

    pw.flush();
    return StringUtils.chomp(out.toString());
}

From source file:com.iorga.iraj.security.SecurityUtils.java

public static String computeDataSignature(final String secretAccessKey, final String data)
        throws NoSuchAlgorithmException, InvalidKeyException {
    final SecretKeySpec secretKeySpec = new SecretKeySpec(secretAccessKey.getBytes(UTF8_CHARSET), "HmacSHA1");
    final Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(secretKeySpec);//from  w w  w.j a v a 2  s. c om
    final String signature = Base64.encodeBase64String(mac.doFinal(data.getBytes(UTF8_CHARSET)));
    return StringUtils.chomp(signature);
}

From source file:com.gs.obevo.db.impl.core.reader.TextMarkupDocumentReader.java

private MutableList<Pair<String, String>> splitIntoMainSections(String text,
        ImmutableList<String> elementsToCheck, String elementPrefix) {
    MutableList<Pair<String, String>> outerSections = Lists.mutable.empty();
    String nextSectionName = null;
    boolean startOfSearch = true;

    // here, we go in a loop searching for the next referenc of "[elementPrefix] [sectionName]", e.g. //// CHANGE
    // By each of those points, we split those into separate text sections and return back to the client.
    // We aim to preserve the line breaks found when parsing the sections
    while (text != null) {
        String currentSectionName = nextSectionName;
        String currentSectionText;

        int earliestIndex = Integer.MAX_VALUE;

        for (String firstLevelElement : elementsToCheck) {
            // on the first search, the text may start w/ the section; hence, we set the search fromIndex param to 0.
            // Subsequently, the index picks up at the beginning of the next section; hence, we must start
            // the search at the next character, so the fromIndex param is 1
            int index = text.indexOf(elementPrefix + " " + firstLevelElement, startOfSearch ? 0 : 1);

            if (index != -1 && index < earliestIndex) {
                earliestIndex = index;//from   w  w  w. j a v a  2s  . co m
                nextSectionName = firstLevelElement;
            }
        }

        startOfSearch = false;

        if (earliestIndex == Integer.MAX_VALUE) {
            currentSectionText = StringUtils.chomp(text);
            text = null;
        } else {
            currentSectionText = StringUtils.chomp(text.substring(0, earliestIndex));
            text = text.substring(earliestIndex);
        }

        outerSections.add(Tuples.pair(currentSectionName, currentSectionText));
    }
    return outerSections;
}

From source file:adapter.davis.DavisSensor.java

/**
 * Sends commands to serial port. /*from w  ww .  ja  va  2s . c om*/
 * @param command String representation of the command which is used as a byte array in UTF-8 encoding.
 */
private void send(String command) {
    try {
        logger.info("Sending command " + StringUtils.chomp(command));

        byte[] byteArray = command.getBytes("UTF-8");

        this.out.write(byteArray);
        this.out.flush();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.flapdoodle.embed.process.runtime.AbstractProcess.java

protected static int getPidFromFile(File pidFile) throws IOException {
    // wait for file to be created
    int tries = 0;
    while (!pidFile.exists() && tries < 5) {
        try {//from w w w.  j  a  v a2  s . co m
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            // ignore
        }
        logger.warn("Didn't find pid file in try {}, waiting 100ms...", tries);
        tries++;
    }
    // don't check file to be there. want to throw IOException if
    // something happens
    if (!pidFile.exists()) {
        throw new IOException("Could not find pid file " + pidFile);
    }

    // read the file, wait for the pid string to appear
    String fileContent = StringUtils
            .chomp(StringUtils.strip(new String(java.nio.file.Files.readAllBytes(pidFile.toPath()))));
    tries = 0;
    while (StringUtils.isBlank(fileContent) && tries < 5) {
        fileContent = StringUtils
                .chomp(StringUtils.strip(new String(java.nio.file.Files.readAllBytes(pidFile.toPath()))));
        try {
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            // ignore
        }
        tries++;
    }
    // check for empty file
    if (StringUtils.isBlank(fileContent)) {
        throw new IOException(
                "Pidfile " + pidFile + "does not contain a pid. Waited for " + tries * 100 + "ms.");
    }
    // pidfile exists and has content
    try {
        return Integer.parseInt(fileContent);
    } catch (NumberFormatException e) {
        throw new IOException("Pidfile " + pidFile + "does not contain a valid pid. Content: " + fileContent);
    }
}

From source file:com.iorga.iraj.security.SecurityUtils.java

/**
 * Generates a 40 length String secret access key
 * @return a 40 length Base64 encoded String
 *///from   w  ww .  j  a v a2s  .  c  om
public static String generateSecretAccessKey() {
    final byte[] secretAccessKeyBytes = new byte[30];
    SECURE_RANDOM.nextBytes(secretAccessKeyBytes);
    return StringUtils.chomp(Base64.encodeBase64String(secretAccessKeyBytes));
}

From source file:de.adorsys.multibanking.hbci.model.HbciMapping.java

private static String getUsage(List<String> lines) {
    StringBuilder sb = new StringBuilder();

    if (lines != null) {
        for (String line : lines) {
            if (line != null) {
                sb.append(StringUtils.chomp(line));
                sb.append(line.length() < 27 ? " " : "");
            }/*from  w ww.  java 2 s.c o  m*/
        }
    }

    return WordUtils.capitalizeFully(sb.toString().trim(), ' ', '/');
}