Example usage for org.apache.commons.lang.text StrBuilder toString

List of usage examples for org.apache.commons.lang.text StrBuilder toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Gets a String version of the string builder, creating a new instance each time the method is called.

Usage

From source file:com.ryft.spark.connector.examples.SimplePairRDDExampleJ.java

public static void main(String[] args) {
    final SparkConf sparkConf = new SparkConf().setAppName("SimplePairRDDExampleJ").setMaster("local[2]");

    final SparkContext sc = new SparkContext(sparkConf);
    final SparkContextJavaFunctions javaFunctions = RyftJavaUtil.javaFunctions(sc);
    final byte fuzziness = 0;
    final int surrounding = 10;
    final List queries = toScalaList(RyftQueryUtil.toSimpleQueries("Jones", "Thomas"));

    final RyftPairJavaRDD rdd = javaFunctions.ryftPairJavaRDD(queries,
            RyftQueryOptions.apply("passengers.txt", surrounding, fuzziness), RyftJavaUtil.ryftQueryToEmptyList,
            RyftJavaUtil.stringToEmptySet);

    final Map<String, Long> countByKey = rdd.countByKey();
    final StrBuilder sb = new StrBuilder();
    countByKey.forEach((key, value) -> sb.append(key + " -> " + value + "\n"));
    logger.info("RDD count by key: \n{}", sb.toString());
}

From source file:me.taylorkelly.mywarp.util.CommandUtils.java

/**
 * Joins all warps in the given collection in one string, separated by {@code ", "}.
 *
 * @param warps a collection of warps/*from   w  ww  . jav  a2  s  . c o m*/
 * @return a string with all warp-names or {@code -} if the collection was empty
 */
public static String joinWarps(Collection<Warp> warps) {
    if (warps.isEmpty()) {
        return "-";
    }

    StrBuilder ret = new StrBuilder();
    for (Warp warp : warps) {
        ret.appendSeparator(", ");
        ret.append(warp.getName());
    }
    return ret.toString();
}

From source file:me.taylorkelly.mywarp.util.CommandUtils.java

/**
 * Joins all worlds in the given collection in one string, separated by {@code ", "}.
 *
 * @param worlds a collection of worlds/*from www.  ja  v a2s . com*/
 * @return a string with all world-names or {@code -} if the collection was empty
 */
public static String joinWorlds(Collection<LocalWorld> worlds) {
    if (worlds.isEmpty()) {
        return "-";
    }

    StrBuilder ret = new StrBuilder();
    for (LocalWorld world : worlds) {
        ret.appendSeparator(", ");
        ret.append(world.getName());
    }
    return ret.toString();
}

From source file:mitm.common.tools.PfxTool.java

private static void printKeystoreDetails(KeyStore keyStore) throws KeyStoreException {
    Enumeration<String> aliases = keyStore.aliases();

    int count = 0;

    System.out.println("**** BEGIN ENTRIES ***");

    while (aliases.hasMoreElements()) {
        count++;/*from  w  w  w.ja  v a2  s  . c o  m*/

        String alias = aliases.nextElement();

        StrBuilder sb = new StrBuilder();

        sb.append("Alias: ").append(alias).append(", key entry: ").append(keyStore.isKeyEntry(alias));

        System.out.println(sb.toString());
    }

    System.out.println("**** END ENTRIES ***");
    System.out.println("Nr of entries: " + count);
}

From source file:mitm.application.djigzo.DjigzoConfigurator.java

private static void logAllPackages() {
    List<Package> packages = Arrays.asList(Package.getPackages());

    Comparator<Package> packageComparator = new Comparator<Package>() {
        @Override//from  www  .  j  a  v a2  s .c  o m
        public int compare(Package package1, Package package2) {
            return package1.getName().compareTo(package2.getName());
        }
    };

    Collections.sort(packages, packageComparator);

    StrBuilder sb = new StrBuilder(1024);

    sb.appendNewLine();

    for (Package pack : packages) {
        sb.append("Package: ").append(pack.getName()).appendSeparator("; ");
        sb.append("Title: ").append(pack.getImplementationTitle()).appendSeparator("; ");
        sb.append("Version: ").append(pack.getImplementationVersion());
        sb.appendNewLine();
    }

    logger.info(sb.toString());
}

From source file:com.archivas.logging.FileHandler.java

