Example usage for org.apache.commons.validator GenericValidator isBlankOrNull

List of usage examples for org.apache.commons.validator GenericValidator isBlankOrNull

Introduction

In this page you can find the example usage for org.apache.commons.validator GenericValidator isBlankOrNull.

Prototype

public static boolean isBlankOrNull(String value) 

Source Link

Document

Checks if the field isn't null and length of the field is greater than zero not including whitespace.

Usage

From source file:com.jd.survey.domain.survey.QuestionAnswerValidator.java

@Override
public void validate(Object obj, Errors errors) {
    try {//  www.  ja v a 2 s.  com

        boolean isValid;
        String validationFieldName = "stringAnswerValue";
        QuestionAnswer questionAnswer = (QuestionAnswer) obj;
        Question question = questionAnswer.getQuestion();
        String valueToValidate;
        BigDecimalValidator bigDecimalValidator;
        int optionsCount;
        int rowCount;
        int columnCount;
        System.out.println("Question type: " + question.getType());
        if (question.getVisible()) {
            switch (question.getType()) {
            case YES_NO_DROPDOWN: //Yes No DropDown 
                break;
            case SHORT_TEXT_INPUT: //Short Text Input
                //validate isRequired
                valueToValidate = questionAnswer.getStringAnswerValue();
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    //validate range
                    if (question.getIntegerMinimum() != null
                            && !GenericValidator.minLength(valueToValidate, question.getIntegerMinimum())) {
                        errors.rejectValue(validationFieldName, "field_length_min",
                                new Object[] { question.getIntegerMinimum() },
                                "The length of the text must exceed " + question.getIntegerMinimum());
                        break;
                    }
                    if (question.getIntegerMaximum() != null
                            && !GenericValidator.maxLength(valueToValidate, question.getIntegerMaximum())) {
                        errors.rejectValue(validationFieldName, "field_length_max",
                                new Object[] { question.getIntegerMaximum() },
                                "The length of the text must not exceed " + question.getIntegerMaximum());
                        break;
                    }

                    //validate regular expression 
                    if (question.getRegularExpression() != null
                            && !question.getRegularExpression().trim().isEmpty() && !GenericValidator
                                    .matchRegexp(valueToValidate, question.getRegularExpression())) {
                        errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid entry");
                        break;
                    }
                }
                break;
            case LONG_TEXT_INPUT: //Long Text Input
                //validate isRequired
                valueToValidate = questionAnswer.getStringAnswerValue();
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    //validate range
                    if (question.getIntegerMinimum() != null
                            && !GenericValidator.minLength(valueToValidate, question.getIntegerMinimum())) {
                        errors.rejectValue(validationFieldName, "field_length_min",
                                new Object[] { question.getIntegerMinimum() },
                                "The length of the text must exceed " + question.getIntegerMinimum());
                        break;
                    }
                    if (question.getIntegerMaximum() != null
                            && !GenericValidator.maxLength(valueToValidate, question.getIntegerMaximum())) {
                        errors.rejectValue(validationFieldName, "field_length_max",
                                new Object[] { question.getIntegerMaximum() },
                                "The length of the text must not exceed " + question.getIntegerMaximum());
                        break;
                    }
                    //validate regular expression 
                    if (question.getRegularExpression() != null
                            && !question.getRegularExpression().trim().isEmpty() && !GenericValidator
                                    .matchRegexp(valueToValidate, question.getRegularExpression())) {
                        errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid entry");
                        break;
                    }
                }
                break;
            case HUGE_TEXT_INPUT: //Huge Text Input
                //validate isRequired
                valueToValidate = questionAnswer.getStringAnswerValue();
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    //validate range   
                    if (question.getIntegerMinimum() != null
                            && !GenericValidator.minLength(valueToValidate, question.getIntegerMinimum())) {
                        errors.rejectValue(validationFieldName, "field_length_min",
                                new Object[] { question.getIntegerMinimum() },
                                "The length of the text must exceed " + question.getIntegerMinimum());
                        break;
                    }
                    if (question.getIntegerMaximum() != null
                            && !GenericValidator.maxLength(valueToValidate, question.getIntegerMaximum())) {
                        errors.rejectValue(validationFieldName, "field_length_max",
                                new Object[] { question.getIntegerMaximum() },
                                "The length of the text must not exceed " + question.getIntegerMaximum());
                        break;
                    }
                    //validate regular expression 
                    if (question.getRegularExpression() != null
                            && !question.getRegularExpression().trim().isEmpty() && !GenericValidator
                                    .matchRegexp(valueToValidate, question.getRegularExpression())) {
                        errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid entry");
                        break;
                    }
                }
                break;
            case INTEGER_INPUT: //Integer Input
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is invalid");
                    break;
                }
                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    if (!GenericValidator.isInt(valueToValidate)) {
                        errors.rejectValue(validationFieldName, "field_invalid_integer",
                                "This field is invalid");
                        break;
                    }

                    //validate range
                    if (question.getIntegerMinimum() != null
                            && !GenericValidator.minValue((int) Integer.parseInt(valueToValidate),
                                    (int) question.getIntegerMinimum())) {

                        errors.rejectValue(validationFieldName, "field_value_min",
                                new Object[] { question.getIntegerMinimum() },
                                "The value of this field must exceed " + question.getIntegerMinimum());
                        break;
                    }
                    if (question.getIntegerMaximum() != null
                            && !GenericValidator.maxValue((int) Integer.parseInt(valueToValidate),
                                    (int) question.getIntegerMaximum())) {
                        errors.rejectValue(validationFieldName, "field_value_max",
                                new Object[] { question.getIntegerMaximum() },
                                "The value of this field must not exceed " + question.getIntegerMaximum());
                        break;
                    }
                }
                questionAnswer.setLongAnswerValue(valueToValidate != null && valueToValidate.length() > 0
                        ? Long.parseLong(valueToValidate)
                        : null);
                break;
            case CURRENCY_INPUT: //Currency Input
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }

                //continue validation if value entered is not null or empty
                if (valueToValidate != null && !valueToValidate.isEmpty()) {

                    CurrencyValidator currencyValidator = new CurrencyValidator(true, true);
                    if (!currencyValidator.isValid(valueToValidate, LocaleContextHolder.getLocale())) {
                        errors.rejectValue(validationFieldName, "field_invalid_currency",
                                "Invalid Currency Entered");
                        break;
                    }

                    //removing all '$' and ',' from string prior to validating max and min
                    valueToValidate = valueToValidate.replaceAll("\\$", "");
                    valueToValidate = valueToValidate.replaceAll(",", "");

                    //validate range
                    if (question.getDecimalMinimum() != null
                            && !GenericValidator.minValue((double) Double.parseDouble(valueToValidate),
                                    question.getDecimalMinimum().doubleValue())) {
                        errors.rejectValue(validationFieldName, "field_value_min",
                                new Object[] { question.getDecimalMinimum() },
                                "The value of this field must exceed " + question.getDecimalMinimum());
                        break;
                    }
                    if (question.getDecimalMaximum() != null
                            && !GenericValidator.maxValue((double) Double.parseDouble(valueToValidate),
                                    question.getDecimalMaximum().doubleValue())) {
                        errors.rejectValue(validationFieldName, "field_value_max",
                                new Object[] { question.getDecimalMaximum() },
                                "The value of this field must not exceed " + question.getDecimalMaximum());
                        break;
                    }

                    questionAnswer.setBigDecimalAnswerValue(
                            currencyValidator.validate(valueToValidate, LocaleContextHolder.getLocale()));
                    questionAnswer.setStringAnswerValue(currencyValidator.format(
                            currencyValidator.validate(valueToValidate, LocaleContextHolder.getLocale()),
                            LocaleContextHolder.getLocale()));

                }
                break;

            case DECIMAL_INPUT: //Numeric Input (Decimal)
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //continue validation if value entered is not null or empty
                bigDecimalValidator = new BigDecimalValidator(true);
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    if (!bigDecimalValidator.isValid(valueToValidate, LocaleContextHolder.getLocale())) {
                        errors.rejectValue(validationFieldName, "field_invalid_decimal",
                                "Invalid Decimal Entered");
                        break;
                    } else {
                        questionAnswer.setStringAnswerValue(bigDecimalValidator.format(
                                bigDecimalValidator.validate(valueToValidate, LocaleContextHolder.getLocale()),
                                LocaleContextHolder.getLocale()));
                    }

                    //removing all commas from string prior to validating max and min
                    valueToValidate = valueToValidate.replaceAll(",", "");
                    //validate range
                    if (question.getDecimalMinimum() != null
                            && !GenericValidator.minValue((double) Double.parseDouble(valueToValidate),
                                    question.getDecimalMinimum().doubleValue())) {
                        errors.rejectValue(validationFieldName, "field_value_min",
                                new Object[] { question.getDecimalMinimum() },
                                "The value of this field must exceed " + question.getDecimalMinimum());
                        break;
                    }
                    if (question.getDecimalMaximum() != null
                            && !GenericValidator.maxValue((double) Double.parseDouble(valueToValidate),
                                    question.getDecimalMaximum().doubleValue())) {
                        errors.rejectValue(validationFieldName, "field_value_max",
                                new Object[] { question.getDecimalMaximum() },
                                "The value of this field must not exceed " + question.getDecimalMaximum());
                        break;
                    }
                }
                questionAnswer.setBigDecimalAnswerValue(valueToValidate.trim().length() > 0
                        ? bigDecimalValidator.validate(valueToValidate, LocaleContextHolder.getLocale())
                        : null);
                break;
            case DATE_INPUT: //Date Input
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired   
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }

                //validate type if value entered is not null
                if (valueToValidate != null && !valueToValidate.isEmpty()) {
                    if (!GenericValidator.isDate(valueToValidate, dateFormat, true)) {
                        errors.rejectValue(validationFieldName, "field_invalid_date", "Invalid Date");
                        break;
                    }
                    if (question.getDateMinimum() != null && (DateValidator.getInstance()
                            .validate(valueToValidate).compareTo(question.getDateMinimum()) <= 0)) {
                        errors.rejectValue(validationFieldName, "field_date_min",
                                new Object[] { question.getDateMinimum() },
                                "The date entered must be after " + question.getDateMinimum());
                        break;
                    }
                    if (question.getDateMaximum() != null && (DateValidator.getInstance()
                            .validate(valueToValidate).compareTo(question.getDateMaximum()) >= 0)) {
                        errors.rejectValue(validationFieldName, "field_date_max",
                                new Object[] { question.getDateMaximum() },
                                "The date entered must be before " + question.getDateMaximum());
                        break;
                    }
                }

                questionAnswer.setDateAnswerValue(valueToValidate.trim().length() > 0
                        ? DateValidator.getInstance().validate(valueToValidate)
                        : null);
                break;
            case SINGLE_CHOICE_DROP_DOWN: //Single choice Drop Down
                valueToValidate = questionAnswer.getStringAnswerValue();
                isValid = false;
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //verify that the value exists in the options
                for (QuestionOption option : question.getOptions()) {
                    if (option.getValue().equalsIgnoreCase(valueToValidate)) {
                        isValid = true;
                        break;
                    }
                }
                if (!isValid && !GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid Option");
                    break;
                }

                break;
            case MULTIPLE_CHOICE_CHECKBOXES: //Multiple Choice Checkboxes
                //validate isRequired
                isValid = false;
                optionsCount = questionAnswer.getQuestion().getOptions().size();
                if (question.getRequired()) {
                    for (int i = 0; i < questionAnswer.getIntegerAnswerValuesArray().length; i++) {
                        if (questionAnswer.getIntegerAnswerValuesArray()[i] != null
                                && questionAnswer.getIntegerAnswerValuesArray()[i] <= optionsCount) {
                            //one element was checked
                            isValid = true;
                            break;
                        }
                    }
                    if (!isValid) {
                        errors.rejectValue(validationFieldName, "field_required", "This field is required");
                        break;
                    }
                }

                isValid = true;
                //verify that the value exists in the options range
                for (int i = 0; i < questionAnswer.getIntegerAnswerValuesArray().length; i++) {
                    if (questionAnswer.getIntegerAnswerValuesArray()[i] != null
                            && questionAnswer.getIntegerAnswerValuesArray()[i] > optionsCount) {
                        //one element was checked
                        isValid = false;
                        break;
                    }
                }
                if (!isValid) {
                    errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid Option");
                    break;
                }

                break;
            case DATASET_DROP_DOWN: //Dataset DropDown
                valueToValidate = questionAnswer.getStringAnswerValue();
                isValid = false;
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                //verify that the value exists in the dataset

                for (DataSetItem dataSetItem : question.getDataSetItems()) {
                    if (dataSetItem.getValue().equalsIgnoreCase(valueToValidate)) {
                        isValid = true;
                        break;
                    }
                }
                if (!isValid && !GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid Option");
                    break;
                }

                break;

            case SINGLE_CHOICE_RADIO_BUTTONS: //Single Choice Radio Buttons 
                isValid = false;
                valueToValidate = questionAnswer.getStringAnswerValue();
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }

                //verify that the value exists in the options
                for (QuestionOption option : question.getOptions()) {
                    if (option.getValue().equalsIgnoreCase(valueToValidate)) {
                        isValid = true;
                        break;
                    }
                }
                if (!isValid && !GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid Option");
                    break;
                }

                break;

            case YES_NO_DROPDOWN_MATRIX://Yes No DropDown Matrix
                break;
            case SHORT_TEXT_INPUT_MATRIX://Short Text Input Matrix
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";
                        //validate isRequired
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is required");
                            continue;
                        }
                        //continue validation if value entered is not null or empty
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            //validate range
                            if (question.getIntegerMinimum() != null && !GenericValidator
                                    .minLength(valueToValidate, question.getIntegerMinimum())) {
                                errors.rejectValue(validationFieldName, "field_length_min",
                                        new Object[] { question.getIntegerMinimum() },
                                        "The length of the text must exceed " + question.getIntegerMinimum());
                                continue;
                            }
                            if (question.getIntegerMaximum() != null && !GenericValidator
                                    .maxLength(valueToValidate, question.getIntegerMaximum())) {
                                errors.rejectValue(validationFieldName, "field_length_max",
                                        new Object[] { question.getIntegerMaximum() },
                                        "The length of the text must not exceed "
                                                + question.getIntegerMaximum());
                                continue;
                            }

                            //validate regular expression 
                            if (question.getRegularExpression() != null
                                    && !question.getRegularExpression().trim().isEmpty() && !GenericValidator
                                            .matchRegexp(valueToValidate, question.getRegularExpression())) {
                                errors.rejectValue(validationFieldName, "field_invalid_type", "Invalid entry");
                                continue;
                            }
                        }
                    }
                }
                break;
            case INTEGER_INPUT_MATRIX://Integer Input Matrix
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";

                        //validate isRequired
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is invalid");
                            continue;
                        }

                        //continue validation if value entered is not null or empty
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            if (!GenericValidator.isInt(valueToValidate)) {
                                errors.rejectValue(validationFieldName, "field_invalid_integer",
                                        "This field is invalid");
                                continue;
                            }

                            //validate range
                            if (question.getIntegerMinimum() != null
                                    && !GenericValidator.minValue((int) Integer.parseInt(valueToValidate),
                                            (int) question.getIntegerMinimum())) {
                                errors.rejectValue(validationFieldName, "field_value_min",
                                        new Object[] { question.getIntegerMinimum() },
                                        "The value of this field must exceed " + question.getIntegerMinimum());
                                continue;
                            }
                            if (question.getIntegerMaximum() != null
                                    && !GenericValidator.maxValue((int) Integer.parseInt(valueToValidate),
                                            (int) question.getIntegerMaximum())) {
                                errors.rejectValue(validationFieldName, "field_value_max",
                                        new Object[] { question.getIntegerMaximum() },
                                        "The value of this field must not exceed "
                                                + question.getIntegerMaximum());
                                continue;
                            }
                        }
                        questionAnswer.getLongAnswerValuesMatrix()[r - 1][c - 1] = (valueToValidate != null
                                && valueToValidate.length() > 0 ? Long.parseLong(valueToValidate) : null);
                    }
                }
                break;
            case CURRENCY_INPUT_MATRIX://Currency Input Matrix  NEED TO ADD MAX MIN???????????????????????????????????????????????????
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        System.out.println("ROW: " + r + " / COL: " + c
                                + " -----------------------------------------------------------------------------------------");
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";
                        //validate isRequired
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is required");
                            continue;
                        }

                        //continue validation if value entered is not null or empty
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            CurrencyValidator currencyValidator = new CurrencyValidator(true, true);
                            if (!currencyValidator.isValid(valueToValidate, LocaleContextHolder.getLocale())) {
                                errors.rejectValue(validationFieldName, "field_invalid_type",
                                        "Invalid Currency Entered");
                                continue;
                            } else {
                                questionAnswer.getBigDecimalAnswerValuesMatrix()[r - 1][c
                                        - 1] = currencyValidator.validate(valueToValidate,
                                                LocaleContextHolder.getLocale());
                                questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1] = currencyValidator
                                        .format(currencyValidator.validate(valueToValidate,
                                                LocaleContextHolder.getLocale()),
                                                LocaleContextHolder.getLocale());
                            }
                            //removing all '$' and ',' from string prior to validating max and min
                            valueToValidate = valueToValidate.replaceAll("\\$", "");
                            valueToValidate = valueToValidate.replaceAll(",", "");

                            //Validating max and min
                            if (question.getDecimalMinimum() == null) {
                                System.out.println(
                                        "MIN IS NULL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                            if (question.getDecimalMinimum() != null
                                    && !GenericValidator.minValue((double) Double.parseDouble(valueToValidate),
                                            question.getDecimalMinimum().doubleValue())) {
                                System.out.println(validationFieldName
                                        + "MIN ##################################################################################");
                                errors.rejectValue(validationFieldName, "field_value_min",
                                        new Object[] { question.getDecimalMinimum() },
                                        "The value of this field must exceed " + question.getDecimalMinimum());
                                continue;
                            }
                            if (question.getDecimalMaximum() == null) {
                                System.out.println(
                                        "MAX IS NULL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                            }

                            if (question.getDecimalMaximum() != null
                                    && !GenericValidator.maxValue((double) Double.parseDouble(valueToValidate),
                                            question.getDecimalMaximum().doubleValue())) {
                                System.out.println(validationFieldName
                                        + "MAX ########################################################################################################");
                                errors.rejectValue(validationFieldName, "field_value_max",
                                        new Object[] { question.getDecimalMaximum() },
                                        "The value of this field must not exceed "
                                                + question.getDecimalMaximum());
                                continue;
                            }
                        }
                    }
                }
                break;

            case DECIMAL_INPUT_MATRIX://Decimal Input Matrix
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";
                        //validate isRequired
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is required");
                            continue;
                        }

                        //continue validation if value entered is not null or empty
                        bigDecimalValidator = new BigDecimalValidator(true);
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            if (!bigDecimalValidator.isValid(valueToValidate,
                                    LocaleContextHolder.getLocale())) {
                                errors.rejectValue(validationFieldName, "field_invalid_type",
                                        "Invalid Decimal Entered");
                                continue;
                            } else {
                                questionAnswer.setStringAnswerValue(bigDecimalValidator.format(
                                        bigDecimalValidator.validate(valueToValidate,
                                                LocaleContextHolder.getLocale()),
                                        LocaleContextHolder.getLocale()));
                            }

                            //validate range
                            if (question.getDecimalMinimum() != null
                                    && !GenericValidator.minValue((double) Double.parseDouble(valueToValidate),
                                            question.getDecimalMinimum().doubleValue())) {
                                errors.rejectValue(validationFieldName, "field_value_min",
                                        new Object[] { question.getDecimalMinimum() },
                                        "The value of this field must exceed " + question.getDecimalMinimum());
                                continue;
                            }
                            if (question.getDecimalMaximum() != null
                                    && !GenericValidator.maxValue((double) Double.parseDouble(valueToValidate),
                                            question.getDecimalMaximum().doubleValue())) {
                                errors.rejectValue(validationFieldName, "field_value_max",
                                        new Object[] { question.getDecimalMaximum() },
                                        "The value of this field must not exceed "
                                                + question.getDecimalMaximum());
                                continue;
                            }
                        }
                        questionAnswer.getBigDecimalAnswerValuesMatrix()[r - 1][c
                                - 1] = (valueToValidate.trim().length() > 0 ? bigDecimalValidator
                                        .validate(valueToValidate, LocaleContextHolder.getLocale()) : null);

                    }
                }
                break;
            case DATE_INPUT_MATRIX://Date Input Matrix
                rowCount = questionAnswer.getQuestion().getRowLabels().size();
                columnCount = questionAnswer.getQuestion().getColumnLabels().size();
                for (int r = 1; r <= rowCount; r++) {
                    for (int c = 1; c <= columnCount; c++) {
                        valueToValidate = questionAnswer.getStringAnswerValuesMatrix()[r - 1][c - 1];
                        validationFieldName = "stringAnswerValuesMatrix[" + (r - 1) + "][" + (c - 1) + "]";

                        //validate isRequired   
                        if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                            errors.rejectValue(validationFieldName, "field_required", "This field is required");
                            continue;
                        }

                        //validate type if value entered is not null
                        if (valueToValidate != null && !valueToValidate.isEmpty()) {
                            if (!GenericValidator.isDate(valueToValidate, dateFormat, true)) {
                                errors.rejectValue(validationFieldName, "field_invalid_date", "Invalid Date");
                                continue;
                            }
                            if (question.getDateMinimum() != null && (DateValidator.getInstance()
                                    .validate(valueToValidate).compareTo(question.getDateMinimum()) <= 0)) {
                                errors.rejectValue(validationFieldName, "field_date_min",
                                        new Object[] { question.getDateMinimum() },
                                        "The date entered must be after " + question.getDateMinimum());
                                continue;
                            }
                            if (question.getDateMaximum() != null && (DateValidator.getInstance()
                                    .validate(valueToValidate).compareTo(question.getDateMaximum()) >= 0)) {
                                errors.rejectValue(validationFieldName, "field_date_max",
                                        new Object[] { question.getDateMaximum() },
                                        "The date entered must be before " + question.getDateMaximum());
                                continue;
                            }
                        }
                        questionAnswer.getDateAnswerValuesMatrix()[r - 1][c
                                - 1] = (valueToValidate.trim().length() > 0
                                        ? DateValidator.getInstance().validate(valueToValidate)
                                        : null);
                    }
                }
                break;
            case STAR_RATING:
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                break;
            case SMILEY_FACES_RATING:
                valueToValidate = questionAnswer.getStringAnswerValue();
                //validate isRequired
                if (question.getRequired() && GenericValidator.isBlankOrNull(valueToValidate)) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }
                break;

            case IMAGE_DISPLAY:
                //no validation
                break;
            case VIDEO_DISPLAY:
                //no validation
                break;
            case FILE_UPLOAD:
                //validate that the file is not null
                if (question.getRequired() && (questionAnswer.getSurveyDocument() == null)
                        && !questionAnswer.getDocumentAlreadyUploded()) {
                    errors.rejectValue(validationFieldName, "field_required", "This field is required");
                    break;
                }

                //check the file type from the file extension    
                if (questionAnswer.getSurveyDocument() != null
                        && !validateFileType(questionAnswer.getSurveyDocument().getContentType())) {
                    errors.rejectValue(validationFieldName, invalidContentMessage, this.invalidContentMessage);
                    break;
                }

                //validate the size
                if (questionAnswer.getSurveyDocument() != null
                        && !((questionAnswer.getSurveyDocument().getContent().length) <= maximunFileSize
                                * ONE_BYTE)) {
                    errors.rejectValue(validationFieldName, invalidFileSizeMessage,
                            this.invalidFileSizeMessage);
                    break;
                }

                break;

            }

        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:it.eng.spagobi.profiling.services.ManageAttributesAction.java

