I have the following CustomValidator and Annotation that work fine when I call it as part of endpoint parameter check (run() method in service). I'd like to call the same validator manually in method run2(), but during execution of the endpoint my custom validator is not being called. What am I doing wrong?
Annotation
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#Target({PARAMETER, FIELD, METHOD, ANNOTATION_TYPE, TYPE_USE})
#Retention(RUNTIME)
#Constraint(validatedBy = {ExecutionRequestValidator.class})
#Documented
public #interface ValidateRequest {
String message() default "{Invalid Request}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
Validator (concrete class implements isValid())
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
#Component
#Slf4j
public abstract class BaseValidator<A extends Annotation, T> implements ConstraintValidator<A, T> {
protected boolean handleConstraintValidationFailure(
ConstraintValidatorContext context, String message, ValidationErrorCode errorCode) {
if (context != null) {
log.error("BaseValidator#handleConstraintValidationFailure ErrorCode: {}, Message: {}",
errorCode, message);
context.disableDefaultConstraintViolation();
HibernateConstraintValidatorContext hibernateContext =
context.unwrap(HibernateConstraintValidatorContext.class);
// passing error code that will be set as code value in the response
hibernateContext
.withDynamicPayload(errorCode.getId().toString())
.buildConstraintViolationWithTemplate(message)
.addConstraintViolation();
}
return false;
}
#Override
public void initialize(A constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
}
}
Service
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory;
import javax.validation.ConstraintViolation;
import java.util.*;
#Service
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class Service {
private final Validator injectedValidator;
private final ConfigurableApplicationContext applicationContext;
public Response run(#ValidateRequest Request request) {
// REQUEST VALIDATION WORKS
...
...
}
public Response run2(#Validated UUID id){
// REQUEST VALIDATION DOESN'T WORK
Request request = RequestProvider.get(id);
// NEITHER OF THESE CALLS TRIGGER CUSTOM VALIDATOR
final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
validator.validate(request);
final Set<ConstraintViolation<Request>> validate = injectedValidator.validate(request);
...
...
}
Related
I need to document my SpringBoot APIs and their possible exceptions with OpenAPI,
and I am using SpringDoc-OpenAPI https://springdoc.org/.
To handle the NotFound cases I created this exception class:
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
public class NotFoundException extends ResponseStatusException {
public NotFoundException() {
super(HttpStatus.NOT_FOUND);
}
}
and this #RestControllerAdvice
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
#RestControllerAdvice
public class GlobalControllerExceptionHandler {
#ExceptionHandler(NotFoundException.class)
#ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<String> handleNotFoundException(RuntimeException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
The problem I am facing is that the generated OpenAPI yaml file has
responses:
"404":
description: Not Found
content:
'*/*':
schema:
type: string
for all #RestController endpoints, instead of only for the methods with throws NotFoundException.
How can I limit the #ControllerAdvice (or the OpenAPI), to generate the 404 Response documentation only for methods with the throwing signature?
Do I need to use something else other than the #RestControllerAdvice?
I would like to avoid having to annotate every single method.
A possible solution is to:
Make the #RestControllerAdvice #Hidden
Provide an OperationCustomizer #Bean
import io.swagger.v3.oas.annotations.Hidden;
import it.eng.cysec.ot.risk.assessment.api.exceptions.NotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
#Hidden
#RestControllerAdvice
public class GlobalControllerExceptionHandler {
#ExceptionHandler(NotFoundException.class)
#ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<String> handleNotFoundException(NotFoundException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
}
}
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import it.eng.cysec.ot.risk.assessment.api.exceptions.NotFoundException;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.web.method.HandlerMethod;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
public class OperationResponseCustomizer implements OperationCustomizer {
public static final ApiResponse NOT_FOUND_API_RESPONSE;
static {
MediaType mediaType = new MediaType();
mediaType.setSchema(new StringSchema());
Content content = new Content();
content.addMediaType("*/*", mediaType);
NOT_FOUND_API_RESPONSE = new ApiResponse()
.description("Not Found")
.content(content);
}
/**
* Customize operation.
*
* #param operation input operation
* #param handlerMethod original handler method
* #return customized operation
*/
#Override
public Operation customize(Operation operation, HandlerMethod handlerMethod) {
Method method = handlerMethod.getMethod();
List<Class<?>> exceptions = Arrays.asList(method.getExceptionTypes());
if(exceptions.contains(NotFoundException.class)){
ApiResponses apiResponses = operation.getResponses();
apiResponses.addApiResponse("404", NOT_FOUND_API_RESPONSE);
}
return operation;
}
}
Controller Code:
#RequestMapping(value="/update", method=RequestMethod.POST, produces =
"application/json; charset=utf-8")
#ResponseBody
public ResponseEntityWrapper update(
HttpServletRequest request,
#RequestBody #Valid InputForm form,
HttpServletResponse response
) {
//logic
}
InputForm:
public class InputForm{
#NotNull
private String formId;
private List<Employee> addEmpList;
private List<Employee> removeEmpList;
//Other fields & getters & setters.....
}
Employee:
public Employee{
#NotNull
private String empId;
private String name;
//Other fields and getters and setters.....
}
When the request to Controller's update is method, I would like to have InputForm validated - Atleast one of the fields in it is mandatory. ie., both addEmpList, removeEmpList cannot be null. And empId in Employee should not be null.
How do I do this?
This can be achieved using javax.validation.Constraint. Annotate your controller using #Validated annotation, and you can create your constraints as below:
Controller
import com.example.model.Employee;
import com.example.model.InputForm;
import com.example.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
#RestController
#Validated
public class MyController {
#Autowired
private MyService myService;
#RequestMapping(value="/update", method= RequestMethod.POST, produces = "application/json; charset=utf-8")
#ResponseBody
public ResponseEntity<List<Employee>> update(
HttpServletRequest request,
#CheckAtLeastOnePresentConstraint #RequestBody #Valid InputForm form,
HttpServletResponse response
) {
return new ResponseEntity<List<Employee>>(myService.getEmployees(form), HttpStatus.OK);
}
}
Contraint Interface:
import java.lang.annotation.*;
import javax.validation.Constraint;
import javax.validation.Payload;
#Constraint(validatedBy = CheckOneValuePresent.class)
#Target( { ElementType.PARAMETER })
#Retention(RetentionPolicy.RUNTIME)
public #interface CheckAtLeastOnePresentConstraint {
String message() default "At least one of the values removeEmpList or addEmpList must be present";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
And your CustomValidator class
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraintvalidation.SupportedValidationTarget;
import javax.validation.constraintvalidation.ValidationTarget;
#SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class CheckOneValuePresent implements ConstraintValidator<CheckAtLeastOnePresentConstraint, InputForm> {
#Override
public boolean isValid(InputForm inputForm,
ConstraintValidatorContext cxt) {
return inputForm.getAddEmpList() != null || inputForm.getRemoveEmpList() != null;
}
}
Hope this will help.
I'm trying to set up a Spring-Data-Rest App using Spring Boot 1.5.9.RELEASE. I have a ConstraintValidator set up like this:
UniqueEmail.java:
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.NotNull;
import java.lang.annotation.*;
#Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Constraint(validatedBy = {UniqueEmailValidator.class})
#NotNull
#ReportAsSingleViolation
public #interface UniqueEmail {
Class<?>[] groups() default {};
String message() default "{eu.icarus.momca.backend.domain.validation.UniqueEmail.message}";
Class<? extends Payload>[] payload() default {};
#Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
#Retention(RetentionPolicy.RUNTIME)
#Documented
static #interface List {
UniqueEmail[] value();
}
}
UniqueEmailValidator.java:
import eu.icarus.momca.backend.domain.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> {
#Autowired
private AccountRepository accountRepository;
#Override
public void initialize(UniqueEmail annotation) {
}
#Override
public boolean isValid(String email, ConstraintValidatorContext context) {
return accountRepository.findByEmail(email) == null;
}
}
I've also set up listeners for the beforeCreate and beforeSave repository methods:
RestConfiguration.java:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.rest.core.event.ValidatingRepositoryEventListener;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
#Configuration
public class RestConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
validatingListener.addValidator("beforeCreate", localValidatorFactoryBean());
validatingListener.addValidator("beforeSave", localValidatorFactoryBean());
}
#Bean
#Primary
LocalValidatorFactoryBean localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
}
My problem:
The validator seems to work when the repository methods are called through REST endpoints, however I also try to set up some stuff in the connected database via a CommandLineRunner that uses the same repository. When the calls to the repository are validated, the autowired AccountRepository in the ConstraintValidator is null even if it isn't null at the same time in the CommandLineRunner that also has the same repository autowired. I don't understand this.
Does anybody have an idea why the repository is null when the validation is triggered from the CommandLineRunner?
Any help is greatly appreciated.
Daniel
Edit: added the CommandLineRunner Code
InitAdminData.java:
import eu.icarus.momca.backend.domain.entity.Account;
import eu.icarus.momca.backend.domain.entity.AccountDetails;
import eu.icarus.momca.backend.domain.entity.AccountProfile;
import eu.icarus.momca.backend.domain.entity.Client;
import eu.icarus.momca.backend.domain.enumeration.AccountRoles;
import eu.icarus.momca.backend.domain.enumeration.ClientRoles;
import eu.icarus.momca.backend.domain.enumeration.GrantTypes;
import eu.icarus.momca.backend.domain.repository.AccountRepository;
import eu.icarus.momca.backend.domain.repository.ClientRepository;
import eu.icarus.momca.backend.domain.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
#Component
public class InitAdminData implements CommandLineRunner {
private static final Collection<AccountRoles> DEFAULT_ACCOUNT_ROLES = Arrays.asList(AccountRoles.ROLE_ACCOUNT, AccountRoles.ROLE_ADMINISTRATOR, AccountRoles.ROLE_CLIENT_OWNER);
private static final Logger logger = LoggerFactory.getLogger(InitAdminData.class);
private AccountRepository accountRepository;
private AccountService accountService;
#Value("${app.admin-email}")
private String adminEmail;
#Value("${app.admin-name}")
private String adminName;
#Value("${app.admin-password}")
private String adminPassword;
private ClientRepository clientRepository;
#Value("${app.default-client-description}")
private String defaultClientDescription;
#Autowired
public InitAdminData(AccountRepository accountRepository, AccountService accountService, ClientRepository clientRepository) {
this.accountRepository = accountRepository;
this.clientRepository = clientRepository;
this.accountService = accountService;
}
private Account initAdminAccount() {
Account adminAccount = accountRepository.findByAccountProfile_Name(adminName);
if (adminAccount == null) {
adminAccount = new Account();
logger.info("Initialized new admin account");
} else {
logger.info("Refreshed admin account");
}
setAdminAccountData(adminAccount);
return accountService.save(adminAccount, adminPassword);
}
private void initDefaultClient(Account adminAccount) {
long adminAccountId = adminAccount.getId();
Collection<Client> adminClients = clientRepository.findAllByOwnerId(adminAccountId);
if (adminClients.isEmpty()) {
Client defaultClient = new Client();
defaultClient.setOwnerId(adminAccountId);
defaultClient.setDescription(defaultClientDescription);
Collection<ClientRoles> clientRoles = new HashSet<>(2);
clientRoles.add(ClientRoles.ROLE_CLIENT);
clientRoles.add(ClientRoles.ROLE_DEFAULT_CLIENT);
defaultClient.setRoles(clientRoles);
Collection<GrantTypes> grantTypes = new HashSet<>();
grantTypes.add(GrantTypes.authorization_code);
grantTypes.add(GrantTypes.client_credentials);
grantTypes.add(GrantTypes.password);
grantTypes.add(GrantTypes.refresh_token);
defaultClient.setGrantTypes(grantTypes);
defaultClient = clientRepository.save(defaultClient);
logger.info(String.format("Added new default client with id '%s'", defaultClient.getId()));
}
}
#Override
public void run(String... args) {
Account adminAccount = initAdminAccount();
initDefaultClient(adminAccount);
}
private void setAdminAccountData(Account adminAccount) {
adminAccount.setEmail(adminEmail);
adminAccount.setRoles(DEFAULT_ACCOUNT_ROLES);
adminAccount.setAccountDetails(new AccountDetails());
adminAccount.setAccountProfile(new AccountProfile(adminName));
}
}
Add the #ComponentScan annotation.
#ComponentScan
public class InitAdminData implements CommandLineRunner {
...
}
I think you may have few cases :-
you haven't autowired your service and Repo
you haven't scan your Repo where you have your service and Repo.
Or you haven't use #Component(any stereotype) annotation on your classes which you are autowiring
I have created a new Spring project and I have some trouble when I run the application. I am new to Spring development and I thing that the annotations are not placed properly. Any detailed explanation would be great for me for better understating. I am currently reading Spring in action, but if any other book or tutorial seems more accurate, please leave me a comment :)[this is the error that I am getting - 500 Internal Server Error].
This is my project:
HelloWorldConfiguration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#ComponentScan(basePackages = "com.websystique.springmvc")
public class HelloWorldConfiguration {
#Bean(name="HelloWorld")
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
HelloWordInitializer
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class HelloWorldInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(HelloWorldConfiguration.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet(
"dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
HelloWorldController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import service.StudentService;
import java.util.HashMap;
import java.util.Map;
#Configuration
#Controller
#ComponentScan(basePackages = "com.websystique.springmvc")
#RequestMapping("/")
public class HelloWorldController {
public HelloWorldController(){
}
#Autowired
private StudentService studentService;
private Map<String, Student> persoaneAdaugate = new HashMap<String, Student>();
#RequestMapping(method = RequestMethod.GET)
public String sayHello(ModelMap model) {
model.addAttribute("greeting", "Hello World from Spring 4 MVC");
return "welcome";
}
#RequestMapping(value = "/helloagain", method = RequestMethod.GET)
public String sayHelloAgain(ModelMap model) {
model.addAttribute("greeting", "Hello World Again, from Spring 4 MVC");
return "welcome";
}
/***
* #ModelAttribute = binds a method parameter or a method return value to a named model attribute and then exposes it to a web view.
* #param student
* #param result
* #param modelMap
* #return
* That is, #ModelAttribute methods are invoked before the controller methods annotated with #RequestMapping are invoked.
* The logic behind the sequence is that, the model object has to be created before any processing starts inside the controller methods.
*/
#RequestMapping(value="/", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("addStudent") Student student, BindingResult result, ModelMap modelMap){
if(result.hasErrors()){
return "error";
}
else {
studentService.addStudent(student);
}
/*modelMap.addAttribute("nume", student.getNume());
modelMap.addAttribute("prenume", student.getPrenume());
persoaneAdaugate.put(student.getNume(), student);
System.out.println("Persoane adaugate: " + persoaneAdaugate +"\n");
System.out.println("nume: " + student.getNume()+" si prenume: " +student.getPrenume());
*/
return "success";
}
}
StudentDao
import com.websystique.springmvc.model.Student;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public interface StudentDao {
List<Student> getAllStudents();
void addStudent(Student student);
}
StudentDaoImpl
import com.websystique.springmvc.model.Student;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository("studentDao")
#Service
#Transactional
public class StudentDaoImpl implements StudentDao{
#Autowired
private SessionFactory sessionFactory;
public List<Student> getAllStudents() {
return null;
// return sessionFactory.getCurrentSession().createQuery("from Date").list();
}
public void addStudent(Student student) {
sessionFactory.getCurrentSession().saveOrUpdate(student);
}
}
Student
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name="DATE")
public class Student implements Serializable{
#Id
#NotEmpty
#Column(name="nume", unique=true, nullable=false )
private String nume;
#NotEmpty
#Column(name="prenume", nullable = false)
private String prenume;
protected Student(){
}
Student(String nume, String prenume){
this.prenume=prenume;
this.nume=nume;
}
public String getNume(){
return nume;
}
public void setNume(String nume){
this.nume=nume;
}
public String getPrenume(){
return prenume;
}
public void setPrenume(String prenume){
this.prenume=prenume;
}
#Override
public String toString(){
return "Numele adaugat: nume= " + nume +" si prenume= " +prenume;
}
}
StudentService
import com.websystique.springmvc.model.Student;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public interface StudentService {
List<Student> getAllStudents();
void addStudent(Student student);
}
StudentServiceImpl
import com.websystique.springmvc.dao.StudentDao;
import com.websystique.springmvc.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
#Transactional
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentDao studentDao;
#Transactional
public List<Student> getAllStudents() {
return studentDao.getAllStudents();
}
public void addStudent(Student student) {
studentDao.addStudent(student);
}
}
I added validation possibility into my GWT project. But it doesn't work. I get these errors each time when I try to validate something:
Rebinding com.val.client.SampleValidatorFactory.GwtValidator
Invoking generator com.google.gwt.validation.rebind.ValidatorGenerator
Unexpected error trying to instantiate Generator 'com.google.gwt.validation.rebind.ValidatorGenerator'
MyEntity.java
package com.val.entity;
public class Pravform implements Serializable {
#Size(min = 4)
private String pfName;
...
SampleValidatorFactory.java
package com.val.client;
import javax.validation.Validator;
import com.google.gwt.core.client.GWT;
import com.google.gwt.validation.client.AbstractGwtValidatorFactory;
import com.google.gwt.validation.client.GwtValidation;
import com.google.gwt.validation.client.impl.AbstractGwtValidator;
import com.val.entity.*;
public final class SampleValidatorFactory extends AbstractGwtValidatorFactory {
#GwtValidation(Pravform.class)
public interface GwtValidator extends Validator {
}
#Override
public AbstractGwtValidator createValidator() {
return GWT.create(GwtValidator.class);
}
}
Main.java
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import com.val.entity.Pravform;
public class Main implements EntryPoint {
Pravform newPravform = new Pravform(pfNameTextBox.getText());
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Pravform>> violations = validator.validate(newPravform);
if (!violations.isEmpty()) {
tempLabel.setText("Error");
}
...
Main.gwt.xml
....
<inherits name="org.hibernate.validator.HibernateValidator" />
<replace-with
class="com.val.client.SampleValidatorFactory">
<when-type-is class="javax.validation.ValidatorFactory" />
</replace-with>
....
Please, help me to resolve this problem.