Example usage for java.math BigDecimal toString

List of usage examples for java.math BigDecimal toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns the string representation of this BigDecimal , using scientific notation if an exponent is needed.

Usage

From source file:org.openbravo.erpCommon.ad_forms.RequisitionToOrder.java

private OBError processPurchaseOrder(VariablesSecureApp vars, String strSelected, String strOrderDate,
        String strVendor, String strPriceListId, String strOrg, String strWarehouse)
        throws IOException, ServletException {
    StringBuffer textMessage = new StringBuffer();
    Connection conn = null;//w w  w.  j  a v a2 s.  co m

    OBError myMessage = null;
    myMessage = new OBError();
    myMessage.setTitle("");

    String strPriceListVersionId = RequisitionToOrderData.getPricelistVersion(this, strPriceListId,
            strOrderDate);
    RequisitionToOrderData[] noprice = RequisitionToOrderData.selectNoPrice(this, vars.getLanguage(),
            strPriceListVersionId, strSelected);
    if (noprice != null && noprice.length > 0) {
        textMessage.append(Utility.messageBD(this, "LinesWithNoPrice", vars.getLanguage())).append("<br><ul>");
        for (int i = 0; i < noprice.length; i++) {
            textMessage.append("<li>").append(noprice[i].product);
        }
        textMessage.append("</ul>");
        myMessage.setType("Error");
        myMessage.setMessage(textMessage.toString());
        return myMessage;
    }

    RequisitionToOrderData[] data1 = RequisitionToOrderData.selectVendorData(this, strVendor);
    if (data1[0].poPaymenttermId == null || data1[0].poPaymenttermId.equals("")) {
        myMessage.setType("Error");
        myMessage.setMessage(Utility.messageBD(this, "VendorWithNoPaymentTerm", vars.getLanguage()));
        return myMessage;
    }
    if ("".equals(RequisitionToOrderData.cBPartnerLocationId(this, strVendor))) {
        myMessage.setType("Error");
        myMessage.setMessage(Utility.messageBD(this, "NoBPLocation", vars.getLanguage()));
        return myMessage;
    }

    try {
        conn = getTransactionConnection();
        String strCOrderId = SequenceIdData.getUUID();
        String docTargetType = RequisitionToOrderData.cDoctypeTarget(conn, this, vars.getClient(), strOrg);
        String strDocumentNo = Utility.getDocumentNo(this, vars, "", "C_Order", docTargetType, docTargetType,
                false, true);
        String cCurrencyId = RequisitionToOrderData.selectCurrency(this, strPriceListId);

        try {
            RequisitionToOrderData.insertCOrder(conn, this, strCOrderId, vars.getClient(), strOrg,
                    vars.getUser(), strDocumentNo, "DR", "CO", "0", docTargetType, strOrderDate, strOrderDate,
                    strOrderDate, strVendor, RequisitionToOrderData.cBPartnerLocationId(this, strVendor),
                    RequisitionToOrderData.billto(this, strVendor).equals("")
                            ? RequisitionToOrderData.cBPartnerLocationId(this, strVendor)
                            : RequisitionToOrderData.billto(this, strVendor),
                    cCurrencyId, isAlternativeFinancialFlow() ? "P" : data1[0].paymentrulepo,
                    data1[0].poPaymenttermId, data1[0].invoicerule.equals("") ? "I" : data1[0].invoicerule,
                    data1[0].deliveryrule.equals("") ? "A" : data1[0].deliveryrule, "I",
                    data1[0].deliveryviarule.equals("") ? "D" : data1[0].deliveryviarule, strWarehouse,
                    strPriceListId, "", "", "", data1[0].poPaymentmethodId);
        } catch (ServletException ex) {
            myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
            releaseRollbackConnection(conn);
            return myMessage;
        }

        int line = 0;
        String strCOrderlineID = "";
        BigDecimal qty = new BigDecimal("0");
        BigDecimal qtyOrder = new BigDecimal("0");
        BigDecimal quantity = new BigDecimal("0");
        BigDecimal quantityOrder = new BigDecimal("0");
        boolean insertLine = false;

        RequisitionToOrderData[] lines = RequisitionToOrderData.linesToOrder(this, strOrderDate, strOrg,
                strWarehouse,
                RequisitionToOrderData.billto(this, strVendor).equals("")
                        ? RequisitionToOrderData.cBPartnerLocationId(this, strVendor)
                        : RequisitionToOrderData.billto(this, strVendor),
                RequisitionToOrderData.cBPartnerLocationId(this, strVendor), cCurrencyId, strPriceListVersionId,
                strSelected);
        for (int i = 0; lines != null && i < lines.length; i++) {
            if ("".equals(lines[i].tax)) {
                RequisitionLine rl = OBDal.getInstance().get(RequisitionLine.class,
                        lines[i].mRequisitionlineId);
                myMessage.setType("Error");
                myMessage.setMessage(String.format(OBMessageUtils.messageBD("NoTaxRequisition"), rl.getLineNo(),
                        rl.getRequisition().getDocumentNo()));
                releaseRollbackConnection(conn);
                return myMessage;
            }

            if (i == 0)
                strCOrderlineID = SequenceIdData.getUUID();
            if (i == lines.length - 1) {
                insertLine = true;
                qtyOrder = qty;
                quantityOrder = quantity;
            } else if (!lines[i + 1].mProductId.equals(lines[i].mProductId)
                    || !lines[i + 1].mAttributesetinstanceId.equals(lines[i].mAttributesetinstanceId)
                    || !lines[i + 1].description.equals(lines[i].description)
                    || !lines[i + 1].priceactual.equals(lines[i].priceactual)
                    || !StringUtils.equals(lines[i + 1].mProductUomId, lines[i].mProductUomId)) {
                insertLine = true;
                qtyOrder = qty;
                qty = new BigDecimal(0);
                quantityOrder = quantity;
                quantity = new BigDecimal(0);
            } else {
                qty = qty.add(new BigDecimal(lines[i].lockqty));
                quantity = quantity.add(new BigDecimal(lines[i].quantityorder));
            }
            lines[i].cOrderlineId = strCOrderlineID;
            if (insertLine) {
                insertLine = false;
                line += 10;
                BigDecimal qtyAux = new BigDecimal(lines[i].lockqty);
                qtyOrder = qtyOrder.add(qtyAux);
                BigDecimal quantityAux = new BigDecimal(lines[i].quantityorder);
                quantityOrder = quantityOrder.add(quantityAux);
                if (log4j.isDebugEnabled())
                    log4j.debug("Lockqty: " + lines[i].lockqty + " qtyorder: " + qtyOrder.toPlainString()
                            + " new BigDecimal: " + (new BigDecimal(lines[i].lockqty)).toString() + " qtyAux: "
                            + qtyAux.toString());

                try {
                    RequisitionToOrderData.insertCOrderline(conn, this, strCOrderlineID, vars.getClient(),
                            strOrg, vars.getUser(), strCOrderId, Integer.toString(line), strVendor,
                            RequisitionToOrderData.cBPartnerLocationId(this, strVendor), strOrderDate,
                            lines[i].needbydate, lines[i].description, lines[i].mProductId,
                            lines[i].mAttributesetinstanceId, strWarehouse, lines[i].mProductUomId,
                            lines[i].cUomId,
                            quantityOrder != null && BigDecimal.ZERO.compareTo(quantityOrder) != 0
                                    ? quantityOrder.toPlainString()
                                    : "",
                            qtyOrder.toPlainString(), cCurrencyId, lines[i].pricelist, lines[i].priceactual,
                            strPriceListId, lines[i].pricelimit, lines[i].tax, "", lines[i].discount,
                            lines[i].grossUnit, lines[i].grossAmt);
                } catch (ServletException ex) {
                    myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                    releaseRollbackConnection(conn);
                    return myMessage;
                }

                strCOrderlineID = SequenceIdData.getUUID();
            }
        }

        unlockRequisitionLines(vars, strSelected);
        for (int i = 0; lines != null && i < lines.length; i++) {
            String strRequisitionOrderId = SequenceIdData.getUUID();
            try {
                RequisitionToOrderData.insertRequisitionOrder(conn, this, strRequisitionOrderId,
                        vars.getClient(), strOrg, vars.getUser(), lines[i].mRequisitionlineId,
                        lines[i].cOrderlineId, lines[i].lockqty);
            } catch (ServletException ex) {
                myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                releaseRollbackConnection(conn);
                return myMessage;
            }
            if (lines[i].toClose.equals("Y"))
                RequisitionToOrderData.requisitionStatus(conn, this, lines[i].mRequisitionlineId,
                        vars.getUser());
        }

        OBError myMessageAux = cOrderPost(conn, vars, strCOrderId);
        releaseCommitConnection(conn);
        String strWindowName = WindowTabsData.selectWindowInfo(this, vars.getLanguage(), "181");
        textMessage.append(strWindowName).append(" ").append(strDocumentNo).append(": ");
        if (myMessageAux.getMessage().equals(""))
            textMessage.append(Utility.messageBD(this, "Success", vars.getLanguage()));
        else
            textMessage.append(myMessageAux.getMessage());

        myMessage.setType(myMessageAux.getType());
        myMessage.setMessage(textMessage.toString());
        return myMessage;
    } catch (Exception e) {
        try {
            if (conn != null)
                releaseRollbackConnection(conn);
        } catch (Exception ignored) {
        }
        e.printStackTrace();
        log4j.warn("Rollback in transaction");
        myMessage.setType("Error");
        myMessage.setMessage(Utility.messageBD(this, "ProcessRunError", vars.getLanguage()));
        return myMessage;
    }
}

