Example usage for java.math BigDecimal toPlainString

List of usage examples for java.math BigDecimal toPlainString

Introduction

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

Prototype

public String toPlainString() 

Source Link

Document

Returns a string representation of this BigDecimal without an exponent field.

Usage

From source file:com.servoy.extension.MarketPlaceExtensionProvider.java

private String getSizeString(int size) {
    String unit;/*from  ww  w .ja  va  2  s  .c  om*/
    double value;
    if (size > 1024 * 1024) {
        unit = " MB"; //$NON-NLS-1$
        value = ((double) size) / 1024 / 1024;
    } else {
        unit = " KB"; //$NON-NLS-1$
        value = ((double) size) / 1024;
    }

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);

    return bd.toPlainString() + unit;
}

From source file:org.whispersystems.bithub.controllers.GithubController.java

@Timed
@POST//from  w w w. j  av  a  2 s.com
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/commits/")
public void handleCommits(@Auth Authentication auth, @HeaderParam("X-Forwarded-For") String clientIp,
        @FormParam("payload") String eventString)
        throws IOException, UnauthorizedHookException, TransferFailedException, CoinbaseException {
    authenticate(clientIp);
    PushEvent event = getEventFromPayload(eventString);

    if (!repositories.containsKey(event.getRepository().getUrl().toLowerCase())) {
        throw new UnauthorizedHookException("Not a valid repository: " + event.getRepository().getUrl());
    }

    if (!event.getRef().equals(MASTER_REF)) {
        logger.info("Not a push to master: " + event.getRef());
        return;
    }

    Repository repository = event.getRepository();
    String defaultMode = repositories.get(repository.getUrl().toLowerCase());
    List<Commit> commits = getQualifyingCommits(event, defaultMode);
    BigDecimal balance = coinbaseClient.getAccountBalance();
    BigDecimal exchangeRate = coinbaseClient.getExchangeRate();

    logger.info("Retrieved balance: " + balance.toPlainString());

    sendPaymentsFor(repository, commits, balance, exchangeRate);
}

From source file:fixio.fixprotocol.fields.FieldFactoryTest.java

@Test
public void testValueOfFloat() throws Exception {
    BigDecimal value = BigDecimal.valueOf(new Random().nextInt()).movePointLeft(5);

    FloatField field = FieldFactory.valueOf(FieldType.SettlCurrFxRate.tag(),
            value.toPlainString().getBytes(US_ASCII));

    assertEquals("tagnum", FieldType.SettlCurrFxRate.tag(), field.getTagNum());
    assertEquals("value", value.doubleValue(), field.getValue().doubleValue(), 0.0);
    assertEquals("value", value.floatValue(), field.floatValue(), 0.0);

}

From source file:no.dusken.annonseweb.control.InvoiceController.java

@RequestMapping("/print/blank/{invoice}")
public String printInvoice(@PathVariable Invoice invoice, Model model) {
    BigDecimal tot = new BigDecimal(0);
    for (Sale s : invoice.getSales()) {
        for (Ad a : s.getAds()) {
            tot.add(a.getFinalPrice());/*www . jav  a  2  s.  c o  m*/
        }
    }
    model.addAttribute("invoice", invoice);
    model.addAttribute("total", tot.toPlainString());
    return "invoice/print";
}

From source file:org.opentestsystem.authoring.testauth.validation.PerformanceLevelValueValidator.java

@Override
public void validate(final Object obj, final Errors errors) {
    final PerformanceLevelValue performanceLevelValue = (PerformanceLevelValue) obj;

    if (performanceLevelValue != null) {
        BigDecimal scaledLoValue = null;
        BigDecimal scaledHiValue = null;
        if (StringUtils.isNotEmpty(performanceLevelValue.getScaledLo())) {
            try {
                scaledLoValue = new BigDecimal(performanceLevelValue.getScaledLo());
                performanceLevelValue.setScaledLo(scaledLoValue.toPlainString());
                if (scaledLoValue.compareTo(BigDecimal.ZERO) < 0) {
                    rejectValue(errors, SCALED_LO, getErrorMessageRoot() + SCALED_LO + MSG_MIN);
                }/*from   w ww  .j a va 2  s .co m*/
            } catch (final NumberFormatException e) {
                rejectValue(errors, SCALED_LO, getErrorMessageRoot() + SCALED_LO + MSG_INVALID);
            }

        }
        if (StringUtils.isNotEmpty(performanceLevelValue.getScaledHi())) {
            try {
                scaledHiValue = new BigDecimal(performanceLevelValue.getScaledHi());
                performanceLevelValue.setScaledHi(scaledHiValue.toPlainString());
                if (scaledHiValue.compareTo(BigDecimal.ZERO) < 0) {
                    rejectValue(errors, SCALED_HI, getErrorMessageRoot() + SCALED_HI + MSG_MIN);
                }
            } catch (final NumberFormatException e) {
                rejectValue(errors, SCALED_HI, getErrorMessageRoot() + SCALED_HI + MSG_INVALID);
            }
        }
        if (scaledLoValue != null && scaledHiValue != null) {
            if (scaledLoValue.compareTo(scaledHiValue) >= 0) {
                rejectValue(errors, SCALED_LO, getErrorMessageRoot() + SCALED_LO + MSG_LESS_THAN_MAX);
            }
        }
    }
}

