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

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

Introduction

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

Prototype

public static boolean isAlphanumeric(final CharSequence cs) 

Source Link

Document

Checks if the CharSequence contains only Unicode letters or digits.

null will return false .

Usage

From source file:org.trnltk.util.MorphemeContainerFormatter.java

private static String formatTransition(final SuffixTransition suffixTransition, final boolean includeForm) {
    final StringBuilder b = new StringBuilder();

    if (suffixTransition.isDerivational()) {
        final SuffixGraphState targetState = suffixTransition.getTargetState();
        b.append(targetState.getPrimaryPos().getStringForm()).append("+");
        if (targetState.getSecondaryPos() != null)
            b.append(targetState.getSecondaryPos().getStringForm()).append("+");
    }/*from w w w  . j a  v a 2 s .c o m*/

    final SuffixForm suffixForm = suffixTransition.getSuffixFormApplication().getSuffixForm();
    final String actualSuffixForm = suffixTransition.getSuffixFormApplication().getActualSuffixForm();
    if (includeForm && StringUtils.isNotBlank(actualSuffixForm)
            && StringUtils.isAlphanumeric(actualSuffixForm)) {
        b.append(String.format("%s(%s[%s])", suffixForm.getSuffix().getPrettyName(),
                suffixForm.getForm().getSuffixFormStr(), actualSuffixForm));
    } else {
        b.append(suffixForm.getSuffix().getPrettyName());
    }

    return b.toString();
}

From source file:org.wise.portal.domain.project.impl.Projectcode.java

/**
 * Checks if this projectcode is legal syntactically
 * //w  w  w  .j  a  v  a 2s  . c  o m
 * @return <code>true</code> iff provided projectcode is legal
 */
public boolean isLegalProjectcode() {
    if (StringUtils.contains(projectcode, SEPARATOR)) {
        String runcode = getRuncode();
        String periodname = getRunPeriod();
        if (!StringUtils.isEmpty(runcode) && !StringUtils.isEmpty(periodname)
                && StringUtils.isAlphanumeric(runcode) && StringUtils.isAlphanumeric(periodname)) {
            return true;
        }
    }
    return false;
}

From source file:org.wise.portal.presentation.validators.ChangePasswordParametersValidator.java

public void validatePasswordAlphaNumeric(Errors errors, String passwd) {
    if (!StringUtils.isAlphanumeric(passwd))
        errors.rejectValue("passwd1",
                "presentation.validators.ChangePasswordParametersValidator.errorPasswordContainsIllegalCharacters");

}

From source file:org.wise.portal.presentation.validators.UserAccountFormValidator.java

/**
 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
 *//*w  w  w.ja  va 2  s  . c  o  m*/
public void validate(Object userAccountFormIn, Errors errors) {
    UserAccountForm userAccountForm = (UserAccountForm) userAccountFormIn;
    MutableUserDetails userDetails = userAccountForm.getUserDetails();

    if (userAccountForm.isNewAccount()) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userDetails.password",
                "error.password-not-specified");

        if (errors.getFieldErrorCount("userDetails.password") > 0) {
            return;
        }

        if (userDetails.getPassword().length() > MAX_PASSWORD_LENGTH) {
            errors.rejectValue("userDetails.password", "error.password-too-long");
            return;
        }

        if (!StringUtils.isAlphanumeric(userDetails.getPassword())) {
            errors.rejectValue("userDetails.password",
                    "presentation.validators.ChangePasswordParametersValidator.errorPasswordContainsIllegalCharacters");
            return;
        }

        if (userDetails.getSignupdate() == null) {
            errors.rejectValue("userDetails.signupdate", "error.signupdate-not-specified");
            return;
        }
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userDetails.username",
                "error.username-not-specified");

        if (!StringUtils.isAlphanumeric(userDetails.getUsername())) {
            errors.rejectValue("userDetails.username", "error.username-illegal-characters");
        }
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userDetails.firstname", "error.firstname-not-specified");

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userDetails.lastname", "error.lastname-not-specified");

    if (!StringUtils.isAlphanumeric(userDetails.getFirstname())
            || !StringUtils.isAsciiPrintable(userDetails.getFirstname())) {
        errors.rejectValue("userDetails.firstname", "error.firstname-illegal-characters");
        return;
    }

    if (!StringUtils.isAlphanumeric(userDetails.getLastname())
            || !StringUtils.isAsciiPrintable(userDetails.getLastname())) {
        errors.rejectValue("userDetails.lastname", "error.lastname-illegal-characters");
        return;
    }

    if (errors.hasErrors())
        userDetails.setPassword("");
}

