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:org.fineract.module.stellar.StellarBridgeTestHelpers.java

public static void deleteTrustLine(final String fromTenant, final String fromTenantApiKey,
        final String toStellarAddress, final String assetCode) {
    String issuer = "";
    try {/*from   w ww.  ja  va2  s  . c o  m*/
        issuer = URLEncoder.encode(toStellarAddress, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Assert.fail();
    }

    given().header(StellarBridgeTestHelpers.CONTENT_TYPE_HEADER)
            .header(StellarBridgeTestHelpers.API_KEY_HEADER_LABEL, fromTenantApiKey)
            .header(StellarBridgeTestHelpers.TENANT_ID_HEADER_LABEL, fromTenant)
            .pathParam("assetCode", assetCode).pathParam("issuer", issuer)
            .body(new TrustLineConfiguration(BigDecimal.ZERO))
            .put("/modules/stellarbridge/trustlines/{assetCode}/{issuer}/").then().assertThat()
            .statusCode(HttpStatus.OK.value());
}

From source file:com.gst.portfolio.shareaccounts.domain.ShareAccountCharge.java

public void resetToOriginal(final MonetaryCurrency currency) {
    this.amount = BigDecimal.ZERO;
    this.amountPaid = BigDecimal.ZERO;
    this.amountWaived = BigDecimal.ZERO;
    this.amountWrittenOff = BigDecimal.ZERO;
    this.amountOutstanding = calculateAmountOutstanding(currency);
    this.paid = false;
    this.waived = false;
}

From source file:net.sourceforge.fenixedu.domain.credits.util.AnnualTeachingCreditsBean.java

public AnnualTeachingCreditsBean(ExecutionYear executionYear, Teacher teacher, RoleType roleType) {
    this.executionYear = executionYear;
    this.teacher = teacher;
    this.teachingCredits = BigDecimal.ZERO;
    this.masterDegreeThesesCredits = BigDecimal.ZERO;
    this.phdDegreeThesesCredits = BigDecimal.ZERO;
    this.projectsTutorialsCredits = BigDecimal.ZERO;
    this.managementFunctionCredits = BigDecimal.ZERO;
    this.othersCredits = BigDecimal.ZERO;
    this.creditsReduction = BigDecimal.ZERO;
    this.serviceExemptionCredits = BigDecimal.ZERO;
    this.annualTeachingLoad = BigDecimal.ZERO;
    this.yearCredits = BigDecimal.ZERO;
    this.finalCredits = BigDecimal.ZERO;
    this.accumulatedCredits = BigDecimal.ZERO;
    setAnnualTeachingCreditsByPeriod(executionYear, teacher, roleType);
}

From source file:org.fineract.module.stellar.TestPaymentInSimpleNetwork.java

@Test
public void cancellingPayments() throws Exception {
    logger.info("cancellingPayments test begin");

    final AccountListener accountListener = new AccountListener(serverAddress, firstTenantId, secondTenantId);

    final BigDecimal transferAmount = BigDecimal.TEN;
    makePayment(firstTenantId, firstTenantApiKey, secondTenantId, ASSET_CODE, transferAmount);

    accountListener.waitForCredits(PAY_WAIT,
            creditMatcher(secondTenantId, BigDecimal.TEN, ASSET_CODE, firstTenantId));

    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
            transferAmount);/*from   w  w w . j  a  va  2s .c  o  m*/

    makePayment(secondTenantId, secondTenantApiKey, firstTenantId, ASSET_CODE, transferAmount);

    accountListener.waitForCredits(PAY_WAIT, creditMatcher(firstTenantId, BigDecimal.TEN, ASSET_CODE,
            vaultMatcher(secondTenantId, firstTenantId)));

    checkBalance(firstTenantId, firstTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(secondTenantId),
            BigDecimal.ZERO);

    checkBalance(firstTenantId, firstTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
            VAULT_BALANCE);

    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
            BigDecimal.ZERO);

    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(secondTenantId),
            VAULT_BALANCE);
}

From source file:org.yamj.core.hibernate.HibernateDao.java

