@Override public Object process(AnnotationInfo ctx, Object value) throws Exception { if (!ctx.isAnnotationPresent(Digits.class)) { return value; } int integrals = ctx.getAnnotation(Digits.class).integer(); String number = "0"; if (integrals > 0) { number = RandomStringUtils.randomNumeric(integrals); } int fractions = ctx.getAnnotation(Digits.class).fraction(); if (fractions > 0) { number += "." + RandomStringUtils.randomNumeric(fractions); } return ReflectionUtils.stringToNumber(number, value.getClass()); }
@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; }
@Test public void testDigits() { Set<ConstraintViolation<ObjectWithValidation>> violations = validator.validate(obj, Digits.class); assertNotNull(violations); assertEquals(violations.size(), 1); if (runPeformance) { long time = System.currentTimeMillis(); for (int index = 0; index < 10000; index++) { validator.validate(obj, Digits.class); } long used = System.currentTimeMillis() - time; System.out.println("Hibernate Validator [Digits] check used " + used + "ms, avg. " + ((double) used) / 10000 + "ms."); } }
/** * 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; } }; } }
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; }
@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) { addItemToThis( type, charge, description, netAmount, vatAmount, grossAmount, tax, dueDate, period, property, project, budgetItem); return this; }
@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; }
@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; }
@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); // (we think there's) no need to add to the getItems(), because the item points back to this order. return this; }
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(); Column col = (Column) property.getColumnIterator().next(); col.setPrecision( integerDigits + fractionalDigits ); col.setScale( fractionalDigits ); } }
/** * 获取商品价格 * * @return 商品价格 */ @JsonProperty @NotNull @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, precision = 21, scale = 6) public BigDecimal getPrice() { return price; }
/** * 获取余额 * * @return 余额 */ @NotNull(groups = Save.class) @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, precision = 27, scale = 12) public BigDecimal getBalance() { return balance; }
/** * 获取付款金额 * * @return 付款金额 */ @NotNull @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, updatable = false, precision = 21, scale = 6) public BigDecimal getAmount() { return amount; }
/** * 获取运费 * * @return 运费 */ @NotNull @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, precision = 21, scale = 6) public BigDecimal getFreight() { return freight; }
/** * 获取调整金额 * * @return 调整金额 */ @NotNull @Digits(integer = 12, fraction = 3) @Column(nullable = false, precision = 21, scale = 6) public BigDecimal getOffsetAmount() { return offsetAmount; }
/** * 获取税金 * * @return 税金 */ @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, precision = 21, scale = 6) public BigDecimal getTax() { return tax; }
/** * 获取最小商品价格 * * @return 最小商品价格 */ @JsonProperty @Min(0) @Digits(integer = 12, fraction = 3) @Column(precision = 21, scale = 6) public BigDecimal getMinimumPrice() { return minimumPrice; }
/** * 获取最大商品价格 * * @return 最大商品价格 */ @JsonProperty @Min(0) @Digits(integer = 12, fraction = 3) @Column(precision = 21, scale = 6) public BigDecimal getMaximumPrice() { return maximumPrice; }
/** * 获取退款金额 * * @return 退款金额 */ @NotNull @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, updatable = false, precision = 21, scale = 6) public BigDecimal getAmount() { return amount; }
/** * 获取物流费用 * * @return 物流费用 */ @Min(0) @Digits(integer = 12, fraction = 3) @Column(updatable = false, precision = 21, scale = 6) public BigDecimal getFreight() { return freight; }
/** * 获取最小商品价格 * * @return 最小商品价格 */ @Min(0) @Digits(integer = 12, fraction = 3) @Column(precision = 21, scale = 6) public BigDecimal getMinimumPrice() { return minimumPrice; }
/** * 获取最大商品价格 * * @return 最大商品价格 */ @Min(0) @Digits(integer = 12, fraction = 3) @Column(precision = 21, scale = 6) public BigDecimal getMaximumPrice() { return maximumPrice; }
/** * 获取优惠比例 * * @return 优惠比例 */ @NotNull @Min(0) @Digits(integer = 3, fraction = 3) @Column(nullable = false, precision = 12, scale = 6) public Double getScale() { return scale; }
/** * 获取消费金额 * * @return 消费金额 */ @Min(0) @Digits(integer = 12, fraction = 3) @Column(unique = true, precision = 21, scale = 6) public BigDecimal getAmount() { return amount; }
/** * 获取首重价格 * * @return 首重价格 */ @NotNull @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, precision = 21, scale = 6) public BigDecimal getFirstPrice() { return firstPrice; }
/** * 获取续重价格 * * @return 续重价格 */ @NotNull @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, precision = 21, scale = 6) public BigDecimal getContinuePrice() { return continuePrice; }
/** * 获取销售价 * * @return 销售价 */ @JsonProperty @Field(store = Store.YES, index = Index.UN_TOKENIZED) @NumericField @FieldBridge(impl = BigDecimalNumericFieldBridge.class) @NotNull @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, precision = 21, scale = 6) public BigDecimal getPrice() { return price; }
/** * 获取成本价 * * @return 成本价 */ @Min(0) @Digits(integer = 12, fraction = 3) @Column(precision = 21, scale = 6) public BigDecimal getCost() { return cost; }
/** * 获取市场价 * * @return 市场价 */ @Field(store = Store.YES, index = Index.NO) @Min(0) @Digits(integer = 12, fraction = 3) @Column(nullable = false, precision = 21, scale = 6) public BigDecimal getMarketPrice() { return marketPrice; }
/** * 获取默认市场价换算比例 * * @return 默认市场价换算比例 */ @NotNull @Min(0) @Digits(integer = 3, fraction = 3) public Double getDefaultMarketPriceScale() { return defaultMarketPriceScale; }
/** * 获取默认积分换算比例 * * @return 默认积分换算比例 */ @NotNull @Min(0) @Digits(integer = 3, fraction = 3) public Double getDefaultPointScale() { return defaultPointScale; }
/** * 获取税率 * * @return 税率 */ @NotNull @Min(0) @Digits(integer = 3, fraction = 3) public Double getTaxRate() { return taxRate; }
@Override public void initialize(Digits constraintAnnotation) { this.maxIntegerLength = constraintAnnotation.integer(); this.maxFractionLength = constraintAnnotation.fraction(); validateParameters(); super.initialize(constraintAnnotation); }
@GetAction("/digits") public void digits(@Digits(integer = 4, fraction = 2) String str, ActionContext context, @Digits(integer = 3, fraction = 0) Integer num) { if (context.hasViolation()) { renderText("Error(s): \n%s", context.violationMessage()); } renderText("digits success with %s and %s", str, num); }
@GET @Path("/byStudentId/{studentId}") @Produces({ "application/json" }) public Response getStudentsByStudentId( @NotNull @Digits(integer = 7, fraction = 0) @PathParam("studentId") String studentId) { Student s = null; try { s = service.getStudentByKey(studentId); } catch (NoResultException e) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok().entity(s).build(); }
@POST @Path("/update/{studentId}") @Produces({ "application/json" }) public Response update(@NotNull @Digits(integer = 7, fraction = 0) @PathParam("studentId") String studentId, @NotNull Student student) throws URISyntaxException { try { service.update(studentId, student); //Here there was a bug because I forgot that EJBException swallow RuntimeException and NoResultException is a Runtime. //To solve that problem I defined NoResultException as an ApplicationException in the ejb-jar.xml } catch (NoResultException e) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.status(200).contentLocation(new URI("students/byStudentId/" + student.getStudentId())).build(); }
/** * Obtiene de la UI los datos validados de la Guarnicion a crear * @param nombreGuarnicion String * @param descripcionGuarnicion String * @param precioGuarnicion BigDecimal * @return crearGuarnicionNueva() Guarnicion */ @Named("Guarnicion") @MemberOrder(name = "Crear", sequence = "1") public Guarnicion crearGuarnicion( @Named("Nombre") @RegEx(validation = "[0-9a-zA-ZáéíoúÁÉÍoÚñÑ\\s]*") @MaxLength(value = 30) final String nombreGuarnicion, @Named("Descripcion") @Optional @MultiLine(numberOfLines = 3) final String descripcionGuarnicion, @Named("Precio") @MaxLength(value = 5) @Digits(integer = 2, fraction = 2) final BigDecimal precioGuarnicion) { return crearGuarnicionNueva(nombreGuarnicion, descripcionGuarnicion, precioGuarnicion); }
/** * Obtiene de la UI los datos validados del Plato de entrada a crear * @param nombre String * @param unaCondicion CondicionDePlatoEnum * @param unaDescripcion String * @param unPrecio BigDecimal * @return crearUnPlatoEntreda() PlatoEntrada */ @Named("Plato de Entrada") @MemberOrder(name = "Crear", sequence = "1") public Plato crearPlatoEntrada( /* Parametros de Entrada */ @RegEx(validation = "[0-9a-zA-ZáéíóúÁÉÍÓÚñÑ\\s]*") @MaxLength(value = 30) @Named("Nombre") final String nombre, @Named("Condición") final CondicionDePlatoEnum unaCondicion, @Optional @MultiLine(numberOfLines = 3) @Named("Descripción") final String unaDescripcion, @Named("Precio") @MaxLength(value = 6) @Digits(integer = 3, fraction = 2) final BigDecimal unPrecio) { /* Empieza el metodo */ return crearUnPlatoEntrada(nombre, unaCondicion, unaDescripcion, unPrecio); }
/** * Obtiene de la UI los datos validados de un postre a crear * @param nombrePostre String * @param descripcionPostre String * @param preciopostre BigDecimal * @return crearGPostreNuevo() Postre */ @Named("Postre") @MemberOrder(name = "Crear", sequence = "1") public Postre crearPostre( @Named("Nombre") @RegEx(validation = "[0-9a-zA-ZáéíóúÁÉÍÓÚñÑ\\s]*") @MaxLength(value = 30) final String nombrePostre, @Optional @MultiLine(numberOfLines = 3) @Named("Descripción") final String descripcionPostre, @Named("Precio") @MaxLength(value = 5) @Digits(integer = 2, fraction = 2) final BigDecimal precioPostre) { return crearPostreNuevo(nombrePostre, descripcionPostre, precioPostre); }