@Override @PreAuthorize("hasAuthority('admin')") public ResponseEntity<Object> globalsettingsHolidaysYearPost( @Min(2000) @Max(2100)@ApiParam(value = "",required=true ) @PathVariable("year") Integer year, @ApiParam(value = "The holidays to set" ,required=true ) @Valid @RequestBody Holidays holidays) throws ApiException { try { globalsettingsService.setHolidays(year, holidays); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } catch (OptimisticLockException ex) { try { Holidays lastHolidays = globalsettingsService.getHolidays(year); throw new ConcurrentModificationException(409, "Concurrent modification error.", lastHolidays); } catch (ApiException ex1) { Logger.getLogger(SettingsApiController.class.getName()).log(Level.SEVERE, null, ex1); throw new ApiException(500, "Concurrent modification exception: internal error"); } } }
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); } }
private void checkNumberInputType(Field field) { if("number".equals(type)){ Min min = field.getAnnotation(Min.class); if(min != null){ this.min = min.value(); } Max max = field.getAnnotation(Max.class); if(max != null){ this.max = max.value(); } Range range = field.getAnnotation(Range.class); if(range != null){ this.min = range.min(); this.max = range.max(); } } }
@Min(0) @Max(1) public double getFractionIdenticalOfAligned() { int nId = 0; int nNotIndel = 0; for (int i = 1; i <= m_sequencePair.getLength(); i++) { String a = m_sequencePair.getCompoundInTargetAt(i).getShortName(); String b = m_sequencePair.getCompoundInQueryAt(i).getShortName(); if (!a.equals("-") && !b.equals("-")) { nNotIndel++; if (a.equals(b)) { nId++; } } } return (double)nId / nNotIndel; }
@RequestMapping("/{year:[0-9]+}/{month:[0-9]+}/") public ModelAndView getArchiveByYearMonth(@PathVariable int year, @Valid @Min(1) @Max(12) @PathVariable int month) { LOGGER.debug("Getting the archive, year={}, month={}", year, month); // should not be needed in 4.1+ if (month < 1 || month > 12) { return new ModelAndView("error", null); } ModelMap model = new ModelMap(); model.addAttribute("posts", documentService.getRecentByYearMonth(year, month, 0, NUM_PER_PAGE)); model.addAttribute("count", documentService.getCountByYearMonth(year, month)); model.addAttribute("year", String.valueOf(year)); model.addAttribute("month", String.format("%02d", month)); LOGGER.trace("Generated model={}", model); return new ModelAndView("archive_year_month", model); }
@RequestMapping("/{year:[0-9]+}/{month:[0-9]+}/page/{page:[0-9]+}") public ModelAndView getArchiveByYearMonth(@PathVariable int year, @Valid @Min(1) @Max(12) @PathVariable int month, @PathVariable int page) { LOGGER.debug("Getting the archive, year={}, month={}, page={}", year, month, page); // should not be needed in 4.1+ if (month < 1 || month > 12) { return new ModelAndView("error", null); } ModelMap model = new ModelMap(); model.addAttribute("posts", documentService.getRecentByYearMonth(year, month, page - 1, NUM_PER_PAGE)); model.addAttribute("count", documentService.getCountByYearMonth(year, month)); model.addAttribute("year", String.valueOf(year)); model.addAttribute("month", String.format("%02d", month)); LOGGER.trace("Generated model={}", model); return new ModelAndView("archive_year_month", model); }
@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(); }
@Test public void testMax() { Set<ConstraintViolation<ObjectWithValidation>> violations = validator.validate(obj, Max.class); assertNotNull(violations); assertEquals(violations.size(), 1); if (runPeformance) { long time = System.currentTimeMillis(); for (int index = 0; index < 10000; index++) { validator.validate(obj, Max.class); } long used = System.currentTimeMillis() - time; System.out.println("Hibernate Validator [Max] check used " + used + "ms, avg. " + ((double) used) / 10000 + "ms."); } }
/** * This helper method provides a comparison implementation to order or compare two distinct * sequence ids by their internal timestamp <b>and</b> counter value. * * @param sequenceId1 the first sequence id to be compared * @param sequenceId2 the second sequence if to be compared * @param maxLogicalNodeCount the maximum node count that was specified at generation time * @return a negative integer, zero, or a positive integer as the first argument is less than, * equal to, or greater than the second. * @throws SnowcastMaxLogicalNodeIdOutOfBoundsException when maxLogicalNodeCount is outside of the legal range */ public static int compareSequence(long sequenceId1, long sequenceId2, @Min(128) @Max(8192) int maxLogicalNodeCount) { int nodeCount = calculateBoundedMaxLogicalNodeCount(maxLogicalNodeCount); int nodeIdShifting = calculateLogicalNodeShifting(nodeCount); long counterMask = calculateCounterMask(nodeCount, nodeIdShifting); long timestampValue1 = timestampValue(sequenceId1); long timestampValue2 = timestampValue(sequenceId2); int compare = Long.compare(timestampValue1, timestampValue2); if (compare != 0) { return compare; } int counterValue1 = InternalSequencerUtils.counterValue(sequenceId1, counterMask); int counterValue2 = InternalSequencerUtils.counterValue(sequenceId2, counterMask); return Integer.compare(counterValue1, counterValue2); }
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; } } }
@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); } }
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); }
@Nonnegative public static int calculateLogicalNodeShifting(@Min(128) @Max(8192) int maxLogicalNodeCount) { switch (maxLogicalNodeCount) { case MAX_LOGICAL_NODE_COUNT_128: return SHIFT_LOGICAL_NODE_ID_128; case MAX_LOGICAL_NODE_COUNT_256: return SHIFT_LOGICAL_NODE_ID_256; case MAX_LOGICAL_NODE_COUNT_512: return SHIFT_LOGICAL_NODE_ID_512; case MAX_LOGICAL_NODE_COUNT_1024: return SHIFT_LOGICAL_NODE_ID_1024; case MAX_LOGICAL_NODE_COUNT_2048: return SHIFT_LOGICAL_NODE_ID_2048; case MAX_LOGICAL_NODE_COUNT_4096: return SHIFT_LOGICAL_NODE_ID_4096; case MAX_LOGICAL_NODE_COUNT_8192: return SHIFT_LOGICAL_NODE_ID_8192; default: throw exception(IllegalArgumentException::new, ILLEGAL_MAX_LOGICAL_NODE_COUNT); } }
@Nonnull @Override public SnowcastSequencer createSequencer(@Nonnull String sequencerName, @Nonnull SnowcastEpoch epoch, @Min(128) @Max(8192) int maxLogicalNodeCount, short backupCount) { SequencerDefinition definition = new SequencerDefinition(sequencerName, epoch, maxLogicalNodeCount, backupCount); Operation operation = new CreateSequencerDefinitionOperation(definition); SequencerDefinition realDefinition = invoke(operation, sequencerName); if (!definition.equals(realDefinition)) { throw exception(SnowcastIllegalStateException::new, SEQUENCER_ALREADY_REGISTERED); } return getOrCreateSequencerProvision(realDefinition).getSequencer(); }
/** * Builds a new constraint from the annotation data. * @param anno JSR-303 annotation instance * @return a new constraint */ public static Constraint fromAnnotation(Annotation anno) { if (anno instanceof Min) { return min(((Min) anno).value()); } else if (anno instanceof Max) { return max(((Max) anno).value()); } else if (anno instanceof Size) { return size(((Size) anno).min(), ((Size) anno).max()); } else if (anno instanceof Digits) { return digits(((Digits) anno).integer(), ((Digits) anno).fraction()); } else if (anno instanceof Pattern) { return pattern(((Pattern) anno).regexp()); } else { return new Constraint(VALIDATORS.get(anno.annotationType()), simplePayload(VALIDATORS.get(anno.annotationType()))) { public boolean isValid(Object actualValue) { return true; } }; } }
@Override protected String getType() { String type = javaToHtmlTypes.get(valueType); if (type != null) { return type; } type = "text"; if (annotations != null) { if (annotations.containsKey(Email.class)) { type = "email"; } else if (annotations.containsKey(URL.class)) { type = "url"; } else if (annotations.containsKey(Max.class) || annotations.containsKey(Min.class)) { type = "number"; } } return type; }
@Test public void testConstraintsExtraction() { DynamicModelConstraints constraints = context.getRenderingContext().getModelConstraints().get(Person.class.getName()); assertNotNull("Constraints cannot be null", constraints); assertFalse("There should be field constraints", constraints.getFieldConstraints().isEmpty()); assertEquals("There should be 3 constraints", 3, constraints.getFieldConstraints().size()); testFieldAnnotation(constraints, "id", Min.class.getName(), Max.class.getName()); testFieldAnnotation(constraints, "name", NotNull.class.getName(), NotEmpty.class.getName()); testFieldAnnotation(constraints, "birthday", NotNull.class.getName()); }
@ApiOperation(value = "", notes = "get holidays by year", response = Holidays.class, authorizations = { @Authorization(value = "Bearer") }, tags={ "admin", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "ok", response = Holidays.class), @ApiResponse(code = 500, message = "An unexpected error occured.", response = com.jrtechnologies.yum.api.model.Error.class) }) @RequestMapping(value = "/globalsettings/holidays/{year}", produces = { "application/json" }, method = RequestMethod.GET) @CrossOrigin ResponseEntity<Holidays> globalsettingsHolidaysYearGet( @Min(2000) @Max(2100)@ApiParam(value = "",required=true ) @PathVariable("year") Integer year) throws ApiException;
@ApiOperation(value = "", notes = "set holidays by year", response = Void.class, authorizations = { @Authorization(value = "Bearer") }, tags={ "admin", }) @ApiResponses(value = { @ApiResponse(code = 204, message = "holidays saved", response = Void.class), @ApiResponse(code = 400, message = "An unexpected error occured.", response = com.jrtechnologies.yum.api.model.Error.class), @ApiResponse(code = 409, message = "Concurrent modification error", response = Holidays.class), @ApiResponse(code = 500, message = "An unexpected error occured.", response = com.jrtechnologies.yum.api.model.Error.class) }) @RequestMapping(value = "/globalsettings/holidays/{year}", produces = { "application/json" }, method = RequestMethod.POST) @CrossOrigin ResponseEntity<Object> globalsettingsHolidaysYearPost( @Min(2000) @Max(2100)@ApiParam(value = "",required=true ) @PathVariable("year") Integer year,@ApiParam(value = "The holidays to set" ,required=true ) @Valid @RequestBody Holidays holidays) throws ApiException;
private static void applyMax(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) { if ( Max.class.equals( descriptor.getAnnotation().annotationType() ) ) { @SuppressWarnings("unchecked") ConstraintDescriptor<Max> maxConstraint = (ConstraintDescriptor<Max>) descriptor; long max = maxConstraint.getAnnotation().value(); Column col = (Column) property.getColumnIterator().next(); String checkConstraint = col.getQuotedName(dialect) + "<=" + max; applySQLCheck( col, checkConstraint ); } }
@GET public Response getAll(@QueryParam("from") @DefaultValue("0") @Min(0) @Max(100) Integer start, @QueryParam("size") @DefaultValue("5") @Min(1) @Max(10) Integer size) { //In a good API-design, pagination (via an envelope or link-headers) would be added to a response that returns a collection. //But this is not in the scope of this demo List<Customer> customers = customerRepository.findAll(start, size); return Response.ok(customers).build(); }
private static MinijaxConstraintDescriptor<Max> buildMaxValidator(final Max max, final Class<?> valueClass) { if ((valueClass.isPrimitive() && valueClass != boolean.class) || Number.class.isAssignableFrom(valueClass)) { return new MinijaxConstraintDescriptor<>(max, new MaxValidator(max)); } throw new ValidationException("Unsupported type for @Min annotation: " + valueClass); }
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; }
@Override public Object process(AnnotationInfo ctx, Object value) throws Exception { if (!ctx.isAnnotationPresent(Min.class) && !ctx.isAnnotationPresent(Max.class)) { return value; } long minValue = 1; if (ctx.isAnnotationPresent(Min.class)) { minValue = ctx.getAnnotation(Min.class).value(); } long maxValue = 50; if (ctx.isAnnotationPresent(Max.class)) { maxValue = ctx.getAnnotation(Max.class).value(); } if (Number.class.isAssignableFrom(value.getClass())) { return range(String.valueOf(minValue), String.valueOf(maxValue), value.getClass()); } else if (value instanceof String) { String strVal = (String) value; if (strVal.length() < minValue) { strVal += RandomStringUtils.randomAlphabetic((int) minValue - strVal.length()); } else if (strVal.length() > maxValue) { strVal = strVal.substring(0, (int) maxValue); } return strVal; } return value; }
@NotNull @Min(0) @Max(9999) @Column(name = "quantidade_estoque", nullable = false) public Integer getQuantidadeEstoque() { return this.quantidadeEstoque; }
@Override public void validate(Max maxAnnotation, String name, ValidationContext validationCtx, Errors errors) { Object value = validationCtx.value(name); if (value == null) return; if (!(value instanceof Number)) errors.add(name, maxAnnotation.message(), value); if (!validateMax(Double.valueOf(maxAnnotation.value()), value)) { errors.add(name, maxAnnotation.message(), value, maxAnnotation.value()); } }
/** * 获取数量 * * @return 数量 */ @JsonProperty @NotNull @Min(1) @Max(10000) @Column(nullable = false) public Integer getQuantity() { return quantity; }
/** * 获取评分 * * @return 评分 */ @NotNull @Min(1) @Max(5) @Column(nullable = false, updatable = false) public Integer getScore() { return score; }
/** * 获取水印透明度 * * @return 水印透明度 */ @NotNull @Min(0) @Max(100) public Integer getWatermarkAlpha() { return watermarkAlpha; }
/** * 获取价格精确位数 * * @return 价格精确位数 */ @NotNull @Min(0) @Max(3) public Integer getPriceScale() { return priceScale; }
/** * 获取用户名最小长度 * * @return 用户名最小长度 */ @NotNull @Min(1) @Max(117) public Integer getUsernameMinLength() { return usernameMinLength; }
/** * 获取用户名最大长度 * * @return 用户名最大长度 */ @NotNull @Min(1) @Max(117) public Integer getUsernameMaxLength() { return usernameMaxLength; }
/** * 获取密码最小长度 * * @return 密码最小长度 */ @NotNull @Min(1) @Max(117) public Integer getPasswordMinLength() { return passwordMinLength; }
/** * 获取密码最大长度 * * @return 密码最大长度 */ @NotNull @Min(1) @Max(117) public Integer getPasswordMaxLength() { return passwordMaxLength; }
protected void addValidation(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); } }
@GET @CacheControl("no-cache") public Response getTopics( @QueryParam("label") final String label, @QueryParam("query") final String query, @QueryParam("offset") @Min(1) @DefaultValue("1") final Integer offset, @QueryParam("limit") @Min(1) @Max(100) @DefaultValue("10") final Integer limit, @QueryParam("setInfo") @DefaultValue("false") final boolean setInfo ) throws ClientErrorException { return delegate.getTopics(label, query, offset, limit, setInfo); }
@GET @Path("/{id}/posts") @CacheControl("no-cache") public Response getTopicPosts( @HeaderParam("If-Modified-Since") final String ifModifiedSince, @PathParam("id") final Long topicId, @QueryParam("offset") @Min(1) @DefaultValue("1") final Integer offset, @QueryParam("limit") @Min(1) @Max(50) @DefaultValue("10") final Integer limit ) throws ClientErrorException { return delegate.getPosts(ifModifiedSince, topicId, offset, limit); }
@GET @CacheControl("no-cache") public Response getMembers( @QueryParam("member") @NotNull(message= "{member.search.notnull}") final String member, @QueryParam("offset") @Min(1) @DefaultValue("1") final Integer offset, @QueryParam("limit") @Min(1) @Max(50) @DefaultValue("10") final Integer limit ) throws ClientErrorException { return delegate.getMembers(member, offset, limit); }
@GET @Path("/{id}/forums") @CacheControl("no-cache") public Response getForums( @HeaderParam("If-Modified-Since") final String ifModifiedSince, @PathParam("id") final Integer id, @QueryParam("offset") @Min(1) @DefaultValue("1") final Integer offset, @QueryParam("limit") @Min(1) @Max(50) @DefaultValue("10") final Integer limit ) throws ClientErrorException, ServerErrorException { return delegate.getForums(ifModifiedSince, id, offset, limit); }
@GET @CacheControl("no-cache") public Response getForums( @QueryParam("name") final String name, @QueryParam("label") final String label, @QueryParam("offset") @Min(1) @DefaultValue("1") final Integer offset, @QueryParam("limit") @Min(1) @Max(50) @DefaultValue("10") final Integer limit ) throws ClientErrorException { return delegate.getForums(name, label, offset, limit); }