org.apache.commons.validator.routines.DateValidator Java Examples

The following examples show how to use org.apache.commons.validator.routines.DateValidator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SurveyPage.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
private String computeMvelExpressionForDateAnswerQuestion(QuestionAnswer questionAnswer , LogicalCondition condition, String groupingOperator,String dateFormat){
 StringBuilder stringBuilder  = new StringBuilder();
 if (condition.getDateMin() != null && condition.getDateMax() != null) {
  stringBuilder.append("(");
  
   
  
  stringBuilder.append("page.questionAnswers[" + (questionAnswer.getOrder() - 1) +"].dateAnswerValue >=" + "org.apache.commons.validator.routines.DateValidator.getInstance().validate('" + DateValidator.getInstance().format(condition.getDateMin(), dateFormat) +"','" + dateFormat +  "')"); 
  stringBuilder.append(" && ");
  stringBuilder.append("page.questionAnswers[" + (questionAnswer.getOrder() - 1) +"].dateAnswerValue <=" + "org.apache.commons.validator.routines.DateValidator.getInstance().validate('" + DateValidator.getInstance().format(condition.getDateMax(), dateFormat) +"','" + dateFormat +  "')");
  stringBuilder.append(")");
  stringBuilder.append(groupingOperator);
  return stringBuilder.toString(); 
 }	
 if (condition.getDateMin() != null) {
  stringBuilder.append("(");
  stringBuilder.append("page.questionAnswers[" + (questionAnswer.getOrder() - 1) +"].dateAnswerValue >=" + "org.apache.commons.validator.routines.DateValidator.getInstance().validate('" + DateValidator.getInstance().format(condition.getDateMin(), dateFormat) +"','" + dateFormat +  "')");
  stringBuilder.append(")");
  stringBuilder.append(groupingOperator);
  return stringBuilder.toString();
 }
 if (condition.getDateMax() != null) {
  stringBuilder.append("(");
  stringBuilder.append("page.questionAnswers[" + (questionAnswer.getOrder() - 1) +"].dateAnswerValue <=" + "org.apache.commons.validator.routines.DateValidator.getInstance().validate('" + DateValidator.getInstance().format(condition.getDateMax(), dateFormat) +"','" + dateFormat +  "')");
  stringBuilder.append(")");
  stringBuilder.append(groupingOperator);
  return stringBuilder.toString();
 }
 return "";
}
 
Example #2
Source File: StatisticsPdf.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeEntry(Document document,String label , Date value, String dateFormat) throws Exception{
	Paragraph questionParagraph = new Paragraph();
	questionParagraph.setLeading(14, 0);
	questionParagraph.setIndentationLeft(18);
	questionParagraph.add(new Chunk(label.trim() + ": ",boldedFont)); 
    questionParagraph.add(new Chunk(DateValidator.getInstance().format(value ,dateFormat) , normalFont));  
	document.add(questionParagraph);
}
 
Example #3
Source File: HIPAAMatcherAttributeValue.java    From arx with Apache License 2.0 5 votes vote down vote up
/**
 * @param value Cell content
 * @return True if input is a date
 */
private boolean isDate(String value) {
    DateValidator validator = DateValidator.getInstance();
    for (String format : DataType.DATE.getDescription().getExampleFormats()) {
        if (validator.isValid(value, format)) {
            return true;
        }
    }
    return false;
}
 
