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.projectforge.web.calendar.TimesheetEventsProvider.java

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime,
 *      org.joda.time.DateTime)//  w w  w . j  av a 2 s  .co m
 */
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    totalDuration = 0;
    for (int i = 0; i < durationsPerDayOfMonth.length; i++) {
        durationsPerDayOfMonth[i] = 0;
    }
    for (int i = 0; i < durationsPerDayOfYear.length; i++) {
        durationsPerDayOfYear[i] = 0;
    }
    final Integer userId = calFilter.getTimesheetUserId();
    if (userId == null) {
        return;
    }
    breaksMap = new HashMap<String, TimesheetDO>();
    int breaksCounter = 0;
    final TimesheetFilter filter = new TimesheetFilter();
    filter.setUserId(userId);
    filter.setStartTime(start.toDate());
    filter.setStopTime(end.toDate());
    filter.setOrderType(OrderDirection.ASC);
    timesheets = timesheetDao.getList(filter);
    boolean longFormat = false;
    days = Days.daysBetween(start, end).getDays();
    if (days < 10) {
        // Week or day view:
        longFormat = true;
        month = null;
        firstDayOfMonth = null;
    } else {
        // Month view:
        final DateTime currentMonth = new DateTime(start.plusDays(10),
                ThreadLocalUserContext.getDateTimeZone()); // Now we're definitely in the right
        // month.
        month = currentMonth.getMonthOfYear();
        firstDayOfMonth = currentMonth.withDayOfMonth(1);
    }
    if (CollectionUtils.isEmpty(timesheets) == false) {
        DateTime lastStopTime = null;
        for (final TimesheetDO timesheet : timesheets) {
            final DateTime startTime = new DateTime(timesheet.getStartTime(),
                    ThreadLocalUserContext.getDateTimeZone());
            final DateTime stopTime = new DateTime(timesheet.getStopTime(),
                    ThreadLocalUserContext.getDateTimeZone());
            if (stopTime.isBefore(start) == true || startTime.isAfter(end) == true) {
                // Time sheet doesn't match time period start - end.
                continue;
            }
            if (calFilter.isShowBreaks() == true) {
                if (lastStopTime != null && DateHelper.isSameDay(stopTime, lastStopTime) == true
                        && startTime.getMillis() - lastStopTime.getMillis() > 60000) {
                    // Show breaks between time sheets of one day (> 60s).
                    final Event breakEvent = new Event();
                    breakEvent.setEditable(false);
                    final String breakId = String.valueOf(++breaksCounter);
                    breakEvent.setClassName(Const.BREAK_EVENT_CLASS_NAME).setId(breakId).setStart(lastStopTime)
                            .setEnd(startTime).setTitle(getString("timesheet.break"));
                    breakEvent.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
                    events.put(breakId, breakEvent);
                    final TimesheetDO breakTimesheet = new TimesheetDO().setStartDate(lastStopTime.toDate())
                            .setStopTime(startTime.getMillis());
                    breaksMap.put(breakId, breakTimesheet);
                }
                lastStopTime = stopTime;
            }
            final long duration = timesheet.getDuration();
            final MyWicketEvent event = new MyWicketEvent();
            final String id = "" + timesheet.getId();
            event.setClassName(Const.EVENT_CLASS_NAME);
            event.setId(id);
            event.setStart(startTime);
            event.setEnd(stopTime);
            final String title = CalendarHelper.getTitle(timesheet);
            if (longFormat == true) {
                // Week or day view:
                event.setTitle(title + "\n" + getToolTip(timesheet) + "\n" + formatDuration(duration, false));
            } else {
                // Month view:
                event.setTitle(title);
            }
            if (month != null && startTime.getMonthOfYear() != month && stopTime.getMonthOfYear() != month) {
                // Display time sheets of other month as grey blue:
                event.setTextColor("#222222").setBackgroundColor("#ACD9E8").setColor("#ACD9E8");
            }
            events.put(id, event);
            if (month == null || startTime.getMonthOfYear() == month) {
                totalDuration += duration;
                addDurationOfDay(startTime.getDayOfMonth(), duration);
            }
            final int dayOfYear = startTime.getDayOfYear();
            addDurationOfDayOfYear(dayOfYear, duration);
            event.setTooltip(getString("timesheet"),
                    new String[][] { { title }, { timesheet.getLocation(), getString("timesheet.location") },
                            { KostFormatter.formatLong(timesheet.getKost2()), getString("fibu.kost2") },
                            { TaskFormatter.getTaskPath(timesheet.getTaskId(), true, OutputType.PLAIN),
                                    getString("task") },
                            { timesheet.getDescription(), getString("description") } });
        }
    }
    if (calFilter.isShowStatistics() == true) {
        // Show statistics: duration of every day is shown as all day event.
        DateTime day = start;
        final Calendar cal = DateHelper.getCalendar();
        cal.setTime(start.toDate());
        final int numberOfDaysInYear = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
        int paranoiaCounter = 0;
        do {
            if (++paranoiaCounter > 1000) {
                log.error(
                        "Paranoia counter exceeded! Dear developer, please have a look at the implementation of buildEvents.");
                break;
            }
            final int dayOfYear = day.getDayOfYear();
            final long duration = durationsPerDayOfYear[dayOfYear];
            final boolean firstDayOfWeek = day.getDayOfWeek() == ThreadLocalUserContext.getJodaFirstDayOfWeek();
            if (firstDayOfWeek == false && duration == 0) {
                day = day.plusDays(1);
                continue;
            }
            final Event event = new Event().setAllDay(true);
            final String id = "s-" + (dayOfYear);
            event.setId(id);
            event.setStart(day);
            final String durationString = formatDuration(duration, false);
            if (firstDayOfWeek == true) {
                // Show week of year at top of first day of week.
                long weekDuration = 0;
                for (short i = 0; i < 7; i++) {
                    int d = dayOfYear + i;
                    if (d > numberOfDaysInYear) {
                        d -= numberOfDaysInYear;
                    }
                    weekDuration += durationsPerDayOfYear[d];
                }
                final StringBuffer buf = new StringBuffer();
                buf.append(getString("calendar.weekOfYearShortLabel")).append(DateHelper.getWeekOfYear(day));
                if (days > 1 && weekDuration > 0) {
                    // Show total sum of durations over all time sheets of current week (only in week and month view).
                    buf.append(": ").append(formatDuration(weekDuration, false));
                }
                if (duration > 0) {
                    buf.append(", ").append(durationString);
                }
                event.setTitle(buf.toString());
            } else {
                event.setTitle(durationString);
            }
            event.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
            event.setEditable(false);
            events.put(id, event);
            day = day.plusDays(1);
        } while (day.isAfter(end) == false);
    }
}

