Example usage for java.lang Short intValue

List of usage examples for java.lang Short intValue

Introduction

In this page you can find the example usage for java.lang Short intValue.

Prototype

public int intValue() 

Source Link

Document

Returns the value of this Short as an int after a widening primitive conversion.

Usage

From source file:org.eurocarbdb.action.hplc.ReferenceUpload.java

public String execute() throws Exception {

    List<Ref> allReferences = (List<Ref>) em.getQuery("org.eurocarbdb.dataaccess.hplc.Ref.SELECT_ALL").list();

    for (Ref r : allReferences) {

        Integer pubmed_id = r.getMedUi();
        String author = r.getAuthor();
        String title = r.getTitle();
        Short year = r.getPubYear();
        String journal_name = r.getJournal();
        Integer volume = r.getVolume();
        Integer startPage = r.getStartPage();
        Integer endPage = r.getStartPage();
        Short ogbi = r.getOgbiId();

        int pubyear = year.intValue();
        String pubmedId = pubmed_id.toString();
        String comments = "Generated from GlycoBase entry (published data)";

        JournalReference jr = new JournalReference();
        logger.info("Pubmed Id" + pubmed_id);
        jr.setJournal(Journal.createOrLookup(journal_name));

        jr.setPubmedId(pubmed_id);/*  w ww.ja va 2  s  .  c  om*/
        jr.setAuthors(author);
        jr.setTitle(title);
        jr.setPublicationYear(pubyear);
        jr.setJournalVolume(volume);
        jr.setFirstPage(startPage);
        jr.setLastPage(endPage);
        jr.setContributor(Contributor.getCurrentContributor());
        jr.setReferenceComments(comments);
        logger.info("what the hell");
        jr.storeOrLookup();
        em.flush();
    }

    List<Glycan> allGlycans = (List<Glycan>) em.getQuery("org.eurocarbdb.dataaccess.hplc.Glycan.SELECT_ALL")
            .list();
    for (Glycan g : allGlycans) {
        int glycanId = g.getGlycanId();

        List<RefLink> FindGlycanIdLink = (List<RefLink>) em
                .getQuery("org.eurocarbdb.dataaccess.hplc.RefLink.REFERENCE_IMPORT")
                .setParameter("glycanId", glycanId).list();
        for (Iterator glycanRef = FindGlycanIdLink.iterator(); glycanRef.hasNext();) {
            Object[] referenceStore = (Object[]) glycanRef.next();
            Integer pubmed_id = (Integer) referenceStore[5];
            String pubmedId = pubmed_id.toString();
            Integer ogbi = (Integer) referenceStore[9];
            Integer lookupRefId = (Integer) referenceStore[10];
            GlycanSequence glycanSeq = em.lookup(GlycanSequence.class, ogbi);

            //jrSeq.setPubmedId(pubmed_id);
            //jrSeq.storeOrLookup();

            if (glycanSeq != null) {
                JournalReference jrSeq = JournalReference.createOrLookup(pubmed_id);
                int refId = jrSeq.getReferenceId();
                int glycanSeqId = glycanSeq.getGlycanSequenceId();
                logger.info("test here" + pubmed_id + "refid" + refId);
                logger.info("we are here");
                glycanSeq.addReference(jrSeq);
                logger.info("something here");
                int glycanRefId = jrSeq.getReferenceId();

                int numberUpdates = em
                        .getQuery("org.eurocarbdb.dataaccess.hplc.RefLink.UPDATE_CORE_REFERENCE_ID")
                        .setParameter("glycanId", glycanId).setParameter("storedCoreRefId", glycanRefId)
                        .setParameter("lookupRefId", lookupRefId).executeUpdate();
                em.flush();
            }
        }

    }

    /*List<Glycan> allGlycans = (List<Glycan>) em.getQuery("org.eurocarbdb.dataaccess.hplc.Glycan.SELECT_ALL").list();
    for(Glycan g : allGlycans) {
    //for(Iterator glycanEntry = allGlycans.iterator(); glycanEntry.hasNext();) {
    //Object [] glycanStore = (Object []) glycanEntry.next();
    //Integer glycanId = (Integer) glycanStore[0];
    int glycanId = g.getGlycanId();
            
    List<RefLink> allReferences = (List<RefLink>) em.getQuery("org.eurocarbdb.dataaccess.hplc.RefLink.REFERENCE_IMPORT").setParameter("glycanId", glycanId).list();
        for (Iterator glycanRef = allReferences.iterator(); glycanRef.hasNext();) {
        Object [] referenceStore = (Object []) glycanRef.next();
        Integer pubmed_id = (Integer) referenceStore[5];
        String author = (String) referenceStore[0];
        String title = (String) referenceStore[1];
        Short year = (Short) referenceStore[3];
        String journal_name = (String) referenceStore[2];
        Integer volume = (Integer) referenceStore[4];
        Integer startPage = (Integer) referenceStore[6];
        Integer endPage = (Integer) referenceStore[7];
        Integer ogbi = (Integer) referenceStore[9];
        Integer glycanFound = (Integer) referenceStore[8];
        logger.info("whatthehell" + pubmed_id);
        int pubyear = year.intValue();
        String pubmedId = pubmed_id.toString();   
        String glycanIdConvert = glycanFound.toString();
            
        //String type = "database";
        String comments = "Generated from GlycoBase entry";
        //String refName = "GlycoBaseNIBRT";
            
        logger.info("lookingatglycanid" + glycanFound + "query by" + glycanId);
        logger.info("ogbi translation id" + ogbi);
        JournalReference jr = new JournalReference();
        logger.info("Pubmed Id" + pubmed_id);
        jr.setJournal(Journal.createOrLookup(journal_name));
            
        jr.setPubmedId(pubmed_id);
        jr.setAuthors(author);
        jr.setTitle(title);
        jr.setPublicationYear(pubyear);
        jr.setJournalVolume(volume);
        jr.setFirstPage(startPage);
        jr.setLastPage(endPage);
        jr.setContributor(Contributor.getCurrentContributor());
        jr.setReferenceComments(comments);
            
        //jr.setReferenceType(type);
        //jr.setExternalReferenceName(refName);
            
        jr.storeOrLookup();
        em.flush();
            
        int RefId = jr.getReferenceId();
        logger.info("the returned refId is:" + RefId);
        //Reference r = em.lookup (Reference.class, RefId);
        GlycanSequence glycanSeq =  em.lookup (GlycanSequence.class, ogbi);
        glycanSeq.addReference( jr ); 
    /*
        int RefId = jr.getReferenceId();
        logger.info("the returned refId is:" + RefId);
            
    //if (ogbi > 0 ) {
        //Reference r = em.lookup (Reference.class, RefId);
        GlycanSequence glycanSeq =  em.lookup (GlycanSequence.class, ogbi);
        glycanSeq.addReference( jr );
        //}
      */

    //}

    return SUCCESS;
}

From source file:org.eurocarbdb.action.hplc.refUpload.java

