javax.validation.constraints.Min Java Examples

The following examples show how to use javax.validation.constraints.Min. 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: CartApi.java    From commerce-cif-api with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{id}/entries")
@ApiOperation(value = "Adds a new cart entry to an existing cart.")
@ApiResponses(value = {
    @ApiResponse(code = HTTP_CREATED, message = HTTP_CREATED_MESSAGE, response = Cart.class,
            responseHeaders = @ResponseHeader(name = "Location", description = "Location of the newly created cart entry.", response = String.class)),
    @ApiResponse(code = HTTP_BAD_REQUEST, message = HTTP_BAD_REQUEST_MESSAGE, response = ErrorResponse.class),
    @ApiResponse(code = HTTP_FORBIDDEN, message = HTTP_FORBIDDEN_MESSAGE, response = ErrorResponse.class),
    @ApiResponse(code = HTTP_NOT_FOUND, message = HTTP_NOT_FOUND_MESSAGE, response = ErrorResponse.class)
})
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
Cart postCartEntry(
    @ApiParam(value = "The ID of the cart for the new entry", required = true)
    @PathParam("id") String id,

    @ApiParam(value = "The product variant id to be added to the cart entry. If product variant exists in the" +
        " cart then the cart entry quantity is increased with the provided quantity.", required = true)
    @FormParam("productVariantId") String productVariantId,

    @ApiParam(value = "The quantity for the new entry.", required = true)
    @FormParam("quantity")
    @Min(value = 0) int quantity,

    @ApiParam(value = ACCEPT_LANGUAGE_DESC)
    @HeaderParam(ACCEPT_LANGUAGE) String acceptLanguage);
 
Example #2
Source File: JpaPersistenceServiceImpl.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void addClusterCriterionForCommand(
    final String id,
    @Valid final Criterion criterion,
    @Min(0) final int priority
) throws NotFoundException {
    log.debug(
        "[addClusterCriterionForCommand] Called to add cluster criteria {} for command {} at priority {}",
        criterion,
        id,
        priority
    );
    this.commandRepository
        .getCommandAndClusterCriteria(id)
        .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists"))
        .addClusterCriterion(this.toCriterionEntity(criterion), priority);
}
 
Example #3
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 #4
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyMin(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) {
	if ( Min.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Min> minConstraint = (ConstraintDescriptor<Min>) descriptor;
		long min = minConstraint.getAnnotation().value();

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			if ( Column.class.isInstance( selectable ) ) {
				Column col = (Column) selectable;
				String checkConstraint = col.getQuotedName(dialect) + ">=" + min;
				applySQLCheck( col, checkConstraint );
			}
		}
	}
}
 
Example #5
Source File: TopicsController.java    From pulsar-manager with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Query topic info by tenant and namespace")
@ApiResponses({
        @ApiResponse(code = 200, message = "ok"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@RequestMapping(value = "/topics/{tenant}/{namespace}", method = RequestMethod.GET)
public Map<String, Object> getTopicsByTenantNamespace(
        @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 requestHost = environmentCacheService.getServiceUrl(request);
    return topicsService.getTopicsList(pageNum, pageSize, tenant, namespace, requestHost);
}
 
Example #6
Source File: ClientSequencerService.java    From snowcast with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public SnowcastSequencer createSequencer(@Nonnull String sequencerName, @Nonnull SnowcastEpoch epoch,
                                         @Min(128) @Max(8192) int maxLogicalNodeCount,
                                         @Nonnegative @Max(Short.MAX_VALUE) short backupCount) {

    TRACER.trace("register sequencer %s with epoch %s, max nodes %s, backups %s", //
            sequencerName, epoch, maxLogicalNodeCount, backupCount);

    SequencerDefinition definition = new SequencerDefinition(sequencerName, epoch, maxLogicalNodeCount, backupCount);

    try {
        SequencerDefinition realDefinition = clientCodec.createSequencerDefinition(sequencerName, definition);
        return getOrCreateSequencerProvision(realDefinition).getSequencer();
    } finally {
        TRACER.trace("register sequencer %s end", sequencerName);
    }
}
 
Example #7
Source File: Tests.java    From proteus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("response/min")
public ServerResponse<ByteBuffer> minValue(ServerRequest request, @QueryParam("param") @Min(10) Integer param ) throws Exception
{
	return response().body(param.toString());

}
 
Example #8
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 #9
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 #10
Source File: NodeSnowcast.java    From snowcast with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public SnowcastSequencer createSequencer(@Nonnull String sequencerName, @Nonnull SnowcastEpoch epoch,
                                         @Min(128) @Max(8192) int maxLogicalNodeCount) {

    return sequencerService.createSequencer(sequencerName, epoch, maxLogicalNodeCount, backupCount);
}
 
Example #11
Source File: Constraint.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new map representing a {@link Min} validation constraint.
 * @param min the minimum value
 * @return a map
 */
static Map<String, Object> minPayload(final Object min) {
	if (min == null) {
		return null;
	}
	Map<String, Object> payload = new LinkedHashMap<>();
	payload.put("value", min);
	payload.put("message", MSG_PREFIX + VALIDATORS.get(Min.class));
	return payload;
}
 
Example #12
Source File: TaskManagerConfig.java    From presto with Apache License 2.0 5 votes vote down vote up
@Min(1)
public int getInitialSplitsPerNode()
{
    if (initialSplitsPerNode == null) {
        return maxWorkerThreads;
    }
    return initialSplitsPerNode;
}
 
Example #13
Source File: TableCache.java    From SpinalTap with Apache License 2.0 5 votes vote down vote up
/**
 * Adds or replaces (if already exists) a {@link Table} entry in the cache for the given table id.
 *
 * @param tableId The table id
 * @param tableName The table name
 * @param database The database name
 * @param binlogFilePos The binlog file position
 * @param columnTypes The list of columnd data types
 */
public void addOrUpdate(
    @Min(0) final long tableId,
    @NonNull final String tableName,
    @NonNull final String database,
    @NonNull final BinlogFilePos binlogFilePos,
    @NonNull final List<ColumnDataType> columnTypes)
    throws Exception {
  final Table table = tableCache.getIfPresent(tableId);

  if (table == null || !validTable(table, tableName, database, columnTypes)) {
    tableCache.put(tableId, fetchTable(tableId, database, tableName, binlogFilePos, columnTypes));
  }
}
 
Example #14
Source File: BeanValidationProcessor.java    From AngularBeans with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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));

}
 