From source file:org.projectforge.web.teamcal.event.TeamCalEventProvider.java

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime,
 *      org.joda.time.DateTime)//  w  w w.j  a v a 2 s . c o m
 */
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    final TemplateEntry activeTemplateEntry = filter.getActiveTemplateEntry();
    if (activeTemplateEntry == null) {
        // Nothing to build.
        return;
    }
    final Set<Integer> visibleCalendars = activeTemplateEntry.getVisibleCalendarIds();
    if (CollectionUtils.isEmpty(visibleCalendars) == true) {
        // Nothing to build.
        return;
    }
    final TeamEventFilter eventFilter = new TeamEventFilter();
    eventFilter.setTeamCals(visibleCalendars);
    eventFilter.setStartDate(start.toDate());
    eventFilter.setEndDate(end.toDate());
    eventFilter.setUser(ThreadLocalUserContext.getUser());
    final List<TeamEvent> teamEvents = teamEventDao.getEventList(eventFilter, true);

    boolean longFormat = false;
    days = Days.daysBetween(start, end).getDays();
    if (days < 10) {
        // Week or day view:
        longFormat = true;
    }

    final TeamCalRight right = new TeamCalRight(accessChecker);
    final PFUserDO user = ThreadLocalUserContext.getUser();
    final TimeZone timeZone = ThreadLocalUserContext.getTimeZone();
    if (CollectionUtils.isNotEmpty(teamEvents) == true) {
        for (final TeamEvent teamEvent : teamEvents) {
            final DateTime startDate = new DateTime(teamEvent.getStartDate(),
                    ThreadLocalUserContext.getDateTimeZone());
            final DateTime endDate = new DateTime(teamEvent.getEndDate(),
                    ThreadLocalUserContext.getDateTimeZone());
            final TeamEventDO eventDO;
            final TeamCalEventId id = new TeamCalEventId(teamEvent, timeZone);
            if (teamEvent instanceof TeamEventDO) {
                eventDO = (TeamEventDO) teamEvent;
            } else {
                eventDO = ((TeamRecurrenceEvent) teamEvent).getMaster();
            }
            teamEventMap.put(id.toString(), teamEvent);
            final MyWicketEvent event = new MyWicketEvent();
            event.setClassName(
                    EVENT_CLASS_NAME + " " + EventDroppedCallbackScriptGenerator.NO_CONTEXTMENU_INDICATOR);
            event.setId("" + id);
            event.setColor(activeTemplateEntry.getColorCode(eventDO.getCalendarId()));

            if (eventRight.hasUpdateAccess(ThreadLocalUserContext.getUser(), eventDO, null)) {
                event.setEditable(true);
            } else {
                event.setEditable(false);
            }

            // id <= 0 is hint for abo events -> not editable
            if (eventDO.getId() != null && eventDO.getId() <= 0) {
                event.setEditable(false);
            }

            if (teamEvent.isAllDay() == true) {
                event.setAllDay(true);
            }

            event.setStart(startDate);
            event.setEnd(endDate);

            String recurrence = null;
            if (eventDO.hasRecurrence() == true) {
                final Recur recur = eventDO.getRecurrenceObject();
                final TeamEventRecurrenceData recurrenceData = new TeamEventRecurrenceData(recur,
                        ThreadLocalUserContext.getTimeZone());
                final RecurrenceFrequency frequency = recurrenceData.getFrequency();
                if (frequency != null) {
                    final String unitI18nKey = frequency.getUnitI18nKey();
                    if (unitI18nKey != null) {
                        recurrence = recurrenceData.getInterval() + " " + getString(unitI18nKey);
                    }
                }
            }
            String reminder = null;
            if (eventDO.getReminderActionType() != null
                    && NumberHelper.greaterZero(eventDO.getReminderDuration()) == true
                    && eventDO.getReminderDurationUnit() != null) {
                reminder = getString(eventDO.getReminderActionType().getI18nKey()) + " "
                        + eventDO.getReminderDuration() + " "
                        + getString(eventDO.getReminderDurationUnit().getI18nKey());
            }
            event.setTooltip(eventDO.getCalendar().getTitle(),
                    new String[][] { { eventDO.getSubject() },
                            { eventDO.getLocation(), getString("timesheet.location") },
                            { eventDO.getNote(), getString("plugins.teamcal.event.note") },
                            { recurrence, getString("plugins.teamcal.event.recurrence") },
                            { reminder, getString("plugins.teamcal.event.reminder") } });
            final String title;
            String durationString = "";
            if (longFormat == true) {
                // String day = duration.getDays() + "";
                final Period period = new Period(startDate, endDate);
                int hourInt = period.getHours();
                if (period.getDays() > 0) {
                    hourInt += period.getDays() * 24;
                }
                final String hour = hourInt < 10 ? "0" + hourInt : "" + hourInt;

                final int minuteInt = period.getMinutes();
                final String minute = minuteInt < 10 ? "0" + minuteInt : "" + minuteInt;

                if (event.isAllDay() == false) {
                    durationString = "\n"
                            + ThreadLocalUserContext.getLocalizedString("plugins.teamcal.event.duration") + ": "
                            + hour + ":" + minute;
                }
                final StringBuffer buf = new StringBuffer();
                buf.append(teamEvent.getSubject());
                if (StringUtils.isNotBlank(teamEvent.getNote()) == true) {
                    buf.append("\n")
                            .append(ThreadLocalUserContext.getLocalizedString("plugins.teamcal.event.note"))
                            .append(": ").append(teamEvent.getNote());
                }
                buf.append(durationString);
                title = buf.toString();
            } else {
                title = teamEvent.getSubject();
            }
            if (right.hasMinimalAccess(eventDO.getCalendar(), user.getId()) == true) {
                // for minimal access
                event.setTitle("");
                event.setEditable(false);
            } else {
                event.setTitle(title);
            }
            events.put(id + "", event);
        }
    }
}

