Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

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

Prototype

RoundingMode HALF_UP

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

Click Source Link

Document

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

Usage

From source file:data.services.EventService.java

public void saveLog(Long evId, List<EntityCar> carList, List<IdealEntityParam> ieplist,
        List<EntityCar> cutCarList, Sequence seq) throws Exception {
    Logger log = Logger.getLogger(this.getClass());
    //Event ev = eventDao.find(evId);
    try {/*from  w  ww . j  a v a2 s  .  c o m*/

        HashSet<String> iepuids = new HashSet();
        for (IdealEntityParam iep : ieplist) {
            iepuids.add(iep.getBaseParam().getUid());
        }

        List<BaseParam> bpList = baseParamService.getParams();

        HashMap<Long, String> genMap = subModelService.getGenerationUrls();

        HSSFWorkbook workbook = new HSSFWorkbook();
        Event ev = eventDao.find(evId);
        HashMap<Long, SubModel> bodyMap = subModelService.getBodies();

        HSSFCellStyle style = workbook.createCellStyle();
        //style.setFillBackgroundColor(HSSFColor.ORANGE.index);
        style.setFillForegroundColor(HSSFColor.ORANGE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        HSSFSheet idealEntitySheet = workbook.createSheet("? ??");
        HSSFSheet chosenSheet = workbook.createSheet(" ?");
        HSSFSheet cutedSheet = workbook.createSheet(" ?");
        HSSFSheet moneySheet = workbook.createSheet("  ");
        HSSFSheet instChosenSheet = workbook.createSheet("");
        int complectList = 1;

        int ierownum = 1;
        idealEntitySheet.createRow(ierownum++).createCell(0)
                .setCellValue(": " + ev.getName() + "; " + ev.getId() + ";");
        idealEntitySheet.createRow(ierownum++).createCell(0)
                .setCellValue("?: " + ev.getAuthor() + ";");
        idealEntitySheet.createRow(ierownum++).createCell(0)
                .setCellValue(": " + ev.getAddDate() + ";");
        idealEntitySheet.createRow(ierownum++).createCell(0)
                .setCellValue(": " + ev.getScene().getName() + ";");
        idealEntitySheet.createRow(ierownum++).createCell(0)
                .setCellValue(": " + ev.getMoney() + ";");
        idealEntitySheet.createRow(ierownum++).createCell(0)
                .setCellValue(" ???: " + ev.getPerception().getName() + ";");
        idealEntitySheet.createRow(ierownum++).createCell(0)
                .setCellValue(": " + ev.getRadical() + "(" + ev.getColor() + ")" + ";");
        idealEntitySheet.createRow(ierownum++).createCell(0)
                .setCellValue("?: " + seq.getRadCore() + ";");

        HSSFRow ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("? A1: ");
        ierowhead.createCell(1).setCellValue(ev.getStrategyA1().getName());
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("? B1: ");
        ierowhead.createCell(1).setCellValue(ev.getStrategyB1().getName());
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("?? : ");
        ierowhead.createCell(1).setCellValue(ev.getResourceType().getName());
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("?? -: ");
        ierowhead.createCell(1).setCellValue(ev.getParamTox1().getName());
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("?? ?: ");
        ierowhead.createCell(1).setCellValue(ev.getValueTox1().getName());
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue(" ?: ");
        ierowhead.createCell(1).setCellValue(seq.getAllowance() + "%");
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("? A2: ");
        ierowhead.createCell(1).setCellValue(ev.getStrategyA2().getName());
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("? B2: ");
        ierowhead.createCell(1).setCellValue(ev.getStrategyB2().getName());
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("?? -, . ?: ");
        ierowhead.createCell(1).setCellValue(ev.getParamTox2().getName());
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("?? ?, . ?: ");
        ierowhead.createCell(1).setCellValue(ev.getValueTox2().getName());
        ierownum++;

        int phn = 1;
        HSSFRow paramsierowhead = idealEntitySheet.createRow(ierownum++);
        paramsierowhead.createCell(phn++).setCellValue("UID");
        paramsierowhead.createCell(phn++).setCellValue("?");
        paramsierowhead.createCell(phn++).setCellValue("?");
        paramsierowhead.createCell(phn++).setCellValue(" .");
        paramsierowhead.createCell(phn++).setCellValue("");
        paramsierowhead.createCell(phn++).setCellValue("?");
        paramsierowhead.createCell(phn++).setCellValue(" ?.");
        paramsierowhead.createCell(phn++).setCellValue("");

        int A = 0;
        int B = 0;
        for (IdealEntityParam iep : ieplist) {
            int pbn = 0;
            HSSFRow paramsierowbody = idealEntitySheet.createRow(ierownum++);
            paramsierowbody.createCell(pbn++).setCellValue(iep.getNumber());
            paramsierowbody.createCell(pbn++).setCellValue(iep.getBaseParam().getUid());
            paramsierowbody.createCell(pbn++).setCellValue(iep.getBaseParam().getName());
            paramsierowbody.createCell(pbn++).setCellValue(iep.getIepClass().getName());
            paramsierowbody.createCell(pbn++).setCellValue(iep.getAmin().doubleValue());
            paramsierowbody.createCell(pbn++).setCellValue(iep.getValueMin().doubleValue());
            paramsierowbody.createCell(pbn++).setCellValue(iep.getValueMax().doubleValue());
            paramsierowbody.createCell(pbn++).setCellValue(iep.getAmax().doubleValue());
            paramsierowbody.createCell(pbn++).setCellValue(StringAdapter.getString(iep.getRank()));
            if (Rank.A.equals(iep.getRank())) {
                A++;
            } else if (Rank.B.equals(iep.getRank())) {
                B++;
            }
        }
        ierownum++;
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("? -  ?:");
        ierowhead.createCell(1).setCellValue((double) A);
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("? -  B");
        ierowhead.createCell(1).setCellValue((double) B);
        ierownum++;
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(0).setCellValue("? :");
        ierowhead = idealEntitySheet.createRow(ierownum++);
        ierowhead.createCell(1).setCellValue("UID");
        ierowhead.createCell(2).setCellValue("?");
        for (SequenceValueRange svr : seq.getSequenceValueRanges()) {
            String uid = svr.getUid();

            if (!iepuids.contains(uid)) {
                ierowhead = idealEntitySheet.createRow(ierownum++);
                ierowhead.createCell(1).setCellValue(svr.getUid());
                ierowhead.createCell(2).setCellValue(baseParamService.getBaseParam(bpList, uid).getName());
            }
        }

        int rowheadNumCell = 0;
        HSSFRow rowhead = chosenSheet.createRow(0);
        rowhead.createCell(rowheadNumCell++).setCellValue("");
        rowhead.createCell(rowheadNumCell++).setCellValue("?");
        rowhead.createCell(rowheadNumCell++).setCellValue("");
        rowhead.createCell(rowheadNumCell++).setCellValue("?");
        rowhead.createCell(rowheadNumCell++).setCellValue("?");
        rowhead.createCell(rowheadNumCell++).setCellValue(" ?");
        rowhead.createCell(rowheadNumCell++).setCellValue("??");
        rowhead.createCell(rowheadNumCell++).setCellValue("?? ??");
        rowhead.createCell(rowheadNumCell++).setCellValue("? A");
        rowhead.createCell(rowheadNumCell++).setCellValue(" A");
        rowhead.createCell(rowheadNumCell++).setCellValue("? ? A ");
        rowhead.createCell(rowheadNumCell++).setCellValue("? B");
        rowhead.createCell(rowheadNumCell++).setCellValue(" ");
        rowhead.createCell(rowheadNumCell++).setCellValue("? ? B");
        rowhead.createCell(rowheadNumCell++).setCellValue("? ???");
        rowhead.createCell(rowheadNumCell++).setCellValue("? ?? ??");
        rowhead.createCell(rowheadNumCell++).setCellValue("? ?? ???");
        rowhead.createCell(rowheadNumCell++).setCellValue("? ?? ???");

        int numscell = 0;
        HSSFRow instrowhead = instChosenSheet.createRow(0);
        instrowhead.createCell(numscell++).setCellValue("");
        instrowhead.createCell(numscell++).setCellValue("?");
        instrowhead.createCell(numscell++).setCellValue("");
        instrowhead.createCell(numscell++).setCellValue("?");
        instrowhead.createCell(numscell++).setCellValue("?");
        instrowhead.createCell(numscell++).setCellValue(" ?");
        instrowhead.createCell(numscell++).setCellValue("??");
        instrowhead.createCell(numscell++).setCellValue("");
        instrowhead.createCell(numscell++).setCellValue("??");
        instrowhead.createCell(numscell++).setCellValue("??");
        instrowhead.createCell(numscell++).setCellValue("");
        instrowhead.createCell(numscell++).setCellValue("??");
        instrowhead.createCell(numscell++).setCellValue("??? 1");
        instrowhead.createCell(numscell++).setCellValue("??? 2");
        instrowhead.createCell(numscell++).setCellValue("? ???");
        instrowhead.createCell(numscell++).setCellValue("? ??");

        moneySheet.addMergedRegion(new CellRangeAddress(0, 0, 6, 13));
        moneySheet.addMergedRegion(new CellRangeAddress(0, 0, 14, 18));
        moneySheet.addMergedRegion(new CellRangeAddress(0, 0, 19, 26));
        moneySheet.addMergedRegion(new CellRangeAddress(0, 0, 27, 32));
        moneySheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
        moneySheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 1));
        moneySheet.addMergedRegion(new CellRangeAddress(0, 1, 2, 2));
        moneySheet.addMergedRegion(new CellRangeAddress(0, 1, 3, 3));
        moneySheet.addMergedRegion(new CellRangeAddress(0, 1, 4, 4));
        moneySheet.addMergedRegion(new CellRangeAddress(0, 1, 5, 5));
        HSSFRow firstRowMoneyHead = moneySheet.createRow(0);
        HSSFRow secondRowMoneyHead = moneySheet.createRow(1);

        int frn = 0;
        firstRowMoneyHead.createCell(frn++).setCellValue("");
        firstRowMoneyHead.createCell(frn++).setCellValue("?");
        firstRowMoneyHead.createCell(frn++).setCellValue("");
        firstRowMoneyHead.createCell(frn++).setCellValue("?");
        firstRowMoneyHead.createCell(frn++).setCellValue("?");
        firstRowMoneyHead.createCell(frn++).setCellValue(" ?");
        firstRowMoneyHead.createCell(frn++).setCellValue("??? I");
        firstRowMoneyHead.createCell(frn + 7).setCellValue("?? I");
        firstRowMoneyHead.createCell(frn + 12).setCellValue("??? II");
        firstRowMoneyHead.createCell(frn + 20).setCellValue("?? II");

        int srn = 6;
        secondRowMoneyHead.createCell(srn++)
                .setCellValue("- ?? ??? ?");
        secondRowMoneyHead.createCell(srn++)
                .setCellValue("- ?? ??? ");
        secondRowMoneyHead.createCell(srn++).setCellValue(" ?");
        secondRowMoneyHead.createCell(srn++)
                .setCellValue(" ?? ?? ??? ?");
        secondRowMoneyHead.createCell(srn++)
                .setCellValue(" ?? ?? ??? ");
        secondRowMoneyHead.createCell(srn++).setCellValue("?  ??");
        secondRowMoneyHead.createCell(srn++).setCellValue("?  ?");
        secondRowMoneyHead.createCell(srn++).setCellValue("? ??");
        secondRowMoneyHead.createCell(srn++).setCellValue("? ?? ");
        secondRowMoneyHead.createCell(srn++).setCellValue("? ?? ???");
        secondRowMoneyHead.createCell(srn++).setCellValue("- ?? ");
        secondRowMoneyHead.createCell(srn++).setCellValue("");
        secondRowMoneyHead.createCell(srn++).setCellValue("? ?? ?");
        secondRowMoneyHead.createCell(srn++)
                .setCellValue("- ?? ??? ?");
        secondRowMoneyHead.createCell(srn++)
                .setCellValue("- ?? ??? ");
        secondRowMoneyHead.createCell(srn++).setCellValue(" ?");
        secondRowMoneyHead.createCell(srn++)
                .setCellValue(" ?? ?? ??? ?");
        secondRowMoneyHead.createCell(srn++)
                .setCellValue(" ?? ?? ??? ");
        secondRowMoneyHead.createCell(srn++).setCellValue("?  ??");
        secondRowMoneyHead.createCell(srn++).setCellValue("?  ?");
        secondRowMoneyHead.createCell(srn++).setCellValue("? ??");
        secondRowMoneyHead.createCell(srn++).setCellValue("? ?? ");
        secondRowMoneyHead.createCell(srn++).setCellValue("? ?? ???");
        secondRowMoneyHead.createCell(srn++).setCellValue("- ?? ");
        secondRowMoneyHead.createCell(srn++).setCellValue("");
        secondRowMoneyHead.createCell(srn++).setCellValue("? ?? ?");

        int n = 1;
        int optrownum = 1;
        if (!carList.isEmpty()) {
            //while (optrownum < 50000) {
            for (EntityCar car : carList) {
                if (optrownum > 60000) {
                    instChosenSheet = workbook.createSheet(" " + complectList++);
                    optrownum = 1;
                    numscell = 0;
                    instrowhead = instChosenSheet.createRow(0);
                    instrowhead.createCell(numscell++).setCellValue("");
                    instrowhead.createCell(numscell++).setCellValue("?");
                    instrowhead.createCell(numscell++).setCellValue("");
                    instrowhead.createCell(numscell++).setCellValue("?");
                    instrowhead.createCell(numscell++).setCellValue("?");
                    instrowhead.createCell(numscell++).setCellValue(" ?");
                    instrowhead.createCell(numscell++).setCellValue("??");
                    instrowhead.createCell(numscell++).setCellValue("");
                    instrowhead.createCell(numscell++).setCellValue("??");
                    instrowhead.createCell(numscell++).setCellValue("??");
                    instrowhead.createCell(numscell++).setCellValue("");
                    instrowhead.createCell(numscell++).setCellValue("??");
                    instrowhead.createCell(numscell++).setCellValue("??? 1");
                    instrowhead.createCell(numscell++).setCellValue("??? 2");
                    instrowhead.createCell(numscell++).setCellValue("? ???");
                    instrowhead.createCell(numscell++).setCellValue("? ??");
                }

                Car realCar = car.car;

                SubModel sm = bodyMap.get(car.car.getCmsqId());
                String body = "";
                if (sm != null) {
                    body = sm.getBody();
                }

                int m = n + 1;
                int bpropsCount = 0;

                int cn = 0;
                HSSFRow carRow = instChosenSheet.createRow(optrownum);
                carRow.createCell(cn++).setCellValue(StringAdapter.getString(car.car.getCarId()));
                carRow.createCell(cn++).setCellValue(StringAdapter.getString(car.getMarkTitle()));
                carRow.createCell(cn++).setCellValue(StringAdapter.getString(car.getModelTitle()));
                carRow.createCell(cn++).setCellValue(StringAdapter.getString(car.car.getCompletionTitle()));
                carRow.createCell(cn++).setCellValue(StringAdapter.getString(car.getCarTitle()));
                carRow.createCell(cn++).setCellValue(StringAdapter.getString(body));
                carRow.createCell(cn++).setCellValue(car.fullPrice.doubleValue());
                carRow.createCell(cn++).setCellValue("");

                carRow.createCell(cn + 6).setCellValue(car.dinamicRateA.add(car.dinamicRateB).doubleValue());
                optrownum++;

                /*carRow.createCell(3).setCellValue(renderDecimalNoPoint(car.basePrice).replace(".", ","));
                 carRow.createCell(6).setCellValue(StringAdapter.getString(car.staticRate).replace(".", ","));
                 carRow.createCell(7).setCellValue(StringAdapter.getString(car.staticRate.add(car.dinamicRate)).replace(".", ","));*/

                for (String uid : car.aprops.keySet()) {
                    EntityPropertyHolder eph = car.aprops.get(uid);

                    boolean alternatives = false;
                    List<EntityProperty> insttalledElems = eph.getActiveProperty();

                    if (insttalledElems.size() > 1) {
                        alternatives = true;
                    }

                    for (EntityProperty ep : insttalledElems) {
                        HSSFRow optRow = instChosenSheet.createRow(optrownum);
                        int on = 0;
                        optRow.createCell(on++).setCellValue(StringAdapter.getString(car.car.getCarId()));
                        optRow.createCell(on++).setCellValue(StringAdapter.getString(car.getMarkTitle()));
                        optRow.createCell(on++).setCellValue(StringAdapter.getString(car.getModelTitle()));
                        optRow.createCell(on++)
                                .setCellValue(StringAdapter.getString(car.car.getCompletionTitle()));
                        optRow.createCell(on++).setCellValue(StringAdapter.getString(car.getCarTitle()));
                        optRow.createCell(on++).setCellValue(body);
                        //optRow.createCell(on++).setCellValue(RenderSupport.renderDecimalNoPoint(ep.getPrice()).replace(".", ","));
                        optRow.createCell(on++).setCellValue(" - ");
                        HSSFCell uidCell = optRow.createCell(on++);
                        uidCell.setCellValue(uid);
                        if (alternatives) {
                            uidCell.setCellStyle(style);
                        }
                        optRow.createCell(on++).setCellValue("A");
                        optRow.createCell(on++).setCellValue(ep.sign);
                        optRow.createCell(on++).setCellValue(ep.type.getName());
                        optRow.createCell(on++).setCellValue(ep.name);
                        optRow.createCell(on++).setCellValue(ep.title);
                        optRow.createCell(on++).setCellValue(ep.value.doubleValue());
                        optRow.createCell(on++).setCellValue(eph.dinamicRate.doubleValue());
                        optrownum++;

                        /*optRow.createCell(1).setCellValue("A");
                         optRow.createCell(2).setCellValue(ep.type.getName());
                         optRow.createCell(3).setCellValue(ep.name);
                         optRow.createCell(4).setCellValue(ep.title);
                         optRow.createCell(5).setCellValue(StringAdapter.getString(ep.value).replace(".", ","));
                         optRow.createCell(6).setCellValue(StringAdapter.getString(eph.dinamicRate).replace(".", ","));
                         optRow.createCell(7).setCellValue(StringAdapter.getString(eph.staticRate).replace(".", ","));*/
                    }
                }

                for (String uid : car.bprops.keySet()) {
                    EntityPropertyHolder eph = car.bprops.get(uid);

                    boolean alternatives = false;
                    List<EntityProperty> insttalledElems = eph.getActiveProperty();

                    if (insttalledElems.size() > 1) {
                        alternatives = true;
                    }

                    if (!insttalledElems.isEmpty()) {
                        bpropsCount++;
                        for (EntityProperty ep : eph.getActiveProperty()) {
                            HSSFRow optRow = instChosenSheet.createRow(optrownum);
                            int on = 0;
                            optRow.createCell(on++).setCellValue(StringAdapter.getString(car.car.getCarId()));
                            optRow.createCell(on++).setCellValue(StringAdapter.getString(car.getMarkTitle()));
                            optRow.createCell(on++).setCellValue(StringAdapter.getString(car.getModelTitle()));
                            optRow.createCell(on++)
                                    .setCellValue(StringAdapter.getString(car.car.getCompletionTitle()));
                            optRow.createCell(on++).setCellValue(StringAdapter.getString(car.getCarTitle()));
                            optRow.createCell(on++).setCellValue(StringAdapter.getString(body));
                            //optRow.createCell(on++).setCellValue(RenderSupport.renderDecimalNoPoint(ep.getPrice()).replace(".", ","));
                            //optRow.createCell(on++).setCellValue(RenderSupport.renderDecimalNoPoint(ep.price));
                            optRow.createCell(on++).setCellValue(" - ");
                            HSSFCell uidCell = optRow.createCell(on++);
                            uidCell.setCellValue(uid);
                            if (alternatives) {
                                uidCell.setCellStyle(style);
                            }
                            optRow.createCell(on++).setCellValue("B");
                            optRow.createCell(on++).setCellValue(ep.sign);
                            optRow.createCell(on++).setCellValue(ep.type.getName());
                            optRow.createCell(on++).setCellValue(ep.name);
                            optRow.createCell(on++).setCellValue(ep.title);
                            optRow.createCell(on++).setCellValue(ep.value.doubleValue());
                            optRow.createCell(on++).setCellValue(eph.dinamicRate.doubleValue());
                            optrownum++;

                            /*HSSFRow optRow = instChosenSheet.createRow((short) optrownum);
                             HSSFCell uidCell = optRow.createCell(0);
                             uidCell.setCellValue(uid);
                             if(alternatives){
                             //optRow.createCell(8).setCellValue("");
                             uidCell.setCellStyle(style);
                             }
                             optRow.createCell(1).setCellValue("B");
                             optRow.createCell(2).setCellValue(ep.type.getName());
                             optRow.createCell(3).setCellValue(ep.name);
                             optRow.createCell(4).setCellValue(ep.title);
                             optRow.createCell(5).setCellValue(StringAdapter.getString(ep.value).replace(".", ","));
                             optRow.createCell(6).setCellValue(StringAdapter.getString(eph.dinamicRate).replace(".", ","));
                             optRow.createCell(7).setCellValue(StringAdapter.getString(eph.staticRate).replace(".", ","));
                             optrownum++;*/
                        }
                    } else {
                        BaseParam bp = baseParamService.getBaseParam(uid);
                        HSSFRow optRow = instChosenSheet.createRow(optrownum);
                        int on = 0;
                        optRow.createCell(on++).setCellValue(StringAdapter.getString(car.car.getCarId()));
                        optRow.createCell(on++).setCellValue(StringAdapter.getString(car.getMarkTitle()));
                        optRow.createCell(on++).setCellValue(StringAdapter.getString(car.getModelTitle()));
                        optRow.createCell(on++)
                                .setCellValue(StringAdapter.getString(car.car.getCompletionTitle()));
                        optRow.createCell(on++).setCellValue(StringAdapter.getString(car.getCarTitle()));
                        optRow.createCell(on++).setCellValue(StringAdapter.getString(body));
                        //optRow.createCell(on++).setCellValue(RenderSupport.renderDecimalNoPoint(ep.getPrice()).replace(".", ","));
                        optRow.createCell(on++).setCellValue(" - ");
                        HSSFCell uidCell = optRow.createCell(on++);
                        uidCell.setCellValue(uid);
                        optRow.createCell(on++).setCellValue("B");
                        optRow.createCell(on++).setCellValue(" - ");
                        optRow.createCell(on++).setCellValue(" - ");
                        optRow.createCell(on++).setCellValue(bp.getName());
                        optRow.createCell(on++).setCellValue(" - ");
                        optRow.createCell(on++).setCellValue("null");
                        optRow.createCell(on++).setCellValue(" - ");
                        optrownum++;
                    }
                }

                /*String aRate = " - ";
                if(car.dinamicRateA.compareTo(BigDecimal.valueOf(0))>0){
                aRate = StringAdapter.getString(car.dinamicRateA).replace(".", ",");
                }
                String acount = " - ";
                if(car.aprops.keySet().size()>0){
                acount = StringAdapter.getString(car.aprops.keySet().size());
                }*/
                String msA = " - ";
                BigDecimal medA = BigDecimal.valueOf(0);
                if (car.aprops.keySet().size() > 0) {
                    medA = car.dinamicRateA.divide(BigDecimal.valueOf(car.aprops.keySet().size()), 2,
                            RoundingMode.HALF_UP);
                    msA = StringAdapter.getString(medA).replace(".", ",");
                }

                /* String bRate = " - ";
                 if(car.dinamicRateB.compareTo(BigDecimal.valueOf(0))>0){
                bRate = StringAdapter.getString(car.dinamicRateB).replace(".", ",");
                 }*/
                String bcount = " - ";
                if (bpropsCount > 0) {
                    bcount = StringAdapter.getString(bpropsCount);
                }
                String msB = " - ";
                BigDecimal medB = BigDecimal.valueOf(0);
                if (bpropsCount > 0) {
                    medB = car.dinamicRateB.divide(BigDecimal.valueOf(bpropsCount), 2, RoundingMode.HALF_UP);
                    msB = StringAdapter.getString(medB).replace(".", ",");
                }

                /*String bsr = " - ";
                if(car.baseStaticRate2.compareTo(BigDecimal.valueOf(0))>0){
                bsr = StringAdapter.getString(car.baseStaticRate2).replace(".", ",");
                }
                String fsr = " - ";
                if(car.freeStaticRate2.compareTo(BigDecimal.valueOf(0))>0){
                fsr = StringAdapter.getString(car.freeStaticRate2).replace(".", ",");
                }
                String msr = " - ";
                if(car.monetaryStaticRate2.compareTo(BigDecimal.valueOf(0))>0){
                msr = StringAdapter.getString(car.monetaryStaticRate2).replace(".", ",");
                }*/

                Model model = realCar.getModel();

                HSSFRow rowbody = chosenSheet.createRow(n);
                int rowbodynum = 0;
                rowbody.createCell(rowbodynum++).setCellValue(StringAdapter.getString(car.car.getCarId()));
                rowbody.createCell(rowbodynum++).setCellValue(StringAdapter.getString(car.getMarkTitle()));
                rowbody.createCell(rowbodynum++).setCellValue(StringAdapter.getString(car.getModelTitle()));
                rowbody.createCell(rowbodynum++)
                        .setCellValue(StringAdapter.getString(car.car.getCompletionTitle()));
                HSSFCell nameCellWithLink = rowbody.createCell(rowbodynum++);
                nameCellWithLink.setCellValue(StringAdapter.getString(car.getCarTitle()));
                HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
                link.setAddress("http://quto.ru/" + model.getMark().getUrl() + "/" + model.getUrl() + "/"
                        + genMap.get(realCar.getCmgqId()) + "/" + bodyMap.get(realCar.getCmsqId()).getUrl()
                        + "/" + realCar.getUrl());
                nameCellWithLink.setHyperlink(link);
                rowbody.createCell(rowbodynum++).setCellValue(StringAdapter.getString(body));
                rowbody.createCell(rowbodynum++).setCellValue(car.basePrice.doubleValue());
                rowbody.createCell(rowbodynum++).setCellValue(car.fullPrice.doubleValue());
                rowbody.createCell(rowbodynum++).setCellValue(car.dinamicRateA.doubleValue());
                rowbody.createCell(rowbodynum++).setCellValue((double) car.aprops.keySet().size());
                rowbody.createCell(rowbodynum++).setCellValue(medA.doubleValue());
                rowbody.createCell(rowbodynum++).setCellValue(car.dinamicRateB.doubleValue());
                rowbody.createCell(rowbodynum++).setCellValue((double) bpropsCount);
                rowbody.createCell(rowbodynum++).setCellValue(medB.doubleValue());
                rowbody.createCell(rowbodynum++).setCellValue(medA.add(medB).doubleValue());
                rowbody.createCell(rowbodynum++).setCellValue(car.baseStaticRate2.doubleValue());
                rowbody.createCell(rowbodynum++).setCellValue(car.freeStaticRate2.doubleValue());
                rowbody.createCell(rowbodynum++).setCellValue(car.monetaryStaticRate2.doubleValue());

                int rmbn = 0;
                HSSFRow rowMoneyBody = moneySheet.createRow(m);
                rowMoneyBody.createCell(rmbn++).setCellValue(StringAdapter.getString(car.car.getId()));
                rowMoneyBody.createCell(rmbn++).setCellValue(StringAdapter.getString(car.getMarkTitle()));
                rowMoneyBody.createCell(rmbn++).setCellValue(StringAdapter.getString(car.getModelTitle()));
                rowMoneyBody.createCell(rmbn++)
                        .setCellValue(StringAdapter.getString(car.car.getCompletionTitle()));
                rowMoneyBody.createCell(rmbn++).setCellValue(StringAdapter.getString(car.getCarTitle()));
                rowMoneyBody.createCell(rmbn++).setCellValue(StringAdapter.getString(body));
                rowMoneyBody.createCell(rmbn++).setCellValue((double) car.aprops.keySet().size());
                rowMoneyBody.createCell(rmbn++).setCellValue((double) bpropsCount);
                rowMoneyBody.createCell(rmbn++).setCellValue(car.basePrice.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.aFund1.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.bFund1.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.aFund1.add(car.bFund1).doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(
                        ev.getMoney().subtract(car.aFund1.add(car.bFund1).add(car.basePrice)).doubleValue());
                rowMoneyBody.createCell(rmbn++)
                        .setCellValue(car.dinamicRateA.add(car.dinamicRateB).doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.baseStaticRate1.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.freeStaticRate1.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.payStaticCount1.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.staticFund1.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.monetaryStaticRate1.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue((double) car.aCount2);
                rowMoneyBody.createCell(rmbn++).setCellValue((double) car.bCount2);
                rowMoneyBody.createCell(rmbn++).setCellValue(car.basePrice.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.aFund2.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.bFund2.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.aFund2.add(car.bFund2).doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(
                        ev.getMoney().subtract(car.aFund2.add(car.bFund2).add(car.basePrice)).doubleValue());
                rowMoneyBody.createCell(rmbn++)
                        .setCellValue(car.dinamicRateA.add(car.dinamicRateB).doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.baseStaticRate2.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.freeStaticRate2.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.payStaticCount2.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.staticFund2.doubleValue());
                rowMoneyBody.createCell(rmbn++).setCellValue(car.monetaryStaticRate2.doubleValue());
                n++;

                HSSFRow carStaticRowHead = instChosenSheet.createRow(optrownum);
                int csn = 0;
                carStaticRowHead.createCell(csn++).setCellValue(StringAdapter.getString(car.car.getCarId()));
                carStaticRowHead.createCell(csn++).setCellValue(StringAdapter.getString(car.getMarkTitle()));
                carStaticRowHead.createCell(csn++).setCellValue(StringAdapter.getString(car.getModelTitle()));
                carStaticRowHead.createCell(csn++)
                        .setCellValue(StringAdapter.getString(car.car.getCompletionTitle()));
                carStaticRowHead.createCell(csn++).setCellValue(StringAdapter.getString(car.getCarTitle()));
                carStaticRowHead.createCell(csn++).setCellValue(StringAdapter.getString(body));
                //carStaticRowHead.createCell(3).setCellValue(RenderSupport.renderDecimalNoPoint(ep.getPrice()));
                carStaticRowHead.createCell(csn++).setCellValue(":");
                carStaticRowHead.createCell(csn + 7).setCellValue(car.staticRate.doubleValue());
                optrownum++;

                Map<String, List<EntityProperty>> StaticMap = car.staticProps;
                for (String uid : StaticMap.keySet()) {
                    List<EntityProperty> insttalledElems = StaticMap.get(uid);
                    if (insttalledElems != null && !insttalledElems.isEmpty()) {
                        boolean alternatives = false;

                        if (insttalledElems.size() > 1) {
                            alternatives = true;
                        }

                        for (EntityProperty ep : insttalledElems) {

                            String title = ep.title;
                            if (!ep.description.trim().equals("")) {
                                title += " - " + ep.description;
                            }

                            HSSFRow carStaticRow = instChosenSheet.createRow(optrownum);
                            int cson = 0;
                            carStaticRow.createCell(cson++)
                                    .setCellValue(StringAdapter.getString(car.car.getCarId()));
                            carStaticRow.createCell(cson++)
                                    .setCellValue(StringAdapter.getString(car.getMarkTitle()));
                            carStaticRow.createCell(cson++)
                                    .setCellValue(StringAdapter.getString(car.getModelTitle()));
                            carStaticRow.createCell(cson++)
                                    .setCellValue(StringAdapter.getString(car.car.getCompletionTitle()));
                            carStaticRow.createCell(cson++)
                                    .setCellValue(StringAdapter.getString(car.getCarTitle()));
                            carStaticRow.createCell(cson++).setCellValue(StringAdapter.getString(body));
                            //carStaticRow.createCell(cson++).setCellValue(StringAdapter.getString(ep.getPrice()).replace(".", ","));
                            carStaticRow.createCell(cson++).setCellValue(" - ");

                            HSSFCell uidCell = carStaticRow.createCell(cson++);
                            uidCell.setCellValue(uid);
                            if (alternatives) {
                                uidCell.setCellStyle(style);
                            }
                            //carStaticRow.createCell(5).setCellValue(uid);

                            carStaticRow.createCell(cson++).setCellValue("S");
                            carStaticRow.createCell(cson++).setCellValue(ep.sign);
                            carStaticRow.createCell(cson++).setCellValue(ep.type.getName());
                            carStaticRow.createCell(cson++).setCellValue(ep.name);
                            carStaticRow.createCell(cson++).setCellValue(title);
                            carStaticRow.createCell(cson++).setCellValue(ep.radicalValue);
                            carStaticRow.createCell(cson + 1).setCellValue(ep.value.doubleValue());

                            /*carStaticRow.createCell(1).setCellValue(ep.name);
                             carStaticRow.createCell(2).setCellValue(ep.title);
                             carStaticRow.createCell(3).setCellValue(ep.type.getName());
                                    
                             carStaticRow.createCell(5).setCellValue(StringAdapter.getString(ep.value).replace(".", ","));*/
                            optrownum++;
                        }
                    }
                }
                /*break;*/
            }
        }
        int k = 0;
        HSSFRow rowhead20 = cutedSheet.createRow(k++);
        HSSFRow rowhead21 = cutedSheet.createRow(k++);
        HSSFRow rowhead22 = cutedSheet.createRow(k++);
        int ccn = 0;
        rowhead20.createCell(0).setCellValue("UID ??");
        rowhead21.createCell(ccn++).setCellValue("");
        rowhead21.createCell(ccn++).setCellValue("?");
        rowhead21.createCell(ccn++).setCellValue("");
        rowhead21.createCell(ccn++).setCellValue("?");
        rowhead21.createCell(ccn++).setCellValue("?");
        rowhead21.createCell(ccn++).setCellValue(" ?");
        rowhead22.createCell(0).setCellValue(" ???");

        int cutoptrownum = 0;
        for (IdealEntityParam iep : ieplist) {
            rowhead20.createCell(ccn).setCellValue(StringAdapter.getString(iep.baseParam.getUid()));
            rowhead21.createCell(ccn).setCellValue(iep.number + "." + iep.baseParam.getName());
            rowhead22.createCell(ccn++).setCellValue(iep.aimBefore.doubleValue());
        }
        if (!cutCarList.isEmpty()) {
            for (EntityCar car : cutCarList) {
                SubModel sm = bodyMap.get(car.car.getCmsqId());
                String body = "";
                if (sm != null) {
                    body = sm.getBody();
                }
                HSSFRow rowbody = cutedSheet.createRow(k++);
                int con = 0;
                rowbody.createCell(con++).setCellValue(StringAdapter.getString(car.car.getCarId()));
                rowbody.createCell(con++).setCellValue(StringAdapter.getString(car.getMarkTitle()));
                rowbody.createCell(con++).setCellValue(StringAdapter.getString(car.getModelTitle()));
                rowbody.createCell(con++).setCellValue(StringAdapter.getString(car.car.getCompletionTitle()));
                rowbody.createCell(con++).setCellValue(StringAdapter.getString(car.getCarTitle()));
                rowbody.createCell(con).setCellValue(body);

                int num = 0;
                if (car.cutNum != null) {
                    num = car.cutNum;
                }
                String cutValue = car.cutVal;
                if (cutValue == null || cutValue.equals("null")) {
                    cutValue = "?     ";
                }

                try {
                    Double cutedValue = Double.valueOf(car.cutVal);
                    rowbody.createCell(con + num).setCellValue(cutedValue);
                } catch (Exception e) {
                    rowbody.createCell(con + num).setCellValue(cutValue.replace(".", ","));
                }

                /*HSSFRow carRow = instCutedSheet.createRow(cutoptrownum);
                carRow.createCell(0).setCellValue(StringAdapter.getString(car.car.getCarId()));
                carRow.createCell(1).setCellValue(StringAdapter.getString(car.getMarkTitle()));
                carRow.createCell(2).setCellValue(StringAdapter.getString(car.getModelTitle()));
                carRow.createCell(3).setCellValue(StringAdapter.getString(car.getCarTitle()));
                carRow.createCell(4).setCellValue(RenderSupport.renderDecimalNoPoint(car.basePrice).replace(".", ","));
                carRow.createCell(5).setCellValue(RenderSupport.renderDecimalNoPoint(car.fixPrice).replace(".", ","));
                carRow.createCell(6).setCellValue(StringAdapter.getString(car.dinamicRateA.add(car.dinamicRateB)).replace(".", ","));
                carRow.createCell(7).setCellValue(StringAdapter.getString(car.staticRate).replace(".", ","));
                carRow.createCell(8).setCellValue(StringAdapter.getString(car.staticRate.add(car.dinamicRateA.add(car.dinamicRateB))).replace(".", ","));
                cutoptrownum++;
                HSSFRow carRowHead = instCutedSheet.createRow(cutoptrownum);
                carRowHead.createCell(0).setCellValue(StringAdapter.getString(""));
                carRowHead.createCell(1).setCellValue(StringAdapter.getString(""));
                carRowHead.createCell(2).setCellValue(StringAdapter.getString("??"));
                carRowHead.createCell(3).setCellValue(StringAdapter.getString("?????"));
                carRowHead.createCell(4).setCellValue(StringAdapter.getString("???"));
                carRowHead.createCell(5).setCellValue(StringAdapter.getString("%"));
                carRowHead.createCell(6).setCellValue(StringAdapter.getString("??"));
                cutoptrownum++;*/
                /*for (PropertyName pn : car.car.getPropertyNames()) {
                 CarProperty p = pn.getCarProperty();
                 if (p != null) {
                 HSSFRow optRow = instCutedSheet.createRow((short) cutoptrownum);
                 if (p.getUid() != null) {
                 optRow.createCell(0).setCellValue(p.getUid());
                 } else {
                 optRow.createCell(0).setCellValue("? ");
                 }
                        
                 optRow.createCell(1).setCellValue("?");
                 if (p.getTitle() != null) {
                 optRow.createCell(2).setCellValue(p.getTitle());
                 } else {
                 optRow.createCell(2).setCellValue("? ");
                 }
                 if (pn.getPropertyNameValue() != null && !pn.getPropertyNameValue().equals("")) {
                 optRow.createCell(3).setCellValue(pn.getPropertyNameValue());
                 } else {
                 optRow.createCell(3).setCellValue("? ");
                 }
                 if (pn.getParamValue() != null && !pn.getParamValue().equals("")) {
                 optRow.createCell(4).setCellValue(pn.getParamValue());
                 } else {
                 optRow.createCell(4).setCellValue("? ");
                 }
                 if (pn.getPercentValue() != null && !pn.getPercentValue().equals("")) {
                 optRow.createCell(5).setCellValue(pn.getPercentValue());
                 } else {
                 optRow.createCell(5).setCellValue("? ");
                 }
                 if (pn.getRadical() != null && !pn.getRadical().equals("")) {
                 optRow.createCell(6).setCellValue(pn.getRadical());
                 } else {
                 optRow.createCell(6).setCellValue("? ");
                 }
                 cutoptrownum++;
                 }
                 }
                 List<Feature> flist = carService.getFeatures(car.car);
                 for (Feature f : flist) {
                 HSSFRow optRow = instCutedSheet.createRow((short) cutoptrownum);
                 if (f.getUid() != null) {
                 optRow.createCell(0).setCellValue(f.getUid());
                 } else {
                 optRow.createCell(0).setCellValue("? ");
                 }
                 optRow.createCell(1).setCellValue("??");
                 optRow.createCell(2).setCellValue("");
                 if (f.getTitle() != null) {
                 optRow.createCell(3).setCellValue(f.getTitle());
                 } else {
                 optRow.createCell(3).setCellValue("? ");
                 }
                 if (f.getParamValue() != null) {
                 optRow.createCell(4).setCellValue(f.getParamValue());
                 } else {
                 optRow.createCell(4).setCellValue("? ");
                 }
                 if (f.getPercentValue() != null) {
                 optRow.createCell(5).setCellValue(f.getPercentValue());
                 } else {
                 optRow.createCell(5).setCellValue("? ");
                 }
                 if (f.getRadical() != null) {
                 optRow.createCell(6).setCellValue(f.getRadical());
                 } else {
                 optRow.createCell(6).setCellValue("? ");
                 }
                 cutoptrownum++;
                 }*/
                /*for (CarOptionValue cov : car.car.getCarOptionValues()) {
                 CarCompletionOption cco = cov.getCCO();
                 if (cco != null) {
                 HSSFRow optRow = instCutedSheet.createRow((short) cutoptrownum);
                 if (cco.getUid() != null) {
                 optRow.createCell(0).setCellValue(cco.getUid());
                 } else {
                 optRow.createCell(0).setCellValue("? ");
                 }
                        
                 optRow.createCell(1).setCellValue("?");
                 if (cco.getTitle() != null) {
                 optRow.createCell(2).setCellValue(cco.getTitle());
                 } else {
                 optRow.createCell(2).setCellValue("? ");
                 }
                 if (cov.getTitle() != null) {
                 optRow.createCell(3).setCellValue(cov.getTitle());
                 } else {
                 optRow.createCell(3).setCellValue("? ");
                 }
                 if (cco.getParamValue() != null) {
                 optRow.createCell(4).setCellValue(cco.getParamValue());
                 } else {
                 optRow.createCell(4).setCellValue("? ");
                 }
                 if (cco.getPercentValue() != null) {
                 optRow.createCell(5).setCellValue(cco.getPercentValue());
                 } else {
                 optRow.createCell(5).setCellValue("? ");
                 }
                 if (cco.getRadical() != null) {
                 optRow.createCell(6).setCellValue(cco.getRadical());
                 } else {
                 optRow.createCell(6).setCellValue("? ");
                 }
                        
                 cutoptrownum++;
                 }
                 }
                 for (CarColorValue ccv : car.car.getCarColorValues()) {
                 Color col = ccv.getColor();
                 if (col != null) {
                 HSSFRow optRow = instCutedSheet.createRow((short) cutoptrownum);
                 if (col.getUid() != null) {
                 optRow.createCell(0).setCellValue(col.getUid());
                 } else {
                 optRow.createCell(0).setCellValue("? ");
                 }
                        
                 optRow.createCell(1).setCellValue("");
                 if (col.getTitle() != null) {
                 optRow.createCell(2).setCellValue(col.getTitle());
                 } else {
                 optRow.createCell(2).setCellValue("? ");
                 }
                 if (col.getName() != null) {
                 optRow.createCell(3).setCellValue(col.getName());
                 } else {
                 optRow.createCell(3).setCellValue("? ");
                 }
                 if (col.getParamValue() != null) {
                 optRow.createCell(4).setCellValue(col.getParamValue());
                 } else {
                 optRow.createCell(4).setCellValue("? ");
                 }
                 if (col.getPercentValue() != null) {
                 optRow.createCell(5).setCellValue(col.getPercentValue());
                 } else {
                 optRow.createCell(5).setCellValue("? ");
                 }
                 if (col.getRadical() != null) {
                 optRow.createCell(6).setCellValue(col.getRadical());
                 } else {
                 optRow.createCell(6).setCellValue("? ");
                 }
                        
                 cutoptrownum++;
                 }
                 }*/
                /*for(String uid:car.aprops.keySet()){
                 for(EntityProperty ep:car.aprops.get(uid).getPropList()){
                 HSSFRow optRow = instCutedSheet.createRow((short) cutoptrownum);
                 optRow.createCell(0).setCellValue(uid);
                 optRow.createCell(1).setCellValue(ep.name);
                 optRow.createCell(2).setCellValue(ep.title);
                 optRow.createCell(3).setCellValue(ep.type.getName());
                 optRow.createCell(4).setCellValue(StringAdapter.getString(ep.value));
                 cutoptrownum++;
                 }
                 }
                 for(String uid:car.bprops.keySet()){
                 for(EntityProperty ep:car.bprops.get(uid).getPropList()){
                 HSSFRow optRow = instCutedSheet.createRow((short) cutoptrownum);
                 optRow.createCell(0).setCellValue(uid);
                 optRow.createCell(1).setCellValue(ep.name);
                 optRow.createCell(2).setCellValue(ep.title);
                 optRow.createCell(3).setCellValue(ep.type.getName());
                 optRow.createCell(4).setCellValue(StringAdapter.getString(ep.value));
                 cutoptrownum++;
                 }
                 }*/
            }
        }
        File f = new File("/usr/local/etc/xls/" + evId + ".xls");
        if (f.exists()) {
            f.delete();
        }
        workbook.write(new FileOutputStream("/usr/local/etc/xls/" + evId + ".xls"));
    } catch (Exception e) {
        //log.warn("HSSFWorkbook.getXls()", e);
        throw new Exception(e);
    }
}

From source file:org.kuali.coeus.common.budget.impl.calculator.SalaryCalculator.java

private ScaleTwoDecimal getPrevSalaryBase(BudgetPerson budgetPerson, Boundary boundary) {
    Date p1StartDate = budget.getBudgetPeriods().get(0).getStartDate();
    BudgetPerson newBudgetPerson = budgetPerson;
    for (BudgetPerson budgetPerson1 : budget.getBudgetPersons()) {
        if (((budgetPerson1.getPersonId() != null
                && budgetPerson1.getPersonId().equals(budgetPerson.getPersonId()))
                || (budgetPerson1.getRolodexId() != null
                        && budgetPerson1.getRolodexId().equals(budgetPerson.getRolodexId()))
                || (budgetPerson1.getTbnId() != null
                        && budgetPerson1.getTbnId().equals(budgetPerson.getTbnId())))
                && !budgetPerson1.getPersonSequenceNumber().equals(newBudgetPerson.getPersonSequenceNumber())
                && budgetPerson1.getJobCode() != null
                && budgetPerson1.getJobCode().equals(newBudgetPerson.getJobCode())
                && budgetPerson1.getEffectiveDate().after(newBudgetPerson.getEffectiveDate())
                && budgetPerson1.getEffectiveDate().compareTo(boundary.getStartDate()) <= 0) {
            newBudgetPerson = budgetPerson1;
        }/* www .  j a v  a2 s  . c o m*/
    }
    BigDecimal calBase = newBudgetPerson.getCalculationBase().bigDecimalValue();
    if (budgetPerson.getEffectiveDate().before(p1StartDate)) {
        p1StartDate = budgetPerson.getEffectiveDate();
    }
    QueryList<BudgetRate> qlist = filterInflationRates(p1StartDate, startDate);
    for (BudgetRate budgetProposalrate : qlist) {
        if (budgetProposalrate.getStartDate().after(budgetPerson.getEffectiveDate())
                && budgetProposalrate.getStartDate().before(startDate)) {
            calBase = calBase.add(calBase.multiply(budgetProposalrate.getApplicableRate().bigDecimalValue())
                    .divide(new ScaleTwoDecimal(100.00).bigDecimalValue(), RoundingMode.HALF_UP));
        }
    }
    return new ScaleTwoDecimal(calBase);

}

From source file:net.tradelib.misc.StrategyText.java

static private String formatOrderPrice(BigDecimal bd) {
    bd = bd.setScale(7, RoundingMode.HALF_UP).stripTrailingZeros();
    int scale = bd.scale() <= 2 ? 2 : bd.scale();
    return String.format("%." + Integer.toString(scale) + "f", bd);
}

From source file:org.egov.works.web.actions.measurementbook.MeasurementBookAction.java

private BigDecimal getAmountsForCurrentMB(final List<MBDetails> mbDetailsList, final double negoPerc,
        final String tenderType) {

    BigDecimal currentMBTenderedAmt = BigDecimal.ZERO;
    BigDecimal currMBAmount = BigDecimal.ZERO;
    BigDecimal tenderedMBAmount = BigDecimal.ZERO;
    BigDecimal currMBTotal = BigDecimal.ZERO;

    if (tenderType.equalsIgnoreCase(WorksConstants.PERC_TENDER)) {
        for (final MBDetails mbd : mbDetailsList)
            if (mbd.getWorkOrderActivity().getActivity().getRevisionType() == null)
                currentMBTenderedAmt = currentMBTenderedAmt.add(BigDecimal.valueOf(mbd.getAmount()));
        currMBAmount = mbHeader.getTotalMBAmount();

        // applying percentage on tendered items
        if (currentMBTenderedAmt != null)
            tenderedMBAmount = currentMBTenderedAmt
                    .add(currentMBTenderedAmt.multiply(BigDecimal.valueOf(negoPerc / 100)));
        // adding tendered amount with the non tendered items amount, to get
        // the total mb amount
        currMBTotal = tenderedMBAmount.add(currMBAmount.subtract(currentMBTenderedAmt));
    } else/*from  w w  w.j a v a2 s.  c o  m*/
        currMBTotal = mbHeader.getTotalMBAmount();

    return currMBTotal.setScale(2, RoundingMode.HALF_UP);
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.HistogramListener.java

/**
 * Calculate the detailed statistics/*from  w  w  w.  j  a  va 2s .c o  m*/
 * 
 * This will populate the HistogramScoresBean with the data associated with the
 * particular versioned assessment based on the publishedId.
 *
 * Some of this code will change when we move this to Hibernate persistence.
 * @param publishedId String
 * @param histogramScores TotalScoresBean
 * @return boolean true if successful
 */
public boolean histogramScores(HistogramScoresBean histogramScores, TotalScoresBean totalScores) {
    DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBean("delivery");
    String publishedId = totalScores.getPublishedId();
    if (publishedId.equals("0")) {
        publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId");
    }
    String actionString = ContextUtil.lookupParam("actionString");
    // See if this can fix SAK-16437
    if (actionString != null && !actionString.equals("reviewAssessment")) {
        // Shouldn't come to here. The action should either be null or reviewAssessment.
        // If we can confirm this is where causes SAK-16437, ask UX for a new screen with warning message.  
        log.error("SAK-16437 happens!! publishedId = " + publishedId + ", agentId = "
                + AgentFacade.getAgentString());
    }

    ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
    ResourceLoader rbEval = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
    String assessmentName = "";

    histogramScores.clearLowerQuartileStudents();
    histogramScores.clearUpperQuartileStudents();

    String which = histogramScores.getAllSubmissions();
    if (which == null && totalScores.getAllSubmissions() != null) {
        // use totalscore's selection
        which = totalScores.getAllSubmissions();
        histogramScores.setAllSubmissions(which); // changed submission pulldown
    }

    histogramScores.setItemId(ContextUtil.lookupParam("itemId"));
    histogramScores.setHasNav(ContextUtil.lookupParam("hasNav"));

    GradingService delegate = new GradingService();
    PublishedAssessmentService pubService = new PublishedAssessmentService();
    List<AssessmentGradingData> allscores = delegate.getTotalScores(publishedId, which);
    //set the ItemGradingData manually here. or we cannot
    //retrieve it later.
    for (AssessmentGradingData agd : allscores) {
        agd.setItemGradingSet(delegate.getItemGradingSet(String.valueOf(agd.getAssessmentGradingId())));
    }
    if (allscores.isEmpty()) {
        // Similar case in Bug 1537, but clicking Statistics link instead of assignment title.
        // Therefore, redirect the the same page.
        delivery.setOutcome("reviewAssessmentError");
        delivery.setActionString(actionString);
        return true;
    }

    histogramScores.setPublishedId(publishedId);
    int callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER;
    String isFromStudent = (String) ContextUtil.lookupParam("isFromStudent");
    if (isFromStudent != null && "true".equals(isFromStudent)) {
        callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER_STUDENT;
    }

    // get the Map of all users(keyed on userid) belong to the selected sections 
    // now we only include scores of users belong to the selected sections
    Map useridMap = null;
    ArrayList scores = new ArrayList();
    // only do section filter if it's published to authenticated users
    if (totalScores.getReleaseToAnonymous()) {
        scores.addAll(allscores);
    } else {
        useridMap = totalScores.getUserIdMap(callerName);
        Iterator allscores_iter = allscores.iterator();
        while (allscores_iter.hasNext()) {
            AssessmentGradingData data = (AssessmentGradingData) allscores_iter.next();
            String agentid = data.getAgentId();
            if (useridMap.containsKey(agentid)) {
                scores.add(data);
            }
        }
    }
    Iterator iter = scores.iterator();
    //log.info("Has this many agents: " + scores.size());

    if (!iter.hasNext()) {
        log.info("Students who have submitted may have been removed from this site");
        return false;
    }

    // here scores contain AssessmentGradingData 
    Map assessmentMap = getAssessmentStatisticsMap(scores);

    /*
     * find students in upper and lower quartiles 
     * of assessment scores
     */
    ArrayList submissionsSortedForDiscrim = new ArrayList(scores);
    boolean anonymous = Boolean.valueOf(totalScores.getAnonymous()).booleanValue();
    Collections.sort(submissionsSortedForDiscrim,
            new AssessmentGradingComparatorByScoreAndUniqueIdentifier(anonymous));
    int numSubmissions = scores.size();
    //int percent27 = ((numSubmissions*10*27/100)+5)/10; // rounded
    int percent27 = numSubmissions * 27 / 100; // rounded down
    if (percent27 == 0)
        percent27 = 1;
    for (int i = 0; i < percent27; i++) {
        histogramScores.addToLowerQuartileStudents(
                ((AssessmentGradingData) submissionsSortedForDiscrim.get(i)).getAgentId());
        histogramScores.addToUpperQuartileStudents(
                ((AssessmentGradingData) submissionsSortedForDiscrim.get(numSubmissions - 1 - i)).getAgentId());
    }

    PublishedAssessmentIfc pub = (PublishedAssessmentIfc) pubService.getPublishedAssessment(publishedId, false);

    if (pub != null) {
        if (actionString != null && actionString.equals("reviewAssessment")) {
            if (AssessmentIfc.RETRACT_FOR_EDIT_STATUS.equals(pub.getStatus())) {
                // Bug 1547: If this is during review and the assessment is retracted for edit now, 
                // set the outcome to isRetractedForEdit2 error page.
                delivery.setOutcome("isRetractedForEdit2");
                delivery.setActionString(actionString);
                return true;
            } else {
                delivery.setOutcome("histogramScores");
                delivery.setSecureDeliveryHTMLFragment("");
                delivery.setBlockDelivery(false);
                SecureDeliveryServiceAPI secureDelivery = SamigoApiFactory.getInstance()
                        .getSecureDeliveryServiceAPI();
                if (secureDelivery.isSecureDeliveryAvaliable()) {

                    String moduleId = pub.getAssessmentMetaDataByLabel(SecureDeliveryServiceAPI.MODULE_KEY);
                    if (moduleId != null && !SecureDeliveryServiceAPI.NONE_ID.equals(moduleId)) {

                        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                                .getExternalContext().getRequest();
                        PhaseStatus status = secureDelivery.validatePhase(moduleId, Phase.ASSESSMENT_REVIEW,
                                pub, request);
                        delivery.setSecureDeliveryHTMLFragment(secureDelivery.getHTMLFragment(moduleId, pub,
                                request, Phase.ASSESSMENT_REVIEW, status, new ResourceLoader().getLocale()));
                        if (PhaseStatus.FAILURE == status) {
                            delivery.setOutcome("secureDeliveryError");
                            delivery.setActionString(actionString);
                            delivery.setBlockDelivery(true);
                            return true;
                        }
                    }
                }
            }
        }

        boolean showObjectivesColumn = Boolean
                .parseBoolean(pub.getAssessmentMetaDataByLabel(AssessmentBaseIfc.HASMETADATAFORQUESTIONS));
        Map<String, Double> objectivesCorrect = new HashMap<String, Double>();
        Map<String, Integer> objectivesCounter = new HashMap<String, Integer>();
        Map<String, Double> keywordsCorrect = new HashMap<String, Double>();
        Map<String, Integer> keywordsCounter = new HashMap<String, Integer>();

        assessmentName = pub.getTitle();

        List<? extends SectionDataIfc> parts = pub.getSectionArraySorted();
        histogramScores.setAssesmentParts((List<PublishedSectionData>) parts);
        ArrayList info = new ArrayList();
        Iterator partsIter = parts.iterator();
        int secseq = 1;
        double totalpossible = 0;
        boolean hasRandompart = false;
        boolean isRandompart = false;
        String poolName = null;

        HashMap itemScoresMap = delegate.getItemScores(Long.valueOf(publishedId), Long.valueOf(0), which);
        HashMap itemScores = new HashMap();

        if (totalScores.getReleaseToAnonymous()) {
            // skip section filter if it's published to anonymous users
            itemScores.putAll(itemScoresMap);
        } else {
            if (useridMap == null) {
                useridMap = totalScores.getUserIdMap(callerName);
            }

            for (Iterator it = itemScoresMap.entrySet().iterator(); it.hasNext();) {
                Map.Entry entry = (Map.Entry) it.next();
                Long itemId = (Long) entry.getKey();
                ArrayList itemScoresList = (ArrayList) entry.getValue();

                ArrayList filteredItemScoresList = new ArrayList();
                Iterator itemScoresIter = itemScoresList.iterator();
                // get the Map of all users(keyed on userid) belong to the
                // selected sections

                while (itemScoresIter.hasNext()) {
                    ItemGradingData idata = (ItemGradingData) itemScoresIter.next();
                    String agentid = idata.getAgentId();
                    if (useridMap.containsKey(agentid)) {
                        filteredItemScoresList.add(idata);
                    }
                }
                itemScores.put(itemId, filteredItemScoresList);
            }
        }

        // Iterate through the assessment parts
        while (partsIter.hasNext()) {
            SectionDataIfc section = (SectionDataIfc) partsIter.next();
            String authortype = section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE);
            try {
                if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.equals(Integer.valueOf(authortype))) {
                    hasRandompart = true;
                    isRandompart = true;
                    poolName = section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW);
                } else {
                    isRandompart = false;
                    poolName = null;
                }
            } catch (NumberFormatException e) {
                isRandompart = false;
                poolName = null;
            }
            if (section.getSequence() == null)
                section.setSequence(Integer.valueOf(secseq++));
            String title = rb.getString("part") + " " + section.getSequence().toString();
            title += ", " + rb.getString("question") + " ";
            List<ItemDataIfc> itemset = section.getItemArraySortedForGrading();
            int seq = 1;
            Iterator<ItemDataIfc> itemsIter = itemset.iterator();

            // Iterate through the assessment questions (items)
            while (itemsIter.hasNext()) {
                HistogramQuestionScoresBean questionScores = new HistogramQuestionScoresBean();
                questionScores.setNumberOfParts(parts.size());
                //if this part is a randompart , then set randompart = true
                questionScores.setRandomType(isRandompart);
                questionScores.setPoolName(poolName);
                ItemDataIfc item = itemsIter.next();

                if (showObjectivesColumn) {
                    String obj = item.getItemMetaDataByLabel(ItemMetaDataIfc.OBJECTIVE);
                    questionScores.setObjectives(obj);
                    String key = item.getItemMetaDataByLabel(ItemMetaDataIfc.KEYWORD);
                    questionScores.setKeywords(key);
                }

                //String type = delegate.getTextForId(item.getTypeId());
                String type = getType(item.getTypeId().intValue());
                if (item.getSequence() == null)
                    item.setSequence(Integer.valueOf(seq++));

                questionScores.setPartNumber(section.getSequence().toString());
                //set the question label depending on random pools and parts
                if (questionScores.getRandomType() && poolName != null) {
                    if (questionScores.getNumberOfParts() > 1) {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_part_pool", null));
                    } else {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_pool", null));
                    }
                } else {
                    if (questionScores.getNumberOfParts() > 1) {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_part", null));
                    } else {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question", null));
                    }
                }
                questionScores.setQuestionNumber(item.getSequence().toString());
                questionScores.setItemId(item.getItemId());
                questionScores.setTitle(title + item.getSequence().toString() + " (" + type + ")");

                if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS)) { // emi question
                    questionScores.setQuestionText(item.getLeadInText());
                } else {
                    questionScores.setQuestionText(item.getText());
                }

                questionScores.setQuestionType(item.getTypeId().toString());
                //totalpossible = totalpossible + item.getScore().doubleValue();
                //ArrayList responses = null;

                //for each question (item) in the published assessment's current part/section
                determineResults(pub, questionScores, (ArrayList) itemScores.get(item.getItemId()));
                questionScores.setTotalScore(item.getScore().toString());

                questionScores.setN("" + numSubmissions);
                questionScores.setItemId(item.getItemId());
                Set studentsWithAllCorrect = questionScores.getStudentsWithAllCorrect();
                Set studentsResponded = questionScores.getStudentsResponded();
                if (studentsWithAllCorrect == null || studentsResponded == null
                        || studentsWithAllCorrect.isEmpty() || studentsResponded.isEmpty()) {
                    questionScores.setPercentCorrectFromUpperQuartileStudents("0");
                    questionScores.setPercentCorrectFromLowerQuartileStudents("0");
                    questionScores.setDiscrimination("0.0");
                } else {
                    int percent27ForThisQuestion = percent27;
                    Set<String> upperQuartileStudents = histogramScores.getUpperQuartileStudents().keySet();
                    Set<String> lowerQuartileStudents = histogramScores.getLowerQuartileStudents().keySet();
                    if (isRandompart) {
                        //we need to calculate the 27% upper and lower
                        //per question for the people that actually answered
                        //this question.
                        upperQuartileStudents = new HashSet<String>();
                        lowerQuartileStudents = new HashSet<String>();
                        percent27ForThisQuestion = questionScores.getNumResponses() * 27 / 100;
                        if (percent27ForThisQuestion == 0)
                            percent27ForThisQuestion = 1;
                        if (questionScores.getNumResponses() != 0) {
                            //need to only get gradings for students that answered this question
                            List<AssessmentGradingData> filteredGradings = filterGradingData(
                                    submissionsSortedForDiscrim, questionScores.getItemId());

                            // SAM-2228: loop control issues because of unsynchronized collection access
                            int filteredGradingsSize = filteredGradings.size();
                            percent27ForThisQuestion = filteredGradingsSize * 27 / 100;

                            for (int i = 0; i < percent27ForThisQuestion; i++) {
                                lowerQuartileStudents
                                        .add(((AssessmentGradingData) filteredGradings.get(i)).getAgentId());
                                //
                                upperQuartileStudents.add(((AssessmentGradingData) filteredGradings
                                        .get(filteredGradingsSize - 1 - i)).getAgentId());
                            }
                        }
                    }
                    if (questionScores.getNumResponses() != 0) {
                        int numStudentsWithAllCorrectFromUpperQuartile = 0;
                        int numStudentsWithAllCorrectFromLowerQuartile = 0;
                        Iterator studentsIter = studentsWithAllCorrect.iterator();
                        while (studentsIter.hasNext()) {
                            String agentId = (String) studentsIter.next();
                            if (upperQuartileStudents.contains(agentId)) {
                                numStudentsWithAllCorrectFromUpperQuartile++;
                            }
                            if (lowerQuartileStudents.contains(agentId)) {
                                numStudentsWithAllCorrectFromLowerQuartile++;
                            }
                        }

                        double percentCorrectFromUpperQuartileStudents = ((double) numStudentsWithAllCorrectFromUpperQuartile
                                / (double) percent27ForThisQuestion) * 100d;

                        double percentCorrectFromLowerQuartileStudents = ((double) numStudentsWithAllCorrectFromLowerQuartile
                                / (double) percent27ForThisQuestion) * 100d;

                        questionScores.setPercentCorrectFromUpperQuartileStudents(
                                Integer.toString((int) percentCorrectFromUpperQuartileStudents));
                        questionScores.setPercentCorrectFromLowerQuartileStudents(
                                Integer.toString((int) percentCorrectFromLowerQuartileStudents));

                        double discrimination = ((double) numStudentsWithAllCorrectFromUpperQuartile
                                - (double) numStudentsWithAllCorrectFromLowerQuartile)
                                / (double) percent27ForThisQuestion;

                        // round to 2 decimals
                        if (discrimination > 999999 || discrimination < -999999) {
                            questionScores.setDiscrimination("NaN");
                        } else {
                            discrimination = ((int) (discrimination * 100.00d)) / 100.00d;
                            questionScores.setDiscrimination(Double.toString(discrimination));
                        }
                    } else {
                        questionScores.setPercentCorrectFromUpperQuartileStudents(rbEval.getString("na"));
                        questionScores.setPercentCorrectFromLowerQuartileStudents(rbEval.getString("na"));
                        questionScores.setDiscrimination(rbEval.getString("na"));
                    }
                }

                info.add(questionScores);
            } // end-while - items

            totalpossible = pub.getTotalScore().doubleValue();

        } // end-while - parts
        histogramScores.setInfo(info);
        histogramScores.setRandomType(hasRandompart);

        int maxNumOfAnswers = 0;
        List<HistogramQuestionScoresBean> detailedStatistics = new ArrayList<HistogramQuestionScoresBean>();
        Iterator infoIter = info.iterator();
        while (infoIter.hasNext()) {
            HistogramQuestionScoresBean questionScores = (HistogramQuestionScoresBean) infoIter.next();
            if (questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MATCHING.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString())
                    || questionScores.getQuestionType()
                            .equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString())
                    || questionScores.getQuestionType().equals("16")) {
                questionScores.setShowIndividualAnswersInDetailedStatistics(true);
                detailedStatistics.add(questionScores);
                if (questionScores.getHistogramBars() != null) {
                    maxNumOfAnswers = questionScores.getHistogramBars().length > maxNumOfAnswers
                            ? questionScores.getHistogramBars().length
                            : maxNumOfAnswers;
                }
            }

            if (showObjectivesColumn) {
                // Get the percentage correct by objective
                String obj = questionScores.getObjectives();
                if (obj != null && !"".equals(obj)) {
                    String[] objs = obj.split(",");
                    for (int i = 0; i < objs.length; i++) {

                        // SAM-2508 set a default value to avoid the NumberFormatException issues
                        Double pctCorrect = 0.0d;
                        Double newAvg = 0.0d;
                        int divisor = 1;

                        try {
                            if (questionScores.getPercentCorrect() != null
                                    && !"N/A".equalsIgnoreCase(questionScores.getPercentCorrect())) {
                                pctCorrect = Double.parseDouble(questionScores.getPercentCorrect());
                            }
                        } catch (NumberFormatException nfe) {
                            log.error("NFE when looking at metadata and objectives", nfe);
                        }

                        if (objectivesCorrect.get(objs[i]) != null) {
                            Double objCorrect = objectivesCorrect.get(objs[i]);
                            divisor = objCorrect.intValue() + 1;

                            newAvg = objCorrect + ((pctCorrect - objCorrect) / divisor);
                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        } else {
                            newAvg = new BigDecimal(pctCorrect).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        }

                        objectivesCounter.put(objs[i], divisor);
                        objectivesCorrect.put(objs[i], newAvg);
                    }
                }

                // Get the percentage correct by keyword
                String key = questionScores.getKeywords();
                if (key != null && !"".equals(key)) {
                    String[] keys = key.split(",");
                    for (int i = 0; i < keys.length; i++) {
                        if (keywordsCorrect.get(keys[i]) != null) {
                            int divisor = keywordsCounter.get(keys[i]) + 1;
                            Double newAvg = keywordsCorrect.get(keys[i])
                                    + ((Double.parseDouble(questionScores.getPercentCorrect())
                                            - keywordsCorrect.get(keys[i])) / divisor);

                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();

                            keywordsCounter.put(keys[i], divisor);
                            keywordsCorrect.put(keys[i], newAvg);
                        } else {
                            Double newAvg = Double.parseDouble(questionScores.getPercentCorrect());
                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();

                            keywordsCounter.put(keys[i], 1);
                            keywordsCorrect.put(keys[i], newAvg);
                        }
                    }
                }
            }

            //i.e. for EMI questions we add detailed stats for the whole
            //question as well as for the sub-questions
            if (questionScores.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString())) {
                questionScores.setShowIndividualAnswersInDetailedStatistics(false);
                detailedStatistics.addAll(questionScores.getInfo());

                Iterator subInfoIter = questionScores.getInfo().iterator();
                while (subInfoIter.hasNext()) {
                    HistogramQuestionScoresBean subQuestionScores = (HistogramQuestionScoresBean) subInfoIter
                            .next();
                    if (subQuestionScores.getHistogramBars() != null) {
                        subQuestionScores.setN(questionScores.getN());
                        maxNumOfAnswers = subQuestionScores.getHistogramBars().length > maxNumOfAnswers
                                ? subQuestionScores.getHistogramBars().length
                                : maxNumOfAnswers;
                    }
                }
                /*                 
                                 Object numberOfStudentsWithZeroAnswers = numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId());
                                 if (numberOfStudentsWithZeroAnswers == null) {
                                    questionScores.setNumberOfStudentsWithZeroAnswers(0);
                                 }
                                 else {
                                    questionScores.setNumberOfStudentsWithZeroAnswers( ((Integer) numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId())).intValue() );
                                 }
                */
            }

        }
        //VULA-1948: sort the detailedStatistics list by Question Label
        sortQuestionScoresByLabel(detailedStatistics);
        histogramScores.setDetailedStatistics(detailedStatistics);
        histogramScores.setMaxNumberOfAnswers(maxNumOfAnswers);
        histogramScores.setShowObjectivesColumn(showObjectivesColumn);

        if (showObjectivesColumn) {
            List<Entry<String, Double>> objectivesList = new ArrayList<Entry<String, Double>>(
                    objectivesCorrect.entrySet());
            Collections.sort(objectivesList, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> e1, Entry<String, Double> e2) {
                    return e1.getKey().compareTo(e2.getKey());
                }
            });
            histogramScores.setObjectives(objectivesList);

            List<Entry<String, Double>> keywordsList = new ArrayList<Entry<String, Double>>(
                    keywordsCorrect.entrySet());

            Collections.sort(keywordsList, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> e1, Entry<String, Double> e2) {
                    return e1.getKey().compareTo(e2.getKey());
                }
            });
            histogramScores.setKeywords(keywordsList);
        }

        // test to see if it gets back empty map
        if (assessmentMap.isEmpty()) {
            histogramScores.setNumResponses(0);
        }

        try {
            BeanUtils.populate(histogramScores, assessmentMap);

            // quartiles don't seem to be working, workaround
            histogramScores.setQ1((String) assessmentMap.get("q1"));
            histogramScores.setQ2((String) assessmentMap.get("q2"));
            histogramScores.setQ3((String) assessmentMap.get("q3"));
            histogramScores.setQ4((String) assessmentMap.get("q4"));
            histogramScores.setTotalScore((String) assessmentMap.get("totalScore"));
            histogramScores.setTotalPossibleScore(Double.toString(totalpossible));
            HistogramBarBean[] bars = new HistogramBarBean[histogramScores.getColumnHeight().length];
            for (int i = 0; i < histogramScores.getColumnHeight().length; i++) {
                bars[i] = new HistogramBarBean();
                bars[i].setColumnHeight(Integer.toString(histogramScores.getColumnHeight()[i]));
                bars[i].setNumStudents(histogramScores.getNumStudentCollection()[i]);
                bars[i].setRangeInfo(histogramScores.getRangeCollection()[i]);
                //log.info("Set bar " + i + ": " + bean.getColumnHeight()[i] + ", " + bean.getNumStudentCollection()[i] + ", " + bean.getRangeCollection()[i]);
            }
            histogramScores.setHistogramBars(bars);

            ///////////////////////////////////////////////////////////
            // START DEBUGGING
            /*
              log.info("TESTING ASSESSMENT MAP");
              log.info("assessmentMap: =>");
              log.info(assessmentMap);
              log.info("--------------------------------------------");
              log.info("TESTING TOTALS HISTOGRAM FORM");
              log.info(
              "HistogramScoresForm Form: =>\n" + "bean.getMean()=" +
              bean.getMean() + "\n" +
              "bean.getColumnHeight()[0] (first elem)=" +
              bean.getColumnHeight()[0] + "\n" + "bean.getInterval()=" +
              bean.getInterval() + "\n" + "bean.getLowerQuartile()=" +
              bean.getLowerQuartile() + "\n" + "bean.getMaxScore()=" +
              bean.getMaxScore() + "\n" + "bean.getMean()=" + bean.getMean() +
              "\n" + "bean.getMedian()=" + bean.getMedian() + "\n" +
              "bean.getNumResponses()=" + bean.getNumResponses() + "\n" +
              "bean.getNumStudentCollection()=" +
              bean.getNumStudentCollection() +
              "\n" + "bean.getQ1()=" + bean.getQ1() + "\n" + "bean.getQ2()=" +
              bean.getQ2() + "\n" + "bean.getQ3()=" + bean.getQ3() + "\n" +
              "bean.getQ4()=" + bean.getQ4());
              log.info("--------------------------------------------");
                    
             */
            // END DEBUGGING CODE
            ///////////////////////////////////////////////////////////
        } catch (IllegalAccessException e) {
            log.warn("IllegalAccessException:  unable to populate bean" + e);
        } catch (InvocationTargetException e) {
            log.warn("InvocationTargetException: unable to populate bean" + e);
        }

        histogramScores.setAssessmentName(assessmentName);
    } else {
        log.error("pub is null. publishedId = " + publishedId);
        return false;
    }
    return true;
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

