javax.validation.constraints.Digits Java Examples

The following examples show how to use javax.validation.constraints.Digits. 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: Constraint.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
					}
				};
	}
}
 
Example #2
Source File: IncomingInvoiceItem.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Action(semantics = SemanticsOf.IDEMPOTENT)
public IncomingInvoiceItem updateAmounts(
        @Digits(integer=13, fraction = 2)
        final BigDecimal netAmount,
        @Nullable
        @Digits(integer=13, fraction = 2)
        final BigDecimal vatAmount,
        @Digits(integer=13, fraction = 2)
        final BigDecimal grossAmount,
        @Nullable
        final Tax tax){
    setNetAmount(netAmount);
    setVatAmount(vatAmount);
    setGrossAmount(grossAmount);
    setTax(tax);
    IncomingInvoice invoice = (IncomingInvoice) getInvoice();
    return this;
}
 
Example #3
Source File: IncomingInvoice.java    From estatio with Apache License 2.0 6 votes vote down vote up
@MemberOrder(name = "items", sequence = "2")
public IncomingInvoice splitItem(
        final IncomingInvoiceItem itemToSplit,
        final String newItemDescription,
        @Digits(integer = 13, fraction = 2) final BigDecimal newItemNetAmount,
        @Nullable
        @Digits(integer = 13, fraction = 2) final BigDecimal newItemVatAmount,
        @Nullable final Tax newItemtax,
        @Digits(integer = 13, fraction = 2) final BigDecimal newItemGrossAmount,
        final Charge newItemCharge,
        @Nullable final Property newItemProperty,
        @Nullable final Project newItemProject,
        @Nullable final BudgetItem newItemBudgetItem,
        final String newItemPeriod
) {
    itemToSplit.subtractAmounts(newItemNetAmount, newItemVatAmount, newItemGrossAmount);
    addItemInternal(getType(), newItemCharge, newItemDescription, newItemNetAmount,
            newItemVatAmount, newItemGrossAmount, newItemtax, getDueDate(), newItemPeriod, newItemProperty,
            newItemProject, newItemBudgetItem);
    return this;
}
 
Example #4
Source File: IncomingInvoice.java    From estatio with Apache License 2.0 6 votes vote down vote up
@MemberOrder(name = "items", sequence = "1")
public IncomingInvoice addItem(
        final IncomingInvoiceType type,
        final Charge charge,
        final String description,
        @Digits(integer = 13, fraction = 2) final BigDecimal netAmount,
        @Nullable
        @Digits(integer = 13, fraction = 2) final BigDecimal vatAmount,
        @Digits(integer = 13, fraction = 2) final BigDecimal grossAmount,
        @Nullable final Tax tax,
        @Nullable final LocalDate dueDate,
        @Nullable final String period,
        @Nullable final Property property,
        @Nullable final Project project,
        @Nullable final BudgetItem budgetItem) {

    addItemInternal(
            type, charge, description, netAmount, vatAmount, grossAmount, tax, dueDate,
            period, property, project, budgetItem);
    return this;
}
 
Example #5
Source File: IncomingDocViewModel.java    From estatio with Apache License 2.0 6 votes vote down vote up
public IncomingDocViewModel changeItemDetails(
        final String description,
        @Digits(integer=13, fraction = 2)
        final BigDecimal netAmount,
        @Digits(integer=13, fraction = 2)
        @Nullable
        final BigDecimal vatAmount,
        @Nullable
        final Tax tax,
        @Digits(integer=13, fraction = 2)
        @Nullable
        final BigDecimal grossAmount
){
    setDescription(description);
    setNetAmount(netAmount);
    setVatAmount(vatAmount);
    setTax(tax);
    setGrossAmount(grossAmount);
    calculateVat();
    determineAmounts();
    return this;
}
 
Example #6
Source File: Order.java    From estatio with Apache License 2.0 6 votes vote down vote up
@MemberOrder(name = "items", sequence = "1")
public Order addItem(
        final Charge charge,
        @Nullable final String description,
        @Digits(integer = 13, fraction = 2) final BigDecimal netAmount,
        @Nullable
        @Digits(integer = 13, fraction = 2) final BigDecimal vatAmount,
        @Nullable
        @Digits(integer = 13, fraction = 2) final BigDecimal grossAmount,
        @Nullable final Tax tax,
        @Nullable final String period,
        @Nullable final org.estatio.module.asset.dom.Property property,
        @Nullable final Project project,
        @Nullable final BudgetItem budgetItem
) {
    orderItemRepository.upsert(
            this, charge, description, netAmount, vatAmount, grossAmount, tax, PeriodUtil.yearFromPeriod(period).startDate(), PeriodUtil.yearFromPeriod(period).endDate(), property, project, budgetItem, determineItemNumber(charge));

    return this;
}
 
