Java Code Examples for javax.validation.Validation

The following are top voted examples for showing how to use javax.validation.Validation. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GoHost   File: AbstractFacade.java   View source code 8 votes vote down vote up
public void create(T entity) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
    if(constraintViolations.size() > 0){
        Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
        while(iterator.hasNext()){
            ConstraintViolation<T> cv = iterator.next();
            System.err.println(cv.getRootBeanClass().getName()+"."+cv.getPropertyPath() + " " +cv.getMessage());

            System.err.println(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
        }
    }else{
        getEntityManager().persist(entity);
    }
}
 
Example 2
Project: java-notes   File: App.java   View source code 8 votes vote down vote up
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
	AutoRunHelper.run(App.class);
	
	// 测试参数校验
	App app = new App();
	
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	ExecutableValidator executableValidator = factory.getValidator().forExecutables();
	Method method = App.class.getMethod("showEmail", String.class);
	
	Object[] parameterValues = {"email"};
	Set<ConstraintViolation<App>> violations = executableValidator.validateParameters(app, method, parameterValues);
	String message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : "";
	System.out.println("values:" + parameterValues[0].toString() + " size: " + violations.size() + " msg:" + message);
	
	Object[] parameterValues2 = {"abc"};
	violations = executableValidator.validateParameters(app, method, parameterValues2);
	message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : "";
	System.out.println("values:" + parameterValues2[0].toString() + " size: " + violations.size() + " msg:" + message);

}
 
Example 3
Project: lambda-forest   File: DefaultRequestValidator.java   View source code 7 votes vote down vote up
@Override
public void validate(Object entity) throws HttpException {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<Object>> violations = validator.validate(entity);
    if (!violations.isEmpty()) {
        List<ConstraintViolationDescription> errors = new ArrayList<>();

        ConstraintViolationResponseError error = new ConstraintViolationResponseError();
        error.setMessage(UNPROCESSABLE_ENTITY_MESSAGE);

        for (ConstraintViolation<Object> violation : violations) {
            String attribute = violation.getPropertyPath().toString();
            String message = violation.getMessage();
            errors.add(new ConstraintViolationDescription(message, attribute));
        }

        error.setErrors(errors);
        throw new UnprocessableEntityException(error);
    }
    
}
 
Example 4
Project: java-validator-safeguard   File: TesteDeObjetosAnotados.java   View source code 6 votes vote down vote up
@Test
public void loads() {
	
	Pessoa pessoa = new Pessoa();
	pessoa.setNome("João da Silva");
	pessoa.setCpf("12345678901");
	pessoa.setTelefone("(11)3266-4455");
	pessoa.setEndereco("Rua A, 123, Bananal, Guarulhos - SP");
		
	Check check = new SafeguardCheck();
	
	/*Validação manual usando a interface Check*/
	Check resultados = check.elementOf(pessoa).validate();
	int quantidadeDeElementosInvalidos = resultados.getInvalidElements().size();
	boolean temErro = resultados.hasError();
		
	/*Validação pelo provedor de validação, usando javax.validation*/
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	javax.validation.Validator validator = factory.getValidator();
	Set<ConstraintViolation<Pessoa>> violacoes = validator.validate(pessoa, Default.class);
	
	Assert.assertEquals(1, quantidadeDeElementosInvalidos);
	Assert.assertEquals(true, temErro);
	Assert.assertEquals(1, violacoes.size());
			  
}
 
Example 5
Project: wall.e   File: Blog.java   View source code 6 votes vote down vote up
public static void main(String[] args) {

    String src = "src.org/hack/controller";
    src = src.replaceAll("/", File.separator + File.separator);
    System.out.println(src);
    System.out.println("src\\org\\hack\\controller");
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    System.out.println(factory.getMessageInterpolator().getClass());

    Validator validator = factory.getValidator();
    Blog blog = new Blog("1", "2121", "212", new Date(), 2);

    Set<ConstraintViolation<Blog>> constraintViolations = validator.validate(blog);
    System.out.println(validator.getClass());
    for (ConstraintViolation<Blog> c : constraintViolations) {
      System.out.println(c.getInvalidValue() + ":" + c.getMessage());
    }
  }
 