Example #4
Source File: ComOptimizationScheduleForm.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

	
	String method = mapping.getParameter() ; // struts-config.xml <action ... parameter ="method">
	String action =	request.getParameter(method);
	
	if("showSchedule".equals(action)) {
		return super.validate(mapping, request);
	}
	
	ActionErrors errors = new ActionErrors();

	DateValidator dateValidator = DateValidator.getInstance();

	if (!dateValidator.isValid(resultSendDateAsString, DATE_PATTERN_FULL)) {
		errors.add( ActionMessages.GLOBAL_MESSAGE,  new ActionMessage("mailing.autooptimization.errors.resultsenddate" , Constants.DATE_PATTERN_FULL));
	}

	if (!dateValidator.isValid(testMailingsSendDateAsString, DATE_PATTERN_FULL)) {
		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("mailing.autooptimization.errors.resultsenddate" ,Constants.DATE_PATTERN_FULL));
	}

	if (!errors.isEmpty()) { // something is wrong with the supplied 'dates' , it doesn't make sense to parse dates from them.
		return errors;
	}

	Date testmailingsSenddate = null;
	Date resultSenddate = null;
	try {
		testmailingsSenddate = DateUtil.parseFullDate(testMailingsSendDateAsString);
		resultSenddate = DateUtil.parseFullDate(resultSendDateAsString);
	} catch (ParseException e) {
		logger.error("Error occured: " + e.getMessage(), e);
	}
		
	Date now = new Date();

	if (resultSenddate == null) {
		throw new RuntimeException("resultSenddate was null");
	}
	
	if (!resultSenddate.after(testmailingsSenddate)) {
		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"mailing.autooptimization.errors.result_is_not_after_test"));
	}

	if (now.after(resultSenddate)) {
		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"mailing.autooptimization.errors.resultsenddate_is_not_in_future"));
	}

	if (now.after(testmailingsSenddate)) {
		errors
				.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"mailing.autooptimization.errors.testmailingssenddate_is_not_infuture"));
	}
	return errors;
}
 
Example #5
Source File: AtlasClassificationType.java    From atlas with Apache License 2.0 4 votes vote down vote up
private boolean validateTimeBoundry(TimeBoundary timeBoundary, List<String> messages) {
    boolean        ret           = true;
    DateValidator  dateValidator = DateValidator.getInstance();
    Date           startDate     = null;
    Date           endDate       = null;
    final TimeZone timezone;

    if (StringUtils.isNotEmpty(timeBoundary.getTimeZone())) {
        if (!isValidTimeZone(timeBoundary.getTimeZone())) {
            addValidationMessageIfNotPresent(new AtlasBaseException(AtlasErrorCode.INVALID_TIMEBOUNDRY_TIMEZONE, timeBoundary.getTimeZone()), messages);

            ret = false;
        }

        timezone = TimeZone.getTimeZone(timeBoundary.getTimeZone());
    } else {
        timezone = TimeZone.getDefault();
    }

    if (StringUtils.isNotEmpty(timeBoundary.getStartTime())) {
        startDate = dateValidator.validate(timeBoundary.getStartTime(), TimeBoundary.TIME_FORMAT, timezone);

        if (startDate == null) {
            addValidationMessageIfNotPresent(new AtlasBaseException(AtlasErrorCode.INVALID_TIMEBOUNDRY_START_TIME, timeBoundary.getStartTime()), messages);

            ret = false;
        }
    }

    if (StringUtils.isNotEmpty(timeBoundary.getEndTime())) {
        endDate = dateValidator.validate(timeBoundary.getEndTime(), TimeBoundary.TIME_FORMAT, timezone);

        if (endDate == null) {
            addValidationMessageIfNotPresent(new AtlasBaseException(AtlasErrorCode.INVALID_TIMEBOUNDRY_END_TIME, timeBoundary.getEndTime()), messages);

            ret = false;
        }
    }

    if (startDate != null && endDate != null) {
        if (endDate.before(startDate)) {
            addValidationMessageIfNotPresent(new AtlasBaseException(AtlasErrorCode.INVALID_TIMEBOUNDRY_DATERANGE, timeBoundary.getStartTime(), timeBoundary.getEndTime()), messages);

            ret = false;
        }
    }

    return ret;
}
 
Example #6
Source File: DateRule.java    From data-binding-validator with Apache License 2.0 4 votes vote down vote up
public DateRule(TextView view, String value, String errorMessage) {
    super(view, value, errorMessage);
    dateValidator = new DateValidator();
}
 
