public boolean isValid(Object value, ConstraintValidatorContext context) { boolean returnValue = false; try { Comparable first = (Comparable) getNestedProperty(value, property); Object second = getNestedProperty(value, otherProperty); if (first == null) { returnValue = true; } else if (second != null) { returnValue = doComparison(first, second, comparison); } // Wenn first != null und second == null: Prüfung würde NPE bewirken, einfach false zurückgeben. } catch (Exception e) { throw new ValidationException("Cannot read property " + property + " and comparison property " + otherProperty); } if (!returnValue) { createViolationMessageForNestedProperty(property, messageTemplate, context); } return returnValue; }
/** * Validates the {@code request} based on its type and returns it or throws a {@code ValidationException} * if any {@link ConstraintViolation} is found. * * @param request the request object to validate * @param <T> request type param * @return The validated request(the same object passed as {@code request}) * @throws ValidationException if any {@link ConstraintViolation} is found */ public static <T extends SafechargeBaseRequest> T validate(T request) throws ValidationException { Set<ConstraintViolation<T>> constraintViolations = validator.validate(request); if (constraintViolations != null && !constraintViolations.isEmpty()) { StringBuilder sb = new StringBuilder(); for (ConstraintViolation<T> constraintViolation : constraintViolations) { sb.append(constraintViolation.getMessage()) .append(" "); } String errorMessage = sb.toString(); if (logger.isDebugEnabled()) { logger.debug(errorMessage); } throw new ConstraintViolationException(constraintViolations); } return request; }
@Override @SuppressWarnings("unchecked") public PaginatedList<RouterDto> list(PagingRequest request) throws CommsRouterException { return transactionManager.execute(em -> { String countString = "SELECT COUNT(id) FROM Router"; long totalCount = (long) em.createQuery(countString).getSingleResult(); int startPosition = (request.getPage() * request.getPerPage()) - request.getPerPage(); if (totalCount > 0 && totalCount <= startPosition) { throw new ValidationException("{resource.list.max.page.number}"); } String qlString = "SELECT r FROM Router r"; List<Router> jpaResult = em.createQuery(qlString) .setFirstResult(startPosition) .setMaxResults(request.getPerPage()) .getResultList(); return new PaginatedList<>(request, entityMapper.toDto(jpaResult), totalCount); }); }
@Override public void deleteAppRole(String id) { AppRole role = appRoleRepository.findById(id); if (role == null) { return; } if (relationshipRepository.findFirstByRole(role) != null) { throw new RoleException("该角色下已绑定用户,请解除和用户的关系后再进行删除角色操作"); } if (roleReferenceList != null) { roleReferenceList.forEach(ref -> { if (ref.hasReference(role)) { throw new ValidationException("该数据已经被其他数据引用,不能删除"); } }); } appRoleRepository.delete(role); }
private static MinijaxConstraintDescriptor<NotEmpty> buildNotEmptyValidator(final NotEmpty notEmpty, final Class<?> valueClass) { if (valueClass.isArray()) { return new MinijaxConstraintDescriptor<>(notEmpty, NotEmptyValidatorForArray.INSTANCE); } if (CharSequence.class.isAssignableFrom(valueClass)) { return new MinijaxConstraintDescriptor<>(notEmpty, NotEmptyValidatorForCharSequence.INSTANCE); } if (Collection.class.isAssignableFrom(valueClass)) { return new MinijaxConstraintDescriptor<>(notEmpty, NotEmptyValidatorForCollection.INSTANCE); } if (Map.class.isAssignableFrom(valueClass)) { return new MinijaxConstraintDescriptor<>(notEmpty, NotEmptyValidatorForMap.INSTANCE); } throw new ValidationException("Unsupported type for @NotEmpty annotation: " + valueClass); }
private static MinijaxConstraintDescriptor<Size> buildSizeValidator(final Size size, final Class<?> valueClass) { if (valueClass.isArray()) { return new MinijaxConstraintDescriptor<>(size, new SizeValidatorForArray(size)); } if (CharSequence.class.isAssignableFrom(valueClass)) { return new MinijaxConstraintDescriptor<>(size, new SizeValidatorForCharSequence(size)); } if (Collection.class.isAssignableFrom(valueClass)) { return new MinijaxConstraintDescriptor<>(size, new SizeValidatorForCollection(size)); } if (Map.class.isAssignableFrom(valueClass)) { return new MinijaxConstraintDescriptor<>(size, new SizeValidatorForMap(size)); } throw new ValidationException("Unsupported type for @Size annotation: " + valueClass); }
private static void assertValidationException( final boolean shouldFail, final String huntingParty, final Required r, final HuntingAreaType huntingAreaType) { try { r.validateHuntingParty(huntingParty, huntingAreaType); if (shouldFail) { fail("Exception should have happend"); } } catch (final ValidationException iex) { if (!shouldFail) { fail("Unexpected exception: " + iex); } } catch (final Exception e) { fail("Unexpected exception thrown: " + e); } }
public RouteDefinition(String text) { int eqIdx = text.indexOf("="); if (eqIdx <= 0) { throw new ValidationException("Unable to parse RouteDefinition text '" + text + "'" + ", must be of the form name=value"); } setId(text.substring(0, eqIdx)); String[] args = tokenizeToStringArray(text.substring(eqIdx+1), ","); setUri(URI.create(args[0])); for (int i=1; i < args.length; i++) { this.predicates.add(new PredicateDefinition(args[i])); } }
@Override public Response toResponse(ValidationException e) { ApiErrorCode errorCode = ApiErrorCode.PARAM_ERROR; StringBuffer errorMsgBuf = new StringBuffer(); final ConstraintViolationException cve = (ConstraintViolationException) e; List<ValidationError> errors = ValidationHelper.constraintViolationToValidationErrors(cve); for (ValidationError error : errors) { errorMsgBuf.append(error.getMessage()).append(";"); } String errorMsg = errorMsgBuf.toString(); if (StringUtils.isBlank(errorMsg)) { errorMsg = IMConstant.MSG_PARAM_ERROR; } String requestId = RequestContext.get("requestId"); ApiErrorCodeException errorCodeException = new ApiErrorCodeException(requestId, errorCode, errorMsg, e); logger.error(requestId, errorCodeException); return RestResult.failure(requestId, errorCode.errorCode, errorMsg); }
@Test public void testLocalityValidation() { TestGeneratorInputOperator input1 = dag.addOperator("input1", TestGeneratorInputOperator.class); GenericTestOperator o1 = dag.addOperator("o1", GenericTestOperator.class); StreamMeta s1 = dag.addStream("input1.outport", input1.outport, o1.inport1).setLocality(Locality.THREAD_LOCAL); dag.validate(); TestGeneratorInputOperator input2 = dag.addOperator("input2", TestGeneratorInputOperator.class); dag.addStream("input2.outport", input2.outport, o1.inport2); try { dag.validate(); Assert.fail("Exception expected for " + o1); } catch (ValidationException ve) { Assert.assertThat("", ve.getMessage(), RegexMatcher.matches("Locality THREAD_LOCAL invalid for operator .* with multiple input streams .*")); } s1.setLocality(null); dag.validate(); }
@Override public void setup(DAGSetupPlugin.Context context) { this.dag = context.getDAG(); try { this.path = context.getConfiguration().get("propertyVisitor.Path"); Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream(path)); for (Map.Entry<Object, Object> entry : properties.entrySet()) { propertyMap.put(entry.getKey().toString(), entry.getValue().toString()); } } catch (IOException ex) { throw new ValidationException("Not able to load input file " + path); } context.register(PRE_VALIDATE_DAG, this); }
public void validate() throws ValidationException { if (accumulation == null) { throw new ValidationException("Accumulation must be set"); } if (dataStorage == null) { throw new ValidationException("Data storage must be set"); } if (windowStateMap == null) { throw new ValidationException("Window state storage must be set"); } if (triggerOption != null) { if (triggerOption.isFiringOnlyUpdatedPanes()) { if (retractionStorage == null) { throw new ValidationException("A retraction storage is required for firingOnlyUpdatedPanes option"); } if (triggerOption.getAccumulationMode() == TriggerOption.AccumulationMode.DISCARDING) { throw new ValidationException("DISCARDING accumulation mode is not valid for firingOnlyUpdatedPanes option"); } } if (triggerOption.getAccumulationMode() == TriggerOption.AccumulationMode.ACCUMULATING_AND_RETRACTING && retractionStorage == null) { throw new ValidationException("A retraction storage is required for ACCUMULATING_AND_RETRACTING accumulation mode"); } } }
private void create(User user, Set<Test> tests, TestSuite parent) throws NotFoundException, ValidationException { for (final Test test : tests) { if (parent != null) { test.setParent(parent); } if (test instanceof TestCase) { create(user, test); } else { final TestSuite testSuite = (TestSuite) test; final Set<Test> testsInSuite = testSuite.getTests(); testSuite.setTests(new HashSet<>()); create(user, testSuite); create(user, testsInSuite, testSuite); } } }
@Override @Transactional public void delete(User user, Long projectId, Long id) throws NotFoundException, ValidationException { if (id == 0) { throw new ValidationException("The root test suite cannot be deleted"); } Test test = get(user, projectId, id); Test parent = test.getParent(); if (parent != null) { ((TestSuite) parent).getTests().remove(test); test.setParent(null); } testRepository.delete(test); }
/** * Create a test. * * @param projectId The id of the project to create the test in. * @param test The test to create. * @return The created test. * @throws NotFoundException If the project with the given id could not be found. */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createTest(@PathParam("project_id") Long projectId, Test test) throws NotFoundException { User user = ((UserPrincipal) securityContext.getUserPrincipal()).getUser(); test.setProjectId(projectId); try { testDAO.create(user, test); return Response.ok(test).status(Response.Status.CREATED).build(); } catch (ValidationException e) { return ResourceErrorHandler.createRESTErrorMessage("TestCase.create", Response.Status.BAD_REQUEST, e); } }
@Override public Validator create() { if (failed) { return null; } else { try { return Validation.buildDefaultValidatorFactory().getValidator(); } catch (final ValidationException e) { LOGGER.info("No implementaion for javax.validation (bean balidation) found " + Validator.class.getName() + ". Bean validation anotations will have no effect!", e); failed = true; return null; } } }
/** * Create a new group. * * @param projectId * The ID of the project. * @param group * The group to create. * @return On success the added group (enhanced with information from the DB); an error message on failure. * @throws NotFoundException If the related Project could not be found. * @responseType de.learnlib.alex.data.entities.SymbolGroup * @successResponse 201 created * @errorResponse 400 bad request `de.learnlib.alex.common.utils.ResourceErrorHandler.RESTError */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createGroup(@PathParam("project_id") long projectId, SymbolGroup group) throws NotFoundException { User user = ((UserPrincipal) securityContext.getUserPrincipal()).getUser(); LOGGER.traceEntry("createGroup({}, {}) for user {}.", projectId, group, user); try { group.setProjectId(projectId); symbolGroupDAO.create(user, group); LOGGER.traceExit(group); String groupURL = uri.getBaseUri() + "projects/" + group.getProjectId() + "/groups/" + group.getId(); return Response.status(Response.Status.CREATED).header("Location", groupURL).entity(group).build(); } catch (ValidationException e) { LOGGER.traceExit(e); return ResourceErrorHandler.createRESTErrorMessage("SymbolGroupResource.create", Response.Status.BAD_REQUEST, e); } }
default P checkDuplicateAndCreate(final P entity, final User user) { final Long RADIUS = 10l; Optional<P> entityWithSameName = findNameDuplicateForOwner(user, entity.getName()); if (entityWithSameName.isPresent()) { // Find 1 entity within {radius} meters around entity.location, owned by user Collection<P> entitiesWithSameNameWithinRange = find( entity.getLocation(), RADIUS, Collections.<String>emptyList(), // tags Optional.of(entity.getName()), Optional.absent(), // street Collections.<Place.Subcategory>emptyList(), // subs Optional.absent(), // paid Optional.absent(), // open Optional.of(user), // owner Optional.of(0), // first page 1); // 1 result if (!entitiesWithSameNameWithinRange.isEmpty()) { throw new ValidationException(String.format("Entity name duplicate within %d meters.", RADIUS)); } } return createWithOwner(entity, user); }
private String getOAuthToken(@QueryParam("state") String state, @QueryParam("code") String code) throws UnsupportedEncodingException, NamingException { InitialContext initialContext = new InitialContext(); String clientId = (String) initialContext.lookup("gitHubClientId"); String clientSecret = (String) initialContext.lookup("gitHubClientSecret"); String oauthUrl = "https://github.com/login/oauth/access_token?client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + code + "&state=" + state; log.info("Requesting token from " + oauthUrl); javax.json.JsonObject oAuthTokenInfo = ClientBuilder .newClient() .target(oauthUrl) .request(MediaType.APPLICATION_JSON_TYPE) .post(null, javax.json.JsonObject.class); String oAuthToken = oAuthTokenInfo.getString("access_token"); if (oAuthToken == null || oAuthToken.length() == 0) { log.severe("No oAuthToken passed in."); throw new ValidationException(); } oAuthToken = URLEncoder.encode(oAuthToken, StandardCharsets.UTF_8.name()); return oAuthToken; }
@Test(expected = ValidationException.class) public void shouldFailToCreateASymbolsWithADuplicateNameWithinOneProject() throws NotFoundException { User user = new User(); user.setId(USER_ID); Project project = new Project(); project.setUser(user); project.setId(PROJECT_ID); SymbolGroup group = new SymbolGroup(); group.setId(GROUP_ID); Symbol symbol = new Symbol(); symbol.setProject(project); symbol.setGroup(group); symbol.setName("Test"); Symbol symbol2 = new Symbol(); symbol2.setProject(project); symbol2.setGroup(group); symbol2.setName("Test"); given(symbolRepository.getSymbolByName(PROJECT_ID, "Test")).willReturn(symbol2); symbolDAO.create(user, symbol); // should fail }
@Test(expected = ValidationException.class) public void shouldHandleDataIntegrityViolationExceptionOnSymbolUpdateGracefully() throws NotFoundException { User user = new User(); user.setId(USER_ID); // Project project = new Project(); project.setUser(user); project.setId(PROJECT_ID); // SymbolGroup group = new SymbolGroup(); group.setId(GROUP_ID); // Symbol symbol = new Symbol(); symbol.setProject(project); symbol.setGroup(group); // // given(symbolGroupRepository.findOneByProject_IdAndId(USER_ID, PROJECT_ID, GROUP_ID)) // .willReturn(group); given(symbolRepository.findOne(PROJECT_ID, symbol.getId())).willReturn(symbol); given(symbolRepository.save(symbol)).willThrow(DataIntegrityViolationException.class); symbolDAO.update(user, symbol); // should fail }
@Test(expected = ValidationException.class) public void shouldHandleDataIntegrityViolationExceptionOnGroupCreationGracefully() throws NotFoundException { User user = new User(); user.setId(USER_ID); // Project project = new Project(); project.setId(PROJECT_ID); // SymbolGroup group = new SymbolGroup(); group.setProject(project); // given(projectDAO.getByID(USER_ID, PROJECT_ID, ProjectDAO.EmbeddableFields.ALL)).willReturn(project); given(symbolGroupRepository.save(group)).willThrow(DataIntegrityViolationException.class); symbolGroupDAO.create(user, group); // should fail }
@Test(expected = ValidationException.class) public void shouldHandleDataIntegrityViolationExceptionOnGroupUpdateGracefully() throws NotFoundException { User user = new User(); user.setId(USER_ID); // Project project = new Project(); project.setId(PROJECT_ID); // SymbolGroup group = new SymbolGroup(); group.setId(GROUP_ID); group.setProject(project); // given(symbolGroupRepository.findOneByProject_IdAndId(PROJECT_ID, GROUP_ID)) .willReturn(group); given(symbolGroupRepository.save(group)).willThrow(DataIntegrityViolationException.class); symbolGroupDAO.update(user, group); // should fail }
@Test(expected = ValidationException.class) public void shouldHandleConstraintViolationExceptionOnCounterUpdateGracefully() throws NotFoundException { User user = new User(); user.setId(USER_ID); // Project project = new Project(); project.setId(PROJECT_ID); // Counter counter = new Counter(); counter.setProject(project); counter.setName(COUNTER_NAME); // given(projectDAO.getByID(USER_ID, PROJECT_ID)).willReturn(project); given(counterRepository.findByProjectAndName(project, COUNTER_NAME)).willReturn(counter); given(counterRepository.save(counter)).willThrow(ConstraintViolationException.class); counterDAO.update(user, counter); // should fail }
public void save() { try { BookBC.defineEmptyValuesAsNull(this.book); BookBC.save(this.book); WebHelper.setSessionAttribute(SessionKey.INFO_MESSAGE.name(), "Book saved successfuly."); logger.info("Book with id " + this.book.getId() + " saved successfuly."); WebHelper.removeSessionAttribute("book.id"); WebHelper.setSessionAttribute("bible.id", this.book.getBible().getId()); String url = UrlHelper.buildWebAppUrl("app/books"); WebHelper.sendRedirect(url); } catch (ValidationException ex) { logger.warn("Book bean validation has failed."); } }
@Test(expected = ValidationException.class) public void shouldNotSaveALearnerResultWithATestNo() { User user = new User(); // Project project = new Project(); // LearnerResult result = new LearnerResult(); result.setProject(project); result.setTestNo(0L); try { learnerResultDAO.create(user, result); // should fail } catch (NotFoundException e) { e.printStackTrace(); } }
@Test(expected = ValidationException.class) public void shouldThrowAnExceptionIfTheTestResultToDeleteIsActive() throws NotFoundException { User user = new User(); // Project project = new Project(); project.setId(PROJECT_ID); // LearnerResult result = new LearnerResult(); result.setProject(project); result.setTestNo(0L); Long[] testNos = new Long[]{0L, 1L}; // LearnerStatus status = new LearnerStatus(result, Learner.LearnerPhase.LEARNING, new ArrayList<>()); given(learner.getStatus(PROJECT_ID)).willReturn(status); learnerResultDAO.delete(learner, PROJECT_ID, testNos); // should fail }
public boolean isValid(Object value, ConstraintValidatorContext context) { boolean returnValue = true; try { Object first = getNestedProperty(value, property); Object second = getNestedProperty(value, verifyValue); returnValue = first == null && second == null || first != null && first.equals(second); } catch (Exception e) { throw new ValidationException("Cannot read property " + property + " and verification " + verifyValue, e); } if (!returnValue) { createViolationMessageForNestedProperty(verifyValue, messageTemplate, context); } return returnValue; }
protected void validateRequest(SafechargeBaseRequest request) { try { ValidationUtils.validate(request); } catch (ValidationException e) { Assert.fail(); } }
private Mono<Void> checkAuthorityDoesntExist(User user, Authority authority) { Mono<Void> error = Mono.error(new ValidationException(String.format("User %s already has authority %s", user, authority))); return user.getAuthorities() .stream() .filter(a -> a.equals(authority)) .findAny() .map(e -> error) .orElse(Mono.empty()); }
private Mono<?> checkAuthorityExist(User user, Authority authority) { Mono<Object> error = Mono.error(new ValidationException(String.format("User %s has not authority %s", user, authority))); return user.getAuthorities() .stream() .filter(a -> a.equals(authority)) .findAny() .map(e -> Mono.empty()) .orElse(error); }
@Override public ErrorResponse toErrorResponse(ValidationException exception) { logger.warn("a ValidationException occured", exception); return ExceptionMapperHelper.toErrorResponse(exception, HttpStatus.UNPROCESSABLE_ENTITY_422, META_TYPE_VALUE); }
@Test public void testValidationException() { Project project = new Project(); project.setId(1L); // trigger ValidationException project.setName(ValidationException.class.getSimpleName()); try { projectRepo.create(project); } catch (ValidationException e) { Assert.assertEquals("messageKey", e.getMessage()); } }
/** * 检查参数是否符合注解(用户自行加的验证注解) * * @param params 参数 * @throws ValidationException 当参数不符合规定时抛出该异常 */ public void check(Object[] params) throws ValidationException { Set<ConstraintViolation<T>> methodValidators = executableValidator.validateParameters(instance, resourceMethod, params); for (ConstraintViolation<T> constraintViolation : methodValidators) { throw new ValidationException(constraintViolation.getMessage()); } }
@Override @SuppressWarnings("unchecked") public PaginatedList<DTOT> list(String routerRef, int page, int perPage) throws CommsRouterException { return app.db.transactionManager.execute((em) -> { String simpleName = entityClass.getSimpleName(); String countString = "SELECT COUNT(e.id) FROM " + simpleName + " e " + "JOIN e.router r WHERE r.ref = :routerRef ORDER BY r.id"; long totalCount = (long) em.createQuery(countString) .setParameter("routerRef", routerRef) .getSingleResult(); int startPosition = (page * perPage) - perPage; if (totalCount > 0 && totalCount <= startPosition) { throw new ValidationException("{resource.list.max.page.number}"); } String qlString = "SELECT e FROM " + simpleName + " e JOIN e.router r " + "WHERE r.ref = :routerRef ORDER BY r.id"; List<ENTITYT> jpaResult = em.createQuery(qlString) .setParameter("routerRef", routerRef) .setFirstResult(startPosition) .setMaxResults(perPage) .getResultList(); return new PaginatedList<>(entityMapper.toDto(jpaResult), page, perPage, totalCount); }); }
@Override public void afterPropertiesSet() { try { super.afterPropertiesSet(); } catch (ValidationException ex) { LogFactory.getLog(getClass()).debug("Failed to set up a Bean Validation provider", ex); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) private static <T extends Annotation> MinijaxConstraintDescriptor<T> buildDeclaredValidator(final T annotation, final Class validatedBy) { final Class<? extends ConstraintValidator<T, ?>> c = validatedBy; try { return new MinijaxConstraintDescriptor<>(annotation, c.getConstructor().newInstance()); } catch (final ReflectiveOperationException ex) { throw new ValidationException(ex); } }
private static MinijaxConstraintDescriptor<AssertFalse> buildAssertFalseValidator(final AssertFalse assertFalse, final Class<?> valueClass) { if (valueClass == boolean.class || valueClass == Boolean.class) { return new MinijaxConstraintDescriptor<>(assertFalse, AssertFalseValidator.INSTANCE); } throw new ValidationException("Unsupported type for @AssertFalse annotation: " + valueClass); }
private static MinijaxConstraintDescriptor<AssertTrue> buildAssertTrueValidator(final AssertTrue assertTrue, final Class<?> valueClass) { if (valueClass == boolean.class || valueClass == Boolean.class) { return new MinijaxConstraintDescriptor<>(assertTrue, AssertTrueValidator.INSTANCE); } throw new ValidationException("Unsupported type for @AssertTrue annotation: " + valueClass); }
private static MinijaxConstraintDescriptor<Max> buildMaxValidator(final Max max, final Class<?> valueClass) { if ((valueClass.isPrimitive() && valueClass != boolean.class) || Number.class.isAssignableFrom(valueClass)) { return new MinijaxConstraintDescriptor<>(max, new MaxValidator(max)); } throw new ValidationException("Unsupported type for @Min annotation: " + valueClass); }