Example #15
Source File: BlogService.java    From Spring-Boot-2-Fundamentals with MIT License 5 votes vote down vote up
public List<BlogEntry> retrievePagedBlogEntries(@Min(0) int page, @Min(1) int pageSize) {
    return blogRepository
            .retrieveBlogEntries()
            .stream()
            .skip(page * pageSize)
            .limit(pageSize)
            .collect(Collectors.toList());
}
 
Example #16
Source File: JpaPersistenceServiceImpl.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@Transactional(isolation = Isolation.READ_COMMITTED)
public long deleteJobsCreatedBefore(
    @NotNull final Instant creationThreshold,
    @NotNull final Set<JobStatus> excludeStatuses,
    @Min(1) final int batchSize
) {
    final String excludeStatusesString = excludeStatuses.toString();
    final String creationThresholdString = creationThreshold.toString();
    log.info(
        "[deleteJobsCreatedBefore] Attempting to delete at most {} jobs created before {} that do not have any of "
            + "these statuses {}",
        batchSize,
        creationThresholdString,
        excludeStatusesString
    );
    final Set<String> ignoredStatusStrings = excludeStatuses.stream().map(Enum::name).collect(Collectors.toSet());
    final long numJobsDeleted = this.jobRepository.deleteByIdIn(
        this.jobRepository.findJobsCreatedBefore(
            creationThreshold,
            ignoredStatusStrings,
            batchSize
        )
    );
    log.info(
        "[deleteJobsCreatedBefore] Deleted {} jobs created before {} that did not have any of these statuses {}",
        numJobsDeleted,
        creationThresholdString,
        excludeStatusesString
    );
    return numJobsDeleted;
}
 
Example #17
Source File: ConnObjectTOQuery.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Min(1)
@Max(MAX_SIZE)
@QueryParam(JAXRSService.PARAM_SIZE)
@DefaultValue("25")
public void setSize(final Integer size) {
    this.size = size;
}
 
Example #18
Source File: ApiRatingResource.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public Page<RatingEntity> list(@PathParam("api") String api, @Min(1) @QueryParam("pageNumber") int pageNumber, @QueryParam("pageSize") int pageSize) {
    final ApiEntity apiEntity = apiService.findById(api);
    if (PUBLIC.equals(apiEntity.getVisibility()) || hasPermission(RolePermission.API_RATING, api, RolePermissionAction.READ)) {
        final Page<RatingEntity> ratingEntityPage =
                ratingService.findByApi(api, new PageableBuilder().pageNumber(pageNumber).pageSize(pageSize).build());
        final List<RatingEntity> filteredRatings =
                ratingEntityPage.getContent().stream().map(ratingEntity -> filterPermission(api, ratingEntity)).collect(toList());
        return new Page<>(filteredRatings, ratingEntityPage.getPageNumber(), (int) ratingEntityPage.getPageElements(), ratingEntityPage.getTotalElements());
    } else {
        throw new UnauthorizedAccessException();
    }
}
 
Example #19
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 #20
Source File: LogicalNodeTable.java    From snowcast with Apache License 2.0 5 votes vote down vote up
@Min(128)
@Max(8192)
int attachLogicalNode(@Nonnull Address address) {
    while (true) {
        Object[] assignmentTable = this.assignmentTable;
        int freeSlot = findFreeSlot(assignmentTable);
        if (freeSlot == -1) {
            throw new SnowcastNodeIdsExceededException();
        }
        long offset = offset(freeSlot);
        if (UNSAFE.compareAndSwapObject(assignmentTable, offset, null, address)) {
            return freeSlot;
        }
    }
}
 
