项目:yum
文件:GlobalsettingsApiController.java
@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");
}
}
}
项目:aml
文件:AbstractGenerator.java
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);
}
}
项目:crud-admin-spring-boot-starter
文件:CrudAdminObjectField.java
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();
}
}
}
项目:sequence-alignment
文件:SequenceAlignment.java
@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;
}
项目:akanke
文件:BlogController.java
@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,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);
}
项目:akanke
文件:BlogController.java
@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,month={},page={}",page);
// should not be needed in 4.1+
if (month < 1 || month > 12) {
return new ModelAndView("error",page - 1,model);
}
项目:osiris
文件:SearchResourceImpl.java
@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,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,@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,"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,short backupCount) {
SequencerDeFinition deFinition = new SequencerDeFinition(sequencerName,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;
}
};
}
}
项目:spring-mvc-toolkit
文件:Html5InputTag.java
@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());
}
项目:yum
文件:GlobalsettingsApi.java
@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),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;
项目:yum
文件:GlobalsettingsApi.java
@ApiOperation(value = "",notes = "set holidays by year",response = Void.class,})
@ApiResponses(value = {
@ApiResponse(code = 204,message = "holidays saved",response = Void.class),response = com.jrtechnologies.yum.api.model.Error.class),@ApiResponse(code = 409,message = "Concurrent modification error",method = RequestMethod.POST)
@CrossOrigin
ResponseEntity<Object> globalsettingsHolidaysYearPost( @Min(2000) @Max(2100)@ApiParam(value = "",required=true ) @Valid @RequestBody Holidays holidays) throws ApiException;
项目:lams
文件:TypeSafeActivator.java
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 );
}
}
项目:java-ee-simple-sample
文件:CustomerResource.java
@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();
}
项目:minijax
文件:MinijaxConstraintDescriptor.java
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);
}
项目:tap17-muggl-javaee
文件:JPAEntityAnalyzer.java
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;
}
项目:randomito-all
文件:MinMaxAnnotationPostProcessor.java
@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;
}
项目:webpedidos
文件:Produto.java
@NotNull
@Min(0)
@Max(9999)
@Column(name = "quantidade_estoque",nullable = false)
public Integer getQuantidadeEstoque() {
return this.quantidadeEstoque;
}
项目:geeMVC-Java-MVC-Framework
文件:MaxValidationAdapter.java
@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,value,maxAnnotation.value());
}
}
项目:my-paper
文件:OrderItem.java
项目:my-paper
文件:Review.java
项目:my-paper
文件:Setting.java
/**
* 获取水印透明度
*
* @return 水印透明度
*/
@NotNull
@Min(0)
@Max(100)
public Integer getWatermarkAlpha() {
return watermarkAlpha;
}
项目:my-paper
文件:Setting.java
/**
* 获取价格精确位数
*
* @return 价格精确位数
*/
@NotNull
@Min(0)
@Max(3)
public Integer getPriceScale() {
return priceScale;
}
项目:my-paper
文件:Setting.java
项目:my-paper
文件:Setting.java
项目:my-paper
文件:Setting.java
项目:my-paper
文件:Setting.java
@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,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("limit") @Min(1) @Max(50) @DefaultValue("10") final Integer limit
)
throws ClientErrorException
{
return delegate.getPosts(ifModifiedSince,topicId,limit);
}
@GET
@Path("/{id}/forums")
@CacheControl("no-cache")
public Response getForums(
@HeaderParam("If-Modified-Since") final String ifModifiedSince,@PathParam("id") final Integer id,@QueryParam("limit") @Min(1) @Max(50) @DefaultValue("10") final Integer limit
)
throws ClientErrorException,ServerErrorException
{
return delegate.getForums(ifModifiedSince,id,limit);
}