List of usage examples for org.apache.commons.validator GenericValidator isEmail
public static boolean isEmail(String value)
Checks if a field has a valid e-mail address.
From source file:com.primeleaf.krystal.web.action.cpanel.EditUserAction.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")) { short userId = 0; try {//from ww w. j av a2 s.co m userId = Short .parseShort(request.getParameter("userid") != null ? request.getParameter("userid") : "0"); } catch (Exception e) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new UsersAction().execute(request, response)); } UserDAO.getInstance().setReadCompleteObject(true); User user = UserDAO.getInstance().readUserById(userId); if (user == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid User"); return (new UsersAction().execute(request, response)); } String userName = request.getParameter("txtUserName") != null ? request.getParameter("txtUserName") : ""; String realName = request.getParameter("txtRealName") != null ? request.getParameter("txtRealName") : ""; String userEmail = request.getParameter("txtUserEmail") != null ? request.getParameter("txtUserEmail") : ""; String userDescription = request.getParameter("txtDescription") != null ? request.getParameter("txtDescription") : ""; String active = request.getParameter("radActive") != null ? request.getParameter("radActive") : "Y"; String userType = request.getParameter("radUserType") != null ? request.getParameter("radUserType") : "A"; 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.isEmail(userEmail)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new UsersAction().execute(request, response)); } if (!GenericValidator.maxLength(userEmail, 50)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Value too large for User Email"); 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 (!"Y".equalsIgnoreCase(active)) { active = "N"; } if (!User.USER_TYPE_ADMIN.equalsIgnoreCase(userType)) { userType = User.USER_TYPE_USER; } //check if new email address is different then existing one if (!user.getUserEmail().equalsIgnoreCase(userEmail)) { //it is different so validate if (UserDAO.getInstance().validateUserEmail(userEmail)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "User with " + userEmail + " already exist"); return (new UsersAction().execute(request, response)); } } if (user.getUserName().equalsIgnoreCase(ServerConstants.SYSTEM_ADMIN_USER)) { active = "Y"; //Administrator user can never be in activated. userType = User.USER_TYPE_ADMIN; } try { user.setUserId(userId); user.setRealName(realName); user.setUserName(userName); user.setUserDescription(userDescription); user.setUserEmail(userEmail); if ("Y".equalsIgnoreCase(active)) { user.setActive(true); } else { user.setActive(false); } user.setUserType(userType); UserDAO.getInstance().updateUser(user, false); AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER, AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "ID :" + user.getUserId(), "Name : " + user.getUserName())); request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "User " + userName.toUpperCase() + " updated successfully"); return (new UsersAction().execute(request, response)); } catch (Exception e) { e.printStackTrace(); } } else { int userId = 0; try { userId = Integer .parseInt(request.getParameter("userid") != null ? request.getParameter("userid") : "0"); } catch (Exception e) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new UsersAction().execute(request, response)); } UserDAO.getInstance().setReadCompleteObject(true); User user = UserDAO.getInstance().readUserById(userId); UserDAO.getInstance().setReadCompleteObject(false); if (user == null) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid User"); return (new UsersAction().execute(request, response)); } request.setAttribute("USER", user); } return (new EditUserView(request, response)); }
From source file:gov.nih.nci.cabig.caaers.service.ScheduledNotificationProcessService.java
/** * This method will process and sends notifications associated to a * scheduled notification. /*from w ww . j a va 2s.co m*/ * * - Will find the recipients, and their email addresses. * - Will generate the subject/body of email * - Will send notification * - Will update notification status. * * @param reportId - A valid {@link Report#id} * @param scheduledNotificationId - A valid {@link ScheduledNotification#id} */ @Transactional public void process(Integer reportId, Integer scheduledNotificationId) { Report report = reportDao.getById(reportId); ScheduledEmailNotification scheduledNotification = (ScheduledEmailNotification) report .fetchScheduledNotification(scheduledNotificationId); DeliveryStatus newDeliveryStatus = DeliveryStatus.RECALLED; if (report.isActive()) { newDeliveryStatus = DeliveryStatus.DELIVERED; PlannedEmailNotification plannedNotification = (PlannedEmailNotification) scheduledNotification .getPlanedNotificaiton(); ExpeditedAdverseEventReport aeReport = report.getAeReport(); StudySite studySite = aeReport.getStudySite(); Study study = aeReport.getStudy(); Set<String> emailAddresses = new HashSet<String>(); //find emails of direct recipients List<ContactMechanismBasedRecipient> contactRecipients = plannedNotification .getContactMechanismBasedRecipients(); if (CollectionUtils.isNotEmpty(contactRecipients)) { for (ContactMechanismBasedRecipient recipient : contactRecipients) { String contact = recipient.getContact(); if (GenericValidator.isEmail(contact)) emailAddresses.add(contact); } } //find emails of role recipients List<RoleBasedRecipient> roleRecipients = plannedNotification.getRoleBasedRecipients(); if (CollectionUtils.isNotEmpty(roleRecipients)) { List<String> emails = null; for (RoleBasedRecipient recipient : roleRecipients) { if (ArrayUtils.contains(RoleUtils.reportSpecificRoles, recipient.getRoleName())) { emails = report.findEmailAddressByRole(recipient.getRoleName()); } else if (ArrayUtils.contains(RoleUtils.sponsorAndCoordinatingCenterSpecificRoles, recipient.getRoleName())) { emails = study.getStudyCoordinatingCenter().findEmailAddressByRole(recipient.getRoleName()); emails.addAll(study.getStudyFundingSponsors().get(0) .findEmailAddressByRole(recipient.getRoleName())); } else if (ArrayUtils.contains(RoleUtils.studySiteSpecificRoles, recipient.getRoleName())) { emails = studySite.findEmailAddressByRole(recipient.getRoleName()); } else { emails = study.findEmailAddressByRole(recipient.getRoleName()); } //now add the valid email addresses obtained if (CollectionUtils.isNotEmpty(emails)) { for (String email : emails) { if (GenericValidator.isEmail(email)) emailAddresses.add(email); } } } } if (CollectionUtils.isNotEmpty(emailAddresses)) { //now process the notifications. String rawSubjectLine = plannedNotification.getSubjectLine(); String rawBody = plannedNotification.getNotificationBodyContent().getBody(); Map<Object, Object> contextVariableMap = report.getContextVariables(); //change the reportURL String reportURL = String.valueOf(contextVariableMap.get("reportURL")); contextVariableMap.put("reportURL", configuration.get(Configuration.CAAERS_BASE_URL) + reportURL); //apply the replacements. String subjectLine = freeMarkerService.applyRuntimeReplacementsForReport(rawSubjectLine, contextVariableMap); String body = freeMarkerService.applyRuntimeReplacementsForReport(rawBody, contextVariableMap); //create the message SimpleMailMessage mailMsg = new SimpleMailMessage(); mailMsg.setSentDate(scheduledNotification.getScheduledOn()); mailMsg.setSubject(subjectLine); mailMsg.setText(body); //send email to each recipient for (String email : emailAddresses) { mailMsg.setTo(email); try { caaersJavaMailSender.send(mailMsg); } catch (Exception e) { //no need to throw and rollback logger.warn("Error while emailing to [" + email + "]", e); } } } } scheduledNotificationDao.updateDeliveryStatus(scheduledNotification, scheduledNotification.getDeliveryStatus(), newDeliveryStatus); }
From source file:com.modelmetrics.cloudconverter.importxls.services.FileServiceImpl.java
/** * Parses an XLS file into a WrapperBean * /*from w w w . j ava2 s .c o m*/ * @param file * @return WrapperBean * @throws ParseException */ @SuppressWarnings("unchecked") public List<ExcelWorksheetWrapperBean> parseXLS(File file) throws ParseException { // keeps date fields real. TimeZone.setDefault(TimeZone.getTimeZone("-0")); List<ExcelWorksheetWrapperBean> wrapperBeans = new ArrayList<ExcelWorksheetWrapperBean>(); try { Workbook workbook; workbook = Workbook.getWorkbook(file); Sheet[] sheets = workbook.getSheets(); for (Sheet sheet : sheets) { ExcelWorksheetWrapperBean bean = new ExcelWorksheetWrapperBean(); bean.setSheetName(StringUtils.applyConstraints(sheet.getName())); int totalRows = sheet.getRows(); for (int i = 0; i < totalRows; i++) { Cell[] cells = sheet.getRow(i); List<Object> list = new ArrayList<Object>(); for (int j = 0; j < cells.length; j++) { Cell c = cells[j]; // log.debug("cell format is: (i,j) (" + i + ", " + j + // "): // " + c.getCellFormat().getFormat().getFormatString()); String value = c.getContents(); if (i == 0) { // parse column names bean.getNames().add(StringUtils.applyConstraints(value)); bean.getLabels().add(value); } if (i == 1) { // parse data types CellType type = c.getType(); if (type.equals(CellType.DATE) || type.equals(CellType.DATE_FORMULA)) { if (value.contains(":")) { bean.getTypes().add(Constants.DATETIME); } else { bean.getTypes().add(Constants.DATE); } } else if (type.equals(CellType.BOOLEAN) || type.equals(CellType.BOOLEAN_FORMULA)) { bean.getTypes().add(Constants.CHECKBOX); } else if (type.equals(CellType.LABEL) || type.equals(CellType.STRING_FORMULA)) { if (GenericValidator.isEmail(value)) { bean.getTypes().add(Constants.EMAIL); } else if (StringUtils.isPhoneNumber(value)) { bean.getTypes().add(Constants.PHONE_NUMBER); } else if (StringUtils.isURL(value)) { bean.getTypes().add(Constants.URL); } else { bean.getTypes().add(Constants.TEXT); } } else if (type.equals(CellType.NUMBER) || type.equals(CellType.NUMBER_FORMULA)) { log.debug("Number: " + value + " : format : " + c.getCellFormat().getFormat().getFormatString()); if (value.contains("%")) { bean.getTypes().add(Constants.PERCENTAGE); } else if (value.contains("$")) { bean.getTypes().add(Constants.CURRENCY); } else if (value.contains(",") || value.contains(".")) { bean.getTypes().add(Constants.DOUBLE); } else { bean.getTypes().add(Constants.INT); } } else { // default. bean.getTypes().add(Constants.TEXT); } } if (i >= 1) { // parse data values CellType type = c.getType(); if (type.equals(CellType.BOOLEAN) || type.equals(CellType.BOOLEAN_FORMULA)) { list.add(((BooleanCell) c).getValue()); } else if (type.equals(CellType.DATE) || type.equals(CellType.DATE_FORMULA)) { Date aux = ((DateCell) c).getDate(); list.add(aux); // } } else if (type.equals(CellType.LABEL) || type.equals(CellType.STRING_FORMULA)) { list.add(value); } else if (type.equals(CellType.EMPTY)) { list.add(null); } else if (type.equals(CellType.NUMBER) || type.equals(CellType.NUMBER_FORMULA)) { if (value.contains("%")) { // otherwise "percentages" show up in SFDC // as // 0.78 when it should be 78%. list.add(((NumberCell) c).getValue() * 100); } else { list.add(((NumberCell) c).getValue()); } } if (i == 1) { bean.getExamples().add(value); } } } if (i >= 1) { /* * RSC 2009-06-02 Check to be sure there is data in a list */ boolean notEmpty = false; for (Object o : list) { if (o != null && o.toString().trim().length() != 0) { notEmpty = true; break; } } if (!notEmpty) { throw new RuntimeException( "Found an empty row. Your spreadsheet should not contain an empty row. Check sheet " + sheet.getName() + ", row " + (i + 1) + "."); } bean.getData().add(list); bean.setOverride(Boolean.FALSE); } } wrapperBeans.add(bean); } } catch (BiffException e) { throw new ParseException("Could not read file"); } catch (IOException e) { throw new ParseException("Input/Output error"); } catch (IndexOutOfBoundsException e) { throw new ParseException("Columns and data do not match"); } catch (NullPointerException e) { throw new ParseException("A reference in the file has a null value"); } return wrapperBeans; }
From source file:com.modelmetrics.cloudconverter.importxls.services.ExcelFileParserServiceImpl.java
/** * Parses an XLS file into a WrapperBean * /*from ww w . ja v a2s. c o m*/ * @param file * @return WrapperBean * @throws ParseException */ @SuppressWarnings("unchecked") public List<ExcelWorksheetWrapperBean> parseXLS(File file) throws ParseException { //TODO DB -- validate that dates are working with TZ and SFDC properly. Use sample input v1 // keeps date fields real. TimeZone.setDefault(TimeZone.getTimeZone("-0")); List<ExcelWorksheetWrapperBean> wrapperBeans = new ArrayList<ExcelWorksheetWrapperBean>(); try { Workbook workbook; workbook = Workbook.getWorkbook(file); Sheet[] sheets = workbook.getSheets(); for (Sheet sheet : sheets) { ExcelWorksheetWrapperBean bean = new ExcelWorksheetWrapperBean(); bean.setSheetName(StringUtils.applyConstraints(sheet.getName())); int totalRows = sheet.getRows(); for (int i = 0; i < totalRows; i++) { Cell[] cells = sheet.getRow(i); List<Object> list = new ArrayList<Object>(); for (int j = 0; j < cells.length; j++) { Cell c = cells[j]; // log.debug("cell format is: (i,j) (" + i + ", " + j + // "): // " + c.getCellFormat().getFormat().getFormatString()); String value = c.getContents(); if (i == 0) { // parse column names bean.getNames().add(StringUtils.applyConstraints(value)); bean.getLabels().add(value); } if (i == 1) { // parse data types CellType type = c.getType(); if (type.equals(CellType.DATE) || type.equals(CellType.DATE_FORMULA)) { if (value.contains(":")) { bean.getTypes().add(Constants.DATETIME); } else { bean.getTypes().add(Constants.DATE); } } else if (type.equals(CellType.BOOLEAN) || type.equals(CellType.BOOLEAN_FORMULA)) { bean.getTypes().add(Constants.CHECKBOX); } else if (type.equals(CellType.LABEL) || type.equals(CellType.STRING_FORMULA)) { if (GenericValidator.isEmail(value)) { bean.getTypes().add(Constants.EMAIL); } else if (StringUtils.isPhoneNumber(value)) { bean.getTypes().add(Constants.PHONE_NUMBER); } else if (StringUtils.isURL(value)) { bean.getTypes().add(Constants.URL); } else { bean.getTypes().add(Constants.TEXT); } } else if (type.equals(CellType.NUMBER) || type.equals(CellType.NUMBER_FORMULA)) { log.debug("Number: " + value + " : format : " + c.getCellFormat().getFormat().getFormatString()); if (value.contains("%")) { bean.getTypes().add(Constants.PERCENTAGE); } else if (value.contains("$")) { bean.getTypes().add(Constants.CURRENCY); } else if (value.contains(",") || value.contains(".")) { bean.getTypes().add(Constants.DOUBLE); } else { bean.getTypes().add(Constants.INT); } } else { // default. bean.getTypes().add(Constants.TEXT); } } if (i >= 1) { // parse data values CellType type = c.getType(); if (type.equals(CellType.BOOLEAN) || type.equals(CellType.BOOLEAN_FORMULA)) { list.add(((BooleanCell) c).getValue()); } else if (type.equals(CellType.DATE) || type.equals(CellType.DATE_FORMULA)) { Date aux = ((DateCell) c).getDate(); list.add(aux); // } } else if (type.equals(CellType.LABEL) || type.equals(CellType.STRING_FORMULA)) { list.add(value); } else if (type.equals(CellType.EMPTY)) { list.add(null); } else if (type.equals(CellType.NUMBER) || type.equals(CellType.NUMBER_FORMULA)) { if (value.contains("%")) { // otherwise "percentages" show up in SFDC // as // 0.78 when it should be 78%. list.add(((NumberCell) c).getValue() * 100); } else { list.add(((NumberCell) c).getValue()); } } if (i == 1) { bean.getExamples().add(value); } } } //TODO DB make sure this is working for worksheets that have no row with DATA (Think Erin's email) if (i >= 1) { /* * RSC 2009-06-02 Check to be sure there is data in a list */ boolean notEmpty = false; for (Object o : list) { if (o != null && o.toString().trim().length() != 0) { notEmpty = true; break; } } if (!notEmpty) { throw new RuntimeException( "Found an empty row. Your spreadsheet should not contain an empty row. Check sheet " + sheet.getName() + ", row " + (i + 1) + "."); } bean.getData().add(list); bean.setOverride(Boolean.FALSE); } } wrapperBeans.add(bean); } } catch (BiffException e) { throw new ParseException("Could not read file"); } catch (IOException e) { throw new ParseException("Input/Output error"); } catch (IndexOutOfBoundsException e) { throw new ParseException("Columns and data do not match"); } catch (NullPointerException e) { throw new ParseException("A reference in the file has a null value"); } return wrapperBeans; }
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 w w . j a v a2 s. co 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.aoindustries.website.clientarea.ticket.TicketForm.java
@Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = super.validate(mapping, request); if (errors == null) errors = new ActionErrors(); // contactEmails must be valid email addresses if (getContactEmails().length() > 0) { for (String email : StringUtility.splitLines(getContactEmails())) { if (!GenericValidator.isEmail(email)) { errors.add("contactEmails", new ActionMessage("TicketForm.field.contactEmails.invalid")); break; }//from w w w .java 2 s. co m } } // annotationSummary required with either summary or details provided if (getAnnotationDetails().length() > 0 && getAnnotationSummary().length() == 0) { errors.add("annotationSummary", new ActionMessage("TicketForm.field.annotationSummary.required")); } return errors; }
From source file:edu.northwestern.bioinformatics.studycalendar.web.admin.AdministerUserCommand.java
public void validate(Errors errors) { if (StringUtils.isBlank(getUser().getCsmUser().getLoginName())) { errors.rejectValue("user.csmUser.loginName", "error.user.name.not.specified"); } else {/* w w w . j a va 2 s. c o m*/ User existing = authorizationManager.getUser(getUser().getCsmUser().getLoginName()); boolean existingMismatch = existing != null && !existing.getUserId().equals(getUser().getCsmUser().getUserId()); if (!lookUpBoundUser && ((isNewUser() && existing != null) || existingMismatch)) { errors.rejectValue("user.csmUser.loginName", "error.user.name.already.exists"); } } if (StringUtils.isBlank(getUser().getCsmUser().getFirstName())) { errors.rejectValue("user.csmUser.firstName", "error.user.firstName.not.specified"); } if (StringUtils.isBlank(getUser().getCsmUser().getLastName())) { errors.rejectValue("user.csmUser.lastName", "error.user.lastName.not.specified"); } if (!GenericValidator.isEmail(getUser().getCsmUser().getEmailId())) { errors.rejectValue("user.csmUser.emailId", "error.user.email.invalid"); } if (isNewUser() && getUsesLocalPasswords() && (StringUtils.isBlank(getPassword()))) { errors.rejectValue("password", "error.user.password.not.specified"); } if (getPassword() != null || getRePassword() != null) { if (!ComparisonUtils.nullSafeEquals(getPassword(), getRePassword())) { errors.rejectValue("rePassword", "error.user.repassword.does.not.match.password"); } } }
From source file:com.aoindustries.website.signup.SignupBillingInformationForm.java
@Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = super.validate(mapping, request); if (errors == null) errors = new ActionErrors(); if (GenericValidator.isBlankOrNull(billingContact)) errors.add("billingContact", new ActionMessage("signupBillingInformationForm.billingContact.required")); if (GenericValidator.isBlankOrNull(billingEmail)) { errors.add("billingEmail", new ActionMessage("signupBillingInformationForm.billingEmail.required")); } else if (!GenericValidator.isEmail(billingEmail)) { errors.add("billingEmail", new ActionMessage("signupBillingInformationForm.billingEmail.invalid")); }/*from w ww.j a v a2s .com*/ if (GenericValidator.isBlankOrNull(billingCardholderName)) errors.add("billingCardholderName", new ActionMessage("signupBillingInformationForm.billingCardholderName.required")); if (GenericValidator.isBlankOrNull(billingCardNumber)) { errors.add("billingCardNumber", new ActionMessage("signupBillingInformationForm.billingCardNumber.required")); } else if (!GenericValidator.isCreditCard(CreditCard.numbersOnly(billingCardNumber))) { errors.add("billingCardNumber", new ActionMessage("signupBillingInformationForm.billingCardNumber.invalid")); } if (GenericValidator.isBlankOrNull(billingExpirationMonth) || GenericValidator.isBlankOrNull(billingExpirationYear)) errors.add("billingExpirationDate", new ActionMessage("signupBillingInformationForm.billingExpirationDate.required")); if (GenericValidator.isBlankOrNull(billingStreetAddress)) errors.add("billingStreetAddress", new ActionMessage("signupBillingInformationForm.billingStreetAddress.required")); if (GenericValidator.isBlankOrNull(billingCity)) errors.add("billingCity", new ActionMessage("signupBillingInformationForm.billingCity.required")); if (GenericValidator.isBlankOrNull(billingState)) errors.add("billingState", new ActionMessage("signupBillingInformationForm.billingState.required")); if (GenericValidator.isBlankOrNull(billingZip)) errors.add("billingZip", new ActionMessage("signupBillingInformationForm.billingZip.required")); return errors; }
From source file:com.aoindustries.website.signup.SignupTechnicalForm.java
@Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = super.validate(mapping, request); if (errors == null) errors = new ActionErrors(); try {/*from w ww . j av a2 s . com*/ if (GenericValidator.isBlankOrNull(baName)) errors.add("baName", new ActionMessage("signupTechnicalForm.baName.required")); if (GenericValidator.isBlankOrNull(baWorkPhone)) errors.add("baWorkPhone", new ActionMessage("signupTechnicalForm.baWorkPhone.required")); if (GenericValidator.isBlankOrNull(baEmail)) { errors.add("baEmail", new ActionMessage("signupTechnicalForm.baEmail.required")); } else if (!GenericValidator.isEmail(baEmail)) { errors.add("baEmail", new ActionMessage("signupTechnicalForm.baEmail.invalid")); } if (GenericValidator.isBlankOrNull(baUsername)) errors.add("baUsername", new ActionMessage("signupTechnicalForm.baUsername.required")); else { ActionServlet myServlet = getServlet(); if (myServlet != null) { AOServConnector rootConn = SiteSettings.getInstance(myServlet.getServletContext()) .getRootAOServConnector(); String lowerUsername = baUsername.toLowerCase(); ValidationResult check = UserId.validate(lowerUsername); if (!check.isValid()) { errors.add("baUsername", new ActionMessage(check.toString(), false)); } else { UserId userId; try { userId = UserId.valueOf(lowerUsername); } catch (ValidationException e) { AssertionError ae = new AssertionError("Already validated"); ae.initCause(e); throw ae; } if (!rootConn.getUsernames().isUsernameAvailable(userId)) errors.add("baUsername", new ActionMessage("signupTechnicalForm.baUsername.unavailable")); } } } return errors; } catch (IOException err) { throw new WrappedException(err); } catch (SQLException err) { throw new WrappedException(err); } }
From source file:gov.nih.nci.cabig.caaers.web.admin.UserTab.java
private void createNewPersonValidation(final UserCommand command, final BeanWrapper commandBean, final Map<String, InputFieldGroup> fieldGroups, final Errors errors) { String em = command.getEmailAddress(); Person person = personRepository.getByEmailAddress(em); if (person != null) errors.rejectValue("emailAddress", "USR_010"); if (StringUtils.isNotEmpty(command.getNciIdentifier())) { person = personRepository.getByPersonIdentifier(command.getNciIdentifier()); if (person != null) errors.rejectValue("nciIdentifier", "USR_018"); }//w w w . ja v a 2 s . c o m List<SitePerson> sitePersonnel = command.getSitePersonnel(); if (CollectionUtils.isEmpty(sitePersonnel)) { errors.reject("USR_005", "Provide at least one organization"); } for (int i = 0; i < sitePersonnel.size(); i++) { if ((sitePersonnel.get(i).getOrganization() == null || sitePersonnel.get(i).getOrganization().getId() == null)) { errors.reject("USR_004", new Object[] { new Integer(i) }, "Provide the organization"); } String email = sitePersonnel.get(i).getEmailAddress(); if (email != null && !email.trim().equals("") && !GenericValidator.isEmail(email)) { errors.rejectValue(String.format("sitePersonnel[%d].emailAddress", i), "USR_006", "Invalid email"); } } }