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

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

Introduction

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

Prototype

public static boolean isInt(String value) 

Source Link

Document

Checks if the value can safely be converted to a int primitive.

Usage

From source file:jp.primecloud.auto.api.util.ValidateUtil.java

/**
 *
 * ???(int)//  w ww.  j  a  va 2  s .  c o m
 *
 * @param value ??
 * @param min ?
 * @param max 
 * @param code ??
 * @param params ??
 */
public static void intInRange(String value, int min, int max, String code, Object[] params) {
    if (GenericValidator.isInt(value) == false) {
        throw new AutoApplicationException(code, params);
    }
    if (GenericValidator.isInRange(Integer.valueOf(value), min, max) == false) {
        throw new AutoApplicationException(code, params);
    }
}

From source file:com.codeup.movies.validation.AddMovieValidator.java

private void validateRating() {
    List<String> messages = new ArrayList<>();

    if (!GenericValidator.isInt(rating)) {
        messages.add("Rating should be an integer number");
        errors.put("rating", messages);
        return;//from   w ww . jav  a2 s.  com
    }

    if (!GenericValidator.isInRange(Integer.parseInt(rating), 1, 5)) {
        messages.add("Rating should be a number between 1 and 5");
        errors.put("rating", messages);
    }
}

From source file:com.surveypanel.form.validation.NumericValidator.java

@Override
public void validate(QuestionImpl question, FormData formData, Locale locale, Map<String, String> config,
        ValidationResult validationResult) throws Exception {
    String errorMsg = config.containsKey("errorKey") ? config.get("errorKey") : "form.error.numeric";
    Integer maximum = 0;/* w w  w . j ava  2  s .c  om*/
    Integer minimum = 0;
    String numericType = config.containsKey("type") ? config.get("type") : "int";

    String error_range = config.containsKey("error_range") ? config.get("error_range") : "form.error.range";

    String min = config.get("min");
    String max = config.get("max");

    if (max != null)
        maximum = Integer.parseInt(max);
    if (min != null)
        minimum = Integer.parseInt(min);

    if (!question.isMulti()) {
        Object value = formData.getValue();
        if (value instanceof String) {
            boolean isRightType = false;
            boolean isInRange = false;
            boolean checkRange = maximum > 0 || minimum > 0;
            if (numericType.equals(INT)) {
                isRightType = GenericValidator.isInt((String) value);
                if (isRightType) {
                    isInRange = checkRange ? GenericValidator.isInRange((Integer) value, minimum, maximum)
                            : true;
                }
            } else if (numericType.equals(FLOAT)) {
                isRightType = GenericValidator.isFloat((String) value);
                if (isRightType) {
                    isInRange = checkRange ? GenericValidator.isInRange((Float) value, minimum, maximum) : true;
                }
            } else if (numericType.equals(DOUBLE)) {
                isRightType = GenericValidator.isDouble((String) value);
                if (isRightType) {
                    isInRange = checkRange ? GenericValidator.isInRange((Double) value, minimum, maximum)
                            : true;
                }
            }

            if (!isRightType) {
                validationResult
                        .addError(qDefinition.getText(errorMsg, new Object[] { question.getName() }, locale));
            } else if (!isInRange) {
                validationResult.addError(qDefinition.getText(error_range,
                        new Object[] { question.getName(), minimum, maximum }, locale));
            }
        }
    }
}

From source file:com.core.validators.CommonValidator.java

/**
 * Checks if the field can be successfully converted to a <code>int</code>.
 *
 * @param    value       The value validation is being performed on.
 * @return   boolean      If the field can be successfully converted 
 *                           to a <code>int</code> <code>true</code> is returned.  
 *                           Otherwise <code>false</code>.
 *///w ww .  j  av a2 s  .  c om