@Override
public void doService() {
    logger.debug("IN");
    ISbiAttributeDAO attrDao;/*from  w w w . j  a  v a 2  s  . com*/
    UserProfile profile = (UserProfile) this.getUserProfile();
    try {
        attrDao = DAOFactory.getSbiAttributeDAO();
        attrDao.setUserProfile(getUserProfile());
    } catch (EMFUserError e1) {
        logger.error(e1.getMessage(), e1);
        throw new SpagoBIServiceException(SERVICE_NAME, "Error occurred");
    }
    HttpServletRequest httpRequest = getHttpRequest();

    Locale locale = getLocale();

    String serviceType = this.getAttributeAsString(MESSAGE_DET);
    logger.debug("Service type " + serviceType);

    if (serviceType != null && serviceType.contains(ATTR_LIST)) {
        String name = null;
        String description = null;
        String idStr = null;

        try {
            BufferedReader b = httpRequest.getReader();
            if (b != null) {
                String respJsonObject = b.readLine();
                if (respJsonObject != null) {
                    JSONObject responseJSON = deserialize(respJsonObject);
                    JSONObject samples = responseJSON.getJSONObject(SAMPLES);
                    if (!samples.isNull(ID)) {
                        idStr = samples.getString(ID);
                    }

                    //checks if it is empty attribute to start insert
                    boolean isNewAttr = this.getAttributeAsBoolean(IS_NEW_ATTR);

                    if (!isNewAttr) {
                        if (!samples.isNull(NAME)) {

                            name = samples.getString(NAME);
                            HashMap<String, String> logParam = new HashMap();
                            logParam.put("NAME", name);
                            if (GenericValidator.isBlankOrNull(name)
                                    || !GenericValidator.matchRegexp(name, ALPHANUMERIC_STRING_REGEXP_NOSPACE)
                                    || !GenericValidator.maxLength(name, nameMaxLenght)) {
                                logger.error(
                                        "Either the field name is blank or it exceeds maxlength or it is not alfanumeric");
                                EMFValidationError e = new EMFValidationError(EMFErrorSeverity.ERROR,
                                        description, "9000", "");
                                getHttpResponse().setStatus(404);
                                JSONObject attributesResponseSuccessJSON = new JSONObject();
                                attributesResponseSuccessJSON.put("success", false);
                                attributesResponseSuccessJSON.put("message",
                                        "Either the field name is blank or it exceeds maxlength or it is not alfanumeric");
                                attributesResponseSuccessJSON.put("data", "[]");

                                writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));

                                AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.ADD",
                                        logParam, "OK");
                                return;

                            }
                        }
                        if (!samples.isNull(DESCRIPTION)) {
                            description = samples.getString(DESCRIPTION);

                            if (GenericValidator.isBlankOrNull(description)
                                    || !GenericValidator.matchRegexp(description,
                                            ALPHANUMERIC_STRING_REGEXP_NOSPACE)
                                    || !GenericValidator.maxLength(description, descriptionMaxLenght)) {
                                logger.error(
                                        "Either the field description is blank or it exceeds maxlength or it is not alfanumeric");

                                EMFValidationError e = new EMFValidationError(EMFErrorSeverity.ERROR,
                                        description, "9000", "");
                                getHttpResponse().setStatus(404);
                                JSONObject attributesResponseSuccessJSON = new JSONObject();
                                attributesResponseSuccessJSON.put("success", false);
                                attributesResponseSuccessJSON.put("message",
                                        "Either the field description is blank or it exceeds maxlength or it is not alfanumeric");
                                attributesResponseSuccessJSON.put("data", "[]");
                                writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));
                                HashMap<String, String> logParam = new HashMap();
                                logParam.put("NAME", name);
                                AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.ADD",
                                        logParam, "OK");
                                return;
                            }
                        }

                        SbiAttribute attribute = new SbiAttribute();
                        if (description != null) {
                            attribute.setDescription(description);
                        }
                        if (name != null) {
                            attribute.setAttributeName(name);
                        }
                        boolean isNewAttrForRes = true;
                        if (idStr != null && !idStr.equals("")) {
                            Integer attributeId = new Integer(idStr);
                            attribute.setAttributeId(attributeId.intValue());
                            isNewAttrForRes = false;
                        }
                        Integer attrID = attrDao.saveOrUpdateSbiAttribute(attribute);
                        logger.debug("Attribute updated");

                        ArrayList<SbiAttribute> attributes = new ArrayList<SbiAttribute>();
                        attribute.setAttributeId(attrID);
                        attributes.add(attribute);

                        getAttributesListAdded(locale, attributes, isNewAttrForRes, attrID);
                        HashMap<String, String> logParam = new HashMap();
                        logParam.put("NAME", attribute.getAttributeName());
                        AuditLogUtilities.updateAudit(getHttpRequest(), profile,
                                "PROF_ATTRIBUTES." + ((isNewAttrForRes) ? "ADD" : "MODIFY"), logParam, "OK");
                    }

                    //else the List of attributes will be sent to the client
                } else {
                    getAttributesList(locale, attrDao);
                }
            } else {
                getAttributesList(locale, attrDao);
            }

        } catch (Throwable e) {
            try {
                AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.ADD", null, "OK");
            } catch (Exception e3) {
                // TODO Auto-generated catch block
                e3.printStackTrace();
            }
            logger.error(e.getMessage(), e);
            getHttpResponse().setStatus(404);
            try {
                JSONObject attributesResponseSuccessJSON = new JSONObject();
                attributesResponseSuccessJSON.put("success", true);
                attributesResponseSuccessJSON.put("message", "Exception occurred while saving attribute");
                attributesResponseSuccessJSON.put("data", "[]");
                writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));
            } catch (IOException e1) {
                logger.error(e1.getMessage(), e1);
            } catch (JSONException e2) {
                logger.error(e2.getMessage(), e2);
            }
            throw new SpagoBIServiceException(SERVICE_NAME, "Exception occurred while retrieving attributes",
                    e);
        }
    } else if (serviceType != null && serviceType.equalsIgnoreCase(ATTR_DELETE)) {

        String idStr = null;
        try {
            BufferedReader b = httpRequest.getReader();
            if (b != null) {
                String respJsonObject = b.readLine();
                if (respJsonObject != null) {
                    JSONObject responseJSON = deserialize(respJsonObject);
                    idStr = responseJSON.getString(SAMPLES);
                }
            }

        } catch (IOException e1) {
            logger.error("IO Exception", e1);
            e1.printStackTrace();
        } catch (SerializationException e) {
            logger.error("Deserialization Exception", e);
            e.printStackTrace();
        } catch (JSONException e) {
            logger.error("JSONException", e);
            e.printStackTrace();
        }
        if (idStr != null && !idStr.equals("")) {
            HashMap<String, String> logParam = new HashMap();
            logParam.put("ATTRIBUTE ID", idStr);
            Integer id = new Integer(idStr);
            try {
                attrDao.deleteSbiAttributeById(id);
                logger.debug("Attribute deleted");
                JSONObject attributesResponseSuccessJSON = new JSONObject();
                attributesResponseSuccessJSON.put("success", true);
                attributesResponseSuccessJSON.put("message", "");
                attributesResponseSuccessJSON.put("data", "[]");
                writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));
                AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.DELETE", logParam,
                        "OK");
            } catch (Throwable e) {
                logger.error("Exception occurred while deleting attribute", e);
                getHttpResponse().setStatus(404);
                try {
                    JSONObject attributesResponseSuccessJSON = new JSONObject();
                    attributesResponseSuccessJSON.put("success", false);
                    attributesResponseSuccessJSON.put("message", "Exception occurred while deleting attribute");
                    attributesResponseSuccessJSON.put("data", "[]");
                    writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));
                    try {
                        AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.DELETE",
                                logParam, "KO");
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                } catch (IOException e1) {
                    logger.error(e1.getMessage(), e1);
                } catch (JSONException e2) {
                    // TODO Auto-generated catch block
                    logger.error(e2.getMessage(), e2);
                }
                /*               throw new SpagoBIServiceException(SERVICE_NAME,
                                     "Exception occurred while deleting attribute",
                                     e);*/
            }
        }
    }
    logger.debug("OUT");

}

