Example usage for org.apache.commons.lang3.text StrBuilder appendSeparator

List of usage examples for org.apache.commons.lang3.text StrBuilder appendSeparator

Introduction

In this page you can find the example usage for org.apache.commons.lang3.text StrBuilder appendSeparator.

Prototype

public StrBuilder appendSeparator(final char separator) 

Source Link

Document

Appends a separator if the builder is currently non-empty.

Usage

From source file:com.mgmtp.perfload.perfalyzer.util.StrBuilderUtils.java

public static void appendEscapedAndQuoted(final StrBuilder sb, final char delimiter, final String value) {
    boolean foundLineBreak = false;

    sb.appendSeparator(delimiter);

    sb.append(CSV_QUOTE);/*from  w  w w  .j a  v  a2 s .c om*/
    if (value != null) {
        for (int i = 0, len = value.length(); i < len; ++i) {
            char c = value.charAt(i);
            switch (c) {
            case CSV_QUOTE:
                if (foundLineBreak) {
                    foundLineBreak = false;
                    sb.append(' ');
                }
                sb.append(c); // escape double quote, i. e. add quote character again
                break;
            case '\r':
            case '\n':
                foundLineBreak = true;
                continue;
            default:
                if (foundLineBreak) {
                    sb.append(' ');
                    foundLineBreak = false;
                }
                break;
            }
            sb.append(c);
        }
    }
    sb.append(CSV_QUOTE);
}

From source file:de.vandermeer.asciithemes.TA_EnumerateList.java

/**
 * Creates a new enumerate list with levels provided by given numbering schemes.
 * @param description list description//from www.  j  av  a2s  . c o  m
 * @param numbering an array with numbering schemes
 * @return new list
 */
public static TA_EnumerateList create(final String description, final TA_Numbering... numbering) {
    Validate.notNull(numbering);
    Validate.noNullElements(numbering);
    Validate.notBlank(description);

    return new TA_EnumerateList() {
        @Override
        public int getMaxLevel() {
            return numbering.length;
        }

        @Override
        public String getLabel(int level) {
            return numbering[0].getNumber(level);
        }

        @Override
        public String getLabel(int[] levels, String separator, boolean useSepOnLast) {
            String simple = TA_EnumerateList.super.getLabel(levels, separator, useSepOnLast);
            if (simple != null) {
                return simple;
            }

            Validate.notNull(levels);
            Validate.validState(numbering.length >= levels.length,
                    "the required levels are going deeper than the provided numbering: levels <" + levels.length
                            + "> provided <" + numbering.length + ">");
            StrBuilder ret = new StrBuilder();
            for (int i = 0; i < levels.length; i++) {
                ret.appendSeparator(separator);
                ret.append(numbering[i].getNumber(levels[i]));
            }
            if (useSepOnLast) {
                ret.append(separator);
            }
            return ret.toString();
        }

        @Override
        public String getDescription() {
            return description;
        }
    };
}

From source file:de.vandermeer.skb.base.utils.Skb_TextUtils.java

/**
 * Returns a transformer that takes an iterator and returns a String Builder.
 * @param <T> common target type/*from w  w w  .j ava2  s.c om*/
 * @param separator string or character to use as separator between elements of the iterator
 * @param toText a transformer used to transform an object to text
 * @return transformer that returns a String Builder that concatenates all elements from the iterator using the given separator
 */
public static final <T extends Object> Skb_Transformer<Object, StrBuilder> MANYOBJECTS_TO_STRBUILDER(
        final Object separator, final Skb_Transformer<Object, T> toText) {
    return new Skb_Transformer<Object, StrBuilder>() {
        @Override
        public StrBuilder transform(Object obj) {
            StrBuilder ret = new StrBuilder(50);
            if (obj != null && toText != null) {
                if (obj instanceof Iterator) {
                    while (((Iterator<?>) obj).hasNext()) {
                        ret.appendSeparator(separator.toString());
                        ret.append(toText.transform(((Iterator<?>) obj).next()));
                    }
                } else if (obj instanceof Iterable) {
                    for (Object o : (Iterable<?>) obj) {
                        ret.appendSeparator(separator.toString());
                        ret.append(toText.transform(o));
                    }
                } else if (obj instanceof Object[]) {
                    for (int i = 0; i < ((Object[]) obj).length; i++) {
                        ret.appendSeparator(separator.toString());
                        ret.append(toText.transform(((Object[]) obj)[i]));
                    }
                } else {
                    ret.appendSeparator(separator.toString());
                    ret.append(toText.transform(obj));
                }
            }
            return ret;
        }
    };
}