public static boolean validateInt(Object bean, Field field) {
    String value = ValidatorUtils.getValueAsString(bean, field.getProperty());

    if (value == null || value.isEmpty()) {
        return true;
    }
    if (!GenericValidator.isInt(value)) {
        return false;
    }

    if (field.getVarValue("lt") != null) {
        int lt = Integer.parseInt(field.getVarValue("lt"));
        int old = Integer.parseInt(value);

        if (old < lt) {
            return false;
        }

    }
    return true;
}

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

@Override
public void validate(Object obj, Errors errors) {
    try {/*from ww  w. 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.sdk.datasets.impl.DataSetsSDKServiceImpl.java

private void checkParameterValues(String[] values, DataSetParameterItem dataSetParameterItem)
        throws InvalidParameterValue {
    logger.debug("IN");
    try {//from  w ww .ja  v a2 s. com
        String parameterType = dataSetParameterItem.getType();
        if (parameterType.equalsIgnoreCase("Number")) {
            for (int i = 0; i < values.length; i++) {
                String value = values[i];
                if (GenericValidator.isBlankOrNull(value) || (!(GenericValidator.isInt(value)
                        || GenericValidator.isFloat(value) || GenericValidator.isDouble(value)
                        || GenericValidator.isShort(value) || GenericValidator.isLong(value)))) {
                    InvalidParameterValue error = new InvalidParameterValue();
                    error.setParameterName(dataSetParameterItem.getName());
                    error.setParameterType(parameterType);
                    error.setWrongParameterValue(value);
                    error.setParameterFormat("");
                    throw error;
                }
            }
        }
    } finally {
        logger.debug("OUT");
    }
}

From source file:gov.nih.nci.cabig.caaers.web.security.FabricatedAuthenticationFilter.java

private URLToEntityIdMapEntry getURLToEntityIdEntryFromRequest(HttpServletRequest request) {
    String path = getPathFromRequest(request);
    String value = getFilterByURLAndEntityMap().get(path);
    if (value != null) {
        String className = value.split(COLON)[0];
        String parameterName = value.split(COLON)[1];
        String parameterValue = request.getParameter(parameterName);
        if (GenericValidator.isInt(parameterValue)) {
            URLToEntityIdMapEntry entry = new URLToEntityIdMapEntry();
            entry.setClassName(className);
            entry.setParameterName(parameterName);
            entry.setObjectId(Integer.parseInt(parameterValue));
            return entry;
        }/*w  w w  .j  av a  2s .com*/
    }
    return null;
}

From source file:it.eng.spagobi.behaviouralmodel.lov.bo.QueryDetail.java

private void validateNumber(String value) {
    if (!(GenericValidator.isInt(value) || GenericValidator.isFloat(value) || GenericValidator.isDouble(value)
            || GenericValidator.isShort(value) || GenericValidator.isLong(value))) {
        throw new SecurityException("Input value " + value + " is not a valid number");
    }//from   ww  w .j  a v a2s. co m
}

From source file:it.eng.spagobi.commons.validation.SpagoBIValidationImpl.java