From source file:com.jive.myco.seyren.core.service.notification.FlowdockNotificationServiceTest.java

@Test
public void basicFlowdockTest() {
    BigDecimal value = new BigDecimal("1.0");

    Check check = new Check().withId("123").withEnabled(true).withName("test-check").withState(AlertType.ERROR);
    Subscription subscription = new Subscription().withEnabled(true).withType(SubscriptionType.FLOWDOCK)
            .withTarget("target");
    Alert alert = new Alert().withValue(value).withTimestamp(new DateTime()).withFromType(AlertType.OK)
            .withToType(AlertType.ERROR);
    List<Alert> alerts = Arrays.asList(alert);

    BodyCapture<JsonNode> bodyCapture = new JsonBodyCapture();

    clientDriver.addExpectation(onRequestTo("/v1/messages/chat/target")
            .withMethod(ClientDriverRequest.Method.POST).capturingBodyIn(bodyCapture)
            .withHeader("Content-Type", "application/json").withHeader("accept", "application/json"),
            giveEmptyResponse());/*from   ww w  .  j av  a 2s.  c o m*/

    notificationService.sendNotification(check, subscription, alerts);

    JsonNode node = bodyCapture.getContent();

    assertThat(node, hasJsonPath("$.content", containsString("test-check")));
    assertThat(node, hasJsonPath("$.content", containsString("ERROR")));
    assertThat(node, hasJsonPath("$.content", containsString(value.toString())));
    assertThat(node, hasJsonPath("$.content", containsString("/#/checks/123")));
    assertThat(node, hasJsonPath("$.external_user_name", is("Seyren")));
    assertThat(node, hasJsonPath("$.tags", hasSize(1)));
    assertThat(node, hasJsonPath("$.tags[0]", is("ERROR")));

    verify(mockSeyrenConfig).getFlowdockExternalUsername();
    verify(mockSeyrenConfig).getFlowdockEmojis();
    verify(mockSeyrenConfig).getFlowdockTags();
    verify(mockSeyrenConfig).getBaseUrl();

}

