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.jd.survey.web.security.AccountController.java

/**
 * Updates  logged in user password//from   www . j  a  v  a2s  .  c  o m
 * @param oldPassword
 * @param newPassword
 * @param newPasswordConfirm
 * @param proceed
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/rpass", method = RequestMethod.POST, produces = "text/html")
public String updatePasswordPost(@RequestParam(value = "password", required = true) String oldPassword,
        @RequestParam(value = "nPassword", required = true) String newPassword,
        @RequestParam(value = "cPassword", required = true) String newPasswordConfirm,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {
        if (proceed != null) {

            //check that the old password is correct
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    principal.getName(), oldPassword);
            authenticationToken.setDetails(new WebAuthenticationDetails(httpServletRequest));
            try {
                Authentication auth = authenticationManager.authenticate(authenticationToken);
                if (auth == null || !auth.isAuthenticated()) {
                    //invalid password enetered
                    uiModel.asMap().clear();
                    uiModel.addAttribute("status", "E"); //Unmatching Passwords
                    return "account/rpass";
                }

            } catch (AuthenticationException e) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "E"); //Unmatching Passwords
                return "account/rpass";
            }
            //Check new password strenght 
            if (!GenericValidator.matchRegexp(newPassword, globalSettings.getPasswordEnforcementRegex())) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "I"); //Unmatching Passwords
                return "account/rpass";
            }
            //check that passwords match    
            if (!newPassword.equals(newPasswordConfirm)) {
                uiModel.asMap().clear();

                uiModel.addAttribute("status", "U"); //Unmatching Passwords
                return "account/rpass";
            }
            User loggedInUser = userService.user_findByLogin(principal.getName());
            //All validations passed, save the HASH of the password in the database
            loggedInUser.setPassword(newPassword);
            userService.user_updatePassword(loggedInUser);
            uiModel.addAttribute("status", "S");//success
            return "account/rpass";
        } else {
            return "redirect:/account/show";
        }

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

From source file:com.primeleaf.krystal.web.action.console.CheckInDocumentAction.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    try {//ww  w.  jav a2 s. c o  m
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            String errorMessage;
            String tempFilePath = System.getProperty("java.io.tmpdir");

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

            String revisionId = "", comments = "", fileName = "", ext = "", version = "";
            int documentId = 0;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest((HttpServletRequest) request);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);
            //Create a file upload progress listener

            Iterator iter = items.iterator();
            FileItem item = null;
            File file = null;
            while (iter.hasNext()) {
                item = (FileItem) iter.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString(HTTPConstants.CHARACTER_ENCODING);
                    if (name.equals("documentid")) {
                        try {
                            documentId = Integer.parseInt(value);
                        } catch (Exception ex) {
                            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                            return (new CheckInDocumentView(request, response));
                        }
                    } else if (name.equals("revisionid")) {
                        revisionId = value;
                    } else if (name.equals("txtNote")) {
                        comments = value;
                    } else if ("version".equalsIgnoreCase(name)) {
                        version = value;
                    }
                } else {
                    fileName = item.getName();
                    ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                    file = new File(tempFilePath + "." + ext);
                    item.write(file);
                }
            }
            iter = null;

            Document document = DocumentDAO.getInstance().readDocumentById(documentId);
            if (document == null) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document");
                return (new CheckInDocumentView(request, response));
            }
            if (document.getStatus().equalsIgnoreCase(Hit.STATUS_AVAILABLE)) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid check-in");
                return (new CheckInDocumentView(request, response));
            }
            revisionId = document.getRevisionId();
            DocumentClass documentClass = DocumentClassDAO.getInstance()
                    .readDocumentClassById(document.getClassId());
            AccessControlManager aclManager = new AccessControlManager();
            ACL acl = aclManager.getACL(documentClass, loggedInUser);
            if (!acl.canCheckin()) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Access Denied");
                return (new CheckInDocumentView(request, response));
            }

            if (file.length() <= 0) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document");
                return (new CheckInDocumentView(request, response));
            }
            if (file.length() > documentClass.getMaximumFileSize()) { //code for checking maximum size of document in a class
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Document size exceeded");
                return (new CheckInDocumentView(request, response));
            }

            String indexValue = "";
            String indexName = "";

            Hashtable indexRecord = new Hashtable();
            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                indexName = indexDefinition.getIndexColumnName();
                Iterator itemsIterator = items.iterator();
                while (itemsIterator.hasNext()) {
                    FileItem fileItem = (FileItem) itemsIterator.next();
                    if (fileItem.isFormField()) {
                        String name = fileItem.getFieldName();
                        String value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING);
                        if (name.equals(indexName)) {
                            indexValue = value;
                            if (indexValue != null) {
                                if (indexDefinition.isMandatory()) {
                                    if (indexValue.trim().length() <= 0) {
                                        errorMessage = "Invalid input for "
                                                + indexDefinition.getIndexDisplayName();
                                        request.setAttribute(HTTPConstants.REQUEST_ERROR, errorMessage);
                                        return (new CheckInDocumentView(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 CheckInDocumentView(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 CheckInDocumentView(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 CheckInDocumentView(request, response));
                                }
                            }
                            indexRecord.put(indexName, indexValue);
                        }
                    }
                    fileItem = null;
                } // while iter
                itemsIterator = null;
            } // while indexDefinitionItr

            CheckedOutDocument checkedOutDocument = new CheckedOutDocument();
            checkedOutDocument.setDocumentId(documentId);
            // Added by Viral Visaria. For the Version Control minor and major.
            // In minor revision increment by 0.1. (No Changes required for the minor revision its handled in the core logic) 
            // In major revision increment by 1.0  (Below chages are incremented by 0.9 and rest 0.1 will be added in the core logic. (0.9 + 0.1 = 1.0)
            double rev = Double.parseDouble(revisionId);
            if ("major".equals(version)) {
                rev = Math.floor(rev);
                rev = rev + 0.9;
                revisionId = String.valueOf(rev);
            }
            checkedOutDocument.setRevisionId(revisionId);
            checkedOutDocument.setUserName(loggedInUser.getUserName());
            RevisionManager revisionManager = new RevisionManager();
            revisionManager.checkIn(checkedOutDocument, documentClass, indexRecord, file, comments, ext,
                    loggedInUser.getUserName());

            //revision id incremented by 0.1 for making entry in audit log 
            rev += 0.1;
            revisionId = String.valueOf(rev);
            //add to audit log 
            AuditLogManager.log(new AuditLogRecord(documentId, AuditLogRecord.OBJECT_DOCUMENT,
                    AuditLogRecord.ACTION_CHECKIN, loggedInUser.getUserName(), request.getRemoteAddr(),
                    AuditLogRecord.LEVEL_INFO, "Document ID :  " + documentId + " Revision ID :" + revisionId,
                    "Checked In"));
            request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Document checked in successfully");
            return (new CheckInDocumentView(request, response));
        }
        int documentId = 0;
        try {
            documentId = Integer.parseInt(
                    request.getParameter("documentid") != null ? request.getParameter("documentid") : "0");
        } catch (Exception e) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
            return (new CheckInDocumentView(request, response));
        }
        Document document = DocumentDAO.getInstance().readDocumentById(documentId);
        if (document == null) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid document");
            return (new CheckInDocumentView(request, response));
        }
        if (!Hit.STATUS_LOCKED.equalsIgnoreCase(document.getStatus())) {
            request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid checkin");
            return (new CheckInDocumentView(request, response));
        }
        DocumentClass documentClass = DocumentClassDAO.getInstance()
                .readDocumentClassById(document.getClassId());
        LinkedHashMap<String, String> documentIndexes = IndexRecordManager.getInstance()
                .readIndexRecord(documentClass, documentId, document.getRevisionId());

        request.setAttribute("DOCUMENTCLASS", documentClass);
        request.setAttribute("DOCUMENT", document);
        request.setAttribute("DOCUMENTINDEXES", documentIndexes);

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

From source file:com.primeleaf.krystal.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 {/*from w w  w.  j  av a  2s  .c om*/
            String userName = loggedInUser.getUserName();
            String sessionid = (String) session.getId();

            String tempFilePath = System.getProperty("java.io.tmpdir");

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

            //variables
            String fileName = "", ext = "", 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();
                        ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        file = new File(tempFilePath + "." + ext);
                        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;
            }

            long usedStorage = DocumentDAO.getInstance().documentSize();
            long availableStorage = ServerConstants.MAX_STORAGE - usedStorage;

            if (file.length() > availableStorage) {
                session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0));
                session.setAttribute("UPLOAD_ERROR", "Document upload failed. Storage limit exceeded.");
                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));
}

