Java Code Examples for java.time.LocalDateTime#ofInstant()

The following examples show how to use java.time.LocalDateTime#ofInstant() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void testStormWorkerLogEntry() throws Exception {
  String logEntry = "2018-05-04 05:10:00.120 o.a.s.d.executor main [INFO] Loaded executor tasks count:[5 5]";
  Map<String, Object> result = testLogEntry(logEntry, "storm_worker", inputConfigTemplate(
          new File(HDP_SERVICES_FOLDER, "STORM/package/templates/input.config-storm.json.j2")));

  assertThat(result.isEmpty(), is(false));
  assertThat(result.get("cluster"), is(CLUSTER));
  assertThat(result.get("level"), is("INFO"));
  assertThat(result.get("event_count"), is(1));
  assertThat(result.get("type"), is("storm_worker"));
  assertThat(result.containsKey("seq_num"), is(true));
  assertThat(result.containsKey("id"), is(true));
  assertThat(result.containsKey("message_md5"), is(true));
  assertThat(result.containsKey("event_md5"), is(true));
  assertThat(result.containsKey("ip"), is(true));
  assertThat(result.containsKey("host"), is(true));
  assertThat(result.get("log_message"), is("Loaded executor tasks count:[5 5]"));
  Date logTime = (Date) result.get("logtime");
  LocalDateTime localDateTime = LocalDateTime.ofInstant(logTime.toInstant(), ZoneId.systemDefault());
  MatcherAssert.assertThat(localDateTime, is(LocalDateTime.of(2018, 5, 4, 5, 10, 0, 120000000)));
}
 
Example 2
Source Project: yes-cart   File: AlertDirectorImpl.java    License: Apache License 2.0 6 votes vote down vote up
List<Pair<String, String>> getAll() {
    final net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) getAlertsStorage().getNativeCache();
    final Map<Object, Element> elems = nativeCache.getAll(nativeCache.getKeys());
    final List<Pair<String, String>> all = new ArrayList<>(100);
    for (final Map.Entry<Object, Element> elem : elems.entrySet()) {
        if (elem.getValue() != null && !elem.getValue().isExpired()) {
            final LocalDateTime last = LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(elem.getValue().getLatestOfCreationAndUpdateTime()),
                    DateUtils.zone()
            );
            final Pair<String, String> elemOriginal = (Pair<String, String>) elem.getValue().getObjectValue();
            final Pair<String, String> elemWithLastTime = new Pair<>(
                    DateUtils.formatSDT(last) + ": " + elemOriginal.getFirst(),
                    elemOriginal.getSecond()
            );
            all.add(elemWithLastTime);
        }
    }
    return all;
}
 
Example 3
Source Project: crate   File: TimestampType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
byte[] encodeAsUTF8Text(@Nonnull Object value) {
    long millis = (long) value;
    LocalDateTime ts =
        LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneOffset.UTC);
    if (millis >= FIRST_MSEC_AFTER_CHRIST) {
        return ts.format(ISO_FORMATTER).getBytes(StandardCharsets.UTF_8);
    } else {
        return ts.format(ISO_FORMATTER_WITH_ERA).getBytes(StandardCharsets.UTF_8);
    }
}
 
Example 4
Source Project: commons-rng   File: StressTestCommand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates the string builder for the progress message with a timestamp prefix.
 *
 * <pre>
 * [HH:mm:ss] Pending [pending]. Running [running]. Completed [completed]
 * </pre>
 *
 * @param current Current time (in milliseconds)
 * @param pending Pending tasks.
 * @param running Running tasks.
 * @param completed Completed tasks.
 * @return the string builder
 */
private static StringBuilder createStringBuilderWithTimestamp(long current,
    int pending, int running, int completed) {
    final StringBuilder sb = new StringBuilder(80);
    // Use local time to adjust for timezone
    final LocalDateTime time = LocalDateTime.ofInstant(
        Instant.ofEpochMilli(current), ZoneId.systemDefault());
    sb.append('[');
    append00(sb, time.getHour()).append(':');
    append00(sb, time.getMinute()).append(':');
    append00(sb, time.getSecond());
    return sb.append("] Pending ").append(pending)
             .append(". Running ").append(running)
             .append(". Completed ").append(completed);
}
 
Example 5
private Date getOlderDateFromEvent(CloudEvent lastEvent) {
    ZoneId systemDefaultZone = ZoneId.systemDefault();
    Instant lastEventInstant = lastEvent.getTimestamp()
                                        .toInstant();
    LocalDateTime lastEventDateTime = LocalDateTime.ofInstant(lastEventInstant, systemDefaultZone);
    LocalDateTime secondBefore = lastEventDateTime.minusSeconds(1);
    Instant secondBeforeInstant = secondBefore.atZone(systemDefaultZone)
                                              .toInstant();
    return Date.from(secondBeforeInstant);
}
 
Example 6
Source Project: dew   File: LocalDateTimeConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public LocalDateTime convert(String str) {
    if (StringUtils.isEmpty(str)) {
        return null;
    }
    if (str.matches("[1-9][0-9]+")) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.valueOf(str)), ZoneId.systemDefault());
    }
    return LocalDateTime.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
 