Example #7
Source File: BeanValidationTest.java    From easy-random with MIT License 6 votes vote down vote up
@Test
void customRegistryTest() {
    // given
    class Salary {
        @Digits(integer = 2, fraction = 2) // OSS developer salary.. :-)
        private BigDecimal amount;
    }
    
    EasyRandomParameters parameters = new EasyRandomParameters()
            .randomizerRegistry(new MyCustomBeanValidationRandomizerRegistry());
    EasyRandom easyRandom = new EasyRandom(parameters);
    
    // when
    Salary salary = easyRandom.nextObject(Salary.class);
    
    // then
    assertThat(salary).isNotNull();
    assertThat(salary.amount).isLessThanOrEqualTo(new BigDecimal("99.99"));
}
 
Example #8
Source File: ToDoItem.java    From isis-app-todoapp with Apache License 2.0 6 votes vote down vote up
@Action(
        semantics = SemanticsOf.IDEMPOTENT
)
public ToDoItem updateCost(
        @Parameter(optionality = Optionality.OPTIONAL)
        @Digits(integer = 10, fraction = 2)
        final BigDecimal newCost) {
    final String titleOf = titleService.titleOf(this);
    LOG.debug("%s: cost updated: %s -> %s", titleOf, getCost(), newCost);

    // just to simulate a long-running action
    try {
        Thread.sleep(3000);
    } catch (final InterruptedException ignored) {
    }

    setCost(newCost);
    return this;
}
 
Example #9
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyDigits(Property property, ConstraintDescriptor<?> descriptor) {
	if ( Digits.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Digits> digitsConstraint = (ConstraintDescriptor<Digits>) descriptor;
		int integerDigits = digitsConstraint.getAnnotation().integer();
		int fractionalDigits = digitsConstraint.getAnnotation().fraction();

		@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;
				col.setPrecision( integerDigits + fractionalDigits );
				col.setScale( fractionalDigits );
			}
		}

	}
}
 
Example #10
Source File: OrderItem_createInvoiceItemLink.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Action(semantics = SemanticsOf.NON_IDEMPOTENT)
@MemberOrder(name = "invoiceItemLinks", sequence = "1")
public OrderItem act(
        final IncomingInvoiceItem invoiceItem,
        @Digits(integer = 13, fraction = 2)
        final BigDecimal netAmount){
    orderItemInvoiceItemLinkRepository.createLink(mixee, invoiceItem, netAmount);
    return mixee;
}
 
Example #11
Source File: IncomingInvoiceItem_updateOrderItemLink.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Action(semantics = SemanticsOf.NON_IDEMPOTENT)
@MemberOrder(name = "linkedAmount", sequence = "1")
public IncomingInvoiceItem act(
        @Digits(integer = 13, fraction = 2)
        final BigDecimal netAmount) {

    linkIfAny().ifPresent(link -> link.setNetAmount(netAmount));

    return mixee;
}
 
Example #12
Source File: ValidationUtils.java    From para with Apache License 2.0 5 votes vote down vote up
private static void buildAndValidateConstraint(Map.Entry<String, Map<String, ?>> constraint, String field,
		Object actualValue, LinkedList<String> errors) {
	if (constraint == null) {
		return;
	}
	String consName = constraint.getKey();
	Map<String, ?> vals = constraint.getValue();
	if (vals == null) {
		vals = Collections.emptyMap();
	}

	Object val = vals.get("value");
	long min = NumberUtils.toLong(vals.get("min") + "", 0);
	long max = NumberUtils.toLong(vals.get("max") + "", Config.DEFAULT_LIMIT);

	if (isValidSimpleConstraint(consName, field, actualValue, errors)) {
		if (matches(Min.class, consName) && !min(NumberUtils.toLong(val + "", 0)).isValid(actualValue)) {
			errors.add(Utils.formatMessage("{0} must be a number larger than {1}.", field, val));
		} else if (matches(Max.class, consName) && !max(NumberUtils.toLong(val + "",
				Config.DEFAULT_LIMIT)).isValid(actualValue)) {
			errors.add(Utils.formatMessage("{0} must be a number smaller than {1}.", field, val));
		} else if (matches(Size.class, consName) && !size(min, max).isValid(actualValue)) {
			errors.add(Utils.formatMessage("{0} must be between {1} and {2}.", field, min, max));
		} else if (matches(Digits.class, consName) && !digits(NumberUtils.toLong(vals.get("integer") + "", 0),
				NumberUtils.toLong(vals.get("fraction") + "", 0)).isValid(actualValue)) {
			errors.add(Utils.formatMessage("{0} is not a valid number or within range.", field));
		} else if (matches(Pattern.class, consName) && !pattern(val).isValid(actualValue)) {
			errors.add(Utils.formatMessage("{0} doesn't match the pattern {1}.", field, val));
		}
	}
}
 
