@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;
}
java类javax.validation.constraints.Size的实例源码
MinItemsMaxItemsRule.java 文件源码
项目:GitHub
阅读 30
收藏 0
点赞 0
评论 0
AddressController.java 文件源码
项目:tokenapp-backend
阅读 31
收藏 0
点赞 0
评论 0
@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);
}
AbstractGenerator.java 文件源码
项目:aml
阅读 34
收藏 0
点赞 0
评论 0
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);
}
}
MinLengthMaxLengthRule.java 文件源码
项目:GitHub
阅读 26
收藏 0
点赞 0
评论 0
@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;
}
MinijaxConstraintDescriptor.java 文件源码
项目:minijax
阅读 30
收藏 0
点赞 0
评论 0
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);
}
JAXRSBeanValidationImplicitInInterceptorTest.java 文件源码
项目:bootstrap
阅读 28
收藏 0
点赞 0
评论 0
/**
* 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());
}
}
SizeValidator.java 文件源码
项目:GPigValidator
阅读 26
收藏 0
点赞 0
评论 0
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();
}
SizeAnnotationPostProcessor.java 文件源码
项目:randomito-all
阅读 23
收藏 0
点赞 0
评论 0
@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;
}
AccountController.java 文件源码
项目:spring-cloud-sample
阅读 32
收藏 0
点赞 0
评论 0
@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:/";
}
ShortUrlController.java 文件源码
项目:short-url
阅读 20
收藏 0
点赞 0
评论 0
@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");
}
EmailToken.java 文件源码
项目:oma-riista-web
阅读 32
收藏 0
点赞 0
评论 0
@Override
@Id
@Size(min = 16, max = 255)
@Access(value = AccessType.PROPERTY)
@Column(name = "token_data", nullable = false, length = 255)
public String getId() {
return id;
}
JpaModelTest.java 文件源码
项目:oma-riista-web
阅读 30
收藏 0
点赞 0
评论 0
@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: ");
}
RegisterController.java 文件源码
项目:tokenapp-backend
阅读 26
收藏 0
点赞 0
评论 0
@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);
}
}
FileController.java 文件源码
项目:esup-ecandidat
阅读 28
收藏 0
点赞 0
评论 0
/** 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;
}
}
TypeSafeActivator.java 文件源码
项目:lams
阅读 30
收藏 0
点赞 0
评论 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 );
}
}
}
JpaEntityCsdlProvider.java 文件源码
项目:olingo-jpa
阅读 24
收藏 0
点赞 0
评论 0
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;
}
JPAEntityAnalyzer.java 文件源码
项目:tap17-muggl-javaee
阅读 34
收藏 0
点赞 0
评论 0
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;
}
LocSwagger2Test.java 文件源码
项目:loc-framework
阅读 25
收藏 0
点赞 0
评论 0
@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);
}
LocBasicResultTest.java 文件源码
项目:loc-framework
阅读 23
收藏 0
点赞 0
评论 0
@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);
}
Employee.java 文件源码
项目:Hibernate_Validation_API_Annotation_Simple
阅读 37
收藏 0
点赞 0
评论 0
@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;
}
SizeValidator.java 文件源码
项目:GPigValidator
阅读 24
收藏 0
点赞 0
评论 0
@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();
}
SizeValidator.java 文件源码
项目:GPigValidator
阅读 27
收藏 0
点赞 0
评论 0
@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));
}
}
SizeValidator.java 文件源码
项目:GPigValidator
阅读 25
收藏 0
点赞 0
评论 0
private boolean areWrongPreconditions(Object objectValue, Annotation annotation) {
if (objectValue == null)
return true;
if (!(annotation instanceof Size))
throw new WrongAnnotationTypeException();
return false;
}
ValidatorTest.java 文件源码
项目:GPigValidator
阅读 35
收藏 0
点赞 0
评论 0
private void mockSizeValidator() throws Exception {
sizeValidator = mock(SizeValidator.class);
whenNew(SizeValidator.class)
.withAnyArguments()
.thenReturn(sizeValidator);
when(sizeValidator.getAnnotationType())
.thenReturn(Size.class);
}
PropertyUtilsTest.java 文件源码
项目:reflection-util
阅读 26
收藏 0
点赞 0
评论 0
@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"));
}
PropertyUtilsTest.java 文件源码
项目:reflection-util
阅读 28
收藏 0
点赞 0
评论 0
@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));
}
PrimaryMetaStore.java 文件源码
项目:waggle-dance
阅读 23
收藏 0
点赞 0
评论 0
@Size(min = 0, max = 0)
@NotNull
@Override
public String getDatabasePrefix() {
// primary is always empty
return EMPTY_PREFIX;
}
MyResource.java 文件源码
项目:parsec-libraries
阅读 39
收藏 0
点赞 0
评论 0
/**
* 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();
}
MyResource.java 文件源码
项目:parsec-libraries
阅读 31
收藏 0
点赞 0
评论 0
@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;
}
AccountResource.java 文件源码
项目:sealion
阅读 29
收藏 0
点赞 0
评论 0
@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();
}