Example usage for org.joda.time Days daysBetween

List of usage examples for org.joda.time Days daysBetween

Introduction

In this page you can find the example usage for org.joda.time Days daysBetween.

Prototype

public static Days daysBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Days representing the number of whole days between the two specified partial datetimes.

Usage

From source file:org.fao.geonet.services.statistics.SearchStatistics.java

License:Open Source License

@RequestMapping(value = { "/{lang}/statistics-search" }, produces = { MediaType.APPLICATION_XML_VALUE,
        MediaType.APPLICATION_JSON_VALUE })
@ResponseBody//  w  ww .j  a  va 2 s  . c o  m
public GeneralSearchStats generalSearchStats(@RequestParam(SERVICE_PARAM) String service) throws Exception {
    final GeneralSearchStats stats = new GeneralSearchStats();

    ISODate begin = requestRepository.getOldestRequestDate();
    ISODate end = requestRepository.getMostRecentRequestDate();
    if (begin == null || end == null) {
        return stats;
    }
    DateTime beginDate = ISODate.parseBasicOrFullDateTime(begin.getDateAndTime());
    DateTime endDate = ISODate.parseBasicOrFullDateTime(end.getDateAndTime());
    int days = Days.daysBetween(beginDate, endDate).getDays();
    int nonZeroDays = max(1, days);
    int months = Months.monthsBetween(beginDate, endDate).getMonths();
    int nonZeroMonths = max(1, months);

    stats.setActivityDays(days);
    stats.setActivityMonths(months);

    // Total number of searches
    long total = requestRepository.count(hasService(service));
    stats.setTotalSearches(total);

    // Average searches by day
    long avgPerDay = total / nonZeroDays;
    stats.setAvgSearchesPerDay(avgPerDay);

    // Average searches by month
    long avgPerMonth = total / nonZeroMonths;
    stats.setAvgSearchersPerMonth(avgPerMonth);

    // Average views by day
    final int views = metadataRepository.getMetadataStatistics().getTotalStat(popularitySum(),
            Optional.<Specification<Metadata>>absent());
    int viewsByDay = views / nonZeroDays;
    stats.setAvgViewsPerDay(viewsByDay);

    // Average views by month
    int viewsByMonth = views / nonZeroMonths;
    stats.setAvgViewsPerMonth(viewsByMonth);

    // Number of search with no hits
    long noHits = requestRepository.count(where(hasService(service)).and(hasHits(0)));
    stats.setSearchesWithNoHits(noHits);

    return stats;
}

From source file:org.fenixedu.academic.domain.accounting.postingRules.ResidencePR.java

License:Open Source License

@Override
public Map<LocalDate, Money> getDueDatePenaltyAmountMap(Event event, DateTime when) {

    ResidenceEvent residenceEvent = (ResidenceEvent) event;
    if (residenceEvent.getPaymentLimitDate().isAfter(when)) {
        return Collections.emptyMap();
    }/*from   w  w  w .  j  av  a2s. co m*/

    final Money penaltyPerDay = getPenaltyPerDay();
    final LocalDate startDate = residenceEvent.getPaymentLimitDate().toLocalDate();
    final LocalDate endDate = when.toLocalDate();

    return Stream.iterate(startDate, d -> d.plusDays(1)).limit(Days.daysBetween(startDate, endDate).getDays())
            .collect(Collectors.toMap(Function.identity(), x -> penaltyPerDay));
}

From source file:org.fenixedu.parking.dto.ParkingCardSearchBean.java

License:Open Source License

