Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelAttributesImportServiceImpl.java

/**
 * This method sets the bounds for NumberATs
 * @param numberAttData contains informations about the new values.
 * @param numberAt the attribute, which should be updated.
 * @param userLog the processing log for saving import messages
 *//*from   w w w.  j a  va  2s . c  om*/
private void setBounds(NumberAttData numberAttData, NumberAT numberAt, ProcessingLog userLog) {
    CellValueHolder lowerBound = numberAttData.getLowerBound();
    CellValueHolder upperBound = numberAttData.getUpperBound();

    String low = lowerBound.getAttributeValue();
    BigDecimal lower = null;
    if (StringUtils.isNotBlank(low)) {
        try {
            lower = new BigDecimal(low);
        } catch (NumberFormatException e) {
            userLog.error("[{0}] Invalid formalt for lower bound: {1}", lowerBound.getCellRef(), low);
            LOGGER.debug(e);
        }
    }
    String up = upperBound.getAttributeValue();
    BigDecimal upper = null;
    if (StringUtils.isNotBlank(up)) {
        try {
            upper = new BigDecimal(up);
        } catch (NumberFormatException e) {
            userLog.error("[{0}] Invalid formalt for upper bound: {1}", upperBound.getCellRef(), up);
            LOGGER.debug(e);
        }
    }

    if (lower != null && upper != null && lower.compareTo(upper) > 0) {
        userLog.error("[{0}] The upper bound ({1}) is smaller than the lower bound ({2}). Cant set values",
                lowerBound.getCellRef(), upper, lower);
        lower = null;
        upper = null;
    }

    numberAt.setMinValue(lower);
    numberAt.setMaxValue(upper);
}

From source file:service.AdService.java