public String execute() throws Exception {

    /*List<RefLink> refList;
    refList = em.getQuery("org.eurocarbdb.dataaccess.hplc.RefLink.SELECT_GROUP_ID").list();
            //from www .  j ava 2s . c  o  m
    //int value = em.getQuery("org.eurocarbdb.dataaccess.hplc.RefLink.SELECT_GROUP_ID").list();
            
    //for (RefLink reference : refList) {
    for (Iterator iterRef = refList.iterator(); iterRef.hasNext();) {
    Object [] refObject = (Object []) iterRef.next();
    Integer refGlycanId = (Integer) refObject[0];
    //int glycanLookup = refs.getGlycanId();
    logger.info("processing glycan:" + refGlycanId);
    */
    int refGlycanIdtest = 1211;
    List<Ref> refInfo = em.getQuery("org.eurocarbdb.dataaccess.hplc.Ref.SELECT_REFERENCES_CORE").list();

    for (Iterator iterRefDetails = refInfo.iterator(); iterRefDetails.hasNext();) {
        Object[] detailsObject = (Object[]) iterRefDetails.next();
        String author = (String) detailsObject[0];
        String title = (String) detailsObject[1];
        String journal_name = (String) detailsObject[2];
        //String volume = (String) detailsObject[3];
        Integer vol = (Integer) detailsObject[3];
        Short year = (Short) detailsObject[4];
        Integer pubmed_id = (Integer) detailsObject[5];
        Integer startPage = (Integer) detailsObject[6];
        Integer endPage = (Integer) detailsObject[7];
        logger.info("error check" + vol + "title" + title + "author" + author);
        //need to convert volume to int
        //int vol = Integer.parseInt(volume);
        //need to convert year 
        int pubyear = year.intValue();
        String pubmedId = pubmed_id.toString();

        String type = "journal";
        String comments = "Generated from GlycoBase entry";
        String refName = "glycobase(dublin)";

        JournalReference jr = new JournalReference();
        /*    Reference newr = new Reference();
            newr.setReferenceType(type);
            newr.setExternalReferenceName(refName);
            newr.setExternalReferenceId(pubmedId);
            newr.storeOrLookup();
        */
        logger.info("Pubmed Id" + pubmed_id);
        jr.setJournal(Journal.createOrLookup(journal_name));

        jr.setPubmedId(pubmed_id);
        jr.setAuthors(author);
        jr.setTitle(title);
        jr.setPublicationYear(pubyear);
        jr.setJournalVolume(vol);
        jr.setFirstPage(startPage);
        jr.setLastPage(endPage);
        jr.setContributor(Contributor.getCurrentContributor());
        jr.setReferenceComments(comments);

        //jr.setReferenceType(type);
        jr.setExternalReferenceName(refName);
        //jr.setExternalReferenceId(pubmedId);
        //Eurocarb.getEntityManager().store(jr);
        jr.storeOrLookup();
    }

    logger.info("successfully added all glycobase references. Now time for Seq-Ref associations");
    //now need to associated each hplc strcture with a reference in the core schema
    /*
            List<Glycan> allGlycans = em.getQuery("org.eurocarbdb.dataaccess.hplc.Glycan.SELECT_ALL").list();
            for (Iterator glycans = allGlycans.iterator(); glycans.hasNext();) {
            Object [] glycanStore = (Object []) glycans.next();
            Integer glycanId = (Integer) glycanStore[0]; 
    */

    //test
    //        
    logger.info("testingareahere");

    logger.info("starting test from here");
    int glycanId = 159;
    logger.info("looking up" + glycanId);
    List<RefLink> allReferences = em.getQuery("org.eurocarbdb.dataaccess.hplc.RefLink.IMPORT_REFERENCE_GWS")
            .setParameter("glycanId", glycanId).list();
    for (Iterator glycanRef = allReferences.iterator(); glycanRef.hasNext();) {
        Object[] referenceStore = (Object[]) glycanRef.next();
        Integer lookupPubmed = (Integer) referenceStore[0];
        Integer lookupTranslationId = (Integer) referenceStore[1];
        Integer lookupRefId = (Integer) referenceStore[3];
        logger.info("ogbi translation id" + lookupTranslationId);
        GlycanSequence glycanSeq = em.lookup(GlycanSequence.class, lookupTranslationId);
        if (glycanSeq != null) {
            logger.info("finding gws with pubmed" + lookupPubmed);
            JournalReference lookupjr = JournalReference.createOrLookup(lookupPubmed);
            // test
            logger.info("check variables" + lookupPubmed + "trans" + lookupTranslationId + "ref" + lookupRefId);
            int storedCoreRefId = lookupjr.getReferenceId();
            logger.info("the reference id dealing with is:" + storedCoreRefId);
            int numberUpdates = em.getQuery("org.eurocarbdb.dataaccess.hplc.RefLink.UPDATE_CORE_REFERENCE_ID")
                    .setParameter("glycanId", glycanId).setParameter("storedCoreRefId", storedCoreRefId)
                    .setParameter("lookupRefId", lookupRefId).executeUpdate();
            // end test
            glycanSeq.addReference(lookupjr);
            /*    getEntityManager().update(lookupjr);
            */ }
    }
    //    }

    /*        logger.info("am i testing");
            //just try getting a reference for a glycan
            int glycanTest = 159;
            GlycanSequence glycanSeqTest =  em.lookup (GlycanSequence.class, glycanTest);
            logger.info("get references for glycan");
            glycanSeqTest.getReferences();
            int sequence_id = glycanSeqTest.getGlycanSequenceId();
            logger.info("i am indeed and the id is:" + sequence_id);
            List<GlycanSequence> glycanReferences = em.getQuery("org.eurocarbdb.dataaccess.core.GlycanSequence.HPLC_REFERENCE").setParameter("sequence_id", sequence_id).list();
            //glycanSeqTest.getReferences();
    */
    return SUCCESS;
}

From source file:org.mifos.accounts.loan.business.LoanBOIntegrationTest.java