protected static String buildPattern(String pattern) {
    String retval;//from  w  w  w  .ja  v a2 s.  c  om
    if (pattern == null) {
        return null;
    }

    StrBuilder newPattern = new StrBuilder(pattern);
    String applicationHomeDir = System.getProperty("application_home_dir");
    String userHomeDir = System.getProperty("user.home");
    String tmpDir = System.getProperty("java.io.tmpdir");
    if (tmpDir == null) {
        tmpDir = userHomeDir;
    }

    if (applicationHomeDir != null) {
        newPattern = newPattern.replaceAll("%a", applicationHomeDir);
    }
    retval = newPattern.toString();

    // ensure that the log directory exists
    // Replace the known variables that are common in directories so we can create the dir.
    newPattern = newPattern.replaceAll("%t", tmpDir);
    newPattern = newPattern.replaceAll("%h", userHomeDir);

    String logPath = FileUtil.getPath(newPattern.toString());
    FileUtil.mkdirs(logPath);
    return retval;
}

From source file:bboss.org.apache.velocity.runtime.parser.node.NodeUtils.java

/**
 * Utility method to interpolate context variables
 * into string literals. So that the following will
 * work:/*  ww w. j a  va2s.  co  m*/
 *
 * #set $name = "candy"
 * $image.getURI("${name}.jpg")
 *
 * And the string literal argument will
 * be transformed into "candy.jpg" before
 * the method is executed.
 * 
 * @deprecated this method isn't called by any class
 * 
 * @param argStr
 * @param vars
 * @return Interpoliation result.
 * @throws MethodInvocationException
 */
public static String interpolate(String argStr, Context vars) throws MethodInvocationException {
    // if there's nothing to replace, skip this (saves buffer allocation)
    if (argStr.indexOf('$') == -1)
        return argStr;

    StrBuilder argBuf = new StrBuilder();

    for (int cIdx = 0, is = argStr.length(); cIdx < is;) {
        char ch = argStr.charAt(cIdx);

        if (ch == '$') {
            StrBuilder nameBuf = new StrBuilder();
            for (++cIdx; cIdx < is; ++cIdx) {
                ch = argStr.charAt(cIdx);
                if (ch == '_' || ch == '-' || Character.isLetterOrDigit(ch))
                    nameBuf.append(ch);
                else if (ch == '{' || ch == '}')
                    continue;
                else
                    break;
            }

            if (nameBuf.length() > 0) {
                Object value = vars.get(nameBuf.toString());

                if (value == null)
                    argBuf.append("$").append(nameBuf.toString());
                else
                    argBuf.append(value.toString());
            }

        } else {
            argBuf.append(ch);
            ++cIdx;
        }
    }

    return argBuf.toString();
}

From source file:com.palantir.atlasdb.keyvalue.rdbms.utils.AtlasSqlUtils.java

public static String makeSlots(String prefix, int number, int arity) {
    Preconditions.checkArgument(arity > 0);
    StrBuilder builder = new StrBuilder();
    for (int i = 0; i < number; ++i) {
        builder.append("(");
        for (int j = 0; j < arity; ++j) {
            builder.append(":").append(prefix).append(i).append("_").append(j);
            if (j + 1 < arity) {
                builder.append(", ");
            }//from   w  ww.  ja v  a  2s .c o  m
        }
        builder.append(")");
        if (i + 1 < number) {
            builder.append(", ");
        }
    }
    return builder.toString();
}

From source file:com.antsdb.saltedfish.sql.vdm.ExprUtil.java

/**
 * <p>Unescapes any Java literals found in the <code>String</code> to a
 * <code>Writer</code>.</p>
 *
 * <p>For example, it will turn a sequence of <code>'\'</code> and
 * <code>'n'</code> into a newline character, unless the <code>'\'</code>
 * is preceded by another <code>'\'</code>.</p>
 * /*from   ww  w  .  j  a  v a2 s .c om*/
 * <p>A <code>null</code> string input has no effect.</p>
 * 
 * @see http://dev.mysql.com/doc/refman/5.7/en/string-literals.html
 * 
 * @param out  the <code>Writer</code> used to output unescaped characters
 * @param str  the <code>String</code> to unescape, may be null
 * @throws IllegalArgumentException if the Writer is <code>null</code>
 * @throws IOException if error occurs on underlying Writer
 */
