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

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

Introduction

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

Prototype

public static boolean matchRegexp(String value, String regexp) 

Source Link

Document

Checks if the value matches the regular expression.

Usage

From source file:com.ao.service.ValidatorService.java

/**
 * Checks if the given character name is valid, or not.
 * /*from w  ww  .j a v  a2 s.  c om*/
 * @param name The character name.
 * @return True if the name is valid, false otherwise.
 */
public static boolean validCharacterName(String name) {
    //TODO: Take this to the security modules.
    boolean res = true;

    res = res && GenericValidator.matchRegexp(name, CHARACTER_NAME_REGEXP);
    res = res
            && GenericValidator.isInRange(name.length(), CHARACTER_NAME_MIN_LENGTH, CHARACTER_NAME_MAX_LENGTH);

    return res;
}

From source file:com.draagon.meta.validator.MaskValidator.java

/**
 * Validates the value of the field in the specified object
 *///from ww w .  j  a  va 2  s . c o m
public void validate(Object object, Object value)
//throws MetaException
{
    String mask = (String) getAttribute(ATTR_MASK);
    String msg = getMessage("Invalid value format");

    String val = (value == null) ? null : value.toString();

    if (!GenericValidator.isBlankOrNull(val) && !GenericValidator.matchRegexp(val, mask)) {
        throw new InvalidValueException(msg);
    }
}

From source file:com.codeup.auth.application.authentication.LoginInput.java

private void validateUsername(String username) {
    ArrayList<String> messages = new ArrayList<>();

    if (GenericValidator.isBlankOrNull(username))
        messages.add("Enter your username");
    if (username != null && !GenericValidator.matchRegexp(username, "[A-Za-z0-9._-]+"))
        messages.add("Your username does not have a valid format");

    if (messages.size() > 0)
        this.messages.put("username", messages);
}

From source file:com.primeleaf.krystal.web.action.cpanel.NewUserAction.java

public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);

    if (request.getMethod().equalsIgnoreCase("POST")) {

        String realName = request.getParameter("txtRealName") != null ? request.getParameter("txtRealName")
                : "";
        String userName = request.getParameter("txtUserName") != null ? request.getParameter("txtUserName")
                : "";
        String password = request.getParameter("txtPassWord") != null ? request.getParameter("txtPassWord")
                : "";
        String confirmPassword = request.getParameter("txtConfirmPassWord") != null
                ? request.getParameter("txtConfirmPassWord")
                : "";
        String userEmail = request.getParameter("txtUserEmail") != null ? request.getParameter("txtUserEmail")
                : "";
        String userDescription = request.getParameter("txtDescription") != null
                ? request.getParameter("txtDescription")
                : "";
        String userType = request.getParameter("radUserType") != null ? request.getParameter("radUserType")
                : "A";

        userName = userName.replace(' ', '_');

        try {//from   w  ww. j av  a  2s  . c o m
            if (!GenericValidator.matchRegexp(userName, HTTPConstants.ALPHA_REGEXP)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input for User Name");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(userName, 15)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Name");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(realName, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Real Name");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(password, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Password");
                return (new UsersAction().execute(request, response));
            }

            if (!GenericValidator.minLength(password, 8)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Password");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.matchRegexp(password, HTTPConstants.PASSWORD_PATTERN_REGEXP)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Password");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.minLength(confirmPassword, 8)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Password");
                return (new UsersAction().execute(request, response));
            }

            if (!GenericValidator.matchRegexp(confirmPassword, HTTPConstants.PASSWORD_PATTERN_REGEXP)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input for Password");
                return (new UsersAction().execute(request, response));
            }
            if (!password.equals(confirmPassword)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Password do not match");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.isEmail(userEmail)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid Email ID");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(userEmail, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for Email ID");
                return (new UsersAction().execute(request, response));
            }
            if (!GenericValidator.maxLength(userDescription, 50)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Description");
                return (new UsersAction().execute(request, response));
            }
            if (!User.USER_TYPE_ADMIN.equalsIgnoreCase(userType)) {
                userType = User.USER_TYPE_USER;
            }

            boolean userExist = UserDAO.getInstance().validateUser(userName);
            boolean emailExist = UserDAO.getInstance().validateUserEmail(userEmail);
            if (userExist) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "User with this username already exist");
                return (new UsersAction().execute(request, response));
            }
            if (emailExist) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "User with this email Id already exist");
                return (new UsersAction().execute(request, response));
            }

            User user = new User();
            user.setUserName(userName);
            user.setPassword(password);
            user.setUserDescription(userDescription);
            user.setUserEmail(userEmail);
            user.setRealName(realName);
            user.setActive(true);
            user.setUserType(userType);

            UserDAO.getInstance().addUser(user);

            user = UserDAO.getInstance().readUserByName(userName);

            PasswordHistory passwordHistory = new PasswordHistory();
            passwordHistory.setUserId(user.getUserId());
            passwordHistory.setPassword(password);
            PasswordHistoryDAO.getInstance().create(passwordHistory);

            AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER,
                    AuditLogRecord.ACTION_CREATED, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "ID :" + user.getUserId(), "Name : " + user.getUserName()));

            request.setAttribute(HTTPConstants.REQUEST_MESSAGE,
                    "User " + userName.toUpperCase() + " added successfully");
            return (new UsersAction().execute(request, response));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return (new NewUserView(request, response));
}

