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:org.apache.hadoop.hive.ql.exec.vector.VectorizationContext.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder(32);
    sb.append("Context name ").append(contextName).append(", level " + level + ", ");

    Comparator<Integer> comparerInteger = new Comparator<Integer>() {
        @Override/*from  w w w .  j ava  2s  . co  m*/
        public int compare(Integer o1, Integer o2) {
            return o1.compareTo(o2);
        }
    };

    Map<Integer, String> sortedColumnMap = new TreeMap<Integer, String>(comparerInteger);
    for (Map.Entry<String, Integer> entry : projectionColumnMap.entrySet()) {
        sortedColumnMap.put(entry.getValue(), entry.getKey());
    }
    sb.append("sorted projectionColumnMap ").append(sortedColumnMap).append(", ");

    sb.append("scratchColumnTypeNames ").append(Arrays.toString(getScratchColumnTypeNames()));

    return sb.toString();
}

From source file:org.kuali.student.enrollment.class2.courseoffering.service.impl.CourseOfferingManagementViewHelperServiceImpl.java

private List<RegistrationGroupWrapper> processRgData(SearchResultInfo searchResults,
        Map<String, ActivityOfferingClusterWrapper> clusterMap, Map<String, ActivityOfferingWrapper> aoMap)
        throws InvalidParameterException, MissingParameterException, DoesNotExistException,
        PermissionDeniedException, OperationFailedException {

    Map<String, RegistrationGroupWrapper> rgMap = new HashMap<String, RegistrationGroupWrapper>();
    Map<String, List<ActivityOfferingWrapper>> storedAOs = new HashMap<String, List<ActivityOfferingWrapper>>();

    processSearchResult(searchResults, aoMap, rgMap, storedAOs);

    for (Map.Entry<String, List<ActivityOfferingWrapper>> entry : storedAOs.entrySet()) {

        RegistrationGroupWrapper rgWrapper = rgMap.get(entry.getKey());

        //Sort aoList by AO types
        List<ActivityOfferingWrapper> aoList = storedAOs.get(entry.getKey());
        Collections.sort(aoList, new ActivityOfferingTypeComparator());

        boolean newLine = false;
        for (ActivityOfferingWrapper aoWrapper : aoList) {

            rgWrapper.getRgInfo().getActivityOfferingIds().add(aoWrapper.getAoInfo().getId());

            ActivityOfferingClusterWrapper clusterWrapper = clusterMap.get(aoWrapper.getAoClusterID());
            if (clusterWrapper.getRgWrapperList().contains(rgWrapper)) {
                clusterWrapper.getRgWrapperList().remove(rgWrapper);
            }/*from  ww  w .  j a va2s.  c o m*/
            if (newLine) {
                rgWrapper.setAoCluster(clusterWrapper.getAoCluster());
                rgWrapper.setAoClusterName(clusterWrapper.getClusterNameForDisplay());
            }

            rgWrapper.setStartTime(aoWrapper.getStartTime());
            rgWrapper.setEndTime(aoWrapper.getEndTime());
            rgWrapper.setWeekDays(aoWrapper.getWeekDays());

            //if there are more than one instructors re-arrange the rows
            String lineBreaksInstructors = computeLineBreaks(aoWrapper.getInstructorDisplayNames());

            //if there are more than one Scheduling Information re-arrange the rows
            String lineBreaksDeliveries = computeLineBreaks(aoWrapper.getDaysDisplayName());

            String lineBreaks;
            //Set different line breaks according to number of instructors and number of Scheduling Information (can it be simpler?)
            if (lineBreaksInstructors.length() < lineBreaksDeliveries.length()) {
                lineBreaks = lineBreaksDeliveries;
                lineBreaksDeliveries = lineBreaksDeliveries.substring(0,
                        lineBreaksDeliveries.length() - lineBreaksInstructors.length());
                lineBreaksInstructors = "";
            } else {
                lineBreaks = lineBreaksInstructors;
                lineBreaksInstructors = lineBreaksInstructors.substring(0,
                        lineBreaksInstructors.length() - lineBreaksDeliveries.length());
                lineBreaksDeliveries = "";
            }

            //Set the wrapper
            rgWrapper.setAoMaxEnrText(rgWrapper.getAoMaxEnrText() + (newLine ? "<br/>" : "")
                    + (aoWrapper.getAoInfo().getMaximumEnrollment() == null ? ""
                            : aoWrapper.getAoInfo().getMaximumEnrollment())
                    + lineBreaks);
            if (rgWrapper.getRgMaxEnrText() != null && rgWrapper.getRgMaxEnrText().length() > 1
                    && aoWrapper.getAoInfo().getMaximumEnrollment() != null) {
                Integer seats = Integer.parseInt(rgWrapper.getRgMaxEnrText());
                Integer nSeats = aoWrapper.getAoInfo().getMaximumEnrollment();
                if (seats.compareTo(nSeats) > 0) {
                    rgWrapper.setRgMaxEnrText(nSeats.toString());
                }
            } else {
                String rgSeats = aoWrapper.getAoInfo().getMaximumEnrollment() == null ? ""
                        : aoWrapper.getAoInfo().getMaximumEnrollment().toString();
                rgWrapper.setRgMaxEnrText(rgSeats);
            }
            rgWrapper.setAoStateNameText(rgWrapper.getAoStateNameText() + (newLine ? "<br/>" : "")
                    + aoWrapper.getStateName() + lineBreaks);

            String aoCode = getAoActivityCodeText(rgWrapper, aoWrapper, lineBreaks);
            rgWrapper.setAoActivityCodeText(
                    rgWrapper.getAoActivityCodeText() + (newLine ? "<br/>" : "") + aoCode);
            rgWrapper.setAoTypeNameText(rgWrapper.getAoTypeNameText() + (newLine ? "<br/>" : "")
                    + aoWrapper.getTypeName() + lineBreaks);
            rgWrapper.setStartTimeDisplay(rgWrapper.getStartTimeDisplay() + (newLine ? "<br/>" : "")
                    + aoWrapper.getStartTimeDisplay() + lineBreaksInstructors);
            rgWrapper.setEndTimeDisplay(rgWrapper.getEndTimeDisplay() + (newLine ? "<br/>" : "")
                    + aoWrapper.getEndTimeDisplay() + lineBreaksInstructors);
            rgWrapper.setDaysDisplayName(rgWrapper.getDaysDisplayName() + (newLine ? "<br/>" : "")
                    + aoWrapper.getDaysDisplayName() + lineBreaksInstructors);
            rgWrapper.setScheduledState(rgWrapper.getScheduledState() + (newLine ? "<br/>" : "")
                    + aoWrapper.getScheduledState() + lineBreaksInstructors);
            rgWrapper.setRoomName(rgWrapper.getRoomName() + (newLine ? "<br/>" : "") + aoWrapper.getRoomName()
                    + lineBreaksInstructors);
            rgWrapper.setBuildingName(rgWrapper.getBuildingName() + (newLine ? "<br/>" : "")
                    + aoWrapper.getBuildingName() + lineBreaksInstructors);
            boolean isScheduled = aoWrapper.getBuildingName().contains("uif-scheduled-dl");
            if (isScheduled) {
                rgWrapper.setBuildingCodeWithTooltip(aoWrapper.getBldgCodeSimple(), aoWrapper.getBuildingName(),
                        "uif-scheduled-dl");
            } else {
                rgWrapper.setBuildingCodeWithTooltip(aoWrapper.getBldgCodeSimple(), aoWrapper.getBuildingName(),
                        (newLine ? "<br>" : "uif-scheduled-dl"));
            }
            rgWrapper.setAoInstructorText(rgWrapper.getAoInstructorText() + (newLine ? "<br/>" : "")
                    + (aoWrapper.getInstructorDisplayNames() == null ? ""
                            : aoWrapper.getInstructorDisplayNames())
                    + lineBreaksDeliveries);

            clusterWrapper.getRgWrapperList().add(rgWrapper);

            newLine = true;
        }
    }

    return new ArrayList<RegistrationGroupWrapper>(rgMap.values());
}