From source file:org.wise.portal.presentation.web.controllers.teacher.run.CreateRunController.java

/**
 * Third page handler. This is where user selects postLevel and real time settings
 *//*from  w  w  w .  j a va  2s .c  o  m*/
@RequestMapping(params = "_page=3")
public String processThirdPage(final @ModelAttribute("runParameters") RunParameters runParameters,
        final BindingResult result, final ModelMap modelMap, final HttpServletRequest request) {
    modelMap.put("periodNames", DefaultPeriodNames.values());

    if (runParameters.getPeriodNames() == null || runParameters.getPeriodNames().size() == 0) {
        if (runParameters.getManuallyEnteredPeriods() == "") {
            result.rejectValue("periodNames", "setuprun.error.selectperiods",
                    "You must select one or more periods or manually" + " create your period names.");
        } else {
            // check if manually entered periods is an empty string or just "," If yes, throw error
            if (runParameters.getManuallyEnteredPeriods() == null
                    || StringUtils.trim(runParameters.getManuallyEnteredPeriods()).length() == 0
                    || StringUtils.trim(runParameters.getManuallyEnteredPeriods()).equals(",")) {
                result.rejectValue("periodNames", "setuprun.error.selectperiods",
                        "You must select one or more periods or manually" + " create your period names.");
            } else {
                String[] parsed = StringUtils.split(runParameters.getManuallyEnteredPeriods(), ",");
                if (parsed.length == 0) {
                    result.rejectValue("periodNames", "setuprun.error.whitespaceornonalphanumeric",
                            "Manually entered"
                                    + " periods cannot contain whitespace or non-alphanumeric characters.");
                    return "teacher/run/create/createrunperiods";
                }
                Set<String> parsedAndTrimmed = new TreeSet<String>();
                for (String current : parsed) {
                    String trimmed = StringUtils.trim(current);
                    if (trimmed.length() == 0 || StringUtils.contains(trimmed, " ")
                            || !StringUtils.isAlphanumeric(trimmed) || trimmed.equals(",")) {
                        result.rejectValue("periodNames", "setuprun.error.whitespaceornonalphanumeric",
                                "Manually entered"
                                        + " periods cannot contain whitespace or non-alphanumeric characters.");
                        break;
                    } else {
                        parsedAndTrimmed.add(trimmed);
                    }
                }
                runParameters.setPeriodNames(parsedAndTrimmed);
                runParameters.setManuallyEnteredPeriods("");
            }
        }
    } else if (runParameters.getManuallyEnteredPeriods() != "") {
        result.rejectValue("periodNames", "setuprun.error.notsupported",
                "Selecting both periods AND" + " manually entering periods is not supported.");
    }
    if (result.hasErrors()) {
        return "teacher/run/create/createrunperiods";
    }

    postLevelTextMap = new HashMap<Long, String>();
    String defaultPostLevelHighMessage = messageSource.getMessage(
            "presentation.web.controllers.teacher.run.CreateRunController.postLevelHighMessage", null,
            Locale.US);
    String postLevelHighMessage = messageSource.getMessage(
            "presentation.web.controllers.teacher.run.CreateRunController.postLevelHighMessage", null,
            defaultPostLevelHighMessage, request.getLocale());
    String defaultPostLevelLowMessage = messageSource.getMessage(
            "presentation.web.controllers.teacher.run.CreateRunController.postLevelLowMessage", null,
            Locale.US);
    String postLevelLowMessage = messageSource.getMessage(
            "presentation.web.controllers.teacher.run.CreateRunController.postLevelLowMessage", null,
            defaultPostLevelLowMessage, request.getLocale());

    postLevelTextMap.put(5l, postLevelHighMessage);
    postLevelTextMap.put(1l, postLevelLowMessage);

    Project project = runParameters.getProject();
    String maxWorkgroupSizeStr = wiseProperties.getProperty("maxWorkgroupSize", "3");
    int maxWorkgroupSize = Integer.parseInt(maxWorkgroupSizeStr);
    runParameters.setMaxWorkgroupSize(maxWorkgroupSize);
    modelMap.put("maxWorkgroupSize", maxWorkgroupSize);
    modelMap.put("implementedPostLevels", IMPLEMENTED_POST_LEVELS);
    modelMap.put("postLevelTextMap", postLevelTextMap);
    modelMap.put("minPostLevel", this.getMinPostLevel(project));
    runParameters.setEnableRealTime(true);
    return "teacher/run/create/createrunconfigure";
}

