List of usage examples for org.apache.commons.validator.routines EmailValidator getInstance
public static EmailValidator getInstance()
From source file:org.sakaiproject.contentreview.urkund.UrkundReviewServiceImpl.java
/** * Is this a valid email the service will recognize * * @param email/* ww w .j a v a 2 s . c om*/ * @return */ private boolean isValidEmail(String email) { if (email == null || email.equals("")) { return false; } email = email.trim(); //must contain @ if (!email.contains("@")) { return false; } //an email can't contain spaces if (email.indexOf(" ") > 0) { return false; } //use commons-validator EmailValidator validator = EmailValidator.getInstance(); return validator.isValid(email); }
From source file:org.sakaiproject.site.tool.SiteAction.java
/** * %%% legacy properties, to be removed/*from w w w .j av a2 s . c om*/ */ private void updateSiteInfo(ParameterParser params, SessionState state) { SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE); // title boolean hasRosterAttached = params.getString("hasRosterAttached") != null ? Boolean.getBoolean(params.getString("hasRosterAttached")) : false; if ((siteTitleEditable(state, siteInfo.site_type) || !hasRosterAttached) && params.getString("title") != null) { // site titel is editable and could not be null String title = StringUtils.trimToNull(params.getString("title")); siteInfo.title = title; if (title == null) { addAlert(state, rb.getString("java.specify") + " "); } // check for site title length else if (title.length() > SiteConstants.SITE_GROUP_TITLE_LIMIT) { addAlert(state, rb.getFormattedMessage("site_group_title_length_limit", new Object[] { SiteConstants.SITE_GROUP_TITLE_LIMIT })); } } if (params.getString("description") != null) { StringBuilder alertMsg = new StringBuilder(); String description = params.getString("description"); siteInfo.description = FormattedText.processFormattedText(description, alertMsg); } if (params.getString("short_description") != null) { siteInfo.short_description = params.getString("short_description"); } String skin = params.getString("skin"); if (skin != null) { // if there is a skin input for course site skin = StringUtils.trimToNull(skin); siteInfo.iconUrl = skin; } else { // if ther is a icon input for non-course site String icon = StringUtils.trimToNull(params.getString("icon")); if (icon != null) { if (icon.endsWith(PROTOCOL_STRING)) { addAlert(state, rb.getString("alert.protocol")); } siteInfo.iconUrl = icon; } else { siteInfo.iconUrl = ""; } } if (params.getString("additional") != null) { siteInfo.additional = params.getString("additional"); } if (params.getString("iconUrl") != null) { siteInfo.iconUrl = params.getString("iconUrl"); } else if (params.getString("skin") != null) { siteInfo.iconUrl = params.getString("skin"); } if (params.getString("joinerRole") != null) { siteInfo.joinerRole = params.getString("joinerRole"); } if (params.getString("joinable") != null) { boolean joinable = params.getBoolean("joinable"); siteInfo.joinable = joinable; if (!joinable) siteInfo.joinerRole = NULL_STRING; } if (params.getString("itemStatus") != null) { siteInfo.published = Boolean.valueOf(params.getString("itemStatus")).booleanValue(); } // bjones86 - SAK-24423 - update site info for joinable site settings JoinableSiteSettings.updateSiteInfoFromParams(params, siteInfo); // site contact information String name = StringUtils.trimToEmpty(params.getString("siteContactName")); if (name.length() == 0) { addAlert(state, rb.getString("alert.sitediinf.sitconnam")); } siteInfo.site_contact_name = name; String email = StringUtils.trimToEmpty(params.getString("siteContactEmail")); if (email != null) { if (!email.isEmpty() && !EmailValidator.getInstance().isValid(email)) { // invalid email addAlert(state, rb.getFormattedMessage("java.invalid.email", new Object[] { FormattedText.escapeHtml(email, false) })); } siteInfo.site_contact_email = email; } int aliasCount = params.getInt("alias_count", 0); siteInfo.siteRefAliases.clear(); for (int j = 0; j < aliasCount; j++) { String alias = StringUtils.trimToNull(params.getString("alias_" + j)); if (alias == null) { continue; } // Kernel will force these to lower case anyway. Forcing // to lower case whenever reading out of the form simplifies // comparisons at save time, though, and provides consistent // on-screen display. alias = alias.toLowerCase(); // An invalid alias will set an alert, which theoretically // disallows further progress in the workflow, but we // still need to re-render the invalid form contents. // Thus siteInfo.aliases contains all input aliases, even if // invalid. (Same thing happens above for email.) validateSiteAlias(alias, state); siteInfo.siteRefAliases.add(alias); } state.setAttribute(STATE_SITE_INFO, siteInfo); }
From source file:org.sakaiproject.user.tool.UsersAction.java
/** * Read the user form and update the user in state. * /* w w w .j a v a 2 s.co m*/ * @return true if the form is accepted, false if there's a validation error (an alertMessage will be set) */ private boolean readUserForm(RunData data, SessionState state) { // boolean parameters and values // --------------Mode----singleUser-createUser-typeEnable // Admin New-----new-----false------false------true // Admin Update--edit----false------false------true // Admin Delete--remove--false------false------false // Gateway New---null----false------true-------false // Account Edit--edit----true-------false------false // read the form String id = StringUtils.trimToNull(data.getParameters().getString("id")); String eid = StringUtils.trimToNull(data.getParameters().getString("eid")); state.setAttribute("valueEid", eid); String firstName = StringUtils.trimToNull(data.getParameters().getString("first-name")); state.setAttribute("valueFirstName", firstName); String lastName = StringUtils.trimToNull(data.getParameters().getString("last-name")); state.setAttribute("valueLastName", lastName); String email = StringUtils.trimToNull(data.getParameters().getString("email")); state.setAttribute("valueEmail", email); String pw = StringUtils.trimToNull(data.getParameters().getString("pw")); String pwConfirm = StringUtils.trimToNull(data.getParameters().getString("pw0")); String pwcur = StringUtils.trimToNull(data.getParameters().getString("pwcur")); Integer disabled = Integer .valueOf(StringUtils.trimToNull(data.getParameters().getString("disabled")) != null ? "1" : "0"); String mode = (String) state.getAttribute("mode"); boolean singleUser = ((Boolean) state.getAttribute("single-user")).booleanValue(); boolean createUser = ((Boolean) state.getAttribute("create-user")).booleanValue(); // SAK-29182 - enforce invalid domains when creating a user through Gateway -> New Account boolean isEidEditable = isEidEditable(state); if (createUser && !isEidEditable) { for (String domain : getInvalidEmailDomains()) { if (email.toLowerCase().endsWith(domain.toLowerCase())) { String defaultMsg = rb.getFormattedMessage("email.invalid.domain", new Object[] { domain }); String customMsg = ServerConfigurationService .getString(SAK_PROP_INVALID_EMAIL_DOMAINS_CUSTOM_MESSAGE, ""); if (!customMsg.isEmpty()) { String institution = ServerConfigurationService.getString("ui.institution", ""); customMsg = new MessageFormat(customMsg, rb.getLocale()) .format(new Object[] { institution, domain }, new StringBuffer(), null).toString(); } addAlert(state, customMsg.isEmpty() ? defaultMsg : customMsg); return false; } } } boolean typeEnable = false; String type = null; if ((mode != null) && (mode.equalsIgnoreCase("new"))) { typeEnable = true; } else if ((mode != null) && (mode.equalsIgnoreCase("edit")) && (!singleUser)) { typeEnable = true; } if (typeEnable) { // for the case of Admin User tool creating new user type = StringUtils.trimToNull(data.getParameters().getString("type")); state.setAttribute("valueType", type); } else { if (createUser) { // for the case of Gateway Account tool creating new user type = (String) state.getAttribute("create-type"); } } if ((Boolean) state.getAttribute("user.recaptcha-enabled")) { String challengeField = data.getParameters().getString("recaptcha_challenge_field"); String responseField = data.getParameters().getString("recaptcha_response_field"); if (challengeField == null) challengeField = ""; if (responseField == null) responseField = ""; ReCaptcha captcha = ReCaptchaFactory.newReCaptcha( (String) state.getAttribute("user.recaptcha-public-key"), (String) state.getAttribute("user.recaptcha-private-key"), false); ReCaptchaResponse response = captcha.checkAnswer(data.getRequest().getRemoteAddr(), challengeField, responseField); if (!response.isValid()) { addAlert(state, rb.getString("useact.capterr")); state.setAttribute("recaptcha-error", response.getErrorMessage()); return false; } } //Ensure valid email address. Empty emails are invalid iff email validation is required. For non-empty email Strings, use EmailValidator. //email.matches(".+@.+\\..+") boolean validateWithAccountValidator = isValidatedWithAccountValidator(state); boolean emailInvalid = StringUtils.isEmpty(email) ? validateWithAccountValidator : !EmailValidator.getInstance().isValid(email); if (emailInvalid) { addAlert(state, rb.getString("useact.invemail")); return false; } // get the user UserEdit user = (UserEdit) state.getAttribute("user"); //process any additional attributes //we continue processing these until we get an empty attribute KEY //counter starts at 1 //data is of the form: // optionalAttr_1:att1 // optionalAttrValue_1:value1 // optionalAttr_2:att2 // optionalAttrValue_2:value2 int count = 1; boolean continueProcessingOptionalAttributes = true; ResourcePropertiesEdit properties; if (user == null) { properties = new BaseResourcePropertiesEdit(); } else { properties = user.getPropertiesEdit(); } //remove all properties that are in the confugred list //then add back in only the ones that were sent //this allows us to remove items via javascript and they get persisted to the db on form save Map<String, String> configuredProperties = getOptionalAttributes(); for (String cp : configuredProperties.keySet()) { properties.removeProperty(cp); } while (continueProcessingOptionalAttributes) { //this stores the key String optionalAttributeKey = data.getParameters().getString("optionalAttr_" + count); if (StringUtils.isBlank(optionalAttributeKey)) { continueProcessingOptionalAttributes = false; break; } String optionalAttributeValue = data.getParameters().getString("optionalAttrValue_" + count); //only single values properties //any null ones will wipe out existing ones //and any duplicate ones will override previous ones (currently) properties.addProperty(optionalAttributeKey, optionalAttributeValue); //System.out.println("optionalAttributeKey: " + optionalAttributeKey + ", optionalAttributeValue: " + optionalAttributeValue); count++; } // add if needed if (user == null) { // make sure we have eid if (isEidEditable) { if (eid == null) { addAlert(state, rb.getString("usecre.eidmis")); return false; } } else { // eid is not editable, so we're using the email as the eid if (email == null) { addAlert(state, rb.getString("useact.invemail")); return false; } eid = email; } // if we validate through email, passwords will be handled in AccountValidator TempUser tempUser = new TempUser(eid, null, null, null, eid, pw, null); if (!validateWithAccountValidator) { // if in create mode, make sure we have a password if (createUser) { if (pw == null) { addAlert(state, rb.getString("usecre.pasismis")); return false; } } // make sure we have matching password fields if (StringUtil.different(pw, pwConfirm)) { addAlert(state, rb.getString("usecre.pass")); return false; } // SAK-23568 - make sure password meets policy requirements if (!validatePassword(pw, tempUser, state)) { return false; } } //Check if the email is duplicated boolean allowEmailDuplicates = ServerConfigurationService.getBoolean("user.email.allowduplicates", true); if (!allowEmailDuplicates && UserDirectoryService.checkDuplicatedEmail(tempUser)) { addAlert(state, rb.getString("useact.theuseemail1")); return false; } try { // add the user in one step so that all you need is add not update permission // (the added might be "anon", and anon has add but not update permission) //SAK-18209 only an admin user should be able to specify a ID if (!SecurityService.isSuperUser()) { id = null; } User newUser; if (validateWithAccountValidator) { // the eid is their email address. The password is random newUser = UserDirectoryService.addUser(id, eid, firstName, lastName, email, PasswordCheck.generatePassword(), type, properties); // Invoke AccountValidator to send an email to the user containing a link to a form on which they can set their name and password ValidationLogic validationLogic = (ValidationLogic) ComponentManager.get(ValidationLogic.class); validationLogic.createValidationAccount(newUser.getId(), ValidationAccount.ACCOUNT_STATUS_REQUEST_ACCOUNT); } else { newUser = UserDirectoryService.addUser(id, eid, firstName, lastName, email, pw, type, properties); if (SecurityService.isSuperUser()) { if (disabled == 1) { try { UserEdit editUser = UserDirectoryService.editUser(newUser.getId()); editUser.getProperties().addProperty("disabled", "true"); newUser = editUser; } catch (UserNotDefinedException e) { addAlert(state, rb.getString("usecre.disableFailed")); return false; } catch (UserLockedException e) { addAlert(state, rb.getString("usecre.disableFailed")); return false; } } } } // put the user in the state state.setAttribute("newuser", newUser); } catch (UserAlreadyDefinedException e) { addAlert(state, rb.getString("useact.theuseid1")); return false; } catch (UserIdInvalidException e) { addAlert(state, rb.getString("useact.theuseid2")); return false; } catch (UserPermissionException e) { addAlert(state, rb.getString("useact.youdonot3")); return false; } } // update else { if (!user.isActiveEdit()) { try { // add the user in one step so that all you need is add not update permission // (the added might be "anon", and anon has add but not update permission) user = UserDirectoryService.editUser(user.getId()); // put the user in the state state.setAttribute("user", user); } catch (UserLockedException e) { addAlert(state, rb.getString("useact.somels")); return false; } catch (UserNotDefinedException e) { Object[] params = new Object[] { id }; addAlert(state, rb.getFormattedMessage("useact.use_notfou", params)); return false; } catch (UserPermissionException e) { addAlert(state, rb.getString("useact.youdonot3")); return false; } } // Still needs super user to change super user password // If the current user isn't a super user but is trying to change the password or email of a super user print an error if (!SecurityService.isSuperUser() && SecurityService.isSuperUser(user.getId())) { addAlert(state, rb.getString("useact.youdonot4")); return false; } // eid, pw, type might not be editable if (eid != null) user.setEid(eid); user.setFirstName(firstName); user.setLastName(lastName); user.setEmail(email); if (type != null) user.setType(type); //add in the updated props user.getPropertiesEdit().addAll(properties); if (SecurityService.isSuperUser()) { if (disabled == 1) { user.getProperties().addProperty("disabled", "true"); } else { user.getProperties().removeProperty("disabled"); } } //validate the password only for local users if (!isProvidedType(user.getType())) { // make sure the old password matches, but don't check for super users if (!SecurityService.isSuperUser()) { if (!user.checkPassword(pwcur)) { addAlert(state, rb.getString("usecre.curpass")); return false; } } if (mode == null || !mode.equalsIgnoreCase("remove")) { // make sure we have matching password fields if (StringUtil.different(pw, pwConfirm)) { addAlert(state, rb.getString("usecre.pass")); return false; } // SAK-23568 - make sure password meets policy requirements if (!validatePassword(pw, user, state)) { return false; } if (pw != null) user.setPassword(pw); } } } return true; }
From source file:org.schedoscope.metascope.controller.MetascopeUserController.java
@RequestMapping(value = "/admin/user/create", method = RequestMethod.POST) public ModelAndView createUser(HttpServletRequest request, String username, String email, String fullname, String password, boolean admin, String group) { ModelAndView mav = new ModelAndView("body/admin/user/index"); if (email != null && !EmailValidator.getInstance().isValid(email)) { return mav.addObject("invalidEmail", true).addObject("service", metascopeUserService); }/*from ww w . j ava 2s . c o m*/ if (metascopeUserService.userExists(username)) { return mav.addObject("userExists", true).addObject("service", metascopeUserService); } else if (metascopeUserService.emailExists(email)) { return mav.addObject("emailExists", true).addObject("service", metascopeUserService); } this.metascopeUserService.createUser(username, email, fullname, password, admin, group); return new ModelAndView(new RedirectView(request.getHeader("Referer"))); }
From source file:org.schedoscope.metascope.controller.UserEntityController.java
@RequestMapping(value = "/admin/user/create", method = RequestMethod.POST) public ModelAndView createUser(HttpServletRequest request, String username, String email, String fullname, String password, boolean admin, String group) { ModelAndView mav = createView("index"); if (email != null && !EmailValidator.getInstance().isValid(email)) { return mav.addObject("invalidEmail", true).addObject("service", userEntityService); }/*from w w w . j av a 2 s.com*/ if (userEntityService.userExists(username)) { return mav.addObject("userExists", true).addObject("service", userEntityService); } else if (userEntityService.emailExists(email)) { return mav.addObject("emailExists", true).addObject("service", userEntityService); } this.userEntityService.createUser(username, email, fullname, password, admin, group); return new ModelAndView(new RedirectView(request.getHeader("Referer"))); }
From source file:org.shadowmask.core.discovery.rules.EmailRule.java
@Override public boolean evaluate() { if (value == null) { throw new DataDiscoveryException("Should fill the column value before fire inspect rules."); }/*from ww w. j a va2s . c o m*/ EmailValidator emailValidator = EmailValidator.getInstance(); return emailValidator.isValid(value); /*int locationOfAt = value.indexOf('@'); // there is only one '@' in the value and not in the beginning if (locationOfAt > 0 && locationOfAt == value.lastIndexOf('@')) { int locationOfDot = value.lastIndexOf('.'); // there is a '.' after '@' if (locationOfDot > locationOfAt) { return true; } } return false;*/ }
From source file:org.teknux.dropbitz.controller.UploadController.java
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_HTML }) @Authenticated/*from w w w . j av a 2 s . c o m*/ public Response uploadFile(@FormDataParam("file") final InputStream inputStream, @FormDataParam("file") final FormDataContentDisposition formDataContentDisposition, @FormDataParam("name") final String name, @FormDataParam("email") final String email, @FormDataParam("fallback") final Boolean fallback) { String fileName = null; try { fileName = new String(formDataContentDisposition.getFileName().getBytes(CHARSET_ISO_8859_1), CHARSET_UTF8); } catch (UnsupportedEncodingException e) { logger.warn("Can not translate file name charset", e); fileName = formDataContentDisposition.getFileName(); } ; logger.trace("Checking email"); if (!email.isEmpty()) { //validate email if (!EmailValidator.getInstance().isValid(email)) { return getResponse(fallback, Status.INTERNAL_SERVER_ERROR, fileName, i18n(I18nKey.DROP_FILE_EMAIL_ERROR)); } } String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(DATE_FORMAT)); String destFileName = date + (name.isEmpty() ? "" : "-" + name) + "-" + fileName; try { if (formDataContentDisposition.getFileName().isEmpty()) { return getResponse(fallback, Status.BAD_REQUEST, fileName, i18n(I18nKey.DROP_FILE_MISSING)); } Configuration config = getServiceManager().getService(IConfigurationService.class).getConfiguration(); java.nio.file.Path outputPath = FileSystems.getDefault() .getPath(config.getDirectory().getAbsolutePath(), destFileName); //Checks destination directory if (!FileUtil.isChildOfDirectory(outputPath.toFile(), config.getDirectory())) { return getResponse(fallback, Status.FORBIDDEN, fileName, i18n(I18nKey.DROP_FILE_MISSING)); } Files.copy(inputStream, outputPath); long fileSize = outputPath.toFile().length(); sendEmail(true, name, fileName, destFileName, fileSize, email); } catch (IOException e) { logger.error("Can not copy file", e); sendEmail(false, name, fileName, null, 0L, email); return getResponse(fallback, Status.INTERNAL_SERVER_ERROR, fileName, i18n(I18nKey.DROP_FILE_ERROR)); } return getResponse(fallback, Status.OK, fileName, null); }
From source file:org.waveprotocol.box.server.persistence.mongodb.MongoDbStore.java
@Override public List<AccountData> getAccountByEmail(String email) throws PersistenceException { if (email == null) { return null; }/*from w w w . j a v a 2s. co m*/ Preconditions.checkArgument(EmailValidator.getInstance().isValid(email)); DBObject query = new BasicDBObject(); query.put(ACCOUNT_HUMAN_DATA_FIELD + "." + EMAIL_FIELD, email); DBCursor result = getAccountCollection().find(query); ArrayList<AccountData> accounts = new ArrayList<AccountData>(); for (DBObject r : result) { accounts.add(accountFromQueryResult(r, null)); } return accounts; }
From source file:piecework.validation.ValidationRule.java
private void evaluateEmail(Map<String, List<Value>> submissionData) throws ValidationRuleException { List<? extends Value> values = safeValues(name, submissionData); for (Value value : values) { if (value != null && StringUtils.isNotEmpty(value.getValue()) && !EmailValidator.getInstance().isValid(value.getValue())) throw new ValidationRuleException(this, "Must be a valid email address"); }/*from ww w .j a v a 2 s .c o m*/ }
From source file:pt.ist.applications.admissions.ui.ApplicationsAdmissionsController.java
@RequestMapping(value = "/contest/{contest}/registerCandidate", method = RequestMethod.POST) public String registerCandidateSave(@PathVariable Contest contest, final Model model, @RequestBody final String stuff, HttpServletRequest request) { final Map<String, String> map = Utils.toMap(stuff, "name", "value"); model.addAttribute("contest", toJsonObject(contest)); if (Authenticate.getUser() == null) { Form form = new Form(); form.param("secret", ApplicationsAdmissionsConfiguration.getConfiguration().recaptchaSecretKey()); form.param("response", map.get("g-recaptcha-response")); WebTarget target = CLIENT.target("https://www.google.com/recaptcha/api/siteverify"); String post = target.request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); JsonObject jo = new JsonParser().parse(post).getAsJsonObject(); if (!jo.get("success").getAsBoolean()) { throw new Error(jo.get("error-codes").getAsString()); }/* w ww .j a v a 2 s .c om*/ } Candidate candidate = null; final String email = map.get("email"); if (EmailValidator.getInstance().isValid(email)) { String path = request.getRequestURL().substring(0, request.getRequestURL().length() - request.getRequestURI().length() + request.getContextPath().length()); candidate = contest.registerCandidate(map.get("name"), email, path, messageSource); } return candidate == null ? "redirect:/admissions/contest/" + contest.getExternalId() : "redirect:/admissions/candidate/" + candidate.getExternalId(); }