From source file:com.sapienter.jbilling.server.user.validator.RepeatedPasswordValidator.java

/**
 * Struts validator that checks whether the password that is being set
 * by the user has been already used in the last two years.
 * @param bean/*from w  w  w. j ava  2s.  c o  m*/
 * @param va
 * @param field
 * @param errors
 * @param request
 * @param application
 * @return <code>true</code> if the validation passes and the password
 * has not been used, otherwise <code>false</code>.
 */
public static boolean validateRepeatedPassword(Object bean, ValidatorAction va, Field field,
        ActionErrors errors, HttpServletRequest request, ServletContext application) {

    boolean result = true;
    String value = ValidatorUtils.getValueAsString(bean, field.getProperty());

    // Determine the id and role of the user changing his password
    Integer userId = (Integer) request.getSession().getAttribute(Constants.SESSION_USER_ID);
    Integer userRole = null;
    try {
        IUserSessionBean user = (IUserSessionBean) Context.getBean(Context.Name.USER_SESSION);
        userRole = user.getUserDTOEx(userId).getMainRoleId();
    } catch (Exception e) {
        result = false;
    }
    // Perform the check in the event_log table to see if the user has
    // previously used the password he's trying to set now.
    if (result && !GenericValidator.isBlankOrNull(value)) {
        result = basicValidation(userId, userRole, value);
    }

    if (result == false) {
        errors.add(field.getKey(), Resources.getActionError(request, va, field));
    }

    return result;
}