Example #13
Source File: Constraint.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new map representing a {@link Digits} validation constraint.
 * @param i the max size of the integral part of the number
 * @param f the max size of the fractional part of the number
 * @return a map
 */
static Map<String, Object> digitsPayload(final Object i, final Object f) {
	if (i == null || f == null) {
		return null;
	}
	Map<String, Object> payload = new LinkedHashMap<>();
	payload.put("integer", i);
	payload.put("fraction", f);
	payload.put("message", MSG_PREFIX + VALIDATORS.get(Digits.class));
	return payload;
}
 
Example #14
Source File: IncomingInvoiceItem_createOrderItemLink.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Action(semantics = SemanticsOf.NON_IDEMPOTENT)
@MemberOrder(name = "orderItem", sequence = "1")
public IncomingInvoiceItem act(
        final OrderItem orderItem,
        @Digits(integer = 13, fraction = 2)
        final BigDecimal netAmount){
    orderItemInvoiceItemLinkRepository.createLink(orderItem, mixee, netAmount);
    mixee.copyChargeAndProjectFromSingleLinkedOrderItemIfAny();
    return mixee;
}
 
Example #15
Source File: Order_itemDetails.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Action()
public Order act(
        final String description,
        @Digits(integer = 13, fraction = 2) final BigDecimal netAmount,
        @Digits(integer = 13, fraction = 2)
        @Nullable final BigDecimal vatAmount,
        @Nullable final Tax tax,
        @Digits(integer = 13, fraction = 2) final BigDecimal grossAmount,
        final Charge charge,
        @Nullable final Project project,
        @Nullable final BudgetItem budgetItem,
        final String period) {
    if (order.getItems().size() <= 1) {
        orderItemRepository.upsert(
                order,
                charge,
                description,
                netAmount,
                vatAmount,
                grossAmount,
                tax,
                PeriodUtil.yearFromPeriod(period).startDate(),
                PeriodUtil.yearFromPeriod(period).endDate(),
                order.getProperty(),
                project,
                budgetItem,
                0);
    }
    return order;
}
 
Example #16
Source File: Order.java    From estatio with Apache License 2.0 5 votes vote down vote up
@MemberOrder(name = "items", sequence = "2")
public Order splitItem(
        final OrderItem itemToSplit,
        final String newItemDescription,
        @Digits(integer = 13, fraction = 2) final BigDecimal newItemNetAmount,
        @Nullable @Digits(integer = 13, fraction = 2) final BigDecimal newItemVatAmount,
        @Nullable final Tax newItemtax,
        @Digits(integer = 13, fraction = 2) final BigDecimal newItemGrossAmount,
        final Charge newItemCharge,
        @Nullable final org.estatio.module.asset.dom.Property newItemProperty,
        @Nullable final Project newItemProject,
        @Nullable final BudgetItem newItemBudgetItem,
        @Nullable final String newItemPeriod
) {
    itemToSplit.subtractAmounts(newItemNetAmount, newItemVatAmount, newItemGrossAmount);
    orderItemRepository.upsert(
            this,
            newItemCharge,
            newItemDescription,
            newItemNetAmount,
            newItemVatAmount,
            newItemGrossAmount,
            newItemtax,
            newItemPeriod != null ? PeriodUtil.yearFromPeriod(newItemPeriod).startDate() : null,
            newItemPeriod != null ? PeriodUtil.yearFromPeriod(newItemPeriod).endDate() : null,
            newItemProperty,
            newItemProject,
            newItemBudgetItem,
            0);
    return this;
}
 
Example #17
Source File: OrderItem.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Action(semantics = SemanticsOf.IDEMPOTENT)
public OrderItem updateAmounts(
        @Digits(integer = 13, fraction = 2) final BigDecimal netAmount,
        @Nullable
        @Digits(integer = 13, fraction = 2) final BigDecimal vatAmount,
        @Nullable
        @Digits(integer = 13, fraction = 2) final BigDecimal grossAmount,
        @Nullable final Tax tax) {
    setNetAmount(netAmount);
    setVatAmount(vatAmount);
    setGrossAmount(grossAmount);
    setTax(tax);
    return this;
}
 