public static void unescapeJava(Writer out, String str) throws IOException {
    if (out == null) {
        throw new IllegalArgumentException("The Writer must not be null");
    }
    if (str == null) {
        return;
    }
    int sz = str.length();
    StrBuilder unicode = new StrBuilder(4);
    boolean hadSlash = false;
    boolean inUnicode = false;
    for (int i = 0; i < sz; i++) {
        char ch = str.charAt(i);
        if (inUnicode) {
            // if in unicode, then we're reading unicode
            // values in somehow
            unicode.append(ch);
            if (unicode.length() == 4) {
                // unicode now contains the four hex digits
                // which represents our unicode character
                try {
                    int value = Integer.parseInt(unicode.toString(), 16);
                    out.write((char) value);
                    unicode.setLength(0);
                    inUnicode = false;
                    hadSlash = false;
                } catch (NumberFormatException nfe) {
                    throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe);
                }
            }
            continue;
        }
        if (hadSlash) {
            // handle an escaped value
            hadSlash = false;
            switch (ch) {
            case '0':
                out.write(0);
                break;
            case '\'':
                out.write('\'');
                break;
            case '\"':
                out.write('"');
                break;
            case 'b':
                out.write('\b');
                break;
            case 'n':
                out.write('\n');
                break;
            case 'r':
                out.write('\r');
                break;
            case 't':
                out.write('\t');
                break;
            case 'Z':
                out.write(26);
                break;
            case '\\':
                out.write('\\');
                break;
            case '%':
                out.write('%');
                break;
            case '_':
                out.write('_');
                break;
            case 'u': {
                // uh-oh, we're in unicode country....
                inUnicode = true;
                break;
            }
            default:
                out.write(ch);
            }
            continue;
        } else if (ch == '\\') {
            hadSlash = true;
            continue;
        }
        out.write(ch);
    }
    if (hadSlash) {
        // then we're in the weird case of a \ at the end of the
        // string, let's output it anyway.
        out.write('\\');
    }
}

From source file:com.evolveum.midpoint.common.policy.ValuePolicyGenerator.java

