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

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

Introduction

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

Prototype

public StrBuilder appendAll(Iterator<?> it) 

Source Link

Document

Appends each item in an iterator to the builder without any separators.

Usage

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

public static String generate(StringPolicyType policy, int defaultLength, boolean generateMinimalSize,
        OperationResult inputResult) {/*  w  w  w .  ja  v  a 2  s  . com*/

    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();
}

From source file:mitm.application.djigzo.james.smtpserver.ThrottlingMailHandler.java

@Override
public void configure(Configuration handlerConfiguration) throws ConfigurationException {
    logger.info("Configuring CommandHandler");

    Configuration[] repositoryConfigs = handlerConfiguration.getChild("repositories").getChildren("repository");

    repositories = new ArrayList<String>(repositoryConfigs.length);

    for (Configuration repositoryConfig : repositoryConfigs) {
        repositories.add(repositoryConfig.getValue());
    }//from  w w  w.j  ava 2 s.  co  m

    Configuration config = handlerConfiguration.getChild("checkRate", false);

    if (config != null) {
        checkRate = config.getValueAsInteger(100);
    }

    parseLimits(handlerConfiguration);

    StrBuilder sb = new StrBuilder();

    sb.append("Repositories: ");
    sb.appendWithSeparators(repositories, ", ");
    sb.appendSeparator("; ");
    sb.append("checkRate: ");
    sb.append(checkRate);
    sb.appendSeparator("; ");
    sb.appendAll(throttlings);

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

From source file:com.evolveum.midpoint.model.common.stringpolicy.ValuePolicyProcessor.java

private String generateAttempt(ValuePolicyType policy, int defaultLength, boolean generateMinimalSize,
        Context ctx, OperationResult result) {

    StringPolicyType stringPolicy = policy.getStringPolicy();
    // if (policy.getLimitations() != null &&
    // policy.getLimitations().getMinLength() != null){
    // generateMinimalSize = true;
    // }/*from  w w  w  .  j  a  v  a2 s .c o  m*/
    // 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
    Map<StringLimitType, List<String>> lims = new HashMap<>();
    int minLen = defaultLength;
    int maxLen = defaultLength;
    int unique = defaultLength / 2;
    if (stringPolicy != null) {
        for (StringLimitType l : stringPolicy.getLimitations().getLimit()) {
            if (null != l.getCharacterClass().getValue()) {
                lims.put(l, StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue()));
            } else {
                lims.put(l, StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(
                        stringPolicy.getCharacterClass(), l.getCharacterClass().getRef())));
            }
        }

        // Get global limitations
        minLen = defaultIfNull(stringPolicy.getLimitations().getMinLength(), 0);
        if (minLen != 0 && minLen > defaultLength) {
            defaultLength = minLen;
        }
        maxLen = defaultIfNull(stringPolicy.getLimitations().getMaxLength(), 0);
        unique = defaultIfNull(stringPolicy.getLimitations().getMinUniqueChars(), minLen);
    }
    // test correctness of definition
    if (unique > minLen) {
        minLen = unique;
        OperationResult reportBug = new OperationResult("Global limitation check");
        reportBug.recordWarning(
                "There is more required unique characters then defined minimum. Raise minimum to number of required unique 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
     */
    Map<StringLimitType, List<String>> mustBeFirst = new HashMap<>();
    for (Map.Entry<StringLimitType, List<String>> entry : lims.entrySet()) {
        final StringLimitType key = entry.getKey();
        if (key.isMustBeFirst() != null && key.isMustBeFirst()) {
            mustBeFirst.put(key, entry.getValue());
        }
    }

    // If any limitation was found to be first
    if (!mustBeFirst.isEmpty()) {
        Map<Integer, List<String>> posibleFirstChars = cardinalityCounter(mustBeFirst, null, false, false,
                result);
        int intersectionCardinality = mustBeFirst.keySet().size();
        List<String> intersectionCharacters = posibleFirstChars.get(intersectionCardinality);
        // If no intersection was found then raise error
        if (null == intersectionCharacters || intersectionCharacters.size() == 0) {
            result.recordFatalError("No intersection for required first character sets in value policy:"
                    + stringPolicy.getDescription());
            // Log error
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Unable to generate value for " + ctx.path
                        + ": No intersection for required first character sets in value policy: ["
                        + stringPolicy.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 " + ctx.path + ".");
            }
            // 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
    Map<Integer, List<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, result);
        // 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)) {
                List<String> validChars = chars.get(card);
                password.append(validChars.get(RAND.nextInt(validChars.size())));
                break;
            }
        }
    }

    // test if maximum is not exceeded
    if (password.length() > maxLen) {
        result.recordFatalError(
                "Unable to meet minimal criteria and not exceed maximal size of " + ctx.path + ".");
        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, result);

        // If something goes badly then go out
        if (null == chars) {
            // we hope this never happend.
            result.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)) {
                List<String> validChars = chars.get(card);
                password.append(validChars.get(RAND.nextInt(validChars.size())));
                break;
            }
        }
    }

    if (password.length() < minLen) {
        result.recordFatalError("Unable to generate value for " + ctx.path + " and meet minimal size of "
                + ctx.path + ". Actual length: " + password.length() + ", required: " + minLen);
        LOGGER.trace("Unable to generate value for " + ctx.path + " and meet minimal size of " + ctx.path
                + ". Actual length: {}, required: {}", password.length(), minLen);
        return null;
    }

    result.recordSuccess();

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

    return sb.toString();
}

From source file:mitm.application.djigzo.james.mailets.Log.java

@Override
public void serviceMail(Mail mail) {
    StrBuilder strBuilder = new StrBuilder(256);

    strBuilder.setNewLineText("; ");

    strBuilder.append(comment);//from   www .j  a va 2  s.c  o m

    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    if (logDetail.compareTo(LogDetail.BASIC) >= 0) {
        strBuilder.append(" | ");

        String mailID = mailAttributes.getMailID();

        strBuilder.append("MailID: ");
        strBuilder.appendln(mailID);
        strBuilder.append("Originator: ");
        strBuilder.appendln(getOriginator(mail));
        strBuilder.append("Sender: ");
        strBuilder.appendln(toString(mail.getSender()));
    }

    if (logDetail.compareTo(LogDetail.MIDDLE) >= 0) {
        strBuilder.append("Remote address: ");
        strBuilder.appendln(mail.getRemoteAddr());
        strBuilder.append("Recipients: ");
        strBuilder.appendln(mail.getRecipients());

        try {
            if (mail.getMessage() != null) {
                String subject = mail.getMessage().getSubject();

                strBuilder.append("Subject: ");
                strBuilder.appendln(subject);
            }
        } catch (MessagingException e) {
            getLogger().error("Error getting subject.", e);
        }

        try {
            if (mail.getMessage() != null) {
                String messageID = mail.getMessage().getMessageID();

                strBuilder.append("Message-ID: ");
                strBuilder.appendln(messageID);
            }
        } catch (MessagingException e) {
            getLogger().error("Error getting messageID.", e);
        }
    }

    if (logDetail.compareTo(LogDetail.FULL) >= 0) {
        strBuilder.append("Last updated: ");
        strBuilder.appendln(mail.getLastUpdated());
        strBuilder.append("Attribute names: ");
        strBuilder.appendAll(mail.getAttributeNames());
    }

    logMessage(strBuilder.toString());
}