From source file:com.ehi.carshare.Main.java

private void run(String logformat, String inputFile, String outputFile) throws Exception {

    printAllPossibles(logformat);/*  w w  w  .ja  va  2 s  .co  m*/

    Parser<ApacheHttpLog> parser = new ApacheHttpdLoglineParser<ApacheHttpLog>(ApacheHttpLog.class, logformat);
    parser.ignoreMissingDissectors();

    // Load file in memory
    File file = new File(inputFile);
    if (!file.exists()) {
        throw new RuntimeException("Input file does not exist");
    }
    BufferedReader reader = new BufferedReader(new FileReader(file));
    List<String> readLines = new ArrayList<String>();
    String line = reader.readLine();
    while (line != null) {
        readLines.add(line);
        line = reader.readLine();
    }
    reader.close();

    // Parse apache logs
    List<ApacheHttpLog> myRecords = new ArrayList<ApacheHttpLog>();
    for (String readLine : readLines) {

        try {
            ApacheHttpLog myRecord = new ApacheHttpLog();
            parser.parse(myRecord, readLine);
            if (myRecord.getAction() != null && "200".equals(myRecord.getStatus())
                    && myRecord.getPath() != null) {
                myRecords.add(myRecord);
            }
        } catch (Exception e) {
            ///      e.printStackTrace();
        }
    }

    // Group by action
    Map<String, List<ApacheHttpLog>> map = new HashMap<String, List<ApacheHttpLog>>();
    for (ApacheHttpLog item : myRecords) {

        String key = item.getAction();
        if (map.get(key) == null) {
            map.put(key, new ArrayList<ApacheHttpLog>());
        }
        map.get(key).add(item);
    }

    // Collect stats
    List<ApacheHttpLogStats> recordStats = new ArrayList<ApacheHttpLogStats>();
    for (Entry<String, List<ApacheHttpLog>> entry : map.entrySet()) {
        ApacheHttpLogStats stats = new ApacheHttpLogStats();
        stats.setActionName(entry.getKey());
        long responseCount = entry.getValue().size();
        stats.setResponseCount(responseCount);
        long sum = 0;
        for (ApacheHttpLog myRecord : entry.getValue()) {
            sum = sum + myRecord.getResponseTime();
        }
        BigDecimal average = new BigDecimal(sum)
                .divide(new BigDecimal(responseCount * 1000000), 2, RoundingMode.HALF_UP)
                .setScale(2, RoundingMode.UP);
        stats.setAverageResponseTime(average.toPlainString());
        recordStats.add(stats);
    }

    // Write lines to file
    PrintWriter f0 = new PrintWriter(new FileWriter(outputFile));
    f0.print(ApacheHttpLogStats.headerString());
    for (ApacheHttpLogStats myRecordStats : recordStats) {
        f0.print(myRecordStats.toString());
    }
    f0.close();

}

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

/**
 * Load Internal Consumption Line//from   w ww. j  a  va  2s.co  m
 * 
 * @return DocLine Array
 */