From source file:org.projectforge.web.timesheet.TimesheetEventsProvider.java

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime, org.joda.time.DateTime)
 *///from w ww.  ja v a 2  s .  co  m
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    totalDuration = 0;
    for (int i = 0; i < durationsPerDayOfMonth.length; i++) {
        durationsPerDayOfMonth[i] = 0;
    }
    for (int i = 0; i < durationsPerDayOfYear.length; i++) {
        durationsPerDayOfYear[i] = 0;
    }
    final Integer userId = calFilter.getTimesheetUserId();
    if (userId == null) {
        return;
    }
    breaksMap = new HashMap<String, TimesheetDO>();
    int breaksCounter = 0;
    final TimesheetFilter filter = new TimesheetFilter();
    filter.setUserId(userId);
    filter.setStartTime(start.toDate());
    filter.setStopTime(end.toDate());
    filter.setOrderType(OrderDirection.ASC);
    timesheets = timesheetDao.getList(filter);
    boolean longFormat = false;
    days = Days.daysBetween(start, end).getDays();
    if (days < 10) {
        // Week or day view:
        longFormat = true;
        month = null;
        firstDayOfMonth = null;
    } else {
        // Month view:
        final DateTime currentMonth = new DateTime(start.plusDays(10), PFUserContext.getDateTimeZone()); // Now we're definitely in the right
        // month.
        month = currentMonth.getMonthOfYear();
        firstDayOfMonth = currentMonth.withDayOfMonth(1);
    }
    if (CollectionUtils.isEmpty(timesheets) == false) {
        DateTime lastStopTime = null;
        for (final TimesheetDO timesheet : timesheets) {
            final DateTime startTime = new DateTime(timesheet.getStartTime(), PFUserContext.getDateTimeZone());
            final DateTime stopTime = new DateTime(timesheet.getStopTime(), PFUserContext.getDateTimeZone());
            if (stopTime.isBefore(start) == true || startTime.isAfter(end) == true) {
                // Time sheet doesn't match time period start - end.
                continue;
            }
            if (calFilter.isShowBreaks() == true) {
                if (lastStopTime != null && DateHelper.isSameDay(stopTime, lastStopTime) == true
                        && startTime.getMillis() - lastStopTime.getMillis() > 60000) {
                    // Show breaks between time sheets of one day (> 60s).
                    final Event breakEvent = new Event();
                    breakEvent.setEditable(false);
                    final String breakId = String.valueOf(++breaksCounter);
                    breakEvent.setClassName(BREAK_EVENT_CLASS_NAME).setId(breakId).setStart(lastStopTime)
                            .setEnd(startTime).setTitle(getString("timesheet.break"));
                    breakEvent.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
                    events.put(breakId, breakEvent);
                    final TimesheetDO breakTimesheet = new TimesheetDO().setStartDate(lastStopTime.toDate())
                            .setStopTime(startTime.getMillis());
                    breaksMap.put(breakId, breakTimesheet);
                }
                lastStopTime = stopTime;
            }
            final long duration = timesheet.getDuration();
            final MyEvent event = new MyEvent();
            final String id = "" + timesheet.getId();
            event.setClassName(EVENT_CLASS_NAME);
            event.setId(id);
            event.setStart(startTime);
            event.setEnd(stopTime);
            final String title = getTitle(timesheet);
            if (longFormat == true) {
                // Week or day view:
                event.setTitle(title + "\n" + getToolTip(timesheet) + "\n" + formatDuration(duration, false));
            } else {
                // Month view:
                event.setTitle(title);
            }
            if (month != null && startTime.getMonthOfYear() != month && stopTime.getMonthOfYear() != month) {
                // Display time sheets of other month as grey blue:
                event.setTextColor("#222222").setBackgroundColor("#ACD9E8").setColor("#ACD9E8");
            }
            events.put(id, event);
            if (month == null || startTime.getMonthOfYear() == month) {
                totalDuration += duration;
                addDurationOfDay(startTime.getDayOfMonth(), duration);
            }
            final int dayOfYear = startTime.getDayOfYear();
            addDurationOfDayOfYear(dayOfYear, duration);
            event.setTooltip(getString("timesheet"),
                    new String[][] { { title }, { timesheet.getLocation(), getString("timesheet.location") },
                            { KostFormatter.formatLong(timesheet.getKost2()), getString("fibu.kost2") },
                            { TaskFormatter.instance().getTaskPath(timesheet.getTaskId(), true,
                                    OutputType.PLAIN), getString("task") },
                            { timesheet.getDescription(), getString("description") } });
        }
    }
    if (calFilter.isShowStatistics() == true) {
        // Show statistics: duration of every day is shown as all day event.
        DateTime day = start;
        final Calendar cal = DateHelper.getCalendar();
        cal.setTime(start.toDate());
        final int numberOfDaysInYear = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
        int paranoiaCounter = 0;
        do {
            if (++paranoiaCounter > 1000) {
                log.error(
                        "Paranoia counter exceeded! Dear developer, please have a look at the implementation of buildEvents.");
                break;
            }
            final int dayOfYear = day.getDayOfYear();
            final long duration = durationsPerDayOfYear[dayOfYear];
            final boolean firstDayOfWeek = day.getDayOfWeek() == PFUserContext.getJodaFirstDayOfWeek();
            if (firstDayOfWeek == false && duration == 0) {
                day = day.plusDays(1);
                continue;
            }
            final Event event = new Event().setAllDay(true);
            final String id = "s-" + (dayOfYear);
            event.setId(id);
            event.setStart(day);
            final String durationString = formatDuration(duration, false);
            if (firstDayOfWeek == true) {
                // Show week of year at top of first day of week.
                long weekDuration = 0;
                for (short i = 0; i < 7; i++) {
                    int d = dayOfYear + i;
                    if (d > numberOfDaysInYear) {
                        d -= numberOfDaysInYear;
                    }
                    weekDuration += durationsPerDayOfYear[d];
                }
                final StringBuffer buf = new StringBuffer();
                buf.append(getString("calendar.weekOfYearShortLabel")).append(DateHelper.getWeekOfYear(day));
                if (days > 1 && weekDuration > 0) {
                    // Show total sum of durations over all time sheets of current week (only in week and month view).
                    buf.append(": ").append(formatDuration(weekDuration, false));
                }
                if (duration > 0) {
                    buf.append(", ").append(durationString);
                }
                event.setTitle(buf.toString());
            } else {
                event.setTitle(durationString);
            }
            event.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
            event.setEditable(false);
            events.put(id, event);
            day = day.plusDays(1);
        } while (day.isAfter(end) == false);
    }
}