private boolean satisfiesPeriodCriteria(ParkingParty parkingParty) {
    if (getParkingCardSearchPeriod() == null) {
        return Boolean.TRUE;
    } else {//from   www.ja  va2s. c o  m
        if (parkingParty.getCardEndDate() == null) {
            return Boolean.FALSE;
        } else {
            YearMonthDay today = new YearMonthDay();
            if (!today.isAfter(parkingParty.getCardEndDate().toYearMonthDay()) && (getParkingCardSearchPeriod()
                    .equals(ParkingCardSearchPeriod.ENDS_BEFORE_ONE_MONTH)
                    || getParkingCardSearchPeriod().equals(ParkingCardSearchPeriod.ENDS_BEFORE_TWO_MONTHS))) {
                int daysBetween = Days.daysBetween(today, parkingParty.getCardEndDate().toYearMonthDay())
                        .getDays();
                return daysBetween <= ParkingCardSearchPeriod.getDays(getParkingCardSearchPeriod());
            } else if (!today.isBefore(parkingParty.getCardEndDate().toYearMonthDay())
                    && (getParkingCardSearchPeriod().equals(ParkingCardSearchPeriod.ENDED_UNTIL_ONE_MONTH_AGO)
                            || getParkingCardSearchPeriod()
                                    .equals(ParkingCardSearchPeriod.ENDED_UNTIL_SIX_MONTHS_AGO)
                            || getParkingCardSearchPeriod()
                                    .equals(ParkingCardSearchPeriod.ENDED_UNTIL_ONE_YEAR_AGO))) {
                int daysBetween = Days.daysBetween(today, parkingParty.getCardEndDate().toYearMonthDay())
                        .getDays();
                return daysBetween <= ParkingCardSearchPeriod.getDays(getParkingCardSearchPeriod());
            }
        }
    }
    return false;
}

From source file:org.fenixedu.treasury.domain.tariff.InterestRate.java

License:Open Source License