From source file:de.vandermeer.skb.mvn.pm.model.PM_Model.java

/**
 * Update dependencies for each loaded project.
 * Once all projects and the build version dependencies are loaded, we can update the dependencies for each individual project.
 * This allows forward definition of dependencies.
 *//*  w w  w. j av a  2s . c o  m*/
public void updateProjectDependencies() {
    StrBuilder error = new StrBuilder();
    for (Model_ManagedProject mp : this.projects.values()) {
        error.appendSeparator('\n');
        error.append(mp.updateDependencies());
    }
    if (error.size() > 0) {
        throw new IllegalArgumentException("problems updating dependencies, see below\n" + error.toString());
    }
}

From source file:de.vandermeer.asciithemes.TA_EnumerateList.java

/**
 * Returns a label constructed of labels for each given level.
 * @param levels the levels, each entry marks the number for the given level
 * @param separator the separator between numbers, can be null
 * @param useSepOnLast use true if the last number gets a separator, false if not
 * @return label string, unless overwritten this will be null if the max level is not -1
 * @throws IllegalArgumentException if any requested level is not supported
 *///w w  w  .  j  a  v  a2 s  .  com
default String getLabel(int[] levels, String separator, boolean useSepOnLast) {
    Validate.notNull(levels);
    if (this.getMaxLevel() == -1) {
        StrBuilder ret = new StrBuilder();
        for (int l : levels) {
            ret.appendSeparator(separator);
            ret.append(this.getLabel(l));
        }
        if (useSepOnLast) {
            ret.append(separator);
        }
        return ret.toString();
    }
    return null;
}

From source file:de.vandermeer.skb.interfaces.transformers.Object_To_StrBuilder.java

/**
 * Transforms an object to a string builder using the given builder.
 * @param obj input object//ww  w  .ja  v a2 s.c o m
 * @param sb a given builder, new builder will be created if null
 * @return string builder
 */
default StrBuilder transform(Object obj, StrBuilder sb) {
    Validate.notNull(obj);
    sb = (sb == null) ? new StrBuilder() : sb;

    if (obj instanceof HasText) {
        sb.appendSeparator(' ').append(((HasText) obj).getText());
    } else if (obj instanceof HasTextCluster) {
        Collection<String> collection = ((HasTextCluster) obj).getTextAsCollection();
        if (collection != null) {
            for (String s : collection) {
                sb.appendSeparator(' ').append(s);
            }
        }
    } else if (obj instanceof ST) {
        sb.appendSeparator(' ').append(((ST) obj).render());
    } else if (obj instanceof DoesRender) {
        sb.appendSeparator(' ').append(((DoesRender) obj).render());
    } else if (obj instanceof DoesRenderToWidth) {
        sb.appendSeparator(' ').append(((DoesRenderToWidth) obj).render(80));
    } else if (obj instanceof RendersToCluster) {
        Collection<String> collection = ((RendersToCluster) obj).renderAsCollection();
        if (collection != null) {
            for (String s : collection) {
                sb.appendSeparator(' ').append(s);
            }
        }
    } else if (obj instanceof RendersToClusterWidth) {
        Collection<String> collection = ((RendersToClusterWidth) obj).renderAsCollection(80);
        if (collection != null) {
            for (String s : collection) {
                sb.appendSeparator(' ').append(s);
            }
        }
    } else if (obj instanceof Iterator<?>) {
        Iterator<?> it = (Iterator<?>) obj;
        while (it.hasNext()) {
            Object o = it.next();
            if (o != null) {
                this.transform(o, sb);
            }
        }
    } else if (obj instanceof Iterable<?>) {
        for (Object o : (Iterable<?>) obj) {
            if (o != null) {
                this.transform(o, sb);
            }
        }
    } else if (obj.getClass().isInstance(new Object[] {})) {
        Object[] oa = (Object[]) obj;
        for (Object o : oa) {
            if (o != null) {
                this.transform(o, sb);
            }
        }
    } else {
        // this will capture Strings and everything that uses toString (like other StrBuilders)
        sb.appendSeparator(' ').append(obj);
    }
    return sb;
}

From source file:com.mgmtp.perfload.perfalyzer.normalization.Normalizer.java