From source file:de.knurt.fam.core.persistence.dao.ibatis.UserDao4ibatis.java

/** {@inheritDoc} */
@Override//  w  w  w . ja v  a 2  s . c o  m
public List<User> getUsersWithRealName(String firstname, String sirname) throws InvalidParameterException {
    String regexp = "^[^=><'\"]+$";
    if (GenericValidator.matchRegexp(firstname, regexp) && GenericValidator.matchRegexp(sirname, regexp)) {
        String where = String.format("fname = \"%s\" AND sname = \"%s\"", firstname, sirname);
        return this.getWhere(where);
    } else {
        throw new InvalidParameterException(firstname + "; " + sirname + " is not a real name");
    }
}

From source file:de.knurt.fam.core.persistence.dao.ibatis.UserDao4ibatis.java

/**
 * {@inheritDoc} username must be only lower case with numbers.
 *///from  ww w .j a v  a 2s. c om
@Override
public User getUserFromUsername(String username) {
    User result = null;
    if (!GenericValidator.isBlankOrNull(username)) {
        username = username.trim();
        String regexp = "^[a-z0-9]+$";
        if (GenericValidator.matchRegexp(username, regexp)) {
            List<User> users = this.getWhere(String.format("username = '%s'", username));
            if (users != null && users.size() == 1) {
                result = users.get(0);
            } else if (users.size() > 1) {
                FamLog.error(String.format("found %s users with username %s", users.size(), username),
                        201205091021l);
            } else {
                FamLog.info("no user found with username " + username, 201205091338l);
            }
        }
    }
    return result;
}