Example #18
Source File: OrderItem_updateInvoiceItemLink.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Action(semantics = SemanticsOf.NON_IDEMPOTENT)
@MemberOrder(name = "invoiceItemLinks", sequence = "1")
public OrderItem act(
        final IncomingInvoiceItem invoiceItem,
        @Digits(integer = 13, fraction = 2)
        final BigDecimal netAmount){
    final OrderItemInvoiceItemLink link = orderItemInvoiceItemLinkRepository.findUnique(mixee, invoiceItem);
    if(link != null) {
        link.setNetAmount(netAmount);
    }
    return mixee;
}
 
Example #19
Source File: HibernateValidatorTestResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/rest-end-point-generic-method-validation/{id}")
@Produces(MediaType.TEXT_PLAIN)
@Override
public Integer testRestEndpointGenericMethodValidation(@Digits(integer = 5, fraction = 0) @PathParam("id") Integer id) {
    return id;
}
 
Example #20
Source File: KeyItem.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Digits(integer = 13, fraction = 6)
@Action(semantics = SemanticsOf.SAFE)
public BigDecimal getDivCalculatedSourceValue(){
    KeyTable keyTable = (KeyTable) getPartitioningTable();
    if (keyTable.getFoundationValueType() == FoundationValueType.AREA) {
        return getUnit().getArea() != null ? getUnit().getArea().subtract(getSourceValue()).setScale(6, RoundingMode.HALF_UP) : BigDecimal.ZERO;
    }
    return BigDecimal.ZERO;
}
 
Example #21
Source File: IncomingInvoice.java    From estatio with Apache License 2.0 5 votes vote down vote up
@org.apache.isis.applib.annotation.Property(hidden = Where.ALL_TABLES)
@Digits(integer = 9, fraction = 2)
public BigDecimal getVatAmount() {
    return getGrossAmount() != null && getNetAmount() != null
            ? getGrossAmount().subtract(getNetAmount())
            : null;
}
 
Example #22
Source File: OrderItem_netAmountInvoiced.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Action(semantics = SemanticsOf.SAFE)
@ActionLayout(contributed= Contributed.AS_ASSOCIATION)
@Digits(integer = 13, fraction = 2)
public BigDecimal prop() {
    return orderItemInvoiceItemLinkRepository.calculateNetAmountLinkedToOrderItem(mixee);
}
 
Example #23
Source File: IncomingDocViewModel.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Digits(integer=13, fraction = 2)
public BigDecimal getVatAmount() {
    return vatAmount;
}
 
Example #24
Source File: LeaseAmendmentItemForDiscount.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Action(semantics = SemanticsOf.IDEMPOTENT)
public LeaseAmendmentItemForDiscount changeDiscountPercentage(@Digits(integer = 3, fraction = 2) final BigDecimal newPercentage){
    setDiscountPercentage(newPercentage);
    this.getLeaseAmendment().createOrRenewLeasePreview();
    return this;
}
 
Example #25
Source File: IncomingDocViewModel.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Digits(integer=13, fraction = 2)
public BigDecimal getGrossAmount() {
    return grossAmount;
}
 
Example #26
Source File: DefaultModelPlugin.java    From BlogManagePlatform with Apache License 2.0 4 votes vote down vote up
private String resolveRange(Field field) {
	String min = Optional.ofNullable(field.getAnnotation(Min.class)).map((item) -> String.valueOf(item.value())).orElse(null);
	if (min == null) {
		min = Optional.ofNullable(field.getAnnotation(DecimalMin.class)).map(DecimalMin::value).orElse(null);
	}
	if (field.isAnnotationPresent(PositiveOrZero.class)) {
		if (min == null || new BigDecimal(min).compareTo(BigDecimal.ZERO) < 0) {
			min = "非负数";
		}
	}
	if (field.isAnnotationPresent(Positive.class)) {
		if (min == null || new BigDecimal(min).compareTo(BigDecimal.ZERO) <= 0) {
			min = "正数";
		}
	}
	min = min == null ? null : StrUtil.concat("最小值为", min);
	if (field.isAnnotationPresent(DecimalMin.class)) {
		if (!field.getAnnotation(DecimalMin.class).inclusive()) {
			min = min == null ? null : StrUtil.concat(min, "且不能等于最小值");
		}
	}
	String max = Optional.ofNullable(field.getAnnotation(Max.class)).map((item) -> String.valueOf(item.value())).orElse(null);
	if (max == null) {
		max = Optional.ofNullable(field.getAnnotation(DecimalMax.class)).map(DecimalMax::value).orElse(null);
	}
	if (field.isAnnotationPresent(NegativeOrZero.class)) {
		if (max == null || new BigDecimal(max).compareTo(BigDecimal.ZERO) > 0) {
			max = "非正数";
		}
	}
	if (field.isAnnotationPresent(Negative.class)) {
		if (max == null || new BigDecimal(min).compareTo(BigDecimal.ZERO) >= 0) {
			max = "负数";
		}
	}
	max = max == null ? null : StrUtil.concat("最大值为", max);
	if (field.isAnnotationPresent(DecimalMax.class)) {
		if (!field.getAnnotation(DecimalMax.class).inclusive()) {
			min = min == null ? null : StrUtil.concat(min, "且不能等于最大值");
		}
	}
	String digit = Optional.ofNullable(field.getAnnotation(Digits.class)).map((item) -> {
		String integer = String.valueOf(item.integer());
		String fraction = String.valueOf(item.fraction());
		return StrUtil.concat("整数位", integer, ",", "小数位", fraction);
	}).orElse(null);
	if (min == null && max == null && digit == null) {
		return null;
	}
	return StrUtil.join(",", min, max, digit);
}
 