From source file:org.kuali.student.enrollment.class2.courseoffering.service.impl.CourseOfferingManagementViewHelperServiceImpl.java

private List<RegistrationGroupWrapper> processRgDataForSocView(SearchResultInfo searchResults,
        Map<String, ActivityOfferingClusterWrapper> clusterMap, Map<String, ActivityOfferingWrapper> aoMap)
        throws InvalidParameterException, MissingParameterException, DoesNotExistException,
        PermissionDeniedException, OperationFailedException {

    Map<String, RegistrationGroupWrapper> rgMap = new HashMap<String, RegistrationGroupWrapper>();
    Map<String, List<ActivityOfferingWrapper>> storedAOs = new HashMap<String, List<ActivityOfferingWrapper>>();

    processSearchResult(searchResults, aoMap, rgMap, storedAOs);

    for (Map.Entry<String, List<ActivityOfferingWrapper>> entry : storedAOs.entrySet()) {

        RegistrationGroupWrapper rgWrapper = rgMap.get(entry.getKey());

        //Sort aoList by AO types
        Collections.sort(entry.getValue(), new ActivityOfferingTypeComparator());

        for (ActivityOfferingWrapper aoWrapper : entry.getValue()) {

            RegistrationGroupWrapper socRGWrapper = (RegistrationGroupWrapper) ObjectUtils.deepCopy(rgWrapper);

            ActivityOfferingClusterWrapper clusterWrapper = clusterMap.get(aoWrapper.getAoClusterID());
            clusterWrapper.getRgWrapperList().add(socRGWrapper);

            socRGWrapper.getRgInfo().getActivityOfferingIds().add(aoWrapper.getAoInfo().getId());
            socRGWrapper.setAoCluster(clusterWrapper.getAoCluster());
            socRGWrapper.setAoClusterName(clusterWrapper.getClusterNameForDisplay());

            socRGWrapper.setStartTime(aoWrapper.getStartTime());
            socRGWrapper.setEndTime(aoWrapper.getEndTime());
            socRGWrapper.setWeekDays(aoWrapper.getWeekDays());

            //if there are more than one instructors re-arrange the rows
            String lineBreaksInstructors = computeLineBreaks(aoWrapper.getInstructorDisplayNames());

            //if there are more than one Scheduling Information re-arrange the rows
            String lineBreaksDeliveries = computeLineBreaks(aoWrapper.getDaysDisplayName());

            //Set different line breaks according to number of instructors and number of Scheduling Information (can it be simpler?)
            String lineBreaks;//from w  w  w  .ja v  a 2 s.c o m
            if (lineBreaksInstructors.length() < lineBreaksDeliveries.length()) {
                lineBreaks = lineBreaksDeliveries;
                lineBreaksDeliveries = lineBreaksDeliveries.substring(0,
                        lineBreaksDeliveries.length() - lineBreaksInstructors.length());
                lineBreaksInstructors = "";
            } else {
                lineBreaks = lineBreaksInstructors;
                lineBreaksInstructors = lineBreaksInstructors.substring(0,
                        lineBreaksInstructors.length() - lineBreaksDeliveries.length());
                lineBreaksDeliveries = "";
            }

            //Set the wrapper
            socRGWrapper.setAoMaxEnrText(aoWrapper.getAoInfo().getMaximumEnrollment() == null ? ""
                    : aoWrapper.getAoInfo().getMaximumEnrollment().toString());
            socRGWrapper.setAoStateNameText(aoWrapper.getStateName());
            socRGWrapper.setAoActivityCodeText(getAoActivityCodeText(rgWrapper, aoWrapper, lineBreaks));

            socRGWrapper.setAoTypeNameText(aoWrapper.getTypeName() + lineBreaks);
            socRGWrapper.setStartTimeDisplay(aoWrapper.getStartTimeDisplay() + lineBreaksInstructors);
            socRGWrapper.setEndTimeDisplay(aoWrapper.getEndTimeDisplay() + lineBreaksInstructors);
            socRGWrapper.setDaysDisplayName(aoWrapper.getDaysDisplayName() + lineBreaksInstructors);
            socRGWrapper.setRoomName(aoWrapper.getRoomName() + lineBreaksInstructors);
            socRGWrapper.setBuildingName(aoWrapper.getBuildingName() + lineBreaksInstructors);
            socRGWrapper.setBuildingCodeWithTooltip(aoWrapper.getBldgCodeSimple(), aoWrapper.getBuildingName());
            socRGWrapper.setAoInstructorText(
                    (aoWrapper.getInstructorDisplayNames() == null ? "" : aoWrapper.getInstructorDisplayNames())
                            + lineBreaksDeliveries);
        }

    }

    for (Map.Entry<String, ActivityOfferingClusterWrapper> cluster : clusterMap.entrySet()) {

        List<RegistrationGroupWrapper> registrationGroupItems = cluster.getValue().getRgWrapperList();
        for (RegistrationGroupWrapper registrationGroupWrapper : registrationGroupItems) {
            RegistrationGroupWrapper regWrapper = new RegistrationGroupWrapper();
            for (RegistrationGroupWrapper partnerRegWrapper : registrationGroupItems) {
                if (registrationGroupWrapper.getRgInfo().getName()
                        .equals(partnerRegWrapper.getRgInfo().getName())
                        && !registrationGroupWrapper.getAoActivityCodeText()
                                .equals(partnerRegWrapper.getAoActivityCodeText())) {
                    regWrapper = partnerRegWrapper;
                    break;
                }
            }
            if (registrationGroupWrapper.getAoMaxEnrText() != null
                    && registrationGroupWrapper.getAoMaxEnrText().length() > 1) {
                if (regWrapper.getAoMaxEnrText() != null && regWrapper.getAoMaxEnrText().length() > 1) {
                    Integer seats = Integer.parseInt(registrationGroupWrapper.getAoMaxEnrText());
                    Integer nSeats = Integer.parseInt(regWrapper.getAoMaxEnrText());
                    if (seats.compareTo(nSeats) > 0) {
                        registrationGroupWrapper.setRgMaxEnrText(nSeats.toString());
                        regWrapper.setRgMaxEnrText(nSeats.toString());
                    } else {
                        registrationGroupWrapper.setRgMaxEnrText(seats.toString());
                        regWrapper.setRgMaxEnrText(seats.toString());
                    }
                }
            }
        }
    }

    return new ArrayList<RegistrationGroupWrapper>(rgMap.values());
}

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