From source file:com.aoindustries.website.signup.SignupBusinessActionHelper.java

public static void printConfirmation(ChainWriter emailOut, AOServConnector rootConn,
        SignupBusinessForm signupBusinessForm) throws IOException, SQLException {
    emailOut.print("    <tr>\n" + "        <td>").print(accessor.getMessage("signup.required"))
            .print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupBusinessForm.businessName.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupBusinessForm.getBusinessName())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.required")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupBusinessForm.businessPhone.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupBusinessForm.getBusinessPhone())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupBusinessForm.businessFax.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupBusinessForm.getBusinessFax())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.required")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupBusinessForm.businessAddress1.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupBusinessForm.getBusinessAddress1())
            .print("</td>\n" + "    </tr>\n");
    if (!GenericValidator.isBlankOrNull(signupBusinessForm.getBusinessAddress2())) {
        emailOut.print("    <tr>\n" + "        <td>").print(accessor.getMessage("signup.notRequired"))
                .print("</td>\n" + "        <td>")
                .print(accessor.getMessage("signupBusinessForm.businessAddress2.prompt"))
                .print("</td>\n" + "        <td>").encodeXhtml(signupBusinessForm.getBusinessAddress2())
                .print("</td>\n" + "    </tr>\n");
    }//from  w ww .  j  a  v a 2s .  c  o  m
    emailOut.print("    <tr>\n" + "        <td>").print(accessor.getMessage("signup.required"))
            .print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupBusinessForm.businessCity.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupBusinessForm.getBusinessCity())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupBusinessForm.businessState.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupBusinessForm.getBusinessState())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.required")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupBusinessForm.businessCountry.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(getBusinessCountry(rootConn, signupBusinessForm))
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupBusinessForm.businessZip.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupBusinessForm.getBusinessZip())
            .print("</td>\n" + "    </tr>\n");
}