Example #27
Source File: IncomingDocViewModel.java    From estatio with Apache License 2.0 4 votes vote down vote up
@Digits(integer=13, fraction = 2)
public BigDecimal getNetAmount() {
    return netAmount;
}
 
Example #28
Source File: MyCustomBeanValidationRandomizerRegistry.java    From easy-random with MIT License 4 votes vote down vote up
@Override
public void init(EasyRandomParameters parameters) {
	super.init(parameters);
	annotationHandlers.put(Digits.class, new MyCustomDigitsAnnotationHandler());
}
 
Example #29
Source File: BatchLeaveManagement.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
@Transactional(rollbackOn = {Exception.class})
public void createLeaveManagement(Employee employee) throws AxelorException {

  batch = batchRepo.find(batch.getId());
  LeaveLine leaveLine = null;
  LeaveReason leaveReason = batch.getHrBatch().getLeaveReason();

  if (employee != null) {
    leaveLine = leaveServiceProvider.get().addLeaveReasonOrCreateIt(employee, leaveReason);

    BigDecimal dayNumber =
        batch.getHrBatch().getUseWeeklyPlanningCoef()
            ? batch
                .getHrBatch()
                .getDayNumber()
                .multiply(employee.getWeeklyPlanning().getLeaveCoef())
            : batch.getHrBatch().getDayNumber();
    dayNumber =
        dayNumber.subtract(
            new BigDecimal(
                publicHolidayService.getImposedDayNumber(
                    employee,
                    batch.getHrBatch().getStartDate(),
                    batch.getHrBatch().getEndDate())));
    LeaveManagement leaveManagement =
        leaveManagementService.createLeaveManagement(
            leaveLine,
            AuthUtils.getUser(),
            batch.getHrBatch().getComments(),
            null,
            batch.getHrBatch().getStartDate(),
            batch.getHrBatch().getEndDate(),
            dayNumber);
    BigDecimal qty = leaveLine.getQuantity().add(dayNumber);
    BigDecimal totalQty = leaveLine.getTotalQuantity().add(dayNumber);

    try {
      int integer =
          LeaveLine.class.getDeclaredField("quantity").getAnnotation(Digits.class).integer();
      BigDecimal limit = new BigDecimal((long) Math.pow(10, integer));
      if (qty.compareTo(limit) >= 0 || totalQty.compareTo(limit) >= 0) {
        throw new AxelorException(
            employee,
            TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
            I18n.get(IExceptionMessage.BATCH_LEAVE_MANAGEMENT_QTY_OUT_OF_BOUNDS),
            limit.longValue());
      }

    } catch (NoSuchFieldException | SecurityException e) {
      throw new AxelorException(e, TraceBackRepository.CATEGORY_CONFIGURATION_ERROR);
    }

    leaveLine.setQuantity(qty.setScale(4, RoundingMode.HALF_EVEN));
    leaveLine.setTotalQuantity(totalQty.setScale(4, RoundingMode.HALF_EVEN));

    leaveManagementRepository.save(leaveManagement);
    leaveLineRepository.save(leaveLine);
    updateEmployee(employee);
  }
}
 
Example #30
Source File: DigitsPropertyValidator.java    From dolphin-platform with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(final Digits digitsAnnotation) {
	this.maxIntegerLength = digitsAnnotation.integer();
	this.maxFractionLength = digitsAnnotation.fraction();
	validateParameters();
}