Skip to content

Introduce Conflict Strategy that defines the behavior when a constraint name conflicts #331

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

Merged
merged 2 commits into from
May 15, 2023
Merged
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
63 changes: 63 additions & 0 deletions src/main/java/am/ik/yavi/builder/ConflictStrategy.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright (C) 2018-2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package am.ik.yavi.builder;

import java.util.List;

import am.ik.yavi.core.ConstraintPredicates;

/**
* Conflict Strategy that defines the behavior when a constraint name conflicts when
* adding a constraint.
*
* @since 0.13.0
*/
@FunctionalInterface
public interface ConflictStrategy {
/**
* Define how to resolve conflicts of a constraint name when adding a constraint.
*
* @param predicatesList existing predicates list
* @param predicates new (conflicting) predicate
* @param <T> target type
*/
<T> void resolveConflict(List<ConstraintPredicates<T, ?>> predicatesList,
ConstraintPredicates<T, ?> predicates);

/**
* Do nothing if a conflict occurs. That means simply appending the predicate.
*/
ConflictStrategy NOOP = new ConflictStrategy() {
@Override
public <T> void resolveConflict(
List<ConstraintPredicates<T, ?>> constraintPredicates,
ConstraintPredicates<T, ?> predicates) {
// NOOP
}
};

/**
* If there is a conflict, remove the existing predicates and adopt the new predicate.
*/
ConflictStrategy OVERRIDE = new ConflictStrategy() {
@Override
public <T> void resolveConflict(
List<ConstraintPredicates<T, ?>> constraintPredicates,
ConstraintPredicates<T, ?> predicates) {
constraintPredicates.clear();
}
};
}
62 changes: 61 additions & 1 deletion src/main/java/am/ik/yavi/builder/ValidatorBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -125,6 +126,8 @@ public class ValidatorBuilder<T> implements Cloneable {

boolean failFast = false;

ConflictStrategy conflictStrategy = ConflictStrategy.NOOP;

public ValidatorBuilder() {
this(DEFAULT_SEPARATOR);
}
Expand Down Expand Up @@ -188,7 +191,8 @@ public static <X> ValidatorBuilder<X> of() {
}

public Validator<T> build() {
return new Validator<>(messageKeySeparator, this.predicatesList,
return new Validator<>(messageKeySeparator,
new PredicatesList<>(this.conflictStrategy, this.predicatesList).toList(),
this.collectionValidators, this.conditionalValidators,
this.messageFormatter == null ? new SimpleMessageFormatter()
: this.messageFormatter,
Expand Down Expand Up @@ -903,6 +907,20 @@ public ValidatorBuilder<T> failFast(boolean failFast) {
return this;
}

/**
* Sets the {@link ConflictStrategy} that defines the behavior when a constraint name
* conflicts when adding a constraint. By default, {@link ConflictStrategy#NOOP} is
* used.
*
* @param conflictStrategy Conflict Strategy
* @return validator builder (self)
* @since 0.13.0
*/
public ValidatorBuilder<T> conflictStrategy(ConflictStrategy conflictStrategy) {
this.conflictStrategy = conflictStrategy;
return this;
}

public <N> ValidatorBuilder<T> nest(Function<T, N> nested, String name,
Validator<N> validator) {
return this.nest(nested, name, validator, NullAs.INVALID);
Expand Down Expand Up @@ -1197,4 +1215,46 @@ public interface ToYearMonthConstraint<T> extends Function<T, YearMonth> {
public interface ValidatorBuilderConverter<T>
extends Function<ValidatorBuilder<T>, ValidatorBuilder<T>> {
}

/**
* An internal class that manages predicate conflicts
*
* @param <T> target type
* @since 0.13.0
*/
static final class PredicatesList<T> {
private final ConflictStrategy conflictStrategy;

private final Map<String, List<ConstraintPredicates<T, ?>>> predicatesListMap = new LinkedHashMap<>();

public PredicatesList(ConflictStrategy conflictStrategy) {
this.conflictStrategy = conflictStrategy;
}

public PredicatesList(ConflictStrategy conflictStrategy,
List<ConstraintPredicates<T, ?>> predicatesList) {
this(conflictStrategy);
predicatesList.forEach(this::add);
}

public void add(ConstraintPredicates<T, ?> predicates) {
final List<ConstraintPredicates<T, ?>> predicatesList = this.predicatesListMap
.computeIfAbsent(predicates.name(), s -> new ArrayList<>());
if (!predicatesList.isEmpty()) {
this.conflictStrategy.resolveConflict(predicatesList, predicates);
}
predicatesList.add(predicates);
}

public List<ConstraintPredicates<T, ?>> toList() {
final int length = predicatesListMap.values().stream().mapToInt(List::size)
.sum();
final List<ConstraintPredicates<T, ?>> list = new ArrayList<>(length);
for (List<ConstraintPredicates<T, ?>> predicates : predicatesListMap
.values()) {
list.addAll(predicates);
}
return list;
}
}
}
15 changes: 15 additions & 0 deletions src/main/java/am/ik/yavi/core/ErrorHandler.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
/*
* Copyright (C) 2018-2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package am.ik.yavi.core;

/**
Expand Down
15 changes: 15 additions & 0 deletions src/test/java/am/ik/yavi/arguments/Car.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
/*
* Copyright (C) 2018-2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package am.ik.yavi.arguments;

import am.ik.yavi.builder.IntegerValidatorBuilder;
Expand Down
15 changes: 15 additions & 0 deletions src/test/java/am/ik/yavi/core/Gh249Test.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
/*
* Copyright (C) 2018-2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package am.ik.yavi.core;

import java.util.Collections;
Expand Down
72 changes: 72 additions & 0 deletions src/test/java/am/ik/yavi/core/Gh253Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright (C) 2018-2023 Toshiaki Maki <makingx@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package am.ik.yavi.core;

import am.ik.yavi.builder.ConflictStrategy;
import am.ik.yavi.builder.ValidatorBuilder;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class Gh253Test {

ValidatorBuilder<Car> baseValidatorBuilder = ValidatorBuilder.<Car> of()
.constraint(Car::getManufacturer, "manufacturer", c -> c.notNull())
.constraint(Car::getSeatCount, "seatCount", c -> c.greaterThanOrEqual(2));

@Test
void overrideConstraint() {
final Car target = new Car("foo", "AAA", 2);
final Validator<Car> baseValidator = baseValidatorBuilder.build();
final ConstraintViolations violations1 = baseValidator.validate(target);
assertThat(violations1.isValid()).isTrue();

final Validator<Car> overwrittenValidator = baseValidatorBuilder
.constraint(Car::getManufacturer, "manufacturer", c -> c.isNull())
.conflictStrategy(ConflictStrategy.OVERRIDE).build();
final ConstraintViolations violations2 = overwrittenValidator.validate(target);
assertThat(violations2.isValid()).isFalse();
assertThat(violations2).hasSize(1);
assertThat(violations2.get(0).message())
.isEqualTo("\"manufacturer\" must be null");
}

public static class Car {
private final String manufacturer;

private final String licensePlate;

private final int seatCount;

public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}

public String getManufacturer() {
return manufacturer;
}

public String getLicensePlate() {
return licensePlate;
}

public int getSeatCount() {
return seatCount;
}
}
}