From source file:org.renjin.primitives.time.Time.java

License:Open Source License

/**
 * Converts a POSIXlt object (in calendar form) to a Date object,
 * which stores dates as an offset from Jan 1, 1970.
 *///from   w w  w  . j  a  v  a 2  s .c o m
@Internal
public static DoubleVector POSIXlt2Date(ListVector x) {
    PosixLtVector ltVector = new PosixLtVector(x);
    DoubleArrayVector.Builder dateVector = DoubleArrayVector.Builder.withInitialCapacity(ltVector.length());
    for (int i = 0; i != ltVector.length(); ++i) {
        DateTime date = ltVector.getElementAsDateTime(i);
        dateVector.add(Days.daysBetween(EPOCH, date).getDays());
    }
    dateVector.setAttribute(Symbols.CLASS, StringVector.valueOf("Date"));
    return dateVector.build();
}

From source file:org.sistemafinanciero.rest.impl.CuentaBancariaRESTService.java

License:Apache License

@Override
public Response getCertificado(BigInteger id) {
    OutputStream file;/*w  ww .  ja v  a2s .  co  m*/

    CuentaBancariaView cuentaBancaria = cuentaBancariaServiceNT.findById(id);
    String codigoAgencia = ProduceObject.getCodigoAgenciaFromNumeroCuenta(cuentaBancaria.getNumeroCuenta());

    Agencia agencia = agenciaServiceNT.findByCodigo(codigoAgencia);

    if (agencia == null) {
        JsonObject model = Json.createObjectBuilder().add("message", "Agencia no encontrado").build();
        return Response.status(Response.Status.NOT_FOUND).entity(model).build();
    }

    try {
        file = new FileOutputStream(new File(certificadoURL + "\\" + id + ".pdf"));
        //Document document = new Document(PageSize.A5.rotate());
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, file);
        document.open();

        //recuperando moneda, redondeando y dando formato
        Moneda moneda = monedaServiceNT.findById(cuentaBancaria.getIdMoneda());
        BigDecimal saldo = cuentaBancaria.getSaldo();
        BigDecimal decimalValue = saldo.subtract(saldo.setScale(0, RoundingMode.FLOOR))
                .movePointRight(saldo.scale());
        Long integerValue = saldo.longValue();

        String decimalString = decimalValue.toString();
        if (decimalString.length() < 2)
            decimalString = "0" + decimalString;

        NumberFormat df1 = NumberFormat.getCurrencyInstance();
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setCurrencySymbol("");
        dfs.setGroupingSeparator(',');
        dfs.setMonetaryDecimalSeparator('.');
        ((DecimalFormat) df1).setDecimalFormatSymbols(dfs);

        //recuperando el plazo en dias
        Date fechaApertura = cuentaBancaria.getFechaApertura();
        Date fechaCierre = cuentaBancaria.getFechaCierre();
        LocalDate localDateApertura = new LocalDate(fechaApertura);
        LocalDate localDateCierre = new LocalDate(fechaCierre);
        Days days = Days.daysBetween(localDateApertura, localDateCierre);

        //fuentes
        Font fontTitulo = FontFactory.getFont("Times New Roman", 14, Font.BOLD);
        Font fontSubTitulo = FontFactory.getFont("Times New Roman", 8);
        Font fontContenidoNegrita = FontFactory.getFont("Times New Roman", 10, Font.BOLD);
        Font fontContenidoNormal = FontFactory.getFont("Times New Roman", 10);

        //dando formato a las fechas
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        String fechaAperturaString = df.format(cuentaBancaria.getFechaApertura());
        String fechaVencimientoString = df.format(cuentaBancaria.getFechaCierre());

        //ingresando datos al documento
        document.add(new Paragraph("\n"));
        document.add(new Paragraph("\n"));

        //parrafo titulo
        Paragraph parrafoTitulo = new Paragraph();
        parrafoTitulo.setFont(fontTitulo);
        parrafoTitulo.setSpacingBefore(30);
        parrafoTitulo.setAlignment(Element.ALIGN_CENTER);

        //parrafo subtitulo
        Paragraph parrafoSubTitulo = new Paragraph();
        parrafoSubTitulo.setFont(fontSubTitulo);
        parrafoSubTitulo.setSpacingAfter(30);
        parrafoSubTitulo.setAlignment(Element.ALIGN_CENTER);

        //parrafo contenido
        Paragraph parrafoContenido = new Paragraph();
        parrafoContenido.setIndentationLeft(50);
        parrafoContenido.setAlignment(Element.ALIGN_LEFT);

        //parrafo firmas
        Paragraph parrafoFirmas = new Paragraph();
        parrafoFirmas.setAlignment(Element.ALIGN_CENTER);

        //agregar titulo al documento
        Chunk titulo = new Chunk("CERTIFICADO DE PLAZO FIJO");
        parrafoTitulo.add(titulo);

        //agregar titulo al documento
        Chunk subTitulo;
        if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ZERO) == 0) {
            subTitulo = new Chunk("DEPSITO A PLAZO FIJO - DOLARES AMERICANOS");
        } else if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ONE) == 0) {
            subTitulo = new Chunk("DEPSITO A PLAZO FIJO - NUEVOS SOLES");
        } else {
            subTitulo = new Chunk("DEPSITO A PLAZO FIJO - EUROS");
        }
        parrafoSubTitulo.add(subTitulo);

        //agregando contenido al documento
        //Agencia
        Chunk agencia1 = new Chunk("AGENCIA", fontContenidoNegrita);
        Chunk agencia2 = new Chunk(": " + agencia.getCodigo() + " - " + agencia.getDenominacion().toUpperCase(),
                fontContenidoNormal);
        parrafoContenido.add(agencia1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(agencia2);
        parrafoContenido.add("\n");

        //cuenta
        Chunk numeroCuenta1 = new Chunk("N CUENTA", fontContenidoNegrita);
        Chunk numeroCuenta2 = new Chunk(": " + cuentaBancaria.getNumeroCuenta(), fontContenidoNormal);
        parrafoContenido.add(numeroCuenta1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(numeroCuenta2);
        parrafoContenido.add("\n");

        //codigo cliente
        Chunk codigoSocio1 = new Chunk("CODIGO CLIENTE", fontContenidoNegrita);
        Chunk codigoSocio2 = new Chunk(": " + cuentaBancaria.getIdSocio().toString(), fontContenidoNormal);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(codigoSocio1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(codigoSocio2);
        parrafoContenido.add("\n");

        //cliente
        Chunk socio1 = new Chunk("CLIENTE", fontContenidoNegrita);
        Chunk socio2 = new Chunk(": " + cuentaBancaria.getSocio(), fontContenidoNormal);
        parrafoContenido.add(socio1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(socio2);
        parrafoContenido.add("\n");

        //tipo cuenta
        Chunk tipoCuenta1 = new Chunk("TIPO CUENTA", fontContenidoNegrita);
        Chunk tipoCuenta2 = new Chunk(": " + "INDIVIDUAL", fontContenidoNormal);
        parrafoContenido.add(tipoCuenta1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(tipoCuenta2);
        parrafoContenido.add("\n");

        //tipo moneda
        Chunk tipoMoneda1 = new Chunk("TIPO MONEDA", fontContenidoNegrita);
        Chunk tipoMoneda2;
        if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ZERO) == 0) {
            tipoMoneda2 = new Chunk(": " + "DOLARES AMERICANOS", fontContenidoNormal);
        } else if (cuentaBancaria.getIdMoneda().compareTo(BigInteger.ONE) == 0) {
            tipoMoneda2 = new Chunk(": " + "NUEVOS SOLES", fontContenidoNormal);
        } else {
            tipoMoneda2 = new Chunk(": " + "EUROS", fontContenidoNormal);
        }
        parrafoContenido.add(tipoMoneda1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(tipoMoneda2);
        parrafoContenido.add("\n");

        //Monto
        Chunk monto1 = new Chunk("MONTO", fontContenidoNegrita);
        Chunk monto2 = new Chunk(": " + moneda.getSimbolo() + df1.format(saldo) + " - "
                + NumLetrasJ.Convierte(integerValue.toString() + "", Tipo.Pronombre).toUpperCase() + " Y "
                + decimalString + "/100 " + moneda.getDenominacion(), fontContenidoNormal);
        parrafoContenido.add(monto1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(monto2);
        parrafoContenido.add("\n");

        //Plazo
        Chunk plazo1 = new Chunk("PLAZO", fontContenidoNegrita);
        Chunk plazo2 = new Chunk(": " + days.getDays() + " D?AS", fontContenidoNormal);
        parrafoContenido.add(plazo1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(plazo2);
        parrafoContenido.add("\n");

        //Fecha Apertura
        Chunk fechaApertura1 = new Chunk("FEC. APERTURA", fontContenidoNegrita);
        Chunk fechaApertura2 = new Chunk(": " + fechaAperturaString, fontContenidoNormal);
        parrafoContenido.add(fechaApertura1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(fechaApertura2);
        parrafoContenido.add("\n");

        //Fecha Vencimiento
        Chunk fechaVencimiento1 = new Chunk("FEC. VENCIMIENTO", fontContenidoNegrita);
        Chunk fechaVencimiento2 = new Chunk(": " + fechaVencimientoString, fontContenidoNormal);
        parrafoContenido.add(fechaVencimiento1);
        parrafoContenido.add(Chunk.SPACETABBING);
        parrafoContenido.add(fechaVencimiento2);
        parrafoContenido.add("\n");

        //tasa efectiva anual
        Chunk tasaEfectivaAnual1 = new Chunk("TASA EFECTIVA ANUAL", fontContenidoNegrita);
        Chunk tasaEfectivaAnual2 = new Chunk(
                ": " + cuentaBancaria.getTasaInteres().multiply(new BigDecimal(100)).toString() + "%",
                fontContenidoNormal);
        parrafoContenido.add(tasaEfectivaAnual1);
        parrafoContenido.add(tasaEfectivaAnual2);
        parrafoContenido.add("\n");

        //frecuencia de capitalizacion
        Chunk frecuenciaCapitalizacion1 = new Chunk("FREC. CAPITALIZACION", fontContenidoNegrita);
        Chunk frecuenciaCapitalizacion2 = new Chunk(": " + "DIARIA", fontContenidoNormal);
        parrafoContenido.add(frecuenciaCapitalizacion1);
        parrafoContenido.add(frecuenciaCapitalizacion2);
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");

        //importante
        Chunk importante = new Chunk("IMPORTANTE: ", fontContenidoNegrita);
        Chunk importanteDetalle1 = new Chunk(
                "DEPSITO CUBIERTO POR EL FONDO DE SEGURO DE DEPOSITOS ESTABLECIDO POR EL BANCO CENTRAL DE RESERVA DEL PER HASTA S/.82,073.00.",
                fontSubTitulo);
        Chunk importanteDetalle2 = new Chunk(
                "LAS PERSONAS JUR?DICAS SIN FINES DE LUCRO SON CUBIERTAS POR EL FONDO DE SEGURO DE DEPSITOS.",
                fontSubTitulo);
        parrafoContenido.add(importante);
        parrafoContenido.add(importanteDetalle1);
        parrafoContenido.add("\n");
        parrafoContenido.add(importanteDetalle2);
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");

        //certificado intranferible
        Chunk certificadoIntransferible = new Chunk("CERTIFICADO INTRANSFERIBLE.", fontContenidoNegrita);
        parrafoContenido.add(certificadoIntransferible);
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");
        parrafoContenido.add("\n");

        //Firmas
        Chunk subGion = new Chunk("___________________", fontContenidoNormal);
        Chunk firmaCajero = new Chunk("CAJERO", fontContenidoNormal);
        Chunk firmaCliente = new Chunk("CLIENTE", fontContenidoNormal);

        parrafoFirmas.add(subGion);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(subGion);
        parrafoFirmas.add("\n");
        parrafoFirmas.add(firmaCajero);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(Chunk.SPACETABBING);
        parrafoFirmas.add(firmaCliente);

        //agregando los parrafos al documento
        document.add(parrafoTitulo);
        document.add(parrafoSubTitulo);
        document.add(parrafoContenido);
        document.add(parrafoFirmas);
        document.close();
        file.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    PdfReader reader;
    try {
        reader = new PdfReader(certificadoURL + "\\" + id + ".pdf");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PdfStamper pdfStamper = new PdfStamper(reader, out);
        AcroFields acroFields = pdfStamper.getAcroFields();
        acroFields.setField("field_title", "test");
        pdfStamper.close();
        reader.close();
        return Response.ok(out.toByteArray()).type("application/pdf").build();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Jsend.getErrorJSend("No encontrado"))
            .build();
}

From source file:org.smartdeveloperhub.harvesters.it.testing.generator.ProjectActivityGenerator.java

License:Apache License

private Duration estimateEffort(final LocalDateTime start, final LocalDateTime dueTo) {
    final Days daysBetween = Days.daysBetween(start, dueTo);
    int workingDays = 0;
    for (int i = 0; i < daysBetween.getDays(); i++) {
        if (Utils.isWorkingDay(start.toLocalDate().plusDays(i))) {
            workingDays++;//w  ww  .ja v  a  2s .  c o m
        }
    }
    final int maxMinutes = workingDays * this.workDay.effortPerDay();
    final double ratio = (100 + this.random.nextInt(900)) / 1000d;
    Duration result = Duration.standardMinutes(
            33 * maxMinutes / 100 + DoubleMath.roundToInt(67 * maxMinutes / 100 * ratio, RoundingMode.CEILING));
    if (result.isShorterThan(MINIMUM_EFFORT)) {
        result = MINIMUM_EFFORT;
    }
    return result;
}

From source file:org.sonatype.nexus.timeline.internal.DefaultTimeline.java

License:Open Source License

/**
 * Purges old clusters based on {@code days} ("older than days") parameters. If input is {@code 0}, all clusters will
 * be removed, meaning all the timeline is purged. As Orient DDL is not atomic, this method must be mutually
 * exclusive//from  w  ww  . java  2s.c  o  m
 * with {@link #maybeAddNewCluster(ODatabaseDocumentTx, long)}, hence both are synchronized.
 */
@Override
public synchronized void purgeOlderThan(final int days) {
    if (!isStarted()) {
        return;
    }
    try (ODatabaseDocumentTx db = openDb()) {
        final DateMidnight nowDm = new DateMidnight(DateTimeZone.UTC);
        final int prefixLen = DB_CLUSTER_PREFIX.length();
        final int[] cids = db.getMetadata().getSchema().getClass(DB_CLASS).getClusterIds();
        for (int cid : cids) {
            final String name = db.getClusterNameById(cid);
            log.debug("Cluster: {} {}", cid, name);
            if (name.startsWith(DB_CLUSTER_PREFIX)) {
                final int year = Integer.parseInt(name.substring(prefixLen, prefixLen + 4));
                final int month = Integer.parseInt(name.substring(prefixLen + 4, prefixLen + 6));
                final int day = Integer.parseInt(name.substring(prefixLen + 6, prefixLen + 8));
                final DateMidnight clusterDm = new DateMidnight(year, month, day, DateTimeZone.UTC);
                if (Days.daysBetween(clusterDm, nowDm).getDays() >= days) {
                    log.info("Cluster {}, is {} days old, purging it", name,
                            Days.daysBetween(clusterDm, nowDm).getDays());
                    OSchema schema = db.getMetadata().getSchema();
                    OClass type = schema.getClass(DB_CLASS);
                    type.removeClusterId(cid);
                    db.dropCluster(cid, true);
                }
            }
        }
    }
}

From source file:org.springframework.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

public AggregateCounter getCounts(Interval interval, AggregateCounterResolution resolution) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();//from  w  w  w.j  a v  a2  s .co  m
    Chronology c = interval.getChronology();

    long[] counts;
    if (resolution == AggregateCounterResolution.minute) {
        List<long[]> days = accumulateDayCounts(minuteCountsByDay, start, end, 60 * 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getMinuteOfDay(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);
    } else if (resolution == AggregateCounterResolution.hour) {
        List<long[]> days = accumulateDayCounts(hourCountsByDay, start, end, 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);
    } else if (resolution == AggregateCounterResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(start.getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearDays = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] dayCounts = dayCountsByYear.get(cursor.getYear());
            if (dayCounts == null) {
                // Querying where we have no data
                dayCounts = new long[daysInYear(cursor.getYear())];
            }
            yearDays.add(dayCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearDays, startDay.getDayOfYear() - 1, nDays);

    } else if (resolution == AggregateCounterResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearMonths = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] monthCounts = monthCountsByYear.get(cursor.getYear());
            if (monthCounts == null) {
                monthCounts = new long[12];
            }
            yearMonths.add(monthCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearMonths, startMonth.getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCounterResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            long[] monthCounts = monthCountsByYear.get(startYear.plusYears(i).getYear());
            counts[i] = MetricUtils.sum(monthCounts);
        }

    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCounter(this.name, interval, counts, resolution);
}

From source file:org.springframework.analytics.metrics.redis.RedisAggregateCounterRepository.java

License:Apache License

/**
 * For each query, we need to convert the interval into two variations. One is the start and end points rounded to
 * the resolution (used to calculate the number of entries to be returned from the query). The second is the start
 * and end buckets we have to retrieve which may contain entries for the interval. For example, when querying
 * at day resolution, the number of entries is the number of Joda time days between the start (rounded down to a
 * day boundary) and the end plus one day (also rounded down). However, we need load the data from the buckets
 * from the month the start day occurs in to the month end day occurs in. These are then concatenated, using the
 * start day as the start index into the first array, and writing the total number of entries in sequence from that
 * point into the combined result counts array.
 *//*  w  ww. ja v a 2s  . c o m*/
@Override
public AggregateCounter getCounts(String name, Interval interval, AggregateCounterResolution resolution) {

    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;

    if (resolution == AggregateCounterResolution.minute) {
        // Iterate through each hour in the interval and load the minutes for it
        MutableDateTime dt = new MutableDateTime(interval.getStart());
        dt.setRounding(c.hourOfDay());
        Duration step = Duration.standardHours(1);
        List<long[]> hours = new ArrayList<long[]>();
        while (dt.isBefore(end) || dt.isEqual(end)) {
            hours.add(getMinCountsForHour(name, dt));
            dt.add(step);
        }
        counts = MetricUtils.concatArrays(hours, interval.getStart().getMinuteOfHour(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);

    } else if (resolution == AggregateCounterResolution.hour) {
        DateTime cursor = new DateTime(c.dayOfMonth().roundFloor(interval.getStart().getMillis()));
        List<long[]> days = new ArrayList<long[]>();
        Duration step = Duration.standardHours(24);
        while (cursor.isBefore(end)) {
            days.add(getHourCountsForDay(name, cursor));
            cursor = cursor.plus(step);
        }

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);

    } else if (resolution == AggregateCounterResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(interval.getStart().getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.monthOfYear().roundFloor(interval.getStart().getMillis()));
        List<long[]> months = new ArrayList<long[]>();
        DateTime endMonth = new DateTime(
                c.monthOfYear().roundCeiling(interval.getEnd().plusMonths(1).getMillis()));
        while (cursor.isBefore(endMonth)) {
            months.add(getDayCountsForMonth(name, cursor));
            cursor = cursor.plusMonths(1);
        }

        counts = MetricUtils.concatArrays(months, interval.getStart().getDayOfMonth() - 1, nDays);
    } else if (resolution == AggregateCounterResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> years = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(interval.getEnd().plusYears(1).getMillis()));
        while (cursor.isBefore(endYear)) {
            years.add(getMonthCountsForYear(name, cursor));
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(years, interval.getStart().getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCounterResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        Map<String, Long> yearCounts = getYearCounts(name);
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            int year = startYear.plusYears(i).getYear();
            Long count = yearCounts.get(Integer.toString(year));
            if (count == null) {
                count = 0L;
            }
            counts[i] = count;
        }
    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCounter(name, interval, counts, resolution);
}

From source file:org.springframework.xd.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

public AggregateCount getCounts(Interval interval, AggregateCountResolution resolution) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();//  ww w.j  av  a  2s . co  m
    Chronology c = interval.getChronology();

    long[] counts;
    if (resolution == AggregateCountResolution.minute) {
        List<long[]> days = accumulateDayCounts(minuteCountsByDay, start, end, 60 * 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getMinuteOfDay(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);
    } else if (resolution == AggregateCountResolution.hour) {
        List<long[]> days = accumulateDayCounts(hourCountsByDay, start, end, 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);
    } else if (resolution == AggregateCountResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(start.getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearDays = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] dayCounts = dayCountsByYear.get(cursor.getYear());
            if (dayCounts == null) {
                // Querying where we have no data
                dayCounts = new long[daysInYear(cursor.getYear())];
            }
            yearDays.add(dayCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearDays, startDay.getDayOfYear() - 1, nDays);

    } else if (resolution == AggregateCountResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearMonths = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] monthCounts = monthCountsByYear.get(cursor.getYear());
            if (monthCounts == null) {
                monthCounts = new long[12];
            }
            yearMonths.add(monthCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearMonths, startMonth.getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCountResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            long[] monthCounts = monthCountsByYear.get(startYear.plusYears(i).getYear());
            counts[i] = MetricUtils.sum(monthCounts);
        }

    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCount(getName(), interval, counts, resolution);
}