Example usage for java.math BigDecimal ZERO

List of usage examples for java.math BigDecimal ZERO

Introduction

In this page you can find the example usage for java.math BigDecimal ZERO.

Prototype

BigDecimal ZERO

To view the source code for java.math BigDecimal ZERO.

Click Source Link

Document

The value 0, with a scale of 0.

Usage

From source file:com.nkapps.billing.dao.PaymentDaoImpl.java

@Override
public void saveKeyPaymentAndTransaction(BigDecimal keyTransactionId, BigDecimal keyCost) throws Exception {
    Session session = getSession();/*  ww w.j  av a2s.  c  om*/
    Transaction transaction = session.beginTransaction();

    LocalDateTime dateTime = LocalDateTime.now();

    KeyTransaction ktr = (KeyTransaction) session.get(KeyTransaction.class, keyTransactionId);
    String q = " SELECT p.id AS id, p.tin AS tin, p.paymentNum AS paymentNum, p.paymentDate AS paymentDate,"
            + "  p.paymentSum AS paymentSum, p.sourceCode AS sourceCode,"
            + " p.state AS state, p.tinDebtor as tinDebtor,p.claim as claim, p.issuerSerialNumber as issuerSerialNumber,"
            + " p.issuerIp as issuerIp,p.dateCreated AS dateCreated, p.dateUpdated as dateUpdated, "
            + " p.paymentSum - COALESCE((SELECT SUM(paidSum) FROM KeyPayment kp WHERE kp.payment = p),0) AS overSum "
            + " FROM Payment p " + " WHERE p.tin = :tin AND p.state IN (1,2) AND p.claim = 0"
            + " ORDER BY p.paymentDate, p.paymentNum ";
    Query query = session.createQuery(q);
    query.setParameter("tin", ktr.getTin());

    query.setResultTransformer(Transformers.aliasToBean(Payment.class));
    List<Payment> paymentList = query.list();

    for (Payment payment : paymentList) {

        if (payment.getOverSum().compareTo(keyCost) <= 0) {
            KeyPayment kp = new KeyPayment();
            kp.setSerialNumber(ktr.getSerialNumber());
            kp.setPayment(payment);
            kp.setPaidSum(payment.getOverSum());
            kp.setDateCreated(dateTime);
            kp.setDateUpdated(dateTime);
            session.save(kp);

            payment.setState((short) 3);
            payment.setDateUpdated(dateTime);
            session.update(payment);

            keyCost = keyCost.subtract(payment.getOverSum());
        } else {
            KeyPayment kp = new KeyPayment();
            kp.setSerialNumber(ktr.getSerialNumber());
            kp.setPayment(payment);
            kp.setPaidSum(keyCost);
            kp.setDateCreated(dateTime);
            kp.setDateUpdated(dateTime);
            session.save(kp);

            payment.setState((short) 2);
            payment.setDateUpdated(dateTime);
            session.update(payment);

            keyCost = BigDecimal.ZERO;
        }
        if (keyCost.compareTo(BigDecimal.ZERO) <= 0) {
            break;
        }
    }
    ktr.setCommitted((short) 1);
    ktr.setDateUpdated(dateTime);
    session.update(ktr);

    transaction.commit();
    session.close();
}

From source file:mx.edu.um.mateo.rh.dao.EmpleadoDaoTest.java

/**
 * Test of crea method, of class EmpleadoDao.
 *///w  w w . ja  v a2 s .c  o  m
@Test
public void debieraCrearEmpleado() {
    log.debug("Debiera crear empleado");
    Organizacion organizacion = new Organizacion("tst-01", "test-01", "test-01");
    currentSession().save(organizacion);
    Empresa empresa = new Empresa("tst-01", "test-01", "test-01", "000000000001", organizacion);
    currentSession().save(empresa);
    Rol rol = new Rol("ROLE_TEST");
    currentSession().save(rol);
    Set<Rol> roles = new HashSet<>();
    roles.add(rol);
    Almacen almacen = new Almacen("TST", "TEST", empresa);
    currentSession().save(almacen);
    Usuario usuario = new Usuario("bugs@um.edu.mx", "TEST-01", "TEST-01", "TEST-01");
    usuario.setEmpresa(empresa);
    usuario.setAlmacen(almacen);
    usuario.setRoles(roles);
    currentSession().save(usuario);
    Long id = usuario.getId();
    assertNotNull(id);

    Empleado empleado = new Empleado("test001", "test", "test", "test", "M", "address", "A", "curp", "rfc",
            "cuenta", "imss", 10, 100, BigDecimal.ZERO, "mo", "ife", "ra", Boolean.TRUE, "padre", "madre", "Ca",
            "Conyugue", Boolean.TRUE, Boolean.TRUE, "iglesia", "responsabilidad", empresa);
    instance.graba(empleado);
    assertNotNull(empleado);
    assertNotNull(empleado.getId());
    assertEquals("test", empleado.getNombre());
}