Example 6
Project: Java-9-Programming-Blueprints   File: AccountService.java   View source code 6 votes vote down vote up
public List<Account> getAccounts() {
    final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    final ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    List<Account> accounts = null;
    try {
        accounts = mapper.readValue(rulesFile, 
                new TypeReference<List<Account>>() {});
        if (accounts != null) {
            accounts.forEach((account) -> {
                final Set<ConstraintViolation<Account>> accountViolations = validator.validate(account);
                if (accountViolations.size() > 0) {
                    throw new AccountValidationException(accountViolations);
                }
                account.getRules().sort((o1, o2) -> o1.getType().compareTo(o2.getType()));
            });
        }
    } catch (IOException ex) {
        Logger.getLogger(AccountService.class.getName()).log(Level.SEVERE, null, ex);
    }

    return accounts;
}
 
Example 7
Project: crnk-framework   File: ValidationEndToEndTest.java   View source code 6 votes vote down vote up
@Test
public void testMapElementAttributeNotNull() {
	ProjectData data = new ProjectData();
	data.setValue(null); // violation

	Project project = new Project();
	project.setId(1L);
	project.setName("test");
	project.setDataMap(new LinkedHashMap());
	project.getDataMap().put("someKey", data);

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();

	try {
		projectRepo.create(project);
	} catch (ConstraintViolationException e) {
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		Assert.assertEquals(1, violations.size());
		ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next();
		Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate());
		Assert.assertEquals("dataMap[someKey].value", violation.getPropertyPath().toString());
		Assert.assertNotNull(violation.getMessage());
		Assert.assertEquals("/data/attributes/dataMap/someKey/value", violation.getErrorData().getSourcePointer());
	}
}
 
Example 8
Project: lams   File: CustomValidatorBean.java   View source code 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	if (this.validatorFactory == null) {
		this.validatorFactory = Validation.buildDefaultValidatorFactory();
	}

	ValidatorContext validatorContext = this.validatorFactory.usingContext();
	MessageInterpolator targetInterpolator = this.messageInterpolator;
	if (targetInterpolator == null) {
		targetInterpolator = this.validatorFactory.getMessageInterpolator();
	}
	validatorContext.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
	if (this.traversableResolver != null) {
		validatorContext.traversableResolver(this.traversableResolver);
	}

	setTargetValidator(validatorContext.getValidator());
}
 
Example 9
Project: KantaCDA-API   File: BeanValidator.java   View source code 5 votes vote down vote up
/**
 * Validoi annettu bean:in siinä annettuja BeanValidation annotaatio-ehtoja vasten.
 *
 * @param bean
 *            Validoitava bean.
 * @return Listaus löytyneistä validointivirheistä.
 */
public Set<ConstraintViolation<T>> doValidation(T bean) {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> errors = validator.validate(bean);
    return errors;
}
 
Example 10
Project: java-bean-validation-extension   File: SimpleValidation.java   View source code 5 votes vote down vote up
public static <T> void validate(T object) {

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> validatorSet = validator.validate(object);

        validatorSet.forEach(cv -> {
            throw new BeanValidationException(cv.getPropertyPath() + " - " + cv.getMessage());
        });
    }
 