public void create(Boolean isAutherized, Long catId, String email, String phone, String price,
        MultipartFile previews[], String name, String desc, Long booleanIds[], String booleanVals[],
        Long stringIds[], String stringVals[], Long numIds[], String snumVals[], Long dateIds[],
        Date dateVals[], Long selIds[], Long selVals[], Long multyIds[], String multyVals[], Date dateFrom,
        Date dateTo, Long localIds[]) throws IOException {
    Boolean newUser = false;/*  w ww  . j a v a 2s  .com*/
    if (catId != null) {
        Category cat = catDao.find(catId);
        if (cat != null) {
            if (isAutherized || (!isAutherized && email != null && !email.equals(""))) {

                PhoneEditor phe = new PhoneEditor();
                phone = phe.getPhone(phone);
                addError(phe.error);

                if ((phone == null || phone.equals("")) && (email == null || email.equals(""))) {
                    addError(
                            "  email    ? ");
                }

                User user = userService.getUserByMail(email);
                if (!isAutherized && user == null) {
                    user = userService.registerStandardUser(email);
                    newUser = true;
                    List<String> userErrors = userService.getErrors();
                    if (!userErrors.isEmpty()) {
                        for (String er : userErrors) {
                            addError("user_service: " + er + "; ");
                        }
                    }
                }
                Ad ad = new Ad();
                ad.setInsertDate(new Date());
                ad.setShowCount((long) 0);
                ad.setStatus(Ad.NEW);
                ad.setDateFrom(dateFrom);
                ad.setDateTo(dateTo);
                ad.setEmail(email);
                ad.setPhone(phone);

                ad.setAuthor(user);

                ad.setCat(cat);

                Set<Locality> locals = new HashSet();
                /*if (region != null) {
                 if (region.isAllRussia()) {
                 locals.addAll(locDao.getAll());
                 } else {
                 locals.addAll(region.getLocalities());
                 }
                 }*/
                if (localIds != null && localIds.length > 0) {
                    locals.addAll(locDao.getLocs(localIds));
                } else {
                    addError("  ?   ");
                }
                ad.setLocalities(locals);
                ad.setName(name);
                ad.setDescription(desc);
                ad.setPrice(getNumFromString(price, true));
                ad.setValues(new HashSet());
                if (validate(ad) && getErrors().isEmpty()) {
                    adDao.save(ad);

                    List<Long> reqParamIds = catDao.getRequiredParamsIds(catId);
                    List<Parametr> catParams = paramDao.getParamsFromCat(catId);
                    int i = 0;
                    ArrayList<String> paramValsErrs = new ArrayList();
                    // ? ??  ? ?  ? ??,  ?, ? ?  
                    //? ad

                    ArrayList<ParametrValue> list4Save = new ArrayList();

                    //      
                    if (booleanIds != null) {
                        if (booleanVals == null) {
                            booleanVals = new String[booleanIds.length];
                        }
                        while (i < booleanIds.length) {
                            Parametr p = paramDao.find(booleanIds[i]);
                            if (catParams.contains(p) && Parametr.BOOL == p.getParamType()) {
                                Long val = ParametrValue.NO;
                                String sval = "";
                                if (booleanVals[i] != null) {
                                    val = ParametrValue.YES;
                                    sval = "";
                                }
                                ParametrValue pv = new ParametrValue();
                                pv.setAd(ad);
                                pv.setParametr(p);
                                pv.setSelectVal(val);
                                pv.setStringVal(sval);
                                if (validate(pv)) {
                                    list4Save.add(pv);
                                }

                            }
                            i++;
                        }
                    }

                    if (stringVals != null && stringVals.length > 0) {
                        i = 0;
                        while (i < stringIds.length) {
                            Long paramId = stringIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.TEXT == p.getParamType()) {
                                String val = stringVals[i];
                                if (val != null && !val.equals("")) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }

                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setStringVal(val);
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    if (snumVals != null && snumVals.length > 0) {
                        i = 0;
                        while (i < numIds.length) {
                            Long paramId = numIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.NUM == p.getParamType()) {
                                String sval = snumVals[i];
                                if (sval != null && !sval.equals("")) {
                                    Double val = getNumFromString(sval, true);
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setNumVal(val);
                                    pv.setStringVal(StringAdapter.getString(val));
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                        if (!getErrors().isEmpty()) {
                            for (String e : getErrors()) {
                                paramValsErrs.add(e);
                            }
                        }
                    }

                    if (dateVals != null && dateVals.length > 0) {
                        i = 0;
                        while (i < dateIds.length) {
                            Long paramId = dateIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.DATE == p.getParamType()) {
                                Date val = dateVals[i];
                                if (val != null) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setDateVal(val);
                                    pv.setStringVal(DateAdapter.formatByDate(val, DateAdapter.SMALL_FORMAT));
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    if (selVals != null && selVals.length > 0) {
                        i = 0;

                        while (i < selIds.length) {
                            Long paramId = selIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.SELECTING == p.getParamType()) {
                                Long val = selVals[i];
                                if (val != null && !val.equals(0L)) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setSelectVal(val);
                                    pv.setStringVal(paramSelDao.find(val).getName());
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    //?  ?
                    //TO DO       (??)
                    if (multyVals != null && multyVals.length > 0) {
                        for (String rawVal : multyVals) {
                            String idValArr[] = rawVal.split("_");
                            if (idValArr.length == 2) {
                                String strId = idValArr[0];
                                String strVal = idValArr[1];
                                Long paramId = Long.valueOf(strId);
                                Long val = Long.valueOf(strVal);
                                Parametr p = paramDao.find(paramId);
                                if (catParams.contains(p) && Parametr.MULTISELECTING == p.getParamType()) {
                                    if (reqParamIds.contains(paramId) && val != null) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setSelectVal(val);
                                    pv.setStringVal(paramSelDao.find(val).getName());
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }
                                }
                            }
                        }
                    }

                    //?  ?    ?    ?
                    if (!reqParamIds.isEmpty() || !paramValsErrs.isEmpty()) {
                        for (Long id : reqParamIds) {
                            addError("    "
                                    + paramDao.find(id).getName() + "; ");
                        }
                        //?
                        adDao.delete(ad);
                    } else {

                        for (ParametrValue pv : list4Save) {
                            paramValueDao.save(pv);
                        }

                        File file = new File("/usr/local/seller/preview/" + ad.getId() + "/");
                        if (file.exists()) {
                            for (File f : file.listFiles()) {
                                f.delete();
                            }
                            file.delete();
                        }
                        file.mkdirs();
                        if (previews != null && previews.length > 0) {
                            i = 0;
                            while (i < 10 && i < previews.length) {
                                MultipartFile prev = previews[i];
                                if (prev != null && 0L < prev.getSize()) {
                                    if (prev.getSize() <= (long) 3 * 1024 * 1024) {
                                        File f = new File(
                                                "/usr/local/seller/preview/" + ad.getId() + "/supPreview");
                                        if (f.exists()) {
                                            f.delete();
                                        }
                                        prev.transferTo(f);
                                        //to do  ? - ??
                                        try {
                                            BufferedImage bi = ImageIO.read(f);
                                            BigDecimal x = BigDecimal.valueOf(0);
                                            BigDecimal y = BigDecimal.valueOf(0);
                                            BigDecimal h = BigDecimal.valueOf(bi.getHeight());
                                            BigDecimal w = BigDecimal.valueOf(bi.getWidth());
                                            if (h.compareTo(w) > 0) {
                                                y = (h.subtract(w)).divide(BigDecimal.valueOf(2),
                                                        RoundingMode.HALF_UP);
                                                h = w;
                                            } else if (h.compareTo(w) < 0) {
                                                x = (w.subtract(h)).divide(BigDecimal.valueOf(2),
                                                        RoundingMode.HALF_UP);
                                                w = h;
                                            }
                                            bi = bi.getSubimage(x.intValue(), y.intValue(), w.intValue(),
                                                    h.intValue());
                                            f.delete();
                                            f = new File("/usr/local/seller/preview/" + ad.getId() + "/" + i);
                                            ImageIO.write(bi, "png", f);
                                        } catch (Exception e) {
                                            addError(
                                                    "? ?   "
                                                            + prev.getName()
                                                            + /*"; s="+prev.getSize()+"; t="+prev.getContentType()+"; l="+previews.length+*/ "; "
                                                            + StringAdapter.getStackTraceException(e));
                                        }
                                    } else {
                                        addError(" " + prev.getName()
                                                + "   ,      ?  3 .");
                                    }
                                }
                                i++;
                            }
                        }

                        if (newUser) {
                            userService.notifyAboutRegistration(email);
                        }
                    }

                } /* else {
                  addError("user:" + user.getId() + " " + user.getName());
                  }*/

            } else {
                addError(
                        "?  ??     email");
            }
        } else {
            addError("? ?  " + catId + "   .");
        }
    } else {
        addError("?  ");
    }
}

From source file:com.farouk.projectapp.FirstGUI.java

private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
    if (jTextField6.getText().isEmpty() || jTextField7.getText().isEmpty()) {
        JOptionPane.showMessageDialog(rootPane, "Please enter a valid input.", "Error", WIDTH);
    } else {/*www .j  ava2s  .c om*/
        try {
            String coMname = jTextField6.getText();
            int quantity = Integer.parseInt(jTextField7.getText());
            if (quantity < 0) {
                JOptionPane.showMessageDialog(rootPane, "Enter a positive number.", "No!", WIDTH);
            } else {
                BigDecimal a = Simulate.simulateBuy(coMname, quantity, userID);
                String name = SQLConnect.getSymbolOfCompanyFromDB(coMname);
                if (a.compareTo(SQLConnect.getBudgetFromDB(userID)) == -1) {
                    SQLConnect.updateQuantityOfComapnyAfterBuy(name, quantity, userID);
                    jTabbedPane1.remove(2);
                    UpdatejTable2();

                    SQLConnect.registerTotalChanges(userID, total);
                    drawChart();
                    jLabel12.setText("Your current buy limit is :"
                            + String.valueOf(SQLConnect.getBudgetFromDB(userID).doubleValue()) + ".");
                } else if (a.compareTo(SQLConnect.getBudgetFromDB(userID)) == 1) {
                    JOptionPane.showMessageDialog(rootPane,
                            "Sorry, You'll exceed your limit if you make this purchase.", "Warning", WIDTH);
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "Please enter a number", "No!", WIDTH);
        }

    }
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
 * Mthode ralisant l'export SI - Agresso des en-ttes pour les journaux de type vente
 * @param mlr/*  w  ww .j a  v  a  2s  .  com*/
 * @param replay
 * @throws AxelorException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public void exportMoveLineTypeSelect1006FILE1(MoveLineReport moveLineReport, boolean replay)
        throws AxelorException, IOException {

    log.info("In export service Type 1006 FILE 1 :");

    Company company = moveLineReport.getCompany();

    String dateQueryStr = String.format(" WHERE self.company = %s", company.getId());
    JournalType journalType = moveLineReportService.getJournalType(moveLineReport);
    if (moveLineReport.getJournal() != null) {
        dateQueryStr += String.format(" AND self.journal = %s", moveLineReport.getJournal().getId());
    } else {
        dateQueryStr += String.format(" AND self.journal.type = %s", journalType.getId());
    }
    if (moveLineReport.getPeriod() != null) {
        dateQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (replay) {
        dateQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        dateQueryStr += " AND self.accountingOk = false ";
    }
    dateQueryStr += " AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false ";
    dateQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);
    Query dateQuery = JPA.em().createQuery(
            "SELECT self.date from Move self" + dateQueryStr + "group by self.date order by self.date");

    List<LocalDate> allDates = new ArrayList<LocalDate>();
    allDates = dateQuery.getResultList();

    log.debug("allDates : {}", allDates);

    List<String[]> allMoveData = new ArrayList<String[]>();
    String companyCode = "";

    String reference = "";
    String moveQueryStr = "";
    String moveLineQueryStr = "";
    if (moveLineReport.getRef() != null) {
        reference = moveLineReport.getRef();
    }
    if (company != null) {
        companyCode = company.getCode();
        moveQueryStr += String.format(" AND self.company = %s", company.getId());
    }
    if (moveLineReport.getPeriod() != null) {
        moveQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (moveLineReport.getDateFrom() != null) {
        moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString());
    }
    if (moveLineReport.getDateTo() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }
    if (replay) {
        moveQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        moveQueryStr += " AND self.accountingOk = false ";
    }
    moveQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);

    LocalDate interfaceDate = moveLineReport.getDate();

    for (LocalDate dt : allDates) {

        List<Journal> journalList = journalRepo.all()
                .filter("self.type = ?1 AND self.notExportOk = false", journalType).fetch();

        if (moveLineReport.getJournal() != null) {
            journalList = new ArrayList<Journal>();
            journalList.add(moveLineReport.getJournal());
        }

        for (Journal journal : journalList) {

            List<? extends Move> moveList = moveRepo.all().filter(
                    "self.date = ?1 AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false AND self.journal = ?2"
                            + moveQueryStr,
                    dt, journal).fetch();

            String journalCode = journal.getExportCode();

            if (moveList.size() > 0) {

                BigDecimal sumDebit = this.getSumDebit(
                        "self.account.reconcileOk = true AND self.debit != 0.00 AND self.move in ?1 "
                                + moveLineQueryStr,
                        moveList);

                if (sumDebit.compareTo(BigDecimal.ZERO) == 1) {

                    String exportNumber = this.getSaleExportNumber(company);

                    Move firstMove = moveList.get(0);
                    String periodCode = firstMove.getPeriod().getFromDate().format(MONTH_FORMAT);

                    this.updateMoveList((List<Move>) moveList, moveLineReport, interfaceDate, exportNumber);

                    String items[] = new String[8];
                    items[0] = companyCode;
                    items[1] = journalCode;
                    items[2] = exportNumber;
                    items[3] = interfaceDate.format(DATE_FORMAT);
                    items[4] = sumDebit.toString();
                    items[5] = reference;
                    items[6] = dt.format(DATE_FORMAT);
                    items[7] = periodCode;
                    allMoveData.add(items);
                }
            }
        }
    }

    String fileName = "entete" + todayTime.format(DATE_TIME_FORMAT) + "ventes.dat";
    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    new File(filePath).mkdirs();

    log.debug("Full path to export : {}{}", filePath, fileName);
    CsvTool.csvWriter(filePath, fileName, '|', null, allMoveData);
    // Utilis pour le debuggage
    //         CsvTool.csvWriter(filePath, fileName, '|', this.createHeaderForHeaderFile(mlr.getTypeSelect()), allMoveData);
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
 * Mthode ralisant l'export SI - Agresso des en-ttes pour les journaux de type avoir
 * @param mlr//w  w w  . jav a 2 s.com
 * @param replay
 * @throws AxelorException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public void exportMoveLineTypeSelect1007FILE1(MoveLineReport moveLineReport, boolean replay)
        throws AxelorException, IOException {

    log.info("In export service 1007 FILE 1:");

    Company company = moveLineReport.getCompany();

    String dateQueryStr = String.format(" WHERE self.company = %s", company.getId());
    JournalType journalType = moveLineReportService.getJournalType(moveLineReport);
    if (moveLineReport.getJournal() != null) {
        dateQueryStr += String.format(" AND self.journal = %s", moveLineReport.getJournal().getId());
    } else {
        dateQueryStr += String.format(" AND self.journal.type = %s", journalType.getId());
    }
    if (moveLineReport.getPeriod() != null) {
        dateQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (replay) {
        dateQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        dateQueryStr += " AND self.accountingOk = false ";
    }
    dateQueryStr += " AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false ";
    dateQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);
    Query dateQuery = JPA.em().createQuery(
            "SELECT self.date from Move self" + dateQueryStr + "group by self.date order by self.date");

    List<LocalDate> allDates = new ArrayList<LocalDate>();
    allDates = dateQuery.getResultList();

    log.debug("allDates : {}", allDates);

    List<String[]> allMoveData = new ArrayList<String[]>();
    String companyCode = "";

    String reference = "";
    String moveQueryStr = "";
    String moveLineQueryStr = "";
    if (moveLineReport.getRef() != null) {
        reference = moveLineReport.getRef();
    }
    if (moveLineReport.getCompany() != null) {
        companyCode = moveLineReport.getCompany().getCode();
        moveQueryStr += String.format(" AND self.company = %s", moveLineReport.getCompany().getId());
    }
    if (moveLineReport.getPeriod() != null) {
        moveQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (moveLineReport.getDateFrom() != null) {
        moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString());
    }
    if (moveLineReport.getDateTo() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }
    if (replay) {
        moveQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        moveQueryStr += " AND self.accountingOk = false ";
    }
    moveQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);

    LocalDate interfaceDate = moveLineReport.getDate();

    for (LocalDate dt : allDates) {

        List<Journal> journalList = journalRepo.all()
                .filter("self.type = ?1 AND self.notExportOk = false", journalType).fetch();

        if (moveLineReport.getJournal() != null) {
            journalList = new ArrayList<Journal>();
            journalList.add(moveLineReport.getJournal());
        }

        for (Journal journal : journalList) {

            List<Move> moveList = moveRepo.all().filter(
                    "self.date = ?1 AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false AND self.journal = ?2"
                            + moveQueryStr,
                    dt, journal).fetch();

            String journalCode = journal.getExportCode();

            if (moveList.size() > 0) {

                BigDecimal sumCredit = this.getSumCredit(
                        "self.account.reconcileOk = true AND self.credit != 0.00 AND self.move in ?1 "
                                + moveLineQueryStr,
                        moveList);

                if (sumCredit.compareTo(BigDecimal.ZERO) == 1) {

                    String exportNumber = this.getSaleExportNumber(company);

                    Move firstMove = moveList.get(0);
                    String periodCode = firstMove.getPeriod().getFromDate().format(MONTH_FORMAT);

                    this.updateMoveList(moveList, moveLineReport, interfaceDate, exportNumber);

                    String items[] = new String[8];
                    items[0] = companyCode;
                    items[1] = journalCode;
                    items[2] = exportNumber;
                    items[3] = interfaceDate.format(DATE_FORMAT);
                    items[4] = sumCredit.toString();
                    items[5] = reference;
                    items[6] = dt.format(DATE_FORMAT);
                    items[7] = periodCode;
                    allMoveData.add(items);
                }
            }
        }
    }

    String fileName = "entete" + todayTime.format(DATE_TIME_FORMAT) + "avoirs.dat";
    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    new File(filePath).mkdirs();

    log.debug("Full path to export : {}{}", filePath, fileName);
    CsvTool.csvWriter(filePath, fileName, '|', null, allMoveData);
    // Utilis pour le debuggage
    //         CsvTool.csvWriter(filePath, fileName, '|', this.createHeaderForHeaderFile(mlr.getTypeSelect()), allMoveData);
}

From source file:org.efaps.esjp.accounting.transaction.evaluation.DocumentInfo_Base.java

/**
 * Apply exchange gain loss./*from  www  .  j a  v a2 s .  c  o m*/
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @throws EFapsException on error
 */
public void applyExchangeGainLoss(final Parameter _parameter) throws EFapsException {
    final AccountInfo gainAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGEGAIN);
    final AccountInfo lossAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGELOSS);

    if (gainAcc != null && lossAcc != null) {
        final QueryBuilder queryBldr = new QueryBuilder(CISales.Payment);
        queryBldr.addWhereAttrEqValue(CISales.Payment.TargetDocument, getInstance());
        final MultiPrintQuery multi = queryBldr.getPrint();
        final SelectBuilder selDocInst = new SelectBuilder().linkto(CISales.Payment.FromAbstractLink)
                .instance();
        final SelectBuilder selCurInst = new SelectBuilder().linkto(CISales.Payment.CurrencyLink).instance();
        multi.addSelect(selDocInst, selCurInst);
        multi.addAttribute(CISales.Payment.Amount, CISales.Payment.Date);
        multi.execute();
        while (multi.next()) {
            final Instance docInst = multi.getSelect(selDocInst);
            final PrintQuery print = new PrintQuery(docInst);
            final SelectBuilder selDocCurInst = new SelectBuilder()
                    .linkto(CISales.DocumentSumAbstract.RateCurrencyId).instance();
            print.addSelect(selDocCurInst);
            print.addAttribute(CIERP.DocumentAbstract.Date);
            print.execute();
            final Instance curInst = multi.getSelect(selCurInst);
            final Instance docCurInst = print.getSelect(selDocCurInst);
            final DateTime docDate = print.getAttribute(CIERP.DocumentAbstract.Date);
            final DateTime dateTmp = multi.getAttribute(CISales.Payment.Date);
            final BigDecimal amountTmp = multi.getAttribute(CISales.Payment.Amount);

            if (!curInst.equals(Currency.getBaseCurrency()) || !docCurInst.equals(Currency.getBaseCurrency())) {
                final Currency currency = new Currency();
                final RateInfo[] rateInfos1 = currency.evaluateRateInfos(_parameter, dateTmp, curInst,
                        docCurInst);
                final RateInfo[] rateInfos2 = currency.evaluateRateInfos(_parameter, docDate, curInst,
                        docCurInst);
                final int idx;
                // payment in BaseCurreny ==> Document was not BaseCurrency therefore current against target
                if (curInst.equals(Currency.getBaseCurrency())) {
                    idx = 2;
                    // Document in  BaseCurrency ==> payment was not BaseCurrency therefore current against base
                } else if (docCurInst.equals(Currency.getBaseCurrency())) {
                    idx = 0;
                    // neither Document nor payment are BaseCurrency but are the same
                } else if (curInst.equals(docCurInst)) {
                    idx = 0;
                } else {
                    idx = 0;
                }

                final BigDecimal rate1 = RateInfo.getRate(_parameter, rateInfos1[idx],
                        docInst.getType().getName());
                final BigDecimal rate2 = RateInfo.getRate(_parameter, rateInfos2[idx],
                        docInst.getType().getName());
                if (rate1.compareTo(rate2) != 0) {
                    final BigDecimal amount1 = amountTmp.divide(rate1, BigDecimal.ROUND_HALF_UP);
                    final BigDecimal amount2 = amountTmp.divide(rate2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal gainLoss = amount1.subtract(amount2);
                    if (idx == 2) {
                        gainLoss = gainLoss.multiply(rate1);
                    }
                    if (gainLoss.compareTo(BigDecimal.ZERO) != 0) {
                        final boolean out = getInstance().getType()
                                .isKindOf(CISales.PaymentDocumentOutAbstract);
                        if (out) {
                            final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) > 0;
                            for (final AccountInfo accinfo : getCreditAccounts()) {
                                if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) {
                                    final BigDecimal accAmount;
                                    if (accinfo.getRateInfo().getCurrencyInstance()
                                            .equals(Currency.getBaseCurrency())) {
                                        accAmount = gainLoss;
                                    } else {
                                        accAmount = gainLoss.multiply(accinfo.getRate(_parameter));
                                    }
                                    accinfo.addAmount(accAmount.negate());
                                }
                            }
                            if (gain) {
                                gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addCredit(gainAcc);
                            } else {
                                lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addDebit(lossAcc);
                            }
                        } else {
                            final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) < 0;
                            for (final AccountInfo accinfo : getDebitAccounts()) {
                                if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) {
                                    final BigDecimal accAmount;
                                    if (!accinfo.getRateInfo().getCurrencyInstance()
                                            .equals(Currency.getBaseCurrency())) {
                                        accAmount = gainLoss;
                                    } else {
                                        accAmount = gainLoss.multiply(accinfo.getRate(_parameter));
                                    }
                                    accinfo.addAmount(accAmount);
                                }
                            }
                            if (gain) {
                                gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addDebit(gainAcc);
                            } else {
                                lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addCredit(lossAcc);
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:net.sourceforge.fenixedu.domain.credits.util.AnnualTeachingCreditsBean.java

public void calculateCredits() {
    masterDegreeThesesCredits = teacher.getMasterDegreeThesesCredits(executionYear);
    phdDegreeThesesCredits = teacher.getPhdDegreeThesesCredits(executionYear);
    projectsTutorialsCredits = teacher.getProjectsTutorialsCredits(executionYear);

    BigDecimal yearCreditsForFinalCredits = BigDecimal.ZERO;
    BigDecimal annualTeachingLoadFinalCredits = BigDecimal.ZERO;

    boolean hasOrientantionCredits = false;
    boolean hasFinalAndAccumulatedCredits = false;

    for (ExecutionSemester executionSemester : executionYear.getExecutionPeriodsSet()) {
        if (getTeacher().isActiveForSemester(executionSemester)
                || getTeacher().hasTeacherAuthorization(executionSemester)) {
            BigDecimal thisSemesterManagementFunctionCredits = new BigDecimal(
                    getTeacher().getManagementFunctionsCredits(executionSemester));
            managementFunctionCredits = managementFunctionCredits.add(thisSemesterManagementFunctionCredits);
            serviceExemptionCredits = serviceExemptionCredits
                    .add(new BigDecimal(getTeacher().getServiceExemptionCredits(executionSemester)));
            BigDecimal thisSemesterTeachingLoad = new BigDecimal(
                    getTeacher().getMandatoryLessonHours(executionSemester));
            annualTeachingLoad = annualTeachingLoad.add(thisSemesterTeachingLoad).setScale(2,
                    BigDecimal.ROUND_HALF_UP);
            TeacherService teacherService = getTeacher().getTeacherServiceByExecutionPeriod(executionSemester);
            BigDecimal thisSemesterCreditsReduction = BigDecimal.ZERO;
            if (teacherService != null) {
                teachingCredits = teachingCredits
                        .add(new BigDecimal(teacherService.getTeachingDegreeCredits()));
                thisSemesterCreditsReduction = teacherService.getReductionServiceCredits();
                othersCredits = othersCredits.add(new BigDecimal(teacherService.getOtherServiceCredits()));
            }/*from   w w w  .j  a v  a  2 s.  c  o  m*/
            creditsReduction = creditsReduction.add(thisSemesterCreditsReduction);
            BigDecimal reductionAndManagement = thisSemesterManagementFunctionCredits
                    .add(thisSemesterCreditsReduction);
            BigDecimal thisSemesterYearCredits = thisSemesterTeachingLoad;
            if (thisSemesterTeachingLoad.compareTo(reductionAndManagement) > 0) {
                thisSemesterYearCredits = reductionAndManagement;
            } else {
                setHasAnyLimitation(true);
            }
            yearCredits = yearCredits.add(thisSemesterYearCredits);
            if (getTeacher().isActiveForSemester(executionSemester)
                    && !getTeacher().isMonitor(executionSemester)) {
                yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(thisSemesterYearCredits);
                annualTeachingLoadFinalCredits = annualTeachingLoadFinalCredits.add(thisSemesterTeachingLoad);
                if (executionSemester.getSemester() == 2) {
                    hasFinalAndAccumulatedCredits = true;
                } else {
                    hasOrientantionCredits = true;
                }
            }
        }
    }
    yearCredits = yearCredits.add(teachingCredits).add(serviceExemptionCredits).add(othersCredits);
    yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(teachingCredits).add(serviceExemptionCredits)
            .add(othersCredits);
    if (hasOrientantionCredits) {
        yearCredits = yearCredits.add(getMasterDegreeThesesCredits()).add(getPhdDegreeThesesCredits())
                .add(getProjectsTutorialsCredits()).setScale(2, BigDecimal.ROUND_HALF_UP);
        yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(getMasterDegreeThesesCredits())
                .add(getPhdDegreeThesesCredits()).add(getProjectsTutorialsCredits());
    }
    if (hasFinalAndAccumulatedCredits) {
        finalCredits = yearCreditsForFinalCredits.subtract(annualTeachingLoadFinalCredits);
        BigDecimal lastYearAccumulated = getPreviousAccumulatedCredits();
        accumulatedCredits = (finalCredits.add(lastYearAccumulated)).setScale(2, BigDecimal.ROUND_HALF_UP);
        finalCredits = finalCredits.setScale(2, BigDecimal.ROUND_HALF_UP);
    }
}

From source file:op.allowance.PnlAllowance.java

private CollapsiblePane createCP4(final Resident resident) {
    /***/*  ww  w  .  j  a v a2s . c  o m*/
     *                          _        ____ ____  _  _    ______           _     _            _ __
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |  / /  _ \ ___  ___(_) __| | ___ _ __ | |\ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_| || |_) / _ \/ __| |/ _` |/ _ \ '_ \| __| |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| ||  _ <  __/\__ \ | (_| |  __/ | | | |_| |
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_| | ||_| \_\___||___/_|\__,_|\___|_| |_|\__| |
     *                                                     \_\                                    /_/
     */
    final String key = resident.getRID();
    if (!cpMap.containsKey(key)) {
        cpMap.put(key, new CollapsiblePane());
        try {
            cpMap.get(key).setCollapsed(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }

    }
    final CollapsiblePane cpResident = cpMap.get(key);

    if (!carrySums.containsKey(getKey(resident, SYSCalendar.eoy(new LocalDate())))) {
        carrySums.put(getKey(resident, SYSCalendar.eoy(new LocalDate())),
                AllowanceTools.getSUM(resident, SYSCalendar.eoy(new LocalDate())));
    }

    BigDecimal sumOverall = carrySums.get(getKey(resident, SYSCalendar.eoy(new LocalDate())));

    String title = "<html><table border=\"0\">" + "<tr>" +

            "<td width=\"520\" align=\"left\"><font size=+1>" + resident.toString() + "</font></td>"
            + "<td width=\"200\" align=\"right\"><font size=+1"
            + (sumOverall.compareTo(BigDecimal.ZERO) < 0 ? " color=\"red\" " : "") + ">" + cf.format(sumOverall)
            + "</font></td>" +

            "</tr>" + "</table>" +

            "</html>";

    DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                cpResident.setCollapsed(!cpResident.isCollapsed());
            } catch (PropertyVetoException pve) {
                // BAH!
            }
        }
    });

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.ARCHIVE, internalClassID)
            && OPDE.getAppInfo().isAllowedTo(InternalClassACL.PRINT, internalClassID)) {
        /***
         *      ____       _       _   ____           _     _            _
         *     |  _ \ _ __(_)_ __ | |_|  _ \ ___  ___(_) __| | ___ _ __ | |_
         *     | |_) | '__| | '_ \| __| |_) / _ \/ __| |/ _` |/ _ \ '_ \| __|
         *     |  __/| |  | | | | | |_|  _ <  __/\__ \ | (_| |  __/ | | | |_
         *     |_|   |_|  |_|_| |_|\__|_| \_\___||___/_|\__,_|\___|_| |_|\__|
         *
         */
        final JButton btnPrintResident = new JButton(SYSConst.icon22print2);
        btnPrintResident.setPressedIcon(SYSConst.icon22print2Pressed);
        btnPrintResident.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnPrintResident.setContentAreaFilled(false);
        btnPrintResident.setBorder(null);
        btnPrintResident.setToolTipText(SYSTools.xx("admin.residents.cash.btnprintresident.tooltip"));
        btnPrintResident.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                SYSFilesTools.print(
                        AllowanceTools.getAsHTML(AllowanceTools.getAll(resident), BigDecimal.ZERO, resident),
                        true);
            }

        });
        cptitle.getRight().add(btnPrintResident);
    }

    cpResident.setTitleLabelComponent(cptitle.getMain());
    cpResident.setSlidingDirection(SwingConstants.SOUTH);

    /***
     *           _ _      _            _                               _     _            _
     *       ___| (_) ___| | _____  __| |   ___  _ __    _ __ ___  ___(_) __| | ___ _ __ | |_
     *      / __| | |/ __| |/ / _ \/ _` |  / _ \| '_ \  | '__/ _ \/ __| |/ _` |/ _ \ '_ \| __|
     *     | (__| | | (__|   <  __/ (_| | | (_) | | | | | | |  __/\__ \ | (_| |  __/ | | | |_
     *      \___|_|_|\___|_|\_\___|\__,_|  \___/|_| |_| |_|  \___||___/_|\__,_|\___|_| |_|\__|
     *
     */
    cpResident.addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
        @Override
        public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
            // somebody clicks on the name of the resident. the cash informations
            // are loaded from the database, if necessary.
            cpResident.setContentPane(createContentPanel4(resident));
        }
    });
    cpResident.setBackground(getBG(resident, 7));

    if (!cpResident.isCollapsed()) {
        cpResident.setContentPane(createContentPanel4(resident));
    }

    cpResident.setHorizontalAlignment(SwingConstants.LEADING);
    cpResident.setOpaque(false);

    return cpResident;
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java

public boolean isBigDecimalBetween(BigDecimal value, BigDecimal lowBound, BigDecimal upperBound) {
    return value.compareTo(lowBound) > 0 && value.compareTo(upperBound) < 0;
}

From source file:com.nkapps.billing.dao.BankStatementDaoImpl.java

private void insertFizPaymentByDebtor(Session sessionTransaction, Validator validator, BankStatement bs,
        LocalDateTime dateTime, List<String> fizTins) throws Exception {
    BigDecimal fullSum = bs.getPaymentSum();
    BigDecimal keyCost = new BigDecimal(getKeyCost());
    int listSize = fizTins.size();
    int currentIndex = 0;

    for (String fizTin : fizTins) {
        currentIndex++;//  ww  w.  j  ava  2  s .  c  o m
        BigDecimal currentSum;
        if (currentIndex == listSize || fullSum.compareTo(keyCost) < 0) {
            currentSum = fullSum;
            fullSum = BigDecimal.ZERO;
        } else {
            currentSum = keyCost;
            fullSum = fullSum.subtract(keyCost);
        }

        if (currentSum.compareTo(BigDecimal.ZERO) > 0) {
            String tinDebtor = fizTin.equals(bs.getTin()) ? null : bs.getTin();

            Payment payment = new Payment();
            payment.setTin(fizTin);
            payment.setPaymentNum(bs.getPaymentNum());
            payment.setPaymentDate(bs.getPaymentDate());
            payment.setPaymentSum(currentSum);
            payment.setSourceCode((short) 1);
            payment.setState((short) 1);
            payment.setTinDebtor(tinDebtor);
            payment.setClaim((short) 0);
            payment.setDateCreated(dateTime);
            payment.setDateUpdated(dateTime);

            Set<ConstraintViolation<Payment>> constraints = validator.validate(payment);
            if (constraints.isEmpty()) {
                sessionTransaction.save(payment);

                BankStatementPayment bsp = new BankStatementPayment();
                BankStatementPaymentId bspId = new BankStatementPaymentId();
                bspId.setBankStatement(bs);
                bspId.setPayment(payment);
                bsp.setId(bspId);

                sessionTransaction.save(bsp);

            } else {
                throw new Exception("payment isnot valid, tin = " + payment.getTin());
            }
        }
        if (fullSum.compareTo(BigDecimal.ZERO) <= 0) {
            break;
        }
    }

    bs.setTransfered((short) 1);
    sessionTransaction.update(bs);

}