public void testCreateNormalLoanAccountWithMonthlyInstallments() throws Exception {
    Short dayOfMonth = (short) 1;

    /*//from   w ww .ja v  a  2  s.  co m
     * A date in the past won't work (we don't yet have a way of telling the
     * validation code "pretend it is such-and-such a date"). The
     * errors.startdateexception message says the date must be less than a
     * year in the future (it really means an end date less than the end of
     * next year).
     */
    long sampleTime = new DateMidnight(2010, 11, 24).getMillis();

    MeetingBO meeting = TestObjectFactory.getNewMeeting(MONTHLY, EVERY_SECOND_MONTH, CUSTOMER_MEETING, MONDAY);
    Calendar meetingStart = Calendar.getInstance();
    meetingStart.setTimeInMillis(sampleTime);
    meeting.setMeetingStartDate(meetingStart.getTime());
    meeting.getMeetingDetails().getMeetingRecurrence().setDayNumber(dayOfMonth);
    TestObjectFactory.createMeeting(meeting);
    center = TestObjectFactory.createWeeklyFeeCenter(this.getClass().getSimpleName() + " Center", meeting);
    group = TestObjectFactory.createWeeklyFeeGroupUnderCenter(this.getClass().getSimpleName() + " Group",
            CustomerStatus.GROUP_ACTIVE, center);
    Date loanStart = new Date(sampleTime);
    LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering("Loan", ApplicableTo.GROUPS, loanStart,
            PrdStatus.LOAN_ACTIVE, 300.0, 1.2, 3, InterestType.FLAT, center.getCustomerMeeting().getMeeting());
    Calendar disbursementDate = new GregorianCalendar();
    disbursementDate.setTimeInMillis(sampleTime);
    int year = disbursementDate.get(Calendar.YEAR);
    int zeroBasedMonth = disbursementDate.get(Calendar.MONTH);
    /*
     * TODO: this "if" is a relic from when sampleTime was based on when the
     * test was run. We should test these two cases somehow.
     */
    if (disbursementDate.get(Calendar.DAY_OF_MONTH) == dayOfMonth.intValue()) {
        disbursementDate = new GregorianCalendar(year, zeroBasedMonth, dayOfMonth);
    } else {
        disbursementDate = new GregorianCalendar(year, zeroBasedMonth + 1, dayOfMonth);
    }
    UserContext userContext = TestUtils.makeUser();
    userContext.setLocaleId(null);
    List<FeeView> feeViewList = new ArrayList<FeeView>();
    FeeBO upfrontFee = TestObjectFactory.createOneTimeRateFee("Upfront Fee", FeeCategory.LOAN,
            Double.valueOf("20"), FeeFormula.AMOUNT, FeePayment.UPFRONT);
    feeViewList.add(new FeeView(userContext, upfrontFee));
    FeeBO disbursementFee = TestObjectFactory.createOneTimeRateFee("Disbursement Fee", FeeCategory.LOAN,
            Double.valueOf("30"), FeeFormula.AMOUNT_AND_INTEREST, FeePayment.TIME_OF_DISBURSEMENT);
    feeViewList.add(new FeeView(userContext, disbursementFee));
    FeeBO firstRepaymentFee = TestObjectFactory.createOneTimeRateFee("First Repayment Fee", FeeCategory.LOAN,
            Double.valueOf("40"), FeeFormula.INTEREST, FeePayment.TIME_OF_FIRSTLOANREPAYMENT);
    feeViewList.add(new FeeView(userContext, firstRepaymentFee));
    FeeBO periodicFee = TestObjectFactory.createPeriodicAmountFee("Periodic Fee", FeeCategory.LOAN, "100",
            RecurrenceType.MONTHLY, Short.valueOf("1"));
    feeViewList.add(new FeeView(userContext, periodicFee));
    accountBO = loanDao.createLoan(TestUtils.makeUser(), loanOffering, group,
            AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(getCurrency(), "300.0"), Short.valueOf("6"),
            disbursementDate.getTime(), false, 1.2, (short) 0, null, feeViewList, null, DOUBLE_ZERO,
            DOUBLE_ZERO, SHORT_ZERO, SHORT_ZERO, false);
    new TestObjectPersistence().persist(accountBO);

    Map<String, String> fees1 = new HashMap<String, String>();
    fees1.put("Periodic Fee", "200.0");

    Map<String, String> fees3 = new HashMap<String, String>();
    fees3.put("Periodic Fee", "100.0");
    fees3.put("Upfront Fee", "60.0");
    fees3.put("First Repayment Fee", "1.5");

    Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO).getAccountActionDates();
    LoanScheduleEntity[] paymentsArray = LoanBOTestUtils.getSortedAccountActionDateEntity(actionDateEntities);

    checkLoanScheduleEntity(null, "50.9", "0.6", fees3, paymentsArray[0]);
    checkLoanScheduleEntity(null, "50.4", "0.6", fees1, paymentsArray[1]);
    checkLoanScheduleEntity(null, "50.4", "0.6", fees1, paymentsArray[2]);
    checkLoanScheduleEntity(null, "50.4", "0.6", fees1, paymentsArray[3]);
    checkLoanScheduleEntity(null, "50.4", "0.6", fees1, paymentsArray[4]);
    checkLoanScheduleEntity(null, "47.5", "1.5", fees1, paymentsArray[5]);

    Assert.assertEquals(4, accountBO.getAccountFees().size());
    for (AccountFeesEntity accountFeesEntity : accountBO.getAccountFees()) {
        if (accountFeesEntity.getFees().getFeeName().equals("Upfront Fee")) {
            Assert.assertEquals(new Money(getCurrency(), "60.0"), accountFeesEntity.getAccountFeeAmount());
            Assert.assertEquals(new Double("20.0"), accountFeesEntity.getFeeAmount());
        } else if (accountFeesEntity.getFees().getFeeName().equals("Disbursement Fee")) {
            // TODO: fee_rounding should there be 2 digits to
            // the right of the decimal here?
            Assert.assertEquals(new Money(getCurrency(), "91.08"), accountFeesEntity.getAccountFeeAmount());
            Assert.assertEquals(new Double("30.0"), accountFeesEntity.getFeeAmount());
        } else if (accountFeesEntity.getFees().getFeeName().equals("First Repayment Fee")) {
            Assert.assertEquals(new Money(getCurrency(), "1.44"), accountFeesEntity.getAccountFeeAmount());
            Assert.assertEquals(new Double("40.0"), accountFeesEntity.getFeeAmount());
        } else {
            Assert.assertEquals(new Money(getCurrency(), "100.0"), accountFeesEntity.getAccountFeeAmount());
            Assert.assertEquals(new Double("100.0"), accountFeesEntity.getFeeAmount());
        }
    }
    LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO).getLoanSummary();
    Assert.assertEquals(new Money(getCurrency(), "300.0"), loanSummaryEntity.getOriginalPrincipal());
    // TODO: fee_rounding is the difference in original interest just
    // a result of compounded rounding adjustments?
    // Assert.assertEquals(new Money(getCurrency(), "3.6"),
    // loanSummaryEntity.getOriginalInterest());
    Assert.assertEquals(new Money(getCurrency(), "4.5"), loanSummaryEntity.getOriginalInterest());
    // Assert.assertEquals(new Money(getCurrency(), "1252.5"),
    // loanSummaryEntity.getOriginalFees());
    Assert.assertEquals(new Money(getCurrency(), "1252.58"), loanSummaryEntity.getOriginalFees());
    Assert.assertEquals(new Money(getCurrency(), "0.0"), loanSummaryEntity.getOriginalPenalty());
}

From source file:org.mifos.accounts.loan.business.LoanBOIntegrationTest.java

