Example usage for java.math RoundingMode HALF_EVEN

List of usage examples for java.math RoundingMode HALF_EVEN

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_EVEN.

Prototype

RoundingMode HALF_EVEN

To view the source code for java.math RoundingMode HALF_EVEN.

Click Source Link

Document

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

Usage

From source file:strat.mining.stratum.proxy.worker.GetworkJobTemplate.java

/**
 * Compute the target based on the difficulty.
 * /*from ww  w.java2s . c  o  m*/
 * @param difficulty
 * @param isScrypt
 */
private void computeTarget(double difficulty, CryptoAlgorithm algo) {
    BigDecimal difficulty1 = new BigDecimal(0);
    switch (algo) {
    case Scrypt:
        difficulty1 = ScryptHashingUtils.DIFFICULTY_1_TARGET;
        break;
    case SHA256:
        difficulty1 = SHA256HashingUtils.DIFFICULTY_1_TARGET;
        break;
    default:
        throw new UnsupportedCryptoAlgorithmException(algo);
    }

    targetInteger = difficulty1.divide(BigDecimal.valueOf(difficulty), 0, RoundingMode.HALF_EVEN)
            .toBigInteger();
    byte[] bigEndianTargetBytes = targetInteger.toByteArray();

    // Build the target on 32 Bytes
    byte[] littleEndianTargetBytes = new byte[32];
    strat.mining.stratum.proxy.utils.ArrayUtils.copyInto(bigEndianTargetBytes, littleEndianTargetBytes,
            32 - bigEndianTargetBytes.length);
    // Then swap bytes from big-endian to little-endian
    littleEndianTargetBytes = strat.mining.stratum.proxy.utils.ArrayUtils.swapBytes(littleEndianTargetBytes, 4);
    // And reverse the order of 4-bytes words (big-endian to little-endian
    // 256-bits integer)
    littleEndianTargetBytes = strat.mining.stratum.proxy.utils.ArrayUtils.reverseWords(littleEndianTargetBytes,
            4);
    this.target = BaseEncoding.base16().encode(littleEndianTargetBytes);
}

From source file:com.artivisi.biller.simulator.gateway.pln.PlnGateway.java

private StringBuffer createBit48InquiryPostpaidResponse(String bit48Request, Pelanggan p,
        List<TagihanPascabayar> daftarTagihan, List<TagihanPascabayar> tagihanDikirim,
        InquiryPostpaidResponse ipr) {/*from w  ww  . j  a v  a 2 s  .  co m*/
    StringBuffer bit48Response = new StringBuffer();
    bit48Response.append(bit48Request);
    bit48Response.append(tagihanDikirim.size());
    bit48Response.append(StringUtils.leftPad(String.valueOf(daftarTagihan.size()), 2, "0"));
    bit48Response.append(ipr.getId().toUpperCase());
    bit48Response.append(StringUtils.rightPad(p.getNama(), 25, " "));
    bit48Response.append(StringUtils.rightPad(p.getServiceUnit(), 5, " "));
    bit48Response.append(StringUtils.rightPad(p.getServiceUnitPhone(), 15, " "));
    bit48Response.append(StringUtils.rightPad(p.getSubscriberSegmentation(), 4, " "));
    bit48Response.append(StringUtils.leftPad(p.getPowerConsumingCategory(), 9, "0"));
    bit48Response.append(StringUtils.leftPad("", 9, "0")); // total admin charges

    for (TagihanPascabayar t : tagihanDikirim) {
        bit48Response.append(DateTimeFormat.forPattern("yyyyMM").print(t.getBillPeriod().getTime()));
        bit48Response.append(DateTimeFormat.forPattern("ddMMyyyy").print(t.getDueDate().getTime()));
        bit48Response.append(DateTimeFormat.forPattern("ddMMyyyy").print(t.getMeterReadDate().getTime()));
        bit48Response.append(
                StringUtils.leftPad(t.getBill().setScale(0, RoundingMode.HALF_EVEN).toString(), 11, "0"));
        if (BigDecimal.ZERO.compareTo(t.getInsentif()) > 0) {
            bit48Response.append("D");
        } else {
            bit48Response.append("C");
        }
        bit48Response.append(StringUtils
                .leftPad(t.getInsentif().abs().setScale(0, RoundingMode.HALF_EVEN).toString(), 10, "0"));
        bit48Response.append(
                StringUtils.leftPad(t.getVat().setScale(0, RoundingMode.HALF_EVEN).toString(), 10, "0"));
        bit48Response.append(
                StringUtils.leftPad(t.getDenda().setScale(0, RoundingMode.HALF_EVEN).toString(), 10, "0"));
        bit48Response.append(StringUtils.leftPad(t.getPreviousMeterRead1(), 8, "0"));
        bit48Response.append(StringUtils.leftPad(t.getCurrentMeterRead1(), 8, "0"));
        bit48Response.append(StringUtils.leftPad(t.getPreviousMeterRead2(), 8, "0"));
        bit48Response.append(StringUtils.leftPad(t.getCurrentMeterRead2(), 8, "0"));
        bit48Response.append(StringUtils.leftPad(t.getPreviousMeterRead3(), 8, "0"));
        bit48Response.append(StringUtils.leftPad(t.getCurrentMeterRead3(), 8, "0"));
    }
    return bit48Response;
}