private InterestRateBean calculateDaily(final Map<LocalDate, BigDecimal> createdInterestEntries,
        final LocalDate dueDate, final LocalDate paymentDate, final TreeMap<LocalDate, BigDecimal> sortedMap) {
    final InterestRateBean result = new InterestRateBean(getInterestType());

    BigDecimal totalInterestAmount = BigDecimal.ZERO;
    int totalOfDays = 0;

    LocalDate startDate = applyOnFirstWorkdayIfNecessary(
            dueDate.plusDays(numberOfDaysAfterDueDate(dueDate.getYear())));

    // Iterate over amountInDebtMap and calculate amountToPay
    BigDecimal amountInDebt = BigDecimal.ZERO;
    for (final Entry<LocalDate, BigDecimal> entry : sortedMap.entrySet()) {

        if (entry.getKey().isAfter(paymentDate)) {
            break;
        }//from   www .j av  a  2 s .  co  m

        if (entry.getKey().isBefore(startDate)) {
            amountInDebt = entry.getValue();
            continue;
        }

        final LocalDate endDate = entry.getKey();

        int numberOfDays = 0;
        BigDecimal partialInterestAmount;
        if (startDate.getYear() != endDate.getYear()) {
            boolean reachedMaxDays = false;

            int firstYearDays = Days.daysBetween(startDate, Constants.lastDayInYear(startDate.getYear()))
                    .getDays() + 1;
            int secondYearDays = Days.daysBetween(Constants.firstDayInYear(endDate.getYear()), endDate)
                    .getDays() + 1;

            {
                if (isMaximumDaysToApplyPenaltyApplied()
                        && totalOfDays + firstYearDays >= getMaximumDaysToApplyPenalty()) {
                    firstYearDays = getMaximumDaysToApplyPenalty() - totalOfDays;
                    reachedMaxDays = true;
                }

                final BigDecimal amountPerDay = Constants.divide(amountInDebt,
                        new BigDecimal(Constants.numberOfDaysInYear(startDate.getYear())));

                final BigDecimal rate = interestRate(startDate.getYear());

                partialInterestAmount = Constants.divide(rate, Constants.HUNDRED_PERCENT).multiply(amountPerDay)
                        .multiply(new BigDecimal(firstYearDays));

                numberOfDays += firstYearDays;

                if (Constants.isPositive(partialInterestAmount)) {
                    result.addDetail(partialInterestAmount, startDate,
                            Constants.lastDayInYear(startDate.getYear()), amountPerDay, amountInDebt);
                }
            }

            if (!reachedMaxDays) {

                if (isMaximumDaysToApplyPenaltyApplied()
                        && totalOfDays + firstYearDays + secondYearDays >= getMaximumDaysToApplyPenalty()) {
                    secondYearDays = getMaximumDaysToApplyPenalty() - totalOfDays - firstYearDays;
                }

                final BigDecimal amountPerDay = Constants.divide(amountInDebt,
                        new BigDecimal(Constants.numberOfDaysInYear(endDate.getYear())));

                final BigDecimal rate = interestRate(endDate.getYear());

                final BigDecimal secondInterestAmount = Constants.divide(rate, Constants.HUNDRED_PERCENT)
                        .multiply(amountPerDay).multiply(new BigDecimal(secondYearDays));

                if (Constants.isPositive(partialInterestAmount)) {
                    result.addDetail(secondInterestAmount, Constants.firstDayInYear(endDate.getYear()), endDate,
                            amountPerDay, amountInDebt);
                }

                partialInterestAmount = partialInterestAmount.add(secondInterestAmount);

                numberOfDays += secondYearDays;
            }

        } else {
            numberOfDays = Days.daysBetween(startDate, endDate).getDays() + 1;

            if (isMaximumDaysToApplyPenaltyApplied()
                    && totalOfDays + numberOfDays >= getMaximumDaysToApplyPenalty()) {
                numberOfDays = getMaximumDaysToApplyPenalty() - totalOfDays;
            }

            final BigDecimal amountPerDay = Constants.divide(amountInDebt,
                    new BigDecimal(Constants.numberOfDaysInYear(startDate.getYear())));

            final BigDecimal rate = interestRate(startDate.getYear());
            partialInterestAmount = Constants.divide(rate, Constants.HUNDRED_PERCENT).multiply(amountPerDay)
                    .multiply(new BigDecimal(numberOfDays));

            if (Constants.isPositive(partialInterestAmount)) {
                result.addDetail(partialInterestAmount, startDate, endDate, amountPerDay, amountInDebt);
            }
        }

        totalInterestAmount = totalInterestAmount.add(partialInterestAmount);
        totalOfDays += numberOfDays;

        amountInDebt = entry.getValue();
        startDate = endDate.plusDays(1);

        if (isMaximumDaysToApplyPenaltyApplied() && totalOfDays >= getMaximumDaysToApplyPenalty()) {
            break;
        }
    }

    if (createdInterestEntries != null) {
        final TreeMap<LocalDate, BigDecimal> interestSortedMap = new TreeMap<LocalDate, BigDecimal>();
        interestSortedMap.putAll(createdInterestEntries);

        for (final Entry<LocalDate, BigDecimal> entry : createdInterestEntries.entrySet()) {
            result.addCreatedInterestEntry(entry.getKey(), entry.getValue());

            totalInterestAmount = totalInterestAmount.subtract(entry.getValue());
        }
    }

    result.setInterestAmount(getRelatedCurrency().getValueWithScale(totalInterestAmount));
    result.setNumberOfDays(totalOfDays);

    return result;
}

From source file:org.fenixedu.treasury.ui.document.managepayments.SettlementNoteController.java

License:Open Source License