Example 11
Project: EatDubbo   File: JValidator.java   View source code 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public JValidator(URL url) {
    this.clazz = ReflectUtils.forName(url.getServiceInterface());
    String jvalidation = url.getParameter("jvalidation");
    ValidatorFactory factory;
    if (jvalidation != null && jvalidation.length() > 0) {
        factory = Validation.byProvider((Class)ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory();
    } else {
        factory = Validation.buildDefaultValidatorFactory();
    }
    this.validator = factory.getValidator();
}
 
Example 12
Project: verify-hub   File: FileBackedTransactionConfigDataSource.java   View source code 5 votes vote down vote up
@Inject
public FileBackedTransactionConfigDataSource(ConfigConfiguration configuration,
                                             ConfigurationFactoryFactory<TransactionConfigEntityData> configurationFactoryFactory,
                                             ObjectMapper objectMapper) {
    super(
            configuration,
            configurationFactoryFactory.create(TransactionConfigEntityData.class,
                    Validation.buildDefaultValidatorFactory().getValidator(),
                    objectMapper,
                    "hub"),
            TRANSACTIONS_DATA_DIRECTORY
    );
}
 
Example 13
Project: verify-hub   File: FileBackedCountriesConfigDataSource.java   View source code 5 votes vote down vote up
@Inject
public FileBackedCountriesConfigDataSource(
        ConfigConfiguration configuration,
        ConfigurationFactoryFactory<CountriesConfigEntityData> configurationFactoryFactory,
        ObjectMapper objectMapper) {
    super(
            configuration,
            configurationFactoryFactory.create(CountriesConfigEntityData.class,
                    Validation.buildDefaultValidatorFactory().getValidator(),
                    objectMapper,
                    "hub"),
            COUNTRIES_DATA_DIRECTORY
    );
}
 
Example 14
Project: verify-hub   File: FileBackedMatchingServiceConfigDataSource.java   View source code 5 votes vote down vote up
@Inject
public FileBackedMatchingServiceConfigDataSource(
        ConfigConfiguration configuration,
        ConfigurationFactoryFactory<MatchingServiceConfigEntityData> configurationFactoryFactory,
        ObjectMapper objectMapper) {
    super(
            configuration,
            configurationFactoryFactory.create(MatchingServiceConfigEntityData.class,
                    Validation.buildDefaultValidatorFactory().getValidator(),
                    objectMapper,
                    "hub"),
            MATCHING_SERVICE_DATA_DIRECTORY
    );
}
 
Example 15
Project: verify-hub   File: FileBackedIdentityProviderConfigDataSource.java   View source code 5 votes vote down vote up
@Inject
public FileBackedIdentityProviderConfigDataSource(
        ConfigConfiguration configuration,
        ConfigurationFactoryFactory<IdentityProviderConfigEntityData> configurationFactoryFactory,
        ObjectMapper objectMapper) {
    super(
            configuration,
            configurationFactoryFactory.create(IdentityProviderConfigEntityData.class,
                    Validation.buildDefaultValidatorFactory().getValidator(),
                    objectMapper,
                    "hub"),
            IDENTITY_PROVIDER_DATA_DIRECTORY
    );
}
 
Example 16
Project: safecharge-java   File: BasePaymentCCTest.java   View source code 5 votes vote down vote up
@BeforeClass
public static void setup() {
    gson = new GsonBuilder().serializeNulls()
            .create();
    validator = Validation.buildDefaultValidatorFactory()
            .getValidator();
}
 
Example 17
Project: jmzTab-m   File: MzTabValidator.java   View source code 5 votes vote down vote up
@Override
public List<ValidationMessage> validate(MzTab mzTab) {
    List<ValidationMessage> list = new LinkedList<>();
    ValidatorFactory validatorFactory = Validation.byDefaultProvider()
            .configure()
            .buildValidatorFactory();
    javax.validation.Validator validator = validatorFactory.getValidator();
    Set<ConstraintViolation<MzTab>> violations = validator.validate(mzTab);
    for(ConstraintViolation<MzTab> violation:violations) {
        list.add(new ValidationMessage().message(getPathLocatorString(
            violation)+": "+violation.getMessage()).messageType(ValidationMessage.MessageTypeEnum.ERROR));
    }
    return list;
}
 
Example 18
Project: jmzTab-m   File: MzTabValidatorTest.java   View source code 5 votes vote down vote up
@Test
public void testDefaultMetadataBeanValidation() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<MzTab>> violations = validator.validate(
        createTestFile());
    for (ConstraintViolation<MzTab> violation : violations) {
        System.err.println("Validation error at " + violation.
            getPropertyPath().
            toString() + ": " + violation.getMessage());
    }
}
 