From source file:org.mifos.config.AccountingRulesIntegrationTest.java

@Test
public void testGetFinalRoundOffMultiple() {
    BigDecimal configuredRoundOffMultiple = AccountingRules.getFinalRoundOffMultiple();
    String roundOffMultiple = "1";
    ConfigurationManager configMgr = ConfigurationManager.getInstance();
    configMgr.setProperty(AccountingRulesConstants.FINAL_ROUND_OFF_MULTIPLE, roundOffMultiple);
    // return value from accounting rules class has to be the value defined
    // in the config file
    Assert.assertEquals(new BigDecimal(roundOffMultiple), AccountingRules.getFinalRoundOffMultiple());
    // clear the RoundingRule property from the config file
    configMgr.clearProperty(AccountingRulesConstants.FINAL_ROUND_OFF_MULTIPLE);
    BigDecimal defaultValue = AccountingRules.getFinalRoundOffMultiple();
    Assert.assertEquals(defaultValue, new BigDecimal("1"));
    // save it back
    configMgr.addProperty(AccountingRulesConstants.FINAL_ROUND_OFF_MULTIPLE,
            configuredRoundOffMultiple.toString());

}

From source file:org.egov.restapi.service.BudgetCheckService.java

public String getPlanningBudgetAvailable(final BudgetCheck budgetCheck) {
    BigDecimal budgetAvailable;
    final Scheme scheme = schemeService.findByCode(budgetCheck.getSchemeCode());
    final SubScheme subScheme = subSchemeService.findByCode(budgetCheck.getSubSchemeCode());

    final List<Long> budgetheadid = new ArrayList<>();
    budgetheadid.add(budgetGroupService.getBudgetGroupByName(budgetCheck.getBudgetHeadName()).getId());
    budgetAvailable = budgetDetailsDAO.getPlanningBudgetAvailable(
            financialYearHibernateDAO.getFinYearByDate(new Date()).getId(),
            Integer.parseInt(/*  ww  w. java2  s . c om*/
                    departmentService.getDepartmentByCode(budgetCheck.getDepartmentCode()).getId().toString()),
            functionService.findByCode(budgetCheck.getFunctionCode()).getId(), null,
            scheme == null ? null : Integer.parseInt(scheme.getId().toString()),
            subScheme == null ? null : Integer.parseInt(subScheme.getId().toString()), null, budgetheadid,
            Integer.parseInt(fundService.findByCode(budgetCheck.getFundCode()).getId().toString()));

    return budgetAvailable.toString();
}