@RequestMapping(value = TRANSACTIONS_SUMMARY_URI, method = RequestMethod.POST)
public String transactionsSummary(
        @RequestParam(value = "finantialInstitution", required = true) FinantialInstitution finantialInstitution,
        @RequestParam(value = "documentdatefrom", required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate documentDateFrom,
        @RequestParam(value = "documentdateto", required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate documentDateTo,
        Model model) {/*w w w  .j  av  a  2 s  .  co m*/
    if (Days.daysBetween(documentDateFrom, documentDateTo)
            .getDays() > SEARCH_SETTLEMENT_ENTRY_LIMIT_DAYS_PERIOD) {
        addErrorMessage(BundleUtil.getString(Constants.BUNDLE, "error.SettlementNote.day.limit.exceeded",
                String.valueOf(SEARCH_SETTLEMENT_ENTRY_LIMIT_DAYS_PERIOD)), model);
    } else {
        List<SettlementNote> notes = filterSearchSettlementNote(finantialInstitution, documentDateFrom,
                documentDateTo);
        model.addAttribute("settlementEntriesDataSet", getSettlementEntriesDataSet(notes));
        model.addAttribute("finantialInstitution", finantialInstitution);

        populateSummaryTransactions(model, notes);
    }
    model.addAttribute("finantial_institutions_options",
            FinantialInstitution.findAll().collect(Collectors.toList()));
    return "treasury/document/managepayments/settlementnote/transactionsSummary";
}

From source file:org.fiware.qa.documentation.measurements.CatalogueComplianceMeasurement.java

License:Open Source License

private boolean measureMeta_checkDate(String meta) {

    boolean match = false;
    Matcher m1 = Pattern.compile("Updated:\\s+\\d{4}-\\d{2}-\\d{2}").matcher(meta);
    while (m1.find()) {
        match = true;//from  w w  w . ja v a  2  s  . c  o  m

    }

    if (!match) {

        protocol.storeEntry(enabler.name, "0/10 points for providing a valid recent date. "
                + "(no 'Updated: YYYY-MM-DD' string provided/identified) " + "\n" + enabler.meta);
        return false;
    }

    Matcher m2 = Pattern.compile("\\d{4}-\\d{2}-\\d{2}").matcher(meta);
    DateTime today = new DateTime();
    int dateCounter = 0;
    while (m2.find()) {

        dateCounter++;
        if (dateCounter > 1)
            logger.warn("");

        DateTime enablerDate = new DateTime(m2.group());
        int diff = Days.daysBetween(enablerDate.toLocalDate(), today.toLocalDate()).getDays();

        if (diff > 0 && diff <= 365) {
            protocol.storeEntry(enabler.name, "10/10 points for providing a valid recent date: "
                    + enablerDate.toString() + " - " + diff + " days since last update.");

        } else {
            String msg = "enabler not updated since more than 1 year: " + diff + " days since last update ("
                    + enablerDate.toString() + ")";

            protocol.storeEntry(enabler.name, "0/10 points for providing a valid recent date. " + msg);
            return false;
        }

    }

    return false;

}

From source file:org.gephi.desktop.timeline.MinimalDrawer.java

License:Open Source License

private void paintUpperRulerForInterval(Graphics2D g2d, DateTime dtFrom, DateTime dtTo) {

    g2d.setFont(settings.graduations.font);
    g2d.setColor(settings.graduations.fontColor);
    int leftMargin = settings.graduations.leftMargin;
    int textTopPosition = settings.graduations.textTopPosition;
    int width = getWidth();
    int height = getHeight();
    // TODO take these from the model

    Interval interval = new Interval(dtFrom, dtTo);

    Period p = interval.toPeriod(PeriodType.days());
    // try to determine length if we had to show milliseconds

    int n = p.getDays();
    int unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("wednesday  ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("jour");
        for (int i = 0; i < n; i++) {
            g2d.drawString(dtFrom.plusDays(i).dayOfWeek().getAsText(LOCALE), leftMargin + 2 + i * (width / n),
                    textTopPosition);//w w w .j av a2s .c o m
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Hours.hoursBetween(dtFrom.plusDays(i), dtFrom.plusDays(i + 1)).getHours());
        }
        return;
    }

    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("wed ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("jou");
        for (int i = 0; i < n; i++) {
            g2d.drawString(dtFrom.plusDays(i).dayOfWeek().getAsShortText(LOCALE),
                    leftMargin + 2 + i * (width / n), textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);

            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Hours.hoursBetween(dtFrom.plusDays(i), dtFrom.plusDays(i + 1)).getHours());
        }
        return;
    }

    p = interval.toPeriod(PeriodType.days());
    n = p.getDays();
    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("30", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("j");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getDayOfMonth() + i), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);

            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Hours.hoursBetween(dtFrom.plusDays(i), dtFrom.plusDays(i + 1)).getHours());
        }
        return;
    }

    p = interval.toPeriod(PeriodType.months());
    n = p.getMonths();
    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("September  ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("mois");
        for (int i = 0; i < n; i++) {
            g2d.drawString(dtFrom.plusMonths(i).monthOfYear().getAsText(LOCALE),
                    leftMargin + 2 + i * (width / n), textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);

            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Days.daysBetween(dtFrom.plusMonths(i), dtFrom.plusMonths(i + 1)).getDays());
        }
        return;
    }

    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("dec ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("mo");
        for (int i = 0; i < n; i++) {
            g2d.drawString(dtFrom.plusMonths(i).monthOfYear().getAsShortText(LOCALE),
                    leftMargin + 2 + i * (width / n), textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Days.daysBetween(dtFrom.plusMonths(i), dtFrom.plusMonths(i + 1)).getDays());
        }
        return;
    }

    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("29 ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("m");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getMonthOfYear() + i), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Days.daysBetween(dtFrom.plusMonths(i), dtFrom.plusMonths(i + 1)).getDays());
        }
        return;
    }

    p = interval.toPeriod(PeriodType.years());
    n = p.getYears();
    unitSize = (int) (settings.graduations.fontMetrics.getStringBounds("1980 ", null)).getWidth();
    if (n < (width / unitSize)) {
        //System.out.println("year");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i), leftMargin + 2 + i * (width / n), textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n),
                    Months.monthsBetween(dtFrom.plusYears(i), dtFrom.plusYears(i + 1)).getMonths());
        }
        return;
    }

    int group = 10;
    n = p.getYears() / group;
    if (n < (width / unitSize)) {
        //System.out.println("10 years");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i * group), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n), Months
                    .monthsBetween(dtFrom.plusYears(i * group), dtFrom.plusYears((i + 1) * group)).getMonths());
        }
        return;
    }
    group = 20;
    n = p.getYears() / group;
    if (n < (width / unitSize)) {
        //System.out.println("20 years");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i * group), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n), Months
                    .monthsBetween(dtFrom.plusYears(i * group), dtFrom.plusYears((i + 1) * group)).getMonths());
        }
        return;
    }
    group = 50;
    n = p.getYears() / group;
    if (n < (width / unitSize)) {
        //System.out.println("50 years");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i * group), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n), Months
                    .monthsBetween(dtFrom.plusYears(i * group), dtFrom.plusYears((i + 1) * group)).getMonths());
        }
        return;
    }
    group = 100;
    n = p.getYears() / group;
    if (n / 100 < (width / unitSize)) {
        //System.out.println("100 years");
        for (int i = 0; i < n; i++) {
            g2d.drawString("" + (dtFrom.getYear() + i * group), leftMargin + 2 + i * (width / n),
                    textTopPosition);
            g2d.drawLine(leftMargin + i * (width / n), 2, leftMargin + i * (width / n),
                    height - settings.graduations.textBottomMargin);
            paintSmallGraduations(g2d, leftMargin + i * (width / n), leftMargin + (i + 1) * (width / n), Months
                    .monthsBetween(dtFrom.plusYears(i * group), dtFrom.plusYears((i + 1) * group)).getMonths());
        }
    }
    return;
}

