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.premiumminds.billy.core.services.builders.impl.GenericInvoiceBuilderImpl.java

protected void validateValues() throws ValidationException {

    GenericInvoiceEntity i = this.getTypeInstance();
    i.setCurrency(Currency.getInstance("EUR")); // FIXME: Hardcoded currency.
                                                // Blocks usage of any other
                                                // currency

    MathContext mc = BillyMathContext.get();

    BigDecimal amountWithTax = BigDecimal.ZERO;
    BigDecimal taxAmount = BigDecimal.ZERO;
    BigDecimal amountWithoutTax = BigDecimal.ZERO;

    for (GenericInvoiceEntry e : this.getTypeInstance().getEntries()) {

        amountWithTax = amountWithTax.add(e.getUnitAmountWithTax().multiply(e.getQuantity(), mc), mc);
        taxAmount = taxAmount.add(e.getUnitTaxAmount().multiply(e.getQuantity(), mc), mc);
        amountWithoutTax = amountWithoutTax.add(e.getUnitAmountWithoutTax().multiply(e.getQuantity(), mc), mc);
        if (e.getCurrency() == null) {
            GenericInvoiceEntryEntity entry = (GenericInvoiceEntryEntity) e;
            entry.setCurrency(i.getCurrency());
            e = entry;/*from  ww  w . j  av  a 2  s .c  om*/
        } else {
            Validate.isTrue(i.getCurrency().getCurrencyCode().equals(e.getCurrency().getCurrencyCode()));
        }
    }

    i.setAmountWithTax(amountWithTax);
    i.setTaxAmount(taxAmount);
    i.setAmountWithoutTax(amountWithoutTax);

    Validate.isTrue(
            i.getAmountWithTax().subtract(i.getTaxAmount(), mc).setScale(7, mc.getRoundingMode())
                    .compareTo(i.getAmountWithoutTax().setScale(7, mc.getRoundingMode())) == 0,
            "The invoice values are invalid", // TODO message
            i.getAmountWithTax(), i.getAmountWithoutTax(), i.getTaxAmount());

    Validate.isTrue(
            i.getAmountWithTax().compareTo(BigDecimal.ZERO) > 0
                    && i.getAmountWithoutTax().compareTo(BigDecimal.ZERO) >= 0
                    && i.getTaxAmount().compareTo(BigDecimal.ZERO) >= 0,
            "The invoice values are lower than zero", // TODO
            // message
            i.getAmountWithTax(), i.getAmountWithoutTax(), i.getTaxAmount());
}

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

public String makeAddressString(Address address, ObjectNode objectNode) {

    BigDecimal latit = address.getLatit();
    BigDecimal longit = address.getLongit();

    if (BigDecimal.ZERO.compareTo(latit) == 0 || BigDecimal.ZERO.compareTo(longit) == 0) {

        String qString = address.getFullName();
        Map<String, Object> latlng = this.getMapGoogle(qString, latit, longit);
        latit = (BigDecimal) latlng.get("latitude");
        longit = (BigDecimal) latlng.get("longitude");
        address.setLatit(latit);//from  w  w  w.j av  a2  s  .c om
        address.setLongit(longit);
    }

    objectNode.put("latit", latit);
    objectNode.put("longit", longit);
    StringBuilder addressString = new StringBuilder();

    if (address.getAddressL2() != null) {
        addressString.append(address.getAddressL2() + "</br>");
    }
    if (address.getAddressL3() != null) {
        addressString.append(address.getAddressL3() + "</br>");
    }
    if (address.getAddressL4() != null) {
        addressString.append(address.getAddressL4() + "</br>");
    }
    if (address.getAddressL5() != null) {
        addressString.append(address.getAddressL5() + "</br>");
    }
    if (address.getAddressL6() != null) {
        addressString.append(address.getAddressL6());
    }
    if (address.getAddressL7Country() != null) {
        addressString = addressString.append("</br>" + address.getAddressL7Country().getName());
    }
    return addressString.toString();
}

From source file:aiai.ai.launchpad.experiment.ExperimentService.java