From source file:org.openvpms.esci.adapter.map.invoice.InvoiceMapperImpl.java

/**
 * Verifies that a tax category matches that expected.
 *
 * @param category the tax category//  w  w  w .j  ava  2s.c  om
 * @param rates    the tax rates
 * @return the tax rate used
 * @throws ESCIAdapterException if the category is invalid
 */
protected BigDecimal checkTaxCategory(UBLTaxCategory category, TaxRates rates) {
    String taxCategory = category.getID();
    BigDecimal rate = category.getTaxRate();
    String taxScheme = category.getTaxTypeCode();
    BigDecimal expectedRate = rates.getTaxRate(taxScheme, taxCategory);
    if (expectedRate == null) {
        ErrorContext context = new ErrorContext(category);
        throw new ESCIAdapterException(ESCIAdapterMessages.invalidTaxSchemeAndCategory(context.getPath(),
                context.getType(), context.getID(), taxScheme, taxCategory));
    }
    if (expectedRate.compareTo(rate) != 0) {
        ErrorContext context = new ErrorContext(category, "Percent");
        throw new ESCIAdapterException(ESCIAdapterMessages.ublInvalidValue(context.getPath(), context.getType(),
                context.getID(), expectedRate.toString(), rate.toString()));
    }
    return rate;
}

From source file:org.mifos.config.AccountingRulesIntegrationTest.java

