Gamelib/src/main/java/uulm/teamname/marvelous/gamelibrary/json/Validation.java

42 lines
1.5 KiB
Java

package uulm.teamname.marvelous.gamelibrary.json;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public class Validation {
private Validation() {}
private static final Validator validator;
static {
var factory = jakarta.validation.Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
public static Set<ConstraintViolation<Object>> validate(Object object) {
return validator.validate(object);
}
/**
* Validates the given object by using a {@link Validator}, and generates
* a {@link String} from the violations. If there aren't any violations, and the object perfectly
* conforms to the shape it should be in, an empty optional is returned.
* @param object is the object to validate
* @return an {@link Optional}<{@link String}> describing the violations the object commits,
* or an empty {@link Optional} if there aren't any
*/
public static Optional<String> validateAndGetString(Object object) {
var violations = validator.validate(object);
if (violations.isEmpty()) return Optional.empty();
else {
return Optional.of(violations.stream()
.map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
.collect(Collectors.joining(", ")));
}
}
}