public void test_convertToInstant_furtherAfterLeap() { OffsetDateTime odt = OffsetDateTime.of(1980, 1, 1, 0, 0, 1, 0, ZoneOffset.UTC); Instant instant = odt.toInstant(); UtcInstant utc = UtcInstant.ofModifiedJulianDay(MJD_1980, NANOS_PER_SEC); assertEquals(rules.convertToInstant(utc), instant); assertEquals(rules.convertToUtc(instant), utc); }
@Test public void testTimestampQueryingAndOrder() throws IOException { ServiceLocator locator = container; SearchByTimestampAndOrderByTimestampRepository analysisGridRepository = locator.resolve(SearchByTimestampAndOrderByTimestampRepository.class); String marker = UUID.randomUUID().toString(); OffsetDateTime dt1 = OffsetDateTime.now(); OffsetDateTime dt2 = dt1.plusDays(1); OffsetDateTime dt3 = dt1.plusDays(2); OffsetDateTime dt4 = dt1.plusDays(3); SearchByTimestampAndOrderByTimestamp[] arr = new SearchByTimestampAndOrderByTimestamp[] { new SearchByTimestampAndOrderByTimestamp().setOndate(dt1).setMarker(marker), new SearchByTimestampAndOrderByTimestamp().setOndate(dt2).setMarker(marker), new SearchByTimestampAndOrderByTimestamp().setOndate(dt3).setMarker(marker), new SearchByTimestampAndOrderByTimestamp().setOndate(dt4).setMarker(marker) }; analysisGridRepository.insert(arr); List<SearchByTimestampAndOrderByTimestamp> queryResults = analysisGridRepository .query(it -> it.getMarker().equals(marker) && it.getOndate().isAfter(dt2)) .sortedDescendingBy(SearchByTimestampAndOrderByTimestamp::getOndate) .list(); Assert.assertEquals(queryResults.size(), arr.length - 2); Assert.assertTrue(queryResults.get(0).getOndate().isEqual(dt4)); }
// ----------------------------------------------------------------------- // convertToUtc(Instant)/convertToInstant(UtcInstant) // ----------------------------------------------------------------------- public void test_convertToInstant_justBeforeLeap() { OffsetDateTime odt = OffsetDateTime.of(1979, 12, 31, 23, 43, 21, 0, ZoneOffset.UTC); Instant instant = odt.toInstant(); UtcInstant utc = UtcInstant.ofModifiedJulianDay(MJD_1980 - 1, (SECS_PER_DAY + 1 - 1000) * NANOS_PER_SEC); assertEquals(rules.convertToInstant(utc), instant); assertEquals(rules.convertToUtc(instant), utc); }
@Override public boolean isSatisfiedBy(Payment payment) { OffsetDateTime offsetPaymentDate; offsetPaymentDate = OffsetDateTime.ofInstant(payment.getDate(), ZoneOffset.UTC); logger.entry(payment); logger.entry(offsetPaymentDate); return logger.exit(offsetPaymentDate.toLocalTime().compareTo(value) <= 0); }
public void test_convertToInstant_slsMicros() { for (int i = 1; i < 1000; i++) { long utcNanos = (SECS_PER_DAY + 1 - 1000) * NANOS_PER_SEC + i * 1000; long startSls = (86401 - 1000) * NANOS_PER_SEC; long slsNanos = (utcNanos - (utcNanos - startSls) / 1000); OffsetDateTime odt = OffsetDateTime.of( 1979, 12, 31, 23, 43, 21, (int) (slsNanos % NANOS_PER_SEC), ZoneOffset.UTC); Instant instant = odt.toInstant(); UtcInstant utc = UtcInstant.ofModifiedJulianDay( MJD_1980 - 1, (SECS_PER_DAY + 1 - 1000) * NANOS_PER_SEC + i * 1000); assertEquals(rules.convertToInstant(utc), instant); assertEquals(rules.convertToUtc(instant), utc); } }
@Override protected void writeDateTime(BsonWriter writer, String name, Object value, EncoderContext ctx) { writer.writeDateTime( OffsetDateTime.parse(((JsonObject) value).getString(DATE_FIELD)) .toInstant() .toEpochMilli()); }
public void test_convertToInstant_slsNanos() { for (int i = 1; i < 5005; i++) { long utcNanos = (SECS_PER_DAY + 1 - 1000) * NANOS_PER_SEC + i; long startSls = (86401 - 1000) * NANOS_PER_SEC; long slsNanos = (utcNanos - (utcNanos - startSls) / 1000); OffsetDateTime odt = OffsetDateTime.of( 1979, 12, 31, 23, 43, 21, (int) (slsNanos % NANOS_PER_SEC), ZoneOffset.UTC); Instant instant = odt.toInstant(); UtcInstant utc = UtcInstant.ofModifiedJulianDay(MJD_1980 - 1, utcNanos); assertEquals(rules.convertToInstant(utc), instant); // not all instants can map back to the correct UTC value long reverseUtcNanos = startSls + ((slsNanos - startSls) * 1000L) / (1000L - 1); assertEquals( rules.convertToUtc(instant), UtcInstant.ofModifiedJulianDay(MJD_1980 - 1, reverseUtcNanos)); } }
@Override protected Object readDateTime(BsonReader reader, DecoderContext ctx) { final JsonObject result = new JsonObject(); result.put( DATE_FIELD, OffsetDateTime.ofInstant(Instant.ofEpochMilli(reader.readDateTime()), ZoneOffset.UTC) .format(ISO_OFFSET_DATE_TIME)); return result; }
// TODO clean up @Override public void testGoogleFitMeasureFromDataPoint( BodyHeight testMeasure, Map<String, Object> properties) { BodyHeight.Builder bodyHeightBuilder = new BodyHeight.Builder(new LengthUnitValue(METER, (double) properties.get("fpValue"))); if (properties.containsKey("endDateTimeString")) { bodyHeightBuilder.setEffectiveTimeFrame( TimeInterval.ofStartDateTimeAndEndDateTime( OffsetDateTime.parse((String) properties.get("startDateTimeString")), OffsetDateTime.parse((String) properties.get("endDateTimeString")))); } else { bodyHeightBuilder.setEffectiveTimeFrame( OffsetDateTime.parse((String) properties.get("startDateTimeString"))); } BodyHeight expectedBodyHeight = bodyHeightBuilder.build(); assertThat(testMeasure, equalTo(expectedBodyHeight)); }
private static Instant getInstant(String str) { try { Instant i = OffsetDateTime.parse(str).toInstant(); LOG.debug(str + " resolved to Instant"); return i; } catch (DateTimeException e) { LOG.debug(str + " does not match to OffsetDateTime pattern"); } return null; }
@PreUpdate public void beforeUpdate(Object entity) { if (entity instanceof AbstractAuditableEntity) { AbstractAuditableEntity o = (AbstractAuditableEntity) entity; o.setUpdatedAt(OffsetDateTime.now()); if (o.getUpdatedBy() == null) { o.setUpdatedBy(currentUser()); } } }
@Test public void shouldReturnJobIfJobExists() throws Exception { // given ZoneId cet = ZoneId.of("CET"); OffsetDateTime now = OffsetDateTime.now(cet); JobInfo expectedJob = newJobInfo("42", "TEST", fixed(now.toInstant(), cet), "localhost"); when(jobService.findJob("42")).thenReturn(Optional.of(expectedJob)); String nowAsString = ISO_OFFSET_DATE_TIME.format(now); mockMvc .perform( MockMvcRequestBuilders.get("/some-microservice/internal/jobs/42") .servletPath("/internal/jobs/42")) .andExpect(MockMvcResultMatchers.status().is(200)) .andExpect(MockMvcResultMatchers.jsonPath("$.status").value("OK")) .andExpect(MockMvcResultMatchers.jsonPath("$.messages").isArray()) .andExpect(MockMvcResultMatchers.jsonPath("$.jobType").value("TEST")) .andExpect(MockMvcResultMatchers.jsonPath("$.hostname").value("localhost")) .andExpect(MockMvcResultMatchers.jsonPath("$.started").value(nowAsString)) .andExpect(MockMvcResultMatchers.jsonPath("$.stopped").value("")) .andExpect(MockMvcResultMatchers.jsonPath("$.lastUpdated").value(nowAsString)) .andExpect( MockMvcResultMatchers.jsonPath("$.jobUri") .value("http://localhost/some-microservice/internal/jobs/42")) .andExpect(MockMvcResultMatchers.jsonPath("$.links").isArray()) .andExpect( MockMvcResultMatchers.jsonPath("$.links[0].href") .value("http://localhost/some-microservice/internal/jobs/42")) .andExpect( MockMvcResultMatchers.jsonPath("$.links[1].href") .value("http://localhost/some-microservice/internal/jobdefinitions/TEST")) .andExpect( MockMvcResultMatchers.jsonPath("$.links[2].href") .value("http://localhost/some-microservice/internal/jobs")) .andExpect( MockMvcResultMatchers.jsonPath("$.links[3].href") .value("http://localhost/some-microservice/internal/jobs?type=TEST")) .andExpect(MockMvcResultMatchers.jsonPath("$.runtime").value("")) .andExpect(MockMvcResultMatchers.jsonPath("$.state").value("Running")); verify(jobService).findJob("42"); }
@Override public int compareTo(TextChannel chan) { if (this == chan) return 0; if (this.getGuild() != chan.getGuild()) throw new IllegalArgumentException( "Cannot compare TextChannels that aren't from the same guild!"); if (this.getPositionRaw() != chan.getPositionRaw()) return chan.getPositionRaw() - this.getPositionRaw(); OffsetDateTime thisTime = MiscUtil.getCreationTime(this); OffsetDateTime chanTime = MiscUtil.getCreationTime(chan); // We compare the provided channel's time to this's time instead of the reverse as one would // expect due to how // discord deals with hierarchy. The more recent a channel was created, the lower its hierarchy // ranking when // it shares the same position as another channel. return chanTime.compareTo(thisTime); }
public void calculateNextScheduledRun(Long immediateFrequency) { if (lastScheduledRun == null) { lastScheduledRun = OffsetDateTime.now(); } switch (getFrequency().getFrequency()) { case IMMEDIATE: setNextScheduledRun(lastScheduledRun.plusMinutes(immediateFrequency)); break; case DAILY: setNextScheduledRun(lastScheduledRun.plusDays(1)); break; case WEEKLY: setNextScheduledRun(lastScheduledRun.plusWeeks(1)); break; case MONTHLY: setNextScheduledRun(lastScheduledRun.plusMonths(1)); break; default: setNextScheduledRun(null); } }
@DataProvider(name = "parseWithOffsetWithoutZone") Object[][] data_parse_WithOffset_WithoutZone() { return new Object[][] { { "2015-12-14T00:45:00-11:30", OffsetDateTime.of(2015, 12, 14, 0, 45, 0, 0, ZoneOffset.of("-11:30")) }, { "2015-12-14T01:45:00-05:00", OffsetDateTime.of(2015, 12, 14, 1, 45, 0, 0, ZoneOffset.of("-05:00")) }, { "2015-12-14T02:45:00-00:00", OffsetDateTime.of(2015, 12, 14, 2, 45, 0, 0, ZoneOffset.of("-00:00")) }, { "2015-12-14T03:45:00+00:00", OffsetDateTime.of(2015, 12, 14, 3, 45, 0, 0, ZoneOffset.of("+00:00")) }, { "2015-12-14T04:45:00+03:30", OffsetDateTime.of(2015, 12, 14, 4, 45, 0, 0, ZoneOffset.of("+03:30")) }, { "2015-12-14T05:45:00+10:00", OffsetDateTime.of(2015, 12, 14, 5, 45, 0, 0, ZoneOffset.of("+10:00")) } }; }
/** * Get a single world by it's ID * * @param id the ID * @return the world */ @RequestMapping("/{id}") @ResponseBody public WorldModel get(@PathVariable("id") final String id) { WorldModel worldModel = new WorldModel(); worldModel.setId(id); worldModel.setName("Middle Earth"); worldModel.setDescription("The world of The Hobbit and The Lord of the Rings"); worldModel.setCreationDate(OffsetDateTime.now()); worldModel.setOwner(new UserLink()); worldModel.getOwner().setId(UUID.randomUUID().toString()); worldModel.getOwner().setName("Tolkien"); return worldModel; }
// @Inject // @AuthenticatedUser // User user; // @PersistenceContext // EntityManager em; @PrePersist public void beforePersist(Object entity) { if (entity instanceof AbstractAuditableEntity) { AbstractAuditableEntity o = (AbstractAuditableEntity) entity; final OffsetDateTime now = OffsetDateTime.now(); o.setCreatedAt(now); o.setUpdatedAt(now); if (o.getCreatedBy() == null) { o.setCreatedBy(currentUser()); } } }
private void updateMetadata(ZdoModel model) throws IOException { Response.StatusType statusInfo = ClientBuilder.newClient() .target(fitTransactionToUrl(model.getUrl())) .request() .put(Entity.entity(model, RDF_SERIALIZATION)) .getStatusInfo(); if (statusInfo.getFamily() != Response.Status.Family.SUCCESSFUL) { logError(fitTransactionToUrl(model.getUrl()), statusInfo); throw new IOException("Failed to update resource " + fitTransactionToUrl(model.getUrl())); } model.removeAllValuesOfProperty(ZdoTerms.fedoraLastModified); if (ZdoType.isAbovePageCategory(model.get(ZdoTerms.zdoType))) { model.add( model.getSubject(), ZdoTerms.fedoraLastModified, OffsetDateTime.now().toString(), XSDDatatype.XSDdateTime); if (model.get(ZdoTerms.fedoraCreated) == null) { model.add( model.getSubject(), ZdoTerms.fedoraCreated, OffsetDateTime.now().toString(), XSDDatatype.XSDdateTime); } } else { model.removeAllValuesOfProperty(ZdoTerms.fedoraCreated); } // Also update triplestore model.stripPossibleBadUrlEnding(); // strip fcr:metadata if (transactionPath == null) { sparqlOnDemandIndexer.update(model); } else { // If in transaction, triplestore operations are delayed till its end toUpdate.add(model); } }
@Test public void CanDecodeFromJson() throws Exception { String content = "[[2015, 6, 28], [[13, 52, 5, 123456],7260]]"; ObjectMapper mapper = JacksonObjectMapperFactory.objectMapper(DataFormat.Text); Object timeObj = mapper.readValue(content, Object.class); SqpTimestamp sqpTimestamp = SqpTimestamp.fromJsonFormatValue(timeObj); OffsetDateTime timestamp = sqpTimestamp.asOffsetDateTime(); assertThat(timestamp.getHour(), is(13)); assertThat(timestamp.getMinute(), is(52)); assertThat(timestamp.getSecond(), is(5)); assertThat(timestamp.getNano(), is(123456)); assertThat(timestamp.getOffset().getTotalSeconds(), is(7260)); assertThat(timestamp.getYear(), is(2015)); assertThat(timestamp.getMonth(), is(Month.JUNE)); assertThat(timestamp.getDayOfMonth(), is(28)); }
public static void main(String[] args) throws ParseException { OffsetDateTime start = OffsetDateTime.parse("2014-06-10T10:45:00+03:00"); // Takes the time stamp and converts to an OffsetDateTime object OffsetDateTime end = OffsetDateTime.parse("2015-06-10T10:50:00+03:00"); Instant startInst = start.toInstant(); // converts it to an Instant Class object Instant endInst = end.toInstant(); Duration dur = Duration.between(startInst, endInst); // calculates the duration between the two instances System.out.println("The Period between the two instants is:\n"); System.out.println(dur.toMillis() + " Millisecs"); // prints the milliseconds }
@Override public Optional<String> validate(final String dateTime) { try { OffsetDateTime.parse(dateTime, ISO_OFFSET_DATE_TIME); // Unfortunately, ISO_OFFSET_DATE_TIME accepts offsets with seconds, which is not RFC3339 // compliant. So // we need to do some further checks using a regex in order to be sure that it adhere to the // given format. final Matcher matcher = pattern.matcher(dateTime); if (matcher.matches()) { return Optional.empty(); } else { return error; } } catch (final DateTimeParseException e) { return error; } }
@Override public TemporalAccessor parse(String text, Locale locale) throws ParseException { DateTimeFormatter formatterToUse = DateTimeContextHolder.getFormatter(this.formatter, locale); if (LocalDate.class.equals(this.temporalAccessorType)) { return LocalDate.parse(text, formatterToUse); } else if (LocalTime.class.equals(this.temporalAccessorType)) { return LocalTime.parse(text, formatterToUse); } else if (LocalDateTime.class.equals(this.temporalAccessorType)) { return LocalDateTime.parse(text, formatterToUse); } else if (ZonedDateTime.class.equals(this.temporalAccessorType)) { return ZonedDateTime.parse(text, formatterToUse); } else if (OffsetDateTime.class.equals(this.temporalAccessorType)) { return OffsetDateTime.parse(text, formatterToUse); } else if (OffsetTime.class.equals(this.temporalAccessorType)) { return OffsetTime.parse(text, formatterToUse); } else { throw new IllegalStateException( "Unsupported TemporalAccessor type: " + this.temporalAccessorType); } }
public static void main(String... args) { F<String, F<String, Date>> simpleDate = df -> s -> { try { return new SimpleDateFormat(df).parse(s); } catch (Exception e) { throw new RuntimeException(e); } }; Either<String, Date> res = parseDate( Either.left(args[0]), s -> Date.from(LocalDateTime.parse(s).toInstant(ZoneOffset.UTC)), s -> Date.from(OffsetDateTime.parse(s).toInstant()), s -> Date.from(ZonedDateTime.parse(s).toInstant()), simpleDate.f("yyyy-MM-dd HH:mm:ss"), s -> "now".equals(s) ? new Date() : null); System.out.println("------"); System.out.println(res); }
protected ResponseEntity<ShimDataResponse> getData( OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { final JawboneDataTypes jawboneDataType; try { jawboneDataType = JawboneDataTypes.valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase()); } catch (NullPointerException | IllegalArgumentException e) { throw new ShimException( "Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey() + " in shimDataRequest, cannot retrieve data."); } // FIXME this needs to get changed or documented long numToReturn = 100; if (shimDataRequest.getNumToReturn() != null) { numToReturn = shimDataRequest.getNumToReturn(); } OffsetDateTime today = OffsetDateTime.now(); OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? today.minusDays(1) : shimDataRequest.getStartDateTime(); long startTimeInEpochSecond = startDateTime.toEpochSecond(); OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? today.plusDays(1) : shimDataRequest.getEndDateTime(); long endTimeInEpochSecond = endDateTime.toEpochSecond(); UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL) .path(jawboneDataType.getEndPoint()) .queryParam("start_time", startTimeInEpochSecond) .queryParam("end_time", endTimeInEpochSecond) .queryParam("limit", numToReturn); ResponseEntity<JsonNode> responseEntity; try { responseEntity = restTemplate.getForEntity(uriComponentsBuilder.build().encode().toUri(), JsonNode.class); } catch (HttpClientErrorException | HttpServerErrorException e) { // FIXME figure out how to handle this logger.error("A request for Jawbone data failed.", e); throw e; } if (shimDataRequest.getNormalize()) { JawboneDataPointMapper mapper; switch (jawboneDataType) { case WEIGHT: mapper = new JawboneBodyWeightDataPointMapper(); break; case STEPS: mapper = new JawboneStepCountDataPointMapper(); break; case BODY_MASS_INDEX: mapper = new JawboneBodyMassIndexDataPointMapper(); break; case ACTIVITY: mapper = new JawbonePhysicalActivityDataPointMapper(); break; case SLEEP: mapper = new JawboneSleepDurationDataPointMapper(); break; case HEART_RATE: mapper = new JawboneHeartRateDataPointMapper(); break; default: throw new UnsupportedOperationException(); } return ResponseEntity.ok() .body( ShimDataResponse.result( JawboneShim.SHIM_KEY, mapper.asDataPoints(singletonList(responseEntity.getBody())))); } else { return ResponseEntity.ok() .body(ShimDataResponse.result(JawboneShim.SHIM_KEY, responseEntity.getBody())); } }
@Test(dataProvider = "parseWithOffsetWithoutZone") public void testWithOffsetWithoutZone(String odtString, OffsetDateTime expectedOTD) { dtFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; odt1 = OffsetDateTime.parse(odtString, dtFormatter); assertEquals(expectedOTD, odt1); }
@Before public void before() { actual = OffsetDateTime.now(); }