/**
 * Convert row object to big decimal.//  w ww  . j a v  a 2s  .c  o  m
 *
 * @param rowElement
 * @return <code>BigDecimal</code>
 */
protected BigDecimal convertRowElementToBigDecimal(Object rowElement) {
    if (rowElement == null) {
        return BigDecimal.ZERO;
    } else if (rowElement instanceof BigDecimal) {
        return (BigDecimal) rowElement;
    } else {
        return new BigDecimal(rowElement.toString());
    }
}

From source file:com.axelor.apps.base.service.MapService.java

public HashMap<String, Object> getMapOsm(String qString, BigDecimal latitude, BigDecimal longitude) {
    HashMap<String, Object> result = new HashMap<String, Object>();
    try {/*from w w  w.  j  a  v a 2  s.c  om*/
        if (BigDecimal.ZERO.compareTo(latitude) == 0 || BigDecimal.ZERO.compareTo(longitude) == 0) {
            RESTClient restClient = new RESTClient("http://nominatim.openstreetmap.org/");
            Map<String, Object> mapQuery = new HashMap<String, Object>();
            mapQuery.put("q", qString);
            mapQuery.put("format", "xml");
            mapQuery.put("polygon", true);
            mapQuery.put("addressdetails", true);
            Map<String, Object> mapHeaders = new HashMap<String, Object>();
            mapHeaders.put("HTTP referrer", "axelor");
            Map<String, Object> mapResponse = new HashMap<String, Object>();
            mapResponse.put("path", "/search");
            mapResponse.put("accept", ContentType.JSON);
            mapResponse.put("query", mapQuery);
            mapResponse.put("headers", mapHeaders);
            mapResponse.put("connectTimeout", 5000);
            mapResponse.put("readTimeout", 10000);
            mapResponse.put("followRedirects", false);
            mapResponse.put("useCaches", false);
            mapResponse.put("sslTrustAllCerts", true);
            Response restResponse = restClient.get(mapResponse);
            GPathResult searchresults = new XmlSlurper().parseText(restResponse.getContentAsString());
            Iterator<Node> iterator = searchresults.childNodes();
            if (iterator.hasNext()) {
                Node node = iterator.next();
                Map attributes = node.attributes();
                if (attributes.containsKey("lat") && attributes.containsKey("lon")) {
                    if (BigDecimal.ZERO.compareTo(latitude) == 0)
                        latitude = new BigDecimal(node.attributes().get("lat").toString());
                    if (BigDecimal.ZERO.compareTo(longitude) == 0)
                        longitude = new BigDecimal(node.attributes().get("lon").toString());
                }
            }
        }
        if (BigDecimal.ZERO.compareTo(latitude) != 0 && BigDecimal.ZERO.compareTo(longitude) != 0) {
            result.put("url", "map/oneMarker.html?x=" + latitude + "&y=" + longitude + "&z=18");
            result.put("latitude", latitude);
            result.put("longitude", longitude);
            return result;
        }

    } catch (Exception e) {
        TraceBackService.trace(e);
    }
    return null;
}

From source file:com.matel.service.impl.ShoppingCartServiceImpl.java

private void mapCartData(ShoppingCart cart, ShoppingCartData cartData) {
    cartData.setCartId(cart.getShpCartId());
    cartData.setCustomer(cart.getUserId());
    BigDecimal totalAmount = BigDecimal.ZERO;
    for (ShoppingCartItem shoppingCartItem : cart.getShoppingCartItemSet()) {
        ShoppingCartItemData cartItemData = new ShoppingCartItemData();
        cartItemData.setName(shoppingCartItem.getProductId().getProductName());
        cartItemData.setProductPrice(shoppingCartItem.getItemPrice());
        cartItemData.setQuantity(shoppingCartItem.getQuantity());
        cartItemData.setFinishedProductId(shoppingCartItem.getFinishId());
        cartItemData.setFinishedProductName(shoppingCartItem.getFinishName());
        shoppingCartItem.getProductId().getQboProduct();
        cartItemData.setProduct(shoppingCartItem.getProductId());
        totalAmount = totalAmount//from  w  ww  .  j  ava 2s.  c  om
                .add(cartItemData.getProductPrice().multiply(new BigDecimal(cartItemData.getQuantity())));
        cartData.getCartItems().add(cartItemData);
    }
    cartData.setSubTotal(totalAmount);
}