From source file:com.jd.survey.web.security.LoginController.java

@RequestMapping(method = RequestMethod.POST, value = "/rpass", produces = "text/html")
public String forgotPasswordPost(@RequestParam(value = "password", required = true) String password,
        @RequestParam(value = "cpassword", required = true) String cpassword,
        @RequestParam(value = "key", required = true) String key,
        @RequestParam(value = "_proceed", required = false) String proceed, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {//from   ww  w  . jav  a2 s  .c o  m
        if (proceed != null) {
            //validate the passed key
            if (!userService.user_validateForgotPasswordKey(key)) {
                log.warn("Attempt to reset password with invalid key, Not successful");
                uiModel.addAttribute("status", "E"); //Error
                throw (new RuntimeException("Attempt to reset password with invalid key, Not successful"));
            }

            //check that passwords match    
            if (!password.equals(cpassword)) {
                uiModel.asMap().clear();
                uiModel.addAttribute("key", key);
                uiModel.addAttribute("status", "U"); //Unmatching Passwords
                return "public/rpass";
            }

            GlobalSettings globalSettings = applicationSettingsService.getSettings();

            //Check new password strength 
            if (!GenericValidator.matchRegexp(password, globalSettings.getPasswordEnforcementRegex())) {
                uiModel.asMap().clear();
                uiModel.addAttribute("key", key);
                uiModel.addAttribute("status", "I"); //Unmatching Passwords
                uiModel.addAttribute("passwordPolicyMsg", globalSettings.getPasswordEnforcementMessage());
                return "public/rpass";
            }

            //All validations passed, save the HASH of the password in the database
            PasswordResetRequest passwordResetRequest = userService.passwordResetRequest_findByHash(key);
            User user = userService.user_findByLogin(passwordResetRequest.getLogin());
            user.setPassword(password);
            userService.user_updatePassword(user, passwordResetRequest);
            uiModel.addAttribute("status", "S");//success
            return "public/rpass";
        } else {
            //cancel button
            return "public/login";
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

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

/**
 * ???????????//  w w  w.  j a v  a2  s .  c  o m
 *
 * <p>???????????true??
 * ???
 *
 * <h5>validation.xml?</h5>
 * <code><pre>
 * &lt;form name=&quot;sample&quot;&gt;
 *  
 *  &lt;field property=&quot;maskField&quot;
 *      depends=&quot;mask&quot;&gt;
 *    &lt;arg key=&quot;sample.escape&quot; position="0"/&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;mask&lt;/var-name&gt;
 *      &lt;var-value&gt;^([0-9]|[a-z]|[A-Z])*$&lt;/var-value&gt;
 *    &lt;/var&gt;
 *  &lt;/field&gt;
 *  
 * &lt;/form&gt;
 * </pre></code>
 *
 * <h5>validation.xml???&lt;var&gt;?</h5>
 * <table border="1">
 *  <tr>
 *   <td><center><b><code>var-name</code></b></center></td>
 *   <td><center><b><code>var-value</code></b></center></td>
 *   <td><center><b></b></center></td>
 *   <td><center><b>?</b></center></td>
 *  </tr>
 *  <tr>
 *   <td> mask </td>
 *   <td>??</td>
 *   <td>true</td>
 *   <td>???????????? <code>true</code>
 *       ????????ValidatorException
 *       ??</td>
 *  </tr>
 * </table>
 *
 * @param bean ?JavaBean
 * @param va ?<code>ValidatorAction</code>
 * @param field ?<code>Field</code>
 * @param errors ?????
 * ??
 * @return ??????<code>true</code>?
 * ????<code>false</code>?
 * @exception ValidatorException ?mask(??)??
 * ?????????
 */
public boolean validateMask(Object bean, ValidatorAction va, Field field, ValidationErrors errors)
        throws ValidatorException {
    // 
    String value = extractValue(bean, field);
    if (StringUtils.isEmpty(value)) {
        return true;
    }

    // ??
    String mask = field.getVarValue("mask");

    // var?mask?????????ValidatorException
    if (StringUtils.isEmpty(mask)) {
        log.error("var[mask] must be specified.");
        throw new ValidatorException("var[mask] must be specified.");
    }

    // 
    if (!GenericValidator.matchRegexp(value, mask)) {
        rejectValue(errors, field, va, bean);
        return false;
    }
    return true;
}

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;/*from ww w  .  ja  va  2 s.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  v a2s . c  o 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);

        }

    }

}

From source file:org.apache.archiva.admin.repository.DefaultRepositoryCommonValidator.java

/**
 * @param abstractRepository/*from ww  w .j  a  va  2  s .  c  o  m*/
 * @param update             in update mode if yes already exists won't be check
 * @throws RepositoryAdminException
 */
@Override
public void basicValidation(AbstractRepository abstractRepository, boolean update)
        throws RepositoryAdminException {
    Configuration config = archivaConfiguration.getConfiguration();

    String repoId = abstractRepository.getId();

    if (!update) {

        if (config.getManagedRepositoriesAsMap().containsKey(repoId)) {
            throw new RepositoryAdminException("Unable to add new repository with id [" + repoId
                    + "], that id already exists as a managed repository.");
        } else if (config.getRepositoryGroupsAsMap().containsKey(repoId)) {
            throw new RepositoryAdminException("Unable to add new repository with id [" + repoId
                    + "], that id already exists as a repository group.");
        } else if (config.getRemoteRepositoriesAsMap().containsKey(repoId)) {
            throw new RepositoryAdminException("Unable to add new repository with id [" + repoId
                    + "], that id already exists as a remote repository.");
        }
    }

    if (StringUtils.isBlank(repoId)) {
        throw new RepositoryAdminException("Repository ID cannot be empty.");
    }

    if (!GenericValidator.matchRegexp(repoId, REPOSITORY_ID_VALID_EXPRESSION)) {
        throw new RepositoryAdminException(
                "Invalid repository ID. Identifier must only contain alphanumeric characters, underscores(_), dots(.), and dashes(-).");
    }

    String name = abstractRepository.getName();

    if (StringUtils.isBlank(name)) {
        throw new RepositoryAdminException("repository name cannot be empty");
    }

    if (!GenericValidator.matchRegexp(name, REPOSITORY_NAME_VALID_EXPRESSION)) {
        throw new RepositoryAdminException(
                "Invalid repository name. Repository Name must only contain alphanumeric characters, white-spaces(' '), "
                        + "forward-slashes(/), open-parenthesis('('), close-parenthesis(')'),  underscores(_), dots(.), and dashes(-).");
    }

}