public void testDisburseLoanWithAllTypeOfFees() throws Exception {
    Date startDate = new Date(System.currentTimeMillis());
    Short dayOfMonth = (short) 25;
    MeetingBO meeting = TestObjectFactory.getNewMeeting(MONTHLY, EVERY_MONTH, CUSTOMER_MEETING, MONDAY);

    TestObjectFactory.createMeeting(meeting);
    meeting.setMeetingStartDate(new Date());
    meeting.getMeetingDetails().getMeetingRecurrence().setDayNumber(dayOfMonth);
    center = TestObjectFactory.createWeeklyFeeCenter(this.getClass().getSimpleName() + " Center", meeting);
    group = TestObjectFactory.createWeeklyFeeGroupUnderCenter(this.getClass().getSimpleName() + " Group",
            CustomerStatus.GROUP_ACTIVE, center);
    LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering("Loan", ApplicableTo.GROUPS, startDate,
            PrdStatus.LOAN_ACTIVE, 300.0, 1.2, 3, InterestType.FLAT, center.getCustomerMeeting().getMeeting());
    Calendar disbursementDate = new GregorianCalendar();
    int year = disbursementDate.get(Calendar.YEAR);
    int month = disbursementDate.get(Calendar.MONTH);
    int day = 25;
    if (disbursementDate.get(Calendar.DAY_OF_MONTH) == dayOfMonth.intValue()) {
        disbursementDate = new GregorianCalendar(year, month, day);
    } else {/* ww w  .  jav a 2 s  . c om*/
        disbursementDate = new GregorianCalendar(year, month + 1, day);
    }
    UserContext userContext = TestUtils.makeUser();
    userContext.setLocaleId(null);
    List<FeeView> feeViewList = new ArrayList<FeeView>();
    FeeBO upfrontFee = TestObjectFactory.createOneTimeRateFee("Upfront Fee", FeeCategory.LOAN,
            Double.valueOf("20"), FeeFormula.AMOUNT, FeePayment.UPFRONT);
    feeViewList.add(new FeeView(userContext, upfrontFee));
    FeeBO disbursementFee = TestObjectFactory.createOneTimeRateFee("Disbursement Fee", FeeCategory.LOAN,
            Double.valueOf("30"), FeeFormula.AMOUNT_AND_INTEREST, FeePayment.TIME_OF_DISBURSEMENT);
    feeViewList.add(new FeeView(userContext, disbursementFee));
    FeeBO firstRepaymentFee = TestObjectFactory.createOneTimeRateFee("First Repayment Fee", FeeCategory.LOAN,
            Double.valueOf("40"), FeeFormula.INTEREST, FeePayment.TIME_OF_FIRSTLOANREPAYMENT);
    feeViewList.add(new FeeView(userContext, firstRepaymentFee));
    FeeBO periodicFee = TestObjectFactory.createPeriodicAmountFee("Periodic Fee", FeeCategory.LOAN, "100",
            RecurrenceType.MONTHLY, Short.valueOf("1"));
    feeViewList.add(new FeeView(userContext, periodicFee));
    accountBO = loanDao.createLoan(TestUtils.makeUser(), loanOffering, group,
            AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(getCurrency(), "300.0"), Short.valueOf("6"),
            disbursementDate.getTime(), false, 1.2, (short) 0, null, feeViewList, null, DOUBLE_ZERO,
            DOUBLE_ZERO, SHORT_ZERO, SHORT_ZERO, false);
    new TestObjectPersistence().persist(accountBO);

    disbursementDate = new GregorianCalendar();
    year = disbursementDate.get(Calendar.YEAR);
    month = disbursementDate.get(Calendar.MONTH);
    day = 25;
    if (disbursementDate.get(Calendar.DAY_OF_MONTH) == dayOfMonth.intValue()) {
        disbursementDate = new GregorianCalendar(year, month + 1, day);
    } else {
        disbursementDate = new GregorianCalendar(year, month + 2, day);
    }
    ((LoanBO) accountBO).disburseLoan("1234", disbursementDate.getTime(), Short.valueOf("1"),
            accountBO.getPersonnel(), disbursementDate.getTime(), Short.valueOf("1"));
    Session session = StaticHibernateUtil.getSessionTL();
    StaticHibernateUtil.startTransaction();
    session.save(accountBO);
    StaticHibernateUtil.getTransaction().commit();
}

From source file:org.mifos.accounts.servicefacade.WebTierAccountServiceFacade.java

@Override
public void applyCharge(Integer accountId, Short chargeId, Double chargeAmount, boolean isPenaltyType) {

    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    try {//w  ww.j  ava  2 s . c  o m
        AccountBO account = new AccountBusinessService().getAccount(accountId);

        if (account instanceof LoanBO && !account.isGroupLoanAccount()) {
            List<LoanBO> individualLoans = this.loanDao.findIndividualLoans(account.getAccountId());

            if (individualLoans != null && individualLoans.size() > 0) {
                for (LoanBO individual : individualLoans) {
                    individual.updateDetails(userContext);

                    if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {
                        PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                        individual.addAccountPenalty(
                                new AccountPenaltiesEntity(individual, penalty, chargeAmount));
                    } else {
                        FeeBO fee = this.feeDao.findById(chargeId);

                        if (fee instanceof RateFeeBO) {
                            individual.applyCharge(chargeId, chargeAmount);
                        } else {
                            Double radio = individual.getLoanAmount().getAmount().doubleValue()
                                    / ((LoanBO) account).getLoanAmount().getAmount().doubleValue();

                            individual.applyCharge(chargeId, chargeAmount * radio);
                        }
                    }
                }
            }
        }

        account.updateDetails(userContext);

        CustomerLevel customerLevel = null;
        if (account.isCustomerAccount()) {
            customerLevel = account.getCustomer().getLevel();
        }
        if (account.getPersonnel() != null) {
            checkPermissionForApplyCharges(account.getType(), customerLevel, userContext,
                    account.getOffice().getOfficeId(), account.getPersonnel().getPersonnelId());
        } else {
            checkPermissionForApplyCharges(account.getType(), customerLevel, userContext,
                    account.getOffice().getOfficeId(), userContext.getId());
        }

        this.transactionHelper.startTransaction();

        if (isPenaltyType && account instanceof LoanBO) {
            PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
            ((LoanBO) account).addAccountPenalty(new AccountPenaltiesEntity(account, penalty, chargeAmount));
        } else {
            account.applyCharge(chargeId, chargeAmount);
        }

        this.transactionHelper.commitTransaction();
    } catch (ServiceException e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } catch (ApplicationException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getKey(), e);
    }
}

From source file:org.mifos.accounts.servicefacade.WebTierAccountServiceFacade.java

@Override
public void applyGroupCharge(Map<Integer, String> idsAndValues, Short chargeId, boolean isPenaltyType) {
    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);
    TreeMap<Integer, String> idsAndValueAsTreeMap = new TreeMap<Integer, String>(idsAndValues);

    try {// w w  w  .  j a  va 2 s.  c o  m
        AccountBO parentAccount = ((LoanBO) legacyAccountDao.getAccount(
                new AccountBusinessService().getAccount(idsAndValueAsTreeMap.firstKey()).getAccountId()))
                        .getParentAccount();
        BigDecimal parentAmount = ((LoanBO) parentAccount).getLoanAmount().getAmount();
        BigDecimal membersAmount = BigDecimal.ZERO;

        for (Map.Entry<Integer, String> entry : idsAndValues.entrySet()) {
            LoanBO individual = loanDao.findById(entry.getKey());
            Double chargeAmount = Double.valueOf(entry.getValue());
            if (chargeAmount.equals(0.0)) {
                continue;
            }
            membersAmount = membersAmount.add(individual.getLoanAmount().getAmount());
            individual.updateDetails(userContext);

            if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {
                PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                individual.addAccountPenalty(new AccountPenaltiesEntity(individual, penalty, chargeAmount));
            } else {
                individual.applyCharge(chargeId, chargeAmount);
            }
        }

        boolean isRateCharge = false;

        if (!chargeId.equals(Short.valueOf(AccountConstants.MISC_FEES))
                && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {

            if (isPenaltyType) {
                PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                if (penalty instanceof RatePenaltyBO) {
                    isRateCharge = true;
                }
            } else {
                FeeBO fee = feeDao.findById(chargeId);
                if (fee.getFeeType().equals(RateAmountFlag.RATE)) {
                    isRateCharge = true;
                }
            }
        }

        Double chargeAmount = null;

        if (!isRateCharge) {
            chargeAmount = sumCharge(idsAndValues);
        } else {
            chargeAmount = Double.valueOf(idsAndValueAsTreeMap.firstEntry().getValue());
            BigDecimal chargeAmountBig = new BigDecimal(chargeAmount);
            membersAmount = membersAmount.multiply(chargeAmountBig);
            int scale = Money.getInternalPrecision();
            chargeAmountBig = membersAmount.divide(parentAmount, scale, RoundingMode.HALF_EVEN);
            chargeAmount = chargeAmountBig.doubleValue();
        }

        parentAccount.updateDetails(userContext);

        CustomerLevel customerLevel = null;
        if (parentAccount.isCustomerAccount()) {
            customerLevel = parentAccount.getCustomer().getLevel();
        }
        if (parentAccount.getPersonnel() != null) {
            checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext,
                    parentAccount.getOffice().getOfficeId(), parentAccount.getPersonnel().getPersonnelId());
        } else {
            checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext,
                    parentAccount.getOffice().getOfficeId(), userContext.getId());
        }

        this.transactionHelper.startTransaction();

        if (isPenaltyType && parentAccount instanceof LoanBO) {
            PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
            ((LoanBO) parentAccount)
                    .addAccountPenalty(new AccountPenaltiesEntity(parentAccount, penalty, chargeAmount));
        } else {
            parentAccount.applyCharge(chargeId, chargeAmount);
        }

        this.transactionHelper.commitTransaction();
    } catch (ServiceException e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } catch (ApplicationException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getKey(), e);
    }

}