public static EMFValidationError validateField(String fieldName, String fieldLabel, String value,
        String validatorName, String arg0, String arg1, String arg2) throws Exception {

    List params = null;/*w  w w  .  j  ava  2s  .c  om*/

    if (validatorName.equalsIgnoreCase("MANDATORY")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the MANDATORY VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (GenericValidator.isBlankOrNull(value)) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_MANDATORY, params);

        }

    } else if (validatorName.equalsIgnoreCase("URL")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the URL VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        UrlValidator urlValidator = new SpagoURLValidator();
        if (!GenericValidator.isBlankOrNull(value) && !urlValidator.isValid(value)) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_URL, params);

        }
    } else if (validatorName.equalsIgnoreCase("LETTERSTRING")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the LETTERSTRING VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value)
                && !GenericValidator.matchRegexp(value, LETTER_STRING_REGEXP)) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_LETTERSTRING, params);

        }
    } else if (validatorName.equalsIgnoreCase("ALFANUMERIC")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the ALFANUMERIC VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value)
                && !GenericValidator.matchRegexp(value, ALPHANUMERIC_STRING_REGEXP)) {

            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_ALFANUMERIC, params);

        }
    } else if (validatorName.equalsIgnoreCase("NUMERIC")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the NUMERIC VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value) && (!(GenericValidator.isInt(value)
                || GenericValidator.isFloat(value) || GenericValidator.isDouble(value)
                || GenericValidator.isShort(value) || GenericValidator.isLong(value)))) {

            // The string is not a integer, not a float, not double, not short, not long
            // so is not a number

            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_NUMERIC, params);

        }

    } else if (validatorName.equalsIgnoreCase("EMAIL")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the EMAIL VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isEmail(value)) {

            // Generate errors
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_EMAIL, params);

        }
    } else if (validatorName.equalsIgnoreCase("BOOLEAN")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the MANDATORY VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value) && !value.equalsIgnoreCase("true")
                && !value.equalsIgnoreCase("false")) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_BOOLEAN, params);

        }

    } else if (validatorName.equalsIgnoreCase("FISCALCODE")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the FISCALCODE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value)
                && !GenericValidator.matchRegexp(value, FISCAL_CODE_REGEXP)) {

            //             Generate errors
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_FISCALCODE, params);

        }
    } else if (validatorName.equalsIgnoreCase("DECIMALS")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the DECIMALS VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            int maxNumberOfDecimalDigit = Integer.valueOf(arg0).intValue();
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Max Numbers of decimals is [" + maxNumberOfDecimalDigit + "]");
            String decimalSeparator = arg1;

            if (GenericValidator.isBlankOrNull(decimalSeparator)) {
                decimalSeparator = ".";
            }

            int pos = value.indexOf(decimalSeparator);
            String decimalCharacters = "";
            if (pos != -1)
                decimalCharacters = value.substring(pos + 1);

            if (decimalCharacters.length() > maxNumberOfDecimalDigit) {
                // Generate errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(String.valueOf(maxNumberOfDecimalDigit));
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_DECIMALS, params);
            }
        }
    } else if (validatorName.equalsIgnoreCase("NUMERICRANGE")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the NUMERICRANGE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String firstValueStr = arg0;
            String secondValueStr = arg1;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
            boolean syntaxCorrect = true;
            if (!GenericValidator.isDouble(value)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE NUMERICRANGE VALIDATOR  value [" + value + "] is not a Number");
                syntaxCorrect = false;
            }
            if (!GenericValidator.isDouble(firstValueStr)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE NUMERICRANGE VALIDATOR  first value of range [" + firstValueStr
                                + "] is not a Number");
                syntaxCorrect = false;
            }
            if (!GenericValidator.isDouble(secondValueStr)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE NUMERICRANGE VALIDATOR  second value of range [" + secondValueStr
                                + "] is not a Number");
                syntaxCorrect = false;
            }
            if (syntaxCorrect) {
                double firstValue = Double.valueOf(firstValueStr).doubleValue();
                double secondValue = Double.valueOf(secondValueStr).doubleValue();
                double valueToCheckDouble = Double.valueOf(value).doubleValue();
                if (!(GenericValidator.isInRange(valueToCheckDouble, firstValue, secondValue))) {

                    params = new ArrayList();
                    params.add(fieldLabel);
                    params.add(firstValueStr);
                    params.add(secondValueStr);
                    return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_RANGE, params);

                }
            } else {
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_GENERIC);
            }
        }
    } else if (validatorName.equalsIgnoreCase("DATERANGE")) {

        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the DATERANGE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String firstValueStr = arg0;
            String secondValueStr = arg1;
            String dateFormat = arg2;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Date Format is  [" + dateFormat + "]");
            //         //boolean syntaxCorrect = false;
            boolean syntaxCorrect = true;

            //if (!GenericValidator.isDate(value,dateFormat,true)){
            if (!GenericValidator.isDate(value, dateFormat, true)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE DATERANGE VALIDATOR  value [" + value
                                + "] is not a is not valid Date according to [" + dateFormat + "]");
                syntaxCorrect = false;
            }
            //if (!GenericValidator.isDate(firstValueStr,dateFormat,true)){
            if (!GenericValidator.isDate(firstValueStr, dateFormat, true)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE DATERANGE VALIDATOR  first value of range [" + firstValueStr
                                + "] is not valid Date according to [" + dateFormat + "]");
                syntaxCorrect = false;
            }
            //if (!GenericValidator.isDate(secondValueStr,dateFormat, true)){
            if (!GenericValidator.isDate(secondValueStr, dateFormat, true)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE DATERANGE VALIDATOR  second value of range [" + secondValueStr
                                + "] is not a valid Date according to [" + dateFormat + "]");
                syntaxCorrect = false;
            }

            if (syntaxCorrect) {
                DateFormat df = new SimpleDateFormat(dateFormat);

                Date firstValueDate = df.parse(firstValueStr);
                Date secondValueDate = df.parse(secondValueStr);
                Date theValueDate = df.parse(value);

                if ((theValueDate.getTime() < firstValueDate.getTime())
                        || (theValueDate.getTime() > secondValueDate.getTime())) {
                    params = new ArrayList();
                    params.add(fieldLabel);
                    params.add(firstValueStr);
                    params.add(secondValueStr);
                    return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_RANGE, params);
                }
            } else {
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_GENERIC);
            }
        }
    } else if (validatorName.equalsIgnoreCase("STRINGRANGE")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the STRINGRANGE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");

            String firstValueStr = arg0;
            String secondValueStr = arg1;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
            //if (firstValueStr.compareTo(secondValueStr) > 0){
            if ((value.compareTo(firstValueStr) < 0) || (value.compareTo(secondValueStr) > 0)) {
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(firstValueStr);
                params.add(secondValueStr);
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_RANGE, params);
            }
        }
    } else if (validatorName.equalsIgnoreCase("MAXLENGTH")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the MAXLENGTH VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            int maxLength = Integer.valueOf(arg0).intValue();
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "maxLength is [" + maxLength + "]");
            if (!GenericValidator.maxLength(value, maxLength)) {

                params = new ArrayList();
                params.add(fieldLabel);
                params.add(String.valueOf(maxLength));

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_MAXLENGTH, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("MINLENGTH")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the MINLENGTH VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            int minLength = Integer.valueOf(arg0).intValue();
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "minLength is [" + minLength + "]");
            if (!GenericValidator.minLength(value, minLength)) {

                // Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(String.valueOf(minLength));

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_MINLENGTH, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("REGEXP")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the REGEXP VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String regexp = arg0;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator", "regexp is [" + regexp + "]");
            if (!(GenericValidator.matchRegexp(value, regexp))) {

                // Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(regexp);

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_REGEXP, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("XSS")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the XSS VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String toVerify = value.toUpperCase();
            if (toVerify.contains("<A") || toVerify.contains("<LINK") || toVerify.contains("<IMG")
                    || toVerify.contains("<SCRIPT") || toVerify.contains("&LT;A")
                    || toVerify.contains("&LT;LINK") || toVerify.contains("&LT;IMG")
                    || toVerify.contains("&LT;SCRIPT")) {

                // Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_XSS, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("DATE")) {

        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the DATE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String dateFormat = arg0;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "dateFormat is [" + dateFormat + "]");
            //if (!GenericValidator.isDate(value, dateFormat, true)){
            if (!GenericValidator.isDate(value, dateFormat, true)) {

                //Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(dateFormat);

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_DATE, params);
            }
        }

    }

    // all checks had positive result (no errors)
    return null;
}

