public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception { String methodClassName = clazz.getName() + "_" + toUpperMethoName(methodName); Class<?> methodClass = null; try { methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { } Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>(); Method method = clazz.getMethod(methodName, parameterTypes); Object parameterBean = getMethodParameterBean(clazz, method, arguments); if (parameterBean != null) { if (methodClass != null) { violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass)); } else { violations.addAll(validator.validate(parameterBean, Default.class, clazz)); } } for (Object arg : arguments) { validate(violations, arg, clazz, methodClass); } if (violations.size() > 0) { throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); } }
/** * Valida vo de pessoa informado * @param pessoaVO2 */ public boolean validatePessoa(PessoaVO pessoaVO2) { boolean isValid = true; Validator validator = validatorFactory.getValidator(); Set<ConstraintViolation<PessoaVO>> constraints = validator.validate(pessoaVO2, Default.class,VGroupUsuario.class); if(CollectionUtils.isNotEmpty(constraints)){ FacesContext context = FacesContext.getCurrentInstance(); for (ConstraintViolation<PessoaVO> constraintViolation : constraints) { context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, constraintViolation.getMessage(), constraintViolation.getMessage())); isValid=false; } } return isValid; }
@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()); }
/** * 校验实体对象,校验所有标识属性 * @param obj * @param validateHandler 校验回调 * @param <T> * @return */ public static <T> ValidateResult validateEntity(T obj, ValidateHandler validateHandler) { ValidateResult result = new ValidateResult(); Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class); if( CollectionUtils.isNotEmpty(set) ){ result.setHasErrors(true); Map<String, String> errorMsg = new HashMap<String,String>(); for(ConstraintViolation<T> cv : set){ errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage()); } result.setErrorMsg(errorMsg); } if(validateHandler != null) { validateHandler.callback(obj, result); } return result; }
/** * 校验实体对象,校验所有不为null的标识属性 * @param obj * @return */ public static <T> ValidateResult validateEntitySelective(T obj, ValidateHandler validateHandler) { ValidateResult result = new ValidateResult(); List<Field> fields = ReflectUtil.getNotNullFields(obj); if(fields != null && !fields.isEmpty()) { Map<String, String> errorMsg = new LinkedHashMap<String, String>(); for(Field field : fields){ Set<ConstraintViolation<T>> set = validator.validateProperty(obj, field.getName(), Default.class); if( CollectionUtils.isNotEmpty(set) ){ result.setHasErrors(true); for(ConstraintViolation<T> cv : set){ errorMsg.put(field.getName(), cv.getMessage()); } } } result.setErrorMsg(errorMsg.isEmpty() ? null : errorMsg); } if(validateHandler != null) { validateHandler.callback(obj, result); } return result; }
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception { String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName); Class<?> methodClass = null; try { methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { } Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>(); Method method = clazz.getMethod(methodName, parameterTypes); Object parameterBean = getMethodParameterBean(clazz, method, arguments); if (parameterBean != null) { if (methodClass != null) { violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass)); } else { violations.addAll(validator.validate(parameterBean, Default.class, clazz)); } } for (Object arg : arguments) { validate(violations, arg, clazz, methodClass); } if (violations.size() > 0) { throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); } }
@Override public Integration create(@Context SecurityContext sec, @ConvertGroup(from = Default.class, to = AllValidations.class) final Integration integration) { Date rightNow = new Date(); Integration encryptedIntegration = encryptionSupport.encrypt(integration); IntegrationRevision revision = IntegrationRevision .createNewRevision(encryptedIntegration) .withCurrentState(IntegrationRevisionState.Draft); Integration updatedIntegration = new Integration.Builder() .createFrom(encryptedIntegration) .deployedRevisionId(revision.getVersion()) .addRevision(revision) .userId(SecurityContextHolder.getContext().getAuthentication().getName()) .statusMessage(Optional.empty()) .lastUpdated(rightNow) .createdDate(rightNow) .currentStatus(determineCurrentStatus(encryptedIntegration)) .userId(sec.getUserPrincipal().getName()) .stepsDone(new ArrayList<>()) .build(); return Creator.super.create(sec, updatedIntegration); }
@Override public void update(String id, @ConvertGroup(from = Default.class, to = AllValidations.class) Integration integration) { Integration existing = Getter.super.get(id); Status currentStatus = determineCurrentStatus(integration); IntegrationRevision currentRevision = IntegrationRevision.deployedRevision(existing) .withCurrentState(IntegrationRevisionState.from(currentStatus)) .withTargetState(IntegrationRevisionState.from(integration.getDesiredStatus().orElse(Status.Pending))); Integration updatedIntegration = new Integration.Builder() .createFrom(encryptionSupport.encrypt(integration)) .deployedRevisionId(existing.getDeployedRevisionId()) .lastUpdated(new Date()) .currentStatus(currentStatus) .addRevision(currentRevision) .stepsDone(new ArrayList<>()) .build(); Updater.super.update(id, updatedIntegration); }
@Override public void update(final String id, @ConvertGroup(from = Default.class, to = AllValidations.class) final Connection connection) { // Lets make sure we store encrypt secrets. Map<String, String> configuredProperties =connection.getConfiguredProperties(); if( connection.getConnectorId().isPresent() ) { Map<String, ConfigurationProperty> connectorProperties = getConnectorProperties(connection.getConnectorId().get()); configuredProperties = encryptionComponent.encryptPropertyValues(configuredProperties, connectorProperties); } final Connection updatedConnection = new Connection.Builder() .createFrom(connection) .configuredProperties(configuredProperties) .lastUpdated(new Date()) .build(); Updater.super.update(id, updatedConnection); }
public static <T> ValidationResult validateProperty(T obj, String propertyName) { ValidationResult result = new ValidationResult(); Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class); if (CollectionUtils.isNotEmpty(set)) { result.setHasErrors(true); Map<String, String> errorMsg = Maps.newHashMap(); for (ConstraintViolation<T> cv : set) { errorMsg.put(propertyName, cv.getMessage()); } result.setErrorMsg(errorMsg); } return result; }
@Test public void shouldAddExtraLoggingDetailsForClientDataValidationError() { ConstraintViolation<Object> violation1 = setupConstraintViolation(SomeValidatableObject.class, "path.to.violation1", NotNull.class, "MISSING_EXPECTED_CONTENT"); ConstraintViolation<Object> violation2 = setupConstraintViolation(Object.class, "path.to.violation2", NotEmpty.class, "TYPE_CONVERSION_ERROR"); ClientDataValidationError ex = new ClientDataValidationError( Arrays.asList(new SomeValidatableObject("someArg1", "someArg2"), new Object()), Arrays.asList(violation1, violation2), new Class<?>[] {Default.class, SomeValidationGroup.class} ); List<Pair<String, String>> extraLoggingDetails = new ArrayList<>(); listener.processClientDataValidationError(ex, extraLoggingDetails); assertThat(extraLoggingDetails, containsInAnyOrder( Pair.of("client_data_validation_failed_objects", SomeValidatableObject.class.getName() + "," + Object.class.getName()), Pair.of("validation_groups_considered", Default.class.getName() + "," + SomeValidationGroup.class.getName()), Pair.of("constraint_violation_details", "SomeValidatableObject.path.to.violation1|javax.validation.constraints.NotNull|MISSING_EXPECTED_CONTENT,Object.path.to.violation2|org.hibernate.validator.constraints" + ".NotEmpty|TYPE_CONVERSION_ERROR")) ); }
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception { String methodClassName = clazz.getName() + "_" + toUpperMethoName(methodName); Class<?> methodClass = null; try { methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException ignore) { } Set<ConstraintViolation<?>> violations = new HashSet<>(); Method method = clazz.getMethod(methodName, parameterTypes); Object parameterBean = getMethodParameterBean(clazz, method, arguments); if (parameterBean != null) { if (methodClass != null) { violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass)); } else { violations.addAll(validator.validate(parameterBean, Default.class, clazz)); } } for (Object arg : arguments) { validate(violations, arg, clazz, methodClass); } if (violations.size() > 0) { throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); } }
@Override public Integration create(@Context SecurityContext sec, @ConvertGroup(from = Default.class, to = AllValidations.class) final Integration integration) { Date rightNow = new Date(); Integration encryptedIntegration = encryptionSupport.encrypt(integration); IntegrationRevision revision = IntegrationRevision .createNewRevision(encryptedIntegration) .withCurrentState(IntegrationRevisionState.Draft); Integration updatedIntegration = new Integration.Builder() .createFrom(encryptedIntegration) .deployedRevisionId(revision.getVersion()) .addRevision(revision) .userId(SecurityContextHolder.getContext().getAuthentication().getName()) .statusMessage(Optional.empty()) .lastUpdated(rightNow) .createdDate(rightNow) .currentStatus(determineCurrentStatus(encryptedIntegration)) .userId(sec.getUserPrincipal().getName()) .build(); return Creator.super.create(sec, updatedIntegration); }
@Override public void update(String id, @ConvertGroup(from = Default.class, to = AllValidations.class) Integration integration) { Integration existing = Getter.super.get(id); Status currentStatus = determineCurrentStatus(integration); IntegrationRevision currentRevision = IntegrationRevision.deployedRevision(existing) .withCurrentState(IntegrationRevisionState.from(currentStatus)) .withTargetState(IntegrationRevisionState.from(integration.getDesiredStatus().orElse(Status.Pending))); Integration updatedIntegration = new Integration.Builder() .createFrom(encryptionSupport.encrypt(integration)) .deployedRevisionId(existing.getDeployedRevisionId()) .lastUpdated(new Date()) .currentStatus(currentStatus) .addRevision(currentRevision) .build(); Updater.super.update(id, updatedIntegration); }
public static <T> DataJsonResponse validateProperty(T obj, String propertyName) { DataJsonResponse result = new DataJsonResponse(); Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class); if (CollectionUtils.isNotEmpty(set)) { result.setStatus(StatusCode.SC_VALID_ERROR); StringBuffer errorMsg = new StringBuffer(); for (ConstraintViolation<T> cv : set) { errorMsg.append("arg:"); errorMsg.append(cv.getPropertyPath().toString()); errorMsg.append("error:"); errorMsg.append(cv.getMessage()); } result.setMessage(errorMsg.toString()); } return result; }
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception { String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName); Class<?> methodClass = null; try { methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { } Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>(); Method method = clazz.getMethod(methodName, parameterTypes); Object parameterBean = getMethodParameterBean(clazz, method, arguments); if (parameterBean != null) { if (methodClass != null) { violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass)); } else { violations.addAll(validator.validate(parameterBean, Default.class, clazz)); } } for (Object arg : arguments) { validate(violations, arg, clazz, methodClass); } if (violations.size() > 0) { JahhanException.throwException(400, JahhanErrorCode.VALIATION_EXCEPTION, violations.iterator().next().getMessageTemplate()); } }
/** * JAVADOC Method Level Comments */ @Test public void testThrowsBindExceptionAndHeaders() { Foo u1 = new Foo(); when(validator.validate(u1, Default.class, Create.class)) .thenReturn(Collections.<ConstraintViolation<Foo>>emptySet()); doThrow(new FatalBeanException("Oops")).when(conversionService) .convert(any(CsvlineWrapper.class), eq(Object.class)); try { rowProcessor.processRow("Foo", new String[] { "name", "value" }, new String[] { "Username", "BRYAN" }, 1); fail("Should throw bind exception"); } catch (BindException be) { // force a parse error, results in a bind exception assertEquals("loader.parseError", be.getAllErrors().get(0).getCode()); } }
/** * JAVADOC Method Level Comments */ @SuppressWarnings("unchecked") @Before public void setup() { MockitoAnnotations.initMocks(this); aliasPropertyMap = new HashMap<String, String>(); aliasPropertyMap.put(ID_ALIAS, ID_PROPERTY); aliasPropertyMap.put(VALUE_ALIAS, VALUE_PROPERTY); aliasPropertyMap.put(NAME_ALIAS, NAME_PROPERTY); factory = new SearchBeanFactoryImpl(); factory.setDefaultProjectionGroup(Default.class); Collection<Class<?>> classList = new ArrayList<Class<?>>(); classList.add(Foo.class); factory.setClassList(classList); factory.setCriteriaOverrides(Collections.EMPTY_MAP); }
/** * JAVADOC Method Level Comments */ // @Test public void testGetProjectionsB() { //these should be the same as the ones above List<ProjectionSeed> result = ProjectionSeed.getProjections(Annoited.class, Default.class); assertNotNull("result is null", result); ProjectionSeed bytes = (ProjectionSeed) CollectionUtils.find(result, new BeanPropertyValueEqualsPredicate("alias", "bytes")); assertNotNull("seed cannot be null", bytes); assertEquals("name.bytes", bytes.getProperty()); assertNull(CollectionUtils.find(result, new BeanPropertyValueEqualsPredicate("alias", "number"))); ProjectionSeed shortname = (ProjectionSeed) CollectionUtils.find(result, new BeanPropertyValueEqualsPredicate("alias", "short name")); assertEquals("name", shortname.getProperty()); assertNull(CollectionUtils.find(result, new BeanPropertyValueEqualsPredicate("alias", "lastDate"))); assertNull(CollectionUtils.find(result, new BeanPropertyValueEqualsPredicate("alias", "nextDate"))); }
/** * @param identifier * Set the sourceId * @param model * Set the model * @param session * Set the session * @param resource * Set the job * @param result * Set the binding results * @return a model and view */ @RequestMapping(method = RequestMethod.POST, produces = "text/html") public String create(Model model, @Validated({Default.class, ReadResource.class}) Resource resource, BindingResult result, RedirectAttributes redirectAttributes) { if (result.hasErrors()) { populateForm(model, resource, new ResourceParameterDto()); return "resource/create"; } logger.error("Creating Resource " + resource + " with organisation " + resource.getOrganisation()); getService().saveOrUpdate(resource); String[] codes = new String[] { "resource.was.created" }; Object[] args = new Object[] { resource.getTitle() }; DefaultMessageSourceResolvable message = new DefaultMessageSourceResolvable(codes, args); redirectAttributes.addFlashAttribute("info", message); return "redirect:/resource"; }
/** * Valida vo de pessoa informado * @param pessoaVO2 */ public boolean validatePessoa(PessoaVO pessoaVO2) { boolean isValid = true; Validator validator = validatorFactory.getValidator(); Set<ConstraintViolation<PessoaVO>> constraints = validator.validate(pessoaVO2, Default.class,VGroupUsuario.class); if(constraints==null){ FacesContext context = FacesContext.getCurrentInstance(); for (ConstraintViolation<PessoaVO> constraintViolation : constraints) { context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, constraintViolation.getMessage(), constraintViolation.getMessage())); isValid=false; } } return isValid; }