下面列出了com.fasterxml.jackson.databind.annotation.JsonDeserialize#javax.validation.constraints.Size 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequestMapping(path = "/personByLastName2", method = RequestMethod.GET)
public List<Person> findByLastName(@RequestParam(name = "lastName", required = true) @NotNull
@NotBlank
@Size(max = 10) String lastName) {
List<Person> hardCoded = new ArrayList<>();
Person person = new Person();
person.setAge(20);
person.setCreditCardNumber("4111111111111111");
person.setEmail("[email protected]");
person.setEmail1("[email protected]");
person.setFirstName("Somefirstname");
person.setLastName(lastName);
person.setId(1);
hardCoded.add(person);
return hardCoded;
}
@Test
public void forArraysMaxOnly() throws Exception {
when(array.minItems()).thenReturn(null);
when(array.maxItems()).thenReturn(5);
FieldSpec.Builder builder =
FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ",
Modifier.PUBLIC);
Jsr303Extension ext = new Jsr303Extension();
ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION);
assertEquals(1, builder.build().annotations.size());
assertEquals(Size.class.getName(), builder.build().annotations.get(0).type.toString());
assertEquals(1, builder.build().annotations.get(0).members.size());
assertEquals("5", builder.build().annotations.get(0).members.get("max").get(0).toString());
}
@GET
@Override
@Path("/{type}/features")
public Response getFeatures(@PathParam("type") @Size(max = 45) String type, @HeaderParam("If-Modified-Since") String ifModifiedSince) {
List<Feature> features;
DeviceManagementProviderService dms;
try {
dms = DeviceMgtAPIUtils.getDeviceManagementService();
FeatureManager fm = dms.getFeatureManager(type);
if (fm == null) {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No feature manager is " +
"registered with the given type '" + type + "'").build()).build();
}
features = fm.getFeatures();
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving the list of features of '" + type + "' device type";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.OK).entity(features).build();
}
@Creator
public Food(
UUID fid,
@Size(max = 36) @NotNull String key,
@Size(max = 9999) @NotNull int carbohydrates,
@Size(max = 9999) @NotNull int portionGrams,
Date createdOn,
Date updatedOn,
@Nullable Meal meal) {
this.fid = fid;
this.key = key;
this.carbohydrates = carbohydrates;
this.portionGrams = portionGrams;
this.createdOn = createdOn;
this.updatedOn = updatedOn;
this.meal = meal;
}
/**
* Change device status.
*
* @param type Device type
* @param id Device id
* @param newsStatus Device new status
* @return {@link Response} object
*/
@PUT
@Path("/{type}/{id}/changestatus")
public Response changeDeviceStatus(@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id,
@QueryParam("newStatus") EnrolmentInfo.Status newsStatus) {
RequestValidationUtil.validateDeviceIdentifier(type, id);
DeviceManagementProviderService deviceManagementProviderService =
DeviceMgtAPIUtils.getDeviceManagementService();
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type);
Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier, false);
if (persistedDevice == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
boolean response = deviceManagementProviderService.changeDeviceStatus(deviceIdentifier, newsStatus);
return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while changing device status of type : " + type + " and " +
"device id : " + id;
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@DELETE
@Path("/type/{device-type}/id/{device-id}")
@Override
public Response deleteDevice(@PathParam("device-type") @Size(max = 45) String deviceType,
@PathParam("device-id") @Size(max = 45) String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
DeviceMgtAPIUtils.getPrivacyComplianceProvider().deleteDeviceDetails(deviceIdentifier);
return Response.status(Response.Status.OK).build();
} catch (PrivacyComplianceException e) {
String msg = "Error occurred while deleting the devices information.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@RequestMapping(path = "/personByLastName", method = RequestMethod.GET)
public List<Person> findByLastName(@RequestParam(name = "lastName", required = true) @NotNull
@NotBlank
@Size(max = 10) String lastName) {
List<Person> hardCoded = new ArrayList<>();
Person person = new Person();
person.setAge(20);
person.setCreditCardNumber("4111111111111111");
person.setEmail("[email protected]");
person.setEmail1("[email protected]");
person.setFirstName("Somefirstname");
person.setLastName(lastName);
person.setId(1);
hardCoded.add(person);
return hardCoded;
}
@RequestMapping(path = "/personByLastName", method = RequestMethod.GET)
public List<Person> findByLastName(@RequestParam(name = "lastName", required = true) @NotNull
@NotBlank
@Size(max = 10) String lastName) {
List<Person> hardCoded = new ArrayList<>();
Person person = new Person();
person.setAge(20);
person.setCreditCardNumber("4111111111111111");
person.setEmail("[email protected]");
person.setEmail1("[email protected]");
person.setFirstName("Somefirstname");
person.setLastName(lastName);
person.setId(1);
hardCoded.add(person);
return hardCoded;
}
@PostConstruct
public void init() {
validationAnnotations = new HashSet<>();
validationAnnotations.addAll(Arrays.asList(NotNull.class, Size.class,
Pattern.class, DecimalMin.class, DecimalMax.class, Min.class,
Max.class));
}
private FieldSpec.Builder getStringBasedSchemaField(String fieldName, Schema innerSchema, TypeSpec.Builder typeSpecBuilder) {
if (innerSchema.getFormat() == null) {
ClassName stringClassName = ClassName.get(JAVA_LANG_PKG, "String");
FieldSpec.Builder fieldBuilder = FieldSpec.builder(stringClassName, fieldName, Modifier.PRIVATE);
if (innerSchema.getPattern() != null) {
fieldBuilder.addAnnotation(AnnotationSpec.builder(Pattern.class)
.addMember("regexp", "$S", innerSchema.getPattern())
.build()
);
}
if (innerSchema.getMinLength() != null || innerSchema.getMaxLength() != null) {
AnnotationSpec.Builder sizeAnnotationBuilder = AnnotationSpec.builder(Size.class);
if (innerSchema.getMinLength() != null) {
sizeAnnotationBuilder.addMember("min", "$L", innerSchema.getMinLength());
}
if (innerSchema.getMaxLength() != null) {
sizeAnnotationBuilder.addMember("max", "$L", innerSchema.getMaxLength());
}
fieldBuilder.addAnnotation(sizeAnnotationBuilder.build());
}
enrichWithGetSet(typeSpecBuilder, stringClassName, fieldName);
return fieldBuilder;
} else if (equalsIgnoreCase(innerSchema.getFormat(), "date")) {
ClassName localDateClassName = ClassName.get(JAVA_TIME_PKG, "LocalDate");
enrichWithGetSet(typeSpecBuilder, localDateClassName, fieldName);
return FieldSpec.builder(localDateClassName, fieldName, Modifier.PRIVATE);
} else if (equalsIgnoreCase(innerSchema.getFormat(), "date-time")) {
ClassName localDateTimeClassName = ClassName.get(JAVA_TIME_PKG, "LocalDateTime");
enrichWithGetSet(typeSpecBuilder, localDateTimeClassName, fieldName);
return FieldSpec.builder(localDateTimeClassName, fieldName, Modifier.PRIVATE);
}
throw new IllegalArgumentException(String.format("Error parsing string based property [%s]", fieldName));
}
protected void applyStringAnnotations(Schema<?> schema, Annotation annotation) {
if (annotation instanceof Pattern) {
schema.pattern(((Pattern) annotation).regexp());
} else if (annotation instanceof Size) {
schema.minLength(((Size) annotation).min());
schema.maxLength(((Size) annotation).max());
}
}
@GET
@Override
@Path("/{id}")
public Response getActivity(@PathParam("id")
@Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
Activity activity;
DeviceManagementProviderService dmService;
Response response = validateAdminUser();
if (response == null) {
try {
RequestValidationUtil.validateActivityId(id);
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activity = dmService.getOperationByActivityId(id);
if (activity == null) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " +
"found upon the provided activity id '" + id + "'").build()).build();
}
return Response.status(Response.Status.OK).entity(activity).build();
} catch (OperationManagementException e) {
String msg = "ErrorResponse occurred while fetching the activity for the supplied id.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
} else {
return response;
}
}
/**
* {@inheritDoc}
*/
@Override
public <R extends CommonResource> void addDependenciesToResource(
@NotBlank final String id,
final Set<@Size(max = 1024) String> dependencies,
final Class<R> resourceClass
) throws NotFoundException {
this.getResourceDependenciesEntities(id, resourceClass).addAll(this.createOrGetFileEntities(dependencies));
}
@GET
@Path("/{dataIn}")
@Produces("text/plain")
public String getInformationWithString(@PathParam("dataIn") @Size(min = 2, max = 10) String dataIn)
throws Exception, IOException {
return ("Hello World From Your Friends at Liberty Boost EE! Your passed in string data is: " + dataIn);
}
@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;
}
@ApiOperation(value = "Query topic stats info by tenant and namespace")
@ApiResponses({
@ApiResponse(code = 200, message = "ok"),
@ApiResponse(code = 500, message = "Internal server error")
})
@RequestMapping(value = "/topics/{tenant}/{namespace}/stats", method = RequestMethod.GET)
public Map<String, Object> getTopicsStats(
@ApiParam(value = "page_num", defaultValue = "1", example = "1")
@RequestParam(name = "page_num", defaultValue = "1")
@Min(value = 1, message = "page_num is incorrect, should be greater than 0.")
Integer pageNum,
@ApiParam(value = "page_size", defaultValue = "10", example = "10")
@RequestParam(name="page_size", defaultValue = "10")
@Range(min = 1, max = 1000, message = "page_size is incorrect, should be greater than 0 and less than 1000.")
Integer pageSize,
@ApiParam(value = "The name of tenant")
@Size(min = 1, max = 255)
@PathVariable String tenant,
@ApiParam(value = "The name of namespace")
@Size(min = 1, max = 255)
@PathVariable String namespace) {
String env = request.getHeader("environment");
String serviceUrl = environmentCacheService.getServiceUrl(request);
return topicsService.getTopicStats(
pageNum, pageSize,
tenant, namespace,
env, serviceUrl);
}
@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 getPassword2() {
return password2;
}
public WriteArticle(@Size(min = 1, max = 60) @NotEmpty String subject, @Size(min = 5) @NotEmpty String content,
String categoryCode, List<GalleryOnBoard> galleries) {
this.subject = subject;
this.content = content;
this.categoryCode = categoryCode;
this.galleries = galleries;
}
@Editable
@ChoiceProvider("getValueChoices")
@OmitName
@Size(min=1, message="At least one value needs to be specified")
public List<String> getValues() {
return values;
}
@POST
@Path("/{username}/credentials")
@Override
public Response resetUserPassword(@PathParam("username")
@Size(max = 45)
String user, @QueryParam("domain") String domain, PasswordResetWrapper credentials) {
if (domain != null && !domain.isEmpty()) {
user = domain + '/' + user;
}
return CredentialManagementResponseBuilder.buildResetPasswordResponse(user, credentials);
}
@NotNull
@Size(max = 100, min = 1, message = "The length of the blueprint's name has to be in range of 1 to 100 and should not contain semicolon "
+ "and percentage character.")
@Pattern(regexp = "^[^;\\/%]*$")
public String getName() {
return super.getName();
}
@Test
public void defaultOperation() {
final Optional<Integer> max = Optional.of(7);
final Optional<Integer> min = Optional.of(4);
Size size = mock(Size.class);
when(size.max()).thenReturn(max.get());
when(size.min()).thenReturn(min.get());
final SizeConstraints sizeConstraints = new SizeConstraints(size);
assertThat(sizeConstraints.getMax()).isEqualTo(max);
assertThat(sizeConstraints.getMin()).isEqualTo(min);
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Widget update(@FormParam("form-param2") @Size(max = 10) String formParam2,
@FormParam("qualifiers") java.util.SortedSet<String> qualifiers) {
return null;
}
/**
* @param email An email.
* @return The public keys of the account corresponding to the introduced email.
*/
@GetMapping("/public-keys")
public AccountDto getAccountPublicKeys(
@RequestParam(name = "email", required = true) @NotBlank @Email(regexp = EMAIL_PATTERN) @Size(min = EMAIL_MIN_LENGTH, max = EMAIL_MAX_LENGTH) String email) {
return accountsService.getAndCheckAccountPublicKeysByEmail(email);
}
String linkTo(@Size(min = 1) final String... args) {
return uriInfo.getBaseUriBuilder()
.path(HealthResource.class)
.path(HealthResource.class, args[0])
.build(args[1])
.toString();
}
/**
* Calculate size.
*
* @param annos the annos
* @param schema the schema
*/
private void calculateSize(Map<String, Annotation> annos, Schema<?> schema) {
if (annos.containsKey(Size.class.getName())) {
Size size = (Size) annos.get(Size.class.getName());
if (OPENAPI_ARRAY_TYPE.equals(schema.getType())) {
schema.setMinItems(size.min());
schema.setMaxItems(size.max());
}
else if (OPENAPI_STRING_TYPE.equals(schema.getType())) {
schema.setMinLength(size.min());
schema.setMaxLength(size.max());
}
}
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@PostMapping("/alliance/manage/logo/save")
@PreAuthorize("hasPermission(#bodyId, 'ACCESS')")
@Activity(bodies = "#bodyId")
public String manageLogoSave(@RequestParam(name = "body") long bodyId,
@RequestParam(name = "alliance") long allianceId,
@RequestParam @URL @Size(max = 128) String url) {
allianceService.saveLogo(bodyId, allianceId, url);
return "redirect:/alliance/manage?body=" + bodyId + "&alliance=" + allianceId;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Parameter(name = "id", in = ParameterIn.PATH, style = ParameterStyle.MATRIX, description = "Additional information for id2")
public Widget get(@MatrixParam("m1") @DefaultValue("default-m1") String m1,
@MatrixParam("m2") @Size(min = 20) String m2) {
return null;
}