From source file:de.codecentric.janus.plugin.bootstrap.BootstrapProjectAction.java

@JavaScriptMethod
public String isValidGroupName(String value) {
    if (GenericValidator.isBlankOrNull(value) || value.length() < 3) {
        return "Please use at least three character long group names.";
    }//w  w  w .  j  a va2s . c o m

    return null;
}

From source file:com.aoindustries.website.signup.SignupTechnicalActionHelper.java

public static void printConfirmation(ChainWriter emailOut, AOServConnector rootConn,
        SignupTechnicalForm signupTechnicalForm) throws IOException, SQLException {
    emailOut.print("    <tr>\n" + "        <td>").print(accessor.getMessage("signup.required"))
            .print("</td>\n" + "        <td>").print(accessor.getMessage("signupTechnicalForm.baName.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupTechnicalForm.getBaName())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baTitle.prompt")).print("</td>\n" + "        <td>")
            .encodeXhtml(signupTechnicalForm.getBaTitle())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.required")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baWorkPhone.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupTechnicalForm.getBaWorkPhone())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baCellPhone.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupTechnicalForm.getBaCellPhone())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baHomePhone.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupTechnicalForm.getBaHomePhone())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baFax.prompt")).print("</td>\n" + "        <td>")
            .encodeXhtml(signupTechnicalForm.getBaFax())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.required")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baEmail.prompt")).print("</td>\n" + "        <td>")
            .encodeXhtml(signupTechnicalForm.getBaEmail())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baAddress1.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupTechnicalForm.getBaAddress1())
            .print("</td>\n" + "    </tr>\n");
    if (!GenericValidator.isBlankOrNull(signupTechnicalForm.getBaAddress2())) {
        emailOut.print("    <tr>\n" + "        <td>").print(accessor.getMessage("signup.notRequired"))
                .print("</td>\n" + "        <td>")
                .print(accessor.getMessage("signupTechnicalForm.baAddress2.prompt"))
                .print("</td>\n" + "        <td>").encodeXhtml(signupTechnicalForm.getBaAddress2())
                .print("</td>\n" + "    </tr>\n");
    }//from  w w w  .  j  a va 2s .  c  o m
    emailOut.print("    <tr>\n" + "        <td>").print(accessor.getMessage("signup.notRequired"))
            .print("</td>\n" + "        <td>").print(accessor.getMessage("signupTechnicalForm.baCity.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupTechnicalForm.getBaCity())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baState.prompt")).print("</td>\n" + "        <td>")
            .encodeXhtml(signupTechnicalForm.getBaState())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baCountry.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(getBaCountry(rootConn, signupTechnicalForm))
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baZip.prompt")).print("</td>\n" + "        <td>")
            .encodeXhtml(signupTechnicalForm.getBaZip())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.required")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baUsername.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupTechnicalForm.getBaUsername())
            .print("</td>\n" + "    </tr>\n" + "    <tr>\n" + "        <td>")
            .print(accessor.getMessage("signup.notRequired")).print("</td>\n" + "        <td>")
            .print(accessor.getMessage("signupTechnicalForm.baPassword.prompt"))
            .print("</td>\n" + "        <td>").encodeXhtml(signupTechnicalForm.getBaPassword())
            .print("</td>\n" + "    </tr>\n");
}