From source file:com.panet.imeta.job.entry.validator.JobEntryValidatorUtils.java

/**
 * Fails if a field's value does not match the given mask.
 *//*from  ww  w  . jav  a 2 s.co  m*/
public static boolean validateMask(CheckResultSourceInterface source, String propertyName, int levelOnFail,
        List<CheckResultInterface> remarks, String mask) {
    final String VALIDATOR_NAME = "matches"; //$NON-NLS-1$
    String value = null;

    value = ValidatorUtils.getValueAsString(source, propertyName);

    try {
        if (null == mask) {
            addGeneralRemark(source, propertyName, VALIDATOR_NAME, remarks, "errors.missingVar", //$NON-NLS-1$
                    CheckResultInterface.TYPE_RESULT_ERROR);
            return false;
        }

        if (StringUtils.isNotBlank(value) && !GenericValidator.matchRegexp(value, mask)) {
            addFailureRemark(source, propertyName, VALIDATOR_NAME, remarks, levelOnFail);
            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        addExceptionRemark(source, propertyName, VALIDATOR_NAME, remarks, e);
        return false;
    }
}

From source file:jp.terasoluna.fw.validation.ValidationUtil.java

/**
 * ??????????/*ww  w . j a  v a2s .  c  o m*/
 *
 * @param value 
 * @param mask ??
 * @return
 *            ????????
 *            <code>true</code>?
 *            ?????<code>false</code>?
 */
public static boolean matchRegexp(String value, String mask) {
    if (!StringUtils.isEmpty(value) && !GenericValidator.matchRegexp(value, mask)) {
        return false;
    }
    return true;
}

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  a2  s .c  om
    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.primeleaf.krystal.web.action.console.EditDocumentIndexesAction.java

public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    try {/*from w w  w .j av  a  2 s  .c o m*/
        int documentId = 0;
        try {
            documentId = Integer.parseInt(request.getParameter("documentid"));
        } catch (Exception e) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
            return (new AJAXResponseView(request, response));
        }
        //   read HTTP request parameters
        String revisionId = request.getParameter("revisionid");

        Document document = DocumentDAO.getInstance().readDocumentById(documentId);

        if (document == null) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document");
            return (new AJAXResponseView(request, response));
        }
        if (Hit.STATUS_LOCKED.equalsIgnoreCase(document.getStatus())) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Document already checkout");
            return (new AJAXResponseView(request, response));
        }
        AccessControlManager aclManager = new AccessControlManager();

        DocumentClass documentClass = DocumentClassDAO.getInstance()
                .readDocumentClassById(document.getClassId());
        ACL acl = aclManager.getACL(documentClass, loggedInUser);

        if (!acl.canWrite()) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Access Denied");
            return (new AJAXResponseView(request, response));
        }
        boolean isHeadRevision = false;
        if (document.getRevisionId().equalsIgnoreCase(revisionId)) {
            isHeadRevision = true;
        }
        if (!isHeadRevision) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Access Denied");
            aclManager = null;
            return (new AJAXResponseView(request, response));
        }
        //local variables
        String indexName = "", indexValue = "";
        String expiryDate = request.getParameter("txtExpiryDate") != null
                ? request.getParameter("txtExpiryDate")
                : "";
        Hashtable<String, String> indexRecord = new Hashtable<String, String>();

        for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
            indexName = indexDefinition.getIndexColumnName();
            indexValue = request.getParameter(indexName);
            if (indexValue != null) {
                String errorMessage = "";
                if (indexDefinition.isMandatory()) {
                    if (indexValue.trim().length() <= 0) {
                        errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName();
                        request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage);
                        return (new AJAXResponseView(request, response));
                    }
                }
                if (IndexDefinition.INDEXTYPE_NUMBER.equalsIgnoreCase(indexDefinition.getIndexType())) {
                    if (indexValue.trim().length() > 0) {
                        if (!GenericValidator.matchRegexp(indexValue, HTTPConstants.NUMERIC_REGEXP)) {
                            errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName();
                            request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage);
                            return (new AJAXResponseView(request, response));
                        }
                    }
                } else if (IndexDefinition.INDEXTYPE_DATE.equalsIgnoreCase(indexDefinition.getIndexType())) {
                    if (indexValue.trim().length() > 0) {
                        if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) {
                            errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName();
                            request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage);
                            return (new AJAXResponseView(request, response));
                        }
                    }
                }
                if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking maximum length of index field
                    errorMessage = "Document index length exceeded " + "Index Name : "
                            + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : "
                            + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : "
                            + indexValue.length() + " ]";

                    request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage);
                    return (new AJAXResponseView(request, response));
                }
            } else {
                indexValue = "";
            }
            indexRecord.put(indexName, indexValue);
        }

        IndexRecordManager.getInstance().updateIndexRecord(documentClass, documentId, revisionId, indexRecord);
        //Update document details like access count last modified etc

        Timestamp modified = new Timestamp(Calendar.getInstance().getTime().getTime());
        document.setStatus(Hit.STATUS_AVAILABLE);
        document.setModified(modified);
        document.setLastAccessed(modified);
        document.setAccessCount(document.getAccessCount() + 1);
        document.setModifiedBy(loggedInUser.getUserName());

        if (expiryDate.trim().length() > 0) {
            Timestamp expiry = new Timestamp(StringHelper.getDate(expiryDate).getTime());
            document.setExpiry(expiry);
        } else {
            document.setExpiry(null);
        }

        DocumentDAO.getInstance().updateDocument(document);

        //Log the entry to audit logs 
        String userName = loggedInUser.getUserName();
        AuditLogManager.log(new AuditLogRecord(documentId, AuditLogRecord.OBJECT_DOCUMENT,
                AuditLogRecord.ACTION_EDITED, userName, request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO,
                "Revision No :" + revisionId));

        request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Indexes updated successfully");

    } catch (Exception e) {
        e.printStackTrace();
    }
    return (new AJAXResponseView(request, response));
}

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

