List of usage examples for org.joda.time DateTime minus
public DateTime minus(ReadablePeriod period)
From source file:google.registry.tools.server.GenerateZoneFilesAction.java
License:Open Source License
@Override public Map<String, Object> handleJsonRequest(Map<String, ?> json) { @SuppressWarnings("unchecked") ImmutableSet<String> tlds = ImmutableSet.copyOf((List<String>) json.get("tlds")); final DateTime exportTime = DateTime.parse(json.get("exportTime").toString()); // We disallow exporting within the past 2 minutes because there might be outstanding writes. // We can only reliably call loadAtPointInTime at times that are UTC midnight and > // datastoreRetention ago in the past. DateTime now = clock.nowUtc(); if (exportTime.isAfter(now.minusMinutes(2))) { throw new BadRequestException("Invalid export time: must be > 2 minutes ago"); }/* w w w .j a va 2s . c o m*/ if (exportTime.isBefore(now.minus(datastoreRetention))) { throw new BadRequestException(String.format("Invalid export time: must be < %d days ago", datastoreRetention.getStandardDays())); } if (!exportTime.equals(exportTime.toDateTime(UTC).withTimeAtStartOfDay())) { throw new BadRequestException("Invalid export time: must be midnight UTC"); } String jobId = mrRunner.setJobName("Generate bind file stanzas").setModuleName("tools") .setDefaultReduceShards(tlds.size()).runMapreduce(new GenerateBindFileMapper(tlds, exportTime), new GenerateBindFileReducer(bucket, exportTime, gcsBufferSize), ImmutableList.of(new NullInput<EppResource>(), createEntityInput(DomainResource.class, HostResource.class))); ImmutableList<String> filenames = FluentIterable.from(tlds).transform(new Function<String, String>() { @Override public String apply(String tld) { return String.format(GCS_PATH_FORMAT, bucket, String.format(FILENAME_FORMAT, tld, exportTime)); } }).toList(); return ImmutableMap.<String, Object>of("jobPath", createJobPath(jobId), "filenames", filenames); }
From source file:io.appform.nautilus.funnel.utils.TimeWindowNormalizer.java
License:Apache License
public static TimeWindow normalize(TimeWindow timeWindow, final DateTime currentTime) throws Exception { if (null != timeWindow.getStart()) { if (null != timeWindow.getEnd()) { //If start and end are both present then return them back ordered return orderedWindow(timeWindow.getStart(), timeWindow.getEnd()) .timeField(timeWindow.getTimeField()).build(); }/*w ww .ja v a2s . c o m*/ if (null != timeWindow.getDuration()) { //If end is not specified, then return a window from start to duration final DateTime endTime = timeWindow.getStart().plus(timeWindow.getDuration().toMilliseconds()); return orderedWindow(timeWindow.getStart(), endTime).timeField(timeWindow.getTimeField()).build(); } else { //Return a window from start to current time return orderedWindow(timeWindow.getStart(), currentTime).timeField(timeWindow.getTimeField()) .build(); } } else { if (null != timeWindow.getEnd()) { if (null != timeWindow.getDuration()) { //If only end is specified and duration is there return an ordered windonw deduced from them final DateTime startTime = timeWindow.getEnd().minus(timeWindow.getDuration().toMilliseconds()); return orderedWindow(startTime, timeWindow.getEnd()).timeField(timeWindow.getTimeField()) .build(); } else { //Return a window from start to current time return orderedWindow(timeWindow.getEnd(), currentTime).timeField(timeWindow.getTimeField()) .build(); } } else { if (null != timeWindow.getDuration()) { return orderedWindow(currentTime, currentTime.minus(timeWindow.getDuration().toMilliseconds())) .timeField(timeWindow.getTimeField()).build(); } } } throw new NautilusException(ErrorMessageTable.ErrorCode.INVALID_TIME_WINDOW, "No start, end, duration"); }
From source file:io.druid.query.TimewarpOperator.java
License:Apache License
public QueryRunner<T> postProcess(final QueryRunner<T> baseRunner, final long now) { return new QueryRunner<T>() { @Override//from w w w . j a v a 2s . c om public Sequence<T> run(final Query<T> query, final Map<String, Object> responseContext) { final long offset = computeOffset(now); final Interval interval = query.getIntervals().get(0); final Interval modifiedInterval = new Interval( Math.min(interval.getStartMillis() + offset, now + offset), Math.min(interval.getEndMillis() + offset, now + offset)); return Sequences .map(baseRunner.run( query.withQuerySegmentSpec( new MultipleIntervalSegmentSpec(Arrays.asList(modifiedInterval))), responseContext), new Function<T, T>() { @Override public T apply(T input) { if (input instanceof Result) { Result res = (Result) input; Object value = res.getValue(); if (value instanceof TimeBoundaryResultValue) { TimeBoundaryResultValue boundary = (TimeBoundaryResultValue) value; DateTime minTime = null; try { minTime = boundary.getMinTime(); } catch (IllegalArgumentException e) { } final DateTime maxTime = boundary.getMaxTime(); return (T) ((TimeBoundaryQuery) query).buildResult( new DateTime(Math .min(res.getTimestamp().getMillis() - offset, now)), minTime != null ? minTime.minus(offset) : null, maxTime != null ? new DateTime( Math.min(maxTime.getMillis() - offset, now)) : null) .iterator().next(); } return (T) new Result(res.getTimestamp().minus(offset), value); } else if (input instanceof MapBasedRow) { MapBasedRow row = (MapBasedRow) input; return (T) new MapBasedRow(row.getTimestamp().minus(offset), row.getEvent()); } // default to noop for unknown result types return input; } }); } }; }
From source file:io.druid.server.audit.SQLAuditManager.java
License:Apache License
private Interval getIntervalOrDefault(Interval interval) { final Interval theInterval; if (interval == null) { DateTime now = new DateTime(); theInterval = new Interval(now.minus(config.getAuditHistoryMillis()), now); } else {//from w w w . j av a 2 s . co m theInterval = interval; } return theInterval; }
From source file:io.prestosql.execution.SqlTaskManager.java
License:Apache License
public void failAbandonedTasks() { DateTime now = DateTime.now(); DateTime oldestAllowedHeartbeat = now.minus(clientTimeout.toMillis()); for (SqlTask sqlTask : tasks.asMap().values()) { try {//from ww w . j a va 2 s . c o m TaskInfo taskInfo = sqlTask.getTaskInfo(); TaskStatus taskStatus = taskInfo.getTaskStatus(); if (taskStatus.getState().isDone()) { continue; } DateTime lastHeartbeat = taskInfo.getLastHeartbeat(); if (lastHeartbeat != null && lastHeartbeat.isBefore(oldestAllowedHeartbeat)) { log.info("Failing abandoned task %s", taskStatus.getTaskId()); sqlTask.failed(new PrestoException(ABANDONED_TASK, format("Task %s has not been accessed since %s: currentTime %s", taskStatus.getTaskId(), lastHeartbeat, now))); } } catch (RuntimeException e) { log.warn(e, "Error while inspecting age of task %s", sqlTask.getTaskId()); } } }
From source file:it.polimi.se.calcare.service.CronJob.java
License:Open Source License
@Schedule(dayOfWeek = "*", month = "*", dayOfMonth = "*", year = "*", hour = "*/12", minute = "0", second = "0", persistent = false) public void weatherFetcher() throws IOException, JSONException, Exception { List<City> cities = em.createNamedQuery("City.findAll", City.class).getResultList(); List<Forecast> newForecasts; List<Forecast> oldForecasts; for (City c : cities) { oldForecasts = (List<Forecast>) c.getForecastCollection(); newForecasts = new GetWeather().updateForecast(c, oldForecasts); //we have to send to all the participants a mail if the weather is changed between forecasts for (Forecast newF : newForecasts) { for (Forecast oldF : oldForecasts) { //we have a forecasts for the city, so let's match only the time if (oldF.getForecastPK().getDt().equals(newF.getForecastPK().getDt())) { //if the weather code is different - so the weather is changed - //we send a mail warning all the participants if (!oldF.getWeatherCondition().getId().equals(newF.getWeatherCondition().getId())) { for (Event e : oldF.getEventCollection()) { NotificationHelper helper = new NotificationHelper(em, NotificationType.Enum.WEATHER_CHANGE, e); //should warn all the participants for (Participation p : getParticipantsForEvent(e)) { helper.sendTo(p.getUser(), composeEventLink(e), e.getName()); }//ww w . j a va 2 s .com } } } } } for (Forecast f : newForecasts) { em.merge(f); Date forecastDate = (f.getForecastPK().getDt()); DateTime forecastDateTime = new DateTime(forecastDate); Long now = new Date().getTime(); if (f.isWeatherBad()) { for (Event event : f.getEventCollection()) { Date eventStart = event.getStart(); DateTime eventStartDt = new DateTime(eventStart); //hours of difference between the event and the current moment Long difference = (eventStartDt.minus(now)).getMillis() / (1000 * 60 * 60); DateTime sunnyDayDt = null; Date sunnyDayDate = new GetWeather().nextSunnyDay(f.getCity1(), forecastDate) .getForecastPK().getDt(); if (sunnyDayDate != null) sunnyDayDt = new DateTime(sunnyDayDate); sendMailForBadWeather(event, difference, sunnyDayDt); } } } } em.flush(); }
From source file:jp.furplag.util.time.JodaPrettifier.java
License:Apache License
/** * Return the prettified String if the period includes specified moment. * * <pre>/*from w w w . ja va2s.c o m*/ * prettify(DateTime.now().minusHours(1), null, null, null, null) = "one hour ago." prettify(DateTime.now(), DateTime.now().plusYears(1), null, null, null) = "one year ago." prettify(DateTime.now().minusHours(1), null, null, null, new Period().withDays(1)) = "one hour ago." prettify(DateTime.now().minusHours(1), null, null, null, new Period().withMinites(10)) = * DateTime.now().withZone(DateTimeZone.UTC).minusHours(1).toString(DateTimeFormat.forStyle("-M")) * * <pre> * * @param then the datetime object, null means current date-time. * @param reference the moment of a starting point ( {@link org.joda.time.ReadableInstant} and {@link Long} specifiable ). Use {@code DateTime.now()} as a start point if {@code reference} is null. * @param locale the language for Localization ( {@code String} and {@code Locale} specifiable ). Use ROOT if {@code locale} is null. * @param limit if the moment is in the specified period, return prettified String ( {@code Period} and {@code Interval} specifiable ). Prettify all, if null. * @return the prettified String if the period includes specified moment. In other situation, return stringified date-time. */ public static String prettify(final Object then, final Object reference, final Locale locale, final DateTimeZone zone, final Object limit) { DateTime temporary = DateTimeUtils.toDT(then, zone, true); if (temporary == null) return StringUtils.EMPTY; DateTime ref = DateTimeUtils.toDT(reference, temporary.getZone(), true); if (ref == null) return doPrettify(temporary, null, locale); if (ref.isEqual(temporary)) ref = ref.plusMillis(1); if (limit == null) return doPrettify(temporary, ref, locale); Interval limitter = null; if (Interval.class.equals(limit)) limitter = (Interval) limit; if (limit instanceof Period) { limitter = new Interval(ref.minus((Period) limit), ref.plusMillis(1).plus((Period) limit)); } if (limit instanceof BaseSingleFieldPeriod) { limitter = new Interval(ref.minus(new Period(limit)), ref.plusMillis(1).plus(new Period(limit))); } if (ObjectUtils.isAny(ClassUtils.primitiveToWrapper(limit.getClass()), Double.class, Float.class)) { limitter = new Interval(toDT(toAJD(ref) - NumberUtils.valueOf(limit, double.class), ref), toDT(toAJD(ref) + NumberUtils.valueOf(limit, double.class), ref)); } else if (BigDecimal.class.equals(limit.getClass())) { if (NumberUtils.compareTo((BigDecimal) limit, NumberUtils.down(limit)) == 0) { limitter = new Interval(ref.minusMillis(NumberUtils.valueOf(limit, int.class)), ref.plusMillis(NumberUtils.valueOf(limit, int.class) + 1)); } else { limitter = new Interval(toDT(toAJD(ref) - NumberUtils.valueOf(limit, double.class), ref), toDT(toAJD(ref) + NumberUtils.valueOf(limit, double.class), ref)); } } else if (Number.class.isAssignableFrom(ClassUtils.primitiveToWrapper(limit.getClass()))) { limitter = new Interval(ref.minusMillis(NumberUtils.valueOf(limit, int.class)), ref.plusMillis(NumberUtils.valueOf(limit, int.class) + 1)); } if (DateTime.class.equals(limit.getClass())) { limitter = new Interval(ref.minus(((DateTime) limit).getMillis()), ref.plus(((DateTime) limit).getMillis() + 1L)); } if (Boolean.class.equals(limit.getClass())) { limitter = new Interval(temporary.minusMillis(1), ((Boolean) limit) ? temporary.plusMillis(1) : temporary.minusMillis(1)); } if (limitter == null) return doPrettify(temporary, ref, locale); if (limitter.contains(temporary)) return doPrettify(temporary, ref, locale); return toDT(temporary, GJChronology.getInstance(temporary.getZone())) .toString(DateTimeFormat.forStyle(isToday(temporary, temporary.getZone()) ? "-M" : "MS") .withLocale(locale == null ? Locale.ROOT : locale)); }
From source file:kr.debop4j.timeperiod.calendars.CalendarDateAdd.java
License:Apache License
@Override public DateTime subtract(DateTime start, Duration offset, SeekBoundaryMode seekBoundary) { log.trace("subtract. start [{}] - offset [{}]? ?? ... seekBoundary=[{}]", start, offset, seekBoundary);//from w ww . j a v a2s . c o m if (getWeekDays().size() == 0 && getExcludePeriods().size() == 0 && getWorkingHours().size() == 0) return start.minus(offset); Pair<DateTime, Duration> endTuple = (offset.compareTo(ZERO) < 0) ? calculateEnd(start, Durations.negate(offset), SeekDirection.Forward, seekBoundary) : calculateEnd(start, offset, SeekDirection.Backward, seekBoundary); DateTime end = endTuple.getV1(); log.trace("subtract. start [{}] - offset [{}] => end=[{}] seekBoundary=[{}]", start, offset, end, seekBoundary); return end; }
From source file:kr.debop4j.timeperiod.calendars.DateAdd.java
License:Apache License
/** * ? offset ? ?? .//www . j av a 2 s .co m * * @param start ? * @param offset * @param seekDir ? * @param seekBoundary ? * @return ? ?, */ protected Pair<DateTime, Duration> calculateEnd(DateTime start, Duration offset, SeekDirection seekDir, SeekBoundaryMode seekBoundary) { if (isTraceEnable) log.trace( "? ? ?? ... start=[{}], offset=[{}], seekDir=[{}], seekBoundary=[{}]", start, offset, seekDir, seekBoundary); shouldBe(offset.compareTo(Duration.ZERO) >= 0, "offset? 0 ??? . offset=[%d]", offset.getMillis()); Duration remaining = offset; DateTime end; // search periods ITimePeriodCollection searchPeriods = new TimePeriodCollection(this.includePeriods); if (searchPeriods.size() == 0) searchPeriods.add(TimeRange.Anytime); // available periods ITimePeriodCollection availablePeriods = new TimePeriodCollection(); if (excludePeriods.size() == 0) { availablePeriods.addAll(searchPeriods); } else { if (isTraceEnable) log.trace(" ? ."); TimeGapCalculator<TimeRange> gapCalculator = new TimeGapCalculator<>(); for (ITimePeriod p : searchPeriods) { if (excludePeriods.hasOverlapPeriods(p)) { if (isTraceEnable) log.trace(" ? ? ? "); for (ITimePeriod gap : gapCalculator.getGaps(excludePeriods, p)) availablePeriods.add(gap); } else { availablePeriods.add(p); } } } if (availablePeriods.size() == 0) { if (isTraceEnable) log.trace(" period ."); return Pair.create(null, remaining); } if (isTraceEnable) log.trace(" ? ? ? ..."); TimePeriodCombiner periodCombiner = new TimePeriodCombiner<TimeRange>(); availablePeriods = periodCombiner.combinePeriods(availablePeriods); if (isTraceEnable) log.trace(" ? ."); Pair<ITimePeriod, DateTime> result = (seekDir == SeekDirection.Forward) ? findNextPeriod(start, availablePeriods) : findPrevPeriod(start, availablePeriods); ITimePeriod startPeriod = result.getV1(); DateTime seekMoment = result.getV2(); // ? . if (startPeriod == null) { if (isTraceEnable) log.trace(" ? ."); return Pair.create(null, remaining); } // offset ? 0 ??, ? ? seekMoment . if (offset.isEqual(Duration.ZERO)) { if (isTraceEnable) log.trace("offset ? 0?, ? ? seekMoment ."); return Pair.create(seekMoment, remaining); } if (seekDir == SeekDirection.Forward) { for (int i = availablePeriods.indexOf(startPeriod); i < availablePeriods.size(); i++) { ITimePeriod gap = availablePeriods.get(i); Duration gapRemaining = new Duration(seekMoment, gap.getEnd()); if (isTraceEnable) log.trace("Seek forward. gap=[{}], gapRemaining=[{}], remaining=[{}], seekMoment=[{}]", gap, gapRemaining, remaining, seekMoment); boolean isTargetPeriod = (seekBoundary == SeekBoundaryMode.Fill) ? gapRemaining.compareTo(remaining) >= 0 : gapRemaining.compareTo(remaining) > 0; if (isTargetPeriod) { end = seekMoment.plus(remaining); remaining = null; return Pair.create(end, remaining); } remaining = remaining.minus(gapRemaining); if (i == availablePeriods.size() - 1) return Pair.create(null, remaining); seekMoment = availablePeriods.get(i + 1).getStart(); // next period } } else { for (int i = availablePeriods.indexOf(startPeriod); i >= 0; i--) { ITimePeriod gap = availablePeriods.get(i); Duration gapRemaining = new Duration(gap.getStart(), seekMoment); if (isTraceEnable) log.trace("Seek backward. gap=[{}], gapRemaining=[{}], remaining=[{}], seekMoment=[{}]", gap, gapRemaining, remaining, seekMoment); boolean isTargetPeriod = (seekBoundary == SeekBoundaryMode.Fill) ? gapRemaining.compareTo(remaining) >= 0 : gapRemaining.compareTo(remaining) > 0; if (isTargetPeriod) { end = seekMoment.minus(remaining); remaining = null; return Pair.create(end, remaining); } remaining = remaining.minus(gapRemaining); if (i == 0) return Pair.create(null, remaining); seekMoment = availablePeriods.get(i - 1).getEnd(); } } if (isTraceEnable) log.trace(" ?? ."); return Pair.create(null, remaining); }
From source file:kr.debop4j.timeperiod.test.samples.TimeBlockPeriodRelationTestData.java
License:Apache License
public TimeBlockPeriodRelationTestData(DateTime start, DateTime end, Duration duration) { Guard.shouldBe(duration.compareTo(Duration.ZERO) >= 0, "duration? 0??? ? ."); setReference(new TimeBlock(start, end, true)); DateTime beforeEnd = start.minus(duration); DateTime beforeStart = beforeEnd.minus(reference.getDuration()); DateTime insideStart = start.plus(duration); DateTime insideEnd = end.minus(duration); DateTime afterStart = end.plus(duration); DateTime afterEnd = afterStart.plus(reference.getDuration()); after = new TimeBlock(beforeStart, beforeEnd, true); startTouching = new TimeBlock(beforeStart, start, true); startInside = new TimeBlock(beforeStart, insideStart, true); insideStartTouching = new TimeBlock(start, afterStart, true); enclosingStartTouching = new TimeBlock(start, insideEnd, true); enclosing = new TimeBlock(insideStart, insideEnd, true); enclosingEndTouching = new TimeBlock(insideStart, end, true); exactMatch = new TimeBlock(start, end, true); inside = new TimeBlock(beforeStart, afterEnd, true); insideEndTouching = new TimeBlock(beforeStart, end, true); endInside = new TimeBlock(insideEnd, afterEnd, true); endTouching = new TimeBlock(end, afterEnd, true); before = new TimeBlock(afterStart, afterEnd, true); allPeriods.add(reference);// www .j av a 2 s . c om allPeriods.add(after); allPeriods.add(startTouching); allPeriods.add(startInside); allPeriods.add(insideStartTouching); allPeriods.add(enclosingStartTouching); allPeriods.add(enclosing); allPeriods.add(enclosingEndTouching); allPeriods.add(exactMatch); allPeriods.add(inside); allPeriods.add(insideEndTouching); allPeriods.add(endInside); allPeriods.add(endTouching); allPeriods.add(before); }