From source file:com.aoindustries.website.clientarea.accounting.CreditCardForm.java

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = super.validate(mapping, request);
    if (errors == null)
        errors = new ActionErrors();
    if (GenericValidator.isBlankOrNull(accounting))
        errors.add("accounting", new ActionMessage("creditCardForm.accounting.required"));
    if (GenericValidator.isBlankOrNull(firstName))
        errors.add("firstName", new ActionMessage("creditCardForm.firstName.required"));
    if (GenericValidator.isBlankOrNull(lastName))
        errors.add("lastName", new ActionMessage("creditCardForm.lastName.required"));
    if (GenericValidator.isBlankOrNull(streetAddress1))
        errors.add("streetAddress1", new ActionMessage("creditCardForm.streetAddress1.required"));
    if (GenericValidator.isBlankOrNull(city))
        errors.add("city", new ActionMessage("creditCardForm.city.required"));
    if (GenericValidator.isBlankOrNull(state))
        errors.add("state", new ActionMessage("creditCardForm.state.required"));
    if (GenericValidator.isBlankOrNull(countryCode))
        errors.add("countryCode", new ActionMessage("creditCardForm.countryCode.required"));
    if (GenericValidator.isBlankOrNull(postalCode))
        errors.add("postalCode", new ActionMessage("creditCardForm.postalCode.required"));
    return errors;
}

