當前位置: 首頁>>代碼示例>>Java>>正文


Java Size類代碼示例

本文整理匯總了Java中javax.validation.constraints.Size的典型用法代碼示例。如果您正苦於以下問題:Java Size類的具體用法?Java Size怎麽用?Java Size使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Size類屬於javax.validation.constraints包,在下文中一共展示了Size類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: apply

import javax.validation.constraints.Size; //導入依賴的package包/類
@Override
public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) {

    if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()
            && (node.has("minItems") || node.has("maxItems"))) {

        JAnnotationUse annotation = field.annotate(Size.class);

        if (node.has("minItems")) {
            annotation.param("min", node.get("minItems").asInt());
        }

        if (node.has("maxItems")) {
            annotation.param("max", node.get("maxItems").asInt());
        }
    }

    return field;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:20,代碼來源:MinItemsMaxItemsRule.java

示例2: address

import javax.validation.constraints.Size; //導入依賴的package包/類
@RequestMapping(value = "/address", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE,
        produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<AddressResponse> address(@Valid @RequestBody AddressRequest addressRequest,
                                               @Valid @Size(max = Constants.UUID_CHAR_MAX_SIZE) @RequestHeader(value="Authorization") String authorizationHeader,
                                               @Context HttpServletRequest httpServletRequest)
        throws BaseException {
    // Get token
    String emailConfirmationToken = getEmailConfirmationToken(authorizationHeader);

    // Get IP address from request
    String ipAddress = httpServletRequest.getHeader("X-Real-IP");
    if (ipAddress == null)
        ipAddress = httpServletRequest.getRemoteAddr();
    LOG.info("/address called from {} with token {}, address {}, refundBTC {} refundETH {}",
            ipAddress,
            emailConfirmationToken,
            addressRequest.getAddress(),
            addressRequest.getRefundBTC(),
            addressRequest.getRefundETH());

    return setWalletAddress(addressRequest, emailConfirmationToken);
}
 
開發者ID:modum-io,項目名稱:tokenapp-backend,代碼行數:23,代碼來源:AddressController.java

示例3: apply

import javax.validation.constraints.Size; //導入依賴的package包/類
@Override
public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) {
    
    if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()
            && (node.has("minLength") || node.has("maxLength"))) {

        JAnnotationUse annotation = field.annotate(Size.class);

        if (node.has("minLength")) {
            annotation.param("min", node.get("minLength").asInt());
        }

        if (node.has("maxLength")) {
            annotation.param("max", node.get("maxLength").asInt());
        }
    }

    return field;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:20,代碼來源:MinLengthMaxLengthRule.java

示例4: buildSizeValidator

import javax.validation.constraints.Size; //導入依賴的package包/類
private static MinijaxConstraintDescriptor<Size> buildSizeValidator(final Size size, final Class<?> valueClass) {
    if (valueClass.isArray()) {
        return new MinijaxConstraintDescriptor<>(size, new SizeValidatorForArray(size));
    }

    if (CharSequence.class.isAssignableFrom(valueClass)) {
        return new MinijaxConstraintDescriptor<>(size, new SizeValidatorForCharSequence(size));
    }

    if (Collection.class.isAssignableFrom(valueClass)) {
        return new MinijaxConstraintDescriptor<>(size, new SizeValidatorForCollection(size));
    }

    if (Map.class.isAssignableFrom(valueClass)) {
        return new MinijaxConstraintDescriptor<>(size, new SizeValidatorForMap(size));
    }

    throw new ValidationException("Unsupported type for @Size annotation: " + valueClass);
}
 
開發者ID:minijax,項目名稱:minijax,代碼行數:20,代碼來源:MinijaxConstraintDescriptor.java

示例5: jsr349CollectionInvalid

import javax.validation.constraints.Size; //導入依賴的package包/類
/**
 * Check validation errors success for collections.
 */
@Test
public void jsr349CollectionInvalid() {
	try {
		final SystemUser userDto = new SystemUser();
		userDto.setLogin("junit");
		validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("jsr349Collection"),
				Arrays.asList(Arrays.asList(userDto, userDto, userDto)));
		Assert.fail("Expected validation errors");
	} catch (final ConstraintViolationException cve) {

		// Check all expected errors are there.
		final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations();
		Assert.assertNotNull(constraintViolations);
		Assert.assertEquals(1, constraintViolations.size());

		// Check expected errors
		final ConstraintViolation<?> error1 = constraintViolations.iterator().next();
		Assert.assertEquals(Size.class, error1.getConstraintDescriptor().getAnnotation().annotationType());
		Assert.assertEquals("jsr349Collection.params", error1.getPropertyPath().toString());
	}
}
 