@Override
@SuppressWarnings("unchecked")
public void sube(byte[] datos, Usuario usuario, OutputStream out, Integer codigoInicial) {
    Date inicio = new Date();
    int idx = 5;/*w w w  .ja v a 2 s .c  o m*/
    int i = 0;
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yy");
    SimpleDateFormat sdf3 = new SimpleDateFormat("dd-MM-yy");

    MathContext mc = new MathContext(16, RoundingMode.HALF_UP);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMaximumFractionDigits(0);
    nf.setMinimumIntegerDigits(5);

    Transaction tx = null;
    try {
        String ejercicioId = "001-2012";
        Map<String, CentroCosto> centrosDeCosto = new HashMap<>();
        Map<String, TipoActivo> tipos = new HashMap<>();
        Query tipoActivoQuery = currentSession()
                .createQuery("select ta from TipoActivo ta " + "where ta.empresa.id = :empresaId "
                        + "and ta.cuenta.id.ejercicio.id.idEjercicio = :ejercicioId "
                        + "and ta.cuenta.id.ejercicio.id.organizacion.id = :organizacionId");
        log.debug("empresaId: {}", usuario.getEmpresa().getId());
        log.debug("ejercicioId: {}", ejercicioId);
        log.debug("organizacionId: {}", usuario.getEmpresa().getOrganizacion().getId());
        tipoActivoQuery.setLong("empresaId", usuario.getEmpresa().getId());
        tipoActivoQuery.setString("ejercicioId", ejercicioId);
        tipoActivoQuery.setLong("organizacionId", usuario.getEmpresa().getOrganizacion().getId());
        List<TipoActivo> listaTipos = tipoActivoQuery.list();
        for (TipoActivo tipoActivo : listaTipos) {
            tipos.put(tipoActivo.getCuenta().getId().getIdCtaMayor(), tipoActivo);
        }
        log.debug("TIPOS: {}", tipos);

        Query proveedorQuery = currentSession().createQuery(
                "select p from Proveedor p where p.empresa.id = :empresaId and p.nombre = :nombreEmpresa");
        proveedorQuery.setLong("empresaId", usuario.getEmpresa().getId());
        proveedorQuery.setString("nombreEmpresa", usuario.getEmpresa().getNombre());
        Proveedor proveedor = (Proveedor) proveedorQuery.uniqueResult();

        Query codigoDuplicadoQuery = currentSession()
                .createQuery("select a from Activo a where a.empresa.id = :empresaId and a.codigo = :codigo");

        XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(datos));
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet ccostoFantasma = wb.createSheet("CCOSTO-FANTASMAS");
        int ccostoFantasmaRow = 0;
        XSSFSheet sinCCosto = wb.createSheet("SIN-CCOSTO");
        int sinCCostoRow = 0;
        XSSFSheet codigoAsignado = wb.createSheet("CODIGO-ASIGNADO");
        int codigoAsignadoRow = 0;
        XSSFSheet fechaInvalida = wb.createSheet("FECHA-INVALIDA");
        int fechaInvalidaRow = 0;
        XSSFSheet sinCosto = wb.createSheet("SIN-COSTO");
        int sinCostoRow = 0;

        tx = currentSession().beginTransaction();
        for (idx = 0; idx <= 5; idx++) {
            XSSFSheet sheet = workbook.getSheetAt(idx);

            int rows = sheet.getPhysicalNumberOfRows();
            for (i = 2; i < rows; i++) {
                log.debug("Leyendo pagina {} renglon {}", idx, i);
                XSSFRow row = sheet.getRow(i);
                if (row.getCell(0) == null) {
                    break;
                }
                String nombreGrupo = row.getCell(0).getStringCellValue().trim();
                TipoActivo tipoActivo = tipos.get(nombreGrupo);
                if (tipoActivo != null) {
                    String cuentaCCosto = row.getCell(2).toString().trim();
                    if (StringUtils.isNotBlank(cuentaCCosto)) {
                        CentroCosto centroCosto = centrosDeCosto.get(cuentaCCosto);
                        if (centroCosto == null) {
                            Query ccostoQuery = currentSession().createQuery("select cc from CentroCosto cc "
                                    + "where cc.id.ejercicio.id.idEjercicio = :ejercicioId "
                                    + "and cc.id.ejercicio.id.organizacion.id = :organizacionId "
                                    + "and cc.id.idCosto like :idCosto");
                            ccostoQuery.setString("ejercicioId", ejercicioId);
                            ccostoQuery.setLong("organizacionId",
                                    usuario.getEmpresa().getOrganizacion().getId());
                            ccostoQuery.setString("idCosto", "1.01." + cuentaCCosto);
                            ccostoQuery.setMaxResults(1);
                            List<CentroCosto> listaCCosto = ccostoQuery.list();
                            if (listaCCosto != null && listaCCosto.size() > 0) {
                                centroCosto = listaCCosto.get(0);
                            }
                            if (centroCosto == null) {
                                XSSFRow renglon = ccostoFantasma.createRow(ccostoFantasmaRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9).setCellValue(row.getCell(8).toString());
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                continue;
                            }
                            centrosDeCosto.put(cuentaCCosto, centroCosto);
                        }
                        String poliza = null;
                        switch (row.getCell(4).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            poliza = row.getCell(4).toString();
                            poliza = StringUtils.removeEnd(poliza, ".0");
                            log.debug("POLIZA-N: {}", poliza);
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            poliza = row.getCell(4).getStringCellValue().trim();
                            log.debug("POLIZA-S: {}", poliza);
                            break;
                        }
                        Boolean seguro = false;
                        if (row.getCell(5) != null && StringUtils.isNotBlank(row.getCell(5).toString())) {
                            seguro = true;
                        }
                        Boolean garantia = false;
                        if (row.getCell(6) != null && StringUtils.isNotBlank(row.getCell(6).toString())) {
                            garantia = true;
                        }
                        Date fechaCompra = null;
                        if (row.getCell(7) != null) {
                            log.debug("VALIDANDO FECHA");
                            XSSFCell cell = row.getCell(7);
                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_NUMERIC:
                                log.debug("ES NUMERIC");
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    log.debug("ES FECHA");
                                    fechaCompra = cell.getDateCellValue();
                                } else if (DateUtil.isCellInternalDateFormatted(cell)) {
                                    log.debug("ES FECHA INTERNAL");
                                    fechaCompra = cell.getDateCellValue();
                                } else {
                                    BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
                                    bd = stripTrailingZeros(bd);

                                    log.debug("CONVIRTIENDO DOUBLE {} - {}",
                                            DateUtil.isValidExcelDate(bd.doubleValue()), bd);
                                    fechaCompra = HSSFDateUtil.getJavaDate(bd.longValue(), true);
                                    log.debug("Cal: {}", fechaCompra);
                                }
                                break;
                            case Cell.CELL_TYPE_FORMULA:
                                log.debug("ES FORMULA");
                                CellValue cellValue = evaluator.evaluate(cell);
                                switch (cellValue.getCellType()) {
                                case Cell.CELL_TYPE_NUMERIC:
                                    if (DateUtil.isCellDateFormatted(cell)) {
                                        fechaCompra = DateUtil.getJavaDate(cellValue.getNumberValue(), true);
                                    }
                                }
                            }
                        }
                        if (row.getCell(7) != null && fechaCompra == null) {
                            String fechaCompraString;
                            if (row.getCell(7).getCellType() == Cell.CELL_TYPE_STRING) {
                                fechaCompraString = row.getCell(7).getStringCellValue();
                            } else {
                                fechaCompraString = row.getCell(7).toString().trim();
                            }
                            try {
                                fechaCompra = sdf.parse(fechaCompraString);
                            } catch (ParseException e) {
                                try {
                                    fechaCompra = sdf2.parse(fechaCompraString);
                                } catch (ParseException e2) {
                                    try {
                                        fechaCompra = sdf3.parse(fechaCompraString);
                                    } catch (ParseException e3) {
                                        // no se pudo convertir
                                    }
                                }
                            }
                        }

                        if (fechaCompra == null) {
                            XSSFRow renglon = fechaInvalida.createRow(fechaInvalidaRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        String codigo = null;
                        switch (row.getCell(8).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            codigo = row.getCell(8).toString();
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            codigo = row.getCell(8).getStringCellValue().trim();
                            break;
                        }
                        if (StringUtils.isBlank(codigo)) {
                            codigo = nf.format(codigoInicial);
                            XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(codigoInicial);
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            codigoInicial++;
                        } else {
                            // busca codigo duplicado
                            if (codigo.contains(".")) {
                                codigo = codigo.substring(0, codigo.lastIndexOf("."));
                                log.debug("CODIGO: {}", codigo);
                            }

                            codigoDuplicadoQuery.setLong("empresaId", usuario.getEmpresa().getId());
                            codigoDuplicadoQuery.setString("codigo", codigo);
                            Activo activo = (Activo) codigoDuplicadoQuery.uniqueResult();
                            if (activo != null) {
                                XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9).setCellValue(codigo + "-" + nf.format(codigoInicial));
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                codigo = nf.format(codigoInicial);
                                codigoInicial++;
                            }
                        }
                        String descripcion = null;
                        if (row.getCell(9) != null) {
                            switch (row.getCell(9).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                descripcion = row.getCell(9).toString();
                                descripcion = StringUtils.removeEnd(descripcion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                descripcion = row.getCell(9).getStringCellValue().trim();
                                break;
                            default:
                                descripcion = row.getCell(9).toString().trim();
                            }
                        }
                        String marca = null;
                        if (row.getCell(10) != null) {
                            switch (row.getCell(10).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                marca = row.getCell(10).toString();
                                marca = StringUtils.removeEnd(marca, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                marca = row.getCell(10).getStringCellValue().trim();
                                break;
                            default:
                                marca = row.getCell(10).toString().trim();
                            }
                        }
                        String modelo = null;
                        if (row.getCell(11) != null) {
                            switch (row.getCell(11).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                modelo = row.getCell(11).toString();
                                modelo = StringUtils.removeEnd(modelo, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                modelo = row.getCell(11).getStringCellValue().trim();
                                break;
                            default:
                                modelo = row.getCell(11).toString().trim();
                            }
                        }
                        String serie = null;
                        if (row.getCell(12) != null) {
                            switch (row.getCell(12).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                serie = row.getCell(12).toString();
                                serie = StringUtils.removeEnd(serie, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                serie = row.getCell(12).getStringCellValue().trim();
                                break;
                            default:
                                serie = row.getCell(12).toString().trim();
                            }
                        }
                        String responsable = null;
                        if (row.getCell(13) != null) {
                            switch (row.getCell(13).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                responsable = row.getCell(13).toString();
                                responsable = StringUtils.removeEnd(responsable, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                responsable = row.getCell(13).getStringCellValue().trim();
                                break;
                            default:
                                responsable = row.getCell(13).toString().trim();
                            }
                        }

                        String ubicacion = null;
                        if (row.getCell(14) != null) {
                            switch (row.getCell(14).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                ubicacion = row.getCell(14).toString();
                                ubicacion = StringUtils.removeEnd(ubicacion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                ubicacion = row.getCell(14).getStringCellValue().trim();
                                break;
                            default:
                                ubicacion = row.getCell(14).toString().trim();
                            }
                        }
                        BigDecimal costo = null;
                        switch (row.getCell(15).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            costo = new BigDecimal(row.getCell(15).getNumericCellValue(), mc);
                            log.debug("COSTO-N: {} - {}", costo, row.getCell(15).getNumericCellValue());
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            costo = new BigDecimal(row.getCell(15).toString(), mc);
                            log.debug("COSTO-S: {} - {}", costo, row.getCell(15).toString());
                            break;
                        case XSSFCell.CELL_TYPE_FORMULA:
                            costo = new BigDecimal(
                                    evaluator.evaluateInCell(row.getCell(15)).getNumericCellValue(), mc);
                            log.debug("COSTO-F: {}", costo);
                        }
                        if (costo == null) {
                            XSSFRow renglon = sinCosto.createRow(sinCostoRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        Activo activo = new Activo(fechaCompra, seguro, garantia, poliza, codigo, descripcion,
                                marca, modelo, serie, responsable, ubicacion, costo, tipoActivo, centroCosto,
                                proveedor, usuario.getEmpresa());
                        this.crea(activo, usuario);

                    } else {
                        XSSFRow renglon = sinCCosto.createRow(sinCCostoRow++);
                        renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                        renglon.createCell(1).setCellValue(row.getCell(0).toString());
                        renglon.createCell(2).setCellValue(row.getCell(1).toString());
                        renglon.createCell(3).setCellValue(row.getCell(2).toString());
                        renglon.createCell(4).setCellValue(row.getCell(3).toString());
                        renglon.createCell(5).setCellValue(row.getCell(4).toString());
                        renglon.createCell(6).setCellValue(row.getCell(5).toString());
                        renglon.createCell(7).setCellValue(row.getCell(6).toString());
                        renglon.createCell(8).setCellValue(row.getCell(7).toString());
                        renglon.createCell(9).setCellValue(row.getCell(8).toString());
                        renglon.createCell(10).setCellValue(row.getCell(9).toString());
                        renglon.createCell(11).setCellValue(row.getCell(10).toString());
                        renglon.createCell(12).setCellValue(row.getCell(11).toString());
                        renglon.createCell(13).setCellValue(row.getCell(12).toString());
                        renglon.createCell(14).setCellValue(row.getCell(13).toString());
                        renglon.createCell(15).setCellValue(row.getCell(14).toString());
                        renglon.createCell(16).setCellValue(row.getCell(15).toString());
                        continue;
                    }
                } else {
                    throw new RuntimeException(
                            "(" + idx + ":" + i + ") No se encontro el tipo de activo " + nombreGrupo);
                }
            }
        }
        tx.commit();
        log.debug("################################################");
        log.debug("################################################");
        log.debug("TERMINO EN {} MINS", (new Date().getTime() - inicio.getTime()) / (1000 * 60));
        log.debug("################################################");
        log.debug("################################################");

        wb.write(out);
    } catch (IOException | RuntimeException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        log.error("Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
        throw new RuntimeException(
                "Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractRegistrationController.java

/**
 * This method gets Product Bundle Revision For TenantCurrency
 * /*from w  w w.ja v a  2 s.  c o  m*/
 * @param currencyCode
 * @param productBundleRevision
 * @return ProductBundleRevision
 */
private ProductBundleRevision getProductBundleRevisionForTenantCurrency(String currencyCode,
        ProductBundleRevision productBundleRevision) {
    // Doing this so that the cached reference is not touched.
    ProductBundleRevision productBundleRevisionForTenantCurrency = new ProductBundleRevision();
    productBundleRevisionForTenantCurrency.setEntitlements(productBundleRevision.getEntitlements());
    productBundleRevisionForTenantCurrency.setProductBundle(productBundleRevision.getProductBundle());
    productBundleRevisionForTenantCurrency
            .setProvisioningConstraints(productBundleRevision.getProvisioningConstraints());
    productBundleRevisionForTenantCurrency.setRevision(productBundleRevision.getRevision());
    List<RateCardCharge> rateCardCharges = new ArrayList<RateCardCharge>();
    for (RateCardCharge charge : productBundleRevision.getRateCardCharges()) {
        if (charge.getCurrencyValue().getCurrencyCode().equals(currencyCode)) {
            BigDecimal price = charge.getPrice().setScale(
                    charge.getCurrencyValue().getCurrency().getDefaultFractionDigits(), RoundingMode.HALF_UP);
            charge.setPrice(price);
            rateCardCharges.add(charge);
        }
    }
    productBundleRevisionForTenantCurrency.setRateCardCharges(rateCardCharges);
    return productBundleRevisionForTenantCurrency;
}

From source file:loci.formats.in.MetamorphReader.java

@Override
protected void initFile(String id) throws FormatException, IOException {
    if (checkSuffix(id, ND_SUFFIX)) {
        LOGGER.info("Initializing " + id);
        // find an associated STK file
        String stkFile = id.substring(0, id.lastIndexOf("."));
        if (stkFile.indexOf(File.separatorChar) != -1) {
            stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1);
        }/* w w  w. j a  v a  2  s.  co m*/
        Location parent = new Location(id).getAbsoluteFile().getParentFile();
        LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath());
        String[] dirList = parent.list(true);
        Arrays.sort(dirList);
        for (String f : dirList) {
            int underscore = f.indexOf('_');
            if (underscore < 0)
                underscore = f.indexOf('.');
            if (underscore < 0)
                underscore = f.length();
            String prefix = f.substring(0, underscore);

            if ((f.equals(stkFile) || stkFile.startsWith(prefix)) && checkSuffix(f, STK_SUFFIX)) {
                stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath();
                break;
            }
        }

        if (!checkSuffix(stkFile, STK_SUFFIX)) {
            throw new FormatException("STK file not found in " + parent.getAbsolutePath() + ".");
        }

        super.initFile(stkFile);
    } else
        super.initFile(id);

    Location ndfile = null;

    if (checkSuffix(id, ND_SUFFIX))
        ndfile = new Location(id);
    else if (canLookForND && isGroupFiles()) {
        // an STK file was passed to initFile
        // let's check the parent directory for an .nd file
        Location stk = new Location(id).getAbsoluteFile();
        String stkName = stk.getName();
        String stkPrefix = stkName;
        if (stkPrefix.indexOf('_') >= 0) {
            stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf('_') + 1);
        }
        Location parent = stk.getParentFile();
        String[] list = parent.list(true);
        int matchingChars = 0;
        for (String f : list) {
            if (checkSuffix(f, ND_SUFFIX)) {
                String prefix = f.substring(0, f.lastIndexOf("."));
                if (prefix.indexOf('_') >= 0) {
                    prefix = prefix.substring(0, prefix.indexOf('_') + 1);
                }
                if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) {
                    int charCount = 0;
                    for (int i = 0; i < f.length(); i++) {
                        if (i >= stkName.length()) {
                            break;
                        }
                        if (f.charAt(i) == stkName.charAt(i)) {
                            charCount++;
                        } else {
                            break;
                        }
                    }

                    if (charCount > matchingChars
                            || (charCount == matchingChars && f.charAt(charCount) == '.')) {
                        ndfile = new Location(parent, f).getAbsoluteFile();
                        matchingChars = charCount;
                    }
                }
            }
        }
    }

    String creationTime = null;

    if (ndfile != null && ndfile.exists()
            && (fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles())) {
        // parse key/value pairs from .nd file

        int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT();
        int nstages = 0;
        String z = null, c = null, t = null;
        final List<Boolean> hasZ = new ArrayList<Boolean>();
        waveNames = new ArrayList<String>();
        stageNames = new ArrayList<String>();
        boolean useWaveNames = true;

        ndFilename = ndfile.getAbsolutePath();
        String[] lines = DataTools.readFile(ndFilename).split("\n");

        boolean globalDoZ = true;
        boolean doTimelapse = false;

        StringBuilder currentValue = new StringBuilder();
        String key = "";

        for (String line : lines) {
            int comma = line.indexOf(',');
            if (comma <= 0) {
                currentValue.append("\n");
                currentValue.append(line);
                continue;
            }

            String value = currentValue.toString();
            addGlobalMeta(key, value);
            if (key.equals("NZSteps"))
                z = value;
            else if (key.equals("DoTimelapse")) {
                doTimelapse = Boolean.parseBoolean(value);
            } else if (key.equals("NWavelengths"))
                c = value;
            else if (key.equals("NTimePoints"))
                t = value;
            else if (key.startsWith("WaveDoZ")) {
                hasZ.add(Boolean.parseBoolean(value));
            } else if (key.startsWith("WaveName")) {
                String waveName = value.substring(1, value.length() - 1);
                if (waveName.equals("Both lasers") || waveName.startsWith("DUAL")) {
                    bizarreMultichannelAcquisition = true;
                }
                waveNames.add(waveName);
            } else if (key.startsWith("Stage")) {
                stageNames.add(value);
            } else if (key.startsWith("StartTime")) {
                creationTime = value;
            } else if (key.equals("ZStepSize")) {
                value = value.replace(',', '.');
                stepSize = Double.parseDouble(value);
            } else if (key.equals("NStagePositions")) {
                nstages = Integer.parseInt(value);
            } else if (key.equals("WaveInFileName")) {
                useWaveNames = Boolean.parseBoolean(value);
            } else if (key.equals("DoZSeries")) {
                globalDoZ = Boolean.parseBoolean(value);
            }

            key = line.substring(1, comma - 1).trim();
            currentValue.delete(0, currentValue.length());
            currentValue.append(line.substring(comma + 1).trim());
        }

        if (!globalDoZ) {
            for (int i = 0; i < hasZ.size(); i++) {
                hasZ.set(i, false);
            }
        }

        // figure out how many files we need

        if (z != null)
            zc = Integer.parseInt(z);
        if (c != null)
            cc = Integer.parseInt(c);
        if (t != null)
            tc = Integer.parseInt(t);
        else if (!doTimelapse) {
            tc = 1;
        }

        if (cc == 0)
            cc = 1;
        if (cc == 1 && bizarreMultichannelAcquisition) {
            cc = 2;
        }
        if (tc == 0) {
            tc = 1;
        }

        int numFiles = cc * tc;
        if (nstages > 0)
            numFiles *= nstages;

        // determine series count
        int stagesCount = nstages == 0 ? 1 : nstages;
        int seriesCount = stagesCount;
        firstSeriesChannels = new boolean[cc];
        Arrays.fill(firstSeriesChannels, true);
        boolean differentZs = false;
        for (int i = 0; i < cc; i++) {
            boolean hasZ1 = i < hasZ.size() && hasZ.get(i);
            boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) && hasZ.get(i - 1);
            if (i > 0 && hasZ1 != hasZ2 && globalDoZ) {
                if (!differentZs)
                    seriesCount *= 2;
                differentZs = true;
            }
        }

        int channelsInFirstSeries = cc;
        if (differentZs) {
            channelsInFirstSeries = 0;
            for (int i = 0; i < cc; i++) {
                if ((!hasZ.get(0) && i == 0) || (hasZ.get(0) && hasZ.get(i))) {
                    channelsInFirstSeries++;
                } else
                    firstSeriesChannels[i] = false;
            }
        }

        stks = new String[seriesCount][];
        if (seriesCount == 1)
            stks[0] = new String[numFiles];
        else if (differentZs) {
            for (int i = 0; i < stagesCount; i++) {
                stks[i * 2] = new String[channelsInFirstSeries * tc];
                stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc];
            }
        } else {
            for (int i = 0; i < stks.length; i++) {
                stks[i] = new String[numFiles / stks.length];
            }
        }

        String prefix = ndfile.getPath();
        prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1, prefix.lastIndexOf("."));

        // build list of STK files

        boolean anyZ = hasZ.contains(Boolean.TRUE);
        int[] pt = new int[seriesCount];
        for (int i = 0; i < tc; i++) {
            for (int s = 0; s < stagesCount; s++) {
                for (int j = 0; j < cc; j++) {
                    boolean validZ = j >= hasZ.size() || hasZ.get(j);
                    int seriesNdx = s * (seriesCount / stagesCount);

                    if ((seriesCount != 1 && (!validZ || (hasZ.size() > 0 && !hasZ.get(0))))
                            || (nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1))) {
                        if (anyZ && j > 0 && seriesNdx < seriesCount - 1 && (!validZ || !hasZ.get(0))) {
                            seriesNdx++;
                        }
                    }
                    if (seriesNdx >= stks.length || seriesNdx >= pt.length
                            || pt[seriesNdx] >= stks[seriesNdx].length) {
                        continue;
                    }
                    stks[seriesNdx][pt[seriesNdx]] = prefix;
                    if (j < waveNames.size() && waveNames.get(j) != null) {
                        stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1);
                        if (useWaveNames) {
                            String waveName = waveNames.get(j);
                            // If there are underscores in the wavelength name, translate
                            // them to hyphens. (See #558)
                            waveName = waveName.replace('_', '-');
                            // If there are slashes (forward or backward) in the wavelength
                            // name, translate them to hyphens. (See #5922)
                            waveName = waveName.replace('/', '-');
                            waveName = waveName.replace('\\', '-');
                            waveName = waveName.replace('(', '-');
                            waveName = waveName.replace(')', '-');
                            stks[seriesNdx][pt[seriesNdx]] += waveName;
                        }
                    }
                    if (nstages > 0) {
                        stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1);
                    }
                    if (tc > 1 || doTimelapse) {
                        stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK";
                    } else
                        stks[seriesNdx][pt[seriesNdx]] += ".STK";
                    pt[seriesNdx]++;
                }
            }
        }

        ndfile = ndfile.getAbsoluteFile();

        // check that each STK file exists

        for (int s = 0; s < stks.length; s++) {
            for (int f = 0; f < stks[s].length; f++) {
                Location l = new Location(ndfile.getParent(), stks[s][f]);
                stks[s][f] = getRealSTKFile(l);
            }
        }

        String file = locateFirstValidFile();
        if (file == null) {
            throw new FormatException("Unable to locate at least one valid STK file!");
        }

        RandomAccessInputStream s = new RandomAccessInputStream(file, 16);
        TiffParser tp = new TiffParser(s);
        IFD ifd = tp.getFirstIFD();
        CoreMetadata ms0 = core.get(0);
        s.close();
        ms0.sizeX = (int) ifd.getImageWidth();
        ms0.sizeY = (int) ifd.getImageLength();

        if (bizarreMultichannelAcquisition) {
            ms0.sizeX /= 2;
        }

        ms0.sizeZ = hasZ.size() > 0 && !hasZ.get(0) ? 1 : zc;
        ms0.sizeC = cc;
        ms0.sizeT = tc;
        ms0.imageCount = getSizeZ() * getSizeC() * getSizeT();
        if (isRGB()) {
            ms0.sizeC *= 3;
        }
        ms0.dimensionOrder = "XYZCT";

        if (stks != null && stks.length > 1) {
            // Note that core can't be replaced with newCore until the end of this block.
            ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>();
            for (int i = 0; i < stks.length; i++) {
                CoreMetadata ms = new CoreMetadata();
                newCore.add(ms);
                ms.sizeX = getSizeX();
                ms.sizeY = getSizeY();
                ms.sizeZ = getSizeZ();
                ms.sizeC = getSizeC();
                ms.sizeT = getSizeT();
                ms.pixelType = getPixelType();
                ms.imageCount = getImageCount();
                ms.dimensionOrder = getDimensionOrder();
                ms.rgb = isRGB();
                ms.littleEndian = isLittleEndian();
                ms.interleaved = isInterleaved();
                ms.orderCertain = true;
            }
            if (stks.length > nstages) {
                for (int j = 0; j < stagesCount; j++) {
                    int idx = j * 2 + 1;
                    CoreMetadata midx = newCore.get(idx);
                    CoreMetadata pmidx = newCore.get(j * 2);
                    pmidx.sizeC = stks[j * 2].length / getSizeT();
                    midx.sizeC = stks[idx].length / midx.sizeT;
                    midx.sizeZ = hasZ.size() > 1 && hasZ.get(1) && core.get(0).sizeZ == 1 ? zc : 1;
                    pmidx.imageCount = pmidx.sizeC * pmidx.sizeT * pmidx.sizeZ;
                    midx.imageCount = midx.sizeC * midx.sizeT * midx.sizeZ;
                }
            }
            core = newCore;
        }
    }

    if (stks == null) {
        stkReaders = new MetamorphReader[1][1];
        stkReaders[0][0] = new MetamorphReader();
        stkReaders[0][0].setCanLookForND(false);
    } else {
        stkReaders = new MetamorphReader[stks.length][];
        for (int i = 0; i < stks.length; i++) {
            stkReaders[i] = new MetamorphReader[stks[i].length];
            for (int j = 0; j < stkReaders[i].length; j++) {
                stkReaders[i][j] = new MetamorphReader();
                stkReaders[i][j].setCanLookForND(false);
                if (j > 0) {
                    stkReaders[i][j].setMetadataOptions(new DynamicMetadataOptions(MetadataLevel.MINIMUM));
                }
            }
        }
    }

    // check stage labels for plate data

    int rows = 0;
    int cols = 0;
    Map<String, Integer> rowMap = null;
    Map<String, Integer> colMap = null;
    isHCS = true;
    if (null == stageLabels) {
        isHCS = false;
    } else {
        Set<Map.Entry<Integer, Integer>> uniqueWells = new HashSet<Map.Entry<Integer, Integer>>();
        rowMap = new HashMap<String, Integer>();
        colMap = new HashMap<String, Integer>();
        for (String label : stageLabels) {
            if (null == label) {
                isHCS = false;
                break;
            }
            Map.Entry<Integer, Integer> wellCoords = getWellCoords(label);
            if (null == wellCoords) {
                isHCS = false;
                break;
            }
            uniqueWells.add(wellCoords);
            rowMap.put(label, wellCoords.getKey());
            colMap.put(label, wellCoords.getValue());
        }
        if (uniqueWells.size() != stageLabels.length) {
            isHCS = false;
        } else {
            rows = Collections.max(rowMap.values());
            cols = Collections.max(colMap.values());
            CoreMetadata c = core.get(0);
            core.clear();
            c.sizeZ = 1;
            c.sizeT = 1;
            c.imageCount = 1;
            for (int s = 0; s < uniqueWells.size(); s++) {
                CoreMetadata toAdd = new CoreMetadata(c);
                if (s > 0) {
                    toAdd.seriesMetadata.clear();
                }
                core.add(toAdd);
            }
            seriesToIFD = true;
        }
    }

    List<String> timestamps = null;
    MetamorphHandler handler = null;

    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);

    if (isHCS) {
        store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
        store.setPlateRows(new PositiveInteger(rows), 0);
        store.setPlateColumns(new PositiveInteger(cols), 0);
        store.setPlateRowNamingConvention(NamingConvention.LETTER, 0);
        store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0);
    }

    int nextObjective = 0;
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    String detectorID = MetadataTools.createLSID("Detector", 0, 0);

    store.setInstrumentID(instrumentID, 0);
    store.setDetectorID(detectorID, 0, 0);
    store.setDetectorType(getDetectorType("Other"), 0, 0);

    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        // do not reparse the same XML for every well
        if (i == 0 || !isHCS) {
            handler = new MetamorphHandler(getSeriesMetadata());
        }

        if (isHCS) {
            String label = stageLabels[i];
            String wellID = MetadataTools.createLSID("Well", 0, i);
            store.setWellID(wellID, 0, i);
            store.setWellColumn(new NonNegativeInteger(colMap.get(label)), 0, i);
            store.setWellRow(new NonNegativeInteger(rowMap.get(label)), 0, i);
            store.setWellSampleID(MetadataTools.createLSID("WellSample", 0, i, 0), 0, i, 0);
            store.setWellSampleImageRef(MetadataTools.createLSID("Image", i), 0, i, 0);
            store.setWellSampleIndex(new NonNegativeInteger(i), 0, i, 0);
        }

        store.setImageInstrumentRef(instrumentID, i);

        String comment = getFirstComment(i);
        if (i == 0 || !isHCS) {
            if (comment != null && comment.startsWith("<MetaData>")) {
                try {
                    XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler);
                } catch (IOException e) {
                }
            }
        }

        if (creationTime != null) {
            String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT, ".");
            if (date != null) {
                store.setImageAcquisitionDate(new Timestamp(date), 0);
            }
        }

        store.setImageName(makeImageName(i).trim(), i);

        if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
            continue;
        }
        store.setImageDescription("", i);

        store.setImagingEnvironmentTemperature(new Temperature(handler.getTemperature(), UNITS.CELSIUS), i);

        if (sizeX == null)
            sizeX = handler.getPixelSizeX();
        if (sizeY == null)
            sizeY = handler.getPixelSizeY();

        Length physicalSizeX = FormatTools.getPhysicalSizeX(sizeX);
        Length physicalSizeY = FormatTools.getPhysicalSizeY(sizeY);
        if (physicalSizeX != null) {
            store.setPixelsPhysicalSizeX(physicalSizeX, i);
        }
        if (physicalSizeY != null) {
            store.setPixelsPhysicalSizeY(physicalSizeY, i);
        }
        if (zDistances != null) {
            stepSize = zDistances[0];
        } else {
            List<Double> zPositions = new ArrayList<Double>();
            final List<Double> uniqueZ = new ArrayList<Double>();

            for (IFD ifd : ifds) {
                MetamorphHandler zPlaneHandler = new MetamorphHandler();

                String zComment = ifd.getComment();
                if (zComment != null && zComment.startsWith("<MetaData>")) {
                    try {
                        XMLTools.parseXML(XMLTools.sanitizeXML(zComment), zPlaneHandler);
                    } catch (IOException e) {
                    }
                }

                zPositions = zPlaneHandler.getZPositions();
                for (Double z : zPositions) {
                    if (!uniqueZ.contains(z))
                        uniqueZ.add(z);
                }
            }
            if (uniqueZ.size() > 1 && uniqueZ.size() == getSizeZ()) {
                BigDecimal lastZ = BigDecimal.valueOf(uniqueZ.get(uniqueZ.size() - 1));
                BigDecimal firstZ = BigDecimal.valueOf(uniqueZ.get(0));
                BigDecimal zRange = (lastZ.subtract(firstZ)).abs();
                BigDecimal zSize = BigDecimal.valueOf((double) (getSizeZ() - 1));
                MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
                stepSize = zRange.divide(zSize, mc).doubleValue();
            }
        }

        Length physicalSizeZ = FormatTools.getPhysicalSizeZ(stepSize);
        if (physicalSizeZ != null) {
            store.setPixelsPhysicalSizeZ(physicalSizeZ, i);
        }

        if (handler.getLensNA() != 0 || handler.getLensRI() != 0) {
            String objectiveID = MetadataTools.createLSID("Objective", 0, nextObjective);
            store.setObjectiveID(objectiveID, 0, nextObjective);
            if (handler.getLensNA() != 0) {
                store.setObjectiveLensNA(handler.getLensNA(), 0, nextObjective);
            }
            store.setObjectiveSettingsID(objectiveID, i);
            if (handler.getLensRI() != 0) {
                store.setObjectiveSettingsRefractiveIndex(handler.getLensRI(), i);
            }
            nextObjective++;
        }

        int waveIndex = 0;
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (firstSeriesChannels == null || (stageNames != null && stageNames.size() == getSeriesCount())) {
                waveIndex = c;
            } else if (firstSeriesChannels != null) {
                int s = i % 2;
                while (firstSeriesChannels[waveIndex] == (s == 1) && waveIndex < firstSeriesChannels.length) {
                    waveIndex++;
                }
            }

            if (waveNames != null && waveIndex < waveNames.size()) {
                store.setChannelName(waveNames.get(waveIndex).trim(), i, c);
            }
            if (handler.getBinning() != null)
                binning = handler.getBinning();
            if (binning != null) {
                store.setDetectorSettingsBinning(getBinning(binning), i, c);
            }
            if (handler.getReadOutRate() != 0) {
                store.setDetectorSettingsReadOutRate(new Frequency(handler.getReadOutRate(), UNITS.HERTZ), i,
                        c);
            }

            if (gain == null) {
                gain = handler.getGain();
            }

            if (gain != null) {
                store.setDetectorSettingsGain(gain, i, c);
            }
            store.setDetectorSettingsID(detectorID, i, c);

            if (wave != null && waveIndex < wave.length) {
                Length wavelength = FormatTools.getWavelength(wave[waveIndex]);

                if ((int) wave[waveIndex] >= 1) {
                    // link LightSource to Image
                    int laserIndex = i * getEffectiveSizeC() + c;
                    String lightSourceID = MetadataTools.createLSID("LightSource", 0, laserIndex);
                    store.setLaserID(lightSourceID, 0, laserIndex);
                    store.setChannelLightSourceSettingsID(lightSourceID, i, c);
                    store.setLaserType(getLaserType("Other"), 0, laserIndex);
                    store.setLaserLaserMedium(getLaserMedium("Other"), 0, laserIndex);

                    if (wavelength != null) {
                        store.setChannelLightSourceSettingsWavelength(wavelength, i, c);
                    }
                }
            }
            waveIndex++;
        }

        timestamps = handler.getTimestamps();

        for (int t = 0; t < timestamps.size(); t++) {
            String date = DateTools.convertDate(DateTools.getTime(timestamps.get(t), SHORT_DATE_FORMAT, "."),
                    DateTools.UNIX, SHORT_DATE_FORMAT + ".SSS");
            addSeriesMetaList("timestamp", date);
        }

        long startDate = 0;
        if (timestamps.size() > 0) {
            startDate = DateTools.getTime(timestamps.get(0), SHORT_DATE_FORMAT, ".");
        }

        final Length positionX = handler.getStagePositionX();
        final Length positionY = handler.getStagePositionY();
        final List<Double> exposureTimes = handler.getExposures();
        if (exposureTimes.size() == 0) {
            for (int p = 0; p < getImageCount(); p++) {
                exposureTimes.add(exposureTime);
            }
        } else if (exposureTimes.size() == 1 && exposureTimes.size() < getEffectiveSizeC()) {
            for (int c = 1; c < getEffectiveSizeC(); c++) {
                MetamorphHandler channelHandler = new MetamorphHandler();

                String channelComment = getComment(i, c);
                if (channelComment != null && channelComment.startsWith("<MetaData>")) {
                    try {
                        XMLTools.parseXML(XMLTools.sanitizeXML(channelComment), channelHandler);
                    } catch (IOException e) {
                    }
                }

                final List<Double> channelExpTime = channelHandler.getExposures();
                exposureTimes.add(channelExpTime.get(0));
            }
        }

        int lastFile = -1;
        IFDList lastIFDs = null;
        IFD lastIFD = null;

        double distance = zStart;
        TiffParser tp = null;
        RandomAccessInputStream stream = null;

        for (int p = 0; p < getImageCount(); p++) {
            int[] coords = getZCTCoords(p);
            Double deltaT = 0d;
            Double expTime = exposureTime;
            Double xmlZPosition = null;

            int fileIndex = getIndex(0, coords[1], coords[2]) / getSizeZ();
            if (fileIndex >= 0) {
                String file = stks == null ? currentId : stks[i][fileIndex];
                if (file != null) {
                    if (fileIndex != lastFile) {
                        if (stream != null) {
                            stream.close();
                        }
                        stream = new RandomAccessInputStream(file, 16);
                        tp = new TiffParser(stream);
                        tp.checkHeader();
                        IFDList f = tp.getMainIFDs();
                        if (f.size() > 0) {
                            lastFile = fileIndex;
                            lastIFDs = f;
                        } else {
                            file = null;
                            stks[i][fileIndex] = null;
                        }
                    }
                }

                if (file != null) {
                    lastIFD = lastIFDs.get(p % lastIFDs.size());
                    Object commentEntry = lastIFD.get(IFD.IMAGE_DESCRIPTION);
                    if (commentEntry != null) {
                        if (commentEntry instanceof String) {
                            comment = (String) commentEntry;
                        } else if (commentEntry instanceof TiffIFDEntry) {
                            comment = tp.getIFDValue((TiffIFDEntry) commentEntry).toString();
                        }
                    }
                    if (comment != null)
                        comment = comment.trim();
                    if (comment != null && comment.startsWith("<MetaData>")) {
                        String[] lines = comment.split("\n");

                        timestamps = new ArrayList<String>();

                        for (String line : lines) {
                            line = line.trim();
                            if (line.startsWith("<prop")) {
                                int firstQuote = line.indexOf("\"") + 1;
                                int lastQuote = line.lastIndexOf("\"");
                                String key = line.substring(firstQuote, line.indexOf("\"", firstQuote));
                                String value = line.substring(line.lastIndexOf("\"", lastQuote - 1) + 1,
                                        lastQuote);

                                if (key.equals("z-position")) {
                                    xmlZPosition = new Double(value);
                                } else if (key.equals("acquisition-time-local")) {
                                    timestamps.add(value);
                                }
                            }
                        }
                    }
                }
            }

            int index = 0;

            if (timestamps.size() > 0) {
                if (coords[2] < timestamps.size())
                    index = coords[2];
                String stamp = timestamps.get(index);
                long ms = DateTools.getTime(stamp, SHORT_DATE_FORMAT, ".");
                deltaT = (ms - startDate) / 1000.0;
            } else if (internalStamps != null && p < internalStamps.length) {
                long delta = internalStamps[p] - internalStamps[0];
                deltaT = delta / 1000.0;
                if (coords[2] < exposureTimes.size())
                    index = coords[2];
            }

            if (index == 0 && p > 0 && exposureTimes.size() > 0) {
                index = coords[1] % exposureTimes.size();
            }

            if (index < exposureTimes.size()) {
                expTime = exposureTimes.get(index);
            }
            if (deltaT != null) {
                store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), i, p);
            }
            if (expTime != null) {
                store.setPlaneExposureTime(new Time(expTime, UNITS.SECOND), i, p);
            }

            if (stageX != null && p < stageX.length) {
                store.setPlanePositionX(stageX[p], i, p);
            } else if (positionX != null) {
                store.setPlanePositionX(positionX, i, p);
            }
            if (stageY != null && p < stageY.length) {
                store.setPlanePositionY(stageY[p], i, p);
            } else if (positionY != null) {
                store.setPlanePositionY(positionY, i, p);
            }
            if (zDistances != null && p < zDistances.length) {
                if (p > 0) {
                    if (zDistances[p] != 0d)
                        distance += zDistances[p];
                    else
                        distance += zDistances[0];
                }
                final Length zPos = new Length(distance, UNITS.REFERENCEFRAME);
                store.setPlanePositionZ(zPos, i, p);
            } else if (xmlZPosition != null) {
                final Length zPos = new Length(xmlZPosition, UNITS.REFERENCEFRAME);
                store.setPlanePositionZ(zPos, i, p);
            }
        }

        if (stream != null) {
            stream.close();
        }
    }
    setSeries(0);
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * {@link java.math.BigDecimal#setScale(int, RoundingMode)}.
 *
 * @param o the object, number or string.
 * @param scale scale of fraction./* w w  w .ja v a  2 s  .  co m*/
 * @param type return type.
 * @return {@code o.setScale(scale, mode)}.
 */
public static <T extends Number> T round(final Object o, final Number scale, RoundingMode mode, Class<T> type) {
    return setScale(o, scale, mode == null ? RoundingMode.HALF_UP : mode, type);
}

From source file:com.baitouwei.swiperefresh.ASwipeRefreshLayout.java

/**
 * compute offset percent when animating
 *
 * @param currentPercent//from  w  ww  .j a  v  a 2s  .co m
 * @param isToStart
 * @param animatedFraction
 */
private void computeOffsetPercent(float currentPercent, boolean isToStart, float animatedFraction) {
    float percent = currentPercent;
    if (isSwipeDown) {
        if (isToStart) {
            percent = new BigDecimal(0).subtract(new BigDecimal(percent))
                    .multiply(new BigDecimal(animatedFraction)).add(new BigDecimal(percent))
                    .setScale(3, RoundingMode.HALF_UP).floatValue();
            percent = Math.max(0, percent);
        } else {
            percent = new BigDecimal(1).subtract(new BigDecimal(percent))
                    .multiply(new BigDecimal(animatedFraction)).add(new BigDecimal(percent))
                    .setScale(3, RoundingMode.HALF_UP).floatValue();
            percent = Math.min(1, percent);
        }
        if (percent != headerView.getPercent()) {
            headerView.updatePercent(percent);
        }
    } else {
        if (isToStart) {
            percent = new BigDecimal(0).subtract(new BigDecimal(percent))
                    .multiply(new BigDecimal(animatedFraction)).add(new BigDecimal(percent))
                    .setScale(3, RoundingMode.HALF_UP).floatValue();
            percent = Math.max(0, percent);
        } else {
            percent = new BigDecimal(1).subtract(new BigDecimal(dragPercent))
                    .multiply(new BigDecimal(animatedFraction)).add(new BigDecimal(percent))
                    .setScale(3, RoundingMode.HALF_UP).floatValue();
            percent = Math.min(1, percent);
        }
        footerView.updatePercent(percent);
    }
}