Example usage for org.joda.time LocalDate equals

List of usage examples for org.joda.time LocalDate equals

Introduction

In this page you can find the example usage for org.joda.time LocalDate equals.

Prototype

public boolean equals(Object partial) 

Source Link

Document

Compares this ReadablePartial with another returning true if the chronology, field types and values are equal.

Usage

From source file:com.gst.portfolio.savings.domain.interest.PostingPeriod.java

License:Apache License

public BigDecimal calculateInterest(final CompoundInterestValues compoundInterestValues) {
    BigDecimal interestEarned = BigDecimal.ZERO;

    // for each compounding period accumulate the amount of interest
    // to be applied to the balanced for interest calculation
    for (final CompoundingPeriod compoundingPeriod : this.compoundingPeriods) {

        final BigDecimal interestUnrounded = compoundingPeriod.calculateInterest(this.interestCompoundingType,
                this.interestCalculationType, compoundInterestValues.getcompoundedInterest(),
                this.interestRateAsFraction, this.daysInYear, this.minBalanceForInterestCalculation.getAmount(),
                this.overdraftInterestRateAsFraction, this.minOverdraftForInterestCalculation.getAmount());
        BigDecimal unCompoundedInterest = compoundInterestValues.getuncompoundedInterest()
                .add(interestUnrounded);
        compoundInterestValues.setuncompoundedInterest(unCompoundedInterest);
        LocalDate compoundingPeriodEndDate = compoundingPeriod.getPeriodInterval().endDate();
        if (!SavingsCompoundingInterestPeriodType.DAILY.equals(this.interestCompoundingType)) {
            compoundingPeriodEndDate = determineInterestPeriodEndDateFrom(
                    compoundingPeriod.getPeriodInterval().startDate(), this.interestCompoundingType,
                    compoundingPeriod.getPeriodInterval().endDate());
        }//w ww .j a  v  a  2 s . co  m

        if (compoundingPeriodEndDate.equals(compoundingPeriod.getPeriodInterval().endDate())) {
            BigDecimal interestCompounded = compoundInterestValues.getcompoundedInterest()
                    .add(unCompoundedInterest);
            compoundInterestValues.setcompoundedInterest(interestCompounded);
            compoundInterestValues.setZeroForInterestToBeUncompounded();
        }
        interestEarned = interestEarned.add(interestUnrounded);
    }

    this.interestEarnedUnrounded = interestEarned;
    this.interestEarnedRounded = Money.of(this.currency, this.interestEarnedUnrounded);

    return interestEarned;
}

From source file:com.gst.portfolio.savings.domain.SavingsAccount.java

License:Apache License