private DocLine[] loadLines(ConnectionProvider conn) {
    ArrayList<Object> list = new ArrayList<Object>();
    DocLineInternalConsumptionData[] data = null;
    OBContext.setAdminMode(false);
    try {
        data = DocLineInternalConsumptionData.select(conn, Record_ID);
        for (int i = 0; data != null && i < data.length; i++) {
            String Line_ID = data[i].getField("mInternalConsumptionlineId");
            DocLine_Material docLine = new DocLine_Material(DocumentType, Record_ID, Line_ID);
            docLine.loadAttributes(data[i], this);
            log4jDocInternalConsumption.debug("MovementQty = " + data[i].getField("movementqty"));
            BigDecimal MovementQty = new BigDecimal(data[i].getField("movementqty"));
            docLine.setQty(MovementQty.toPlainString(), conn);
            docLine.m_M_Locator_ID = data[i].getField("mLocatorId");

            // Get related M_Transaction_ID
            InternalConsumptionLine intConsLine = OBDal.getInstance().get(InternalConsumptionLine.class,
                    Line_ID);
            if (intConsLine.getMaterialMgmtMaterialTransactionList().size() > 0) {
                docLine.setTransaction(intConsLine.getMaterialMgmtMaterialTransactionList().get(0));
            }
            DocInternalConsumptionData[] data1 = null;
            try {
                data1 = DocInternalConsumptionData.selectWarehouse(conn, docLine.m_M_Locator_ID);
            } catch (ServletException e) {
                log4jDocInternalConsumption.warn(e);
            }
            if (data1 != null && data1.length > 0)
                this.M_Warehouse_ID = data1[0].mWarehouseId;
            list.add(docLine);
        }
    } catch (ServletException e) {
        log4jDocInternalConsumption.warn(e);
    } finally {
        OBContext.restorePreviousMode();
    }
    // Return Array
    DocLine[] dl = new DocLine[list.size()];
    list.toArray(dl);
    return dl;
}

From source file:org.jvnet.hudson.plugins.backup.utils.RestoreTask.java

public void run() {
    assert (logFilePath != null);
    assert (backupFileName != null);

    startDate = new Date();
    try {//  w  ww.j a v  a2  s  . co m
        logger = new BackupLogger(logFilePath, configuration.isVerbose());
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Unable to open log file for writing : {0}", logFilePath);
        return;
    }

    logger.info("Restore started at " + getTimestamp(startDate));

    File directory = new File(hudsonWorkDir);

    String tempDirectoryPath = hudsonWorkDir + "_restore";
    logger.info("Working into " + tempDirectoryPath + " directory");

    File temporary_directory = new File(tempDirectoryPath);

    if (temporary_directory.exists()) {
        logger.info("A old restore working dir exists, cleaning ...");
        try {
            FileUtils.deleteDirectory(temporary_directory);
        } catch (IOException e) {
            logger.error("Unable to delete " + tempDirectoryPath);
            e.printStackTrace(logger.getWriter());
            finished = true;
            return;
        }
    }
    temporary_directory.mkdir();

    File archive = new File(backupFileName);

    logger.info("Uncompressing archive file...");
    UnArchiver unAchiver = configuration.getArchiveType().getUnArchiver();

    try {
        unAchiver.unArchive(archive, tempDirectoryPath);
    } catch (Exception e) {
        e.printStackTrace(logger.getWriter());
        logger.error("Error uncompressiong archive : " + e.getMessage());
        finished = true;
        return;
    }

    // Not using tools like FileUtils.deleteDirectory
    // because it is failing with non existing symbolic links
    logger.info("Removing old configuration files...");
    delete(directory);

    logger.info("Making temporary directory the hudson home...");
    temporary_directory.renameTo(directory);

    logger.info("*****************************************");
    logger.info("Reloading hudson configuration from disk.");
    logger.info("*****************************************");

    StaplerRequest request = FakeObject.getStaplerRequestFake(servletContext);
    StaplerResponse response = FakeObject.getStaplerResponseFake();

    try {
        Hudson.getInstance().doReload(request, response);
    } catch (IOException e) {
        logger.error("Error reloading config files from disk.");
        logger.error("Call this method manually");
        e.printStackTrace(logger.getWriter());
    }

    endDate = new Date();
    logger.info("Backup end at " + getTimestamp(endDate));
    BigDecimal delay = new BigDecimal(endDate.getTime() - startDate.getTime());
    delay = delay.setScale(2, BigDecimal.ROUND_HALF_UP);
    delay = delay.divide(new BigDecimal("1000"));

    logger.info("[" + delay.toPlainString() + "s]");
    finished = true;
    logger.close();
}

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

/**
 * Create Facts (the accounting logic) for MIC.
 * /*ww w. j  av  a 2 s  .co  m*/
 * <pre>
 *  Internal Consumption
 *      CoGS            DR      
 *      Inventory               CR
 * </pre>
 * 
 * @param as
 *          account schema
 * @return Fact
 */