public void validateForCreate(final String json) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }//from w  w w  . ja va 2 s  .co 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);

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

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

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

private void validateNumberOfRepaymentsMinMaxConstraint(final JsonElement element,
        final LoanProduct loanProduct, final DataValidatorBuilder baseDataValidator) {
    boolean numberOfRepaymentsUpdated = false;
    boolean minNumberOfRepaymentsUpdated = false;
    boolean maxNumberOfRepaymentsUpdated = false;

    final String numberOfRepaymentsParameterName = "numberOfRepayments";
    Integer numberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) {
        numberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element);
        numberOfRepaymentsUpdated = true;
    } else {//from   w w w  . j av a  2 s. com
        numberOfRepayments = loanProduct.getNumberOfRepayments();
    }

    final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments";
    Integer minNumberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) {
        minNumberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element);
        minNumberOfRepaymentsUpdated = true;
    } else {
        minNumberOfRepayments = loanProduct.getMinNumberOfRepayments();
    }

    final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments";
    Integer maxNumberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) {
        maxNumberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element);
        maxNumberOfRepaymentsUpdated = true;
    } else {
        maxNumberOfRepayments = loanProduct.getMaxNumberOfRepayments();
    }

    if (minNumberOfRepaymentsUpdated) {
        baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments)
                .ignoreIfNull().notGreaterThanMax(maxNumberOfRepayments);
    }

    if (maxNumberOfRepaymentsUpdated) {
        baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments)
                .notLessThanMin(minNumberOfRepayments);
    }

    if (numberOfRepaymentsUpdated || minNumberOfRepaymentsUpdated || maxNumberOfRepaymentsUpdated) {
        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);
        }
    }
}

From source file:org.intermine.bio.dataconversion.SgdConverter.java

private String getLength(String start, String end) throws NumberFormatException {
    Integer a = new Integer(start);
    Integer b = new Integer(end);

    // if the coordinates are on the crick strand, they need to be reversed
    // or they result in a negative number
    if (a.compareTo(b) > 0) {
        a = new Integer(end);
        b = new Integer(start);
    }/* ww w  .j a  v  a 2 s  . com*/

    Integer length = new Integer(b.intValue() - a.intValue());
    return length.toString();
}

From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasicPlus.CatBasicPlusControllerImpl.java

@Override
public int compare(TerminoVO tvoA, TerminoVO tvoB) {
    ///*from   ww  w. j ava2s. c  om*/
    // We are comparing term IDs of the form [0-9]+(.[0-9]+)* at the same
    // vocabulary term level; eg IDs for format terms run range from 4.1.1
    // to 4.1.33.  For ordering, we simply compare the leaf node numbers
    // the range for which is 1 to 33.
    //
    Integer idA = getIdInt(tvoA.getIdTermino());
    Integer idB = getIdInt(tvoB.getIdTermino());

    return idA.compareTo(idB);
}

From source file:org.kuali.ole.service.impl.OLEEResourceSearchServiceImpl.java