public void payCharge(final SavingsAccountCharge savingsAccountCharge, final BigDecimal amountPaid,
        final LocalDate transactionDate, final DateTimeFormatter formatter, final AppUser user) {

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

    if (isClosed()) {
        baseDataValidator.reset()/*from   w  w  w  . j  a va 2  s  .  c  o  m*/
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.closed");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    if (isNotActive()) {
        baseDataValidator.reset()
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.not.active");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    if (savingsAccountCharge.isNotActive()) {
        baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("charge.is.not.active");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    if (getActivationLocalDate() != null && transactionDate.isBefore(getActivationLocalDate())) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName)
                .value(getActivationLocalDate().toString(formatter))
                .failWithCodeNoParameterAddedToErrorCode("transaction.before.activationDate");
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    if (DateUtils.isDateInTheFuture(transactionDate)) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName).value(transactionDate.toString(formatter))
                .failWithCodeNoParameterAddedToErrorCode("transaction.is.futureDate");
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    if (savingsAccountCharge.isSavingsActivation()) {
        baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(
                "transaction.not.valid.cannot.pay.activation.time.charge.is.automated");
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    if (savingsAccountCharge.isAnnualFee()) {
        final LocalDate annualFeeDueDate = savingsAccountCharge.getDueLocalDate();
        if (annualFeeDueDate == null) {
            baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("no.annualfee.settings");
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }

        if (!annualFeeDueDate.equals(transactionDate)) {
            baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("invalid.date");
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }

        Date currentAnnualFeeNextDueDate = findLatestAnnualFeeTransactionDueDate();
        if (currentAnnualFeeNextDueDate != null
                && new LocalDate(currentAnnualFeeNextDueDate).isEqual(transactionDate)) {
            baseDataValidator.reset().parameter("dueDate").value(transactionDate.toString(formatter))
                    .failWithCodeNoParameterAddedToErrorCode("transaction.exists.on.date");

            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    // validate charge is not already paid or waived
    if (savingsAccountCharge.isWaived()) {
        baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(
                "transaction.invalid.account.charge.is.already.waived");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    } else if (savingsAccountCharge.isPaid()) {
        baseDataValidator.reset()
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.charge.is.paid");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    final Money chargePaid = Money.of(currency, amountPaid);
    if (!savingsAccountCharge.getAmountOutstanding(getCurrency()).isGreaterThanOrEqualTo(chargePaid)) {
        baseDataValidator.reset()
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.charge.amount.paid.in.access");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    this.payCharge(savingsAccountCharge, chargePaid, transactionDate, user);
}

From source file:com.ideaspymes.arthyweb.ventas.web.controllers.ResumenMetasBean.java

public Integer getDaysBetweenIgnoreWeekends(org.joda.time.LocalDate startDate,
        org.joda.time.LocalDate endDate) {
    // If the start date is equal to the closing date, spent 0 days
    if (startDate.equals(endDate)) {
        return 0;
    }//from   w w w. j  a  v a  2s .  c  o  m

    // A number that represents the day for the start date, Monday = 1 , Tuesday = 2 , Wednesday = 3 ...
    int dayOfWeekStartDateNumber = startDate.getDayOfWeek();

    // If the starting date is Saturday or Sunday , pretend to be Monday
    if (dayOfWeekStartDateNumber == 6 || dayOfWeekStartDateNumber == 7) {
        int DaysToAdd = 8 - dayOfWeekStartDateNumber;
        startDate = startDate.plusDays(DaysToAdd);
        dayOfWeekStartDateNumber = Integer.valueOf(startDate.dayOfWeek().getAsString());
    }

    // How many days have passed counting weekends
    int days = Days.daysBetween(startDate, endDate).getDays();

    // How many weeks have passed
    int weeks = days / 7;
    // Excess days left. E.g. one week and three days the excess will be 3
    int excess = days % 7;

    // Excess of days spent for the weekend , then it must be removed two days
    // the final number of days
    if (excess + dayOfWeekStartDateNumber >= 6) {
        // Week count * 5 working days + excess days - the weekend that excess crossed
        return weeks * 5 + excess - 2;
    }
    // Weeks count * 5 working days + excess days
    return weeks * 5 + excess;
}

From source file:com.jgoetsch.eventtrader.filter.SymbolOncePerDayFilter.java

License:Apache License

@Override
protected boolean handleProcessing(TradeSignal trade, Map<Object, Object> context) {
    LocalDate date = new LocalDate(trade.getDate());
    if (!date.equals(curDate)) {
        used.clear();//w  w  w  .  j  a va  2 s .c  o  m
        curDate = date;
    }
    if (used.contains(trade.getContract()))
        return false;
    else {
        used.add(trade.getContract());
        return true;
    }
}

From source file:com.mbc.jfin.daycount.impl.calculator.AFBActualActualDaycountCalculator.java

License:Open Source License

public double calculateDaycountFraction(SchedulePeriod period) {
    int daysBetween = DateUtils.daysBetween(period.getStart(), period.getEnd());

    if (daysBetween == 0)
        return 0;

    LocalDate newD2 = period.getEnd();
    LocalDate temp = period.getEnd();

    double sum = 0.0;
    while (temp.isAfter(period.getStart())) {
        temp = newD2;/*from  w ww  .  j av  a  2 s .  co  m*/
        temp = temp.minus(Years.ONE);
        if (temp.getDayOfMonth() == 28 && temp.getMonthOfYear() == 2 && DateUtils.isLeapYear(temp)) {
            temp = temp.plus(Days.ONE);
        }
        if (temp.isAfter(period.getStart()) || temp.equals(period.getStart())) {
            sum += 1.0;
            newD2 = temp;
        }
    }

    double den = 365.0;

    if (DateUtils.isLeapYear(newD2)) {
        temp = newD2;

        temp = new LocalDate(temp.getYear(), 2, 29);

        if (newD2.isAfter(temp) && (period.getStart().isBefore(temp) || period.getStart().equals(temp)))
            den += 1.0;
    } else if (DateUtils.isLeapYear(period.getStart())) {

        temp = new LocalDate(period.getStart().getYear(), 2, 29);

        if (newD2.isAfter(temp) && (period.getStart().isBefore(temp) || period.getStart().equals(temp)))
            den += 1.0;
    }

    return sum + DateUtils.daysBetween(period.getStart(), newD2) / den;

}

From source file:com.mbc.jfin.daycount.impl.calculator.ISMAActualActualDaycountCalculator.java

License:Open Source License

public double calculateDaycountFraction(SchedulePeriod schedulePeriod) {

    if (schedulePeriod.getStart().equals(schedulePeriod.getEnd()))
        return 0;

    // when the reference period is not specified, try taking
    // it equal to (d1,d2)
    LocalDate refPeriodStart = (schedulePeriod.getReferenceStart() != null ? schedulePeriod.getReferenceStart()
            : schedulePeriod.getStart());
    LocalDate refPeriodEnd = (schedulePeriod.getReferenceEnd() != null ? schedulePeriod.getReferenceEnd()
            : schedulePeriod.getEnd());/* w w w.j av a 2s. com*/

    LocalDate startCalendar = schedulePeriod.getStart();
    LocalDate endCalendar = schedulePeriod.getEnd();

    if (!(refPeriodEnd.isAfter(refPeriodStart) && refPeriodEnd.isAfter(startCalendar))) {
        throw new InvalidReferencePeriodException(schedulePeriod);
    }

    // estimate roughly the length in months of a period
    // Integer months =
    // Integer(0.5+12*Real(refPeriodEnd-refPeriodStart)/365);

    double monthsEstimate = DateUtils.daysBetween(refPeriodStart, refPeriodEnd) * (12.0d / 365.0d);
    int months = (int) Math.round(monthsEstimate);

    if (months == 0) {
        refPeriodStart = startCalendar;
        refPeriodEnd = startCalendar.plus(Years.ONE);
        months = 12;
    }

    double period = (double) months / 12.0;

    if (endCalendar.isBefore(refPeriodEnd) || endCalendar.equals(refPeriodEnd)) {
        if (startCalendar.isAfter(refPeriodStart) || startCalendar.equals(refPeriodStart)) {
            long numerator = DateUtils.daysBetween(startCalendar, endCalendar);
            long denominator = DateUtils.daysBetween(refPeriodStart, refPeriodEnd);

            return period * (double) numerator / (double) denominator;
        } else {

            LocalDate previousRef = startCalendar;

            //previousRef.add(Calendar.MONTH, months * -1);
            if (endCalendar.isAfter(refPeriodStart))
                return calculateDaycountFraction(
                        new SchedulePeriod(startCalendar, refPeriodStart, previousRef, refPeriodStart))
                        + calculateDaycountFraction(
                                new SchedulePeriod(refPeriodStart, endCalendar, refPeriodStart, refPeriodEnd));
            else
                return calculateDaycountFraction(
                        new SchedulePeriod(startCalendar, endCalendar, previousRef, refPeriodStart));
        }
    } else {
        if (!(refPeriodStart.isBefore(startCalendar) || refPeriodStart.equals(startCalendar))) {
            throw new InvalidReferencePeriodException(schedulePeriod);
        }

        // the part from d1 to refPeriodEnd
        double sum = calculateDaycountFraction(
                new SchedulePeriod(startCalendar, refPeriodEnd, refPeriodStart, refPeriodEnd));

        // the part from refPeriodEnd to d2
        // count how many regular periods are in [refPeriodEnd, d2],
        // then add the remaining time
        int i = 0;
        LocalDate newRefStart, newRefEnd;
        do {
            newRefStart = refPeriodEnd.plus(Months.months(months * i));
            newRefEnd = refPeriodEnd.plus(Months.months(months * (i + 1)));
            if (endCalendar.isBefore(newRefEnd)) {
                break;
            } else {
                sum += period;
                i++;
            }
        } while (true);
        double secondSum = calculateDaycountFraction(
                new SchedulePeriod(newRefStart, endCalendar, newRefStart, newRefEnd));

        sum += secondSum;
        return sum;
    }
}

From source file:com.ning.billing.invoice.model.InAdvanceBillingMode.java

License:Apache License

@Override
public List<RecurringInvoiceItemData> calculateInvoiceItemData(final LocalDate startDate,
        @Nullable final LocalDate endDate, final LocalDate targetDate, final int billingCycleDayLocal,
        final BillingPeriod billingPeriod) throws InvalidDateSequenceException {
    if (endDate != null && endDate.isBefore(startDate)) {
        throw new InvalidDateSequenceException();
    }/*from  ww  w  . ja  v a 2s .  c  o m*/
    if (targetDate.isBefore(startDate)) {
        throw new InvalidDateSequenceException();
    }

    final List<RecurringInvoiceItemData> results = new ArrayList<RecurringInvoiceItemData>();

    final LocalDate firstBillingCycleDate = calculateBillingCycleDateOnOrAfter(startDate, billingCycleDayLocal);

    // We are not billing for less than a day (we could...)
    if (endDate != null && endDate.equals(startDate)) {
        return results;
    }
    //
    // If there is an endDate and that endDate is before our first coming firstBillingCycleDate, all we have to do
    // is to charge for that period
    //
    if (endDate != null && !endDate.isAfter(firstBillingCycleDate)) {
        final BigDecimal leadingProRationPeriods = calculateProRationBeforeFirstBillingPeriod(startDate,
                endDate, billingPeriod);
        final RecurringInvoiceItemData itemData = new RecurringInvoiceItemData(startDate, endDate,
                leadingProRationPeriods);
        results.add(itemData);
        return results;
    }

    //
    // Leading proration if
    // i) The first firstBillingCycleDate is strictly after our start date AND
    // ii) The endDate is is not null and is strictly after our firstBillingCycleDate (previous check)
    //
    if (firstBillingCycleDate.isAfter(startDate)) {
        final BigDecimal leadingProRationPeriods = calculateProRationBeforeFirstBillingPeriod(startDate,
                firstBillingCycleDate, billingPeriod);
        if (leadingProRationPeriods != null && leadingProRationPeriods.compareTo(BigDecimal.ZERO) > 0) {
            // Not common - add info in the logs for debugging purposes
            final RecurringInvoiceItemData itemData = new RecurringInvoiceItemData(startDate,
                    firstBillingCycleDate, leadingProRationPeriods);
            log.info("Adding pro-ration: {}", itemData);
            results.add(itemData);
        }
    }

    //
    // Calculate the effectiveEndDate from the firstBillingCycleDate:
    // - If endDate != null and targetDate is after endDate => this is the endDate and will lead to a trailing pro-ration
    // - If not, this is the last billingCycleDate calculation right after the targetDate
    //
    final LocalDate effectiveEndDate;
    if (endDate != null) {
        effectiveEndDate = calculateEffectiveEndDate(firstBillingCycleDate, targetDate, endDate, billingPeriod);
    } else {
        effectiveEndDate = calculateEffectiveEndDate(firstBillingCycleDate, targetDate, billingPeriod);
    }

    //
    // Based on what we calculated previously, code recompute one more time the numberOfWholeBillingPeriods
    //
    final LocalDate lastBillingCycleDate = calculateLastBillingCycleDateBefore(effectiveEndDate,
            firstBillingCycleDate, billingCycleDayLocal, billingPeriod);
    final int numberOfWholeBillingPeriods = calculateNumberOfWholeBillingPeriods(firstBillingCycleDate,
            lastBillingCycleDate, billingPeriod);
    final int numberOfMonthsPerBillingPeriod = billingPeriod.getNumberOfMonths();

    for (int i = 0; i < numberOfWholeBillingPeriods; i++) {
        final LocalDate servicePeriodStartDate;
        if (results.size() > 0) {
            // Make sure the periods align, especially with the pro-ration calculations above
            servicePeriodStartDate = results.get(results.size() - 1).getEndDate();
        } else if (i == 0) {
            // Use the specified start date
            servicePeriodStartDate = startDate;
        } else {
            throw new IllegalStateException("We should at least have one invoice item!");
        }

        // Make sure to align the end date with the BCD
        final LocalDate servicePeriodEndDate = firstBillingCycleDate
                .plusMonths((i + 1) * numberOfMonthsPerBillingPeriod);

        results.add(new RecurringInvoiceItemData(servicePeriodStartDate, servicePeriodEndDate, BigDecimal.ONE));
    }

    //
    // Now we check if indeed we need a trailing proration and add that incomplete item
    //
    if (effectiveEndDate.isAfter(lastBillingCycleDate)) {
        final BigDecimal trailingProRationPeriods = calculateProRationAfterLastBillingCycleDate(
                effectiveEndDate, lastBillingCycleDate, billingPeriod);
        if (trailingProRationPeriods.compareTo(BigDecimal.ZERO) > 0) {
            // Not common - add info in the logs for debugging purposes
            final RecurringInvoiceItemData itemData = new RecurringInvoiceItemData(lastBillingCycleDate,
                    effectiveEndDate, trailingProRationPeriods);
            log.info("Adding trailing pro-ration: {}", itemData);
            results.add(itemData);
        }
    }
    return results;
}

From source file:com.ofalvai.bpinfo.util.UiUtils.java

License:Apache License

/**
 * Transforms the start and end timestamps into a human-friendly readable string,
 * with special replacements for special dates, times, and the API's strange notations.
 * @param context Context/*  w  w w  .  jav  a 2  s  .  c  o  m*/
 * @param startTimestamp Start of the alert in seconds since the UNIX epoch
 * @param endTimestamp   End of the alert in seconds since the UNIX epoch
 * @return  A string in the format of [startdate] [starttime] [separator] [enddate] [endtime]
 */
@NonNull
public static String alertDateFormatter(Context context, long startTimestamp, long endTimestamp) {
    DateTime startDateTime = new DateTime(startTimestamp * 1000L);
    DateTime endDateTime = new DateTime(endTimestamp * 1000L);
    LocalDate startDate = startDateTime.toLocalDate();
    LocalDate endDate = endDateTime.toLocalDate();

    DateTime today = new DateTime();
    LocalDate todayDate = new DateTime().toLocalDate();
    DateTime yesterday = today.minusDays(1);
    LocalDate yesterdayDate = yesterday.toLocalDate();
    DateTime tomorrow = today.plusDays(1);
    LocalDate tomorrowDate = tomorrow.toLocalDate();

    // Alert start, date part
    String startDateString;
    if (startDate.equals(todayDate)) {
        // Start day is today, replacing month and day with today string
        startDateString = context.getString(R.string.date_today) + " ";
    } else if (startDate.year().get() < today.year().get()) {
        // The start year is less than the current year, displaying the year too
        startDateString = Config.FORMATTER_DATE_YEAR.print(startDateTime);
    } else if (startDate.equals(yesterdayDate)) {
        startDateString = context.getString(R.string.date_yesterday) + " ";
    } else if (startDate.equals(tomorrowDate)) {
        startDateString = context.getString(R.string.date_tomorrow) + " ";
    } else {
        startDateString = Config.FORMATTER_DATE.print(startDateTime);
    }

    // Alert start, time part
    String startTimeString;
    if (startDateTime.hourOfDay().get() == 0 && startDateTime.minuteOfHour().get() == 0) {
        // The API marks "first departure" as 00:00
        startTimeString = context.getString(R.string.date_first_departure);
    } else {
        startTimeString = Config.FORMATTER_TIME.print(startDateTime);
    }

    // Alert end, date part
    String endDateString;
    if (endTimestamp == 0) {
        // The API marks "until further notice" as 0 (in UNIX epoch), no need to display date
        // (the replacement string is displayed as the time part, not the date)
        endDateString = " ";
    } else if (endDate.year().get() > today.year().get()) {
        // The end year is greater than the current year, displaying the year too
        endDateString = Config.FORMATTER_DATE_YEAR.print(endDateTime);
    } else if (endDate.equals(todayDate)) {
        // End  day is today, replacing month and day with today string
        endDateString = context.getString(R.string.date_today) + " ";
    } else if (endDate.equals(yesterdayDate)) {
        endDateString = context.getString(R.string.date_yesterday) + " ";
    } else if (endDate.equals(tomorrowDate)) {
        endDateString = context.getString(R.string.date_tomorrow) + " ";
    } else {
        endDateString = Config.FORMATTER_DATE.print(endDateTime);
    }

    // Alert end, time part
    String endTimeString;
    if (endTimestamp == 0) {
        // The API marks "until further notice" as 0 (in UNIX epoch)
        endTimeString = context.getString(R.string.date_until_revoke);
    } else if (endDateTime.hourOfDay().get() == 23 && endDateTime.minuteOfHour().get() == 59) {
        // The API marks "last departure" as 23:59
        endTimeString = context.getString(R.string.date_last_departure);
    } else {
        endTimeString = Config.FORMATTER_TIME.print(endDateTime);
    }

    return startDateString + startTimeString + Config.DATE_SEPARATOR + endDateString + endTimeString;
}

From source file:com.sonicle.webtop.core.Service.java

License:Open Source License

public void processManageIMChat(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    UserProfile up = getEnv().getProfile();
    DateTimeZone utz = up.getTimeZone();

    try {//from  ww w .j av  a  2s  . co m
        String crud = ServletUtils.getStringParameter(request, "crud", true);
        if (crud.equals("presence")) {
            String chatId = ServletUtils.getStringParameter(request, "chatId", true);

            if (xmppCli != null) {
                if (!XMPPClient.isInstantChat(chatId))
                    throw new WTException("Presence feature non available for a grupchat");

                String friendFullId = null;
                String presenceStatus = null;
                FriendPresence presence = xmppCli.getChatPresence(chatId);
                if (presence == null) {
                    presenceStatus = EnumUtils.toSerializedName(PresenceStatus.OFFLINE);
                } else {
                    friendFullId = presence.getFriendFullJid();
                    presenceStatus = EnumUtils.toSerializedName(presence.getPresenceStatus());
                }
                new JsonResult(new JsIMPresenceStatus(friendFullId, presenceStatus)).printTo(out);

            } else {
                throw new WTException("XMPPClient not available");
            }

        } else if (crud.equals("dates")) {
            String chatId = ServletUtils.getStringParameter(request, "chatId", true);
            int year = ServletUtils.getIntParameter(request, "year", true);

            List<String> items = new ArrayList<>();
            List<LocalDate> dates = coreMgr.listIMMessageDates(chatId, year, utz);
            for (LocalDate date : dates) {
                items.add(date.toString());
            }

            new JsonResult(items).printTo(out);

        } else if (crud.equals("send")) {
            String chatId = ServletUtils.getStringParameter(request, "chatId", true);
            String text = ServletUtils.getStringParameter(request, "text", true);
            String lastSeenDate = ServletUtils.getStringParameter(request, "lastSeenDate", null);

            LocalDate lastSeen = (lastSeenDate == null) ? null
                    : DateTimeUtils.parseYmdHmsWithZone(lastSeenDate, "00:00:00", utz).toLocalDate();

            if (xmppCli != null) {
                EntityBareJid chatJid = XMPPHelper.asEntityBareJid(chatId);
                List<JsGridIMMessage> items = new ArrayList<>();

                ChatMessage message = xmppCli.sendTextMessage(chatJid, text);
                if (message == null)
                    throw new Exception("Message is null");

                if (lastSeen != null) {
                    final LocalDate mesDate = message.getTimestampDate(utz);
                    if (!mesDate.equals(lastSeen)) {
                        final String msgId = ChatMessage.buildUniqueId(chatJid, "dummy-date",
                                message.getTimestamp());
                        items.add(JsGridIMMessage.asDateAction(msgId, mesDate));
                    }
                }
                items.add(new JsGridIMMessage(true, message, getEnv().getProfile().getTimeZone()));

                new JsonResult(items, items.size()).printTo(out);

            } else {
                throw new WTException("XMPPClient not available");
            }

        }

    } catch (Exception ex) {
        logger.error("Error in ManageIMChat", ex);
        new JsonResult(ex).printTo(out);
    }
}

From source file:com.sonicle.webtop.core.Service.java

License:Open Source License

public void processManageGridIMChatMessages(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {/*  ww  w  . j  a  v a2  s  . c o  m*/
    UserProfile up = getEnv().getProfile();
    DateTimeZone utz = up.getTimeZone();

    try {
        String crud = ServletUtils.getStringParameter(request, "crud", true);
        if (crud.equals(Crud.READ)) {
            String chatId = ServletUtils.getStringParameter(request, "chatId", true);
            String date = ServletUtils.getStringParameter(request, "date", null);

            final LocalDate nowLd = DateTime.now().withZone(utz).toLocalDate();
            LocalDate ld = (date == null) ? nowLd
                    : DateTimeUtils.parseYmdHmsWithZone(date, "00:00:00", utz).toLocalDate();
            boolean history = (ld.compareTo(nowLd) != 0);

            IMChat chat = coreMgr.getIMChat(chatId);
            if (xmppCli != null) {
                List<JsGridIMMessage> items = new ArrayList<>();
                EntityBareJid chatJid = XMPPHelper.asEntityBareJid(chatId);
                EntityBareJid myJid = xmppCli.getUserJid().asEntityBareJid();

                final DateTime messageTs = ChatMessage.nowTimestamp();
                LocalDate lastDate = null;

                HashMap<String, String> cacheNicks = new HashMap<>();
                cacheNicks.put(myJid.toString(), xmppCli.getUserNickame()); // Fill cache with my data
                List<IMMessage> messages = coreMgr.listIMMessages(chatId, ld, utz, !history);

                // Add unavailable warning at the beginning
                if (history && !messages.isEmpty()) {
                    if (chat != null && chat.isUnavailable()) {
                        final String msgId = ChatMessage.buildUniqueId(chatJid, "dummy-unavailable1",
                                messageTs);
                        items.add(JsGridIMMessage.asWarnAction(msgId, messageTs, "unavailable"));
                    }
                }

                for (IMMessage mes : messages) {
                    final LocalDate mesDate = mes.getTimestampDate(utz);
                    if (!mesDate.equals(lastDate)) {
                        lastDate = mesDate;
                        final String msgId = ChatMessage.buildUniqueId(chatJid, "dummy-date",
                                mes.getTimestamp());
                        items.add(JsGridIMMessage.asDateAction(msgId, lastDate));
                    }

                    if (!cacheNicks.containsKey(mes.getSenderJid())) {
                        if (xmppCli.isAuthenticated()) {
                            cacheNicks.put(mes.getSenderJid(),
                                    xmppCli.getFriendNickname(XMPPHelper.asEntityBareJid(mes.getSenderJid())));
                        } else {
                            cacheNicks.put(mes.getSenderJid(),
                                    XMPPHelper.buildGuessedString(mes.getSenderJid()));
                        }
                    }
                    final String nick = cacheNicks.get(mes.getSenderJid());
                    items.add(new JsGridIMMessage(myJid.equals(mes.getSenderJid()), mes, nick, utz));
                }

                // Add unavailable warning at the end
                if (chat != null && chat.isUnavailable()) {
                    final String msgId = ChatMessage.buildUniqueId(chatJid, "dummy-unavailable2", messageTs);
                    items.add(JsGridIMMessage.asWarnAction(msgId, messageTs, "unavailable"));
                }

                new JsonResult(items, items.size()).printTo(out);

            } else {
                throw new WTException("XMPPClient not available");
            }
        }

    } catch (Exception ex) {
        logger.error("Error in ManageGridIMChatMessages", ex);
        new JsonResult(ex).printTo(out);
    }
}