Example #21
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 #22
Source File: TaskManagerConfig.java    From presto with Apache License 2.0 5 votes vote down vote up
@Min(1)
public int getMinDrivers()
{
    if (minDrivers == null) {
        return 2 * maxWorkerThreads;
    }
    return minDrivers;
}
 
Example #23
Source File: ShoppingListApi.java    From commerce-cif-api with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/{id}/entries/{entryId}")
@ApiOperation(value = "Replaces an entry with the given one.")
@ApiResponses(value = {
    @ApiResponse(code = HTTP_BAD_REQUEST, message = HTTP_BAD_REQUEST_MESSAGE, response = ErrorResponse.class),
    @ApiResponse(code = HTTP_UNAUTHORIZED, message = HTTP_UNAUTHORIZED_MESSAGE, response = ErrorResponse.class),
    @ApiResponse(code = HTTP_NOT_FOUND, message = HTTP_NOT_FOUND_MESSAGE, response = ErrorResponse.class)
})
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
ShoppingListEntry putShoppingListEntry(
    @ApiParam(value = "The id of the shopping list.", required = true)
    @PathParam("id")
    String id,

    @ApiParam(value = "The id of the entry to replace.", required = true)
    @PathParam("entryId")
    String entryId,

    @ApiParam(value = "The quantity for the new entry.", required = true)
    @FormParam("quantity")
    @Min(value = 0)
    int quantity,

    @ApiParam(value = "The product variant id to be added to the entry. If the product variant exists in another entry in the shopping list, this request fails.", required = true)
    @FormParam("productVariantId")
    String productVariantId,

    @ApiParam(value = ACCEPT_LANGUAGE_DESC)
    @HeaderParam(ACCEPT_LANGUAGE) String acceptLanguage
);
 
Example #24
Source File: ConcurrencyUtil.java    From SpinalTap with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to shutdown the {@link ExecutorService}. If the service does not terminate within the
 * specified timeout, a force shutdown will be triggered.
 *
 * @param executorService the {@link ExecutorService}.
 * @param timeout the timeout.
 * @param unit the time unit.
 * @return {@code true} if shutdown was successful within the specified timeout, {@code false}
 *     otherwise.
 */
public boolean shutdownGracefully(
    @NonNull ExecutorService executorService, @Min(1) long timeout, @NonNull TimeUnit unit) {
  boolean shutdown = false;
  executorService.shutdown();
  try {
    shutdown = executorService.awaitTermination(timeout, unit);
  } catch (InterruptedException e) {
    executorService.shutdownNow();
  }
  if (!shutdown) {
    executorService.shutdownNow();
  }
  return shutdown;
}
 
Example #25
Source File: StoreApi.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Operation(summary = "Find purchase order by ID", tags = { "store" })
@ApiResponses(value = {
		@ApiResponse(responseCode = "200", description = "successful operation", content = @Content(schema = @Schema(implementation = Order.class))),
		@ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
		@ApiResponse(responseCode = "404", description = "Order not found") })
@GetMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" })
@ResponseBody
default ResponseEntity<Order> getOrderById(
		@Min(1L) @Max(5L) @Parameter(description = "ID of pet that needs to be fetched", required = true) @PathVariable("orderId") Long orderId) {
	return getDelegate().getOrderById(orderId);
}
 
Example #26
Source File: MyResource.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #27
Source File: JobExecutionEnvironment.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param request    The job request object.
 * @param clusterObj The cluster object.
 * @param commandObj The command object.
 * @param memory     The amount of memory (in MB) to use to run the job
 * @param dir        The directory location for this job.
 */
public Builder(
    @NotNull(message = "Job Request cannot be null") final JobRequest request,
    @NotNull(message = "Cluster cannot be null") final Cluster clusterObj,
    @NotNull(message = "Command cannot be null") final Command commandObj,
    @Min(value = 1, message = "Amount of memory can't be less than 1 MB") final int memory,
    @NotBlank(message = "Job working directory cannot be empty") final File dir
) {
    this.bJobRequest = request;
    this.bCluster = clusterObj;
    this.bCommand = commandObj;
    this.bMemory = memory;
    this.bJobWorkingDir = dir;
}
 
Example #28
Source File: FeaturesConfig.java    From presto with Apache License 2.0 4 votes vote down vote up
@Min(0)
public int getConcurrentLifespansPerTask()
{
    return concurrentLifespansPerTask;
}
 
Example #29
Source File: FeaturesConfig.java    From presto with Apache License 2.0 4 votes vote down vote up
@Min(0)
public int getRe2JDfaRetries()
{
    return re2JDfaRetries;
}
 
Example #30
Source File: SequencerDefinition.java    From snowcast with Apache License 2.0 4 votes vote down vote up
@Min(128)
@Max(8192)
public short getBackupCount() {
    return backupCount;
}