public void getPOInvoiceForERS(OLEEResourceRecordDocument oleERSDoc) {
    try {// w ww. j  ava 2 s  .  com
        Holdings holdings = null;
        List<OLEEResourcePO> oleeResourcePOs = new ArrayList<>();
        List<OLEEResourceInvoices> oleeResourceInvoiceses = new ArrayList<>();
        for (OLEEResourceInstance oleeResourceInstance : oleERSDoc.getOleERSInstances()) {
            holdings = getDocstoreClientLocator().getDocstoreClient()
                    .retrieveHoldings(oleeResourceInstance.getInstanceId());
            if (holdings != null) {
                Map<String, String> criteriaMap = new HashMap<String, String>();
                criteriaMap.put(OLEConstants.INSTANCE_ID, holdings.getId());
                List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class,
                        criteriaMap);
                for (OleCopy copy : copies) {
                    if (copy.getPoItemId() != null) {
                        OLEEResourcePO oleeResourcePO = new OLEEResourcePO();
                        oleeResourcePO.setTitle(holdings.getBib().getTitle());
                        Map<String, String> criteriaPOIdMap = new HashMap<String, String>();
                        criteriaPOIdMap.put(OLEConstants.OLEEResourceRecord.PO_ITEM_ID,
                                copy.getPoItemId().toString());
                        List<OlePurchaseOrderItem> olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService()
                                .findMatching(OlePurchaseOrderItem.class, criteriaPOIdMap);
                        if (olePurchaseOrderItems.size() > 0) {
                            for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
                                Map map = new HashMap();
                                map.put(OLEConstants.DOC_NUM, olePurchaseOrderItem.getDocumentNumber());
                                OlePurchaseOrderDocument olePurchaseOrderDocument = getBusinessObjectService()
                                        .findByPrimaryKey(OlePurchaseOrderDocument.class, map);
                                if (olePurchaseOrderDocument != null) {
                                    oleeResourcePO.setOlePOItemId(
                                            olePurchaseOrderDocument.getPurapDocumentIdentifier());
                                    Integer poCreatedYear = olePurchaseOrderDocument.getPostingYear();
                                    Integer currentYear = Calendar.getInstance().get(Calendar.YEAR);
                                    if (currentYear.compareTo(poCreatedYear) == 0) {
                                        oleeResourcePO.setPaidAmountCurrentFY(
                                                olePurchaseOrderItem.getItemInvoicedTotalAmount().intValue());
                                    } else if (currentYear.compareTo(poCreatedYear) == 1) {
                                        oleeResourcePO.setPaidAmountPreviousFY(
                                                olePurchaseOrderItem.getItemInvoicedTotalAmount().intValue());
                                    } else if (currentYear.compareTo(poCreatedYear) > 1) {
                                        oleeResourcePO.setPaidAmountTwoYearsPreviousFY(
                                                olePurchaseOrderItem.getItemInvoicedTotalAmount().intValue());
                                    }
                                }
                            }
                        }
                        oleeResourcePOs.add(oleeResourcePO);

                        Map<String, String> criteriaInvIdMap = new HashMap<String, String>();
                        criteriaInvIdMap.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID,
                                copy.getPoItemId().toString());
                        List<OleInvoiceItem> oleInvoiceItems = (List<OleInvoiceItem>) getBusinessObjectService()
                                .findMatching(OleInvoiceItem.class, criteriaInvIdMap);
                        if (oleInvoiceItems.size() > 0) {
                            for (OleInvoiceItem oleInvoiceItem : oleInvoiceItems) {
                                OLEEResourceInvoices oleEResInvoice = new OLEEResourceInvoices();
                                oleEResInvoice.setInvoiceId(oleInvoiceItem.getItemIdentifier().toString());
                                OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceItem
                                        .getInvoiceDocument();
                                if (oleInvoiceItem.getInvoiceDocument() != null) {
                                    oleEResInvoice.setInvoiceNumber(
                                            oleInvoiceItem.getInvoiceDocument().getDocumentNumber());
                                    oleEResInvoice.setInvoiceDate(
                                            oleInvoiceItem.getInvoiceDocument().getInvoiceDate());
                                    oleEResInvoice
                                            .setVendorName(oleInvoiceItem.getInvoiceDocument().getVendorName());
                                    if (SpringContext.getBean(DocumentHeaderService.class) != null) {
                                        oleInvoiceDocument.setDocumentHeader(SpringContext
                                                .getBean(DocumentHeaderService.class)
                                                .getDocumentHeaderById(oleInvoiceDocument.getDocumentNumber()));
                                        oleEResInvoice.setInvoiceStatus(
                                                oleInvoiceDocument.getApplicationDocumentStatus());
                                    }
                                }
                                oleEResInvoice.setInvoicedAmount(oleInvoiceItem.getExtendedPrice().toString());
                                Map map = new HashMap();
                                map.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID,
                                        oleInvoiceItem.getItemIdentifier());
                                OlePaymentRequestItem olePaymentRequestItem = getBusinessObjectService()
                                        .findByPrimaryKey(OlePaymentRequestItem.class, map);
                                if (olePaymentRequestItem != null) {
                                    oleEResInvoice.setPaidDate(olePaymentRequestItem.getPaymentRequestDocument()
                                            .getPaymentRequestPayDate());
                                }
                                StringBuffer fundCode = new StringBuffer();
                                if (oleInvoiceItem.getSourceAccountingLines() != null
                                        && oleInvoiceItem.getSourceAccountingLines().size() > 0) {
                                    for (PurApAccountingLine accountingLine : oleInvoiceItem
                                            .getSourceAccountingLines()) {
                                        map.clear();
                                        map.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
                                        map.put(OLEConstants.OBJECT_CODE,
                                                accountingLine.getFinancialObjectCode());
                                        OleVendorAccountInfo oleVendorAccountInfo = KRADServiceLocator
                                                .getBusinessObjectService()
                                                .findByPrimaryKey(OleVendorAccountInfo.class, map);
                                        if (oleVendorAccountInfo != null) {
                                            fundCode.append(oleVendorAccountInfo.getVendorRefNumber());
                                            fundCode.append(OLEConstants.COMMA);
                                            fundCode.append(' ');
                                        }
                                    }
                                }
                                if (fundCode.length() > 0) {
                                    fundCode.deleteCharAt(fundCode.length() - 2);
                                    oleEResInvoice.setFundCode(fundCode.toString());
                                }
                                oleeResourceInvoiceses.add(oleEResInvoice);
                            }
                        }
                    }
                }
            }
        }
        oleERSDoc.setOleERSPOItems(oleeResourcePOs);
        oleERSDoc.setOleERSInvoices(oleeResourceInvoiceses);
    } catch (Exception e) {
        LOG.error("Exception " + e);
    }
}