@Override
public void validate(Object obj, Errors errors) {
    try {/*w w  w.j  av a2  s. c o  m*/

        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:kreidos.diamond.web.action.console.NewDocumentAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    String classId = request.getParameter("classid") != null ? request.getParameter("classid") : "0";

    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {//  www .j av a2 s  . c  o  m
            String userName = loggedInUser.getUserName();
            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }

            //variables
            String fileName = "", comments = "";
            File file = null;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);

            //Create a file upload progress listener
            FileUploadProgressListener listener = new FileUploadProgressListener();
            upload.setProgressListener(listener);
            //put the listener in session
            session.setAttribute("LISTENER", listener);
            session.setAttribute("UPLOAD_ERROR", null);
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0));

            DocumentClass documentClass = null;

            Hashtable<String, String> indexRecord = new Hashtable<String, String>();
            String name = "";
            String value = "";

            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (fileItem.isFormField()) {
                    name = fileItem.getFieldName();
                    value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING);
                    if (name.equals("classid")) {
                        classId = value;
                    }
                    if (name.equals("txtNote")) {
                        comments = value;
                    }
                } else {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        file = new File(tempFilePath + fileName);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return null;
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                session.setAttribute("UPLOAD_ERROR", "Zero length document");
                return null;
            }
            documentClass = DocumentClassDAO.getInstance().readDocumentClassById(Integer.parseInt(classId));
            if (documentClass == null) {
                session.setAttribute("UPLOAD_ERROR", "Invalid document class");
                return null;
            }
            AccessControlManager aclManager = new AccessControlManager();
            ACL acl = aclManager.getACL(documentClass, loggedInUser);

            if (!acl.canCreate()) {
                session.setAttribute("UPLOAD_ERROR", "Access Denied");
                return null;
            }

            String indexValue = "";
            String indexName = "";
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(50));

            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                indexName = indexDefinition.getIndexColumnName();
                Iterator iter1 = listItems.iterator();
                while (iter1.hasNext()) {
                    FileItem item1 = (FileItem) iter1.next();
                    if (item1.isFormField()) {
                        name = item1.getFieldName();
                        value = item1.getString(HTTPConstants.CHARACTER_ENCODING);
                        if (name.equals(indexName)) {
                            indexValue = value;
                            String errorMessage = "";
                            if (indexValue != null) {
                                if (indexDefinition.isMandatory()) {
                                    if (indexValue.trim().length() <= 0) {
                                        errorMessage = "Invalid input for "
                                                + indexDefinition.getIndexDisplayName();
                                        session.setAttribute("UPLOAD_ERROR", errorMessage);
                                        return null;
                                    }
                                }
                                if (IndexDefinition.INDEXTYPE_NUMBER
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.matchRegexp(indexValue,
                                                HTTPConstants.NUMERIC_REGEXP)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                } else if (IndexDefinition.INDEXTYPE_DATE
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                }
                                if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking index field length
                                    errorMessage = "Document index size exceeded for " + "Index Name : "
                                            + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : "
                                            + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : "
                                            + indexValue.length() + " ]";
                                    session.setAttribute("UPLOAD_ERROR", errorMessage);
                                    return null;
                                }
                            }
                            indexRecord.put(indexName, indexValue);
                        }
                    }
                } //while iter
            } //while indexCfgList
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(70));

            DocumentRevision documentRevision = new DocumentRevision();
            documentRevision.setClassId(documentClass.getClassId());
            documentRevision.setDocumentId(0);
            documentRevision.setRevisionId("1.0");
            documentRevision.setDocumentFile(file);
            documentRevision.setUserName(loggedInUser.getUserName());
            documentRevision.setIndexRecord(indexRecord);
            documentRevision.setComments(comments);

            DocumentManager documentManager = new DocumentManager();
            documentManager.storeDocument(documentRevision, documentClass);

            //Log the entry to audit logs 
            AuditLogManager.log(new AuditLogRecord(documentRevision.getDocumentId(),
                    AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CREATED, userName,
                    request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Document created"));

            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(100));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return null;
    } else {
        try {
            ArrayList<DocumentClass> availableDocumentClasses = DocumentClassDAO.getInstance()
                    .readDocumentClasses(" ACTIVE = 'Y'");
            ArrayList<DocumentClass> documentClasses = new ArrayList<DocumentClass>();
            AccessControlManager aclManager = new AccessControlManager();
            for (DocumentClass documentClass : availableDocumentClasses) {
                ACL acl = aclManager.getACL(documentClass, loggedInUser);
                if (acl.canCreate()) {
                    documentClasses.add(documentClass);
                }
            }
            int documentClassId = 0;
            try {
                documentClassId = Integer.parseInt(classId);
            } catch (Exception ex) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                return (new NewDocumentView(request, response));
            }
            if (documentClassId > 0) {
                DocumentClass selectedDocumentClass = DocumentClassDAO.getInstance()
                        .readDocumentClassById(documentClassId);
                request.setAttribute("DOCUMENTCLASS", selectedDocumentClass);
            }
            request.setAttribute("CLASSID", documentClassId);
            request.setAttribute("CLASSLIST", documentClasses);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return (new NewDocumentView(request, response));
}