Example 7
@Test
public void shouldProperlyAddCookieWithNameValuePathAndExpiry() {
    Instant now = Instant.now();
    Cookie cookie = new Cookie("chocolate", "chip", "/home/", LocalDateTime.ofInstant(now,
            ZoneId.systemDefault()));
    org.openqa.selenium.Cookie seleniumCookie = new org.openqa.selenium.Cookie("chocolate",
            "chip", "/home/", Date.from(Instant.now()));

    cookieManager.add(cookie);

    verify(mockOptions)
            .addCookie(seleniumCookie);
}
 
Example 8
private static void testDumpBeginEndLocalDateTime() throws IOException {
    LocalDateTime centerLeftLocal = LocalDateTime.ofInstant(centerLeft, ZoneOffset.systemDefault());
    LocalDateTime centerRightLocal = LocalDateTime.ofInstant(centerRight, ZoneOffset.systemDefault());
    Path testBeginEnd = Paths.get("testBeginEndLocalDateTime.jfr");
    JcmdHelper.jcmd("JFR.dump", "filename=" + testBeginEnd.toFile().getAbsolutePath(), "begin=" + centerLeftLocal, "end=" + centerRightLocal);
    Asserts.assertEquals(centerSize, Files.size(testBeginEnd), "Expected dump with begin=" + centerLeftLocal + " end=" + centerRightLocal + " contain data from the 'center'-recordings");
    Files.delete(testBeginEnd);
}
 
Example 9
Source Project: eda-tutorial   File: Transaction.java    License: Apache License 2.0 5 votes vote down vote up
public static Transaction of(JSONObject jsonObject) {
    checkNotNull(jsonObject);
    return new Transaction(
            jsonObject.getLong("id"),
            AccountNumber.of(jsonObject.getInt("account_number")),
            LocalDateTime.ofInstant(Instant.ofEpochMilli(jsonObject.getLong("time")), ZoneId.systemDefault()),
            Operation.fromString(jsonObject.getString("operation")),
            new BigDecimal(jsonObject.getString("amount"))
    );
}
 
Example 10
/**
 * Test that verifies we can decode an 'Instant' represented as floating point number, in epoch
 * seconds.
 */
@Test
void decoder() {
  final InstantExample event = JsonDecoder.decoder().fromJson(JSON_STRING, InstantExample.class);

  assertThat(event.instant, notNullValue());

  final LocalDateTime dateTime = LocalDateTime.ofInstant(event.instant, ZoneOffset.UTC);
  assertThat(dateTime.getMonth(), is(Month.JUNE));
  assertThat(dateTime.getDayOfMonth(), is(6));
  assertThat(dateTime.getYear(), is(2019));
  assertThat(dateTime.getHour(), is(4));
  assertThat(dateTime.getMinute(), is(20));
}
 
Example 11
@Override
public void setKey(GraphReadMethods graph, int attribute, int element) {
    bin.setKey(graph, attribute, element);
    key = bin.getKeyAsObject() == null ? null : LocalDateTime.ofInstant(((ZonedDateTime) bin.getKeyAsObject()).toInstant(), TimeZoneUtilities.UTC);
}
 
Example 12
Source Project: dremio-oss   File: ConstExecutor.java    License: Apache License 2.0 4 votes vote down vote up
private static TimestampString toTimestampString(long epoch) {
  LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(epoch), ZoneOffset.UTC);

  return new TimestampString(localDateTime.format(DateTimes.CALCITE_LOCAL_DATETIME_FORMATTER));
}
 
Example 13
@Test(expectedExceptions=NullPointerException.class)
public void factory_ofInstant_nullInstant() {
    LocalDateTime.ofInstant((Instant) null, ZONE_GAZA);
}
 
Example 14
@Test(expectedExceptions=DateTimeException.class)
public void factory_ofInstant_instantTooBig() {
    LocalDateTime.ofInstant(Instant.MAX, OFFSET_PONE) ;
}
 
Example 15
protected LocalDateTime getLocalDateTime(Date date){
	return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
 
Example 16
Source Project: gantt   File: GanttTimeUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static LocalDateTime getStartLocalDateTime(AbstractStep step) {
    return (step.getStartDate() > -1)
            ? LocalDateTime.ofInstant(Instant.ofEpochMilli(step.getStartDate()), ZoneId.systemDefault()) : null;
}
 
Example 17
@Test(dataProvider="instantFactory")
public void factory_ofInstant(Instant instant, ZoneId zone, LocalDateTime expected) {
    LocalDateTime test = LocalDateTime.ofInstant(instant, zone);
    assertEquals(test, expected);
}
 
Example 18
@Test(expectedExceptions=NullPointerException.class)
public void factory_ofInstant_nullInstant() {
    LocalDateTime.ofInstant((Instant) null, ZONE_GAZA);
}
 
Example 19
Source Project: gantt   File: Gantt.java    License: Apache License 2.0 4 votes vote down vote up
public LocalDateTime getEndLocalDateTime() {
    return (endDate != null) ? LocalDateTime.ofInstant(endDate.toInstant(), getTimeZone().toZoneId()) : null;
}
 
Example 20
Source Project: game-server   File: TimeUtil.java    License: MIT License 2 votes vote down vote up
/**@
 * 获取时间字符串
 * @param formatter
 * @return
 */
public static String getDateTimeFormat(DateTimeFormatter formatter) {
    LocalDateTime ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(currentTimeMillis()), ZoneId.systemDefault());
    return ldt.format(formatter);
}