From source file:it.eng.spagobi.commons.utilities.BIObjectValidator.java

/**
 * For each input field type (Numeric, URL, extc:), this method applies validation.
 * Every time a validation fails, an error is added to the <code>errorHandler</code>
 * errors stack./*from w w w. j  a va2s  . co m*/
 * The field label to be displayed is defined in file validation.xml for each 
 * validation: if it is not defined it is set with the field name; if it starts with 
 * "#" it is interpreted as a key and the message is recovered by 
 * PortletUtilities.getMessage(key, "messages") method, else it remains unchanged. 
 * 
 * @param serviceRequest The request Source Bean
 * @param errorHandler The errors Stack 
 * @throws Exception If any exception occurs.
 */
private void automaticValidation(SourceBean serviceRequest, EMFErrorHandler errorHandler) throws Exception {

    // Reperisco l'elenco di tutti gli attributi che mi aspetto di trovare
    // nella richiesta
    List fields = _validationStructure.getAttributeAsList("FIELDS.FIELD");

    for (Iterator iter = fields.iterator(); iter.hasNext();) {

        String value = null;

        List validators = null;
        SourceBean currentValidator = null;
        String validatorName = null;
        Iterator itValidators = null;
        try {
            SourceBean field = (SourceBean) iter.next();

            String fieldName = (String) field.getAttribute("name");

            value = (String) serviceRequest.getAttribute(fieldName);

            //********************************************
            String fieldLabel = (String) field.getAttribute("label");
            if (fieldLabel != null && fieldLabel.startsWith("#")) {
                String key = fieldLabel.substring(1);
                String fieldDescription = PortletUtilities.getMessage(key, "messages");
                if (fieldDescription != null && !fieldDescription.trim().equals(""))
                    fieldLabel = fieldDescription;
            }
            if (fieldLabel == null || fieldLabel.trim().equals(""))
                fieldLabel = fieldName;
            //********************************************

            validators = field.getAttributeAsList("VALIDATOR");

            itValidators = validators.iterator();

            Vector params = new Vector();
            while (itValidators.hasNext()) {
                currentValidator = (SourceBean) itValidators.next();
                validatorName = (String) currentValidator.getAttribute("validatorName");

                if (validatorName.equalsIgnoreCase("MANDATORY")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the MANDATORY VALIDATOR to field [" + field + "] with value [" + value
                                    + "]");
                    if (GenericValidator.isBlankOrNull(value)) {
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler
                                .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_MANDATORY, params));

                    }

                } else if (validatorName.equalsIgnoreCase("URL")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the URL VALIDATOR to field [" + field + "] with value [" + value + "]");
                    UrlValidator urlValidator = new SpagoURLValidator();
                    if (!GenericValidator.isBlankOrNull(value) && !urlValidator.isValid(value)) {
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_URL, params));

                    }
                } else if (validatorName.equalsIgnoreCase("LETTERSTRING")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the LETTERSTRING VALIDATOR to field [" + field + "] with value [" + value
                                    + "]");
                    if (!GenericValidator.isBlankOrNull(value)
                            && !GenericValidator.matchRegexp(value, LETTER_STRING_REGEXP)) {
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler
                                .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_LETTERSTRING, params));

                    }
                } else if (validatorName.equalsIgnoreCase("ALFANUMERIC")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the ALFANUMERIC VALIDATOR to field [" + field + "] with value [" + value
                                    + "]");
                    if (!GenericValidator.isBlankOrNull(value)
                            && !GenericValidator.matchRegexp(value, ALPHANUMERIC_STRING_REGEXP)) {

                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler
                                .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_ALFANUMERIC, params));

                    }
                } else if (validatorName.equalsIgnoreCase("NUMERIC")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the NUMERIC VALIDATOR to field [" + field + "] with value [" + value + "]");
                    if (!GenericValidator.isBlankOrNull(value) && (!(GenericValidator.isInt(value)
                            || GenericValidator.isFloat(value) || GenericValidator.isDouble(value)
                            || GenericValidator.isShort(value) || GenericValidator.isLong(value)))) {

                        // The string is not a integer, not a float, not double, not short, not long
                        // so is not a number

                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_NUMERIC, params));

                    }

                } else if (validatorName.equalsIgnoreCase("EMAIL")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the EMAIL VALIDATOR to field [" + field + "] with value [" + value + "]");
                    if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isEmail(value)) {

                        // Generate errors
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_EMAIL, params));

                    }
                } else if (validatorName.equalsIgnoreCase("FISCALCODE")) {
                    SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                            "Apply the FISCALCODE VALIDATOR to field [" + field + "] with value [" + value
                                    + "]");
                    if (!GenericValidator.isBlankOrNull(value)
                            && !GenericValidator.matchRegexp(value, FISCAL_CODE_REGEXP)) {

                        //                      Generate errors
                        params = new Vector();
                        params.add(fieldLabel);
                        errorHandler
                                .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_FISCALCODE, params));

                    }
                } else if (validatorName.equalsIgnoreCase("DECIMALS")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the DECIMALS VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        int maxNumberOfDecimalDigit = Integer
                                .valueOf((String) currentValidator.getAttribute("arg0")).intValue();
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Max Numbers of decimals is [" + maxNumberOfDecimalDigit + "]");
                        String decimalSeparator = (String) currentValidator.getAttribute("arg1");

                        if (GenericValidator.isBlankOrNull(decimalSeparator)) {
                            decimalSeparator = ".";
                        }

                        int pos = value.indexOf(decimalSeparator);
                        String decimalCharacters = "";
                        if (pos != -1)
                            decimalCharacters = value.substring(pos + 1);

                        if (decimalCharacters.length() > maxNumberOfDecimalDigit) {
                            // Generate errors
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(String.valueOf(maxNumberOfDecimalDigit));
                            errorHandler
                                    .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_DECIMALS, params));
                        }
                    }
                } else if (validatorName.equalsIgnoreCase("NUMERICRANGE")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the NUMERICRANGE VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        String firstValueStr = (String) currentValidator.getAttribute("arg0");
                        String secondValueStr = (String) currentValidator.getAttribute("arg1");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
                        boolean syntaxCorrect = true;
                        if (!GenericValidator.isDouble(value)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE NUMERICRANGE VALIDATOR  value [" + value
                                            + "] is not a Number");
                            syntaxCorrect = false;
                        }
                        if (!GenericValidator.isDouble(firstValueStr)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE NUMERICRANGE VALIDATOR  first value of range ["
                                            + firstValueStr + "] is not a Number");
                            syntaxCorrect = false;
                        }
                        if (!GenericValidator.isDouble(secondValueStr)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE NUMERICRANGE VALIDATOR  second value of range ["
                                            + secondValueStr + "] is not a Number");
                            syntaxCorrect = false;
                        }
                        if (syntaxCorrect) {
                            double firstValue = Double.valueOf(firstValueStr).doubleValue();
                            double secondValue = Double.valueOf(secondValueStr).doubleValue();
                            double valueToCheckDouble = Double.valueOf(value).doubleValue();
                            if (!(GenericValidator.isInRange(valueToCheckDouble, firstValue, secondValue))) {

                                params = new Vector();
                                params.add(fieldLabel);
                                params.add(firstValueStr);
                                params.add(secondValueStr);
                                errorHandler.addError(
                                        new EMFUserError(EMFErrorSeverity.ERROR, ERROR_RANGE, params));

                            }
                        } else {
                            errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_GENERIC));
                        }
                    }
                } else if (validatorName.equalsIgnoreCase("DATERANGE")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the DATERANGE VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        String firstValueStr = (String) currentValidator.getAttribute("arg0");
                        String secondValueStr = (String) currentValidator.getAttribute("arg1");
                        String dateFormat = (String) currentValidator.getAttribute("arg2");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Date Format is  [" + dateFormat + "]");
                        boolean syntaxCorrect = false;

                        if (!GenericValidator.isDate(value, dateFormat, true)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE DATERANGE VALIDATOR  value [" + value
                                            + "] is not a is not valid Date according to [" + dateFormat + "]");
                            syntaxCorrect = false;
                        }
                        if (!GenericValidator.isDate(firstValueStr, dateFormat, true)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE DATERANGE VALIDATOR  first value of range ["
                                            + firstValueStr + "] is not valid Date according to [" + dateFormat
                                            + "]");
                            syntaxCorrect = false;
                        }
                        if (!GenericValidator.isDate(secondValueStr, dateFormat, true)) {
                            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                    " CANNOT APPLY THE DATERANGE VALIDATOR  second value of range ["
                                            + secondValueStr + "] is not a valid Date according to ["
                                            + dateFormat + "]");
                            syntaxCorrect = false;
                        }

                        if (syntaxCorrect) {
                            DateFormat df = new SimpleDateFormat(dateFormat);

                            Date firstValueDate = df.parse(firstValueStr);
                            Date secondValueDate = df.parse(secondValueStr);
                            Date theValueDate = df.parse(value);

                            if ((theValueDate.getTime() < firstValueDate.getTime())
                                    || (theValueDate.getTime() > secondValueDate.getTime())) {
                                params = new Vector();
                                params.add(fieldLabel);
                                params.add(firstValueStr);
                                params.add(secondValueStr);
                                errorHandler.addError(
                                        new EMFUserError(EMFErrorSeverity.ERROR, ERROR_RANGE, params));
                            }
                        } else {
                            errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_GENERIC));
                        }
                    }

                } else if (validatorName.equalsIgnoreCase("STRINGRANGE")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the STRINGRANGE VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");

                        String firstValueStr = (String) currentValidator.getAttribute("arg0");
                        String secondValueStr = (String) currentValidator.getAttribute("arg1");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");

                        if (firstValueStr.compareTo(secondValueStr) > 0) {
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(firstValueStr);
                            params.add(secondValueStr);
                            errorHandler
                                    .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_RANGE, params));
                        }
                    }
                } else if (validatorName.equalsIgnoreCase("MAXLENGTH")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the MAXLENGTH VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        int maxLength = Integer.valueOf((String) currentValidator.getAttribute("arg0"))
                                .intValue();
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "maxLength is [" + maxLength + "]");
                        if (!GenericValidator.maxLength(value, maxLength)) {

                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(String.valueOf(maxLength));

                            errorHandler.addError(
                                    new EMFUserError(EMFErrorSeverity.ERROR, ERROR_MAXLENGTH, params));

                        }
                    }
                } else if (validatorName.equalsIgnoreCase("MINLENGTH")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the MINLENGTH VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        int minLength = Integer.valueOf((String) currentValidator.getAttribute("arg0"))
                                .intValue();
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "minLength is [" + minLength + "]");
                        if (!GenericValidator.minLength(value, minLength)) {

                            // Generate Errors
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(String.valueOf(minLength));

                            errorHandler.addError(
                                    new EMFUserError(EMFErrorSeverity.ERROR, ERROR_MINLENGTH, params));

                        }
                    }
                } else if (validatorName.equalsIgnoreCase("REGEXP")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the REGEXP VALIDATOR to field [" + field + "] with value [" + value
                                        + "]");
                        String regexp = (String) currentValidator.getAttribute("arg0");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "regexp is [" + regexp + "]");
                        if (!(GenericValidator.matchRegexp(value, regexp))) {

                            //                      Generate Errors
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(regexp);

                            errorHandler
                                    .addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_REGEXP, params));

                        }
                    }
                } else if (validatorName.equalsIgnoreCase("DATE")) {
                    if (!GenericValidator.isBlankOrNull(value)) {
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "Apply the DATE VALIDATOR to field [" + field + "] with value [" + value + "]");
                        String dateFormat = (String) currentValidator.getAttribute("arg0");
                        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                                "dateFormat is [" + dateFormat + "]");
                        if (!GenericValidator.isDate(value, dateFormat, true)) {

                            //Generate Errors
                            params = new Vector();
                            params.add(fieldLabel);
                            params.add(dateFormat);

                            errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, ERROR_DATE, params));
                        }
                    }

                }
            } //while (itValidators.hasNext())

        } catch (Exception ex) {
            TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.INFORMATION,
                    "ValidationModule::automaticValidation", ex);

        }

    }

}