Example usage for org.joda.time DateTime plusMonths

List of usage examples for org.joda.time DateTime plusMonths

Introduction

In this page you can find the example usage for org.joda.time DateTime plusMonths.

Prototype

public DateTime plusMonths(int months) 

Source Link

Document

Returns a copy of this datetime plus the specified number of months.

Usage

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

License:Educational Community License

/**
 * Add the correct start and end value for the given quarter count query
 * <p/>/*from   w  w  w.  j  a va 2s  .  c om*/
 * Please note that the start instant is inclusive while the end instant is exclusive.
 *
 * @param query
 *          The query where the parameters have to be added
 * @return the same query instance
 */
private Query setDateForQuarterQuery(Query query) {
    final DateTime today = new DateTime().withTimeAtStartOfDay();
    final Partial partialToday = partialize(today);
    final DateTime quarterBeginning = mlist(quarterBeginnings)
            .foldl(quarterBeginnings.get(0), new Function2<Partial, Partial, Partial>() {
                @Override
                public Partial apply(Partial sum, Partial quarterBeginning) {
                    return partialToday.isAfter(quarterBeginning) ? quarterBeginning : sum;
                }
            }).toDateTime(today);
    return query.setParameter("start", quarterBeginning.toDate()).setParameter("end",
            quarterBeginning.plusMonths(3).toDate());
}

From source file:org.opendaylight.streamhandler.impl.KafkaStreamProducer.java

License:Open Source License

/**
 * @param timeStamp// ww  w.  ja v a2s.c  o  m
 *            timestamp.
 * @return long
 *           return rfc3164TimeStamp.
 */
protected long rfc3164TimeStamp(String timeStamp) {
    DateTime currentDateTime = DateTime.now();
    int yearCurrent = currentDateTime.getYear();
    timeStamp = SPACES_TWO_CHECK.matcher(timeStamp).replaceFirst(" ");
    DateTime dateReturned;
    try {
        dateReturned = RFC3164_FORMAT_DATETIME.parseDateTime(timeStamp);
    } catch (IllegalArgumentException e) {
        log.error("rfc3164 date parse failed on (" + timeStamp + "): invalid format", e);
        return 0;
    }
    if (dateReturned != null) {
        DateTime fixedDate = dateReturned.withYear(yearCurrent);
        if (fixedDate.isAfter(currentDateTime) && fixedDate.minusMonths(1).isAfter(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent - 1);
        } else if (fixedDate.isBefore(currentDateTime) && fixedDate.plusMonths(1).isBefore(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent + 1);
        }
        dateReturned = fixedDate;
    }
    if (dateReturned == null) {
        return 0;
    }
    return dateReturned.getMillis();
}

From source file:org.opendaylight.streamhandler.impl.LogCollector.java

License:Open Source License

protected long rfc3164TimeStamp(String timeStamp) {
    DateTime currentDateTime = DateTime.now();
    int yearCurrent = currentDateTime.getYear();
    timeStamp = SPACES_TWO_CHECK.matcher(timeStamp).replaceFirst(" ");
    DateTime dateReturned;//w  w  w.j a  v  a2  s. co  m
    try {
        dateReturned = RFC3164_FORMAT_DATETIME.parseDateTime(timeStamp);
    } catch (IllegalArgumentException e) {
        LOG.error("rfc3164 date parse failed on (" + timeStamp + "): invalid format", e);
        return 0;
    }
    if (dateReturned != null) {
        DateTime fixedDate = dateReturned.withYear(yearCurrent);
        if (fixedDate.isAfter(currentDateTime) && fixedDate.minusMonths(1).isAfter(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent - 1);
        } else if (fixedDate.isBefore(currentDateTime) && fixedDate.plusMonths(1).isBefore(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent + 1);
        }
        dateReturned = fixedDate;
    }
    if (dateReturned == null) {
        return 0;
    }
    return dateReturned.getMillis();
}

From source file:org.opendaylight.streamhandler.impl.LogCollectorTLS.java