@Override
public Fact createFact(AcctSchema as, ConnectionProvider conn, Connection con, VariablesSecureApp vars)
        throws ServletException {
    // Select specific definition
    String strClassname = AcctServerData.selectTemplateDoc(conn, as.m_C_AcctSchema_ID, DocumentType);
    if (StringUtils.isEmpty(strClassname)) {
        strClassname = AcctServerData.selectTemplate(conn, as.m_C_AcctSchema_ID, AD_Table_ID);
    } else {
        try {
            DocInternalConsumptionTemplate newTemplate = (DocInternalConsumptionTemplate) Class
                    .forName(strClassname).newInstance();
            return newTemplate.createFact(this, as, conn, con, vars);
        } catch (Exception e) {
            log4j.error("Error while creating new instance for DocInternalConsumptionTemplate - " + e);
        }
    }

    C_Currency_ID = as.getC_Currency_ID();
    // create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    String Fact_Acct_Group_ID = SequenceIdData.getUUID();
    // Line pointers
    FactLine dr = null;
    FactLine cr = null;
    log4jDocInternalConsumption.debug("CreateFact - before loop");
    for (int i = 0; i < p_lines.length; i++) {
        DocLine_Material line = (DocLine_Material) p_lines[i];

        Currency costCurrency = FinancialUtils
                .getLegalEntityCurrency(OBDal.getInstance().get(Organization.class, line.m_AD_Org_ID));
        if (!CostingStatus.getInstance().isMigrated()) {
            costCurrency = OBDal.getInstance().get(Client.class, AD_Client_ID).getCurrency();
        } else if (line.transaction != null && line.transaction.getCurrency() != null) {
            costCurrency = line.transaction.getCurrency();
        }
        if (CostingStatus.getInstance().isMigrated() && line.transaction != null
                && !line.transaction.isCostCalculated()) {
            Map<String, String> parameters = getNotCalculatedCostParameters(line.transaction);
            setMessageResult(conn, STATUS_NotCalculatedCost, "error", parameters);
            throw new IllegalStateException();
        }
        String costs = line.getProductCosts(DateAcct, as, conn, con);
        log4jDocInternalConsumption.debug("CreateFact - before DR - Costs: " + costs);
        BigDecimal b_Costs = new BigDecimal(costs);
        String strCosts = b_Costs.toPlainString();
        Account cogsAccount = line.getAccount(ProductInfo.ACCTTYPE_P_Cogs, as, conn);
        Product product = OBDal.getInstance().get(Product.class, line.m_M_Product_ID);
        if (cogsAccount == null) {
            org.openbravo.model.financialmgmt.accounting.coa.AcctSchema schema = OBDal.getInstance().get(
                    org.openbravo.model.financialmgmt.accounting.coa.AcctSchema.class, as.m_C_AcctSchema_ID);
            log4j.error("No Account COGS for product: " + product.getName() + " in accounting schema: "
                    + schema.getName());
        }
        Account assetAccount = line.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn);
        if (assetAccount == null) {
            org.openbravo.model.financialmgmt.accounting.coa.AcctSchema schema = OBDal.getInstance().get(
                    org.openbravo.model.financialmgmt.accounting.coa.AcctSchema.class, as.m_C_AcctSchema_ID);
            log4j.error("No Account Asset for product: " + product.getName() + " in accounting schema: "
                    + schema.getName());
        }
        if (b_Costs.compareTo(BigDecimal.ZERO) == 0 && !CostingStatus.getInstance().isMigrated()
                && DocInOutData.existsCost(conn, DateAcct, line.m_M_Product_ID).equals("0")) {
            Map<String, String> parameters = getInvalidCostParameters(
                    OBDal.getInstance().get(Product.class, line.m_M_Product_ID).getIdentifier(), DateAcct);
            setMessageResult(conn, STATUS_InvalidCost, "error", parameters);
            throw new IllegalStateException();
        }
        dr = fact.createLine(line, cogsAccount, costCurrency.getId(), strCosts, "", Fact_Acct_Group_ID,
                nextSeqNo(SeqNo), DocumentType, conn);
        if (dr != null) {
            dr.setM_Locator_ID(line.m_M_Locator_ID);
            dr.setLocationFromLocator(line.m_M_Locator_ID, true, conn); // from
            dr.setLocationFromBPartner(C_BPartner_Location_ID, false, conn); // to
        }
        log4jDocInternalConsumption.debug("CreateFact - before CR");
        cr = fact.createLine(line, assetAccount, costCurrency.getId(), "", strCosts, Fact_Acct_Group_ID,
                nextSeqNo(SeqNo), DocumentType, conn);
        if (cr != null) {
            cr.setM_Locator_ID(line.m_M_Locator_ID);
            cr.setLocationFromLocator(line.m_M_Locator_ID, true, conn); // from
            cr.setLocationFromBPartner(C_BPartner_Location_ID, false, conn); // to
        }
    }
    log4jDocInternalConsumption.debug("CreateFact - after loop");
    SeqNo = "0";
    return fact;
}

From source file:org.kuali.rice.core.api.util.type.AbstractKualiDecimal.java

public AbstractKualiDecimal(BigDecimal value, int scale) {
    this(value.toPlainString(), scale);
}