From source file:org.mifos.application.servicefacade.ClientServiceFacadeWebTier.java

@Override
public CustomerDetailsDto createNewClient(ClientCreationDetail clientCreationDetail, MeetingDto meetingDto,
        List<SavingsDetailDto> allowedSavingProducts) {

    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    OfficeBO userOffice = this.officeDao.findOfficeById(userContext.getBranchId());
    userContext.setBranchGlobalNum(userOffice.getGlobalOfficeNum());

    try {//from w ww .  ja v  a  2s  .c o  m

        ClientBO client = null;

        List<AccountFeesEntity> feesForCustomerAccount = convertFeeViewsToAccountFeeEntities(
                clientCreationDetail.getFeesToApply());
        List<SavingsOfferingBO> selectedOfferings = new ArrayList<SavingsOfferingBO>();
        for (Short productId : clientCreationDetail.getSelectedSavingProducts()) {
            if (productId != null) {
                for (SavingsDetailDto savingsOffering : allowedSavingProducts) {
                    if (productId.equals(savingsOffering.getPrdOfferingId())) {

                        SavingsOfferingBO savingsProduct = savingsProductDao.findById(productId.intValue());
                        selectedOfferings.add(savingsProduct);
                    }
                }
            }
        }

        List<ClientInitialSavingsOfferingEntity> offeringsAssociatedInCreate = new ArrayList<ClientInitialSavingsOfferingEntity>();
        for (SavingsOfferingBO offering : selectedOfferings) {
            offeringsAssociatedInCreate.add(new ClientInitialSavingsOfferingEntity(null, offering));
        }

        Short personnelId = null;
        Short officeId = null;

        ClientNameDetailDto spouseNameDetailView = null;
        if (ClientRules.isFamilyDetailsRequired()) {
            //                actionForm.setFamilyDateOfBirth();
            //                actionForm.constructFamilyDetails();
        } else {
            spouseNameDetailView = clientCreationDetail.getSpouseFatherName();
        }

        String secondMiddleName = null;
        ClientNameDetailEntity clientNameDetailEntity = new ClientNameDetailEntity(null, secondMiddleName,
                clientCreationDetail.getClientNameDetailDto());

        ClientNameDetailEntity spouseFatherNameDetailEntity = null;
        if (spouseNameDetailView != null) {
            spouseFatherNameDetailEntity = new ClientNameDetailEntity(null, secondMiddleName,
                    spouseNameDetailView);
        }

        ClientDetailEntity clientDetailEntity = new ClientDetailEntity();
        clientDetailEntity.updateClientDetails(clientCreationDetail.getClientPersonalDetailDto());

        DateTime dob = new DateTime(clientCreationDetail.getDateOfBirth());
        boolean trainedBool = clientCreationDetail.isTrained();
        DateTime trainedDateTime = null;
        if (clientCreationDetail.getTrainedDate() != null) {
            trainedDateTime = new DateTime(clientCreationDetail.getTrainedDate());
        }
        String clientFirstName = clientCreationDetail.getClientNameDetailDto().getFirstName();
        String clientLastName = clientCreationDetail.getClientNameDetailDto().getLastName();
        String secondLastName = clientCreationDetail.getClientNameDetailDto().getSecondLastName();

        CustomerStatus clientStatus = CustomerStatus.fromInt(clientCreationDetail.getClientStatus());
        PersonnelBO formedBy = this.personnelDao.findPersonnelById(clientCreationDetail.getFormedBy());
        Address address = null;
        if (clientCreationDetail.getAddress() != null) {
            AddressDto dto = clientCreationDetail.getAddress();
            address = new Address(dto.getLine1(), dto.getLine2(), dto.getLine3(), dto.getCity(), dto.getState(),
                    dto.getCountry(), dto.getZip(), dto.getPhoneNumber());
        }

        if (YesNoFlag.YES.getValue().equals(clientCreationDetail.getGroupFlag())) {

            Integer parentGroupId = Integer.parseInt(clientCreationDetail.getParentGroupId());
            CustomerBO group = this.customerDao.findCustomerById(parentGroupId);

            if (group.getPersonnel() != null) {
                personnelId = group.getPersonnel().getPersonnelId();
            }

            officeId = group.getOffice().getOfficeId();

            client = ClientBO.createNewInGroupHierarchy(userContext, clientCreationDetail.getClientName(),
                    clientStatus, new DateTime(clientCreationDetail.getMfiJoiningDate()), group, formedBy,
                    clientNameDetailEntity, dob, clientCreationDetail.getGovernmentId(), trainedBool,
                    trainedDateTime, clientCreationDetail.getGroupFlag(), clientFirstName, clientLastName,
                    secondLastName, spouseFatherNameDetailEntity, clientDetailEntity,
                    offeringsAssociatedInCreate, clientCreationDetail.getExternalId(), address,
                    clientCreationDetail.getActivationDate());

            if (ClientRules.isFamilyDetailsRequired()) {
                client.setFamilyAndNameDetailSets(clientCreationDetail.getFamilyNames(),
                        clientCreationDetail.getFamilyDetails());
            }

            this.customerService.createClient(client, client.getCustomerMeetingValue(), feesForCustomerAccount,
                    selectedOfferings);

        } else {
            personnelId = clientCreationDetail.getLoanOfficerId();
            officeId = clientCreationDetail.getOfficeId();

            PersonnelBO loanOfficer = this.personnelDao.findPersonnelById(personnelId);
            OfficeBO office = this.officeDao.findOfficeById(officeId);

            int lastSearchIdCustomerValue = customerDao
                    .retrieveLastSearchIdValueForNonParentCustomersInOffice(officeId);

            MeetingBO clientMeeting = null;
            if (meetingDto != null) {
                clientMeeting = new MeetingFactory().create(meetingDto);
                clientMeeting.setUserContext(userContext);
            }

            client = ClientBO.createNewOutOfGroupHierarchy(userContext, clientCreationDetail.getClientName(),
                    clientStatus, new DateTime(clientCreationDetail.getMfiJoiningDate()), office, loanOfficer,
                    clientMeeting, formedBy, clientNameDetailEntity, dob,
                    clientCreationDetail.getGovernmentId(), trainedBool, trainedDateTime,
                    clientCreationDetail.getGroupFlag(), clientFirstName, clientLastName, secondLastName,
                    spouseFatherNameDetailEntity, clientDetailEntity, offeringsAssociatedInCreate,
                    clientCreationDetail.getExternalId(), address, lastSearchIdCustomerValue);

            if (ClientRules.isFamilyDetailsRequired()) {
                client.setFamilyAndNameDetailSets(clientCreationDetail.getFamilyNames(),
                        clientCreationDetail.getFamilyDetails());
            }

            this.customerService.createClient(client, clientMeeting, feesForCustomerAccount, selectedOfferings);
        }

        clientPhotoService.create(client.getCustomerId().longValue(), clientCreationDetail.getPicture());

        return new CustomerDetailsDto(client.getCustomerId(), client.getGlobalCustNum());
    } catch (CustomerException e) {
        throw new BusinessRuleException(e.getKey(), e.getValues(), e);
    }
}