From source file:com.osafe.events.CheckOutEvents.java

public static String autoCaptureAuthPayments(HttpServletRequest request, HttpServletResponse response) {
    // warning there can only be ONE payment preference for this to work
    // you cannot accept multiple payment type when using an external gateway
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    String orderId = (String) request.getAttribute("orderId");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
    String result = "success";

    //LS: Note: This service is automatically called from controller_ecommerce (autoCpaturePayments) checkout flow.
    //If a client wants to only 'approve' orders and not capture when order is placed update parameter CHECKOUT_CC_CAPTURE_FLAG=FALSE.
    String autoCapture = Util.getProductStoreParm(request, "CHECKOUT_CC_CAPTURE_FLAG");
    if (UtilValidate.isNotEmpty(autoCapture) && "FALSE".equals(autoCapture.toUpperCase())) {
        OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
        return result;

    }/*from   w w  w  . java2  s .  co m*/

    try {
        /*
         * A bit of a hack here to get the admin user since to capture payments and complete the order requires a user who has
         * the proper security permissions
         */
        GenericValue sysLogin = delegator.findByPrimaryKeyCache("UserLogin",
                UtilMisc.toMap("userLoginId", "admin"));

        List<GenericValue> lOrderPaymentPreference = delegator.findByAnd("OrderPaymentPreference",
                UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_AUTHORIZED"));
        if (UtilValidate.isNotEmpty(lOrderPaymentPreference)) {
            /*
             * This will complete the order generate invoice and capture any payments.
             * OrderChangeHelper.completeOrder(dispatcher, sysLogin, orderId);
             */

            /*
             * To only capture payments and leave the order in approved status. Remove the complete order call,
             */
            //Get the amount to capture
            BigDecimal amountToCapture = BigDecimal.ZERO;
            for (GenericValue orderPaymentPreference : lOrderPaymentPreference) {
                amountToCapture = amountToCapture.add(orderPaymentPreference.getBigDecimal("maxAmount"))
                        .setScale(scale, rounding);
            }

            Map<String, Object> serviceContext = UtilMisc.toMap("userLogin", sysLogin, "orderId", orderId,
                    "captureAmount", amountToCapture);
            String captureResp = "";
            try {
                Map callResult = dispatcher.runSync("captureOrderPayments", serviceContext);
                if (ModelService.RESPOND_ERROR.equals(callResult.get(ModelService.RESPONSE_MESSAGE))) {
                    captureResp = "ERROR";
                } else {
                    captureResp = (String) callResult.get("processResult");
                }
                ServiceUtil.getMessages(request, callResult, null);
            } catch (Exception e) {
                captureResp = "ERROR";
                Debug.logError(e, module);
            }
            if (captureResp.equals("FAILED") || captureResp.equals("ERROR")) {
                OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
                // Remove all payment method from cart except GIFT_CARD
                List pmi = cart.getPaymentMethodIds();
                List giftCards = cart.getGiftCards();
                List giftCardPmi = new LinkedList();
                if (UtilValidate.isNotEmpty(giftCards)) {
                    Iterator i = giftCards.iterator();
                    while (i.hasNext()) {
                        GenericValue gc = (GenericValue) i.next();
                        giftCardPmi.add(gc.getString("paymentMethodId"));
                    }
                    pmi.removeAll(giftCardPmi);
                }
                cart.clearPaymentMethodsById(pmi);
                // Set order id as null in cart because order has been canceled
                cart.setOrderId(null);
                return "error";
            }
        } else {
            //If no payments were authorized, there are no payments to capture; approve the order.
            OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);

        }

    } catch (Exception e) {
        Debug.logError(e, module);
    }

    return result;
}