Example #7
Source File: LoginController.java    From JDeSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST, value = "/", params = "fpass", produces = "text/html")
public String forgotPasswordPost(@RequestParam(value = "login", required = true) String login,
								@RequestParam(value = "dob", required = true) String dob,
		  						@RequestParam(value = "_proceed", required = false) String proceed,
		  						Model uiModel,HttpServletRequest httpServletRequest) {
	try {
		if(proceed != null){
			String resetPasswordLink;
			String dateFormat = messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale());
			
			//Validate date and login entries (sanitize) 
			if (login == null || login.isEmpty() || login.length() > 100 || 
				dob	 == null || dob.isEmpty() || 
				!GenericValidator.isDate(dob,dateFormat, true)) {
				uiModel.addAttribute("status", "I");
				return "public/fpass";
			}
			
			//Check if provided DOB and login match
			if (!userService.user_validateDateofBirthAndLogin(login,DateValidator.getInstance().validate(dob))) {
				uiModel.addAttribute("status", "I");
				return "public/fpass";
			}
			
			User user  = userService.user_findByLogin(login);
			if (httpServletRequest.getRequestURI().contains("external")) {
				//resetPasswordLink =messageSource.getMessage(EXTERNAL_SITE_BASE_URL, null, LocaleContextHolder.getLocale());
				resetPasswordLink = externalBaseUrl;
			} 
			else {
				//resetPasswordLink =messageSource.getMessage(INTERNAL_SITE_BASE_URL, null, LocaleContextHolder.getLocale());
				resetPasswordLink = internalBaseUrl;
			}
			if (resetPasswordLink.endsWith("/")) {resetPasswordLink = resetPasswordLink +"public/rpass?key=";}	else {resetPasswordLink = resetPasswordLink +"/public/rpass?key=";}
				
		
			
			StringWriter sw = new StringWriter();
			Map model = new HashMap();
			model.put(messageSource.getMessage(RESET_PASSWORD_LINK_PARAMETER_NAME, null, LocaleContextHolder.getLocale()).replace("${", "").replace("}", ""), 
					  "<a href='"+ resetPasswordLink + userService.user_prepareForgotPasswordMessage(user.getId())+ "'>" + 
					   messageSource.getMessage(RESET_PASSWORD_LINK_LABEL, null, LocaleContextHolder.getLocale()) +"</a>");
			VelocityContext velocityContext = new VelocityContext(model);
			Velocity.evaluate(velocityContext, sw, "velocity-log" , 
							  surveySettingsService.velocityTemplate_findById(FORGOT_PASSWORD_VELOCITY_EMAIL_TEMPLATE_ID).getDefinition());
			
			mailService.sendEmail(user.getEmail(), 
								messageSource.getMessage(FORGOT_PASSWORD_EMAIL_TITLE, null, LocaleContextHolder.getLocale()),
								sw.toString());
			uiModel.addAttribute("status", "S");
			return "public/fpass";
		}
		else { //cancel button
			return "public/login";	
		}
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}	
}
 
Example #8
Source File: GenericValidator.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * <p>Checks if the field is a valid date.  The <code>Locale</code> is
 * used with <code>java.text.DateFormat</code>.  The setLenient method
 * is set to <code>false</code> for all.</p>
 *
 * @param value The value validation is being performed on.
 * @param locale The locale to use for the date format, defaults to the
 * system default if null.
 * @return true if the value can be converted to a Date.
 */
public static boolean isDate(String value, Locale locale) {
    return DateValidator.getInstance().isValid(value, locale);
}
 
Example #9
Source File: GenericValidator.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * <p>Checks if the field is a valid date.  The pattern is used with
 * <code>java.text.SimpleDateFormat</code>.  If strict is true, then the
 * length will be checked so '2/12/1999' will not pass validation with
 * the format 'MM/dd/yyyy' because the month isn't two digits.
 * The setLenient method is set to <code>false</code> for all.</p>
 *
 * @param value The value validation is being performed on.
 * @param datePattern The pattern passed to <code>SimpleDateFormat</code>.
 * @param strict Whether or not to have an exact match of the datePattern.
 * @return true if the value can be converted to a Date.
 */
public static boolean isDate(String value, String datePattern, boolean strict) {
    // TODO method isValid() not yet supported in routines version
    return org.apache.commons.validator.DateValidator.getInstance().isValid(value, datePattern, strict);
}
 
Example #10
Source File: ValidationUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Validates whether a date string is valid for the given Locale.
 *
 * @param date   the date string.
 * @param locale the Locale
 * @return true if the date string is valid, false otherwise.
 */
public static boolean dateIsValid( String date, Locale locale )
{
    return DateValidator.getInstance().isValid( date, locale );
}