private PlotData collectDataForPlotting(Experiment experiment, List<Task> selected, String[] paramsAxis) {
    final PlotData data = new PlotData();
    final List<String> paramCleared = new ArrayList<>();
    for (String param : paramsAxis) {
        if (StringUtils.isBlank(param)) {
            continue;
        }// w  w w.  jav a  2 s  .co  m
        if (!paramCleared.contains(param)) {
            paramCleared.add(param);
        }
    }
    if (paramCleared.size() != 2) {
        throw new IllegalStateException(
                "Wrong number of params for axes. Expected: 2, actual: " + paramCleared.size());
    }
    Map<String, Map<String, Integer>> map = experiment.getHyperParamsAsMap(false);
    data.x.addAll(map.get(paramCleared.get(0)).keySet());
    data.y.addAll(map.get(paramCleared.get(1)).keySet());

    Map<String, Integer> mapX = new HashMap<>();
    int idx = 0;
    for (String x : data.x) {
        mapX.put(x, idx++);
    }
    Map<String, Integer> mapY = new HashMap<>();
    idx = 0;
    for (String y : data.y) {
        mapY.put(y, idx++);
    }

    data.z = new BigDecimal[data.y.size()][data.x.size()];
    for (int i = 0; i < data.y.size(); i++) {
        for (int j = 0; j < data.x.size(); j++) {
            data.z[i][j] = BigDecimal.ZERO;
        }
    }

    String metricKey = null;
    for (Task sequence : selected) {

        MetricValues metricValues = MetricsUtils.getValues(MetricsUtils.to(sequence.metrics));
        if (metricValues == null) {
            continue;
        }
        if (metricKey == null) {
            //noinspection LoopStatementThatDoesntLoop
            for (Map.Entry<String, BigDecimal> entry : metricValues.values.entrySet()) {
                metricKey = entry.getKey();
                break;
            }
        }

        final TaskParamYaml taskParamYaml = taskParamYamlUtils.toTaskYaml(sequence.getParams());
        int idxX = mapX.get(taskParamYaml.hyperParams.get(paramCleared.get(0)));
        int idxY = mapY.get(taskParamYaml.hyperParams.get(paramCleared.get(1)));
        data.z[idxY][idxX] = data.z[idxY][idxX].add(metricValues.values.get(metricKey));
    }

    return data;
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java

private void checkItemRemoval(List<FinancialAct> acts) {
    BigDecimal quantity = new BigDecimal(10);
    FinancialAct item = acts.get(1);//from  w  w  w  . j a v a 2 s  . c o m
    item.setQuantity(quantity);

    save(acts);

    boolean credit = TypeHelper.isA(item, CustomerAccountArchetypes.CREDIT_ITEM);

    BigDecimal expected = getQuantity(BigDecimal.ZERO, quantity, credit);

    checkEquals(expected, getStock(stockLocation, product));
    remove(item);

    checkEquals(BigDecimal.ZERO, getStock(stockLocation, product));
}

From source file:pe.gob.mef.gescon.web.ui.RangoMB.java

public void desactivar(ActionEvent event) {
    try {//from   www. java2  s.c o m
        if (event != null) {
            if (this.getSelectedRango() != null) {
                LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
                User user = loginMB.getUser();
                RangoService service = (RangoService) ServiceFinder.findBean("RangoService");
                this.getSelectedRango().setNactivo(BigDecimal.ZERO);
                this.getSelectedRango().setDfechamodificacion(new Date());
                this.getSelectedRango().setVusuariomodificacion(user.getVlogin());
                service.saveOrUpdate(this.getSelectedRango());
                this.setListaRango(service.getRangos());
            } else {
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA,
                        "Debe seleccionar el rango a desactivar.");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.kcs.service.impl.GenerateXmlOtherServiceImpl.java

@Override
public byte[] generateXmlOpa(String dataSetDate, String category) throws Exception {
    try {//from ww w. j  av a2s . co m
        List<Datasetopa> mainList = opaDao.findMainList(dataSetDate, category);
        if (CollectionUtil.isEmpty(mainList)) {
            logger.error("main list is empty");
            return new byte[0];
        }
        Datasetopa obj = mainList.get(0);
        DSOPA dsopa = opaOf.createDSOPA();
        HeadGenXMLControl head = headDao.getHeadGenXMLControlByDatasetCode("DS_OPA");
        if (head != null) {
            dsopa.setName(head.getAttributesName());
            dsopa.setType(head.getAttributesType());
            dsopa.setSchemaVersion(head.getAttributesSchemaVersion());
        }

        com.kcs.genxml.beans.opa.DataSetCommonHeader dataSetCommonHeader = opaOf.createDataSetCommonHeader();
        dataSetCommonHeader.setDataSetDate(getXMLGregorianCalendarDate(obj.getDataSetDate()));
        dataSetCommonHeader.setOrganizationId(obj.getOrgId());

        DSOPA.DSOPAHeader dSOPAHeader = opaOf.createDSOPADSOPAHeader();
        dSOPAHeader.setDataSubmissionPeriod(obj.getDataSubPrd());

        DSOPA.DSOPAContent content = opaOf.createDSOPADSOPAContent();
        List<Datasetopa> childApprList = opaDao.findChildAppvList(dataSetDate);
        List<Datasetopa> childBotNumList = opaDao.findChildBotRefList(dataSetDate);

        for (Datasetopa main : mainList) {
            nullToEmptyString(main);
            DSOPA.DSOPAContent.ContentRecordGroup contentRecordGroup = opaOf
                    .createDSOPADSOPAContentContentRecordGroup();
            contentRecordGroup.setFiArrangementNumber(main.getFiArrgNo());
            contentRecordGroup.setOptionsProductType(main.getOptProdType());
            contentRecordGroup.setOptionType(main.getOptType());
            contentRecordGroup.setPrimaryInvolvedPartyId(main.getPriIpId());
            contentRecordGroup.setPrimaryInvolvedPartyUniqueIdType(main.getPriIpIdType());
            contentRecordGroup.setPrimaryInvolvedPartyBranchNumber(main.getPriIpBrcNo());
            contentRecordGroup.setPrimaryInvolvedPartyIbfIndicator(main.getPriIpIbfInd());
            contentRecordGroup.setArrangementContractDate(getXMLGregorianCalendarDate(main.getArrgCtrDate()));
            contentRecordGroup.setExpireDate(getXMLGregorianCalendarDate(main.getExpDate()));
            contentRecordGroup.setObjectiveType(main.getObjectiveType());
            contentRecordGroup.setOptionsPurposeCode(main.getOptPurpCode());
            contentRecordGroup.setOptionsRightType(main.getOptRightType());
            contentRecordGroup.setAuctionType(main.getActType());
            contentRecordGroup.setContractPrice(getXmlString(main.getCtrPrice()));
            contentRecordGroup.setBaseExchangeRate(getXmlString(main.getBaseExcRate()));
            contentRecordGroup.setPremiumAmount(getXmlString(main.getPremAmt()));
            if (BigDecimal.ZERO.equals(main.getNtnAmt())) {
                contentRecordGroup.setNotionalAmount("");
            } else {
                contentRecordGroup.setNotionalAmount(getXmlString(main.getNtnAmt()));
            }
            contentRecordGroup.setNotionalCurrencyId(main.getNatCurr());
            contentRecordGroup.setLegType(main.getLegType());
            contentRecordGroup.setBuyCurrencyId(main.getBuyCurr());
            contentRecordGroup.setBuyAmount(getXmlString(main.getBuyAmt()));
            contentRecordGroup.setSellCurrencyId(main.getSellCurr());
            contentRecordGroup.setSellAmount(getXmlString(main.getSellAmt()));

            DSOPA.DSOPAContent.ContentRecordGroup.ApprovalDocumentGroupInfo adgi = opaOf
                    .createDSOPADSOPAContentContentRecordGroupApprovalDocumentGroupInfo();
            List<Datasetopa> subChildList = filterChildOpa(main, childApprList);
            for (Datasetopa child : subChildList) {
                DSOPA.DSOPAContent.ContentRecordGroup.ApprovalDocumentGroupInfo.ApprovalDocumentGroupDetails details = opaOf
                        .createDSOPADSOPAContentContentRecordGroupApprovalDocumentGroupInfoApprovalDocumentGroupDetails();
                details.setApprovalDocumentDate(getXMLGregorianCalendarDate(child.getApprovalDocDate()));
                details.setApprovalDocumentNumber(child.getApprovalDocNum());
                adgi.getApprovalDocumentGroupDetails().add(details);
            }
            contentRecordGroup.setApprovalDocumentGroupInfo(adgi);

            DSOPA.DSOPAContent.ContentRecordGroup.BotReferenceNumberGroupInfo brngi = opaOf
                    .createDSOPADSOPAContentContentRecordGroupBotReferenceNumberGroupInfo();
            subChildList = filterChildOpa(main, childBotNumList);
            for (Datasetopa child : subChildList) {
                DSOPA.DSOPAContent.ContentRecordGroup.BotReferenceNumberGroupInfo.BotReferenceNumberGroupDetails details = opaOf
                        .createDSOPADSOPAContentContentRecordGroupBotReferenceNumberGroupInfoBotReferenceNumberGroupDetails();
                details.setBotReferenceNumber(child.getBotRefNum());
                brngi.getBotReferenceNumberGroupDetails().add(details);
            }
            contentRecordGroup.setBotReferenceNumberGroupInfo(brngi);

            content.getContentRecordGroup().add(contentRecordGroup);
        }
        dsopa.setCommonHeader(dataSetCommonHeader);
        dsopa.setDSOPAHeader(dSOPAHeader);
        dsopa.setDSOPAContent(content);

        return generateToBytes(dsopa);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:pe.gob.mef.gescon.web.ui.MaestroMB.java

public void desactivar(ActionEvent event) {
    try {/*from   w  ww .  j av a2 s .  c  o  m*/
        if (event != null) {
            if (this.getSelectedMaestro() != null) {
                LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
                User user = loginMB.getUser();
                MaestroService service = (MaestroService) ServiceFinder.findBean("MaestroService");
                this.getSelectedMaestro().setNactivo(BigDecimal.ZERO);
                this.getSelectedMaestro().setDfechamodificacion(new Date());
                this.getSelectedMaestro().setVusuariomodificacion(user.getVlogin());
                service.saveOrUpdate(this.getSelectedMaestro());
                this.setListaMaestro(service.getMaestros());
            } else {
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA,
                        "Debe seleccionar el maestro a desactivar.");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.fineract.module.stellar.service.BridgeService.java

public BigDecimal adjustVaultIssuedAssets(final String mifosTenantId, final String assetCode,
        final BigDecimal amount) throws InvalidConfigurationException {
    final AccountBridgePersistency bridge = accountBridgeRepositoryDecorator.getBridge(mifosTenantId);

    if (bridge == null) {
        throw new IllegalArgumentException(mifosTenantId);
    }/*  w  w  w . j a  v  a  2s.co  m*/

    final StellarAccountId stellarVaultAccountId;
    final char[] stellarVaultAccountPrivateKey;

    if (bridge.getStellarVaultAccountId() == null) {
        final KeyPair vaultAccountKeyPair = createVaultAccount(bridge);

        if (amount.compareTo(BigDecimal.ZERO) <= 0)
            return BigDecimal.ZERO;

        stellarVaultAccountId = StellarAccountId.mainAccount(vaultAccountKeyPair.getAccountId());
        stellarVaultAccountPrivateKey = vaultAccountKeyPair.getSecretSeed();
    } else {
        stellarVaultAccountId = StellarAccountId.mainAccount(bridge.getStellarVaultAccountId());
        stellarVaultAccountPrivateKey = bridge.getStellarVaultAccountPrivateKey();
    }

    final StellarAccountId stellarAccountId = StellarAccountId.mainAccount(bridge.getStellarAccountId());

    return horizonServerUtilities.adjustVaultIssuedAssets(stellarAccountId,
            bridge.getStellarAccountPrivateKey(), stellarVaultAccountId, stellarVaultAccountPrivateKey,
            assetCode, amount);
}

From source file:net.sourceforge.fenixedu.domain.Shift.java

public BigDecimal getCourseLoadTotalHours() {
    BigDecimal weeklyHours = BigDecimal.ZERO;
    for (CourseLoad courseLoad : getCourseLoadsSet()) {
        weeklyHours = weeklyHours.add(courseLoad.getTotalQuantity());
    }//from w  w  w .ja  va 2s.  co  m
    return weeklyHours;
}

From source file:jgnash.ui.report.compiled.PayeePieChart.java

private JFreeChart createPieChart(Account a, PieDataset[] data, int index) {
    PiePlot plot = new PiePlot(data[index]);

    // rebuilt each time because they're based on the account's commodity
    NumberFormat valueFormat = CommodityFormat.getFullNumberFormat(a.getCurrencyNode());
    NumberFormat percentFormat = new DecimalFormat("0.0#%");
    defaultLabels = new StandardPieSectionLabelGenerator("{0} = {1}", valueFormat, percentFormat);
    percentLabels = new StandardPieSectionLabelGenerator("{0} = {1}\n{2}", valueFormat, percentFormat);

    plot.setLabelGenerator(showPercentCheck.isSelected() ? percentLabels : defaultLabels);

    plot.setLabelGap(.02);/*from  ww w .  j  a v a  2s . c om*/
    plot.setInteriorGap(.1);

    BigDecimal thisTotal = BigDecimal.ZERO;
    for (int i = 0; i < data[index].getItemCount(); i++) {
        thisTotal = thisTotal.add((BigDecimal) (data[index].getValue(i)));
    }
    BigDecimal acTotal = a.getTreeBalance(startField.getLocalDate(), endField.getLocalDate()).abs();

    String title = "";
    String subtitle = "";

    // pick an appropriate title(s)
    if (index == 0) {
        title = a.getPathName();
        subtitle = rb.getString("Column.Credit") + " : " + valueFormat.format(thisTotal);
    } else if (index == 1) {
        title = rb.getString("Column.Balance") + " : " + valueFormat.format(acTotal);
        subtitle = rb.getString("Column.Debit") + " : " + valueFormat.format(thisTotal);
    }

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, false);

    chart.addSubtitle(new TextTitle(subtitle));
    chart.setBackgroundPaint(null);

    return chart;
}