Example 19
Project: dubbo2   File: JValidator.java   View source code 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public JValidator(URL url) {
    this.clazz = ReflectUtils.forName(url.getServiceInterface());
    String jvalidation = url.getParameter("jvalidation");
    ValidatorFactory factory;
    if (jvalidation != null && jvalidation.length() > 0) {
        factory = Validation.byProvider((Class)ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory();
    } else {
        factory = Validation.buildDefaultValidatorFactory();
    }
    this.validator = factory.getValidator();
}
 
Example 20
Project: syndesis   File: ValidatorContextResolver.java   View source code 5 votes vote down vote up
@Override
public GeneralValidator getContext(final Class<?> type) {
    final ResourceBundleLocator resourceBundleLocator = new PlatformResourceBundleLocator("messages");
    final MessageInterpolator messageInterpolator = new ResourceBundleMessageInterpolator(resourceBundleLocator);
    final Configuration<?> config = Validation.byDefaultProvider().configure()
        .messageInterpolator(messageInterpolator);
    final BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration();
    final boolean isExecutableValidationEnabled = bootstrapConfiguration.isExecutableValidationEnabled();
    final Set<ExecutableType> defaultValidatedExecutableTypes = bootstrapConfiguration
        .getDefaultValidatedExecutableTypes();

    return new GeneralValidatorImpl(validatorFactory, isExecutableValidationEnabled,
        defaultValidatedExecutableTypes);
}
 
Example 21
Project: syndesis   File: IntegrationTest.java   View source code 5 votes vote down vote up
public IntegrationTest() {
    final DefaultConstraintMapping mapping = new DefaultConstraintMapping();
    mapping.constraintDefinition(UniqueProperty.class).validatedBy(UniqnenessValidator.class);
    final ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
        .addMapping(mapping).buildValidatorFactory();

    validator = validatorFactory.getValidator();
}
 
Example 22
Project: easybinder   File: BeanValidationBinderStringTest.java   View source code 5 votes vote down vote up
@Test
public void testValid() {
	TextField text = new TextField();

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();

	Binder<MyEntity> binder = new BeanValidationBinder<>(MyEntity.class);
	binder.forField(text).withNullRepresentation("").bind("text");

	MyEntity t = new MyEntity();

	// valid
	t.setText("bla");
	binder.setBean(t);

	assertTrue(validator.validate(t).isEmpty());
	assertTrue(binder.validate().isOk());

	text.setValue("");
	assertNull(t.getText());

	/*
	 * // invalid t.setText(""); binder.setBean(t);
	 * assertFalse(validator.validate(t).isEmpty());
	 * assertFalse(binder.validate().isOk());
	 * 
	 * t.setText(null); binder.setBean(t);
	 * assertTrue(validator.validate(t).isEmpty());
	 * assertTrue(binder.validate().isOk());
	 */
}
 
Example 23
Project: nifi-registry   File: TestRegistryService.java   View source code 5 votes vote down vote up
@Before
public void setup() {
    metadataService = mock(MetadataService.class);
    flowPersistenceProvider = mock(FlowPersistenceProvider.class);
    snapshotSerializer = mock(VersionedProcessGroupSerializer.class);

    final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    validator = validatorFactory.getValidator();

    registryService = new RegistryService(metadataService, flowPersistenceProvider, snapshotSerializer, validator);
}
 
Example 24
Project: java-microservice   File: TodoIT.java   View source code 5 votes vote down vote up
@Test
public void validateTodoValid() {
    ToDo toDo = new ToDo("[email protected]","caption", "description 1", 6);
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<ToDo>> constraintViolations = validator.validate(toDo);
    assertTrue(constraintViolations.isEmpty());       
}
 
Example 25
Project: esup-ecandidat   File: MethodUtils.java   View source code 5 votes vote down vote up
/**
 * Valide un bean
 * 
 * @param bean
 * @throws CustomException
 */
public static <T> Boolean validateBean(T bean, Logger logger) {
	logger.debug(" ***VALIDATION*** : " + bean);
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<T>> constraintViolations = validator.validate(bean);
	if (constraintViolations != null && constraintViolations.size() > 0) {
		for (ConstraintViolation<?> violation : constraintViolations) {
			logger.debug(" *** " + violation.getPropertyPath().toString() + " : " + violation.getMessage());
		}
		return false;
	}
	return true;
}
 
Example 26
Project: esup-ecandidat   File: IndividuController.java   View source code 5 votes vote down vote up
/** Valide un bean d'individu
 * @param ind
 * @throws CustomException
 */
public void validateIndividuBean(Individu ind) throws CustomException{
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<Individu>> constraintViolations = validator.validate(ind);
	if (constraintViolations!=null && constraintViolations.size() > 0) {
		String erreur = ""; 
		for (ConstraintViolation<?> violation : constraintViolations) {
			erreur += (" *** "+ violation.getPropertyPath().toString() + " : " + violation.getMessage());
		  }
		throw new CustomException(applicationContext.getMessage("droitprofil.individu.error", null, UI.getCurrent().getLocale())+" : "+erreur);
	}
}
 
Example 27
Project: automatic-mower   File: MowerPosition.java   View source code 5 votes vote down vote up
public MowerPosition(int x, int y, Direction direction, Lawn lawn) {
	this.x = x;
	this.y = y;
	this.direction = direction;
	this.lawn = lawn;
	this.vf = Validation.buildDefaultValidatorFactory();
}
 
Example 28
Project: aaden-pay   File: PaymentValidate.java   View source code 5 votes vote down vote up
private void validMust(PayRequest request) throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
	validator.validate(request.getMust());
	Set<ConstraintViolation<PayMustData>> validators = validator.validate(request.getMust());
	for (ConstraintViolation<PayMustData> constraintViolation : validators) {
		throw new Exception(constraintViolation.getMessage());
	}
}
 
Example 29
Project: aaden-pay   File: PaymentValidate.java   View source code 5 votes vote down vote up
private void validCash(PayRequest request) throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
	validator.validate(request.getCash());
	Set<ConstraintViolation<PayCashData>> validators = validator.validate(request.getCash());
	for (ConstraintViolation<PayCashData> constraintViolation : validators) {
		throw new Exception(constraintViolation.getMessage());
	}
}
 
