Example usage for java.lang Integer compareTo

List of usage examples for java.lang Integer compareTo

Introduction

In this page you can find the example usage for java.lang Integer compareTo.

Prototype

public int compareTo(Integer anotherInteger) 

Source Link

Document

Compares two Integer objects numerically.

Usage

From source file:net.sourceforge.fenixedu.presentationTier.Action.teacher.StudentGroupManagementDA.java

public ActionForward createGroupProperties(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {
    DynaActionForm insertGroupPropertiesForm = (DynaActionForm) form;
    String name = (String) insertGroupPropertiesForm.get("name");
    String projectDescription = (String) insertGroupPropertiesForm.get("projectDescription");
    String maximumCapacityString = (String) insertGroupPropertiesForm.get("maximumCapacity");
    String minimumCapacityString = (String) insertGroupPropertiesForm.get("minimumCapacity");
    String idealCapacityString = (String) insertGroupPropertiesForm.get("idealCapacity");
    String groupMaximumNumber = (String) insertGroupPropertiesForm.get("groupMaximumNumber");
    String enrolmentBeginDayString = (String) insertGroupPropertiesForm.get("enrolmentBeginDay");
    String enrolmentBeginHourString = (String) insertGroupPropertiesForm.get("enrolmentBeginHour");
    String enrolmentEndDayString = (String) insertGroupPropertiesForm.get("enrolmentEndDay");
    String enrolmentEndHourString = (String) insertGroupPropertiesForm.get("enrolmentEndHour");
    String shiftType = (String) insertGroupPropertiesForm.get("shiftType");
    Boolean optional = new Boolean((String) insertGroupPropertiesForm.get("enrolmentPolicy"));
    Boolean automaticEnrolment = getAutomaticEnrolment(insertGroupPropertiesForm);
    Boolean differentiatedCapacity = getDifferentiatedCapacity(insertGroupPropertiesForm);

    final ArrayList<InfoShift> infoShifts = getRenderedObject("shiftsTable");

    if ("".equals(name)) {
        ActionMessages actionErrors = new ActionMessages();
        ActionMessage error = new ActionMessage("error.groupProperties.missingName");
        actionErrors.add("error.groupProperties.missingName", error);
        saveErrors(request, actionErrors);
        return prepareCreateGroupProperties(mapping, form, request, response);
    }/* w  w w.j a  v  a2s .co m*/

    InfoGrouping infoGroupProperties = new InfoGrouping();
    infoGroupProperties.setName(name);
    infoGroupProperties.setProjectDescription(projectDescription);

    if (!shiftType.equalsIgnoreCase("Sem Turno")) {
        infoGroupProperties.setShiftType(ShiftType.valueOf(shiftType));
    }

    if (differentiatedCapacity) {
        for (InfoShift info : infoShifts) {
            if (info.getLotacao() != 0) { //it means it was locked from students enrolment only
                if (!maximumCapacityString.equals("") && info.getGroupCapacity()
                        * Integer.parseInt(maximumCapacityString) > info.getLotacao()) {
                    ActionMessages actionErrors = new ActionMessages();
                    ActionMessage error = new ActionMessage("error.groupProperties.capacityOverflow");
                    actionErrors.add("error.groupProperties.capacityOverflow", error);
                    saveErrors(request, actionErrors);
                    return prepareCreateGroupProperties(mapping, form, request, response);
                }
            }
        }
        infoGroupProperties.setInfoShifts(infoShifts);
    }

    Integer maximumCapacity = null;
    Integer minimumCapacity = null;
    Integer idealCapacity = null;

    if (!maximumCapacityString.equals("")) {
        maximumCapacity = new Integer(maximumCapacityString);
        infoGroupProperties.setMaximumCapacity(maximumCapacity);
    }

    if (!minimumCapacityString.equals("")) {
        minimumCapacity = new Integer(minimumCapacityString);
        if (maximumCapacity != null) {
            if (minimumCapacity.compareTo(maximumCapacity) > 0) {
                ActionMessages actionErrors = new ActionMessages();
                ActionMessage error = null;
                error = new ActionMessage("error.groupProperties.minimum");
                actionErrors.add("error.groupProperties.minimum", error);
                saveErrors(request, actionErrors);
                return prepareCreateGroupProperties(mapping, form, request, response);
            }
        }
        infoGroupProperties.setMinimumCapacity(minimumCapacity);
    }

    if (!idealCapacityString.equals("")) {

        idealCapacity = new Integer(idealCapacityString);

        if (!minimumCapacityString.equals("")) {
            if (idealCapacity.compareTo(minimumCapacity) < 0) {
                ActionMessages actionErrors = new ActionMessages();
                ActionMessage error = null;
                error = new ActionMessage("error.groupProperties.ideal.minimum");
                actionErrors.add("error.groupProperties.ideal.minimum", error);
                saveErrors(request, actionErrors);
                return prepareCreateGroupProperties(mapping, form, request, response);
            }
        }

        if (!maximumCapacityString.equals("")) {
            if (idealCapacity.compareTo(maximumCapacity) > 0) {
                ActionMessages actionErrors = new ActionMessages();
                ActionMessage error = null;
                error = new ActionMessage("error.groupProperties.ideal.maximum");
                actionErrors.add("error.groupProperties.ideal.maximum", error);
                saveErrors(request, actionErrors);
                return prepareCreateGroupProperties(mapping, form, request, response);
            }
        }
        infoGroupProperties.setIdealCapacity(idealCapacity);
    }

    if (!groupMaximumNumber.equals("")) {
        infoGroupProperties.setGroupMaximumNumber(new Integer(groupMaximumNumber));
    }

    infoGroupProperties.setDifferentiatedCapacity(differentiatedCapacity);

    EnrolmentGroupPolicyType enrolmentPolicy;
    if (optional.booleanValue()) {
        enrolmentPolicy = new EnrolmentGroupPolicyType(1);
    } else {
        enrolmentPolicy = new EnrolmentGroupPolicyType(2);
    }
    infoGroupProperties.setEnrolmentPolicy(enrolmentPolicy);
    infoGroupProperties.setAutomaticEnrolment(automaticEnrolment);
    Calendar enrolmentBeginDay = null;
    if (!enrolmentBeginDayString.equals("")) {
        String[] beginDate = enrolmentBeginDayString.split("/");
        enrolmentBeginDay = Calendar.getInstance();
        enrolmentBeginDay.set(Calendar.DAY_OF_MONTH, (new Integer(beginDate[0])).intValue());
        enrolmentBeginDay.set(Calendar.MONTH, (new Integer(beginDate[1])).intValue() - 1);
        enrolmentBeginDay.set(Calendar.YEAR, (new Integer(beginDate[2])).intValue());

        if (!enrolmentBeginHourString.equals("")) {
            String[] beginHour = enrolmentBeginHourString.split(":");
            enrolmentBeginDay.set(Calendar.HOUR_OF_DAY, (new Integer(beginHour[0])).intValue());
            enrolmentBeginDay.set(Calendar.MINUTE, (new Integer(beginHour[1])).intValue());
            enrolmentBeginDay.set(Calendar.SECOND, 0);
        }
    } else {
        ActionMessages actionErrors = new ActionMessages();
        ActionMessage error = new ActionMessage("error.groupProperties.missingEnrolmentBeginDay");
        actionErrors.add("error.groupProperties.missingEnrolmentBeginDay", error);
        saveErrors(request, actionErrors);
        return prepareCreateGroupProperties(mapping, form, request, response);
    }

    infoGroupProperties.setEnrolmentBeginDay(enrolmentBeginDay);

    Calendar enrolmentEndDay = null;
    if (!enrolmentEndDayString.equals("")) {
        String[] endDate = enrolmentEndDayString.split("/");
        enrolmentEndDay = Calendar.getInstance();
        enrolmentEndDay.set(Calendar.DAY_OF_MONTH, (new Integer(endDate[0])).intValue());
        enrolmentEndDay.set(Calendar.MONTH, (new Integer(endDate[1])).intValue() - 1);
        enrolmentEndDay.set(Calendar.YEAR, (new Integer(endDate[2])).intValue());

        if (!enrolmentEndHourString.equals("")) {
            String[] endHour = enrolmentEndHourString.split(":");
            enrolmentEndDay.set(Calendar.HOUR_OF_DAY, (new Integer(endHour[0])).intValue());
            enrolmentEndDay.set(Calendar.MINUTE, (new Integer(endHour[1])).intValue());
            enrolmentEndDay.set(Calendar.SECOND, 0);
        }
    } else {
        ActionMessages actionErrors = new ActionMessages();
        ActionMessage error = new ActionMessage("error.groupProperties.missingEnrolmentEndDay");
        actionErrors.add("error.groupProperties.missingEnrolmentEndDay", error);
        saveErrors(request, actionErrors);
        return prepareCreateGroupProperties(mapping, form, request, response);
    }

    float compareDate = enrolmentBeginDay.compareTo(enrolmentEndDay);

    if (compareDate >= 0.0) {
        ActionMessages actionErrors = new ActionMessages();
        ActionMessage error = null;
        error = new ActionMessage("error.manager.wrongDates");
        actionErrors.add("error.manager.wrongDates", error);
        saveErrors(request, actionErrors);
        return prepareCreateGroupProperties(mapping, form, request, response);
    }

    infoGroupProperties.setEnrolmentEndDay(enrolmentEndDay);

    String objectCode = getExecutionCourse(request).getExternalId();
    try {
        CreateGrouping.runCreateGrouping(objectCode, infoGroupProperties);
    } catch (DomainException e) {
        ActionMessages actionErrors = new ActionMessages();
        ActionMessage error = new ActionMessage("error.exception.existing.groupProperties");
        actionErrors.add("error.exception.existing.groupProperties", error);
        saveErrors(request, actionErrors);
        return prepareCreateGroupProperties(mapping, form, request, response);
    } catch (FenixServiceException fenixServiceException) {
        throw new FenixActionException(fenixServiceException.getMessage());
    }
    return prepareViewExecutionCourseProjects(mapping, form, request, response);
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.teacher.StudentGroupManagementDA.java

public ActionForward editGroupProperties(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {

    DynaActionForm editGroupPropertiesForm = (DynaActionForm) form;
    String groupPropertiesString = request.getParameter("groupPropertiesCode");
    String groupPropertiesCode = groupPropertiesString;
    String name = (String) editGroupPropertiesForm.get("name");
    String projectDescription = (String) editGroupPropertiesForm.get("projectDescription");
    String maximumCapacityString = (String) editGroupPropertiesForm.get("maximumCapacity");
    String minimumCapacityString = (String) editGroupPropertiesForm.get("minimumCapacity");
    String idealCapacityString = (String) editGroupPropertiesForm.get("idealCapacity");

    String groupMaximumNumber = (String) editGroupPropertiesForm.get("groupMaximumNumber");
    String enrolmentBeginDayString = (String) editGroupPropertiesForm.get("enrolmentBeginDayFormatted");
    String enrolmentBeginHourString = (String) editGroupPropertiesForm.get("enrolmentBeginHourFormatted");
    String enrolmentEndDayString = (String) editGroupPropertiesForm.get("enrolmentEndDayFormatted");
    String enrolmentEndHourString = (String) editGroupPropertiesForm.get("enrolmentEndHourFormatted");
    String shiftType = (String) editGroupPropertiesForm.get("shiftType");
    String enrolmentPolicy = (String) editGroupPropertiesForm.get("enrolmentPolicy");
    Boolean automaticEnrolment = getAutomaticEnrolment(editGroupPropertiesForm);
    Boolean differentiatedCapacity = getDifferentiatedCapacity(editGroupPropertiesForm);

    final ArrayList<InfoShift> infoShifts = getRenderedObject("shiftsTable");

    if ("".equals(name)) {
        ActionMessages actionErrors = new ActionMessages();
        ActionMessage error = new ActionMessage("error.groupProperties.missingName");
        actionErrors.add("error.groupProperties.missingName", error);
        saveErrors(request, actionErrors);
        return prepareEditGroupProperties(mapping, form, request, response);
    }//w  ww  . j  a v  a  2 s . c o m

    Calendar enrolmentBeginDay = null;
    if (!enrolmentBeginDayString.equals("")) {
        String[] beginDate = enrolmentBeginDayString.split("/");
        enrolmentBeginDay = Calendar.getInstance();
        enrolmentBeginDay.set(Calendar.DAY_OF_MONTH, (new Integer(beginDate[0])).intValue());
        enrolmentBeginDay.set(Calendar.MONTH, (new Integer(beginDate[1])).intValue() - 1);
        enrolmentBeginDay.set(Calendar.YEAR, (new Integer(beginDate[2])).intValue());

        if (!enrolmentBeginHourString.equals("")) {
            String[] beginHour = enrolmentBeginHourString.split(":");
            enrolmentBeginDay.set(Calendar.HOUR_OF_DAY, (new Integer(beginHour[0])).intValue());
            enrolmentBeginDay.set(Calendar.MINUTE, (new Integer(beginHour[1])).intValue());
            enrolmentBeginDay.set(Calendar.SECOND, 0);
        }
    }
    Calendar enrolmentEndDay = null;
    if (!enrolmentEndDayString.equals("")) {
        String[] endDate = enrolmentEndDayString.split("/");
        enrolmentEndDay = Calendar.getInstance();
        enrolmentEndDay.set(Calendar.DAY_OF_MONTH, (new Integer(endDate[0])).intValue());
        enrolmentEndDay.set(Calendar.MONTH, (new Integer(endDate[1])).intValue() - 1);
        enrolmentEndDay.set(Calendar.YEAR, (new Integer(endDate[2])).intValue());

        if (!enrolmentEndHourString.equals("")) {
            String[] endHour = enrolmentEndHourString.split(":");
            enrolmentEndDay.set(Calendar.HOUR_OF_DAY, (new Integer(endHour[0])).intValue());
            enrolmentEndDay.set(Calendar.MINUTE, (new Integer(endHour[1])).intValue());
            enrolmentEndDay.set(Calendar.SECOND, 0);
        }
    }

    float compareDate = enrolmentBeginDay.compareTo(enrolmentEndDay);

    if (compareDate >= 0.0) {
        ActionMessages actionErrors = new ActionMessages();
        ActionMessage error = null;
        error = new ActionMessage("error.manager.wrongDates");
        actionErrors.add("error.manager.wrongDates", error);
        saveErrors(request, actionErrors);
        return prepareEditGroupProperties(mapping, form, request, response);
    }

    InfoGrouping infoGroupProperties = new InfoGrouping();
    infoGroupProperties.setExternalId(groupPropertiesCode);
    infoGroupProperties.setEnrolmentBeginDay(enrolmentBeginDay);
    infoGroupProperties.setEnrolmentEndDay(enrolmentEndDay);
    infoGroupProperties.setEnrolmentPolicy(new EnrolmentGroupPolicyType(new Integer(enrolmentPolicy)));
    infoGroupProperties.setAutomaticEnrolment(automaticEnrolment);
    infoGroupProperties.setDifferentiatedCapacity(differentiatedCapacity);

    if (differentiatedCapacity) {
        for (InfoShift info : infoShifts) {
            if (!maximumCapacityString.equals("")
                    && info.getGroupCapacity() * Integer.parseInt(maximumCapacityString) > info.getLotacao()) {
                ActionMessages actionErrors = new ActionMessages();
                ActionMessage error = null;
                error = new ActionMessage("error.groupProperties.capacityOverflow");
                actionErrors.add("error.groupProperties.capacityOverflow", error);
                saveErrors(request, actionErrors);
                return prepareEditGroupProperties(mapping, form, request, response);
            }
        }
        infoGroupProperties.setInfoShifts(infoShifts);
    }

    infoGroupProperties.setDifferentiatedCapacity(differentiatedCapacity);

    if (!groupMaximumNumber.equals("")) {
        infoGroupProperties.setGroupMaximumNumber(new Integer(groupMaximumNumber));
    }
    Integer maximumCapacity = null;
    Integer minimumCapacity = null;
    Integer idealCapacity = null;

    if (!maximumCapacityString.equals("")) {
        maximumCapacity = new Integer(maximumCapacityString);
        infoGroupProperties.setMaximumCapacity(maximumCapacity);
    }

    if (!minimumCapacityString.equals("")) {
        minimumCapacity = new Integer(minimumCapacityString);
        if (maximumCapacity != null) {
            if (minimumCapacity.compareTo(maximumCapacity) > 0) {
                ActionMessages actionErrors = new ActionMessages();
                ActionMessage error = null;
                error = new ActionMessage("error.groupProperties.minimum");
                actionErrors.add("error.groupProperties.minimum", error);
                saveErrors(request, actionErrors);
                return prepareEditGroupProperties(mapping, form, request, response);

            }
        }
        infoGroupProperties.setMinimumCapacity(minimumCapacity);
    }

    if (!idealCapacityString.equals("")) {

        idealCapacity = new Integer(idealCapacityString);

        if (!minimumCapacityString.equals("")) {
            if (idealCapacity.compareTo(minimumCapacity) < 0) {
                ActionMessages actionErrors = new ActionMessages();
                ActionMessage error = null;
                error = new ActionMessage("error.groupProperties.ideal.minimum");
                actionErrors.add("error.groupProperties.ideal.minimum", error);
                saveErrors(request, actionErrors);
                return prepareEditGroupProperties(mapping, form, request, response);

            }
        }

        if (!maximumCapacityString.equals("")) {
            if (idealCapacity.compareTo(maximumCapacity) > 0) {
                ActionMessages actionErrors = new ActionMessages();
                ActionMessage error = null;
                error = new ActionMessage("error.groupProperties.ideal.maximum");
                actionErrors.add("error.groupProperties.ideal.maximum", error);
                saveErrors(request, actionErrors);
                return prepareEditGroupProperties(mapping, form, request, response);

            }
        }

        infoGroupProperties.setIdealCapacity(idealCapacity);
    }

    infoGroupProperties.setName(name);
    infoGroupProperties.setProjectDescription(projectDescription);

    if (!shiftType.equalsIgnoreCase("Sem Turno")) {
        infoGroupProperties.setShiftType(ShiftType.valueOf(shiftType));
    }
    String objectCode = getExecutionCourse(request).getExternalId();
    List errors = new ArrayList();
    try {
        errors = EditGrouping.runEditGrouping(objectCode, infoGroupProperties);
    } catch (InvalidSituationServiceException e) {
        ActionMessages actionErrors = new ActionMessages();
        ActionMessage error = null;
        error = new ActionMessage("error.noGroupProperties");
        actionErrors.add("error.noGroupProperties", error);
        saveErrors(request, actionErrors);
        return prepareViewExecutionCourseProjects(mapping, form, request, response);
    } catch (DomainException e) {
        ActionMessages actionErrors = new ActionMessages();
        ActionMessage error = null;
        error = new ActionMessage(e.getArgs()[0]);
        actionErrors.add("error.noGroupProperties", error);
        saveErrors(request, actionErrors);
        return prepareViewExecutionCourseProjects(mapping, form, request, response);
    } catch (FenixServiceException e) {
        throw new FenixActionException(e);
    }
    if (errors.size() != 0) {
        ActionMessages actionErrors = new ActionMessages();

        Iterator iterErrors = errors.iterator();
        ActionMessage errorInt = null;
        errorInt = new ActionMessage("error.exception.editGroupProperties");
        actionErrors.add("error.exception.editGroupProperties", errorInt);
        while (iterErrors.hasNext()) {
            Integer intError = (Integer) iterErrors.next();

            if (intError.equals(Integer.valueOf(-1))) {
                ActionMessage error = null;
                error = new ActionMessage("error.exception.nrOfGroups.editGroupProperties");
                actionErrors.add("error.exception.nrOfGroups.editGroupProperties", error);
            }
            if (intError.equals(Integer.valueOf(-2))) {
                ActionMessage error = null;
                error = new ActionMessage("error.exception.maximumCapacity.editGroupProperties");
                actionErrors.add("error.exception.maximumCapacity.editGroupProperties", error);
            }
            if (intError.equals(Integer.valueOf(-3))) {
                ActionMessage error = null;
                error = new ActionMessage("error.exception.minimumCapacity.editGroupProperties");
                actionErrors.add("error.exception.minimumCapacity.editGroupProperties", error);
            }
        }
        saveErrors(request, actionErrors);

    }
    return prepareViewExecutionCourseProjects(mapping, form, request, response);
}

From source file:org.mifosplatform.infrastructure.sms.scheduler.SmsMessageScheduledJobServiceImpl.java

/**
 * handles the sending of messages to the intermediate gateway and updating of the external ID, status and sources address
 * of each message/*from   w  ww. j  a va2  s .c o  m*/
 * 
 * @param httpEntity
 * @param apiAuthUsername
 * @param apiAuthPassword
 * @param apiBaseUrl
 * @param smsCredits
 * @param sourceAddress
 * @return the number of SMS credits left
 */
private Integer sendMessages(final StringBuilder httpEntity, final String apiAuthUsername,
        final String apiAuthPassword, final String apiBaseUrl, Integer smsCredits, final String sourceAddress,
        final Integer smsCreditReminder) {
    // trust all SSL certificates
    trustAllSSLCertificates();

    // make request
    final ResponseEntity<SmsMessageApiResponseData> entity = restTemplate.postForEntity(apiBaseUrl + "/queue",
            getHttpEntity(httpEntity.toString(), apiAuthUsername, apiAuthPassword),
            SmsMessageApiResponseData.class);

    final List<SmsMessageDeliveryReportData> smsMessageDeliveryReportDataList = entity.getBody().getData();
    final Iterator<SmsMessageDeliveryReportData> deliveryReportIterator = smsMessageDeliveryReportDataList
            .iterator();

    while (deliveryReportIterator.hasNext()) {
        SmsMessageDeliveryReportData smsMessageDeliveryReportData = deliveryReportIterator.next();

        SmsMessage smsMessage = this.smsMessageRepository.findOne(smsMessageDeliveryReportData.getId());

        if (!smsMessageDeliveryReportData.getHasError()) {

            // initially set the status type enum to 100
            Integer statusType = SmsMessageStatusType.PENDING.getValue();

            switch (smsMessageDeliveryReportData.getDeliveryStatus()) {
            case 100:
            case 200:
                statusType = SmsMessageStatusType.SENT.getValue();
                break;

            case 300:
                statusType = SmsMessageStatusType.DELIVERED.getValue();
                break;

            case 400:
                statusType = SmsMessageStatusType.FAILED.getValue();
                break;

            default:
                statusType = SmsMessageStatusType.INVALID.getValue();
                break;
            }

            // update the externalId of the SMS message
            smsMessage.setExternalId(smsMessageDeliveryReportData.getExternalId());

            // update the SMS message sender
            smsMessage.setSourceAddress(sourceAddress);

            // update the status Type enum
            smsMessage.setStatusType(statusType);

            // deduct one credit from the tenant's SMS credits
            smsCredits--;
            if (smsCreditReminder.compareTo(smsCredits) == 0) {
                this.sendEmailLowSmsCreditReminder(smsCredits);
            }

        } else {
            Integer statusType = SmsMessageStatusType.FAILED.getValue();

            // update the status Type enum
            smsMessage.setStatusType(statusType);
        }

        // save the SmsMessage entity
        this.smsMessageRepository.save(smsMessage);
    }

    return smsCredits;
}

From source file:org.apache.fineract.infrastructure.sms.scheduler.SmsMessageScheduledJobServiceImpl.java

/**
 * handles the sending of messages to the intermediate gateway and updating of the external ID, status and sources address
 * of each message// w w w  . ja  v a 2  s  . c  om
 * 
 * @param httpEntity
 * @param apiAuthUsername
 * @param apiAuthPassword
 * @param apiBaseUrl
 * @param smsCredits
 * @param sourceAddress
 * @return the number of SMS credits left
 */
private Integer sendMessages(final StringBuilder httpEntity, final String apiAuthUsername,
        final String apiAuthPassword, final String apiBaseUrl, Integer smsCredits, final String sourceAddress,
        final Integer smsCreditReminder) {
    // trust all SSL certificates
    trustAllSSLCertificates();

    // make request
    final ResponseEntity<SmsMessageApiResponseData> entity = restTemplate.postForEntity(apiBaseUrl + "/queue",
            getHttpEntity(httpEntity.toString(), apiAuthUsername, apiAuthPassword),
            SmsMessageApiResponseData.class);

    final List<SmsMessageDeliveryReportData> smsMessageDeliveryReportDataList = entity.getBody().getData();
    final Iterator<SmsMessageDeliveryReportData> deliveryReportIterator = smsMessageDeliveryReportDataList
            .iterator();

    while (deliveryReportIterator.hasNext()) {
        SmsMessageDeliveryReportData smsMessageDeliveryReportData = deliveryReportIterator.next();

        if (!smsMessageDeliveryReportData.getHasError()) {
            SmsMessage smsMessage = this.smsMessageRepository.findOne(smsMessageDeliveryReportData.getId());

            // initially set the status type enum to 100
            Integer statusType = SmsMessageStatusType.PENDING.getValue();

            switch (smsMessageDeliveryReportData.getDeliveryStatus()) {
            case 100:
            case 200:
                statusType = SmsMessageStatusType.SENT.getValue();
                break;

            case 300:
                statusType = SmsMessageStatusType.DELIVERED.getValue();
                break;

            case 400:
                statusType = SmsMessageStatusType.FAILED.getValue();
                break;

            default:
                statusType = SmsMessageStatusType.INVALID.getValue();
                break;
            }

            // update the externalId of the SMS message
            smsMessage.setExternalId(smsMessageDeliveryReportData.getExternalId());

            // update the SMS message sender
            smsMessage.setSourceAddress(sourceAddress);

            // update the status Type enum
            smsMessage.setStatusType(statusType);

            // save the SmsMessage entity
            this.smsMessageRepository.save(smsMessage);

            // deduct one credit from the tenant's SMS credits
            smsCredits--;
            if (smsCreditReminder.compareTo(smsCredits) == 0) {
                this.sendEmailLowSmsCreditReminder(smsCredits);
            }
        }
    }

    return smsCredits;
}

From source file:org.kuali.kra.coi.disclosure.CoiDisclosureServiceImpl.java

private List<InstitutionalProposal> getInstitutionalProposals(
        List<InstitutionalProposalPerson> proposalPersons) {
    List<InstitutionalProposal> proposals = new ArrayList<InstitutionalProposal>();
    Map<String, Integer> propNumbers = new HashMap<String, Integer>();
    Map<String, String> propPerson = new HashMap<String, String>();
    for (InstitutionalProposalPerson proposalPerson : proposalPersons) {
        Integer newSequenceNumber = proposalPerson.getSequenceNumber();
        Integer oldSequenceNumber = propNumbers.get(proposalPerson.getProposalNumber());
        if ((oldSequenceNumber == null) || (oldSequenceNumber.compareTo(newSequenceNumber) < 0)) {
            propNumbers.put(proposalPerson.getProposalNumber(), newSequenceNumber);
            propPerson.put(proposalPerson.getProposalNumber(), proposalPerson.getPersonId());
        }/*w ww .j a v a 2  s .c om*/
    }
    for (String propNumber : propNumbers.keySet()) {
        Map<String, Object> ipFieldValues = new HashMap<String, Object>();
        ipFieldValues.put("proposalNumber", propNumber);
        ipFieldValues.put("sequenceNumber", propNumbers.get(propNumber));
        String personId = propPerson.get(propNumber);
        // get singleton list of IP's that match IP number
        List<InstitutionalProposal> searchResults = (List<InstitutionalProposal>) businessObjectService
                .findMatching(InstitutionalProposal.class, ipFieldValues);
        for (InstitutionalProposal institutionalProposal : searchResults) {
            if (isInstitutionalProposalDisclosurable(institutionalProposal)
                    && !isProjectReported(institutionalProposal.getProposalNumber(),
                            CoiDisclosureEventType.INSTITUTIONAL_PROPOSAL, personId)) {
                proposals.add(institutionalProposal);
            }
        }
    }
    return proposals;

}

From source file:org.sakaiproject.tool.assessment.ui.listener.author.ItemAddListener.java

/**
 ** shift sequence number down when inserting or reordering
 **//*w  ww.  ja  v  a  2 s. c o m*/

public void shiftSequences(ItemService delegate, SectionFacade sectfacade, Integer currSeq) {
    Set itemset = sectfacade.getItemFacadeSet();
    Iterator iter = itemset.iterator();
    while (iter.hasNext()) {
        ItemFacade itemfacade = (ItemFacade) iter.next();
        Integer itemfacadeseq = itemfacade.getSequence();
        if (itemfacadeseq.compareTo(currSeq) > 0) {
            itemfacade.setSequence(Integer.valueOf(itemfacadeseq.intValue() + 1));
            delegate.saveItem(itemfacade);
        }
    }
}

From source file:org.sakaiproject.tool.assessment.ui.listener.author.ItemAddListener.java

private void shiftItemsInOrigSection(ItemService delegate, SectionFacade sectfacade, Integer currSeq) {
    Set itemset = sectfacade.getItemFacadeSet();
    // should be size-1 now.
    Iterator iter = itemset.iterator();
    while (iter.hasNext()) {
        ItemFacade itemfacade = (ItemFacade) iter.next();
        Integer itemfacadeseq = itemfacade.getSequence();
        if (itemfacadeseq.compareTo(currSeq) > 0) {
            itemfacade.setSequence(Integer.valueOf(itemfacadeseq.intValue() - 1));
            delegate.saveItem(itemfacade);
        }//from  w  w w . j a v a2s.  com
    }

}

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * Sorts the changes so that they can be executed by the database. E.g. tables need to be created before
 * they can be referenced by foreign keys, indexes should be dropped before a table is dropped etc.
 * /* w  w w. j  a  v a 2s  .co  m*/
 * @param changes The original changes
 * @return The sorted changes - this can be the original list object or a new one
 */
protected List sortChanges(List changes) {
    final Map typeOrder = new HashMap();

    typeOrder.put(RemoveForeignKeyChange.class, new Integer(0));
    typeOrder.put(RemoveIndexChange.class, new Integer(1));
    typeOrder.put(RemoveTableChange.class, new Integer(2));
    typeOrder.put(RecreateTableChange.class, new Integer(3));
    typeOrder.put(RemovePrimaryKeyChange.class, new Integer(3));
    typeOrder.put(RemoveColumnChange.class, new Integer(4));
    typeOrder.put(ColumnDefinitionChange.class, new Integer(5));
    typeOrder.put(ColumnOrderChange.class, new Integer(5));
    typeOrder.put(AddColumnChange.class, new Integer(5));
    typeOrder.put(PrimaryKeyChange.class, new Integer(5));
    typeOrder.put(AddPrimaryKeyChange.class, new Integer(6));
    typeOrder.put(AddTableChange.class, new Integer(7));
    typeOrder.put(AddIndexChange.class, new Integer(8));
    typeOrder.put(AddForeignKeyChange.class, new Integer(9));

    Collections.sort(changes, new Comparator() {
        public int compare(Object objA, Object objB) {
            Integer orderValueA = (Integer) typeOrder.get(objA.getClass());
            Integer orderValueB = (Integer) typeOrder.get(objB.getClass());

            if (orderValueA == null) {
                return (orderValueB == null ? 0 : 1);
            } else if (orderValueB == null) {
                return -1;
            } else {
                return orderValueA.compareTo(orderValueB);
            }
        }
    });
    return changes;
}

From source file:com.gst.portfolio.loanproduct.serialization.LoanProductDataValidator.java

public void validateMinMaxConstraints(final JsonElement element, final DataValidatorBuilder baseDataValidator,
        final LoanProduct loanProduct, Integer cycleNumber) {

    final Map<String, BigDecimal> minmaxValues = loanProduct
            .fetchBorrowerCycleVariationsForCycleNumber(cycleNumber);
    final String principalParameterName = "principal";
    BigDecimal principalAmount = null;
    BigDecimal minPrincipalAmount = null;
    BigDecimal maxPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(principalParameterName, element)) {
        principalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName,
                element);//from   ww w  . j a v a  2 s .  c o m
        minPrincipalAmount = minmaxValues.get(LoanProductConstants.minPrincipal);
        maxPrincipalAmount = minmaxValues.get(LoanProductConstants.maxPrincipal);
    }

    if ((minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)
            && (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)) {
        baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
                .inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount);
    } else {
        if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
            baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
                    .notLessThanMin(minPrincipalAmount);
        } else if (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
            baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
                    .notGreaterThanMax(maxPrincipalAmount);
        }
    }

    final String numberOfRepaymentsParameterName = "numberOfRepayments";
    Integer maxNumberOfRepayments = null;
    Integer minNumberOfRepayments = null;
    Integer numberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) {
        numberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element);
        if (minmaxValues.get(LoanProductConstants.minNumberOfRepayments) != null) {
            minNumberOfRepayments = minmaxValues.get(LoanProductConstants.minNumberOfRepayments)
                    .intValueExact();
        }
        if (minmaxValues.get(LoanProductConstants.maxNumberOfRepayments) != null) {
            maxNumberOfRepayments = minmaxValues.get(LoanProductConstants.maxNumberOfRepayments)
                    .intValueExact();
        }
    }

    if (maxNumberOfRepayments != null && maxNumberOfRepayments.compareTo(0) == 1) {
        if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
            baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
                    .inMinMaxRange(minNumberOfRepayments, maxNumberOfRepayments);
        } else {
            baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
                    .notGreaterThanMax(maxNumberOfRepayments);
        }
    } else if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
        baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments)
                .notLessThanMin(minNumberOfRepayments);
    }

    final String interestRatePerPeriodParameterName = "interestRatePerPeriod";
    BigDecimal interestRatePerPeriod = null;
    BigDecimal minInterestRatePerPeriod = null;
    BigDecimal maxInterestRatePerPeriod = null;
    if (this.fromApiJsonHelper.parameterExists(interestRatePerPeriodParameterName, element)) {
        interestRatePerPeriod = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, element);
        minInterestRatePerPeriod = minmaxValues.get(LoanProductConstants.minInterestRatePerPeriod);
        maxInterestRatePerPeriod = minmaxValues.get(LoanProductConstants.maxInterestRatePerPeriod);
    }
    if (maxInterestRatePerPeriod != null) {
        if (minInterestRatePerPeriod != null) {
            baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
                    .inMinAndMaxAmountRange(minInterestRatePerPeriod, maxInterestRatePerPeriod);
        } else {
            baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
                    .notGreaterThanMax(maxInterestRatePerPeriod);
        }
    } else if (minInterestRatePerPeriod != null) {
        baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
                .notLessThanMin(minInterestRatePerPeriod);
    }

}