From source file:org.kuali.ole.service.impl.OLEEResourceSearchServiceImpl.java

public void getAcquisitionInfoFromPOAndInvoice(String holdingsId,
        WorkEInstanceOlemlForm workEInstanceOlemlForm) {
    Map map = new HashMap();
    map.put(OLEConstants.INSTANCE_ID, holdingsId);
    List<OleCopy> oleCopyList = (List) getBusinessObjectService().findMatching(OleCopy.class, map);
    StringBuffer linkedPos = new StringBuffer();
    StringBuffer vendor = new StringBuffer();
    StringBuffer orderType = new StringBuffer();
    StringBuffer orderFormat = new StringBuffer();
    StringBuffer fundCode = new StringBuffer();
    List fundCodeList = new ArrayList();
    List<PurApAccountingLine> accountingLines = new ArrayList<>();
    KualiDecimal currentFYCost = new KualiDecimal(0);
    for (OleCopy oleCopy : oleCopyList) {
        if (oleCopy.getPoItemId() != null) {
            map.clear();//from   www. j a  va 2s  . c o m
            map.put(OLEConstants.OLEEResourceRecord.PO_ITEM_ID, oleCopy.getPoItemId().toString());
            OlePurchaseOrderItem olePurchaseOrderItem = getBusinessObjectService()
                    .findByPrimaryKey(OlePurchaseOrderItem.class, map);
            if (olePurchaseOrderItem != null) {
                // vendor, current FY cost & order type
                map.clear();
                map.put(OLEConstants.DOC_NUM, olePurchaseOrderItem.getDocumentNumber());
                OlePurchaseOrderDocument olePurchaseOrderDocument = getBusinessObjectService()
                        .findByPrimaryKey(OlePurchaseOrderDocument.class, map);
                if (olePurchaseOrderDocument != null) {
                    // po
                    linkedPos.append(olePurchaseOrderDocument.getPurapDocumentIdentifier());
                    linkedPos.append(OLEConstants.COMMA);
                    linkedPos.append(' ');

                    Integer poCreatedYear = olePurchaseOrderDocument.getPostingYear();
                    Integer currentYear = Calendar.getInstance().get(Calendar.YEAR);
                    if (currentYear.compareTo(poCreatedYear) == 0) {
                        currentFYCost = currentFYCost.add(olePurchaseOrderItem.getItemInvoicedTotalAmount());
                    }

                    vendor.append(olePurchaseOrderDocument.getVendorName());
                    vendor.append(OLEConstants.COMMA);
                    vendor.append(' ');

                    map.clear();
                    map.put(OLEConstants.PURCHASE_ORDER_TYPE_ID,
                            olePurchaseOrderDocument.getPurchaseOrderTypeId());
                    Collection<PurchaseOrderType> purchaseOrderTypeDocumentList = getBusinessObjectService()
                            .findMatching(PurchaseOrderType.class, map);
                    if (purchaseOrderTypeDocumentList != null && purchaseOrderTypeDocumentList.size() > 0) {
                        PurchaseOrderType purchaseOrderTypeDoc = purchaseOrderTypeDocumentList.iterator()
                                .next();
                        orderType.append(purchaseOrderTypeDoc.getPurchaseOrderType());
                        orderType.append(OLEConstants.SEMI_COLON);
                        orderType.append(' ');
                    }
                }
                // payment status & Fund code
                map.clear();
                map.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID,
                        olePurchaseOrderItem.getItemIdentifier());
                List<OleInvoiceItem> oleInvoiceItems = (List<OleInvoiceItem>) getBusinessObjectService()
                        .findMatching(OleInvoiceItem.class, map);
                if (oleInvoiceItems != null && oleInvoiceItems.size() > 0) {
                    for (OleInvoiceItem oleInvoiceItem : oleInvoiceItems) {
                        map.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID,
                                oleInvoiceItem.getItemIdentifier());
                        OlePaymentRequestItem olePaymentRequestItem = getBusinessObjectService()
                                .findByPrimaryKey(OlePaymentRequestItem.class, map);
                        if (olePaymentRequestItem != null) {
                            workEInstanceOlemlForm.getExtendedEHoldingFields()
                                    .setPaymentStatus(OLEConstants.PAID);
                            break;
                        }
                    }
                    for (OleInvoiceItem oleInvoiceItem : oleInvoiceItems) {
                        List purApAccountingLines = oleInvoiceItem.getSourceAccountingLines();
                        if (purApAccountingLines != null && purApAccountingLines.size() > 0) {
                            accountingLines.addAll(purApAccountingLines);
                        }
                    }
                }
                // order format
                if (olePurchaseOrderItem.getFormatTypeId() != null) {
                    map.clear();
                    map.put(OLEConstants.FORMAT_TYPE_ID, olePurchaseOrderItem.getFormatTypeId());
                    OleFormatType oleFormatType = getBusinessObjectService()
                            .findByPrimaryKey(OleFormatType.class, map);
                    if (oleFormatType != null) {
                        orderFormat.append(oleFormatType.getFormatTypeName());
                        orderFormat.append(OLEConstants.COMMA);
                        orderFormat.append(' ');
                    }
                }
            }
        }
    }
    if (linkedPos.length() > 0) {
        if (vendor.length() > 0) {
            vendor.deleteCharAt(vendor.length() - 2);
            workEInstanceOlemlForm.getExtendedEHoldingFields().setVendorName(vendor.toString());
        }
        if (orderType.length() > 0) {
            orderType.deleteCharAt(orderType.length() - 2);
            workEInstanceOlemlForm.getExtendedEHoldingFields().setOrderType(orderType.toString());
        }
        if (orderFormat.length() > 0) {
            orderFormat.deleteCharAt(orderFormat.length() - 2);
            workEInstanceOlemlForm.getExtendedEHoldingFields().setOrderFormat(orderFormat.toString());
        }
        String pos[] = linkedPos.toString().split(",");
        Set set = new HashSet();
        for (String po : pos) {
            set.add(po.trim());
        }
        pos = (String[]) set.toArray(new String[0]);
        StringBuffer poLink = new StringBuffer();
        for (String po : pos) {
            String link = null;
            if (StringUtils.isNotBlank(po)) {
                Map poMap = new HashMap();
                poMap.put(org.kuali.ole.sys.OLEConstants.PUR_DOC_IDENTIFIER, po.trim());
                List<OlePurchaseOrderDocument> olePurchaseOrderDocumentList = (List) getBusinessObjectService()
                        .findMatching(OlePurchaseOrderDocument.class, poMap);
                if (olePurchaseOrderDocumentList != null && olePurchaseOrderDocumentList.size() > 0) {
                    for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocumentList) {
                        boolean validPO = olePurchaseOrderDocumentList != null
                                ? olePurchaseOrderDocument.getPurchaseOrderCurrentIndicatorForSearching()
                                : false;
                        if (validPO) {
                            link = ConfigContext.getCurrentContextConfig().getProperty("kew.url")
                                    + org.kuali.ole.sys.OLEConstants.PO_LINE_ITEM_URL
                                    + olePurchaseOrderDocument.getDocumentNumber();
                            poLink.append("<a href=" + link + " target='_blank'>" + po.trim() + "</a>, ");
                        }
                    }
                }
            }
        }
        if (poLink.length() > 0) {
            poLink.deleteCharAt(poLink.length() - 2);
            workEInstanceOlemlForm.getExtendedEHoldingFields().setPurchaseOrderId(poLink.toString());
        }
        workEInstanceOlemlForm.getExtendedEHoldingFields().setCurrentFYCost(currentFYCost.toString());
        if (org.apache.commons.lang.StringUtils
                .isBlank(workEInstanceOlemlForm.getExtendedEHoldingFields().getPaymentStatus())) {
            workEInstanceOlemlForm.getExtendedEHoldingFields().setPaymentStatus(OLEConstants.NOT_PAID);
        }
        if (accountingLines.size() > 0) {
            for (PurApAccountingLine accountingLine : accountingLines) {
                map.clear();
                map.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber());
                map.put(OLEConstants.OBJECT_CODE, accountingLine.getFinancialObjectCode());
                OleVendorAccountInfo oleVendorAccountInfo = getBusinessObjectService()
                        .findByPrimaryKey(OleVendorAccountInfo.class, map);
                if (oleVendorAccountInfo != null
                        && !fundCodeList.contains(oleVendorAccountInfo.getVendorRefNumber())) {
                    fundCodeList.add(oleVendorAccountInfo.getVendorRefNumber());
                    fundCode.append(oleVendorAccountInfo.getVendorRefNumber());
                    fundCode.append(OLEConstants.COMMA);
                    fundCode.append(' ');
                }
            }
        }
        if (fundCode.length() > 0) {
            fundCode.deleteCharAt(fundCode.length() - 2);
            workEInstanceOlemlForm.getExtendedEHoldingFields().setFundCode(fundCode.toString());
        }
    }
}