開發者ID:ligoj,項目名稱:bootstrap,代碼行數:25,代碼來源:JAXRSBeanValidationImplicitInInterceptorTest.java

示例6: createErrorMessage

import javax.validation.constraints.Size; //導入依賴的package包/類
private String createErrorMessage(Size sizeAnnotation, Message errorForLowerBound, Message errorForUpperBound) {
    StringBuilder errorMessageBuilder = new StringBuilder();

    appendNotProperSizeErrorMessage(errorMessageBuilder);
    if (sizeAnnotation.min() != 0) {
        appendFormattedErrorMessage(
                errorMessageBuilder,
                errorForLowerBound,
                sizeAnnotation.min());
    }
    if (sizeAnnotation.max() != Integer.MAX_VALUE) {
        appendFormattedErrorMessage(
                errorMessageBuilder,
                errorForUpperBound,
                sizeAnnotation.max());
    }

    return errorMessageBuilder.toString();
}
 
開發者ID:pablo127,項目名稱:GPigValidator,代碼行數:20,代碼來源:SizeValidator.java

示例7: process

import javax.validation.constraints.Size; //導入依賴的package包/類
@Override
public Object process(AnnotationInfo ctx, Object value) throws Exception {
    if (!ctx.isAnnotationPresent(Size.class)) {
        return value;
    }
    long minValue = ctx.getAnnotation(Size.class).min();
    if(minValue < 0 ) {
        minValue = 0;
    }
    long maxValue = ctx.getAnnotation(Size.class).max();
    if( maxValue > 10000 ){
        maxValue = 10000;
    }
    if (Number.class.isAssignableFrom(value.getClass())) {
        return range(String.valueOf(minValue), String.valueOf(maxValue), value.getClass());
    } else if (value instanceof String) {
        return RandomStringUtils.randomAlphanumeric((int) minValue, (int) maxValue);
    }
    return value;
}
 
開發者ID:randomito,項目名稱:randomito-all,代碼行數:21,代碼來源:SizeAnnotationPostProcessor.java

示例8: login

import javax.validation.constraints.Size; //導入依賴的package包/類
@PostMapping("/login")
public String login(
        @NotNull @Size(min = 1) String username,
        @NotNull @Size(min = 1) String password,
        Model model,
        HttpServletRequest request,
        HttpServletResponse response) throws UserApiException {

    LoginReq loginReq = new LoginReq();
    loginReq.setUsername(username);
    loginReq.setPassword(password);
    loginReq.setClientId("web_admin");
    loginReq.setClientVersion("1.0.0");
    LoginResult loginResult = accountApi.login(loginReq);

    UserContext userContext = new UserContext();
    userContext.setAccessToken(loginResult.getAccessToken());
    userContextProcessor.initialize(userContext, request, response);

    return "redirect:/";
}
 
開發者ID:richterplus,項目名稱:spring-cloud-sample,代碼行數:22,代碼來源:AccountController.java

示例9: compress

import javax.validation.constraints.Size; //導入依賴的package包/類
@RequestMapping(value = "compress")
public ResponseMessage compress(
		@RequestParam("url")
           @Size(min = 20, max = 300, message = "url 長度不符合規定")
		String url) {

       String shortUrl = null;
       try {
           shortUrl = service.compress(url);
       } catch (Exception e) {
           e.printStackTrace();
           logger.info("failed in compressing, unknown error");
           return new ResponseMessage(shortUrl, url, false, "url is not valid");
       }

	return new ResponseMessage(shortUrl, url, true, "succeed in compressing");
}
 
開發者ID:code4wt,項目名稱:short-url,代碼行數:18,代碼來源:ShortUrlController.java

示例10: getId

import javax.validation.constraints.Size; //導入依賴的package包/類
@Override
@Id
@Size(min = 16, max = 255)
@Access(value = AccessType.PROPERTY)
@Column(name = "token_data", nullable = false, length = 255)
public String getId() {
    return id;
}
 
開發者ID:suomenriistakeskus,項目名稱:oma-riista-web,代碼行數:9,代碼來源:EmailToken.java

示例11: stringFieldsMustHaveExplicitAndConsistentLengthDefinition