From source file:org.apache.fineract.portfolio.loanproduct.serialization.LoanProductDataValidator.java

public void validateForCreate(final String json) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }//from   ww  w  . j  a  v  a 2s . c o m

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("loanproduct");

    final JsonElement element = this.fromApiJsonHelper.parse(json);

    final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
    baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);

    final String shortName = this.fromApiJsonHelper.extractStringNamed(LoanProductConstants.shortName, element);
    baseDataValidator.reset().parameter(LoanProductConstants.shortName).value(shortName).notBlank()
            .notExceedingLengthOf(4);

    final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
    baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500);

    if (this.fromApiJsonHelper.parameterExists("fundId", element)) {
        final Long fundId = this.fromApiJsonHelper.extractLongNamed("fundId", element);
        baseDataValidator.reset().parameter("fundId").value(fundId).ignoreIfNull().integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper
            .parameterExists(LoanProductConstants.minimumDaysBetweenDisbursalAndFirstRepayment, element)) {
        final Long minimumDaysBetweenDisbursalAndFirstRepayment = this.fromApiJsonHelper
                .extractLongNamed(LoanProductConstants.minimumDaysBetweenDisbursalAndFirstRepayment, element);
        baseDataValidator.reset().parameter(LoanProductConstants.minimumDaysBetweenDisbursalAndFirstRepayment)
                .value(minimumDaysBetweenDisbursalAndFirstRepayment).ignoreIfNull().integerGreaterThanZero();
    }

    final Boolean includeInBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed("includeInBorrowerCycle",
            element);
    baseDataValidator.reset().parameter("includeInBorrowerCycle").value(includeInBorrowerCycle).ignoreIfNull()
            .validateForBooleanValue();

    // terms
    final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
    baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3);

    final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element,
            Locale.getDefault());
    baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull()
            .inMinMaxRange(0, 6);

    final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element,
            Locale.getDefault());
    baseDataValidator.reset().parameter("inMultiplesOf").value(inMultiplesOf).ignoreIfNull()
            .integerZeroOrGreater();

    final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element);
    baseDataValidator.reset().parameter("principal").value(principal).positiveAmount();

    final String minPrincipalParameterName = "minPrincipal";
    BigDecimal minPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) {
        minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName,
                element);
        baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount).ignoreIfNull()
                .positiveAmount();
    }

    final String maxPrincipalParameterName = "maxPrincipal";
    BigDecimal maxPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) {
        maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName,
                element);
        baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).ignoreIfNull()
                .positiveAmount();
    }

    if (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) != -1) {

        if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) != -1) {
            baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount)
                    .notLessThanMin(minPrincipalAmount);
            if (minPrincipalAmount.compareTo(maxPrincipalAmount) <= 0 && principal != null) {
                baseDataValidator.reset().parameter("principal").value(principal)
                        .inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount);
            }
        } else if (principal != null) {
            baseDataValidator.reset().parameter("principal").value(principal)
                    .notGreaterThanMax(maxPrincipalAmount);
        }
    } else if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) != -1
            && principal != null) {
        baseDataValidator.reset().parameter("principal").value(principal).notLessThanMin(minPrincipalAmount);
    }

    final Integer numberOfRepayments = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("numberOfRepayments", element);
    baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notNull()
            .integerGreaterThanZero();

    final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments";
    Integer minNumberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) {
        minNumberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element);
        baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments)
                .ignoreIfNull().integerGreaterThanZero();
    }

    final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments";
    Integer maxNumberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) {
        maxNumberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element);
        baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments)
                .ignoreIfNull().integerGreaterThanZero();
    }

    if (maxNumberOfRepayments != null && maxNumberOfRepayments.compareTo(0) == 1) {
        if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
            baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments)
                    .notLessThanMin(minNumberOfRepayments);
            if (minNumberOfRepayments.compareTo(maxNumberOfRepayments) <= 0) {
                baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments)
                        .inMinMaxRange(minNumberOfRepayments, maxNumberOfRepayments);
            }
        } else {
            baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments)
                    .notGreaterThanMax(maxNumberOfRepayments);
        }
    } else if (minNumberOfRepayments != null && minNumberOfRepayments.compareTo(0) == 1) {
        baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments)
                .notLessThanMin(minNumberOfRepayments);
    }

    final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery",
            element);
    baseDataValidator.reset().parameter("repaymentEvery").value(repaymentEvery).notNull()
            .integerGreaterThanZero();

    final Integer repaymentFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("repaymentFrequencyType",
            element, Locale.getDefault());
    baseDataValidator.reset().parameter("repaymentFrequencyType").value(repaymentFrequencyType).notNull()
            .inMinMaxRange(0, 3);

    // settings
    final Integer amortizationType = this.fromApiJsonHelper.extractIntegerNamed("amortizationType", element,
            Locale.getDefault());
    baseDataValidator.reset().parameter("amortizationType").value(amortizationType).notNull().inMinMaxRange(0,
            1);

    final Integer interestType = this.fromApiJsonHelper.extractIntegerNamed("interestType", element,
            Locale.getDefault());
    baseDataValidator.reset().parameter("interestType").value(interestType).notNull().inMinMaxRange(0, 1);

    final Integer interestCalculationPeriodType = this.fromApiJsonHelper
            .extractIntegerNamed("interestCalculationPeriodType", element, Locale.getDefault());
    baseDataValidator.reset().parameter("interestCalculationPeriodType").value(interestCalculationPeriodType)
            .notNull().inMinMaxRange(0, 1);

    final BigDecimal inArrearsTolerance = this.fromApiJsonHelper
            .extractBigDecimalWithLocaleNamed("inArrearsTolerance", element);
    baseDataValidator.reset().parameter("inArrearsTolerance").value(inArrearsTolerance).ignoreIfNull()
            .zeroOrPositiveAmount();

    final Long transactionProcessingStrategyId = this.fromApiJsonHelper
            .extractLongNamed("transactionProcessingStrategyId", element);
    baseDataValidator.reset().parameter("transactionProcessingStrategyId")
            .value(transactionProcessingStrategyId).notNull().integerGreaterThanZero();

    // grace validation
    final Integer graceOnPrincipalPayment = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element);
    baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment)
            .zeroOrPositiveAmount();

    final Integer graceOnInterestPayment = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("graceOnInterestPayment", element);
    baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment)
            .zeroOrPositiveAmount();

    final Integer graceOnInterestCharged = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("graceOnInterestCharged", element);
    baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged)
            .zeroOrPositiveAmount();

    final Integer graceOnArrearsAgeing = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(LoanProductConstants.graceOnArrearsAgeingParameterName, element);
    baseDataValidator.reset().parameter(LoanProductConstants.graceOnArrearsAgeingParameterName)
            .value(graceOnArrearsAgeing).integerZeroOrGreater();

    final Integer overdueDaysForNPA = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(LoanProductConstants.overdueDaysForNPAParameterName, element);
    baseDataValidator.reset().parameter(LoanProductConstants.overdueDaysForNPAParameterName)
            .value(overdueDaysForNPA).integerZeroOrGreater();

    /**
     * { @link DaysInYearType }
     */
    final Integer daysInYearType = this.fromApiJsonHelper.extractIntegerNamed(
            LoanProductConstants.daysInYearTypeParameterName, element, Locale.getDefault());
    baseDataValidator.reset().parameter(LoanProductConstants.daysInYearTypeParameterName).value(daysInYearType)
            .notNull().isOneOfTheseValues(1, 360, 364, 365);

    /**
     * { @link DaysInMonthType }
     */
    final Integer daysInMonthType = this.fromApiJsonHelper.extractIntegerNamed(
            LoanProductConstants.daysInMonthTypeParameterName, element, Locale.getDefault());
    baseDataValidator.reset().parameter(LoanProductConstants.daysInMonthTypeParameterName)
            .value(daysInMonthType).notNull().isOneOfTheseValues(1, 30);

    if (this.fromApiJsonHelper.parameterExists(
            LoanProductConstants.accountMovesOutOfNPAOnlyOnArrearsCompletionParamName, element)) {
        Boolean npaChangeConfig = this.fromApiJsonHelper.extractBooleanNamed(
                LoanProductConstants.accountMovesOutOfNPAOnlyOnArrearsCompletionParamName, element);
        baseDataValidator.reset()
                .parameter(LoanProductConstants.accountMovesOutOfNPAOnlyOnArrearsCompletionParamName)
                .value(npaChangeConfig).notNull().isOneOfTheseValues(true, false);
    }

    // Interest recalculation settings
    final Boolean isInterestRecalculationEnabled = this.fromApiJsonHelper
            .extractBooleanNamed(LoanProductConstants.isInterestRecalculationEnabledParameterName, element);
    baseDataValidator.reset().parameter(LoanProductConstants.isInterestRecalculationEnabledParameterName)
            .value(isInterestRecalculationEnabled).notNull().isOneOfTheseValues(true, false);

    if (isInterestRecalculationEnabled != null) {
        if (isInterestRecalculationEnabled.booleanValue()) {
            validateInterestRecalculationParams(element, baseDataValidator, null);
        }
    }

    // interest rates
    if (this.fromApiJsonHelper.parameterExists("isLinkedToFloatingInterestRates", element)
            && this.fromApiJsonHelper.extractBooleanNamed("isLinkedToFloatingInterestRates", element) == true) {
        if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "interestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true");
        }

        if (this.fromApiJsonHelper.parameterExists("minInterestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("minInterestRatePerPeriod").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "minInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true");
        }

        if (this.fromApiJsonHelper.parameterExists("maxInterestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("maxInterestRatePerPeriod").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "maxInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true");
        }

        if (this.fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) {
            baseDataValidator.reset().parameter("interestRateFrequencyType").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "interestRateFrequencyType param is not supported when isLinkedToFloatingInterestRates is true");
        }
        if ((interestType == null || interestType != InterestMethod.DECLINING_BALANCE.getValue())
                || (isInterestRecalculationEnabled == null || isInterestRecalculationEnabled == false)) {
            baseDataValidator.reset().parameter("isLinkedToFloatingInterestRates").failWithCode(
                    "supported.only.for.declining.balance.interest.recalculation.enabled",
                    "Floating interest rates are supported only for declining balance and interest recalculation enabled loan products");
        }

        final Integer floatingRatesId = this.fromApiJsonHelper.extractIntegerNamed("floatingRatesId", element,
                Locale.getDefault());
        baseDataValidator.reset().parameter("floatingRatesId").value(floatingRatesId).notNull();

        final BigDecimal interestRateDifferential = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed("interestRateDifferential", element);
        baseDataValidator.reset().parameter("interestRateDifferential").value(interestRateDifferential)
                .notNull().zeroOrPositiveAmount();

        final String minDifferentialLendingRateParameterName = "minDifferentialLendingRate";
        BigDecimal minDifferentialLendingRate = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(minDifferentialLendingRateParameterName, element);
        baseDataValidator.reset().parameter(minDifferentialLendingRateParameterName)
                .value(minDifferentialLendingRate).notNull().zeroOrPositiveAmount();

        final String defaultDifferentialLendingRateParameterName = "defaultDifferentialLendingRate";
        BigDecimal defaultDifferentialLendingRate = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(defaultDifferentialLendingRateParameterName, element);
        baseDataValidator.reset().parameter(defaultDifferentialLendingRateParameterName)
                .value(defaultDifferentialLendingRate).notNull().zeroOrPositiveAmount();

        final String maxDifferentialLendingRateParameterName = "maxDifferentialLendingRate";
        BigDecimal maxDifferentialLendingRate = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(maxDifferentialLendingRateParameterName, element);
        baseDataValidator.reset().parameter(maxDifferentialLendingRateParameterName)
                .value(maxDifferentialLendingRate).notNull().zeroOrPositiveAmount();

        if (defaultDifferentialLendingRate != null
                && defaultDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
            if (minDifferentialLendingRate != null
                    && minDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter("defaultDifferentialLendingRate")
                        .value(defaultDifferentialLendingRate).notLessThanMin(minDifferentialLendingRate);
            }
        }

        if (maxDifferentialLendingRate != null && maxDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
            if (minDifferentialLendingRate != null
                    && minDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter("maxDifferentialLendingRate")
                        .value(maxDifferentialLendingRate).notLessThanMin(minDifferentialLendingRate);
            }
        }

        if (maxDifferentialLendingRate != null && maxDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
            if (defaultDifferentialLendingRate != null
                    && defaultDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter("maxDifferentialLendingRate")
                        .value(maxDifferentialLendingRate).notLessThanMin(defaultDifferentialLendingRate);
            }
        }

        final Boolean isFloatingInterestRateCalculationAllowed = this.fromApiJsonHelper
                .extractBooleanNamed("isFloatingInterestRateCalculationAllowed", element);
        baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed")
                .value(isFloatingInterestRateCalculationAllowed).notNull().isOneOfTheseValues(true, false);
    } else {
        if (this.fromApiJsonHelper.parameterExists("floatingRatesId", element)) {
            baseDataValidator.reset().parameter("floatingRatesId").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "floatingRatesId param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("interestRateDifferential", element)) {
            baseDataValidator.reset().parameter("interestRateDifferential").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "interestRateDifferential param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("minDifferentialLendingRate", element)) {
            baseDataValidator.reset().parameter("minDifferentialLendingRate").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "minDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("defaultDifferentialLendingRate", element)) {
            baseDataValidator.reset().parameter("defaultDifferentialLendingRate").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "defaultDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("maxDifferentialLendingRate", element)) {
            baseDataValidator.reset().parameter("maxDifferentialLendingRate").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "maxDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("isFloatingInterestRateCalculationAllowed", element)) {
            baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "isFloatingInterestRateCalculationAllowed param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element);
        baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod).notNull()
                .zeroOrPositiveAmount();

        final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod";
        BigDecimal minInterestRatePerPeriod = null;
        if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) {
            minInterestRatePerPeriod = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, element);
            baseDataValidator.reset().parameter(minInterestRatePerPeriodParameterName)
                    .value(minInterestRatePerPeriod).ignoreIfNull().zeroOrPositiveAmount();
        }

        final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod";
        BigDecimal maxInterestRatePerPeriod = null;
        if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) {
            maxInterestRatePerPeriod = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, element);
            baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName)
                    .value(maxInterestRatePerPeriod).ignoreIfNull().zeroOrPositiveAmount();
        }

        if (maxInterestRatePerPeriod != null && maxInterestRatePerPeriod.compareTo(BigDecimal.ZERO) != -1) {
            if (minInterestRatePerPeriod != null && minInterestRatePerPeriod.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName)
                        .value(maxInterestRatePerPeriod).notLessThanMin(minInterestRatePerPeriod);
                if (minInterestRatePerPeriod.compareTo(maxInterestRatePerPeriod) <= 0) {
                    baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod)
                            .inMinAndMaxAmountRange(minInterestRatePerPeriod, maxInterestRatePerPeriod);
                }
            } else {
                baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod)
                        .notGreaterThanMax(maxInterestRatePerPeriod);
            }
        } else if (minInterestRatePerPeriod != null
                && minInterestRatePerPeriod.compareTo(BigDecimal.ZERO) != -1) {
            baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod)
                    .notLessThanMin(minInterestRatePerPeriod);
        }

        final Integer interestRateFrequencyType = this.fromApiJsonHelper
                .extractIntegerNamed("interestRateFrequencyType", element, Locale.getDefault());
        baseDataValidator.reset().parameter("interestRateFrequencyType").value(interestRateFrequencyType)
                .notNull().inMinMaxRange(0, 3);
    }

    // Guarantee Funds
    Boolean holdGuaranteeFunds = false;
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.holdGuaranteeFundsParamName, element)) {
        holdGuaranteeFunds = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.holdGuaranteeFundsParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.holdGuaranteeFundsParamName)
                .value(holdGuaranteeFunds).notNull().isOneOfTheseValues(true, false);
    }

    if (holdGuaranteeFunds != null) {
        if (holdGuaranteeFunds) {
            validateGuaranteeParams(element, baseDataValidator, null);
        }
    }

    BigDecimal principalThresholdForLastInstallment = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(
            LoanProductConstants.principalThresholdForLastInstallmentParamName, element);
    baseDataValidator.reset().parameter(LoanProductConstants.principalThresholdForLastInstallmentParamName)
            .value(principalThresholdForLastInstallment).notLessThanMin(BigDecimal.ZERO)
            .notGreaterThanMax(BigDecimal.valueOf(100));
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.canDefineEmiAmountParamName, element)) {
        final Boolean canDefineInstallmentAmount = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.canDefineEmiAmountParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.canDefineEmiAmountParamName)
                .value(canDefineInstallmentAmount).isOneOfTheseValues(true, false);
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.installmentAmountInMultiplesOfParamName,
            element)) {
        final Integer installmentAmountInMultiplesOf = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(
                LoanProductConstants.installmentAmountInMultiplesOfParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.installmentAmountInMultiplesOfParamName)
                .value(installmentAmountInMultiplesOf).ignoreIfNull().integerGreaterThanZero();
    }

    // accounting related data validation
    final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element,
            Locale.getDefault());
    baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).notNull().inMinMaxRange(1,
            4);

    if (isCashBasedAccounting(accountingRuleType) || isAccrualBasedAccounting(accountingRuleType)) {

        final Long fundAccountId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue())
                .value(fundAccountId).notNull().integerGreaterThanZero();

        final Long loanPortfolioAccountId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue())
                .value(loanPortfolioAccountId).notNull().integerGreaterThanZero();

        final Long transfersInSuspenseAccountId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue())
                .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero();

        final Long incomeFromInterestId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue())
                .value(incomeFromInterestId).notNull().integerGreaterThanZero();

        final Long incomeFromFeeId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue())
                .value(incomeFromFeeId).notNull().integerGreaterThanZero();

        final Long incomeFromPenaltyId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue())
                .value(incomeFromPenaltyId).notNull().integerGreaterThanZero();

        final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_RECOVERY.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_RECOVERY.getValue())
                .value(incomeFromRecoveryAccountId).notNull().integerGreaterThanZero();

        final Long writeOffAccountId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue())
                .value(writeOffAccountId).notNull().integerGreaterThanZero();

        final Long overpaymentAccountId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue())
                .value(overpaymentAccountId).notNull().integerGreaterThanZero();

        validatePaymentChannelFundSourceMappings(baseDataValidator, element);
        validateChargeToIncomeAccountMappings(baseDataValidator, element);

    }

    if (isAccrualBasedAccounting(accountingRuleType)) {

        final Long receivableInterestAccountId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue())
                .value(receivableInterestAccountId).notNull().integerGreaterThanZero();

        final Long receivableFeeAccountId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue())
                .value(receivableFeeAccountId).notNull().integerGreaterThanZero();

        final Long receivablePenaltyAccountId = this.fromApiJsonHelper
                .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element);
        baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue())
                .value(receivablePenaltyAccountId).notNull().integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.useBorrowerCycleParameterName, element)) {
        final Boolean useBorrowerCycle = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.useBorrowerCycleParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.useBorrowerCycleParameterName)
                .value(useBorrowerCycle).ignoreIfNull().validateForBooleanValue();
        if (useBorrowerCycle) {
            validateBorrowerCycleVariations(element, baseDataValidator);
        }
    }

    validateMultiDisburseLoanData(baseDataValidator, element);

    validateLoanConfigurableAttributes(baseDataValidator, element);

    validateVariableInstallmentSettings(baseDataValidator, element);

    validatePartialPeriodSupport(interestCalculationPeriodType, baseDataValidator, element, null);

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}