net.sf.aguacate.configuration.field.FieldDynamicDate Maven / Gradle / Ivy
package net.sf.aguacate.configuration.field;
import java.text.Format;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.sf.aguacate.validator.ValidationConversionResult;
public class FieldDynamicDate extends Field {
private static final Logger LOGGER = LogManager.getLogger(FieldDynamicDate.class);
private final Format format;
private final String minVal;
private final String maxVal;
public FieldDynamicDate(String name, boolean optional, Format format, String minVal, String maxVal) {
super(name, Field.DYNAMIC_DATE, optional);
this.format = format;
this.minVal = minVal;
this.maxVal = maxVal;
}
public Date getMinValue(Calendar calendar) {
if ("TODAY".equalsIgnoreCase(minVal)) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
} else {
throw new IllegalStateException(minVal);
}
}
public Date getMaxValue() {
if ("FUTURE".equalsIgnoreCase(maxVal)) {
return null;
} else {
throw new IllegalStateException(maxVal);
}
}
@Override
public ValidationConversionResult validateAndConvert(Object value) {
LOGGER.trace(value);
if (String.class == value.getClass()) {
String val = (String) value;
try {
Date date = (Date) format.parseObject(val);
if (date == null) {
return new ValidationConversionResult("Invalid format");
} else {
LOGGER.trace(date);
int ndx = FieldTimeUtil.timeZone(val);
date = FastDateFormat.getInstance("yyyy-MM-dd").parse(val.substring(0, ndx));
Calendar calendar = Calendar.getInstance();
int minutes = FieldTimeUtil.calculateDiff(calendar, val);
calendar.add(Calendar.MINUTE, minutes);
int hr = calendar.get(Calendar.HOUR_OF_DAY);
int mins = calendar.get(Calendar.MINUTE);
int secs = calendar.get(Calendar.SECOND);
int mills = calendar.get(Calendar.MILLISECOND);
Date min = getMinValue(calendar);
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, hr);
calendar.set(Calendar.MINUTE, mins);
calendar.set(Calendar.SECOND, secs);
calendar.set(Calendar.MILLISECOND, mills);
date = calendar.getTime();
LOGGER.debug("{} & {}", min, date);
if (min.compareTo(date) <= 0) {
Date max = getMaxValue();
LOGGER.debug("{} & {}", date, max);
if (max == null || date.compareTo(max) < 0) {
return new ValidationConversionResult(date);
} else {
return new ValidationConversionResult("Invalid maximum value");
}
} else {
return new ValidationConversionResult("Invalid minimum value");
}
}
} catch (ParseException e) {
return new ValidationConversionResult("Invalid format");
}
} else {
return new ValidationConversionResult("Invalid value");
}
}
}