public static String generate(StringPolicyType policy, int defaultLength, boolean generateMinimalSize,
        OperationResult inputResult) {/* www  .ja  v  a2s  .c o m*/

    if (null == policy) {
        throw new IllegalArgumentException("Provided password policy can not be null.");
    }

    if (null == inputResult) {
        throw new IllegalArgumentException("Provided operation result cannot be null");
    }
    // Define result from generator
    OperationResult generatorResult = new OperationResult(
            "Password generator running policy :" + policy.getDescription());
    inputResult.addSubresult(generatorResult);

    // if (policy.getLimitations() != null &&
    // policy.getLimitations().getMinLength() != null){
    // generateMinimalSize = true;
    // }
    // setup default values where missing
    // PasswordPolicyUtils.normalize(pp);

    // Optimize usage of limits ass hashmap of limitas and key is set of
    // valid chars for each limitation
    HashMap<StringLimitType, ArrayList<String>> lims = new HashMap<StringLimitType, ArrayList<String>>();
    for (StringLimitType l : policy.getLimitations().getLimit()) {
        if (null != l.getCharacterClass().getValue()) {
            lims.put(l, StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue()));
        } else {
            lims.put(l, StringPolicyUtils.stringTokenizer(StringPolicyUtils
                    .collectCharacterClass(policy.getCharacterClass(), l.getCharacterClass().getRef())));
        }
    }

    // Get global limitations
    int minLen = policy.getLimitations().getMinLength() == null ? 0
            : policy.getLimitations().getMinLength().intValue();
    if (minLen != 0 && minLen > defaultLength) {
        defaultLength = minLen;
    }
    int maxLen = (policy.getLimitations().getMaxLength() == null ? 0
            : policy.getLimitations().getMaxLength().intValue());
    int unique = policy.getLimitations().getMinUniqueChars() == null ? minLen
            : policy.getLimitations().getMinUniqueChars().intValue();

    // test correctness of definition
    if (unique > minLen) {
        minLen = unique;
        OperationResult reportBug = new OperationResult("Global limitation check");
        reportBug.recordWarning(
                "There is more required uniq characters then definied minimum. Raise minimum to number of required uniq chars.");
    }

    if (minLen == 0 && maxLen == 0) {
        minLen = defaultLength;
        maxLen = defaultLength;
        generateMinimalSize = true;
    }

    if (maxLen == 0) {
        if (minLen > defaultLength) {
            maxLen = minLen;
        } else {
            maxLen = defaultLength;
        }
    }

    // Initialize generator
    StringBuilder password = new StringBuilder();

    /* **********************************
     * Try to find best characters to be first in password
     */
    HashMap<StringLimitType, ArrayList<String>> mustBeFirst = new HashMap<StringLimitType, ArrayList<String>>();
    for (StringLimitType l : lims.keySet()) {
        if (l.isMustBeFirst() != null && l.isMustBeFirst()) {
            mustBeFirst.put(l, lims.get(l));
        }
    }

    // If any limitation was found to be first
    if (!mustBeFirst.isEmpty()) {
        HashMap<Integer, ArrayList<String>> posibleFirstChars = cardinalityCounter(mustBeFirst, null, false,
                false, generatorResult);
        int intersectionCardinality = mustBeFirst.keySet().size();
        ArrayList<String> intersectionCharacters = posibleFirstChars.get(intersectionCardinality);
        // If no intersection was found then raise error
        if (null == intersectionCharacters || intersectionCharacters.size() == 0) {
            generatorResult
                    .recordFatalError("No intersection for required first character sets in password policy:"
                            + policy.getDescription());
            // Log error
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(
                        "Unable to generate password: No intersection for required first character sets in password policy: ["
                                + policy.getDescription()
                                + "] following character limitation and sets are used:");
                for (StringLimitType l : mustBeFirst.keySet()) {
                    StrBuilder tmp = new StrBuilder();
                    tmp.appendSeparator(", ");
                    tmp.appendAll(mustBeFirst.get(l));
                    LOGGER.error("L:" + l.getDescription() + " -> [" + tmp + "]");
                }
            }
            // No more processing unrecoverable conflict
            return null; // EXIT
        } else {
            if (LOGGER.isDebugEnabled()) {
                StrBuilder tmp = new StrBuilder();
                tmp.appendSeparator(", ");
                tmp.appendAll(intersectionCharacters);
                LOGGER.trace("Generate first character intersection items [" + tmp + "] into password.");
            }
            // Generate random char into password from intersection
            password.append(intersectionCharacters.get(rand.nextInt(intersectionCharacters.size())));
        }
    }

    /* **************************************
     * Generate rest to fulfill minimal criteria
     */

    boolean uniquenessReached = false;

    // Count cardinality of elements
    HashMap<Integer, ArrayList<String>> chars;
    for (int i = 0; i < minLen; i++) {

        // Check if still unique chars are needed
        if (password.length() >= unique) {
            uniquenessReached = true;
        }
        // Find all usable characters
        chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), false,
                uniquenessReached, generatorResult);
        // If something goes badly then go out
        if (null == chars) {
            return null;
        }

        if (chars.isEmpty()) {
            LOGGER.trace("Minimal criterias was met. No more characters");
            break;
        }
        // Find lowest possible cardinality and then generate char
        for (int card = 1; card < lims.keySet().size(); card++) {
            if (chars.containsKey(card)) {
                ArrayList<String> validChars = chars.get(card);
                password.append(validChars.get(rand.nextInt(validChars.size())));
                //               LOGGER.trace(password.toString());
                break;
            }
        }
    }

    // test if maximum is not exceeded
    if (password.length() > maxLen) {
        generatorResult
                .recordFatalError("Unable to meet minimal criteria and not exceed maximxal size of password.");
        return null;
    }

    /* ***************************************
     * Generate chars to not exceed maximal
     */

    for (int i = 0; i < minLen; i++) {
        // test if max is reached
        if (password.length() == maxLen) {
            // no more characters maximal size is reached
            break;
        }

        if (password.length() >= minLen && generateMinimalSize) {
            // no more characters are needed
            break;
        }

        // Check if still unique chars are needed
        if (password.length() >= unique) {
            uniquenessReached = true;
        }
        // find all usable characters
        chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), true,
                uniquenessReached, generatorResult);

        // If something goes badly then go out
        if (null == chars) {
            // we hope this never happend.
            generatorResult
                    .recordFatalError("No valid characters to generate, but no all limitation are reached");
            return null;
        }

        // if selection is empty then no more characters and we can close
        // our work
        if (chars.isEmpty()) {
            if (i == 0) {
                password.append(RandomStringUtils.randomAlphanumeric(minLen));

            }
            break;
            //            if (!StringUtils.isBlank(password.toString()) && password.length() >= minLen) {
            //               break;
            //            }
            // check uf this is a firs cycle and if we need to user some
            // default (alphanum) character class.

        }

        // Find lowest possible cardinality and then generate char
        for (int card = 1; card <= lims.keySet().size(); card++) {
            if (chars.containsKey(card)) {
                ArrayList<String> validChars = chars.get(card);
                password.append(validChars.get(rand.nextInt(validChars.size())));
                //               LOGGER.trace(password.toString());
                break;
            }
        }
    }

    if (password.length() < minLen) {
        generatorResult.recordFatalError(
                "Unable to generate password and meet minimal size of password. Password lenght: "
                        + password.length() + ", required: " + minLen);
        LOGGER.trace(
                "Unable to generate password and meet minimal size of password. Password lenght: {}, required: {}",
                password.length(), minLen);
        return null;
    }

    generatorResult.recordSuccess();

    // Shuffle output to solve pattern like output
    StrBuilder sb = new StrBuilder(password.substring(0, 1));
    ArrayList<String> shuffleBuffer = StringPolicyUtils.stringTokenizer(password.substring(1));
    Collections.shuffle(shuffleBuffer);
    sb.appendAll(shuffleBuffer);

    return sb.toString();
}