From source file:com.aoindustries.website.signup.SignupBillingInformationForm.java

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = super.validate(mapping, request);
    if (errors == null)
        errors = new ActionErrors();
    if (GenericValidator.isBlankOrNull(billingContact))
        errors.add("billingContact", new ActionMessage("signupBillingInformationForm.billingContact.required"));
    if (GenericValidator.isBlankOrNull(billingEmail)) {
        errors.add("billingEmail", new ActionMessage("signupBillingInformationForm.billingEmail.required"));
    } else if (!GenericValidator.isEmail(billingEmail)) {
        errors.add("billingEmail", new ActionMessage("signupBillingInformationForm.billingEmail.invalid"));
    }/* w w w. j a va  2s  .c  o  m*/
    if (GenericValidator.isBlankOrNull(billingCardholderName))
        errors.add("billingCardholderName",
                new ActionMessage("signupBillingInformationForm.billingCardholderName.required"));
    if (GenericValidator.isBlankOrNull(billingCardNumber)) {
        errors.add("billingCardNumber",
                new ActionMessage("signupBillingInformationForm.billingCardNumber.required"));
    } else if (!GenericValidator.isCreditCard(CreditCard.numbersOnly(billingCardNumber))) {
        errors.add("billingCardNumber",
                new ActionMessage("signupBillingInformationForm.billingCardNumber.invalid"));
    }
    if (GenericValidator.isBlankOrNull(billingExpirationMonth)
            || GenericValidator.isBlankOrNull(billingExpirationYear))
        errors.add("billingExpirationDate",
                new ActionMessage("signupBillingInformationForm.billingExpirationDate.required"));
    if (GenericValidator.isBlankOrNull(billingStreetAddress))
        errors.add("billingStreetAddress",
                new ActionMessage("signupBillingInformationForm.billingStreetAddress.required"));
    if (GenericValidator.isBlankOrNull(billingCity))
        errors.add("billingCity", new ActionMessage("signupBillingInformationForm.billingCity.required"));
    if (GenericValidator.isBlankOrNull(billingState))
        errors.add("billingState", new ActionMessage("signupBillingInformationForm.billingState.required"));
    if (GenericValidator.isBlankOrNull(billingZip))
        errors.add("billingZip", new ActionMessage("signupBillingInformationForm.billingZip.required"));
    return errors;
}