public void normalize(final File file) throws IOException {
    checkState(!file.isAbsolute(), "'file' must be relative");

    String filePath = file.getPath();
    String[] pathElements = split(getPath(filePath), SystemUtils.FILE_SEPARATOR); // strip out dir

    StrBuilder sb = new StrBuilder();
    for (int i = 0; i < pathElements.length; ++i) {
        if (i == 1) {
            continue; // strip out dir, e. g. perfmon-logs, measuring-logs
        }// w w  w.ja v a  2s. c  o m
        sb.appendSeparator(SystemUtils.FILE_SEPARATOR);
        sb.append(pathElements[i]);
    }
    String dirPath = sb.toString();

    Map<String, FileChannel> channels = newHashMap();
    List<OutputStream> outputStreams = newArrayList();
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(new File(sourceDir, filePath)); //relative to source dir
        for (Scanner scanner = new Scanner(fis.getChannel(), Charsets.UTF_8.name()); scanner.hasNext();) {
            String line = scanner.nextLine();
            if (trimToNull(line) == null || line.startsWith("#")) {
                continue;
            }
            List<ChannelData> channelDataList = normalizingStrategy.normalizeLine(line);
            for (ChannelData channelData : channelDataList) {

                FileChannel channel = channels.get(channelData.getChannelKey());
                if (channel == null) {
                    String baseName = channelData.getChannelBaseName();
                    String key = channelData.getChannelKey();
                    String fileName = new File(dirPath, String.format("[%s][%s].csv", baseName, key)).getPath();
                    File destFile = new File(destDir, fileName);
                    destFile.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(destFile);
                    outputStreams.add(fos);
                    channel = fos.getChannel();
                    channels.put(channelData.getChannelKey(), channel);
                }

                writeLineToChannel(channel, channelData.getValue(), Charsets.UTF_8);
            }
        }
    } finally {
        outputStreams.forEach(IOUtils::closeQuietly);
        closeQuietly(fis);
    }
}

From source file:de.vandermeer.skb.datatool.entries.affiliations.AffiliationEntry.java

@Override
public void loadEntry(String keyStart, Map<String, Object> data, CoreSettings cs) throws URISyntaxException {
    this.entryMap = DataUtilities.loadEntry(this.getSchema(), keyStart, data, this.loadedTypes, cs);

    this.entryMap.put(EntryKeys.LOCAL_ACRONYM_LINK, DataUtilities.loadDataString(EntryKeys.ACRONYM, data));
    this.entryMap.put(AffiliationKeys.LOCAL_AFF_TYPE_LINK,
            DataUtilities.loadDataString(AffiliationKeys.AFF_TYPE, data));

    StrBuilder msg = new StrBuilder(50);
    if (this.getName() == null) {
        if (this.getAcronymLink() == null) {
            msg.appendSeparator(", ");
            msg.append("no long name and no acronym given");
        }//  ww  w.j  a  va2s . c  o m
    } else {
        if (this.getAcronymLink() == null && this.getShortName() == null) {
            msg.appendSeparator(", ");
            msg.append("no short name nor acronym given");
        }
        if (this.getAcronymLink() != null && this.getShortName() != null) {
            msg.appendSeparator(", ");
            msg.append("no short name and acronym given");
        }
    }

    if (this.getKey() != null) {
        this.entryMap.put(CommonKeys.KEY, keyStart + this.getKey());
    } else if (this.getShortName() != null) {
        this.entryMap.put(CommonKeys.KEY, keyStart + this.getShortName());
    } else if (this.getAcronymLink() != null) {
        this.entryMap.put(AffiliationKeys.AFF_LONG, this.getAcronym().getLong());
        this.entryMap.put(AffiliationKeys.AFF_SHORT, this.getAcronym().getShort());
        this.entryMap.put(CommonKeys.KEY, keyStart + this.getShortName());
    } else {
        msg.appendSeparator(", ");
        msg.append("cannot generate key");
    }

    if (msg.size() > 0) {
        throw new IllegalArgumentException(msg.toString());
    }
}

From source file:com.mgmtp.perfload.perfalyzer.workflow.GcLogWorkflow.java