From source file:org.glucosio.android.presenter.OverviewPresenter.java

License:Open Source License

private void addZeroReadings(final ArrayList<IntGraphObject> graphObjects, final DateTime firstDate,
        final DateTime lastDate) {
    int daysBetween = Days.daysBetween(firstDate, lastDate).getDays();
    for (int i = 1; i < daysBetween; i++) {
        graphObjects.add(new IntGraphObject(firstDate.plusDays(i), 0));
    }/*ww  w. j av  a 2s  . co m*/
}

From source file:org.gnucash.android.model.Recurrence.java

License:Apache License

/**
 * Return the number of days left in this period
 * @return Number of days left in period
 *//* ww  w .j  a v a  2  s  . c o m*/
public int getDaysLeftInCurrentPeriod() {
    LocalDate startDate = new LocalDate(System.currentTimeMillis());
    int interval = mPeriodType.getMultiplier() - 1;
    LocalDate endDate = null;
    switch (mPeriodType) {
    case DAY:
        endDate = new LocalDate(System.currentTimeMillis()).plusDays(interval);
        break;
    case WEEK:
        endDate = startDate.dayOfWeek().withMaximumValue().plusWeeks(interval);
        break;
    case MONTH:
        endDate = startDate.dayOfMonth().withMaximumValue().plusMonths(interval);
        break;
    case YEAR:
        endDate = startDate.dayOfYear().withMaximumValue().plusYears(interval);
        break;
    }

    return Days.daysBetween(startDate, endDate).getDays();
}