From source file:org.kuali.ole.select.document.service.impl.OleInvoiceServiceImpl.java

public void createCreditMemoDocument(OleInvoiceDocument invoiceDocument, List<OleInvoiceItem> items,
        boolean flag) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating Payment Request document");
    }/*from   ww w  .  ja  va 2  s.c  o m*/

    KNSGlobalVariables.getMessageList().clear();

    //   validateInvoiceOrderValidForPREQCreation(inv);

    if (LOG.isDebugEnabled()) {
        if (invoiceDocument.isInvoiceCancelIndicator()) {
            LOG.debug("Not possible to convert cancelled Invoice details into payment request");
        } else {
            LOG.debug("Payment request document creation validation succeeded");
        }
    }

    if (invoiceDocument.isInvoiceCancelIndicator()) {
        LOG.debug("Invoice Cancelled, Payment Request not created");
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Total Dollar Amount above line items >>>>"
                + invoiceDocument.getTotalDollarAmountAboveLineItems());
    }
    Integer invId = invoiceDocument.getPurapDocumentIdentifier();
    Integer poId = 0;
    List<Integer> poList = new ArrayList();

    List<OleInvoiceItem> oleInvoiceItemList = items;
    KualiDecimal invTotalAmount = new KualiDecimal(0);
    KualiDecimal invItemCount = new KualiDecimal(0);
    invTotalAmount = invoiceDocument.getTotalDollarAmountAboveLineItems();
    for (OleInvoiceItem oleInvoiceItem : oleInvoiceItemList) {
        if (oleInvoiceItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
            invItemCount = invItemCount.add(oleInvoiceItem.getItemQuantity());
        }
        if (!(poList.contains(oleInvoiceItem.getPurchaseOrderIdentifier()))) {
            poList.add(oleInvoiceItem.getPurchaseOrderIdentifier());
        }
    }

    String prorateBy = invoiceDocument.getProrateBy();
    OleVendorCreditMemoDocument vendorCreditMemoDocument = null;

    Integer invoicePoId = 0;
    for (Integer purchaseOrderId : poList) {
        if (purchaseOrderId != null && invoicePoId.compareTo(purchaseOrderId) != 0) {

            try {
                //GlobalVariables.setUserSession(new UserSession("ole-khuntley"));
                String user = null;
                if (GlobalVariables.getUserSession() == null) {
                    kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
                    user = kualiConfigurationService.getPropertyValueAsString(getOleSelectDocumentService()
                            .getSelectParameterValue(OleSelectNotificationConstant.ACCOUNT_DOCUMENT_INTIATOR));
                    GlobalVariables.setUserSession(new UserSession(user));
                }

                vendorCreditMemoDocument = (OleVendorCreditMemoDocument) SpringContext
                        .getBean(DocumentService.class).getNewDocument("OLE_CM");
                //  PaymentRequestDocument  preqDoc = new PaymentRequestDocument();
                //vendorCreditMemoDocument.setCreditMemoDate(invoiceDocument.getInvoiceDate());
                vendorCreditMemoDocument.setCreditMemoNumber(invoiceDocument.getInvoiceNumber());
                //vendorCreditMemoDocument.setVendorInvoiceAmount(invoiceDocument.getVendorInvoiceAmount());
                vendorCreditMemoDocument.setVendorDetail(invoiceDocument.getVendorDetail());
                vendorCreditMemoDocument.setVendorName(invoiceDocument.getVendorName());
                vendorCreditMemoDocument.setVendorHeaderGeneratedIdentifier(
                        invoiceDocument.getVendorHeaderGeneratedIdentifier());
                vendorCreditMemoDocument
                        .setVendorDetailAssignedIdentifier(invoiceDocument.getVendorDetailAssignedIdentifier());
                vendorCreditMemoDocument.setVendorNumber(invoiceDocument.getVendorNumber());
                vendorCreditMemoDocument.setVendorHeaderGeneratedIdentifier(
                        invoiceDocument.getVendorHeaderGeneratedIdentifier());
                vendorCreditMemoDocument
                        .setVendorDetailAssignedIdentifier(invoiceDocument.getVendorDetailAssignedIdentifier());
                //vendorCreditMemoDocument.setVendorFaxNumber(invoiceDocument.getDefaultFaxNumber());
                //oleInvoiceDocument.
                /* vendorCreditMemoDocument.setVendorPaymentTerms(invoiceDocument.getVendorPaymentTerms());
                 vendorCreditMemoDocument.setVendorPaymentTermsCode(invoiceDocument.getVendorPaymentTerms().getVendorPaymentTermsCode());
                 vendorCreditMemoDocument.setVendorShippingTitleCode(invoiceDocument.getVendorShippingTitleCode());
                 vendorCreditMemoDocument.setVendorShippingPaymentTerms(invoiceDocument.getVendorShippingPaymentTerms());*/
                vendorCreditMemoDocument.setVendorCityName(invoiceDocument.getVendorCityName());
                vendorCreditMemoDocument.setVendorLine1Address(invoiceDocument.getVendorLine1Address());
                vendorCreditMemoDocument.setVendorLine2Address(invoiceDocument.getVendorLine2Address());
                vendorCreditMemoDocument.setVendorAttentionName(invoiceDocument.getVendorAttentionName());
                vendorCreditMemoDocument.setVendorPostalCode(invoiceDocument.getVendorPostalCode());
                vendorCreditMemoDocument.setVendorStateCode(invoiceDocument.getVendorStateCode());
                vendorCreditMemoDocument.setVendorAttentionName(invoiceDocument.getVendorAttentionName());
                vendorCreditMemoDocument.setVendorAddressInternationalProvinceName(
                        invoiceDocument.getVendorAddressInternationalProvinceName());
                vendorCreditMemoDocument.setVendorCountryCode(invoiceDocument.getVendorCountryCode());
                vendorCreditMemoDocument.setVendorCountry(invoiceDocument.getVendorCountry());
                vendorCreditMemoDocument.setVendorCustomerNumber(invoiceDocument.getVendorCustomerNumber());
                vendorCreditMemoDocument.setAccountsPayableProcessorIdentifier(
                        invoiceDocument.getAccountsPayableProcessorIdentifier());
                vendorCreditMemoDocument.setProcessingCampusCode(invoiceDocument.getProcessingCampusCode());
                vendorCreditMemoDocument.setPurchaseOrderIdentifier(purchaseOrderId);
                // vendorCreditMemoDocument.setReopenPurchaseOrderIndicator(oleInvoiceItem.isReopenPurchaseOrderIndicator());
                // vendorCreditMemoDocument.setClosePurchaseOrderIndicator(oleInvoiceItem.isClosePurchaseOrderIndicator());
                vendorCreditMemoDocument.setCreditMemoDate(invoiceDocument.getInvoiceDate());
                //  vendorCreditMemoDocument.setImmediatePaymentIndicator(invoiceDocument.getImmediatePaymentIndicator());
                // vendorCreditMemoDocument.setPaymentRequestCostSource(invoiceDocument.getInvoiceCostSource());
                //   LOG.info("invoiceDocument.getPaymentMethod().getPaymentMethodId() >>>>>>>>>" + invoiceDocument.getPaymentMethod().getPaymentMethodId());

                // vendorCreditMemoDocument.setGrandTotal(invoiceDocument.getTotalDollarAmount());
                vendorCreditMemoDocument.setVendorCustomerNumber(invoiceDocument.getVendorCustomerNumber());
                vendorCreditMemoDocument.setAccountsPayableProcessorIdentifier(
                        invoiceDocument.getAccountsPayableProcessorIdentifier());
                vendorCreditMemoDocument.setProcessingCampusCode(invoiceDocument.getProcessingCampusCode());
                vendorCreditMemoDocument.setPurchaseOrderIdentifier(purchaseOrderId);
                vendorCreditMemoDocument.setProrateBy(invoiceDocument.getProrateBy());
                vendorCreditMemoDocument.setProrateDollar(invoiceDocument.isProrateDollar());
                vendorCreditMemoDocument.setProrateQty(invoiceDocument.isProrateQty());
                vendorCreditMemoDocument.setProrateManual(invoiceDocument.isProrateManual());
                vendorCreditMemoDocument.setNoProrate(invoiceDocument.isNoProrate());

                if (invoiceDocument.getPaymentMethodId() != null) {
                    OlePaymentMethod olePaymentMethod = SpringContext.getBean(BusinessObjectService.class)
                            .findBySinglePrimaryKey(OlePaymentMethod.class,
                                    invoiceDocument.getPaymentMethodId());
                    vendorCreditMemoDocument.setOlePaymentMethod(olePaymentMethod);
                    //vendorCreditMemoDocument.getPaymentMethod().setPaymentMethodId(olePaymentMethod.getPaymentMethodId());
                    vendorCreditMemoDocument.setPaymentMethodId(olePaymentMethod.getPaymentMethodId());
                }

                vendorCreditMemoDocument.setInvoiceIdentifier(invoiceDocument.getPurapDocumentIdentifier());
                /* if (invoiceDocument.getAccountsPayablePurchasingDocumentLinkIdentifier() != null) {
                vendorCreditMemoDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(invoiceDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
                 } */
                vendorCreditMemoDocument.setBankCode(invoiceDocument.getBankCode());
                vendorCreditMemoDocument.setBank(invoiceDocument.getBank());
                //vendorCreditMemoDocument.setProcessingCampusCode(invoiceDocument.getProcessingCampusCode());
            } catch (WorkflowException e) {
                String extraDescription = "Error=" + e.getMessage();
                LOG.error("Exception creating Payment request document - " + e.getMessage());
            }

            Map invItemMap = new HashMap();
            invItemMap.put(PurapConstants.PRQSDocumentsStrings.PUR_ID,
                    invoiceDocument.getPurapDocumentIdentifier());
            invItemMap.put(PurapConstants.PRQSDocumentsStrings.PO_ID, purchaseOrderId);
            List<OleInvoiceItem> invoiceItems = (List<OleInvoiceItem>) businessObjectService
                    .findMatchingOrderBy(OleInvoiceItem.class, invItemMap,
                            PurapConstants.PRQSDocumentsStrings.PO_ID, true);
            KualiDecimal itemCount = new KualiDecimal(0);
            KualiDecimal itemPrice = new KualiDecimal(0);
            PurchaseOrderDocument poDoc = invoiceDocument.getPurchaseOrderDocument(purchaseOrderId);
            if (poDoc == null) {
                throw new RuntimeException(
                        "Purchase Order document " + purchaseOrderId + " does not exist in the system");
            }
            if (vendorCreditMemoDocument.getDocumentHeader() != null) {
                vendorCreditMemoDocument.getDocumentHeader().setDocumentDescription(
                        createPreqDocumentDescription(poDoc.getPurapDocumentIdentifier(),
                                invoiceDocument.getVendorName()));
            }

            try {
                vendorCreditMemoDocument
                        .updateAndSaveAppDocStatus(PurapConstants.PaymentRequestStatuses.APPDOC_IN_PROCESS);
            } catch (WorkflowException we) {
                throw new RuntimeException("Unable to save route status data for document: "
                        + vendorCreditMemoDocument.getDocumentNumber(), we);
            }
            List<OleCreditMemoItem> creditMemoItems = new ArrayList<>();

            HashMap<String, ExpiredOrClosedAccountEntry> expiredOrClosedAccountList = SpringContext
                    .getBean(AccountsPayableService.class).expiredOrClosedAccountsList(poDoc);
            //int itemLineNumberCount = 0;
            for (OleInvoiceItem invoiceItem : invoiceItems) {
                if ((flag || !invoiceItem.isDebitItem()) && invoiceItem.getExtendedPrice().isNonZero()) {

                    OleCreditMemoItem creditMemoItem = new OleCreditMemoItem(invoiceItem,
                            vendorCreditMemoDocument, expiredOrClosedAccountList);
                    if (flag && invoiceItem.isDebitItem()) {
                        creditMemoItem.setItemUnitPrice(creditMemoItem.getItemUnitPrice().negate());
                        creditMemoItem.setExtendedPrice(creditMemoItem.getExtendedPrice().negated());
                        for (PurApAccountingLine purApAccountingLine : creditMemoItem
                                .getSourceAccountingLines()) {
                            purApAccountingLine.setAmount(purApAccountingLine.getAmount().negated());
                        }
                    }
                    creditMemoItems.add(creditMemoItem);
                    if (vendorCreditMemoDocument.getAccountsPayablePurchasingDocumentLinkIdentifier() == null) {
                        vendorCreditMemoDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(
                                invoiceItem.getAccountsPayablePurchasingDocumentLinkIdentifier());
                    }
                }

            }
            vendorCreditMemoDocument.setItems(creditMemoItems);
            vendorCreditMemoDocument.setCreditMemoAmount(vendorCreditMemoDocument.getTotalDollarAmount());
            SpringContext.getBean(OleCreditMemoService.class).calculateCreditMemo(vendorCreditMemoDocument);

            SpringContext.getBean(KualiRuleService.class)
                    .applyRules(new AttributedCalculateAccountsPayableEvent(vendorCreditMemoDocument));

            if (expiredOrClosedAccountList == null) {
                expiredOrClosedAccountList = new HashMap();
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug(expiredOrClosedAccountList.size() + " accounts has been found as Expired or Closed");
            }

            invoicePoId = purchaseOrderId;

            SpringContext.getBean(CreditMemoService.class).populateAndSaveCreditMemo(vendorCreditMemoDocument);

            SpringContext.getBean(OleCreditMemoService.class).autoApproveCreditMemo(vendorCreditMemoDocument);
        }
    }
}