@Override public String getGerritQuery(ServerVersion serverVersion) { String operator = getOperator(); if ("<=".equals(operator) || "<".equals(operator)) { return BeforeSearch._getGerritQuery(this, serverVersion); } else if (">=".equals(operator) || ">".equals(operator)) { return AfterSearch._getGerritQuery(this, serverVersion); } if (serverVersion != null && serverVersion.isFeatureSupported(ServerVersion.VERSION_BEFORE_SEARCH) && mDateTime != null) { // Use a combination of before and after to get an interval DateTime now = new DateTime(); if (mPeriod == null) { mPeriod = new Period(mDateTime, now); } DateTime earlier = now.minus(adjust(mPeriod, +1)); DateTime later = now.minus(mPeriod); SearchKeyword newer = new AfterSearch(earlier.toString(sGerritFormat)); SearchKeyword older = new BeforeSearch(later.toString(sGerritFormat)); return newer.getGerritQuery(serverVersion) + "+" + older.getGerritQuery(serverVersion); } else { // Need to leave off the operator and make sure we are using relative format /* Gerrit only supports specifying one time unit, so we will normalize the period * into days. */ return OP_NAME + ":" + String.valueOf(toDays()) + "d"; } }
/** * Handles the Time.now macro * * @param tokens list of tokens * @param iter iterator used to iterate over the list of tokens * @return string containing the interpolated time token */ private static String handleTime(List<String> tokens, Iterator<String> iter) { DateTime dt = new DateTime(); // Add some amount if (iter.hasNext()) { String operationToken = iter.next(); if (operationToken.equals("+") || operationToken.equals("-")) { if (iter.hasNext()) { String quantityToken = iter.next(); // Get the magnitude to // add or subtract ReadablePeriod period = getTimePeriod(quantityToken); if (operationToken.equals("-")) { dt = dt.minus(period); } else { dt = dt.plus(period); } } else { logger.warn("Token '{}' not followed by a quantity", operationToken); } } else { logger.warn("Invalid token '{}', must be operator '+' or '-'", operationToken); } } return DATE_UTIL.formatDateTime(dt); }
private DateTime truncateAndUTC(final DateTime input) { if (input == null) { return null; } final DateTime result = input.minus(input.getMillisOfSecond()); return result.toDateTime(DateTimeZone.UTC); }
/** * Retrieve counts for a given time interval, using some precision. * * @param name the name of the aggregate counter we want to retrieve data from * @param from the start-time for the interval, default depends on the resolution (e.g. go back 1 * day for hourly buckets) * @param to the end-time for the interval, default "now" * @param resolution the size of buckets to aggregate, <i>e.g.</i> hourly, daily, <i>etc.</i> * (default "hour") */ @ResponseBody @RequestMapping( value = "/{name}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public AggregateCountsResource display( @PathVariable("name") String name, // @RequestParam(value = "from", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) DateTime from, // @RequestParam(value = "to", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) DateTime to, // @RequestParam(value = "resolution", defaultValue = "hour") Resolution resolution) { if (to == null) { to = new DateTime(); } if (from == null) { from = to.minus(resolution.rewindDuration); } AggregateCount aggregate = repository.getCounts(name, new Interval(from, to), resolution.toJoda()); return aggregateCountResourceAssembler.toResource(aggregate); }
@Test public void testResetSanity() throws IOException { IncrementalIndex index = indexCreator.createIndex(); DateTime t = DateTime.now(); Interval interval = new Interval(t.minusMinutes(1), t.plusMinutes(1)); index.add( new MapBasedInputRow( t.minus(1).getMillis(), Lists.newArrayList("billy"), ImmutableMap.<String, Object>of("billy", "hi"))); index.add( new MapBasedInputRow( t.minus(1).getMillis(), Lists.newArrayList("sally"), ImmutableMap.<String, Object>of("sally", "bo"))); IncrementalIndexStorageAdapter adapter = new IncrementalIndexStorageAdapter(index); for (boolean descending : Arrays.asList(false, true)) { Sequence<Cursor> cursorSequence = adapter.makeCursors( new SelectorFilter("sally", "bo"), interval, QueryGranularity.NONE, descending); Cursor cursor = Sequences.toList(Sequences.limit(cursorSequence, 1), Lists.<Cursor>newArrayList()).get(0); DimensionSelector dimSelector; dimSelector = cursor.makeDimensionSelector(new DefaultDimensionSpec("sally", "sally")); Assert.assertEquals("bo", dimSelector.lookupName(dimSelector.getRow().get(0))); index.add( new MapBasedInputRow( t.minus(1).getMillis(), Lists.newArrayList("sally"), ImmutableMap.<String, Object>of("sally", "ah"))); // Cursor reset should not be affected by out of order values cursor.reset(); dimSelector = cursor.makeDimensionSelector(new DefaultDimensionSpec("sally", "sally")); Assert.assertEquals("bo", dimSelector.lookupName(dimSelector.getRow().get(0))); } }
@Override public String[] getEscapeArgument() { DateTime now = new DateTime(); Period period = mPeriod; // Equals: we need to do some arithmetic to get a range from the period if ("=".equals(getOperator())) { if (period == null) { period = new Period(mDateTime, now); } DateTime earlier = now.minus(adjust(period, +1)); DateTime later = now.minus(period); return new String[] {earlier.toString(sLocalFormat), later.toString(sLocalFormat)}; } else { if (period == null) { return new String[] {mDateTime.toString(sLocalFormat)}; } return new String[] {now.minus(period).toString(sLocalFormat)}; } }
@Override public TimeInstant createScenario(Session session) throws OwsExceptionReport { Transaction transaction = null; try { DateTime ref = new DateTime(DateTimeZone.UTC).minusDays(1); transaction = session.beginTransaction(); HibernateObservationBuilder b = getBuilder(session); b.createObservation(PI_BEGUN_BY_ID, ref, ref.plus(1)); b.createObservation(PI_ENDED_BY_ID, ref.minus(1), ref); b.createObservation(PI_AFTER_ID, ref.plus(1), ref.plus(2)); b.createObservation(PI_BEFORE_ID, ref.minus(2), ref.minus(1)); b.createObservation(PI_CONTAINS_ID, ref.minus(1), ref.plus(1)); session.flush(); transaction.commit(); return new TimeInstant(ref); } catch (HibernateException he) { if (transaction != null) { transaction.rollback(); } throw he; } }
public static Result index() { DateTime today = DateTime.now(); DateTime yesterday = today.minus(Days.ONE); Chat chat11 = new Chat( yesterday, 1, asList( new Item("me", LocalTime.now(), "Hello!"), new Item("other", LocalTime.now(), "Hi!"), new Item("me", LocalTime.now(), "Fine?"), new Item("other", LocalTime.now(), "Yes"))); // later on Chat chat12 = new Chat( yesterday, 2, asList( new Item("me", LocalTime.now(), "It's hot today!"), new Item("other", LocalTime.now(), "Indeed..."))); Chat chat21 = new Chat( today, 1, asList( new Item("me", LocalTime.now(), "Hello!"), new Item("me", LocalTime.now(), "Youhou?"), new Item("no-one", LocalTime.now(), "..."))); Chat chat22 = new Chat( today, 2, asList( new Item("me", LocalTime.now(), "Ding ding!"), new Item("me", LocalTime.now(), "Poueeeeeeeeeet?"), new Item("no-one", LocalTime.now(), "..."))); Chat chat23 = new Chat( today, 3, asList( new Item("me", LocalTime.now(), "No one?"), new Item("no-one", LocalTime.now(), "Yes?"))); return ok(index.render("It Works!", asList(chat23, chat11, chat21, chat12, chat22))); }
public void apply(Document doc, List<Object> values, Span span, DateTime ref) { Map params = getParameters(); String value = (String) params.get("value"); String diff = (String) params.get("diff"); String dir = (String) params.get("dir"); DateTime val = ref; if (value != null) { value = assignValues(value, values); val = new DateTime(value); } else if (diff != null) { diff = assignValues(diff, values); Period period = new Period(diff); if (dir == null || dir.equals("plus")) { val = ref.plus(period); } else if (dir.equals("minus")) { val = ref.minus(period); } } else { val = ref; // use set_xxx for (Map.Entry entry : (Set<Map.Entry>) params.entrySet()) { Matcher m = Pattern.compile("set_(.*)").matcher((String) entry.getKey()); if (m.matches()) { String field = assignValues((String) entry.getValue(), values); String fieldName = m.group(1); if (fieldName.equals("month")) { int month = Integer.parseInt(field); val = getTimeAnnotator().normalizeMonth(val, month); } else if (fieldName.equals("day")) { int day = Integer.parseInt(field); val = val.withField(DateTimeFieldType.dayOfMonth(), day); } else { throw new InternalError(); } } } } String formattedDate = formatter.print(val); FeatureSet attrs = new FeatureSet(); attrs.put("VAL", formattedDate); doc.annotate("TIMEX2", span, attrs); }
@Override protected ComputationResult compute() { try { final String filter; if (!isNullOrEmpty(streamId)) { filter = "streams:" + streamId; } else { filter = null; } // if we only need the cardinality, we can skip calculating the extended stats and vice versa boolean isCardinalityFunction = "cardinality".equals(statsFunction); final FieldStatsResult fieldStatsResult = getSearches() .fieldStats( field, query, filter, timeRange, isCardinalityFunction, isCardinalityFunction); if (trend && timeRange instanceof RelativeRange) { DateTime toPrevious = timeRange.getFrom(); DateTime fromPrevious = toPrevious.minus(Seconds.seconds(((RelativeRange) timeRange).getRange())); TimeRange previousTimeRange = new AbsoluteRange(fromPrevious, toPrevious); final FieldStatsResult previousFieldStatsResult = getSearches() .fieldStats( field, query, filter, previousTimeRange, isCardinalityFunction, isCardinalityFunction); Map<String, Object> results = Maps.newHashMap(); results.put("now", getStatisticalValue(fieldStatsResult)); results.put("previous", getStatisticalValue(previousFieldStatsResult)); long tookMs = fieldStatsResult.took().millis() + previousFieldStatsResult.took().millis(); return new ComputationResult(results, tookMs); } else { return new ComputationResult( getStatisticalValue(fieldStatsResult), fieldStatsResult.took().millis()); } } catch (Searches.FieldTypeException e) { throw new RuntimeException("Invalid field provided.", e); } }
@Test public void periodLimitsSubtract() { DateTime test = asDate(2011, 4, 30); ITimePeriod period1 = new TimeRange(asDate(2011, 4, 20), asDate(2011, 4, 25)); ITimePeriod period2 = new TimeRange(null, asDate(2011, 4, 6)); // 4월 6일까지 CalendarDateAdd dateAdd = new CalendarDateAdd(); // 예외기간을 설정합니다. 4월 6일 이전, 4월 20일 ~ 4월 25일 dateAdd.getExcludePeriods().add(period1); dateAdd.getExcludePeriods().add(period2); assertThat(dateAdd.subtract(test, Durations.Day)).isEqualTo(test.minus(Durations.Day)); // 4월 30일로부터 5일 전이면 4월 25일이지만, 예외기간이므로 4월20일이 된다. assertThat(dateAdd.subtract(test, Durations.days(5))).isEqualTo(period1.getStart()); // 4월 30일로부터 20일 전이면, 5월 전이 4월20일이므로, 4월 5일이 된다. 근데, 4월 6일 이전은 모두 제외기간이므로 null을 반환한다. assertThat(dateAdd.subtract(test, Durations.days(20))).isNull(); }
@Test public void testSingleValueTopN() throws IOException { IncrementalIndex index = indexCreator.createIndex(); DateTime t = DateTime.now(); index.add( new MapBasedInputRow( t.minus(1).getMillis(), Lists.newArrayList("sally"), ImmutableMap.<String, Object>of("sally", "bo"))); TopNQueryEngine engine = new TopNQueryEngine( new StupidPool<ByteBuffer>( new Supplier<ByteBuffer>() { @Override public ByteBuffer get() { return ByteBuffer.allocate(50000); } })); final Iterable<Result<TopNResultValue>> results = Sequences.toList( engine.query( new TopNQueryBuilder() .dataSource("test") .granularity(QueryGranularity.ALL) .intervals(Lists.newArrayList(new Interval(0, new DateTime().getMillis()))) .dimension("sally") .metric("cnt") .threshold(10) .aggregators( Lists.<AggregatorFactory>newArrayList( new LongSumAggregatorFactory("cnt", "cnt"))) .build(), new IncrementalIndexStorageAdapter(index)), Lists.<Result<TopNResultValue>>newLinkedList()); Assert.assertEquals(1, Iterables.size(results)); Assert.assertEquals(1, results.iterator().next().getValue().getValue().size()); }
@Test public void periodLimitsAdd() { DateTime test = asDate(2011, 4, 12); ITimePeriod period1 = new TimeRange(asDate(2011, 4, 20), asDate(2011, 4, 25)); ITimePeriod period2 = new TimeRange(asDate(2011, 4, 30), (DateTime) null); // 4월 30일 이후 CalendarDateAdd dateAdd = new CalendarDateAdd(); // 예외기간을 설정합니다. 4월 20일 ~ 4월25일, 4월 30일 이후 dateAdd.getExcludePeriods().add(period1); dateAdd.getExcludePeriods().add(period2); assertThat(dateAdd.add(test, Durations.Day)).isEqualTo(test.plus(Durations.Day)); // 4월 12일에 8일을 더하면 4월 20일이지만, 20~25일까지 제외되므로, 4월 25일이 된다. assertThat(dateAdd.add(test, Durations.days(8))).isEqualTo(period1.getEnd()); // 4월 12에 20일을 더하면 4월 20~25일을 제외한 후 계산하면 4월 30 이후가 된다. (5월 3일). // 하지만 4월 30 이후는 모두 제외되므로 결과값은 null이다. assertThat(dateAdd.add(test, Durations.days(20))).isNull(); assertThat(dateAdd.subtract(test, Durations.days(3))).isEqualTo(test.minus(Durations.days(3))); }
protected static DateTime getDateTimeFromPeriod(Period period) { DateTime now = new DateTime(); Duration duration = period.toDurationTo(now); return now.minus(duration); }
@Test public void shouldFilterLogEntriesOnMultipleCriteria() throws Exception { DocumentModel doc = RestServerInit.getFile(1, session); DateTime firstDate = new DateTime(); DateTime secondDate = firstDate.plusDays(10); List<LogEntry> logEntries = new ArrayList<>(); LogEntry logEntry = auditLogger.newLogEntry(); logEntry.setDocUUID(doc.getRef()); logEntry.setCategory("One"); logEntry.setEventId("firstEvent"); logEntry.setPrincipalName("bender"); logEntry.setEventDate(firstDate.toDate()); logEntries.add(logEntry); logEntry = auditLogger.newLogEntry(); logEntry.setDocUUID(doc.getRef()); logEntry.setCategory("One"); logEntry.setEventId("secondEvent"); logEntry.setPrincipalName("leela"); logEntry.setEventDate(firstDate.toDate()); logEntries.add(logEntry); logEntry = auditLogger.newLogEntry(); logEntry.setDocUUID(doc.getRef()); logEntry.setCategory("One"); logEntry.setEventId("firstEvent"); logEntry.setPrincipalName("leela"); logEntry.setEventDate(secondDate.toDate()); logEntries.add(logEntry); logEntry = auditLogger.newLogEntry(); logEntry.setDocUUID(doc.getRef()); logEntry.setCategory("One"); logEntry.setEventId("thirdEvent"); logEntry.setPrincipalName("leela"); logEntry.setEventDate(secondDate.toDate()); logEntries.add(logEntry); auditLogger.addLogEntries(logEntries); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.putSingle("category", "One"); queryParams.add("principalName", "leela"); ClientResponse response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); JsonNode node = mapper.readTree(response.getEntityInputStream()); List<JsonNode> nodes = getLogEntries(node); assertEquals(3, nodes.size()); queryParams = new MultivaluedMapImpl(); queryParams.putSingle("category", "One"); queryParams.add("principalName", "leela"); queryParams.add("eventId", "thirdEvent"); response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); node = mapper.readTree(response.getEntityInputStream()); nodes = getLogEntries(node); assertEquals(1, nodes.size()); queryParams = new MultivaluedMapImpl(); queryParams.putSingle("category", "One"); queryParams.add("principalName", "leela"); queryParams.add("eventId", "thirdEvent"); queryParams.add("startEventDate", ISODateTimeFormat.date().print(firstDate.plusDays(1))); queryParams.add("endEventDate", ISODateTimeFormat.date().print(secondDate.minus(1))); response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); node = mapper.readTree(response.getEntityInputStream()); nodes = getLogEntries(node); assertEquals(0, nodes.size()); }
/* (non-Javadoc) * @see com.vmware.identity.samlservice.SamlValidator#validate(java.lang.Object) */ @Override public ValidationResult validate(AuthnRequestState t) { log.debug("Validating request {}", t); ValidationResult vr = null; try { Validate.notNull(t); HttpServletRequest httpRequest = t.getRequest(); Validate.notNull(httpRequest); AuthnRequest request = t.getAuthnRequest(); Validate.notNull(request); Validate.notNull(request.getIssuer()); IdmAccessor accessor = t.getIdmAccessor(); Validate.notNull(accessor); Validate.notNull(accessor.getTenant()); // Validate assertion consumer service first, if that is valid, we can send SAML replies try { boolean validateACSWithMetadata = !this.isRequestSigned(t); String acsUrl = accessor.getAcsForRelyingParty( request.getIssuer().getValue(), request.getAssertionConsumerServiceIndex(), request.getAssertionConsumerServiceURL(), request.getProtocolBinding(), validateACSWithMetadata); t.setAcsUrl(acsUrl); } catch (IllegalStateException e) { // set validation result to 400 log.debug("Caught illegal state exception while Validating {} returning 400", e.toString()); vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null); } // Validate ID if (vr == null && request.getID() == null) { vr = new ValidationResult(OasisNames.REQUESTER); log.debug("Validation FAILED - Request ID is missing"); } // Validate version if (vr == null) { SAMLVersion version = request.getVersion(); if ((version.getMajorVersion() > Shared.REQUIRED_SAML_VERSION.getMajorVersion()) || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion() && version.getMinorVersion() > Shared.REQUIRED_SAML_VERSION.getMinorVersion()) { // version too high vr = new ValidationResult( OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_HIGH); log.debug("Validation FAILED - Version is too high"); } else if ((version.getMajorVersion() < Shared.REQUIRED_SAML_VERSION.getMajorVersion()) || version.getMajorVersion() == Shared.REQUIRED_SAML_VERSION.getMajorVersion() && version.getMinorVersion() < Shared.REQUIRED_SAML_VERSION.getMinorVersion()) { // version too low vr = new ValidationResult(OasisNames.VERSION_MISMATCH, OasisNames.REQUEST_VERSION_TOO_LOW); log.debug("Validation FAILED - Version is too low"); } } // Validate IssueInstant only if this is a new request (i.e. it had not pass been validated) if (vr == null && !t.isExistingRequest()) { DateTime dtPlus = request.getIssueInstant(); DateTime dtMinus = request.getIssueInstant(); DateTime instant = new DateTime(); long clockTolerance = accessor.getClockTolerance(); if (dtPlus == null) { vr = new ValidationResult(OasisNames.REQUESTER); log.debug("Validation FAILED - Issue Instant is missing"); } else { dtPlus = dtPlus.plus(clockTolerance); dtMinus = dtMinus.minus(clockTolerance); // dtPlus must be after now and dtMinus must be before now // in order to satisfy clock tolerance if (dtPlus.isBefore(instant) || dtMinus.isAfter(instant)) { vr = new ValidationResult(OasisNames.REQUESTER); log.debug("Validation FAILED - Issue Instant outside of clock tolerance"); log.debug("clockTolerance {}", clockTolerance); log.debug("now {}", instant); log.debug("dtPlus {}", dtPlus.toString()); log.debug("dtMinus {}", dtMinus.toString()); } } } // Destination URL skipped, this is already done by OpenSAML when parsing // validate scoping if presenet if (vr == null) { vr = validateScoping(t); } // signature must NOT be included if (vr == null) { if (request.getSignature() != null) { log.debug("Validation FAILED - Signature MUST NOT be present"); vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.REQUEST_UNSUPPORTED); } } // ensure that we don't accept unsigned requests if configuration requires signing if (vr == null) { try { boolean mustBeSigned = accessor.getAuthnRequestsSignedForRelyingParty(request.getIssuer().getValue()); this.validateSigning(mustBeSigned, t); } catch (IllegalStateException e) { // set validation result to request denied log.error("Validation FAILED - unsigned request detected, signing required"); vr = new ValidationResult(OasisNames.RESPONDER, OasisNames.REQUEST_DENIED); } } // validate NameIDPolicy if present if (vr == null) { NameIDPolicy policy = request.getNameIDPolicy(); if (policy != null) { String format = policy.getFormat(); if (format != null && !format.equals(OasisNames.PERSISTENT) && !format.equals(OasisNames.EMAIL_ADDRESS) && !format.equals(SAMLNames.IDFORMAT_VAL_UPN.toString())) { log.error("Validation FAILED - unknown NameIDPolicy Format"); vr = new ValidationResult(OasisNames.REQUESTER, OasisNames.INVALID_NAMEID_POLICY); } } } // validate conditions if (vr == null) { Conditions conditions = request.getConditions(); if (conditions != null) { // notBefore processing DateTime notBefore = conditions.getNotBefore(); if (notBefore != null) { // no additional validation, we'll use whatever client wants t.setStartTime(notBefore.toDate()); } // delegable and renewable conditions for (Condition c : conditions.getConditions()) { if (c == null) { continue; } if (c instanceof RenewableType) { t.setRenewable(true); } if (c instanceof DelegableType) { t.setDelegable(true); } } } } if (vr == null) { computeSupportedAuthnTypes(t, request); } // validation done if (vr == null) { log.info("Authentication request validation succeeded"); vr = new ValidationResult(); // success // check if we need to convert a principal into emailAddress if (request.getNameIDPolicy() != null && request.getNameIDPolicy().getFormat() != null && request.getNameIDPolicy().getFormat().equals(OasisNames.EMAIL_ADDRESS)) { t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_EMAIL_ADDRESS); } else { t.setIdentityFormat(OasisNames.IDENTITY_FORMAT_UPN); } } } catch (Exception e) { vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null); log.debug("Caught exception while Validating " + e.toString() + ", returning 400"); } return vr; }
public static String computeTime(String dateString, String val, String timeUnit) { DateTime date = new DateTime(); int value = 0; boolean isLong = false; if (!Strings.isEmpty(val) && !Strings.isEmpty(dateString) && !Strings.isEmpty(timeUnit)) { if (dateString.substring(dateString.indexOf("T") + 1, dateString.length()).length() == 0) { dateString = dateString + DEFAULT_TIME_FORMAT; } date = new DateTime(dateString); if (val.indexOf(".") > 0) { val = val.substring(0, val.indexOf(".")); } Long l = new Long(val); if ((l.longValue() < 0 && -l.longValue() > 32768) || (l.longValue() > 0 && l.longValue() > 32768)) { isLong = true; } if (!isLong) { value = Integer.parseInt(val); } if (!Strings.isEmpty(timeUnit)) { if (timeUnit.equals("d")) { if (!isLong) { if (value > 0) { date = date.plusDays(value); } else { date = date.minusDays(-value); } } else { if (l.longValue() < 0) { date = date.minus(-l.longValue() * 24 * 60 * 60 * 1000); } else { date = date.plus(l.longValue() * 24 * 60 * 60 * 1000); } } } else if (timeUnit.equals(HOUR)) { if (!isLong) { if (value > 0) { date = date.plusHours(value); } else { date = date.minusHours(-value); } } else { if (l.longValue() < 0) { date = date.minus(-l.longValue() * 60 * 60 * 1000); } else { date = date.plus(l.longValue() * 60 * 60 * 1000); } } } else if (timeUnit.equals(MIN)) { if (!isLong) { if (value > 0) { date = date.plusMinutes(value); } else { date = date.minusMinutes(-value); } } else { if (l.longValue() < 0) { date = date.minus(-l.longValue() * 60 * 1000); } else { date = date.plus(l.longValue() * 60 * 1000); } } } else if (timeUnit.equals(SEC)) { if (!isLong) { if (value > 0) { date = date.plusSeconds(value); } else { date = date.minusSeconds(-value); } } else { if (l.longValue() < 0) { date = date.minus(-l.longValue() * 1000); } else { date = date.plus(l.longValue() * 1000); } } } } } return FormatUtils.formatDateTimeToISO(date.toDate()); }
private static BooleanExpression isWithinPredictionWindow(DateTime time) { time = toPredictionResolution(time); return qPrediction.start.between( time.minus(PREDICTION_WINDOW).plus(PREDICTION_RESOLUTION), time); }