Snažím potvrdit Enum pomocí vlastní validátor, v mé vlastní validátor snažím se vrátit vlastní zprávu, když parametr není v enum hodnot.
Níže moje enum
public enum Type {
MISSING_SITE,
INACTIVE_SITE;
}
Níže moje PostMapping
metoda
@PostMapping(value = "/line-kpi", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Find Kpis by one or more customer property")
public ResponseEntity<List<KpiDTO>> findKPILineByCustomer(@RequestBody @ValidCustomerParameter CustomerParameter customerParameter, @RequestParam @ValidExtractionDate String extractionDate) {
var linesKpi = Optional.ofNullable(
kpiService.findKPILineByCustomer(
Optional.ofNullable(customerParameter.getEntityPerimeter()).orElse(List.of()),
Optional.ofNullable(customerParameter.getName()).orElse(List.of()),
Optional.ofNullable(customerParameter.getIc01()).orElse(List.of()),
Optional.ofNullable(customerParameter.getSiren()).orElse(List.of()),
Optional.ofNullable(customerParameter.getEnterpriseId()).orElse(List.of()),
LocalDate.parse(extractionDate)
)
);
return linesKpi.map(ResponseEntity::ok).orElseThrow(() -> new ResourceNotFoundException(KPIS));
}
Nemůžu přepínat typ enum řetězec v metodě samotné, protože jsem pomocí swagger, který zobrazuje pěkný výběr seznamu pro výčtové typy.
Bohužel, když se snažím dát jinou hodnotu pro Typ, vrátí chybný požadavek a můj validátory nejsou spuštěna.
Takže se snažím serializovat můj enum být interpretován jako Řetězec, když to přijde k regulátoru a k tomu, že musím použít Jackson, snažil jsem se hledat řešení, ale nemůžu najít dobrý pro můj případ.
Níže jsou mé validátory
public class ReportTypeValidator implements ConstraintValidator<ValidReportType, Type> {
private String globalMessage;
@Override
public void initialize(ValidReportType constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
globalMessage = constraintAnnotation.message();
}
@Override
public boolean isValid(Type type, ConstraintValidatorContext constraintValidatorContext) {
if (Arrays.stream(Type.values()).filter(type1 -> type1.equals(type)).toList().isEmpty()) {
constraintValidatorContext
.buildConstraintViolationWithTemplate(globalMessage + ", report type does not exist")
.addConstraintViolation();
return false;
}
return true;
}
}
@Constraint(validatedBy = ReportTypeValidator.class)
@Target( { ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Valid
public @interface ValidReportType {
String message() default "Invalid value for report type";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Mohl by mi někdo říct, jak se mohu obrátit svou enum jako řetězec, takže můj validátor, že to zvládnu?