From source file:org.mifos.application.servicefacade.LoanAccountServiceFacadeWebTier.java

@Override
public LoanCreationLoanDetailsDto retrieveLoanDetailsForLoanAccountCreation(Integer customerId, Short productId,
        boolean isLoanWithBackdatedPayments) {

    try {// www.  j a v a  2s  .co  m
        List<org.mifos.dto.domain.FeeDto> additionalFees = new ArrayList<org.mifos.dto.domain.FeeDto>();
        List<org.mifos.dto.domain.FeeDto> defaultFees = new ArrayList<org.mifos.dto.domain.FeeDto>();
        List<PenaltyDto> defaultPenalties = new ArrayList<PenaltyDto>();

        LoanOfferingBO loanProduct = this.loanProductDao.findById(productId.intValue());

        MeetingBO loanProductMeeting = loanProduct.getLoanOfferingMeetingValue();
        MeetingDto loanOfferingMeetingDto = loanProductMeeting.toDto();

        List<FeeBO> fees = this.feeDao.getAllAppllicableFeeForLoanCreation();

        for (FeeBO fee : fees) {
            if (!fee.isPeriodic() || (MeetingBO.isMeetingMatched(fee.getFeeFrequency().getFeeMeetingFrequency(),
                    loanProductMeeting))) {

                org.mifos.dto.domain.FeeDto feeDto = fee.toDto();

                FeeFrequencyType feeFrequencyType = FeeFrequencyType
                        .getFeeFrequencyType(fee.getFeeFrequency().getFeeFrequencyType().getId());

                FeeFrequencyTypeEntity feeFrequencyEntity = this.loanProductDao
                        .retrieveFeeFrequencyType(feeFrequencyType);
                String feeFrequencyTypeName = ApplicationContextProvider.getBean(MessageLookup.class)
                        .lookup(feeFrequencyEntity.getLookUpValue());
                feeDto.setFeeFrequencyType(feeFrequencyTypeName);

                if (feeDto.getFeeFrequency().isOneTime()) {
                    FeePayment feePayment = FeePayment
                            .getFeePayment(fee.getFeeFrequency().getFeePayment().getId());
                    FeePaymentEntity feePaymentEntity = this.loanProductDao.retrieveFeePaymentType(feePayment);
                    String feePaymentName = ApplicationContextProvider.getBean(MessageLookup.class)
                            .lookup(feePaymentEntity.getLookUpValue());
                    feeDto.getFeeFrequency().setPayment(feePaymentName);
                }

                if (loanProduct.isFeePresent(fee)) {
                    defaultFees.add(feeDto);
                } else {
                    additionalFees.add(feeDto);
                }
            }
        }

        List<PenaltyBO> penalties = this.penaltyDao.getAllAppllicablePenaltyForLoanCreation();

        for (PenaltyBO penalty : penalties) {
            if (loanProduct.isPenaltyPresent(penalty)) {
                defaultPenalties.add(penalty.toDto());
            }
        }

        if (AccountingRules.isMultiCurrencyEnabled()) {
            defaultFees = getFilteredFeesByCurrency(defaultFees, loanProduct.getCurrency().getCurrencyId());
            additionalFees = getFilteredFeesByCurrency(additionalFees,
                    loanProduct.getCurrency().getCurrencyId());
        }

        Map<String, String> defaultFeeOptions = new LinkedHashMap<String, String>();
        for (org.mifos.dto.domain.FeeDto feeDto : defaultFees) {
            defaultFeeOptions.put(feeDto.getId(), feeDto.getName());
        }

        Map<String, String> additionalFeeOptions = new LinkedHashMap<String, String>();
        for (org.mifos.dto.domain.FeeDto feeDto : additionalFees) {
            additionalFeeOptions.put(feeDto.getId(), feeDto.getName());
        }

        CustomerBO customer = this.customerDao.findCustomerById(customerId);
        boolean isRepaymentIndependentOfMeetingEnabled = new ConfigurationBusinessService()
                .isRepaymentIndepOfMeetingEnabled();

        LoanDisbursementDateFactory loanDisbursementDateFactory = new LoanDisbursmentDateFactoryImpl();
        LoanDisbursementDateFinder loanDisbursementDateFinder = loanDisbursementDateFactory.create(customer,
                loanProduct, isRepaymentIndependentOfMeetingEnabled, isLoanWithBackdatedPayments);
        LocalDate nextPossibleDisbursementDate = loanDisbursementDateFinder
                .findClosestMatchingDateFromAndInclusiveOf(new LocalDate());

        LoanAmountOption eligibleLoanAmount = loanProduct.eligibleLoanAmount(
                customer.getMaxLoanAmount(loanProduct), customer.getMaxLoanCycleForProduct(loanProduct));
        LoanOfferingInstallmentRange eligibleNoOfInstall = loanProduct.eligibleNoOfInstall(
                customer.getMaxLoanAmount(loanProduct), customer.getMaxLoanCycleForProduct(loanProduct));

        Double defaultInterestRate = loanProduct.getDefInterestRate();
        Double maxInterestRate = loanProduct.getMaxInterestRate();
        Double minInterestRate = loanProduct.getMinInterestRate();

        LinkedHashMap<String, String> collateralOptions = new LinkedHashMap<String, String>();
        LinkedHashMap<String, String> purposeOfLoanOptions = new LinkedHashMap<String, String>();

        CustomValueDto customValueDto = legacyMasterDao.getLookUpEntity(MasterConstants.COLLATERAL_TYPES);
        List<CustomValueListElementDto> collateralTypes = customValueDto.getCustomValueListElements();
        for (CustomValueListElementDto element : collateralTypes) {
            collateralOptions.put(element.getId().toString(), element.getName());
        }

        // Business activities got in getPrdOfferings also but only for glim.
        List<ValueListElement> loanPurposes = legacyMasterDao
                .findValueListElements(MasterConstants.LOAN_PURPOSES);
        for (ValueListElement element : loanPurposes) {
            purposeOfLoanOptions.put(element.getId().toString(), element.getName());
        }

        List<FundDto> fundDtos = new ArrayList<FundDto>();
        List<FundBO> funds = getFunds(loanProduct);
        for (FundBO fund : funds) {
            FundDto fundDto = new FundDto();
            fundDto.setId(Short.toString(fund.getFundId()));
            fundDto.setCode(translateFundCodeToDto(fund.getFundCode()));
            fundDto.setName(fund.getFundName());

            fundDtos.add(fundDto);
        }

        ProductDetailsDto productDto = loanProduct.toDetailsDto();
        CustomerDetailDto customerDetailDto = customer.toCustomerDetailDto();

        Integer gracePeriodInInstallments = loanProduct.getGracePeriodDuration().intValue();

        final List<PrdOfferingDto> loanProductDtos = retrieveActiveLoanProductsApplicableForCustomer(customer,
                isRepaymentIndependentOfMeetingEnabled);

        InterestType interestType = InterestType.fromInt(loanProduct.getInterestTypes().getId().intValue());
        InterestTypesEntity productInterestType = this.loanProductDao.findInterestType(interestType);
        String interestTypeName = ApplicationContextProvider.getBean(MessageLookup.class)
                .lookup(productInterestType.getLookUpValue());

        LinkedHashMap<String, String> daysOfTheWeekOptions = new LinkedHashMap<String, String>();
        List<WeekDay> workingDays = new FiscalCalendarRules().getWorkingDays();
        for (WeekDay workDay : workingDays) {
            String weekdayName = ApplicationContextProvider.getBean(MessageLookup.class)
                    .lookup(workDay.getPropertiesKey());
            workDay.setWeekdayName(weekdayName);
            daysOfTheWeekOptions.put(workDay.getValue().toString(), weekdayName);
        }

        LinkedHashMap<String, String> weeksOfTheMonthOptions = new LinkedHashMap<String, String>();
        for (RankOfDay weekOfMonth : RankOfDay.values()) {
            String weekOfMonthName = ApplicationContextProvider.getBean(MessageLookup.class)
                    .lookup(weekOfMonth.getPropertiesKey());
            weeksOfTheMonthOptions.put(weekOfMonth.getValue().toString(), weekOfMonthName);
        }

        boolean variableInstallmentsAllowed = loanProduct.isVariableInstallmentsAllowed();
        boolean fixedRepaymentSchedule = loanProduct.isFixedRepaymentSchedule();
        Integer minGapInDays = Integer.valueOf(0);
        Integer maxGapInDays = Integer.valueOf(0);
        BigDecimal minInstallmentAmount = BigDecimal.ZERO;
        if (variableInstallmentsAllowed) {
            VariableInstallmentDetailsBO variableInstallmentsDetails = loanProduct
                    .getVariableInstallmentDetails();
            minGapInDays = variableInstallmentsDetails.getMinGapInDays();
            maxGapInDays = variableInstallmentsDetails.getMaxGapInDays();
            minInstallmentAmount = variableInstallmentsDetails.getMinInstallmentAmount().getAmount();
        }

        boolean compareCashflowEnabled = loanProduct.isCashFlowCheckEnabled();

        // GLIM specific
        final boolean isGroup = customer.isGroup();
        final boolean isGlimEnabled = new ConfigurationPersistence().isGlimEnabled();

        List<LoanAccountDetailsDto> clientDetails = new ArrayList<LoanAccountDetailsDto>();

        if (isGroup && isGlimEnabled) {
            final List<ClientBO> activeClientsOfGroup = customerDao.findActiveClientsUnderGroup(customer);

            if (activeClientsOfGroup == null || activeClientsOfGroup.isEmpty()) {
                throw new BusinessRuleException(GroupConstants.IMPOSSIBLE_TO_CREATE_GROUP_LOAN);
            }

            for (ClientBO client : activeClientsOfGroup) {
                LoanAccountDetailsDto clientDetail = new LoanAccountDetailsDto();
                clientDetail.setClientId(client.getGlobalCustNum());
                clientDetail.setClientName(client.getDisplayName());
                clientDetails.add(clientDetail);
            }
        }
        // end of GLIM specific

        int digitsAfterDecimalForInterest = AccountingRules.getDigitsAfterDecimalForInterest().intValue();
        int digitsBeforeDecimalForInterest = AccountingRules.getDigitsBeforeDecimalForInterest().intValue();
        int digitsAfterDecimalForMonetaryAmounts = AccountingRules.getDigitsAfterDecimal().intValue();
        int digitsBeforeDecimalForMonetaryAmounts = AccountingRules.getDigitsBeforeDecimal().intValue();

        ApplicationConfigurationDto appConfig = new ApplicationConfigurationDto(digitsAfterDecimalForInterest,
                digitsBeforeDecimalForInterest, digitsAfterDecimalForMonetaryAmounts,
                digitsBeforeDecimalForMonetaryAmounts);

        Map<String, String> disbursalPaymentTypes = new LinkedHashMap<String, String>();
        try {
            for (PaymentTypeDto paymentTypeDto : accountService.getLoanDisbursementTypes()) {
                disbursalPaymentTypes.put(paymentTypeDto.getValue().toString(), paymentTypeDto.getName());
            }
        } catch (Exception e) {
            throw new SystemException(e);
        }
        Map<String, String> repaymentpaymentTypes = new LinkedHashMap<String, String>();
        try {
            for (PaymentTypeDto paymentTypeDto : accountService.getLoanPaymentTypes()) {
                repaymentpaymentTypes.put(paymentTypeDto.getValue().toString(), paymentTypeDto.getName());
            }
        } catch (Exception e) {
            throw new SystemException(e);
        }

        return new LoanCreationLoanDetailsDto(isRepaymentIndependentOfMeetingEnabled, loanOfferingMeetingDto,
                customer.getCustomerMeetingValue().toDto(), loanPurposes, productDto, gracePeriodInInstallments,
                customerDetailDto, loanProductDtos, interestTypeName, fundDtos, collateralOptions,
                purposeOfLoanOptions, defaultFeeOptions, additionalFeeOptions, defaultFees, additionalFees,
                BigDecimal.valueOf(eligibleLoanAmount.getDefaultLoanAmount()),
                BigDecimal.valueOf(eligibleLoanAmount.getMaxLoanAmount()),
                BigDecimal.valueOf(eligibleLoanAmount.getMinLoanAmount()), defaultInterestRate, maxInterestRate,
                minInterestRate, eligibleNoOfInstall.getDefaultNoOfInstall().intValue(),
                eligibleNoOfInstall.getMaxNoOfInstall().intValue(),
                eligibleNoOfInstall.getMinNoOfInstall().intValue(), nextPossibleDisbursementDate,
                daysOfTheWeekOptions, weeksOfTheMonthOptions, variableInstallmentsAllowed,
                fixedRepaymentSchedule, minGapInDays, maxGapInDays, minInstallmentAmount,
                compareCashflowEnabled, isGlimEnabled, isGroup, clientDetails, appConfig, defaultPenalties,
                disbursalPaymentTypes, repaymentpaymentTypes);

    } catch (SystemException e) {
        throw new MifosRuntimeException(e);
    }
}