From source file:org.broadleafcommerce.vendor.cybersource.service.tax.CyberSourceTaxServiceImpl.java

protected void setTaxRates(CyberSourceTaxResponse taxResponse, CyberSourceTaxRequest taxRequest,
        TaxReplyItem[] replyItems) {/*from   ww w .j  ava  2 s.  c  o  m*/
    CyberSourceTaxItemRequest requestItem = (CyberSourceTaxItemRequest) taxRequest.getItemRequests().get(0);
    BigDecimal unitPrice = requestItem.getUnitPrice().getAmount();
    BigInteger requestId = new BigInteger(String.valueOf(requestItem.getId()));
    TaxReplyItem key = new TaxReplyItem();
    key.setId(requestId);
    int pos = Arrays.binarySearch(replyItems, key, new Comparator<TaxReplyItem>() {

        public int compare(TaxReplyItem one, TaxReplyItem two) {
            return one.getId().compareTo(two.getId());
        }

    });
    if (pos >= 0) {
        TaxReplyItem replyItem = replyItems[pos];
        if (replyItem.getCityTaxAmount() != null) {
            BigDecimal cityRate = new BigDecimal(replyItem.getCityTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setCityRate(cityRate);
        }
        if (replyItem.getCountyTaxAmount() != null) {
            BigDecimal countyRate = new BigDecimal(replyItem.getCountyTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setCountyRate(countyRate);
        }
        if (replyItem.getDistrictTaxAmount() != null) {
            BigDecimal districtRate = new BigDecimal(replyItem.getDistrictTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setDistrictRate(districtRate);
        }
        if (replyItem.getStateTaxAmount() != null) {
            BigDecimal stateRate = new BigDecimal(replyItem.getStateTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setStateRate(stateRate);
        }
        if (replyItem.getTotalTaxAmount() != null) {
            BigDecimal totalRate = new BigDecimal(replyItem.getTotalTaxAmount()).divide(unitPrice, 5,
                    RoundingMode.HALF_EVEN);
            taxResponse.setTotalRate(totalRate);
        }
    }
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private String generateERPFile(FinantialInstitution institution, DateTime fromDate, DateTime toDate,
        List<? extends FinantialDocument> allDocuments, Boolean generateAllCustomers,
        Boolean generateAllProducts,
        java.util.function.UnaryOperator<AuditFile> preProcessFunctionBeforeSerialize) {

    // Build SAFT-AuditFile
    AuditFile auditFile = new AuditFile();
    // ThreadInformation information = 
    // SaftThreadRegister.retrieveCurrentThreadInformation();

    // Build SAFT-HEADER (Chapter 1 in AuditFile)
    Header header = this.createSAFTHeader(fromDate, toDate, institution, ERP_HEADER_VERSION_1_00_00);
    // SetHeader// w  w  w.  ja v  a  2s  . co  m
    auditFile.setHeader(header);

    // Build Master-Files
    oecd.standardauditfile_tax.pt_1.AuditFile.MasterFiles masterFiles = new oecd.standardauditfile_tax.pt_1.AuditFile.MasterFiles();

    // SetMasterFiles
    auditFile.setMasterFiles(masterFiles);

    // Build SAFT-MovementOfGoods (Customer and Products are built inside)
    // ProductsTable (Chapter 2.4 in AuditFile)
    List<oecd.standardauditfile_tax.pt_1.Product> productList = masterFiles.getProduct();
    Map<String, oecd.standardauditfile_tax.pt_1.Product> productMap = new HashMap<String, oecd.standardauditfile_tax.pt_1.Product>();
    Set<String> productCodes = new HashSet<String>();

    // ClientsTable (Chapter 2.2 in AuditFile)
    List<oecd.standardauditfile_tax.pt_1.Customer> customerList = masterFiles.getCustomer();
    Map<String, oecd.standardauditfile_tax.pt_1.Customer> customerMap = new HashMap<String, oecd.standardauditfile_tax.pt_1.Customer>();

    // Readd All  Clients if needed
    if (generateAllCustomers) {
        logger.info("Reading all Customers in Institution " + institution.getCode());

        Set<Customer> allCustomers = new HashSet<Customer>();
        for (DebtAccount debt : institution.getDebtAccountsSet()) {
            allCustomers.add(debt.getCustomer());
        }

        // Update the Total Objects Count
        // information.setTotalCounter(allCustomers.size() +
        // allProducts.size() + allDocuments.size() * 10);

        int i = 0;
        for (Customer customer : allCustomers) {
            oecd.standardauditfile_tax.pt_1.Customer saftCustomer = this
                    .convertCustomerToSAFTCustomer(customer);
            // information.setCurrentCounter(information.getCurrentCounter()
            // + 1);
            customerMap.put(saftCustomer.getCustomerID(), saftCustomer);
            i++;
            if (i % 100 == 0) {
                logger.info("Processing " + i + "/" + allCustomers.size() + " Customers in Institution "
                        + institution.getCode());
            }
        }
    }
    // Readd All Products if needed
    if (generateAllProducts) {

        logger.info("Reading all Customers in Institution " + institution.getCode());
        Set<Product> allProducts = institution.getAvailableProductsSet();
        int i = 0;
        for (Product product : allProducts) {
            if (!productCodes.contains(product.getCode())) {
                oecd.standardauditfile_tax.pt_1.Product saftProduct = this.convertProductToSAFTProduct(product);
                productCodes.add(product.getCode());
                productMap.put(saftProduct.getProductCode(), saftProduct);
            }

            i++;
            if (i % 100 == 0) {
                logger.info("Processing " + i + "/" + allProducts.size() + " Products in Institution "
                        + institution.getCode());
            }

            // information.setCurrentCounter(information.getCurrentCounter()
            // + 1);
        }
    } else {
        // information.setTotalCounter(allDocuments.size() * 10);
        // Update the Total Objects Count
        // information.setCurrentCounter(0);
    }

    // TaxTable (Chapter 2.5 in AuditFile)
    oecd.standardauditfile_tax.pt_1.TaxTable taxTable = new oecd.standardauditfile_tax.pt_1.TaxTable();
    masterFiles.setTaxTable(taxTable);

    for (Vat vat : institution.getVatsSet()) {
        taxTable.getTaxTableEntry().add(this.convertVATtoTaxTableEntry(vat, institution));
    }

    // Set MovementOfGoods in SourceDocuments(AuditFile)
    oecd.standardauditfile_tax.pt_1.SourceDocuments sourceDocuments = new oecd.standardauditfile_tax.pt_1.SourceDocuments();
    auditFile.setSourceDocuments(sourceDocuments);

    SourceDocuments.SalesInvoices invoices = new SourceDocuments.SalesInvoices();
    SourceDocuments.WorkingDocuments workingDocuments = new SourceDocuments.WorkingDocuments();
    Payments paymentsDocuments = new Payments();

    BigInteger numberOfPaymentsDocuments = BigInteger.ZERO;
    BigDecimal totalDebitOfPaymentsDocuments = BigDecimal.ZERO;
    BigDecimal totalCreditOfPaymentsDocuments = BigDecimal.ZERO;

    BigInteger numberOfWorkingDocuments = BigInteger.ZERO;
    BigDecimal totalDebitOfWorkingDocuments = BigDecimal.ZERO;
    BigDecimal totalCreditOfWorkingDocuments = BigDecimal.ZERO;

    invoices.setNumberOfEntries(BigInteger.ZERO);
    invoices.setTotalCredit(BigDecimal.ZERO);
    invoices.setTotalDebit(BigDecimal.ZERO);

    //        int i = 0;
    for (FinantialDocument document : allDocuments) {
        if ((document.isCreditNote() || document.isDebitNote())
                && (document.isClosed() || document.isAnnulled())) {
            try {
                WorkDocument workDocument = convertToSAFTWorkDocument((Invoice) document, customerMap,
                        productMap);
                workingDocuments.getWorkDocument().add(workDocument);

                // AcumulateValues
                numberOfWorkingDocuments = numberOfWorkingDocuments.add(BigInteger.ONE);
                if (!document.isAnnulled()) {
                    if (document.isDebitNote()) {
                        totalDebitOfWorkingDocuments = totalDebitOfWorkingDocuments
                                .add(workDocument.getDocumentTotals().getNetTotal());
                    } else if (document.isCreditNote()) {
                        totalCreditOfWorkingDocuments = totalCreditOfWorkingDocuments
                                .add(workDocument.getDocumentTotals().getNetTotal());
                    }
                }

                //                    i++;

            } catch (Exception ex) {
                logger.error("Error processing document " + document.getUiDocumentNumber() + ": "
                        + ex.getLocalizedMessage());
                throw ex;
            }
        } else {
            logger.info("Ignoring document " + document.getUiDocumentNumber() + " because is not closed yet.");
        }

    }
    // Update Totals of Workingdocuments
    workingDocuments.setNumberOfEntries(numberOfWorkingDocuments);
    workingDocuments.setTotalCredit(totalCreditOfWorkingDocuments.setScale(2, RoundingMode.HALF_EVEN));
    workingDocuments.setTotalDebit(totalDebitOfWorkingDocuments.setScale(2, RoundingMode.HALF_EVEN));

    sourceDocuments.setWorkingDocuments(workingDocuments);

    //PROCESSING PAYMENTS TABLE

    paymentsDocuments.setNumberOfEntries(BigInteger.ZERO);
    paymentsDocuments.setTotalCredit(BigDecimal.ZERO);
    paymentsDocuments.setTotalDebit(BigDecimal.ZERO);
    for (FinantialDocument document : allDocuments) {
        if (document.isSettlementNote() && (document.isClosed() || document.isAnnulled())) {
            try {
                Payment paymentDocument = convertToSAFTPaymentDocument((SettlementNote) document, customerMap,
                        productMap);
                paymentsDocuments.getPayment().add(paymentDocument);

                // AcumulateValues
                numberOfPaymentsDocuments = numberOfPaymentsDocuments.add(BigInteger.ONE);
                if (!document.isAnnulled()) {
                    totalCreditOfPaymentsDocuments = totalCreditOfPaymentsDocuments
                            .add(((SettlementNote) document).getTotalCreditAmount());
                    totalDebitOfPaymentsDocuments = totalDebitOfPaymentsDocuments
                            .add(((SettlementNote) document).getTotalDebitAmount());
                }
                //                    i++;
            } catch (Exception ex) {
                // persistenceSupport.flush();
                logger.error("Error processing document " + document.getUiDocumentNumber() + ": "
                        + ex.getLocalizedMessage());
                throw ex;
            }
        } else {
            logger.info("Ignoring document " + document.getUiDocumentNumber() + " because is not closed yet.");
        }

    }

    // Update Totals of Payment Documents
    paymentsDocuments.setNumberOfEntries(numberOfPaymentsDocuments);
    paymentsDocuments.setTotalCredit(totalCreditOfPaymentsDocuments.setScale(2, RoundingMode.HALF_EVEN));
    paymentsDocuments.setTotalDebit(totalDebitOfPaymentsDocuments.setScale(2, RoundingMode.HALF_EVEN));
    sourceDocuments.setPayments(paymentsDocuments);

    // Update the Customer Table in SAFT
    for (oecd.standardauditfile_tax.pt_1.Customer customer : customerMap.values()) {
        customerList.add(customer);
    }

    // Update the Product Table in SAFT
    for (oecd.standardauditfile_tax.pt_1.Product product : productMap.values()) {
        productList.add(product);
    }

    if (preProcessFunctionBeforeSerialize != null) {
        auditFile = preProcessFunctionBeforeSerialize.apply(auditFile);
    }
    String xml = exportAuditFileToXML(auditFile);

    logger.info("SAFT File export concluded with success.");
    return xml;
}

From source file:com.automaster.autoview.server.servlet.ExcelServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /*response.setContentType("application/vnd.ms-excel");
     response.setHeader("Content-Disposition", "attachment; filename=filename.xls");
     HSSFWorkbook workbook = new HSSFWorkbook();
     // ...//from  w  w w.j  a va  2 s .  c o m
     // Now populate workbook the usual way.
     // ...
     OutputStream arqSaida = response.getOutputStream();
     workbook.write(arqSaida); // Write workbook to response.
     arqSaida.flush();
     arqSaida.close();*/
    //getServletContext().getRealPath("/")
    String tempoDecorrido = " 0";
    String url = getServletContext().getRealPath("/");
    String placa = request.getParameter("placa");
    //TimeZone timeZoneMundial = TimeZone.getTimeZone(ZoneId.ofOffset("UTC", ZoneOffset.UTC));
    Timestamp dataInicio = new Timestamp(Long.parseLong(request.getParameter("dataInicio")));
    Timestamp dataFim = new Timestamp(Long.parseLong(request.getParameter("dataFim")));
    //String timeZoneInterface = request.getParameter("timeZone");
    /*String timeZone = "Z";
    if(timeZoneInterface.equalsIgnoreCase("0")){
    timeZone = "Z";
    } else {
    timeZone = String.valueOf((-1) * (Integer.parseInt(timeZoneInterface) / 60));
    }  */
    TimeZone timeZonePadrao = TimeZone.getTimeZone(ZoneId.of("-3"));
    System.out.println("Time zone Cliente : " + timeZonePadrao);
    //System.out.println("timeZoneInterface: "+timeZoneInterface);
    //System.out.println("timeZone: "+timeZone);
    //String ign = request.getParameter("ign");
    ZzzPosPlacaVeiculoDAO zzzPosPlacaVeiculoDAO = new ZzzPosPlacaVeiculoDAO();
    ArrayList<TreeMap<String, String>> posicoes = zzzPosPlacaVeiculoDAO.buscarPosicoesPorIntervaloData(placa,
            dataInicio, dataFim);

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition", "attachment; filename=Historico-" + placa + ".xlsx");

    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("Histrico - " + placa);
    int pictureIdx;
    try ( //add picture data to this workbook.
            InputStream is = new FileInputStream(url + "/imagens/logo.jpg")) {
        byte[] bytes = IOUtils.toByteArray(is);
        pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
    }

    CreationHelper helper = wb.getCreationHelper();

    // Create the drawing patriarch.  This is the top level container for all shapes. 
    Drawing drawing = sheet.createDrawingPatriarch();

    //add a picture shape
    ClientAnchor anchor = helper.createClientAnchor();
    //set top-left corner of the picture,
    //subsequent call of Picture#resize() will operate relative to it
    anchor.setCol1(1);
    anchor.setRow1(0);
    Picture pict = drawing.createPicture(anchor, pictureIdx);
    //auto-size picture relative to its top-left corner
    pict.resize(3, 3);
    //pict.resize();
    //sheet.setColumnWidth(0, 200);

    Font fonte = wb.createFont();
    fonte.setFontHeightInPoints((short) 24);
    fonte.setFontName("Arial");
    fonte.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    fonte.setItalic(true);
    CellStyle estiloTitulo = wb.createCellStyle();
    estiloTitulo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    estiloTitulo.setFont(fonte);

    Font fonteCabecalho = wb.createFont();
    fonteCabecalho.setFontHeightInPoints((short) 14);
    fonteCabecalho.setFontName("Arial");
    fonteCabecalho.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    //fonteCabecalho.setItalic(true);
    CellStyle estiloCabecalho = wb.createCellStyle();
    estiloCabecalho.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    estiloCabecalho.setFont(fonteCabecalho);

    Font fonteTituloTabela = wb.createFont();
    //fonteTituloTabela.setFontHeightInPoints((short) 14);
    fonteTituloTabela.setFontName("Arial");
    fonteTituloTabela.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

    CellStyle estilo = wb.createCellStyle();
    estilo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    estilo.setFont(fonteTituloTabela);

    CellStyle estiloCorpo = wb.createCellStyle();
    estiloCorpo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    //estiloCorpo.setFillBackgroundColor(HSSFColor.WHITE.index);
    //estiloCorpo.setFont(fonteTituloTabela);

    XSSFRow linha6 = (XSSFRow) sheet.createRow(6);
    XSSFCell cell046 = linha6.createCell(3);
    cell046.setCellValue("Relatrio de Posies");
    cell046.setCellStyle(estiloTitulo);
    //sheet.addMergedRegion(new CellRangeAddress(6, 6, 0, 3));

    XSSFRow linha7 = (XSSFRow) sheet.createRow(7);
    XSSFCell cell047 = linha7.createCell(3);
    cell047.setCellValue("Veculo : " + placa);
    cell047.setCellStyle(estiloCabecalho);
    //sheet.addMergedRegion(new CellRangeAddress(7, 7, 0, 3));

    XSSFRow linha8 = (XSSFRow) sheet.createRow(8);
    XSSFCell cell038 = linha8.createCell(3);
    //TimeZone.setDefault(timeZoneMundial);
    //Date dataHoraInicio0 = new Date(Long.parseLong(request.getParameter("dataInicio")));
    //TimeZone.setDefault(timeZoneCliente);
    //Date dataHoraInicio = new Date(dataHoraInicio0.getTime());
    SimpleDateFormat dataFormatadaCabecalho = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    dataFormatadaCabecalho.setTimeZone(timeZonePadrao);
    cell038.setCellValue("Perodo: De: " + dataFormatadaCabecalho.format(dataInicio) + " at: "
            + dataFormatadaCabecalho.format(dataFim));
    cell038.setCellStyle(estiloCabecalho);
    //sheet.addMergedRegion(new CellRangeAddress(8, 8, 0, 3));

    sheet.setColumnWidth(0, 5000);
    sheet.setColumnWidth(1, 3000);
    sheet.setColumnWidth(2, 3500);
    //sheet.setColumnWidth(3, 4000);
    sheet.setColumnWidth(3, 30000);
    //sheet.setColumnWidth(4, 4000);
    //sheet.setColumnWidth(4, 30000);
    sheet.setColumnWidth(5, 3000);
    sheet.setColumnWidth(6, 3000);
    sheet.setColumnWidth(7, 3000);
    sheet.setColumnWidth(8, 3000);
    sheet.setColumnWidth(9, 3000);
    //sheet.setColumnWidth(10, 20000);        
    sheet.setColumnWidth(11, 3000);
    XSSFRow linha9 = (XSSFRow) sheet.createRow(10);
    XSSFCell cell0 = linha9.createCell(0);
    cell0.setCellValue("Data e hora");
    cell0.setCellStyle(estilo);
    XSSFCell cell1 = linha9.createCell(1);
    cell1.setCellValue("Velocidade");
    cell1.setCellStyle(estilo);
    XSSFCell cell2 = linha9.createCell(2);
    cell2.setCellValue("Ignio");
    cell2.setCellStyle(estilo);
    //XSSFCell cell3 = linha9.createCell(3);
    //cell3.setCellValue("Latitude");
    //cell3.setCellStyle(estilo);
    //XSSFCell cell4 = linha9.createCell(4);
    //cell4.setCellValue("Longitude");
    //cell4.setCellStyle(estilo);
    //XSSFCell cell5 = linha9.createCell(5);
    //cell5.setCellValue("Satlite");
    //cell5.setCellStyle(estilo);
    //XSSFCell cell6 = linha9.createCell(6);
    //cell6.setCellValue("GPS");
    //cell6.setCellStyle(estilo);
    //XSSFCell cell7 = linha9.createCell(7);
    //cell7.setCellValue("Entrada");
    //cell7.setCellStyle(estilo);
    //XSSFCell cell8 = linha9.createCell(8);
    //cell8.setCellValue("Sada");
    //cell8.setCellStyle(estilo);
    //XSSFCell cell9 = linha9.createCell(9);
    //cell9.setCellValue("Evento");
    //cell9.setCellStyle(estilo);
    XSSFCell cell10 = linha9.createCell(3);
    cell10.setCellValue("Endereo");
    cell10.setCellStyle(estilo);
    //sheet.addMergedRegion(new CellRangeAddress(11, 11, 4, 8));
    //XSSFCell cell11 = linha9.createCell(11);
    //cell11.setCellValue("Direo");
    //cell11.setCellStyle(estilo);
    int linha = 0;
    int j = 11;
    double latAnt = 0;
    double lonAnt = 0;
    double latAtual = 0;
    double lonAtual = 0;
    double distancia = 0;
    double distanciaTotal = 0;
    for (int i = 0; i < posicoes.size(); i++) {
        XSSFRow row = (XSSFRow) sheet.createRow(j);
        if (i == 0) {
            distancia = 0;
            //System.out.println("linha 00 - EXCEL");
        } else {
            //System.out.println("linha 01 - EXCEL");
            latAnt = Double.parseDouble(posicoes.get(i - 1).get("lat"));
            lonAnt = Double.parseDouble(posicoes.get(i - 1).get("lon"));
            latAtual = Double.parseDouble(posicoes.get(i).get("lat"));
            lonAtual = Double.parseDouble(posicoes.get(i).get("lon"));
            //System.out.println("linha 02 - PDF");
            if (latAnt == latAtual && lonAnt == lonAtual) {
                distancia = 0;
            } else {
                distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual);
                //System.out.println("linha 03 - PDF");
            }

        }
        distanciaTotal = distanciaTotal + distancia;
        /*if(i==0) {
         latAnt = Double.parseDouble(posicoes.get(i).get("lat"));
         lonAnt = Double.parseDouble(posicoes.get(i).get("lon"));
        } else{
            latAnt = Double.parseDouble(posicoes.get(i-1).get("lat"));
            lonAnt = Double.parseDouble(posicoes.get(i-1).get("lon"));
        }
        double latAtual = Double.parseDouble(posicoes.get(i).get("lat"));
        double lonAtual = Double.parseDouble(posicoes.get(i).get("lon"));
        double distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual);
        distanciaTotal = distanciaTotal + distancia;*/
        for (int col = 0; col < posicoes.get(linha).size(); col++) {
            XSSFCell cell = row.createCell(col);
            cell.setCellStyle(estiloCorpo);
            switch (col) {
            case 0:
                Date dataHora0 = new Date(Long.parseLong(posicoes.get(i).get("dataHora")));
                Date dataHora = new Date(dataHora0.getTime());
                SimpleDateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                dataFormatada.setTimeZone(timeZonePadrao);
                cell.setCellValue(dataFormatada.format(dataHora));
                break;
            case 1:
                cell.setCellValue(posicoes.get(linha).get("vel"));
                break;
            case 2:
                cell.setCellValue(
                        posicoes.get(linha).get("ign").equalsIgnoreCase("True") ? "Ligada" : "Desligada");
                break;
            /*case 3:
                cell.setCellValue(posicoes.get(linha).get("lat"));
                break;
            case 4:
                cell.setCellValue(posicoes.get(linha).get("lon"));
                break;
            case 5:
                cell.setCellValue(posicoes.get(linha).get("sat"));
                break;
            case 6:
                cell.setCellValue(posicoes.get(linha).get("gps"));
                break;
            case 7:
                cell.setCellValue(posicoes.get(linha).get("entrada"));
                break;
            case 8:
                cell.setCellValue(posicoes.get(linha).get("saida"));
                break;
            case 9:
                cell.setCellValue(posicoes.get(linha).get("evento"));
                break;*/
            case 3:
                cell.setCellValue(posicoes.get(linha).get("endereco") == null ? "Sem endereo"
                        : posicoes.get(linha).get("endereco"));
                break;
            /*case 11:
                cell.setCellValue(posicoes.get(linha).get("direcao"));
                break;*/
            }

        }
        j = j + 1;
        linha = linha + 1;

    }
    tempoDecorrido = calculaDatas(Long.parseLong(posicoes.get(0).get("dataHora")),
            Long.parseLong(posicoes.get(posicoes.size() - 1).get("dataHora")));
    int index = 0;
    String kms = "0";
    String m = "";
    double metros = 0;
    if (distanciaTotal > 0) {
        BigDecimal decimalFormatado = new BigDecimal(distanciaTotal).setScale(2, RoundingMode.HALF_EVEN);
        index = String.valueOf(decimalFormatado).indexOf(".");
        kms = String.valueOf(decimalFormatado).substring(0, index);
        m = "0" + (String.valueOf(decimalFormatado).substring(index));
        metros = Double.parseDouble(m) * 1000;
    }
    //String formatted = NumberFormat.getFormat("000.00").format(metros);
    //System.out.println("Percorridos aproximadamente : "+kms+" KM e "+metros+" metros");
    XSSFRow linhaX = (XSSFRow) sheet.createRow(linha + 12);
    XSSFCell cellX = linhaX.createCell(0);
    sheet.addMergedRegion(new CellRangeAddress(linha + 12, linha + 12, 0, 3));
    cellX.setCellStyle(estilo);
    cellX.setCellValue(
            "Percorridos: " + kms + " KM e " + String.valueOf(metros) + " metros. Tempo: " + tempoDecorrido);
    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
    wb.write(outByteStream);

    byte[] outArray = outByteStream.toByteArray();
    OutputStream outStream = response.getOutputStream();
    outStream.write(outArray);
    outStream.flush();

}

From source file:com.aegiswallet.utils.WalletUtils.java

public static String getWalletCurrencyValue(Context context, SharedPreferences prefs, BigInteger balance) {
    String result = "";

    File file = context.getApplicationContext().getFileStreamPath(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME);
    if (file.exists()) {
        JSONObject jsonObject = BasicUtils.parseJSONData(context, Constants.BLOCKCHAIN_CURRENCY_FILE_NAME);
        try {//from   w  w w.  j a  v a  2 s .  co m

            String balanceInBTC = balance.toString();

            if (balance.longValue() > 0)
                balanceInBTC = BasicUtils.formatValue(balance, Constants.BTC_MAX_PRECISION, 0);
            BigDecimal formattedBalance = new BigDecimal(balanceInBTC);

            if (jsonObject != null) {

                JSONObject newObject = jsonObject
                        .getJSONObject(prefs.getString(Constants.CURRENCY_PREF_KEY, null));
                Double doubleVal = newObject.getDouble("last");
                BigDecimal decimal = BigDecimal.valueOf(doubleVal);

                result = newObject.getString("symbol")
                        + decimal.multiply(formattedBalance).setScale(2, RoundingMode.HALF_EVEN).toString();
            }
        } catch (JSONException e) {
            Log.e("Wallet Utils", "JSON Exception " + e.getMessage());
        }
    }

    return result;
}

From source file:org.mifosplatform.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*  www . j av  a  2s .  co  m*/
public CommandProcessingResult calculateInterest(final Long savingsId) {

    final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId);
    checkClientOrGroupActive(account);

    final LocalDate today = DateUtils.getLocalDateOfTenant();
    final MathContext mc = new MathContext(15, RoundingMode.HALF_EVEN);

    account.calculateInterestUsing(mc, today);

    this.savingAccountRepository.save(account);

    return new CommandProcessingResultBuilder() //
            .withEntityId(savingsId) //
            .withOfficeId(account.officeId()) //
            .withClientId(account.clientId()) //
            .withGroupId(account.groupId()) //
            .withSavingsId(savingsId) //
            .build();
}

From source file:org.mayocat.shop.checkout.front.CheckoutResource.java

/**
 * Prepare checkout response context//from  w  w  w .j  a  va 2 s .  c  o m
 *
 * @param order the order concerned by the notification
 * @param customer the customer
 * @param ba an optional billing address
 * @param da an optional shipping address
 * @param tenant the tenant the order was checked out from
 * @param locale the main locale of the tenant
 * @return a JSON context as map
 */
private Map<String, Object> prepareContext(Order order, Customer customer, Optional<Address> ba,
        Optional<Address> da, Tenant tenant, Locale locale) {
    List<OrderItem> items = order.getOrderItems();
    Map<String, Object> context = Maps.newHashMap();

    MoneyFormatter formatter = new MoneyFormatterBuilder().appendAmount(MoneyAmountStyle.of(locale))
            .appendLiteral(" ").appendCurrencySymbolLocalized().toFormatter();

    CurrencyUnit currencyUnit = CurrencyUnit.of(order.getCurrency());
    String grandTotal = formatter.withLocale(locale)
            .print(Money.of(currencyUnit, order.getGrandTotal(), RoundingMode.HALF_EVEN));
    String itemsTotal = formatter.withLocale(locale)
            .print(Money.of(currencyUnit, order.getItemsTotal(), RoundingMode.HALF_EVEN));

    List<Map<String, Object>> orderItems = Lists.newArrayList();
    for (OrderItem item : items) {
        Map<String, Object> orderItem = Maps.newHashMap();
        orderItem.put("title", item.getTitle());
        orderItem.put("quantity", item.getQuantity());

        // Replace big decimal values by formatted values
        Double unitPrice = item.getUnitPrice().doubleValue();
        Double itemTotal = item.getItemTotal().doubleValue();

        orderItem.put("unitPrice",
                formatter.withLocale(locale).print(Money.of(currencyUnit, unitPrice, RoundingMode.HALF_EVEN)));
        orderItem.put("itemTotal",
                formatter.withLocale(locale).print(Money.of(currencyUnit, itemTotal, RoundingMode.HALF_EVEN)));

        orderItems.add(orderItem);
    }

    context.put("items", orderItems);

    if (order.getShipping() != null) {
        String shippingTotal = formatter.withLocale(locale)
                .print(Money.of(currencyUnit, order.getShipping(), RoundingMode.HALF_EVEN));
        context.put("shippingTotal", shippingTotal);
        context.put("shipping", order.getOrderData().get("shipping"));
    }

    context.put("siteName", tenant.getName());
    context.put("itemsTotal", itemsTotal);
    context.put("orderId", order.getSlug());
    context.put("grandTotal", grandTotal);

    Map<String, Object> customerMap = Maps.newHashMap();
    customerMap.put("firstName", customer.getFirstName());
    customerMap.put("lastName", customer.getLastName());
    customerMap.put("email", customer.getEmail());
    customerMap.put("phone", customer.getPhoneNumber());
    context.put("customer", customerMap);

    if (ba.isPresent()) {
        context.put("billingAddress", prepareAddressContext(ba.get()));
    }
    if (da.isPresent()) {
        context.put("deliveryAddress", prepareAddressContext(da.get()));
    }

    context.put("siteUrl", urlHelper.getContextWebURL("").toString());

    return context;
}

From source file:com.automaster.autoview.server.servlet.ExcelServlet.java

private double caculaDistanciaEntreDoisPontos(double lat1, double lon1, double lat2, double lon2) {

    //Transforma cordenadas em radianos
    /*String lat1Reduzida = String.valueOf(lat1);
    int index = lat1Reduzida.indexOf(".");
    String latFinal1 = lat1Reduzida.substring(0, index+5);
            //  w ww .java  2s .c om
    String lon1Reduzida = String.valueOf(lon1);
    String lonFinal1 = lon1Reduzida.substring(0, index+5);
            
    String lat2Reduzida = String.valueOf(lat2);
    String latFinal2 = lat2Reduzida.substring(0, index+5);
            
    String lon2Reduzida = String.valueOf(lon2);
    String lonFinal2 = lon2Reduzida.substring(0, index+5);*/

    double lat01 = Math.toRadians(lat1);
    double lon01 = Math.toRadians(lon1);
    double lat02 = Math.toRadians(lat2);
    double lon02 = Math.toRadians(lon2);
    //calcula a distncia em KM atravs da frmula
    double dist = (6371 * Math.acos(
            Math.cos(lat01) * Math.cos(lat02) * Math.cos(lon02 - lon01) + Math.sin(lat01) * Math.sin(lat02)));
    //formata o resultado
    if (dist > 0) {
        BigDecimal decimalFormatado = new BigDecimal(dist).setScale(2, RoundingMode.HALF_EVEN);
        return decimalFormatado.doubleValue();
    }
    return 0;
    //return dist;

}