From source file:org.jahia.modules.portal.sitesettings.PortalFactoryHandler.java

License:Open Source License

public void doUserPortalsQuery(RequestContext ctx, UserPortalsTable userPortalsTable) {
    try {//from   www  . jav  a 2  s  .co  m
        JCRSessionWrapper sessionWrapper = getCurrentUserSession(ctx, "live");
        final String siteKey = getRenderContext(ctx).getSite().getSiteKey();
        final UserPortalsTable finalTable = userPortalsTable;
        LinkedHashMap<String, UserPortalsTableRow> tableRows = JCRTemplate.getInstance()
                .doExecuteWithSystemSession(sessionWrapper.getUser().getUsername(), "live",
                        sessionWrapper.getLocale(),
                        new JCRCallback<LinkedHashMap<String, UserPortalsTableRow>>() {
                            @Override
                            public LinkedHashMap<String, UserPortalsTableRow> doInJCR(JCRSessionWrapper session)
                                    throws RepositoryException {
                                Query query = getUserPortalsQuery(siteKey, finalTable, session);
                                query.setLimit(finalTable.getPager().getItemsPerPage());
                                query.setOffset(finalTable.getPager().getItemsPerPage()
                                        * (finalTable.getPager().getPage() - 1));

                                LinkedHashMap<String, UserPortalsTableRow> tableRowsToReturn = new LinkedHashMap<String, UserPortalsTableRow>();
                                if (query.getStatement().contains("isdescendantnode")
                                        || finalTable.getSearchCriteria() == null || !StringUtils
                                                .isNotEmpty(finalTable.getSearchCriteria().getSearchString())) {
                                    NodeIterator nodeIterator = query.execute().getNodes();
                                    while (nodeIterator.hasNext()) {
                                        JCRNodeWrapper portalNode = (JCRNodeWrapper) nodeIterator.next();
                                        UserPortalsTableRow row = new UserPortalsTableRow();
                                        row.setUserNodeIdentifier(JCRContentUtils
                                                .getParentOfType(portalNode, "jnt:user").getIdentifier());
                                        try {
                                            row.setModelName(((JCRNodeWrapper) portalNode.getProperty("j:model")
                                                    .getNode()).getDisplayableName());
                                        } catch (Exception e) {
                                            // model deleted
                                            row.setModelName("No model found");
                                        }
                                        DateTime sinceDate = ISODateTimeFormat.dateOptionalTimeParser()
                                                .parseDateTime(portalNode.getPropertyAsString("j:lastViewed"));
                                        row.setLastUsed(
                                                Days.daysBetween(new LocalDate(sinceDate), new LocalDate())
                                                        .getDays());
                                        row.setCreated(
                                                portalNode.getProperty("jcr:created").getDate().getTime());
                                        tableRowsToReturn.put(portalNode.getPath(), row);
                                    }
                                }
                                return tableRowsToReturn;
                            }
                        });
        userPortalsTable.setRows(tableRows);
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }
}