javax.validation.constraints.Max Java Examples

The following examples show how to use javax.validation.constraints.Max. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CollectionController.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
@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)));
}
 
Example #2
Source File: SequencerDefinition.java    From snowcast with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: TestOracleConfig.java    From presto with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: ListenerController.java    From ic with MIT License 6 votes vote down vote up
@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());
}
 
Example #5
Source File: JavaxValidationModule.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source File: LogicalNodeTable.java    From snowcast with Apache License 2.0 6 votes vote down vote up
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;
        }
    }
}
 
Example #7
Source File: Tests.java    From proteus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("response/max")
public ServerResponse<ByteBuffer> maxValue(ServerRequest request, @QueryParam("param") @Max(100) Integer param ) throws Exception
{
	return response().body(param.toString());

}
 
Example #8
Source File: InventoryApi.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@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);
 
Example #9
Source File: SpringMvcDefaultValues.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #10
Source File: OpenApiTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
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);
	}
}
 
Example #11
Source File: SearchResourceImpl.java    From osiris with Apache License 2.0 5 votes vote down vote up
@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();		
}
 
Example #12
Source File: InventoryApiController.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #13
Source File: InternalSequencerUtils.java    From snowcast with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: Meal.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #15
Source File: ParameterScanTests.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #16
Source File: JaxRSDefaultValues.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #17
Source File: ClientSequencer.java    From snowcast with Apache License 2.0 5 votes vote down vote up
@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");
    }
}
 
Example #18
Source File: NodeSequencerService.java    From snowcast with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #19
Source File: SampleController.java    From blog-tutorials with MIT License 5 votes vote down vote up
@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());

}
 
Example #20
Source File: LinkManager.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #21
Source File: BusinessController.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #22
Source File: ClientSnowcast.java    From snowcast with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #23
Source File: ItemResource.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #24
Source File: ArtistBizController.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #25
Source File: RankController.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #26
Source File: DeviceCommandResource.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
 
Example #27
Source File: IllustHistoryController.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #28
Source File: Constraint.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source File: ReflectionMagicWorksTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example #30
Source File: BusinessController.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 4 votes vote down vote up
@GetMapping("/{userId}/followed")
@PermissionRequired(PermissionLevel.ANONYMOUS)
public ResponseEntity<Result<List<Artist>>> queryFollowed(@PathVariable Integer userId, @RequestParam(defaultValue = "1") @Max(100) int page, @RequestParam(defaultValue = "30") @Max(30) int pageSize, @RequestHeader(value = "Authorization", required = false) String token) {
    List<Artist> artists = businessService.queryFollowed(userId, (page - 1) * pageSize, pageSize);
    return ResponseEntity.ok().body(new Result<>("获取follow画师列表成功", artists));
}