Example 30
Project: aaden-pay   File: PaymentValidate.java   View source code 5 votes vote down vote up
private void validRecharge(PayRequest request) throws Exception {
	if (request.getSys().getPayType() == PayType.GATEWAY)
		return;
	Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
	validator.validate(request.getRecharge());
	Set<ConstraintViolation<PayRechargeData>> validators = validator.validate(request.getRecharge());
	for (ConstraintViolation<PayRechargeData> constraintViolation : validators) {
		throw new Exception(constraintViolation.getMessage());
	}
}
 
Example 31
Project: testing_security_development_enterprise_systems   File: NotStandardTest.java   View source code 5 votes vote down vote up
@Before
public void init() {
    emFactory = Persistence.createEntityManagerFactory("DB");
    em = emFactory.createEntityManager();

    valFactory = Validation.buildDefaultValidatorFactory();
    validator = valFactory.getValidator();
}
 
Example 32
Project: testing_security_development_enterprise_systems   File: UserTest.java   View source code 5 votes vote down vote up
@Before
public void init() {
    emFactory = Persistence.createEntityManagerFactory("DB");
    em = emFactory.createEntityManager();

    valFactory = Validation.buildDefaultValidatorFactory();
    validator = valFactory.getValidator();
}
 
Example 33
Project: dubbocloud   File: JValidator.java   View source code 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public JValidator(URL url) {
    this.clazz = ReflectUtils.forName(url.getServiceInterface());
    String jvalidation = url.getParameter("jvalidation");
    ValidatorFactory factory;
    if (jvalidation != null && jvalidation.length() > 0) {
        factory = Validation.byProvider((Class)ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory();
    } else {
        factory = Validation.buildDefaultValidatorFactory();
    }
    this.validator = factory.getValidator();
}
 
Example 34
Project: lams   File: BeanValidationEventListener.java   View source code 5 votes vote down vote up
public void initialize(Configuration cfg) {
	if ( !initialized ) {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Properties props = cfg.getProperties();
		init( factory, props );
	}
}
 
Example 35
Project: hibatis   File: EntityManagerImpl.java   View source code 5 votes vote down vote up
public EntityManagerImpl(SqlSessionFactory sqlSessionFactory) {
	super(sqlSessionFactory);
	try {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		this.validator = factory.getValidator();
	} catch (Exception e) {
		logger.warn("Unable to create  validator");
	}
}
 
Example 36
Project: WordnetLoom   File: PartOfSpeechServicesUTest.java   View source code 5 votes vote down vote up
@Before
public void initTestCase() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();

    partOfSpeechRepository = mock(PartOfSpeechRepository.class);

    partOfSpeechService = new PartOfSpeechServiceBean();
    partOfSpeechService.validator = validator;
    partOfSpeechService.partOfSpeechRepository = partOfSpeechRepository;
}
 
Example 37
Project: WordnetLoom   File: LocalisedServicesUTest.java   View source code 5 votes vote down vote up
@Before
public void initTestCase() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();

    repository = mock(LocalisedStringRepository.class);

    service = new LocalisedStringServiceBean();
    service.validator = validator;
    service.repository = repository;
}
 
Example 38
Project: WordnetLoom   File: LexiconServicesUTest.java   View source code 5 votes vote down vote up
@Before
public void initTestCase() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();

    lexiconRepository = mock(LexiconRepository.class);

    lexiconService = new LexiconServiceBean();
    lexiconService.validator = validator;
    lexiconService.lexiconRepository = lexiconRepository;
}
 
Example 39
Project: mafia   File: ValidatorUtil.java   View source code 5 votes vote down vote up
public static <E> void checkParam(E obj, Class mafExceptionClass, Integer respCode, Class... validateGroup) throws Exception
{
    ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    Validator validator = vf.getValidator();
    Set<ConstraintViolation<Object>> set = validator.validate(obj, validateGroup);
    for(ConstraintViolation<Object> cv : set)
    {
        Constructor constructor = mafExceptionClass.getConstructor(int.class, String.class);
        MafiaException mafException = (MafiaException) constructor.newInstance(respCode, cv.getMessage());
        throw mafException;
    }
}
 
Example 40
Project: WordnetLoom   File: RelationTypeServicesUTest.java   View source code 5 votes vote down vote up
@Before
public void initTestCase() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();

    repository = mock(RelationTypeRepository.class);

    service = new RelationTypeServiceBean();
    service.validator = validator;
    service.relationTypeRepository = repository;
}