From source file:com.akartkam.inShop.domain.order.OrderItem.java

@Transient
@CurrencyFormat/*from w  ww.ja  v a 2 s  . co m*/
public BigDecimal getRowTotal() {
    BigDecimal returnValue = BigDecimal.ZERO;
    if (quantity != null) {
        BigDecimal quant = BigDecimal.valueOf(quantity);
        if (price != null) {
            returnValue = price.multiply(quant);
        }
    }
    return returnValue;
}

From source file:alfio.controller.form.ReservationForm.java

public Optional<Pair<List<TicketReservationWithOptionalCodeModification>, List<ASReservationWithOptionalCodeModification>>> validate(
        Errors bindingResult, TicketReservationManager tickReservationManager,
        AdditionalServiceRepository additionalServiceRepository, EventManager eventManager, Event event) {
    int selectionCount = ticketSelectionCount();

    if (selectionCount <= 0) {
        bindingResult.reject(ErrorsCode.STEP_1_SELECT_AT_LEAST_ONE);
        return Optional.empty();
    }/*from  w  w  w.  j ava  2s . c  o m*/

    List<Pair<TicketReservationModification, Integer>> maxTicketsByTicketReservation = selected().stream()
            .map(r -> Pair.of(r, tickReservationManager.maxAmountOfTicketsForCategory(event.getOrganizationId(),
                    event.getId(), r.getTicketCategoryId())))
            .collect(toList());
    Optional<Pair<TicketReservationModification, Integer>> error = maxTicketsByTicketReservation.stream()
            .filter(p -> p.getKey().getAmount() > p.getValue()).findAny();

    if (error.isPresent()) {
        bindingResult.reject(ErrorsCode.STEP_1_OVER_MAXIMUM, new Object[] { error.get().getValue() }, null);
        return Optional.empty();
    }

    final List<TicketReservationModification> categories = selected();
    final List<AdditionalServiceReservationModification> additionalServices = selectedAdditionalServices();

    final boolean validCategorySelection = categories.stream().allMatch(c -> {
        TicketCategory tc = eventManager.getTicketCategoryById(c.getTicketCategoryId(), event.getId());
        return OptionalWrapper.optionally(() -> eventManager.findEventByTicketCategory(tc)).isPresent();
    });

    final boolean validAdditionalServiceSelected = additionalServices.stream().allMatch(asm -> {
        AdditionalService as = eventManager.getAdditionalServiceById(asm.getAdditionalServiceId(),
                event.getId());
        ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
        return as.getInception(event.getZoneId()).isBefore(now)
                && as.getExpiration(event.getZoneId()).isAfter(now) && asm.getQuantity() >= 0
                && ((as.isFixPrice() && asm.isQuantityValid(as, selectionCount)) || (!as.isFixPrice()
                        && asm.getAmount() != null && asm.getAmount().compareTo(BigDecimal.ZERO) >= 0))
                && OptionalWrapper.optionally(() -> eventManager.findEventByAdditionalService(as)).isPresent();
    });

    if (!validCategorySelection || !validAdditionalServiceSelected) {
        bindingResult.reject(ErrorsCode.STEP_1_TICKET_CATEGORY_MUST_BE_SALEABLE);
        return Optional.empty();
    }

    List<TicketReservationWithOptionalCodeModification> res = new ArrayList<>();
    //
    Optional<SpecialPrice> specialCode = Optional.ofNullable(StringUtils.trimToNull(promoCode))
            .flatMap((trimmedCode) -> tickReservationManager.getSpecialPriceByCode(trimmedCode));
    //
    final ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
    maxTicketsByTicketReservation.forEach((pair) -> validateCategory(bindingResult, tickReservationManager,
            eventManager, event, pair.getRight(), res, specialCode, now, pair.getLeft()));
    return bindingResult.hasErrors() ? Optional.empty()
            : Optional.of(Pair.of(res,
                    additionalServices.stream()
                            .map(as -> new ASReservationWithOptionalCodeModification(as, specialCode))
                            .collect(Collectors.toList())));
}

From source file:com.qcadoo.mes.productionCounting.listeners.ProductionBalanceDetailsListeners.java

private void checkOrderDoneQuantity(final ComponentState componentState, final Entity productionBalance) {
    final Entity order = productionBalance.getBelongsToField(ProductionBalanceFields.ORDER);
    final BigDecimal doneQuantityFromOrder = order.getDecimalField(OrderFields.DONE_QUANTITY);

    if (doneQuantityFromOrder == null || BigDecimal.ZERO.compareTo(doneQuantityFromOrder) == 0) {
        componentState.addMessage("productionCounting.productionBalance.report.info.orderWithoutDoneQuantity",
                MessageType.INFO);//from w  ww  .  j  a  v a2 s .c o  m
    }
}

From source file:com.siapa.managedbean.DetalleCompraAlimentoManagedBean.java

