下面列出了javax.annotation.Nonnegative#javax.validation.constraints.Max 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public SequencerDefinition(@Nonnull String sequencerName, @Nonnull SnowcastEpoch epoch,
@Min(128) @Max(8192) int maxLogicalNodeCount,
@Nonnegative @Max(Short.MAX_VALUE) short backupCount) {
if (maxLogicalNodeCount < NODE_ID_LOWER_BOUND) {
throw exception(SnowcastMaxLogicalNodeIdOutOfBoundsException::new, //
ILLEGAL_MAX_LOGICAL_NODE_ID_BOUNDARY, "smaller", NODE_ID_LOWER_BOUND);
}
if (maxLogicalNodeCount > NODE_ID_UPPER_BOUND) {
throw exception(SnowcastMaxLogicalNodeIdOutOfBoundsException::new, //
ILLEGAL_MAX_LOGICAL_NODE_ID_BOUNDARY, "larger", NODE_ID_UPPER_BOUND);
}
this.sequencerName = sequencerName;
this.epoch = epoch;
this.maxLogicalNodeCount = maxLogicalNodeCount;
this.backupCount = backupCount;
this.boundedMaxLogicalNodeCount = InternalSequencerUtils.calculateBoundedMaxLogicalNodeCount(maxLogicalNodeCount);
}
@Test
public void testValidation()
{
assertFailsValidation(
new OracleConfig()
.setDefaultNumberScale(-1),
"defaultNumberScale",
"must be greater than or equal to 0",
Min.class);
assertFailsValidation(
new OracleConfig()
.setDefaultNumberScale(39),
"defaultNumberScale",
"must be less than or equal to 38",
Max.class);
}
@Override
@Path("/room")
@GET
@ValidationRequired(processor = RestViolationProcessor.class)
@ApiOperation(value = "Get room according to indoor location", httpMethod="GET",response=RoomDTO.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Room belongs to location", response=RoomDTO.class),
@ApiResponse(code = 400, message = "Invalid input parameter"),
@ApiResponse(code = 404, message = "Room not found"),
@ApiResponse(code = 500, message = "Problem in the system")})
public Response getRoomByLocation(@Auth BasicAuth principal,
@ApiParam(value = "Application identifier", required = true) @NotBlank @NotNull @HeaderParam("api_key") String appIdentifier,
@ApiParam(value="Longitude of location", required=true) @Min(-180) @Max(180) @NotNull @QueryParam("longitude") Double longitude,
@ApiParam(value="Latitude of location", required=true) @Min(-90) @Max(90) @NotNull @QueryParam("latitude") Double latitude,
@ApiParam(value = "Floor of location", required = true) @NotNull @QueryParam("floor") Integer floor) throws AssemblyException, RoomNotFoundException{
validations.checkIsNotNullAndNotBlank(appIdentifier);
validations.checkMin(-180.0, longitude);
validations.checkMax(180.0, longitude);
validations.checkMin(-90.0, latitude);
validations.checkMax(90.0, latitude);
validations.checkIsNotNull(floor);
Feature room=searchManager.getRoomByLocation(appIdentifier, longitude, latitude, floor);
RoomDTO roomDTO=roomAssembler.createDataTransferObject(room);
return Response.ok(roomDTO).build();
}
/**
* Determine a number type's maximum (inclusive) value.
*
* @param member the field or method to check
* @return specified inclusive maximum value (or null)
* @see Max
* @see DecimalMax#inclusive()
* @see NegativeOrZero
*/
protected BigDecimal resolveNumberInclusiveMaximum(MemberScope<?, ?> member) {
Max maxAnnotation = this.getAnnotationFromFieldOrGetter(member, Max.class, Max::groups);
if (maxAnnotation != null) {
return new BigDecimal(maxAnnotation.value());
}
DecimalMax decimalMaxAnnotation = this.getAnnotationFromFieldOrGetter(member, DecimalMax.class, DecimalMax::groups);
if (decimalMaxAnnotation != null && decimalMaxAnnotation.inclusive()) {
return new BigDecimal(decimalMaxAnnotation.value());
}
NegativeOrZero negativeAnnotation = this.getAnnotationFromFieldOrGetter(member, NegativeOrZero.class, NegativeOrZero::groups);
if (negativeAnnotation != null) {
return BigDecimal.ZERO;
}
return null;
}
@GetMapping("/api/v2/event/listener/{token}")
@ResponseBody
public ListenerFetchResult getEvents(
@NotBlank
@PathVariable String token,
@RequestParam(required = false) String type,
@NonNull
@RequestParam(required = false, defaultValue = "") List<String> types,
@Max(100)
@Min(1)
@NotNull
@RequestParam(required = false, defaultValue = "100") int maxResults,
@RequestParam(required = false, defaultValue = "false") boolean longPoll) {
List<String> targetTypes = Lists.newArrayList(types);
if(!Strings.isNullOrEmpty(type)) {
targetTypes.add(type);
}
return listenerService.consumeEvents(token, targetTypes, maxResults, longPoll, getClientIp());
}
void detachLogicalNode(@Nonnull Address address, @Min(128) @Max(8192) int logicalNodeId) {
while (true) {
Object[] assignmentTable = this.assignmentTable;
Address addressOnSlot = (Address) assignmentTable[logicalNodeId];
if (addressOnSlot == null) {
break;
}
if (!address.equals(addressOnSlot)) {
throw exception(SnowcastIllegalStateException::new, ILLEGAL_DETACH_ATTEMPT);
}
long offset = offset(logicalNodeId);
if (UNSAFE.compareAndSwapObject(assignmentTable, offset, addressOnSlot, null)) {
break;
}
}
}
@GetMapping("/users/{userId}/collections")
@PermissionRequired(PermissionLevel.ANONYMOUS)
public ResponseEntity<Result<List<Collection>>> queryUserCollection(@PathVariable Integer userId, @RequestHeader(value = "Authorization", required = false) String token, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") @Max(15) Integer pageSize, @RequestParam(required = false) Integer isPublic) {
//是否登陆,是否查看本人画集
Map<String, Object> context = AppContext.get();
Integer isSelf = 0;
if (context != null && context.get(AuthConstant.USER_ID) != null) {
if ((int) context.get(AuthConstant.USER_ID) == userId) {
isSelf = 1;
} else {
if (isPublic == null || isPublic == 0) {
throw new BusinessException(HttpStatus.FORBIDDEN, "禁止查看他人非公开画作");
}
}
} else {
if (isPublic == null || isPublic == 0) {
throw new BusinessException(HttpStatus.FORBIDDEN, "禁止查看他人非公开画作");
}
}
return ResponseEntity.ok().body(new Result<>("获取用户画集成功", collectionService.queryCollectionSummary(userId, isPublic), collectionService.queryUserCollection(userId, isSelf, isPublic, page, pageSize)));
}
@GetMapping("/query2")
public String query2(@RequestParam(name = "e", required = false) int e,
@RequestParam(name = "a", defaultValue = "20") int a,
@RequestParam(name = "b", defaultValue = "bobo") String b,
@RequestParam(name = "c", defaultValue = "40") Integer c,
@Min(value = 20) @Max(value = 30) @RequestParam(name = "d", required = false) int d) {
return "Hello " + a + b + c + d + e;
}
/**
* Makes sure that the Reflections helper stuff is working properly and capturing all annotation possibilities (class type, constructor, constructor param, method, method param, and field).
*/
@Test
public void verifyThatTheReflectionsConfigurationIsCapturingAllAnnotationPossibilities() {
List<Pair<Annotation, AnnotatedElement>> annotationOptionsClassAnnotations = getSubAnnotationListForElementsOfOwnerClass(TROLLER.allConstraintAnnotationsMasterList,
DifferentValidationAnnotationOptions.class);
assertThat(annotationOptionsClassAnnotations.size(), is(10));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, SomeClassLevelJsr303Annotation.class).size(), is(2));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, OtherClassLevelJsr303Annotation.class).size(), is(1));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, AssertTrue.class).size(), is(1));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, AssertFalse.class).size(), is(1));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, NotNull.class).size(), is(2));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, Min.class).size(), is(2));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, Max.class).size(), is(1));
}
protected void applyAnnotationDetailsOnParameter(AbstractSerializableParameter schema, Annotation annotation) {
if (annotation instanceof DecimalMin) {
schema.setMinimum(new BigDecimal(((DecimalMin) annotation).value()));
} else if (annotation instanceof DecimalMax) {
schema.setMaximum(new BigDecimal(((DecimalMax) annotation).value()));
} else if (annotation instanceof Min) {
schema.setMinimum(BigDecimal.valueOf(((Min) annotation).value()));
} else if (annotation instanceof Max) {
schema.setMaximum(BigDecimal.valueOf(((Max) annotation).value()));
}
if (annotation instanceof Pattern) {
schema.setPattern(((Pattern) annotation).regexp());
} else if (annotation instanceof Size) {
schema.setMinLength(((Size) annotation).min());
schema.setMaxLength(((Size) annotation).max());
} else if (annotation instanceof Deprecated) {
schema.setVendorExtension("x-deprecated", true);
}
}
@Operation(description = "searches inventory", operationId = "searchInventory", summary = "By passing in the appropriate options, you can search for available inventory in the system ", tags = {
"developers", }, parameters = {
@Parameter(description = "pass an optional search string for looking up inventory", name = "searchString") })
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "search results matching criteria"),
@ApiResponse(responseCode = "400", description = "bad input parameter") })
@GetMapping(value = "/inventory", produces = { "application/json" })
ResponseEntity<List<InventoryItem>> searchInventory(
@Valid @RequestParam(value = "searchString", required = false) String searchString,
@Min(0) @Parameter(description = "number of records to skip for pagination") @Valid @RequestParam(value = "skip", required = true) Integer skip,
@Min(0) @Max(50) @Parameter(description = "maximum number of records to return") @Valid @RequestParam(value = "limit", required = true) Integer limit);
public ResponseEntity<List<InventoryItem>> searchInventory(
@Parameter(description = "pass an optional search string for looking up inventory") @Valid @RequestParam(value = "searchString", required = false) String searchString,
@Min(0) @Parameter(description = "number of records to skip for pagination") @Valid @RequestParam(value = "skip", required = true) Integer skip,
@Min(0) @Max(50) @Parameter(description = "maximum number of records to return") @Valid @RequestParam(value = "limit", required = true) Integer limit) {
@SuppressWarnings("unused")
String accept = request.getHeader("Accept");
return new ResponseEntity<List<InventoryItem>>(HttpStatus.NOT_IMPLEMENTED);
}
public static long generateSequenceId(@Nonnegative long timestamp, @Min(128) @Max(8192) int logicalNodeID,
@Nonnegative int nextId, @Nonnegative int nodeIdShiftFactor) {
int maxCounter = calculateMaxMillisCounter(nodeIdShiftFactor);
if (maxCounter < nextId) {
throw exception(NEXT_ID_LARGER_THAN_ALLOWED_MAX_COUNTER);
}
long id = timestamp << SHIFT_TIMESTAMP;
id |= logicalNodeID << nodeIdShiftFactor;
id |= nextId;
return id;
}
@Creator
public Meal(
UUID mid,
@NotNull @Max(999) int currentBloodGlucose,
Date createdOn,
Date updatedOn,
@Nullable Set<Food> foods) {
this.mid = mid;
this.currentBloodGlucose = currentBloodGlucose;
this.createdOn = createdOn;
this.updatedOn = updatedOn;
this.foods = foods;
}
@GET
@Path("/seg1/seg2/resourceA")
@Produces(MediaType.APPLICATION_JSON)
@Parameter(in = ParameterIn.PATH, name = "resourceA", style = ParameterStyle.MATRIX)
public Widget get(@MatrixParam("m1") @DefaultValue("default-m1") int m1,
@MatrixParam("m2") @DefaultValue("100") @Max(200) int m2) {
return null;
}
@Path("/packages")
@GET
public String queryPackages(HttpServletRequest httpRequest,
@Max(value = 2147483647L) @Min(value = -1L) @NotNull @QueryParam("pageNo") Integer pageNo,
@Max(value = 2147483647L) @Min(value = -1L) @NotNull @QueryParam("pageSize") Integer pageSize,
@Size(max = 64, min = 0) @QueryParam("packageName") String packageName,
@Max(value = 127L) @Min(value = 0L) @QueryParam("packageType") Integer packageType,
@Max(value = 2147483647L) @Min(value = 1L) @QueryParam("roleID") Integer roleID,
@Max(value = 2147483647L) @Min(value = 1L) @QueryParam("categoryID") Integer categoryID,
@Max(value = 127L) @Min(value = 0L) @QueryParam("appType") @DefaultValue("1") Integer appType,
@Max(value = 2L) @Min(value = 1L) @QueryParam("packageScope") Integer packageScope) {
return "" + appType;
}
@Override
protected void doDetachLogicalNode(@Nonnull SequencerDefinition definition, @Min(128) @Max(8192) int logicalNodeId) {
TRACER.trace("doDetachLogicalNode begin");
try {
clientCodec.detachLogicalNode(getSequencerName(), definition, logicalNodeId);
} finally {
TRACER.trace("doDetachLogicalNode end");
}
}
void detachSequencer(@Nonnull SequencerDefinition definition, @Min(128) @Max(8192) int logicalNodeId) {
IPartitionService partitionService = nodeEngine.getPartitionService();
int partitionId = partitionService.getPartitionId(definition.getSequencerName());
DetachLogicalNodeOperation operation = new DetachLogicalNodeOperation(definition, logicalNodeId);
OperationService operationService = nodeEngine.getOperationService();
InvocationBuilder invocationBuilder = operationService.createInvocationBuilder(SERVICE_NAME, operation, partitionId);
completableFutureGet(invocationBuilder.invoke());
}
@GetMapping("/messages")
public List<String> getMessages(@RequestParam("size") @Positive @Max(6) Integer size) {
return List.of("Hello", "World", "Foo", "Bar", "Duke", "Spring")
.stream()
.limit(size)
.collect(Collectors.toList());
}
@Override
public ValidationInfo getValidationInfo() {
if (Integer.class.isAssignableFrom(Primitives.wrap(getType()))) {
Annotation[] annotations = attribute.getAnnotations();
return newNumberValidationInfo(find(annotations, Min.class)
.or(minValueProvider).value(),
find(annotations, Max.class).or(maxValueProvider)
.value());
}
return ValidationInfo.NULL;
}
@GetMapping("/{userId}/bookmarked/{type}")
@PermissionRequired(PermissionLevel.ANONYMOUS)
@WithUserInfo
public ResponseEntity<Result<List<Illustration>>> queryBookmark(@PathVariable Integer userId, @PathVariable String type, @RequestParam(defaultValue = "1") @Max(300) int page, @RequestParam(defaultValue = "30") @Max(30) int pageSize, @RequestHeader(value = "Authorization", required = false) String token) {
List<Illustration> illustrations = businessService.queryBookmarked(userId, type, (page - 1) * pageSize, pageSize);
/* int userIdFromAppContext;
if (token != null) {
userIdFromAppContext = (int) AppContext.get().get(AuthConstant.USER_ID);
businessService.dealIfFollowedInfo(illustrations, userIdFromAppContext);
}*/
return ResponseEntity.ok().body(new Result<>("获取收藏画作成功", illustrations));
}
ClientSnowcast(@Nonnull HazelcastInstance hazelcastInstance, @Nonnegative @Max(Short.MAX_VALUE) short backupCount) {
this.backupCount = backupCount;
HazelcastClientInstanceImpl client = getHazelcastClient(hazelcastInstance);
ClientInvocator clientInvocator = buildClientInvocator(client);
ClientCodec clientCodec = new ClientCodec(client, clientInvocator);
ProxyManager proxyManager = client.getProxyManager();
this.sequencerService = new ClientSequencerService(proxyManager, clientCodec);
printStartupMessage(true);
}
/**
* Searches for item based on lookup parameters.
* <p>
* An example of using Pageable, Page and customized translation for paging text.
*
* @param descMatch Lookup on description field.
* @param hint Lookup hint.
* @return response
* @see <a href="https://scacap.github.io/spring-auto-restdocs/#paging">paging documentation</a>
*/
@GetMapping("search")
public Page<ItemResponse> searchItem(
@RequestParam("desc") @NotBlank @Size(max = 255) String descMatch,
@RequestParam(required = false) @Min(10) @Max(100) Integer hint,
Pageable page) {
if (ITEM.getDescription().contains(descMatch)) {
return new PageImpl<>(singletonList(ITEM), page, 1);
} else {
return new PageImpl<>(Collections.<ItemResponse>emptyList(), page, 0);
}
}
@GetMapping("/artists/{artistId}/illusts/{type}")
@PermissionRequired(PermissionLevel.ANONYMOUS)
@WithUserInfo
public ResponseEntity<Result<List<Illustration>>> queryIllustrationsByArtistId(@PathVariable Integer artistId, @PathVariable String type, @RequestParam(defaultValue = "1") @Max(333) int page, @RequestParam(defaultValue = "30") int pageSize, @RequestHeader(value = "Authorization", required = false) String token) throws InterruptedException {
List<Illustration> illustrationList = artistBizService.queryIllustrationsByArtistId(artistId, type, (page - 1) * pageSize, pageSize);
return ResponseEntity.ok().body(new Result<>("获取画师画作列表成功", illustrationList));
}
@GetMapping
@WithUserInfo
@WithAdvertisement
@PermissionRequired(PermissionLevel.ANONYMOUS)
public ResponseEntity<Result<List<Illustration>>> queryByDateAndMode(@RequestParam String date, @RequestParam String mode, @RequestParam(defaultValue = "1") @Max(30) int page, @RequestParam(defaultValue = "30") int pageSize, @RequestHeader(value = "Authorization", required = false) String token) {
List<Illustration> rank = rankService.queryByDateAndMode(date, mode, page, pageSize);
return ResponseEntity.ok().body(new Result<>("获取排行成功", rank));
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceCommand/poll">DeviceHive RESTful
* API: DeviceCommand: poll</a>
*
* @param deviceId Device unique identifier.
* @param namesString Command names
* @param timestamp Timestamp of the last received command (UTC). If not specified, the server's timestamp is taken
* instead.
* @param timeout Waiting timeout in seconds (default: 30 seconds, maximum: 60 seconds). Specify 0 to disable
* waiting.
* @param limit Limit number of commands
*/
@GET
@Path("/{deviceId}/command/poll")
@PreAuthorize("isAuthenticated() and hasPermission(#deviceId, 'GET_DEVICE_COMMAND')")
@ApiOperation(value = "Polls the server to get commands.",
notes = "This method returns all device commands that were created after specified timestamp.\n" +
"In the case when no commands were found, the method blocks until new command is received. If no commands are received within the waitTimeout period, the server returns an empty response. In this case, to continue polling, the client should repeat the call with the same timestamp value.",
response = DeviceCommand.class,
responseContainer = "List")
@ApiImplicitParams({
@ApiImplicitParam(name = "Authorization", value = "Authorization token", required = true, dataType = "string", paramType = "header")
})
void poll(
@ApiParam(name = "deviceId", value = "Device ID", required = true)
@PathParam("deviceId")
String deviceId,
@ApiParam(name = "names", value = "Command names")
@QueryParam("names")
String namesString,
@ApiParam(name = "timestamp", value = "Timestamp to start from")
@QueryParam("timestamp")
String timestamp,
@ApiParam(name = RETURN_UPDATED_COMMANDS, value = "Checks if updated commands should be returned", defaultValue = "false")
@QueryParam(RETURN_UPDATED_COMMANDS)
boolean returnUpdatedCommands,
@ApiParam(name = "waitTimeout", value = "Wait timeout in seconds", defaultValue = Constants.DEFAULT_WAIT_TIMEOUT)
@DefaultValue(Constants.DEFAULT_WAIT_TIMEOUT)
@Min(value = Constants.MIN_WAIT_TIMEOUT, message = "Timeout can't be less than " + Constants.MIN_WAIT_TIMEOUT + " seconds. ")
@Max(value = Constants.MAX_WAIT_TIMEOUT, message = "Timeout can't be more than " + Constants.MAX_WAIT_TIMEOUT + " seconds. ")
@QueryParam("waitTimeout")
long timeout,
@ApiParam(name = "limit", value = "Limit number of commands", defaultValue = Constants.DEFAULT_TAKE_STR)
@DefaultValue(Constants.DEFAULT_TAKE_STR)
@Min(value = 0L, message = "Limit can't be less than " + 0L + ".")
@QueryParam("limit")
int limit,
@Suspended AsyncResponse asyncResponse) throws Exception;
@PermissionRequired
@WithUserInfo
@GetMapping("/users/{userId}/illustHistory")
public ResponseEntity<Result<List<Illustration>>> queryIllustHistory(@PathVariable Integer userId, @RequestParam(defaultValue = "1") @Max(30) int page, @RequestParam(defaultValue = "30") int pageSize, @RequestHeader(value = "Authorization", required = false) String token) {
List<Illustration> illustrations = illustHistoryService.pullFromRedis((int) AppContext.get().get(AuthConstant.USER_ID), page, pageSize);
return ResponseEntity.ok(new Result<>("获取近期历史记录成功", illustrations));
}
/**
* Creates a new map representing a {@link Max} validation constraint.
* @param max the maximum value
* @return a map
*/
static Map<String, Object> maxPayload(final Object max) {
if (max == null) {
return null;
}
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("value", max);
payload.put("message", MSG_PREFIX + VALIDATORS.get(Max.class));
return payload;
}
@GET
@Path("response/max")
public ServerResponse<ByteBuffer> maxValue(ServerRequest request, @QueryParam("param") @Max(100) Integer param ) throws Exception
{
return response().body(param.toString());
}
@Override
public Randomizer<?> getRandomizer(Field field) {
Class<?> fieldType = field.getType();
Max maxAnnotation = ReflectionUtils
.getAnnotation(field, Max.class);
Min minAnnotation = ReflectionUtils
.getAnnotation(field, Min.class);
Long maxValue = null;
Long minValue = null;
if (maxAnnotation != null) {
maxValue = maxAnnotation.value();
}
if (minAnnotation != null) {
minValue = minAnnotation.value();
}
if (fieldType.equals(Byte.TYPE) || fieldType.equals(Byte.class)) {
return new ByteRangeRandomizer(
minValue == null ? null : minValue.byteValue(),
maxValue == null ? null : maxValue.byteValue(),
random.nextLong()
);
}
if (fieldType.equals(Short.TYPE) || fieldType.equals(Short.class)) {
return new ShortRangeRandomizer(
minValue == null ? null : minValue.shortValue(),
maxValue == null ? null : maxValue.shortValue(),
random.nextLong()
);
}
if (fieldType.equals(Integer.TYPE) || fieldType.equals(Integer.class)) {
return new IntegerRangeRandomizer(
minValue == null ? null : minValue.intValue(),
maxValue == null ? null : maxValue.intValue(),
random.nextLong()
);
}
if (fieldType.equals(Long.TYPE) || fieldType.equals(Long.class)) {
return new LongRangeRandomizer(
minValue == null ? null : minValue,
maxValue == null ? null : maxValue,
random.nextLong()
);
}
if (fieldType.equals(BigInteger.class)) {
return new BigIntegerRangeRandomizer(
minValue == null ? null : minValue.intValue(),
maxValue == null ? null : maxValue.intValue(),
random.nextLong()
);
}
if (fieldType.equals(BigDecimal.class)) {
return new BigDecimalRangeRandomizer(
minValue == null ? null : minValue.doubleValue(),
maxValue == null ? null : maxValue.doubleValue(),
random.nextLong()
);
}
return null;
}