Skip to content

Instantly share code, notes, and snippets.

@sezRR
Last active November 2, 2023 22:37
Show Gist options
  • Save sezRR/32683c680ece3f9dbc82f2c08f06f42c to your computer and use it in GitHub Desktop.
Save sezRR/32683c680ece3f9dbc82f2c08f06f42c to your computer and use it in GitHub Desktop.
@Component
public class BeanValidation<T> {
private final Validator validator;
private DtoConverterService dtoConverterService;
private BeanValidation(ResourceBundleMessageSourceBean resourceBundleMessageSourceBean) {
ValidatorFactory validatorFactory = resourceBundleMessageSourceBean.validator();
this.validator = validatorFactory.getValidator();
}
@Autowired
public BeanValidation(ResourceBundleMessageSourceBean resourceBundleMessageSourceBean, DtoConverterService dtoConverterService) {
this(resourceBundleMessageSourceBean);
this.dtoConverterService = dtoConverterService;
}
public BindingResult validate(Object validationObject) {
Set<ConstraintViolation<Object>> violations = validator.validate(validationObject);
BindingResult bindingResult = new BeanPropertyBindingResult(validationObject, "object");
for (var violation : violations) {
ObjectError objectError = new ObjectError(validationObject.toString(), violation.getMessage());
bindingResult.addError(objectError);
}
return bindingResult;
}
public Dictionary<String, Object> validateUnmappedObject(Object object, Class<T> baseObject){
Dictionary<String, Object> validatedObject = new Hashtable<>();
Object mappedObject = dtoConverterService.dtoToBaseClassConverter(object, baseObject);
validatedObject.put("mappedObject", mappedObject);
validatedObject.put("bindingResult", this.validate(mappedObject));
return validatedObject;
}
}
@Component
public class ValidationResponseChecker<T> {
private final BeanValidation<T> beanValidation;
@Autowired
public ValidationResponseChecker(BeanValidation<T> beanValidation) {
this.beanValidation = beanValidation;
}
@SuppressWarnings("unchecked")
public DataValidationCustomResponseEntity<T> validateUnmappedObject(Object object, Class<T> mainObject){
var validationResponse = beanValidation.validateUnmappedObject(object, mainObject);
BindingResult bindingResult = (BindingResult) validationResponse.get("bindingResult");
if (bindingResult.hasErrors())
return new DataValidationCustomResponseEntity<>(bindingResult, HttpStatus.BAD_REQUEST);
return new DataValidationCustomResponseEntity<>((T) validationResponse.get("mappedObject"), bindingResult, HttpStatus.OK);
}
public DataValidationCustomResponseEntity<T> validateMappedObject(T object){
var bindingResult = beanValidation.validate(object);
if (bindingResult.hasErrors())
return new DataValidationCustomResponseEntity<>(bindingResult, HttpStatus.BAD_REQUEST);
return new DataValidationCustomResponseEntity<>(object, bindingResult, HttpStatus.OK);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment