Displaying validation messages
You have set up annotations as quality control on video game sales data. Now try running the validation on data with mistakes to see what messages are printed. The bad data is missing a platform
, has year
before 1960, and has negative sales
, which violates the constraints specified in the annotations. Validate the video game sales data and print any violation messages.
This exercise is part of the course
Cleaning Data in Java
Exercise instructions
- Print the violation message when the data violates a constraint.
- Validate the video game sale by applying the
validator
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.util.Set;
import jakarta.validation.*;
import jakarta.validation.constraints.*;
public class VideoGameSale {
@NotNull(message = "Name cannot be empty")
private String name;
@NotNull(message = "Platform cannot be empty")
private String platform;
@Min(value = 1960, message = "Year must be greater than 1960")
private Integer year;
@Min(value = 0, message = "Sales amount must be positive")
private Double sales;
public VideoGameSale(String name, String platform, Integer year, Double sales) {
this.name = name;
this.platform = platform;
this.year = year;
this.sales = sales;
}
public static void main(String[] args) {
VideoGameSale sale = new VideoGameSale(
"Super Mario Bros.", null, 1950,
29.08);
Set> violations =
SalesValidator.validateSale(sale);
// Print the violation message
violations.forEach(violation ->
System.out.println(____.____()));
if (!violations.isEmpty()) throw new ConstraintViolationException(violations);
}
}
class SalesValidator {
private static final ValidatorFactory factory =
Validation.buildDefaultValidatorFactory();
private static final Validator validator = factory.getValidator();
public static Set> validateSale(VideoGameSale sale) {
// Validate the video game sale
return ____.____(sale);
}
}