Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HV-1552 Adding new MinAge Constraint #913

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.cfg.defs;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs a license header comment as in the other classes

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @marko-bekhta I have done all your suggestions except the one for ChronoUnit attribute. I'm not sure what you mean. Is it something like this: add to @interface AgeMin a attribute like ChronoUnit unit();, so users can define the value when use the annotation like this:
@AgeMin( value = MINIMUM_AGE , inclusive = true, unit= ChronoUnit.YEARS)
or @AgeMin( value = MINIMUM_AGE , inclusive = true, unit= ChronoUnit.MONTHS) ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Hilmerc yes, that's exactly it! :) This will make the constraint more versatile.
I've also prepared a short plan, with items that are still needed to finish this work. I'll post it in the separate comment. I hope it'll be helpful.


import org.hibernate.validator.cfg.ConstraintDef;
import org.hibernate.validator.constraints.AgeMin;

/**
* @author Hillmer Chona
* @since 6.0.8
*/
public class AgeMinDef extends ConstraintDef<AgeMinDef, AgeMin> {

public AgeMinDef() {
super( AgeMin.class );
}

public AgeMinDef value(int value) {
addParameter( "value", value );
return this;
}

public AgeMinDef unit(AgeMin.Unit unit) {
addParameter( "unit", unit );
return this;
}

public AgeMinDef inclusive(boolean inclusive) {
addParameter( "inclusive", inclusive );
return this;
}
}
115 changes: 115 additions & 0 deletions engine/src/main/java/org/hibernate/validator/constraints/AgeMin.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.constraints;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.time.temporal.ChronoUnit;