From source file:com.aoindustries.website.signup.SignupTechnicalForm.java

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = super.validate(mapping, request);
    if (errors == null)
        errors = new ActionErrors();
    try {/*from   ww w .j  a  va  2  s. co  m*/
        if (GenericValidator.isBlankOrNull(baName))
            errors.add("baName", new ActionMessage("signupTechnicalForm.baName.required"));
        if (GenericValidator.isBlankOrNull(baWorkPhone))
            errors.add("baWorkPhone", new ActionMessage("signupTechnicalForm.baWorkPhone.required"));
        if (GenericValidator.isBlankOrNull(baEmail)) {
            errors.add("baEmail", new ActionMessage("signupTechnicalForm.baEmail.required"));
        } else if (!GenericValidator.isEmail(baEmail)) {
            errors.add("baEmail", new ActionMessage("signupTechnicalForm.baEmail.invalid"));
        }
        if (GenericValidator.isBlankOrNull(baUsername))
            errors.add("baUsername", new ActionMessage("signupTechnicalForm.baUsername.required"));
        else {
            ActionServlet myServlet = getServlet();
            if (myServlet != null) {
                AOServConnector rootConn = SiteSettings.getInstance(myServlet.getServletContext())
                        .getRootAOServConnector();
                String lowerUsername = baUsername.toLowerCase();
                ValidationResult check = UserId.validate(lowerUsername);
                if (!check.isValid()) {
                    errors.add("baUsername", new ActionMessage(check.toString(), false));
                } else {
                    UserId userId;
                    try {
                        userId = UserId.valueOf(lowerUsername);
                    } catch (ValidationException e) {
                        AssertionError ae = new AssertionError("Already validated");
                        ae.initCause(e);
                        throw ae;
                    }
                    if (!rootConn.getUsernames().isUsernameAvailable(userId))
                        errors.add("baUsername",
                                new ActionMessage("signupTechnicalForm.baUsername.unavailable"));
                }
            }
        }
        return errors;
    } catch (IOException err) {
        throw new WrappedException(err);
    } catch (SQLException err) {
        throw new WrappedException(err);
    }
}

From source file:de.codecentric.janus.plugin.bootstrap.BootstrapProjectAction.java

@JavaScriptMethod
public String isValidJIRAProjectKey(String jiraConfigName, String key) {
    if (GenericValidator.isBlankOrNull(key)) {
        return "Please provide a key";
    } else if (!KEY_PATTERN.matcher(key).matches()) {
        return "The project key is not in the required format (^[A-Z]+$).";
    }/*from w ww .j  a  va2  s  .c  o m*/

    try {
        JiraSession session = getJiraSession(getJiraConfig(jiraConfigName));
        JiraClient client = new JiraClient(session);

        client.getProject(key);

        session.close();
        return "Project key already used.";
    } catch (AtlassianException ex) {
        if (ex.getMessage().contains("No project could be found")) {
            return null;
        }

        throw ex;
    }
}