@Test
public void testGetInitialRoundOffMultiple() {
    BigDecimal configuredRoundOffMultiple = AccountingRules.getInitialRoundOffMultiple();
    String roundOffMultiple = "1";
    ConfigurationManager configMgr = ConfigurationManager.getInstance();
    configMgr.setProperty(AccountingRulesConstants.INITIAL_ROUND_OFF_MULTIPLE, roundOffMultiple);
    // return value from accounting rules class has to be the value defined
    // in the config file
    Assert.assertEquals(new BigDecimal(roundOffMultiple), AccountingRules.getInitialRoundOffMultiple());
    // clear the RoundingRule property from the config file
    configMgr.clearProperty(AccountingRulesConstants.INITIAL_ROUND_OFF_MULTIPLE);
    BigDecimal defaultValue = AccountingRules.getInitialRoundOffMultiple();
    Assert.assertEquals(defaultValue, new BigDecimal("1"));
    // save it back
    configMgr.addProperty(AccountingRulesConstants.INITIAL_ROUND_OFF_MULTIPLE,
            configuredRoundOffMultiple.toString());

}

From source file:com.dotmarketing.portlets.cmsmaintenance.action.ViewCMSMaintenanceAction.java

/**
 * Retrieves the basic information of the contents in the
 * {@code dist_reindex_journal} table that could not be re-indexed and sends
 * it back to the user as a CSV file. This way users can keep track of them
 * and check the logs to get more information about the failure.
 * //  w w  w. j  av a  2  s  .co m
 * @param response
 *            - The {@link HttpServletResponse} object that allows to send
 *            the CSV file to the user.
 */
private void downloadRemainingRecordsAsCsv(HttpServletResponse response) {
    String fileName = "failed_reindex_records" + new java.util.Date().getTime();
    String[] fileColumns = new String[] { "ID", "Identifier To Index", "Inode To Index", "Priority" };
    PrintWriter pr = null;
    try {
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".csv\"");
        pr = response.getWriter();
        pr.print(StringUtils.join(fileColumns, ","));
        pr.print("\r\n");
        DotConnect dc = new DotConnect();
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT drj.id, drj.ident_to_index, drj.inode_to_index, drj.priority ")
                .append("FROM dist_reindex_journal drj WHERE drj.priority >= ")
                .append(DistributedJournalFactory.REINDEX_JOURNAL_PRIORITY_FAILED_FIRST_ATTEMPT);
        dc.setSQL(sql.toString());
        List<Map<String, Object>> failedRecords = dc.loadObjectResults();
        if (!failedRecords.isEmpty()) {
            for (Map<String, Object> row : failedRecords) {
                StringBuilder entry = new StringBuilder();
                String id = null;
                String priority = null;
                if (DbConnectionFactory.isOracle()) {
                    BigDecimal rowVal = (BigDecimal) row.get("id");
                    id = new Long(rowVal.toPlainString()).toString();
                    rowVal = (BigDecimal) row.get("priority");
                    priority = new Long(rowVal.toPlainString()).toString();
                } else {
                    Long rowVal = (Long) row.get("id");
                    id = rowVal.toString();
                    priority = String.valueOf((Integer) row.get("priority"));
                }
                entry.append(id).append(", ");
                entry.append(row.get("ident_to_index").toString()).append(", ");
                entry.append(row.get("inode_to_index").toString()).append(", ");
                entry.append(priority);
                pr.print(entry.toString());
                pr.print("\r\n");
            }
        } else {
            Logger.debug(this,
                    "Re-index table contained zero failed records. The CSV file will not be created.");
        }
    } catch (Exception e) {
        Logger.error(this, "Download of CSV file with remaining non-indexed records failed.", e);
    } finally {
        pr.flush();
        pr.close();
    }
}

From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java