From source file:uk.dsxt.voting.tests.TestDataGenerator.java

private void generate(String name, int totalParticipant, int holdersCount, int vmCount, int levelsCount,
        int minutes, boolean generateVotes, int victimsCount, boolean generateDisconnect, int disconnectNodes)
        throws Exception {
    ClientFullInfo[] clients = new ClientFullInfo[totalParticipant];
    Participant[] participants = new Participant[totalParticipant];
    //generating keys
    long start = System.currentTimeMillis();
    log.debug("generating {} keys", totalParticipant);
    KeyPair[] holderKeys = cryptoHelper.createCryptoKeysGenerator().generateKeys(holdersCount + 1);
    KeyPair[] keys = new KeyPair[totalParticipant];
    for (int i = 0; i < keys.length; i++) {
        keys[i] = holderKeys[Math.min(i, holderKeys.length - 1)];
    }//from w w w.ja v  a  2  s .c o m
    log.debug("{} keys generated. {} seconds spent", totalParticipant,
            (System.currentTimeMillis() - start) / 1000);

    //generating voting
    long now = System.currentTimeMillis();
    long dayStart = now - now % (24 * 60 * 60 * 1000);
    Voting voting = generateVotingEn(dayStart, dayStart + minutes * 60000);
    //generating participants info
    for (int i = 0; i < totalParticipant; i++) {
        ParticipantRole role;
        if (i == 0)
            role = ParticipantRole.NRD;
        else if (i < holdersCount)
            role = ParticipantRole.NominalHolder;
        else
            role = ParticipantRole.Owner;
        HashMap<String, BigDecimal> securities = new HashMap<>();
        securities.put(SECURITY,
                role == ParticipantRole.Owner ? new BigDecimal(randomInt(15, 100)) : BigDecimal.ZERO);
        int ownerIdx = role == ParticipantRole.NRD ? -1
                : i < 6 ? 0 : randomInt(0, Math.min(i, holdersCount) - 1);
        VoteResult vote = role != ParticipantRole.Owner ? null
                : generateVote(Integer.toString(i), securities, voting);
        clients[i] = new ClientFullInfo(securities, i, ownerIdx, role, keys[i].getPrivateKey(),
                keys[i].getPublicKey(), String.format("Random name #%d", i), vote, new ArrayList<>(), false,
                true, "");
        participants[i] = new Participant(i == 0 ? "00" : Integer.toString(i), clients[i].getName(),
                clients[i].getPublicKey());
        if (role != ParticipantRole.NRD) {
            clients[ownerIdx].clients.add(clients[i]);
            for (; ownerIdx >= 0; ownerIdx = clients[ownerIdx].getHolderId()) {
                for (Map.Entry<String, BigDecimal> secEntry : securities.entrySet()) {
                    clients[ownerIdx].getPacketSizeBySecurity().put(secEntry.getKey(), clients[ownerIdx]
                            .getPacketSizeBySecurity().get(secEntry.getKey()).add(secEntry.getValue()));
                }
            }
        }
    }

    if (victimsCount > 0) {
        ThreadLocalRandom.current().ints(1, holdersCount - 1).distinct().limit(victimsCount)
                .forEach(i -> clients[i].setVictim(true));
        ThreadLocalRandom.current().ints(1, holdersCount - 1).filter(i -> !clients[i].isVictim()).distinct()
                .limit(victimsCount).forEach(i -> clients[i].setHonest(false));
    }

    saveData(clients, participants, name, voting, holdersCount, vmCount, minutes, generateVotes,
            generateDisconnect, disconnectNodes);
}

From source file:cimav.client.data.domain.EmpleadoNomina.java

public BigDecimal getTotalPercepciones() {
    List<Movimiento> percepciones = this.getMovimientos(ETipoConcepto.PERCEPCION);
    BigDecimal result = BigDecimal.ZERO;
    for (Movimiento percepcion : percepciones) {
        if (percepcion.getConcepto().getSuma()) {
            result = result.add(percepcion.getCantidad());
        }/*w w w.java  2  s .  c o m*/
    }
    return result;
}