@Override
public List<Runnable> getNormalizationTasks(final File inputDir, final File outputDir) {
    List<File> inputFiles = listFiles(inputDir);
    return inputFiles.stream().filter(fileNameStartsWith("gclog")).map(file -> {
        Runnable task = () -> {
            String filePath = file.getPath();
            String[] pathElements = split(getPath(filePath), SystemUtils.FILE_SEPARATOR); // strip out dir

            StrBuilder sb = new StrBuilder();
            for (int i = 0; i < pathElements.length; ++i) {
                if (i == 1) {
                    continue; // strip out dir, e. g. perfmon-logs, measuring-logs
                }//from w w w . j ava 2 s  . c o m
                sb.appendSeparator(SystemUtils.FILE_SEPARATOR);
                sb.append(pathElements[i]);
            }
            String dirPath = sb.toString();

            String s = trimToNull(substringAfter(getBaseName(filePath), "gclog"));
            File destFile = new File(outputDir, dirPath + SystemUtils.FILE_SEPARATOR + "[gclog]"
                    + (s != null ? "[" + s + "]." : ".") + getExtension(filePath));

            try {
                copyFile(new File(inputDir, file.getPath()), destFile);
            } catch (IOException ex) {
                throw new PerfAlyzerException("Error copying file: " + file, ex);
            }
        };
        return task;
    }).collect(toList());
}

From source file:de.vandermeer.skb.interfaces.transformers.textformat.Text_To_WrappedFormat.java

@Override
default Pair<ArrayList<String>, ArrayList<String>> transform(String input) {
    Validate.notBlank(input);/*ww  w.  j  ava 2 s. com*/
    Validate.isTrue(this.getWidth() > 0);

    ArrayList<String> topList = new ArrayList<>();
    ArrayList<String> bottomList = new ArrayList<>();

    //an emergency break, counting loops to avoid endless loops
    int count;

    String text = StringUtils.replacePattern(input, "\\r\\n|\\r|\\n", LINEBREAK);
    text = StringUtils.replace(text, "<br>", LINEBREAK);
    text = StringUtils.replace(text, "<br/>", LINEBREAK);

    StrBuilder sb = new StrBuilder(text);
    if (this.getTopSettings() != null) {
        //we have a top request, do that one first
        Validate.notNull(this.getTopSettings().getLeft());
        Validate.notNull(this.getTopSettings().getRight());
        Validate.isTrue(this.getTopSettings().getLeft() > 0);
        Validate.isTrue(this.getTopSettings().getRight() > 0);

        int topLines = this.getTopSettings().getLeft();
        int topWidth = this.getTopSettings().getRight();
        count = 0;

        while (sb.size() > 0 && topLines > 0 && count++ < 200) {
            if (sb.startsWith(LINEBREAK)) {
                sb.replaceFirst(LINEBREAK, "");
            }
            String s = null;
            boolean wln = false;
            if (sb.indexOf(LINEBREAK) > 0) {
                s = sb.substring(0, sb.indexOf(LINEBREAK));
                wln = true;
                //sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), "");
            } else {
                s = sb.toString();
                //sb.clear();
            }
            String wrap = WordUtils.wrap(s, topWidth, LINEBREAK, true);
            StrTokenizer tok = new StrTokenizer(wrap, LINEBREAK).setIgnoreEmptyTokens(false);
            String[] ar = tok.getTokenArray();
            if (ar.length <= topLines) {
                //all lines done, cleanup
                for (String str : ar) {
                    topList.add(str.trim());
                }
                if (wln == true) {
                    //if we had a conditional linebreak there might be more text, remove the line we processed
                    sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), "");
                } else {
                    //no conditional line break, clean builder
                    sb.clear();
                }
                topLines = 0;
            } else {
                //we have more lines than we need, so remove the text we have from the builder and copy processed lines
                StrBuilder replace = new StrBuilder();
                for (int i = 0; i < topLines; i++) {
                    topList.add(ar[i].trim());
                    replace.appendSeparator(' ').append(ar[i]);
                }
                if (wln == true) {
                    replace.append(LINEBREAK);
                }
                sb.replaceFirst(replace.toString(), "");
                topLines = 0;
            }
        }
    }

    //no top, simple wrapping with recognition of conditional line breaks
    count = 0;
    while (sb.size() > 0 && count++ < 200) {
        if (sb.startsWith(LINEBREAK)) {
            sb.replaceFirst(LINEBREAK, "");
        }
        String s = null;
        if (sb.indexOf(LINEBREAK) > 0) {
            s = sb.substring(0, sb.indexOf(LINEBREAK));
            sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), "");
        } else {
            s = sb.toString();
            sb.clear();
        }
        s = WordUtils.wrap(s, this.getWidth(), LINEBREAK, true);
        StrTokenizer tok = new StrTokenizer(s, LINEBREAK).setIgnoreEmptyTokens(false);
        for (String str : tok.getTokenArray()) {
            bottomList.add(str.trim());
        }
    }

    return Pair.of(topList, bottomList);
}