@Test
public void testConvertToAvroStreamForBigDecimal() throws SQLException, IOException {
    final ResultSetMetaData metadata = mock(ResultSetMetaData.class);
    when(metadata.getColumnCount()).thenReturn(1);
    when(metadata.getColumnType(1)).thenReturn(Types.NUMERIC);
    when(metadata.getColumnName(1)).thenReturn("The.Chairman");
    when(metadata.getTableName(1)).thenReturn("1the::table");

    final ResultSet rs = mock(ResultSet.class);
    when(rs.getMetaData()).thenReturn(metadata);

    final AtomicInteger counter = new AtomicInteger(1);
    Mockito.doAnswer(new Answer<Boolean>() {
        @Override/*from  w w  w .java 2s. co m*/
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            return counter.getAndDecrement() > 0;
        }
    }).when(rs).next();

    final BigDecimal bigDecimal = new BigDecimal(38D);
    when(rs.getObject(Mockito.anyInt())).thenReturn(bigDecimal);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    JdbcCommon.convertToAvroStream(rs, baos, true);

    final byte[] serializedBytes = baos.toByteArray();

    final InputStream instream = new ByteArrayInputStream(serializedBytes);

    final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
    try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) {
        GenericRecord record = null;
        while (dataFileReader.hasNext()) {
            record = dataFileReader.next(record);
            assertEquals("_1the__table", record.getSchema().getName());
            assertEquals(bigDecimal.toString(), record.get("The_Chairman").toString());
        }
    }
}

From source file:org.openbravo.advpaymentmngt.ad_actionbutton.Reconciliation.java

private void printGrid(HttpServletResponse response, String strFinancialAccountId, String strStatmentDate,
        boolean afterDate, String selectedTransactionsIds, String strCurrentlyCleared, String strTotalPayment,
        String strTotalDeposit) throws IOException, ServletException {

    log4j.debug("Output: Grid on Financial Account || Transaction tab || Reconciliation window");

    XmlDocument xmlDocument = xmlEngine/*  ww w  .  j  a  va2  s. co  m*/
            .readXmlTemplate("org/openbravo/advpaymentmngt/ad_actionbutton/ReconciliationGrid")
            .createXmlDocument();

    FIN_FinancialAccount account = OBDal.getInstance().get(FIN_FinancialAccount.class, strFinancialAccountId);

    Map<String, String> map = FIN_Utility.getMapFromStringList(selectedTransactionsIds);

    FieldProvider[] data = TransactionsDao.getTransactionsFiltered(account,
            FIN_Utility.getDate(DateTimeData.nDaysAfter(this, strStatmentDate, "1")), afterDate);

    BigDecimal currentlyCleared = new BigDecimal(strCurrentlyCleared);
    BigDecimal totalPayment = new BigDecimal(strTotalPayment);
    BigDecimal totalDeposit = new BigDecimal(strTotalDeposit);

    for (FieldProvider fp : data) {

        if (!map.containsKey(fp.getField("transactionId")) && !fp.getField("markSelectedId").isEmpty()) {
            BigDecimal payAmt = new BigDecimal(fp.getField("paymentAmount"));
            BigDecimal depAmt = new BigDecimal(fp.getField("depositAmount"));
            currentlyCleared = currentlyCleared.add(payAmt).subtract(depAmt);
            totalPayment = totalPayment.add(payAmt);
            totalDeposit = totalDeposit.add(depAmt);
        }
    }

    xmlDocument.setParameter("calcTotalPayment", totalPayment.toString());
    xmlDocument.setParameter("caclTotalDeposit", totalDeposit.toString());
    xmlDocument.setParameter("calcCurrentlyCleared", currentlyCleared.toString());
    xmlDocument.setData("structure", data);

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
}

From source file:me.j360.idgen.impl.test.TableIdGenServiceJdbcTest.java

/**
 * initialze next BigDecimal Id//from ww w .  j  a  v  a2 s . com
 * 
 * @param tableName
 *            table name
 * @param nextId
 *            next id
 */
private void initializeNextBigDecimalId(String tableName, BigDecimal nextId) {
    try {
        DataSource dataSource = (DataSource) applicationContext.getBean("util_datasource");
        Connection conn = dataSource.getConnection();
        try {
            Statement statement = conn.createStatement();

            // Need to quote the BigDecimal as it
            // is larger than normal
            // numbers can be.
            // Was causing problems with MySQL
            statement.executeUpdate("INSERT INTO idstest (table_name, next_id) VALUES ('" + tableName + "', '"
                    + nextId.toString() + "')");
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        System.err.println("Unable to initialize next_id." + e);
        fail("Unable to initialize next_id. " + e);
    }
}