License:Open Source License

protected long rfc3164TimeStamp(String timeStamp) {
    DateTime currentDateTime = DateTime.now();
    int yearCurrent = currentDateTime.getYear();
    timeStamp = SPACES_TWO_CHECK.matcher(timeStamp).replaceFirst(" ");
    DateTime dateReturned;/*from   ww w. j a  va2  s. c  o m*/
    try {
        dateReturned = rfc3164_FORMAT_DATETIME.parseDateTime(timeStamp);
    } catch (IllegalArgumentException e) {
        LOG.error("rfc3164 date parse failed on (" + timeStamp + "): invalid format", e);
        return 0;
    }
    if (dateReturned != null) {
        DateTime fixedDate = dateReturned.withYear(yearCurrent);
        if (fixedDate.isAfter(currentDateTime) && fixedDate.minusMonths(1).isAfter(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent - 1);
        } else if (fixedDate.isBefore(currentDateTime) && fixedDate.plusMonths(1).isBefore(currentDateTime)) {
            fixedDate = dateReturned.withYear(yearCurrent + 1);
        }
        dateReturned = fixedDate;
    }
    if (dateReturned == null) {
        return 0;
    }
    return dateReturned.getMillis();
}

From source file:org.openlmis.core.presenter.RnRFormListPresenter.java

License:Open Source License

protected void addPreviousPeriodMissedViewModels(List<RnRFormViewModel> viewModels) throws LMISException {
    int offsetMonth = periodService.getMissedPeriodOffsetMonth(this.programCode);

    DateTime inventoryBeginDate = periodService.getCurrentMonthInventoryBeginDate();
    for (int i = 0; i < offsetMonth; i++) {
        viewModels.add(RnRFormViewModel.buildMissedPeriod(inventoryBeginDate.toDate(),
                inventoryBeginDate.plusMonths(1).toDate()));
        inventoryBeginDate = inventoryBeginDate.minusMonths(1);
    }//from  w  w w  .jav  a 2 s . c o  m
    generateFirstMissedRnrFormViewModel(viewModels, offsetMonth, inventoryBeginDate);
}

From source file:org.openlmis.core.presenter.RnRFormListPresenter.java

License:Open Source License

private void generateFirstMissedRnrFormViewModel(List<RnRFormViewModel> viewModels, int offsetMonth,
        DateTime inventoryBeginDate) throws LMISException {
    if (isAllRnrFormInDBCompletedOrNoRnrFormInDB()) {
        addFirstMissedAndNotPendingRnrForm(viewModels, offsetMonth);
    } else {/*w w w .ja  va  2 s  .c o m*/
        viewModels.add(RnRFormViewModel.buildMissedPeriod(inventoryBeginDate.toDate(),
                inventoryBeginDate.plusMonths(1).toDate()));
    }
}

From source file:org.openvpms.archetype.i18n.time.DateDurationFormatter.java

License:Open Source License

/**
 * Formats the duration between two timestamps.
 * <p/>/*from ww w.  java 2s . c  o m*/
 * NOTE: this currently doesn't do anything sensible for from > to. Possible solution would be to simply
 * reverse the times, and then prepend a - between each field using  the
 *
 * @param from the starting time
 * @param to   the ending time
 * @return the formatted duration
 */
protected String format(DateTime from, DateTime to) {
    int years = 0;
    int months = 0;
    int weeks = 0;
    int days = 0;
    int hours = 0;
    int minutes = 0;

    DateTime start = from;
    if (showYears) {
        years = Years.yearsBetween(start, to).getYears();
        start = start.plusYears(years);
    }
    if (showMonths) {
        months = Months.monthsBetween(start, to).getMonths();
        start = start.plusMonths(months);
    }
    if (showWeeks) {
        weeks = Weeks.weeksBetween(start, to).getWeeks();
        start = start.plusWeeks(weeks);
    }
    if (showDays) {
        days = Days.daysBetween(start, to).getDays();
        start = start.plusDays(days);
    }
    if (showHours) {
        hours = Hours.hoursBetween(start, to).getHours();
        start = start.plusHours(hours);
    }
    if (showMinutes) {
        minutes = Minutes.minutesBetween(start, to).getMinutes();
    }

    Period period = new Period(years, months, weeks, days, hours, minutes, 0, 0);
    return formatter.print(period);
}

