@Override public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && (node.has("minItems") || node.has("maxItems"))) { JAnnotationUse annotation = field.annotate(Size.class); if (node.has("minItems")) { annotation.param("min", node.get("minItems").asInt()); } if (node.has("maxItems")) { annotation.param("max", node.get("maxItems").asInt()); } } return field; }
@RequestMapping(value = "/address", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<AddressResponse> address(@Valid @RequestBody AddressRequest addressRequest, @Valid @Size(max = Constants.UUID_CHAR_MAX_SIZE) @RequestHeader(value="Authorization") String authorizationHeader, @Context HttpServletRequest httpServletRequest) throws BaseException { // Get token String emailConfirmationToken = getEmailConfirmationToken(authorizationHeader); // Get IP address from request String ipAddress = httpServletRequest.getHeader("X-Real-IP"); if (ipAddress == null) ipAddress = httpServletRequest.getRemoteAddr(); LOG.info("/address called from {} with token {}, address {}, refundBTC {} refundETH {}", ipAddress, emailConfirmationToken, addressRequest.getAddress(), addressRequest.getRefundBTC(), addressRequest.getRefundETH()); return setWalletAddress(addressRequest, emailConfirmationToken); }
private void addJsr303Annotations(final INamedParam parameter, final JVar argumentVariable) { if (isNotBlank(parameter.getPattern())) { JAnnotationUse patternAnnotation = argumentVariable.annotate(Pattern.class); patternAnnotation.param("regexp", parameter.getPattern()); } final Integer minLength = parameter.getMinLength(); final Integer maxLength = parameter.getMaxLength(); if ((minLength != null) || (maxLength != null)) { final JAnnotationUse sizeAnnotation = argumentVariable .annotate(Size.class); if (minLength != null) { sizeAnnotation.param("min", minLength); } if (maxLength != null) { sizeAnnotation.param("max", maxLength); } } final BigDecimal minimum = parameter.getMinimum(); if (minimum != null) { addMinMaxConstraint(parameter, "minimum", Min.class, minimum, argumentVariable); } final BigDecimal maximum = parameter.getMaximum(); if (maximum != null) { addMinMaxConstraint(parameter, "maximum", Max.class, maximum, argumentVariable); } if (parameter.isRequired()) { argumentVariable.annotate(NotNull.class); } }
@Override public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) { if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations() && (node.has("minLength") || node.has("maxLength"))) { JAnnotationUse annotation = field.annotate(Size.class); if (node.has("minLength")) { annotation.param("min", node.get("minLength").asInt()); } if (node.has("maxLength")) { annotation.param("max", node.get("maxLength").asInt()); } } return field; }
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); }
/** * Check validation errors success for collections. */ @Test public void jsr349CollectionInvalid() { try { final SystemUser userDto = new SystemUser(); userDto.setLogin("junit"); validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("jsr349Collection"), Arrays.asList(Arrays.asList(userDto, userDto, userDto))); Assert.fail("Expected validation errors"); } catch (final ConstraintViolationException cve) { // Check all expected errors are there. final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations(); Assert.assertNotNull(constraintViolations); Assert.assertEquals(1, constraintViolations.size()); // Check expected errors final ConstraintViolation<?> error1 = constraintViolations.iterator().next(); Assert.assertEquals(Size.class, error1.getConstraintDescriptor().getAnnotation().annotationType()); Assert.assertEquals("jsr349Collection.params", error1.getPropertyPath().toString()); } }
private String createErrorMessage(Size sizeAnnotation, Message errorForLowerBound, Message errorForUpperBound) { StringBuilder errorMessageBuilder = new StringBuilder(); appendNotProperSizeErrorMessage(errorMessageBuilder); if (sizeAnnotation.min() != 0) { appendFormattedErrorMessage( errorMessageBuilder, errorForLowerBound, sizeAnnotation.min()); } if (sizeAnnotation.max() != Integer.MAX_VALUE) { appendFormattedErrorMessage( errorMessageBuilder, errorForUpperBound, sizeAnnotation.max()); } return errorMessageBuilder.toString(); }
@Override public Object process(AnnotationInfo ctx, Object value) throws Exception { if (!ctx.isAnnotationPresent(Size.class)) { return value; } long minValue = ctx.getAnnotation(Size.class).min(); if(minValue < 0 ) { minValue = 0; } long maxValue = ctx.getAnnotation(Size.class).max(); if( maxValue > 10000 ){ maxValue = 10000; } if (Number.class.isAssignableFrom(value.getClass())) { return range(String.valueOf(minValue), String.valueOf(maxValue), value.getClass()); } else if (value instanceof String) { return RandomStringUtils.randomAlphanumeric((int) minValue, (int) maxValue); } return value; }
@PostMapping("/login") public String login( @NotNull @Size(min = 1) String username, @NotNull @Size(min = 1) String password, Model model, HttpServletRequest request, HttpServletResponse response) throws UserApiException { LoginReq loginReq = new LoginReq(); loginReq.setUsername(username); loginReq.setPassword(password); loginReq.setClientId("web_admin"); loginReq.setClientVersion("1.0.0"); LoginResult loginResult = accountApi.login(loginReq); UserContext userContext = new UserContext(); userContext.setAccessToken(loginResult.getAccessToken()); userContextProcessor.initialize(userContext, request, response); return "redirect:/"; }
@RequestMapping(value = "compress") public ResponseMessage compress( @RequestParam("url") @Size(min = 20, max = 300, message = "url 长度不符合规定") String url) { String shortUrl = null; try { shortUrl = service.compress(url); } catch (Exception e) { e.printStackTrace(); logger.info("failed in compressing, unknown error"); return new ResponseMessage(shortUrl, url, false, "url is not valid"); } return new ResponseMessage(shortUrl, url, true, "succeed in compressing"); }
@Override @Id @Size(min = 16, max = 255) @Access(value = AccessType.PROPERTY) @Column(name = "token_data", nullable = false, length = 255) public String getId() { return id; }
@Test public void stringFieldsMustHaveExplicitAndConsistentLengthDefinition() { final Stream<Field> failedFields = filterFieldsOfManagedJpaTypes(field -> { final int modifiers = field.getModifiers(); if (String.class.isAssignableFrom(field.getType()) && !Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && !field.isAnnotationPresent(Transient.class) && !field.isAnnotationPresent(Lob.class)) { final Column column = field.getAnnotation(Column.class); final Size size = field.getAnnotation(Size.class); return column == null && !hasIdGetter(field) || column != null && size != null && column.length() != size.max(); } return false; }); assertNoFields(failedFields, "These entity fields should be explicitly annotated with @Column and @Size with consistency on " + "field's maximum length: "); }
@RequestMapping(value = "/register/{emailConfirmationToken}/validate", method = GET) public ResponseEntity<?> isConfirmationTokenValid(@Valid @Size(max = Constants.UUID_CHAR_MAX_SIZE) @PathVariable("emailConfirmationToken") String emailConfirmationToken, @Context HttpServletRequest httpServletRequest) throws BaseException { // Get IP address from request String ipAddress = httpServletRequest.getHeader("X-Real-IP"); if (ipAddress == null) ipAddress = httpServletRequest.getRemoteAddr(); LOG.info("/validate called from {} with token {}", ipAddress, emailConfirmationToken); Optional<Investor> oInvestor = Optional.empty(); try { oInvestor = investorRepository.findOptionalByEmailConfirmationToken(emailConfirmationToken); } catch (Exception e) { throw new UnexpectedException(); } if (!oInvestor.isPresent()) { throw new ConfirmationTokenNotFoundException(); } if (oInvestor.get().getWalletAddress() == null) { return ResponseEntity.ok().build(); } else { AddressResponse addressResponse = new AddressResponse() .setBtc(addressService.getBitcoinAddressFromPublicKey(oInvestor.get().getPayInBitcoinPublicKey())) .setEther(addressService.getEthereumAddressFromPublicKey(oInvestor.get().getPayInEtherPublicKey())); return new ResponseEntity<>(addressResponse, HttpStatus.OK); } }
/** Verifie quele nom de fichier n'est pas trop long * @return la taille max d'un nom de fichier */ public Integer getSizeMaxFileName(){ try { return Fichier.class.getDeclaredField(Fichier_.nomFichier.getName()).getAnnotation(Size.class).max(); } catch (NoSuchFieldException | SecurityException e) { return 0; } }
private static void applySize(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) { if ( Size.class.equals( descriptor.getAnnotation().annotationType() ) && String.class.equals( propertyDescriptor.getElementClass() ) ) { @SuppressWarnings("unchecked") ConstraintDescriptor<Size> sizeConstraint = (ConstraintDescriptor<Size>) descriptor; int max = sizeConstraint.getAnnotation().max(); Column col = (Column) property.getColumnIterator().next(); if ( max < Integer.MAX_VALUE ) { col.setLength( max ); } } }
private CsdlProperty extractProperty(Field f) { ODataProperty odataPropAnn = f.getAnnotation(ODataProperty.class); String odataName = odataPropAnn.name(); CsdlProperty result = new CsdlProperty().setName(odataName).setType(odataPropAnn.type().getFullQualifiedName()) .setCollection(ReflectionUtil.isArrayOrCollection(f)) .setNullable(!f.isAnnotationPresent(NotNull.class)); if (f.isAnnotationPresent(Size.class)) { result.setMaxLength(f.getAnnotation(Size.class).max()); } ODataToJavaProperties.put(odataName, f.getName()); return result; }
private JPAFieldConstraints getJPAFieldConstraint(Field field) { JPAFieldConstraints fieldConstraint = new JPAFieldConstraints(); // is field ID? fieldConstraint.setIsId(field.isAnnotationPresent(Id.class)); // is field 'not-null'? fieldConstraint.setIsNotNull(field.isAnnotationPresent(NotNull.class)); Column columnAnnotation = field.getAnnotation(Column.class); if(columnAnnotation != null) { // is field unique? fieldConstraint.setIsUnique(columnAnnotation.unique()); } // get minimum and maximum size Size sizeAnnotation = field.getAnnotation(Size.class); if(sizeAnnotation != null) { fieldConstraint.setMinSize(sizeAnnotation.min()); fieldConstraint.setMaxSize(sizeAnnotation.max()); } Min minAnnotation = field.getAnnotation(Min.class); if(minAnnotation != null) { fieldConstraint.setMinSize((int)minAnnotation.value()); } Max maxAnnotation = field.getAnnotation(Max.class); if(maxAnnotation != null) { fieldConstraint.setMaxSize((int)maxAnnotation.value()); } return fieldConstraint; }
@PostMapping(value = "/swagger/post1") public BasicResult<Demo> swaggerPost1( @RequestParam @Size(min = 1, max = 10, message = "字符串长度在1~10之间") String name, @NotNull(message = "age不能为空") @RequestParam int age, @NotNull(message = "address不能为空") @Size(min = 1, max = 3, message = "数组长度范围在1~3之间") @RequestParam(required = false) List<String> address) { Demo demo = new Demo(); demo.setName(name); demo.setAge(age); demo.setAddress(address); return BasicResult.success(demo); }
@PostMapping(value = "/formParam/fail") public BasicResult<Demo> responseParamFail( @RequestParam @Size(min = 1, max = 10, message = "字符串长度在1~10之间") String name, @NotNull(message = "age不能为空") @RequestParam int age, @NotNull(message = "address不能为空") @Size(min = 1, max = 3, message = "数组长度范围在1~3之间") @RequestParam(required = false) List<String> address) { Demo demo = new Demo(); demo.setName(name); demo.setAge(age); demo.setAddress(address); return BasicResult.success(demo); }
@Column(length=15) @Type(type="string") @NotNull(message="Name is Required") @Size(min=4,max=10,message="Name Must be in 5 to 10 chars only") @Pattern(regexp="ps[A-Z]*",message="Name Must be Starts with ps") public String getName() { return name; }
@Override public boolean isCorrect(Object objectValue, Annotation annotation) { if (areWrongPreconditions(objectValue, annotation)) return false; Size sizeAnnotation = (Size) annotation; int size = getSize(objectValue); return sizeAnnotation.min() <= size && size <= sizeAnnotation.max(); }
@Override public Optional<String> getErrorMessage(Object objectValue, Annotation annotation) { if (isCorrect(objectValue, annotation)) return Optional.absent(); Size sizeAnnotation = (Size) annotation; if (objectValue instanceof String) { return Optional.of(createErrorMessageForString(sizeAnnotation)); } else { return Optional.of(createErrorMessageForCollection(sizeAnnotation)); } }
private boolean areWrongPreconditions(Object objectValue, Annotation annotation) { if (objectValue == null) return true; if (!(annotation instanceof Size)) throw new WrongAnnotationTypeException(); return false; }
private void mockSizeValidator() throws Exception { sizeValidator = mock(SizeValidator.class); whenNew(SizeValidator.class) .withAnyArguments() .thenReturn(sizeValidator); when(sizeValidator.getAnnotationType()) .thenReturn(Size.class); }
@Test public void testGetPropertyDescriptorsWithAnnotation() { Map<PropertyDescriptor, Nullable> map = PropertyUtils.getPropertyDescriptorsWithAnnotation(TestEntity.class, Nullable.class); assertThat(map.keySet(), hasSize(1)); PropertyDescriptor someObject = PropertyUtils.getPropertyDescriptor(TestEntity.class, TestEntity::getSomeObject); assertThat(map.get(someObject), instanceOf(Nullable.class)); Map<PropertyDescriptor, Size> sizeProperties = PropertyUtils.getPropertyDescriptorsWithAnnotation(new DerivedClass(), Size.class); assertThat(collectPropertyNames(sizeProperties.keySet()), contains("baseClassStringProperty", "otherStringProperty")); }
@Test public void testGetAnnotationOfProperty() throws Exception { Nullable relationship = PropertyUtils.getAnnotationOfProperty(TestEntity.class, TestEntity::getSomeObject, Nullable.class); assertNotNull(relationship); Size size = PropertyUtils.getAnnotationOfProperty(TestEntity.class, TestEntity::getSomeObject, Size.class); assertNull(size); Size numberSize = PropertyUtils.getAnnotationOfProperty(TestEntity.class, TestEntity::getNumber, Size.class); assertNotNull(numberSize); assertThat(numberSize.min(), is(10)); assertThat(numberSize.max(), is(20)); Size stringSize = PropertyUtils.getAnnotationOfProperty(TestEntity.class, TestEntity::getString, Size.class); assertNotNull(stringSize); assertThat(stringSize.min(), is(0)); assertThat(stringSize.max(), is(1000)); assertTrue(Modifier.isPublic(BaseClass.class.getField(PropertyUtils.getPropertyName(DerivedClass.class, DerivedClass::getOtherStringProperty)).getModifiers())); Size otherStringSize = PropertyUtils.getAnnotationOfProperty(DerivedClass.class, DerivedClass::getOtherStringProperty, Size.class); assertNotNull(otherStringSize); assertThat(otherStringSize.min(), is(10)); assertThat(otherStringSize.max(), is(20)); Size baseClassStringSize = PropertyUtils.getAnnotationOfProperty(DerivedClass.class, BaseClass::getBaseClassStringProperty, Size.class); assertNotNull(baseClassStringSize); assertThat(baseClassStringSize.max(), is(30)); Size interfaceStringSize = PropertyUtils.getAnnotationOfProperty(BaseInterface.class, BaseInterface::getSizeFromInterface, Size.class); assertNotNull(interfaceStringSize); assertThat(interfaceStringSize.max(), is(40)); PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(TestEntity.class, TestEntity::getString); assertNotNull(PropertyUtils.getAnnotationOfProperty(new TestEntity(), propertyDescriptor, Size.class)); }
@Size(min = 0, max = 0) @NotNull @Override public String getDatabasePrefix() { // primary is always empty return EMPTY_PREFIX; }
/** * Method handling HTTP GET requests. The returned object will be sent * to the client as "text/plain" media type. * * @return String that will be returned as a text/plain response. */ @Path("myresource/{id1}") @GET @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String getIt( @Named("namedValue1") @NotNull @Size(min=5,max=10,message="${validatedValue} min {min}") @PathParam("id1") String value1, @Named("namedValue2") @NotNull @Size(min=2,max=10) @QueryParam("key1") String value2, @NotNull @Min(1) @QueryParam("key2") Integer value3 ) { return "OK-" + value1 + "-" + value2 + "-" + value3.toString(); }
@Path("myresource/{id1}") @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String postIt( @NotNull @Size(min=5,max=10,message="'${validatedValue}' min {min}") @PathParam("id1") String value1, @Valid MyDto dto ) { return "OK-" + value1; }
@Path("new") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Permissions(roles = AccountRole.ADMIN) public Response create(@NotNull @FormParam("username") Username username, @NotNull @FormParam("email") EmailAddress email, @NotNull @Size(min = 1) @FormParam("password") String password, @Context UriInfo uriInfo) throws DuplicateEmailException { Account account = accountService.create(username, email, password); URI location = uriInfo.getBaseUriBuilder().path(AccountResource.class).build(account.id); return Response.seeOther(location).build(); }
@Override @Id @Access(value = AccessType.PROPERTY) @Column(name = "integration_id", nullable = false) @Size(max = 255) public String getId() { return this.id; }
@Override public void validate(Size sizeAnnotation, String name, ValidationContext validationCtx, Errors errors) { Object value = validationCtx.value(name); if (value == null) return; if (!validateMinLength(sizeAnnotation.min(), value) && !validateMaxLength(sizeAnnotation.max(), value)) { errors.add(name, sizeAnnotation.message(), value, sizeAnnotation.min(), sizeAnnotation.max()); } else if (!validateMinLength(sizeAnnotation.min(), value)) { errors.add(name, sizeAnnotation.message(), value, sizeAnnotation.min(), sizeAnnotation.max()); } else if (!validateMaxLength(sizeAnnotation.max(), value)) { errors.add(name, sizeAnnotation.message(), value, sizeAnnotation.min(), sizeAnnotation.max()); } }
@NotNull(groups = PasswordValidationGroup.class) @Size(max = 16, min = 8, message = "Password must be between 8 and 16 characters long", groups = PasswordValidationGroup.class) @Override public String getPassword1() { return password1; }
@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Permissions(NotSignedIn.class) public Response signin(@NotNull @FormParam("email") EmailAddress email, @NotNull @Size(min = 1) @FormParam("password") String password, @Context UriInfo uriInfo) { if (securityService.signin(email, password) == false) { String errorMessage = "ログインできませんでした。ユーザーID、またはパスワードをお間違えではありませんか?"; Response response = Response.status(Status.BAD_REQUEST) .entity(UIResponse.render("signin", errorMessage)).build(); throw new BadRequestException(response); } URI location = uriInfo.getBaseUriBuilder().path(ProjectResource.class).build(); return Response.seeOther(location).build(); }
/** * The login used to login */ @NotEmpty @Size(max = 100) @Column(name = "LOGIN", nullable = false, unique = true, length = 100) public String getLogin() { return login; }
protected void addValidation(final INamedParam parameter, final JVar argumentVariable) { if (isNotBlank(parameter.getPattern())) { JAnnotationUse patternAnnotation = argumentVariable.annotate(Pattern.class); patternAnnotation.param("regexp", parameter.getPattern()); } final Integer minLength = parameter.getMinLength(); final Integer maxLength = parameter.getMaxLength(); if ((minLength != null) || (maxLength != null)) { final JAnnotationUse sizeAnnotation = argumentVariable .annotate(Size.class); if (minLength != null) { sizeAnnotation.param("min", minLength); } if (maxLength != null) { sizeAnnotation.param("max", maxLength); } } final BigDecimal minimum = parameter.getMinimum(); if (minimum != null) { addMinMaxConstraint(parameter, "minimum", Min.class, minimum, argumentVariable); } final BigDecimal maximum = parameter.getMaximum(); if (maximum != null) { addMinMaxConstraint(parameter, "maximum", Max.class, maximum, argumentVariable); } if (parameter.isRequired()) { argumentVariable.annotate(NotNull.class); } }
@ApiOperation(value = "Find movies") @GetMapping(produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public PagedResources<MovieSearchResultResource> findMovies( @ApiParam(value = "The title of the movie") @RequestParam(value = "title", required = false) final String title, @ApiParam(value = "The type of the movie") @RequestParam(value = "type", required = false) final MovieType type, @ApiParam(value = "Release date range \"from\"") @RequestParam(value = "fromDate", required = false) @DateTimeFormat(pattern="yyyy-MM-dd") final Date fromDate, @ApiParam(value = "Release date range \"to\"") @RequestParam(value = "toDate", required = false) @DateTimeFormat(pattern="yyyy-MM-dd") final Date toDate, @ApiParam(value = "List of countries") @RequestParam(value = "country", required = false) final List<CountryType> countries, @ApiParam(value = "List of languages") @RequestParam(value = "language", required = false) final List<LanguageType> languages, @ApiParam(value = "List of genres") @RequestParam(value = "genre", required = false) final List<GenreType> genres, @ApiParam(value = "Min. rating") @RequestParam(value = "minRating", required = false) @Size(max = 10) final Integer minRating, @ApiParam(value = "Max. rating") @RequestParam(value = "maxRating", required = false) @Size(max = 10) final Integer maxRating, @PageableDefault(sort = {"title"}, direction = Sort.Direction.DESC) final Pageable page, final PagedResourcesAssembler<MovieSearchResult> assembler ) { log.info("Called with" + " title {}, type {}," + "fromDate {}, toDate {}, countries {}," + "languages {}, genres {}, minRating {}," + "maxRating {}, page {},", title, type, fromDate, toDate, countries, languages, genres, minRating, maxRating, page); // Build the self link which will be used for the next, previous, etc links final Link self = ControllerLinkBuilder .linkTo( ControllerLinkBuilder .methodOn(MovieRestController.class) .findMovies( title, type, fromDate, toDate, countries, languages, genres, minRating, maxRating, page, assembler ) ).withSelfRel(); return assembler.toResource(this.movieSearchService.findMovies( title, type, fromDate, toDate, countries, languages, genres, minRating, maxRating, page ), this.movieSearchResultResourceAssembler, self); }
@JsonProperty("operating_system") @NotNull @Size(min = 1) public abstract String operatingSystem();
@JsonProperty("node_id") @NotNull @Size(min = 1) public abstract String nodeId();
@Size(min = 1) public String[] getUrl() { return url; }