From source file:org.mifos.application.servicefacade.LoanAccountServiceFacadeWebTier.java

private List<org.mifos.dto.domain.FeeDto> getFilteredFeesByCurrency(
        List<org.mifos.dto.domain.FeeDto> defaultFees, Short currencyId) {
    List<org.mifos.dto.domain.FeeDto> filteredFees = new ArrayList<org.mifos.dto.domain.FeeDto>();
    for (org.mifos.dto.domain.FeeDto feeDto : defaultFees) {
        if (feeDto.isValidForCurrency(currencyId.intValue())) {
            filteredFees.add(feeDto);/*from   w w w.  j  a  va  2  s. com*/
        }
    }
    return filteredFees;
}

From source file:org.mifos.application.servicefacade.LoanAccountServiceFacadeWebTier.java

@Override
public List<String> createMultipleLoans(List<CreateLoanRequest> multipleLoans) {

    MifosUser mifosUser = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = new UserContextFactory().create(mifosUser);

    OfficeBO userOffice = this.officeDao.findOfficeById(userContext.getBranchId());
    userContext.setBranchGlobalNum(userOffice.getGlobalOfficeNum());

    List<String> createdLoanAccountNumbers = new ArrayList<String>();
    for (CreateLoanRequest loanDetail : multipleLoans) {

        CustomerBO center = this.customerDao.findCustomerById(loanDetail.getCenterId());
        Short loanProductId = loanDetail.getLoanProductId();
        LoanOfferingBO loanProduct = this.loanProductDao.findById(loanProductId.intValue());

        List<QuestionGroupDetail> questionGroups = new ArrayList<QuestionGroupDetail>();
        LoanAccountCashFlow loanAccountCashFlow = null;

        BigDecimal loanAmount = BigDecimal.valueOf(Double.valueOf(loanDetail.getLoanAmount()));
        BigDecimal minAllowedLoanAmount = BigDecimal.valueOf(Double.valueOf(loanDetail.getMinLoanAmount()));
        BigDecimal maxAllowedLoanAmount = BigDecimal.valueOf(Double.valueOf(loanDetail.getMaxLoanAmount()));
        Double interestRate = loanProduct.getDefInterestRate();
        LocalDate disbursementDate = new LocalDate(center.getCustomerAccount().getNextMeetingDate());
        int numberOfInstallments = loanDetail.getDefaultNoOfInstall();
        int minAllowedNumberOfInstallments = loanDetail.getMinNoOfInstall();
        int maxAllowedNumberOfInstallments = loanDetail.getMaxNoOfInstall();

        int graceDuration = loanProduct.getGracePeriodDuration();
        boolean isRepaymentIndepOfMeetingEnabled = new ConfigurationBusinessService()
                .isRepaymentIndepOfMeetingEnabled();

        Integer sourceOfFundId = null;
        Integer loanPurposeId = loanDetail.getLoanPurpose();
        Integer collateralTypeId = null;
        String collateralNotes = null;
        String externalId = null;
        RecurringSchedule recurringSchedule = null;
        List<CreateAccountFeeDto> accountFees = new ArrayList<CreateAccountFeeDto>();
        CreateLoanAccount loanAccountInfo = new CreateLoanAccount(loanDetail.getClientId(),
                loanDetail.getLoanProductId().intValue(), loanDetail.getAccountStateId().intValue(), loanAmount,
                minAllowedLoanAmount, maxAllowedLoanAmount, interestRate, disbursementDate, null,
                numberOfInstallments, minAllowedNumberOfInstallments, maxAllowedNumberOfInstallments,
                graceDuration, sourceOfFundId, loanPurposeId, collateralTypeId, collateralNotes, externalId,
                isRepaymentIndepOfMeetingEnabled, recurringSchedule, accountFees,
                new ArrayList<CreateAccountPenaltyDto>());

        LoanCreationResultDto result = this.createLoan(loanAccountInfo, questionGroups, loanAccountCashFlow);
        createdLoanAccountNumbers.add(result.getGlobalAccountNum());

        //            try {
        //                CustomerBO center = this.customerDao.findCustomerById(loanDetail.getCenterId());
        ////from  w ww  .j a  va 2  s.  c  o  m
        //                Short loanProductId = loanDetail.getLoanProductId();
        //                LoanOfferingBO loanProduct = this.loanProductDao.findById(loanProductId.intValue());
        //                CustomerBO client = this.customerDao.findCustomerById(loanDetail.getClientId());
        //
        //                AccountState accountState = AccountState.fromShort(loanDetail.getAccountStateId());
        //                Money loanAmount = new Money(loanProduct.getCurrency(), loanDetail.getLoanAmount());
        //                Short defaultNumOfInstallments = loanDetail.getDefaultNoOfInstall();
        //                Date disbursementDate = center.getCustomerAccount().getNextMeetingDate();
        //                boolean interestDeductedAtDisbursement = loanProduct.isIntDedDisbursement();
        //                boolean isRepaymentIndepOfMeetingEnabled = new ConfigurationBusinessService().isRepaymentIndepOfMeetingEnabled();
        //
        //                MeetingBO newMeetingForRepaymentDay = null;
        //                if (isRepaymentIndepOfMeetingEnabled) {
        //                    MeetingBO meeting = center.getCustomerAccount().getMeetingForAccount();
        //                    LoanAccountMeetingDto loanAccountMeetingDto = null;
        //
        //                    if (meeting.isWeekly()) {
        //                        loanAccountMeetingDto = new LoanAccountMeetingDto(RecurrenceType.WEEKLY.getValue().toString(),
        //                                meeting.getMeetingDetails().getWeekDay().getValue().toString(),
        //                                meeting.getMeetingDetails().getRecurAfter().toString(),
        //                                null, null, null, null, null, null);
        //                    } else if (meeting.isMonthly()) {
        //                        if (meeting.isMonthlyOnDate()) {
        //                            loanAccountMeetingDto = new LoanAccountMeetingDto(RecurrenceType.MONTHLY.getValue().toString(),
        //                                    null, null, "1",
        //                                    meeting.getMeetingDetails().getDayNumber().toString(),
        //                                    meeting.getMeetingDetails().getRecurAfter().toString(),
        //                                    null, null, null);
        //                        } else {
        //                            loanAccountMeetingDto = new LoanAccountMeetingDto(RecurrenceType.MONTHLY.getValue().toString(),
        //                                    null, null, "2", null, null,
        //                                    meeting.getMeetingDetails().getWeekDay().getValue().toString(),
        //                                    meeting.getMeetingDetails().getRecurAfter().toString(),
        //                                    meeting.getMeetingDetails().getWeekRank().getValue().toString());
        //                        }
        //                    }
        //
        //                    newMeetingForRepaymentDay = this.createNewMeetingForRepaymentDay(new LocalDate(disbursementDate), loanAccountMeetingDto, client);
        //                }
        //
        //                checkPermissionForCreate(accountState.getValue(), userContext, userContext.getBranchId(), userContext.getId());
        //
        //                List<FeeDto> additionalFees = new ArrayList<FeeDto>();
        //                List<FeeDto> defaultFees = new ArrayList<FeeDto>();
        //
        //                new LoanProductService().getDefaultAndAdditionalFees(loanProductId, userContext, defaultFees, additionalFees);
        //
        //                FundBO fund = null;
        //                List<CustomFieldDto> customFields = new ArrayList<CustomFieldDto>();
        //                boolean isRedone = false;
        //
        //                // FIXME - keithw - tidy up constructor and use domain concepts rather than primitives, e.g. money v double, loanpurpose v integer.
        //
        //                LoanBO loan = new LoanBO(userContext, loanProduct, client, accountState, loanAmount, defaultNumOfInstallments,
        //                        disbursementDate, interestDeductedAtDisbursement, interestRate, gracePeriodDuration, fund, defaultFees,
        //                        customFields, isRedone, maxLoanAmount, minLoanAmount,
        //                        loanProduct.getMaxInterestRate(), loanProduct.getMinInterestRate(),
        //                        maxNoOfInstall, minNoOfInstall, isRepaymentIndepOfMeetingEnabled, newMeetingForRepaymentDay);
        //                loan.setBusinessActivityId(loanDetail.getLoanPurpose());
        //
        //                PersonnelBO loggedInUser = this.personnelDao.findPersonnelById(userContext.getId());
        //                AccountStateEntity newAccountState = new AccountStateEntity(accountState);
        //                AccountStatusChangeHistoryEntity statusChange = new AccountStatusChangeHistoryEntity(null, newAccountState, loggedInUser, loan);
        //
        //                this.transactionHelper.startTransaction();
        //                loan.addAccountStatusChangeHistory(statusChange);
        //                this.loanDao.save(loan);
        //                this.transactionHelper.flushSession();
        //                String globalAccountNum = loan.generateId(userContext.getBranchGlobalNum());
        //                loan.setGlobalAccountNum(globalAccountNum);
        //                this.loanDao.save(loan);
        //                this.transactionHelper.commitTransaction();
        //
        //                createdLoanAccountNumbers.add(loan.getGlobalAccountNum());
        //            } catch (ServiceException e) {
        //                this.transactionHelper.rollbackTransaction();
        //                throw new MifosRuntimeException(e);
        //            } catch (PersistenceException e) {
        //                this.transactionHelper.rollbackTransaction();
        //                throw new MifosRuntimeException(e);
        //            } catch (AccountException e) {
        //                this.transactionHelper.rollbackTransaction();
        //                throw new BusinessRuleException(e.getKey(), e);
        //            }
    }

    return createdLoanAccountNumbers;
}