From source file:org.pidome.server.system.network.http.Http2ClientHandler.java

@Override
public void writeResponse(ChannelHandlerContext ctx, HttpResponseStatus status, byte[] buf, String fileType,
        String streamId, boolean cache) {

    String plainIp = HttpRequestHandler.getPlainIp(ctx.channel().localAddress());

    ByteBuf content = ctx.alloc().buffer(buf.length);
    content.writeBytes(buf);/*from  ww w  .  ja  v  a  2  s . c om*/
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);
    HttpUtil.setContentLength(response, response.content().readableBytes());
    streamId(response, streamId);

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, fileType);

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpRequestHandler.getContentTypeHeader(fileType));
    response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN,
            "https://" + plainIp + ((port != 80) ? ":" + port : ""));
    response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    response.headers().set(HttpHeaderNames.SERVER, "PiDome integrated 0.2 HTTP2");

    if (cache == true) {
        DateTime dt = new DateTime();
        HttpHeaderDateFormat dateFormat = HttpHeaderDateFormat.get();
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "public, max-age=3153600");
        response.headers().set(HttpHeaderNames.EXPIRES, dateFormat.format(dt.plusMonths(12).toDate()));
    } else {
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, must-revalidate");
        response.headers().set(HttpHeaderNames.EXPIRES, "Sat, 26 Jul 1997 05:00:00 GMT");
    }

    ctx.writeAndFlush(response);
}

From source file:org.pidome.server.system.network.http.HttpClientHandler.java

License:Apache License

/**
 * Writes the response to the output/*w  w w .jav a 2 s  .c o  m*/
 * @param ctx The channel context
 * @param status The response status
 * @param buf The buffer containing the data to send.
 * @param fileType The file type.
 * @param streamId The Stream id (only used in http2)
 * @param cache (if cache headers should be send).
 */
@Override
public final void writeResponse(ChannelHandlerContext ctx, HttpResponseStatus status, byte[] buf,
        String fileType, String streamId, boolean cache) {

    ByteBuf content = ctx.alloc().buffer(buf.length);
    content.writeBytes(buf);
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);

    HttpUtil.setContentLength(response, response.content().readableBytes());

    // In case of SPDY protocol used.
    if (spdyId != null) {
        response.headers().set(SPDY_STREAM_ID, spdyId);
        response.headers().set(SPDY_STREAM_PRIO, 0);
        response.headers().set(HttpHeaderNames.SERVER, "PiDome integrated 0.2 SPDY");
    } else {
        response.headers().set(HttpHeaderNames.SERVER, "PiDome integrated 0.2 HTTP1.1");
    }

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpRequestHandler.getContentTypeHeader(fileType));
    response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN,
            "http" + ((ssl == true) ? "s" : "") + "://" + plainIp + ((port != 80) ? ":" + port : ""));
    response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");

    if (cache == true) {
        DateTime dt = new DateTime();
        HttpHeaderDateFormat dateFormat = HttpHeaderDateFormat.get();
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "public, max-age=3153600");
        response.headers().set(HttpHeaderNames.EXPIRES, dateFormat.format(dt.plusMonths(12).toDate()));
    } else {
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, must-revalidate");
        response.headers().set(HttpHeaderNames.EXPIRES, "Sat, 26 Jul 1997 05:00:00 GMT");
    }

    if (keepAlive) {
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

        ctx.write(response);
    } else {
        // If keep-alive is off, close the connection once the content is fully written.
        ctx.write(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}

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();
    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())];
            }//from  ww w . j a va 2 s  .  c o  m
            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);
}