public void guardarCompra() {

    try {/*from   ww  w . j av  a2 s. com*/
        if (getSumaTotal().compareTo(BigDecimal.ZERO) > 0) {

            Compra newcompra = new Compra();
            Proveedor proveedorSelected = proveedorService.findById(idProveedor);
            newcompra.setIdProveedor(proveedorSelected);
            newcompra.setFechaHoraCompra(new Date());
            newcompra.setUsuarioCompra(getUsuario());
            newcompra.setTotalCompra(
                    (BigDecimal) ((getSumaTotal() != null) ? getSumaTotal() : new BigDecimal(0.0)));
            compraService.save(newcompra);

            for (DetalleCompraAlimento detalle : tablaDetalleAlimentoPojoLista) {
                existencia = BigDecimal.ZERO;

                detalle.setIdCompra(newcompra);
                detalleCompraAlimentoService.save(detalle);

                Alimento newAlimento = getAlimento();
                Alimento idAlimento = detalle.getIdAlimento();
                Alimento cactual = alimentoService.findById(idAlimento.getIdAlimento());
                BigDecimal compra = detalle.getCantDetalleCompraAlimento();
                existencia = cactual.getExistenciaAlimento().add(compra);
                newAlimento.setExistenciaAlimento(existencia);
                alimentoService.merge(newAlimento);
            }
            tablaDetalleAlimentoPojoLista = new ArrayList<DetalleCompraAlimento>();
            sumaTotal = BigDecimal.ZERO;
        }
    } catch (Exception e) {
    }

}

From source file:com.opensourcestrategies.financials.accounts.GLAccountInTree.java

/**
 * Gets the debit of this GL account given child GL account.
 * @param childAccount a <code>GLAccountInTree</code> value
 * @return a <code>BigDecimal</code> value
 *///w ww  .j  a  va2  s  . c  o m
private BigDecimal getDebitOfChildrenRec(GLAccountInTree childAccount) {
    if (childAccount == null) {
        return BigDecimal.ZERO;
    }
    BigDecimal debitOfChildren = BigDecimal.ZERO;
    if (childAccount.isDebitAccount) {
        debitOfChildren = childAccount.balance;
    }
    for (GLAccountInTree grandchildAccount : childAccount.childAccounts) {
        debitOfChildren = debitOfChildren.add(getDebitOfChildrenRec(grandchildAccount));
    }
    return debitOfChildren;
}

From source file:dk.clanie.money.Money.java

/**
 * Returns a Money whose value is the absolute value of this.
 * /*from   w  w  w .j a va 2 s  .  c o  m*/
 * @return abs(this)
 */
public Money abs() {
    if (amount.compareTo(BigDecimal.ZERO) >= 0)
        return this;
    return negate();
}

From source file:com.msopentech.odatajclient.proxy.InvokeTestITCase.java

@Test
public void changeProductDimensions() {
    // 0. create a product
    final Integer id = 101;

    Product product = container.getProduct().newProduct();
    product.setProductId(id);//from  www.j  av a2s  .co m
    product.setDescription("New product");

    final Dimensions origDimensions = new Dimensions();
    origDimensions.setDepth(BigDecimal.ZERO);
    origDimensions.setHeight(BigDecimal.ZERO);
    origDimensions.setWidth(BigDecimal.ZERO);
    product.setDimensions(origDimensions);

    container.flush();

    product = container.getProduct().get(id);
    assertNotNull(product);
    assertEquals(id, product.getProductId());
    assertEquals(BigDecimal.ZERO, product.getDimensions().getDepth());
    assertEquals(BigDecimal.ZERO, product.getDimensions().getHeight());
    assertEquals(BigDecimal.ZERO, product.getDimensions().getWidth());

    try {
        // 1. invoke action bound to the product just created
        final Dimensions newDimensions = new Dimensions();
        newDimensions.setDepth(BigDecimal.ONE);
        newDimensions.setHeight(BigDecimal.ONE);
        newDimensions.setWidth(BigDecimal.ONE);

        product.changeProductDimensions(newDimensions);

        // 2. check that invoked action has effectively run
        product = container.getProduct().get(id);
        assertEquals(BigDecimal.ONE, product.getDimensions().getDepth());
        assertEquals(BigDecimal.ONE, product.getDimensions().getHeight());
        assertEquals(BigDecimal.ONE, product.getDimensions().getWidth());
    } finally {
        // 3. remove the test product
        container.getProduct().delete(product.getProductId());
        container.flush();
    }
}

From source file:com.teamj.distribuidas.web.ExcursionUserBean.java

@PostConstruct
public void init() {
    excursions = excursionServicio.obtenerTodas();
    this.excursion = new Excursion();
    this.cantidad = 1;
    this.subtotal = new BigDecimal(0);
    this.totalArticulos = 0;
    this.derechoExcursionSeleccionada = BigDecimal.ZERO;
    this.excursionArticulos = new ArrayList<>();

    // this.excursionSelected = new Excursion();
}