import javax.validation.constraints.Size; //導入依賴的package包/類
@Test
public void stringFieldsMustHaveExplicitAndConsistentLengthDefinition() {
    final Stream<Field> failedFields = filterFieldsOfManagedJpaTypes(field -> {
        final int modifiers = field.getModifiers();

        if (String.class.isAssignableFrom(field.getType()) &&
                !Modifier.isStatic(modifiers) &&
                !Modifier.isTransient(modifiers) &&
                !field.isAnnotationPresent(Transient.class) &&
                !field.isAnnotationPresent(Lob.class)) {

            final Column column = field.getAnnotation(Column.class);
            final Size size = field.getAnnotation(Size.class);

            return column == null && !hasIdGetter(field) ||
                    column != null && size != null && column.length() != size.max();
        }

        return false;
    });

    assertNoFields(failedFields,
            "These entity fields should be explicitly annotated with @Column and @Size with consistency on " +
                    "field's maximum length: ");
}
 
開發者ID:suomenriistakeskus,項目名稱:oma-riista-web,代碼行數:26,代碼來源:JpaModelTest.java

示例12: addJsr303Annotations

import javax.validation.constraints.Size; //導入依賴的package包/類
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);
	}
}
 
開發者ID:OnPositive,項目名稱:aml,代碼行數:39,代碼來源:AbstractGenerator.java

示例13: isConfirmationTokenValid

import javax.validation.constraints.Size; //導入依賴的package包/類
@RequestMapping(value = "/register/{emailConfirmationToken}/validate", method = GET)
public ResponseEntity<?> isConfirmationTokenValid(@Valid @Size(max = Constants.UUID_CHAR_MAX_SIZE) @PathVariable("emailConfirmationToken") String emailConfirmationToken,
                                                  @Context HttpServletRequest httpServletRequest)
        throws BaseException {
    // Get IP address from request
    String ipAddress = httpServletRequest.getHeader("X-Real-IP");
    if (ipAddress == null)
        ipAddress = httpServletRequest.getRemoteAddr();
    LOG.info("/validate called from {} with token {}", ipAddress, emailConfirmationToken);

    Optional<Investor> oInvestor = Optional.empty();
    try {
        oInvestor = investorRepository.findOptionalByEmailConfirmationToken(emailConfirmationToken);
    } catch (Exception e) {
        throw new UnexpectedException();
    }
    if (!oInvestor.isPresent()) {
        throw new ConfirmationTokenNotFoundException();
    }
    if (oInvestor.get().getWalletAddress() == null) {
        return ResponseEntity.ok().build();
    } else {
        AddressResponse addressResponse = new AddressResponse()
                .setBtc(addressService.getBitcoinAddressFromPublicKey(oInvestor.get().getPayInBitcoinPublicKey()))
                .setEther(addressService.getEthereumAddressFromPublicKey(oInvestor.get().getPayInEtherPublicKey()));
        return new ResponseEntity<>(addressResponse, HttpStatus.OK);
    }
}
 
開發者ID:modum-io,項目名稱:tokenapp-backend,代碼行數:29,代碼來源:RegisterController.java

示例14: getSizeMaxFileName

import javax.validation.constraints.Size; //導入依賴的package包/類
/** Verifie quele nom de fichier n'est pas trop long
 * @return la taille max d'un nom de fichier
 */
public Integer getSizeMaxFileName(){
	try {
		return Fichier.class.getDeclaredField(Fichier_.nomFichier.getName()).getAnnotation(Size.class).max();
	} catch (NoSuchFieldException | SecurityException e) {
		return 0;
	}
}
 
開發者ID:EsupPortail,項目名稱:esup-ecandidat,代碼行數:11,代碼來源:FileController.java

示例15: applySize

import javax.validation.constraints.Size; //導入依賴的package包/類
private static void applySize(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) {
	if ( Size.class.equals( descriptor.getAnnotation().annotationType() )
			&& String.class.equals( propertyDescriptor.getElementClass() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Size> sizeConstraint = (ConstraintDescriptor<Size>) descriptor;
		int max = sizeConstraint.getAnnotation().max();
		Column col = (Column) property.getColumnIterator().next();
		if ( max < Integer.MAX_VALUE ) {
			col.setLength( max );
		}
	}
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:13,代碼來源:TypeSafeActivator.java


注:本文中的javax.validation.constraints.Size類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。