import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
* The annotated element must be an instant, date or time for which at least
* the specified amount ({@link AgeMin#value()}) of Years/Days/Months/etc. defined
* by {@link AgeMin#unit()} have passed till now.
* <p>
* Supported types are:
* <ul>
* <li>{@code java.util.Calendar}</li>
* <li>{@code java.util.Date}</li>
* <li>{@code java.time.chrono.HijrahDate}</li>
* <li>{@code java.time.chrono.JapaneseDate}</li>
* <li>{@code java.time.LocalDate}</li>
* <li>{@code java.time.chrono.MinguoDate}</li>
* <li>{@code java.time.chrono.ThaiBuddhistDate}</li>
* <li>{@code java.time.Year}</li>
* <li>{@code java.time.YearMonth}</li>
* </ul>
* <p>
* {@code null} elements are considered valid.
*
* @author Hillmer Chona
* @since 6.0.8
*/
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(AgeMin.List.class)
@Documented
@Constraint(validatedBy = {})
public @interface AgeMin {

String message() default "{org.hibernate.validator.constraints.AgeMin.message}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

/**
* @return the age according to unit from a given instant, date or time must be greater or equal to
*/
int value();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think in the previous discussion, there was an idea to try out to support other units (ChronoUnit) with the ChronoUnit#YEARS by default. Could you please try to experiment with that ? Should be simple to add something like ChronoUnit unit() default ChronoUnit.YEARS; to the constraint. If it works the programmatic definition (AgeMinDef) would need this attribute to be added as well.


/**
* Specifies the date period unit ( Years/Days/Months. ) that will be used to compare the given instant,
* date or time with the reference value.
* By default, it is ({@link AgeMin.Unit#YEARS}).
*
* @return the date period unit
*/

Unit unit() default Unit.YEARS;

/**
* Specifies whether the specified value is inclusive or exclusive.
* By default, it is inclusive.
*
* @return {@code true} if the date period units from a given instant, date or time must be higher or equal to the specified value,
* {@code false} if date period units from a given instant, date or time must be higher
*/
boolean inclusive() default true;

/**
* Defines several {@link AgeMin} annotations on the same element.
*
* @see AgeMin
*/
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@interface List {
AgeMin[] value();
}

enum Unit {
YEARS( ChronoUnit.YEARS ), MONTHS( ChronoUnit.MONTHS ), DAYS( ChronoUnit.DAYS );

private final ChronoUnit chronoUnit;

Unit(ChronoUnit chronoUnit) {
this.chronoUnit = chronoUnit;

}

public ChronoUnit getChronoUnit() {
return chronoUnit;
}

}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.internal.constraintvalidators.hv.age;

import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandles;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;

import javax.validation.ConstraintValidatorContext;

import org.hibernate.validator.constraintvalidation.HibernateConstraintValidator;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorInitializationContext;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;

/**
* Base class for all age validators that use an {@link Instant} to be compared to the age reference.
*
* @author Hillmer Chona
* @since 6.0.8
*/
public abstract class AbstractAgeInstantBasedValidator<C extends Annotation, T>
implements HibernateConstraintValidator<C, T> {

private static final Log LOG = LoggerFactory.make( MethodHandles.lookup() );

private Clock referenceClock;

private int referenceAge;

private boolean inclusive;

private ChronoUnit unit;

public void initialize(
int referenceAge,
ChronoUnit unit,
boolean inclusive,
HibernateConstraintValidatorInitializationContext initializationContext) {
try {
this.referenceClock = Clock.offset(
initializationContext.getClockProvider().getClock(),
getEffectiveTemporalValidationTolerance( initializationContext.getTemporalValidationTolerance() )
);
}
catch (Exception e) {
throw LOG.getUnableToGetCurrentTimeFromClockProvider( e );
}
this.referenceAge = referenceAge;
this.unit = unit;
this.inclusive = inclusive;
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can add

public void initialize(int referenceAge, ChronoUnit unit, boolean inclusive, HibernateConstraintValidatorInitializationContext initializationContext) {
    try {
        this.referenceClock = Clock.offset(
                initializationContext.getClockProvider().getClock(),
                getEffectiveTemporalValidationTolerance( initializationContext.getTemporalValidationTolerance() )
        );
    }
    catch (Exception e) {
        throw LOG.getUnableToGetCurrentTimeFromClockProvider( e );
    }
    this.referenceAge = referenceAge;
    this.unit = unit;
    this.inclusive = inclusive;
}

here. This way we will not need to repeat same logic for referenceClock in all other validators.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to do something like you say, but no good ideas came to me, thanks. Done.

@Override
public boolean isValid(T value, ConstraintValidatorContext context) {
// null values are valid
if ( value == null ) {
return true;
}
// As Instant does not support plus operation on ChronoUnits greater than DAYS we need to convert it to LocalDate
// first, which supports such operations.

int result = getInstant( value ).atZone( ZoneOffset.ofHours( 0 ) ).toLocalDate()
.compareTo( LocalDate.now( referenceClock ).minus( referenceAge, unit ) );

return isValid( result );
}

/**
* Returns whether the specified value is inclusive or exclusive.
*/
protected boolean isInclusive() {
return this.inclusive;
}

/**
* Returns the temporal validation tolerance to apply.
*/
protected abstract Duration getEffectiveTemporalValidationTolerance(Duration absoluteTemporalValidationTolerance);

/**
* Returns the {@link Instant} measured from Epoch.
*/
protected abstract Instant getInstant(T value);

/**
* Returns whether the result of the comparison between the validated value and the reference age is considered
* valid.
*/
protected abstract boolean isValid(int result);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.internal.constraintvalidators.hv.age;

import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandles;
import java.time.Clock;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;

import javax.validation.ClockProvider;
import javax.validation.ConstraintValidatorContext;

import org.hibernate.validator.constraintvalidation.HibernateConstraintValidator;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorInitializationContext;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;

/**
* Base class for all age validators that are based on the {@code java.time} package.
*
* @author Hillmer Chona
* @since 6.0.8
*/
public abstract class AbstractAgeTimeBasedValidator<C extends Annotation, T extends TemporalAccessor & Comparable<? super T>>
implements HibernateConstraintValidator<C, T> {

private static final Log LOG = LoggerFactory.make( MethodHandles.lookup() );

private Clock referenceClock;

private int referenceAge;

private boolean inclusive;

private ChronoUnit unit;

public void initialize(
int referenceAge,
ChronoUnit unit,
boolean inclusive,
HibernateConstraintValidatorInitializationContext initializationContext) {
try {
this.referenceClock = Clock.offset(
initializationContext.getClockProvider().getClock(),
getEffectiveTemporalValidationTolerance( initializationContext.getTemporalValidationTolerance() )
);
}
catch (Exception e) {
throw LOG.getUnableToGetCurrentTimeFromClockProvider( e );
}
this.referenceAge = referenceAge;
this.unit = unit;
this.inclusive = inclusive;
}

@Override
public boolean isValid(T value, ConstraintValidatorContext context) {
// null values are valid
if ( value == null ) {
return true;
}

int result = value.compareTo( getReferenceValue( referenceClock, referenceAge, unit ) );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe better to follow the same pattern as in the instant validatior ? I mean do the operation once here in the validator rather than do the minus in each type's impl. Also I've noticed that you've used the minus for these TemporalAccessor types and for Instant there's add. Would be better to use the same one in both, both are fine just pick one :)


return isValid( result );
}

/**
* Returns whether the specified value is inclusive or exclusive.
*/
protected boolean isInclusive() {
return this.inclusive;
}

/**
* Returns the temporal validation tolerance to apply.
*/
protected abstract Duration getEffectiveTemporalValidationTolerance(Duration absoluteTemporalValidationTolerance);

/**
* Returns an object of the validated type corresponding to the time reference as provided by the
* {@link ClockProvider} increased or decreased with the specified referenceAge of Years/Days/Months/etc.
* defined by {@link ChronoUnit}.
*/
protected abstract T getReferenceValue(Clock reference, int referenceAge, ChronoUnit unit);

/**
* Returns whether the result of the comparison between the validated value and the age reference is considered
* valid.
*/
protected abstract boolean isValid(int result);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.internal.constraintvalidators.hv.age.min;

import java.time.Duration;
import java.time.Instant;

import javax.validation.metadata.ConstraintDescriptor;

import org.hibernate.validator.constraints.AgeMin;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorInitializationContext;
import org.hibernate.validator.internal.constraintvalidators.hv.age.AbstractAgeInstantBasedValidator;


/**
* Base class for all {@code @AgeMin} validators that use an {@link Instant} to be compared to the age reference.
*
* @author Hillmer Chona
* @since 6.0.8
*/
public abstract class AbstractAgeMinInstantBasedValidator<T> extends AbstractAgeInstantBasedValidator<AgeMin, T> {

@Override
public void initialize(ConstraintDescriptor<AgeMin> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) {
super.initialize( constraintDescriptor.getAnnotation().value(), constraintDescriptor.getAnnotation().unit().getChronoUnit(),
constraintDescriptor.getAnnotation().inclusive(), initializationContext );
}

@Override
protected Duration getEffectiveTemporalValidationTolerance(Duration absoluteTemporalValidationTolerance) {
return absoluteTemporalValidationTolerance;
}

@Override
protected boolean isValid(int result) {
return isInclusive() ? result <= 0 : result < 0;
}
}
Loading