From source file:sirjacob.BlockDEA.Display.java

/**
 * Queries BDEA's EasyAPI (Simple Text Output Method) Checks the supplied
 * domain (getDomain()) and adds its status to the list. Possible Responses:
 * ok, block, fail_key, fail_server, fail_input_domain,
 * fail_parameter_count, fail_key_low_credits (EasyAPI v0.2)
 * <p>/* w w  w. j  a v a  2  s  . c o  m*/
 * preformCheckDomain also validates that the API key is Alphanumeric.
 */
private void preformCheckDomain() {
    if (StringUtils.isAlphanumeric(getKey())) {
        String response = getURLData(
                "http://check.block-disposable-email.com/easyapi/txt/" + getKey() + "/" + getDomain());
        if (response == null) {
            return;
        }
        switch (response) {
        case "ok":
            list.add(getTime() + " | ALLOW: " + getDomain(), 0);
            break;
        case "block":
            list.add(getTime() + " | BLOCK: " + getDomain(), 0);
            break;
        default:
            list.add(getTime() + " | FAILURE: " + response, 0);
            break;
        }
    } else {
        showBadKeyError();
    }
}

From source file:tech.sirwellington.alchemy.test.junit.runners.GenerateStringTest.java

@Test
public void testValues() {
    System.out.println("testValues");

    AlchemyGenerator<String> result = GenerateString.Values.createGeneratorFor(annotation);
    assertThat(result, notNullValue());//from  www.  j ava2  s.  c om

    String string = result.get();
    assertThat(string, not(isEmptyOrNullString()));

    if (type == UUID) {
        int uuidLength = java.util.UUID.randomUUID().toString().length();
        assertThat(string.length(), is(uuidLength));
    } else {
        assertThat(string.length(), is(length));
    }

    switch (type) {
    case ALPHABETIC:
        assertThat(StringUtils.isAlpha(string), is(true));
        break;
    case ALPHANUMERIC:
        assertThat(StringUtils.isAlphanumeric(string), is(true));
        break;
    case HEXADECIMAL:
        assertThat(string.matches("[A-Fa-f0-9]+"), is(true));
        break;
    //No additional assertions
    }

}

From source file:uk.ac.kcl.utils.StringTools.java

private static String getCompletingString(String string, int begin, int end) {
    while (begin > 0 && StringUtils.isAlphanumeric(string.substring(begin, begin + 1))) {
        begin -= 1;//from   w  w w  .  j av a 2s.  c  om
    }
    if (begin != 0)
        begin += 1;

    while (end < string.length() - 1 && StringUtils.isAlphanumeric(string.substring(end, end + 1))) {
        end += 1;
    }

    String regex = "\\w+(\\(?\\)?\\s+\\w+)*";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(string.substring(begin, end));

    if (matcher.find()) {
        return matcher.group();
    }

    return StringUtils.EMPTY;
}

From source file:us.fatehi.schemacrawler.webapp.service.storage.FileSystemStorageService.java

/**
 * Prevent malicious injection attacks./*w w  w  .  j a v a 2 s .  c o m*/
 *
 * @param filenameKey
 *        Filename key
 * @throws Exception
 *         On a badly constructed filename key.
 */
private void validateFilenameKey(final String filenameKey) throws Exception {
    if (StringUtils.length(filenameKey) != 12 || !StringUtils.isAlphanumeric(filenameKey)) {
        throw new Exception(String.format("Invalid filename key \"%s\"", filenameKey));
    }
}

From source file:vista.controlador.Validador.java

/**
 * Valida si el campo es un usuario, esto es que slo contenga letras o
 * nmeros y sin espacios//from ww  w  . jav  a2 s  .c o m
 *
 * @param campo la cadena de texto a validar
 * @return true si el campo es un usuario
 */
public static boolean esUsuario(String campo) {
    boolean ok = true;

    if (estaVacio(campo) || !StringUtils.isAlphanumeric(campo)) {
        ok = false;
    }
    return ok;
}