Java Code Examples for java.time.Instant#toEpochMilli()

The following examples show how to use java.time.Instant#toEpochMilli() . 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
Source Project: presto   File: CurrentTimestamp.java    License: Apache License 2.0 8 votes vote down vote up
@LiteralParameters("p")
@SqlType("timestamp(p) with time zone")
public static long shortTimestamp(
        @LiteralParameter("p") long precision,
        ConnectorSession session,
        @SqlNullable @SqlType("timestamp(p) with time zone") Long dummy) // need a dummy value since the type inferencer can't bind type arguments exclusively from return type
{
    Instant start = session.getStart();

    long epochMillis = start.toEpochMilli();

    if (precision < MAX_SHORT_PRECISION) {
        epochMillis = round(epochMillis, (int) (MAX_SHORT_PRECISION - precision));
    }
    else {
        long nanosOfMilli = start.getNano() % NANOSECONDS_PER_MILLISECOND;
        if (roundToNearest(nanosOfMilli, NANOSECONDS_PER_MILLISECOND) == NANOSECONDS_PER_MILLISECOND) {
            epochMillis++;
        }
    }

    return packDateTimeWithZone(epochMillis, session.getTimeZoneKey());
}
 
Example 2
Source Project: conductor   File: TestHttpTask.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHTTPGetConnectionTimeOut() throws Exception{
    Task task = new Task();
    Input input = new Input();
    Instant start  = Instant.now();
    input.setConnectionTimeOut(110);
    input.setMethod("GET");
    input.setUri("http://10.255.14.15");
    task.getInputData().put(HttpTask.REQUEST_PARAMETER_NAME, input);
    task.setStatus(Status.SCHEDULED);
    task.setScheduledTime(0);
    httpTask.start(workflow,task,workflowExecutor);
    Instant end  = Instant.now();
    long diff = end.toEpochMilli()-start.toEpochMilli();
    Assert.assertEquals(task.getStatus(),Status.FAILED);
    Assert.assertTrue(diff >= 110l);
}
 
Example 3
Source Project: immutables   File: JavaTimeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void instant() throws IOException {
  Instant now = Instant.now();
  long epoch = now.toEpochMilli();

  TypeAdapter<Instant> adapter = gson.getAdapter(Instant.class);

  // read
  Instant date = adapter.read(Jsons.readerAt(new BsonDateTime(epoch)));
  check(date).is(now);

  // write
  BsonValue bson = writeAndReadBson(now);
  check(bson.getBsonType()).is(BsonType.DATE_TIME);
  check(Instant.ofEpochMilli(bson.asDateTime().getValue())).is(now);
}
 
Example 4
@Override
public void removeMessages(Instant olderThan) {
    long epochMillis = olderThan.toEpochMilli();
    int toIndex = -1;

    for(int i = 0; i < messages.size(); i++) {
        FileMessage message = messages.get(i);

        if(message.getLastModified() < epochMillis || message.getTimestamp().getTime() < epochMillis) {
            toIndex++;
            continue;
        }

        break;
    }

    messages.subList(0, toIndex + 1).clear();
}
 
Example 5
public void test_instant() {
    Clock system = Clock.systemUTC();
    assertEquals(system.getZone(), ZoneOffset.UTC);
    for (int i = 0; i < 10000; i++) {
        // assume can eventually get these within 10 milliseconds
        Instant instant = system.instant();
        long systemMillis = System.currentTimeMillis();
        if (systemMillis - instant.toEpochMilli() < 10) {
            return;  // success
        }
    }
    fail();
}
 
Example 6
@Test
public void testConvert_utilDate() {
    Instant now = Instant.now();
    LocalDate localDate = now.atZone(ZoneId.systemDefault()).toLocalDate();
    Date date = new Date(now.toEpochMilli());
    assertEquals(localDate, CONVERTER.convert(date));
}
 
Example 7
public void test_instant() {
    Clock system = Clock.systemUTC();
    assertEquals(system.getZone(), ZoneOffset.UTC);
    for (int i = 0; i < 10000; i++) {
        // assume can eventually get these within 10 milliseconds
        Instant instant = system.instant();
        long systemMillis = System.currentTimeMillis();
        if (systemMillis - instant.toEpochMilli() < 10) {
            return;  // success
        }
    }
    fail();
}
 
Example 8
Source Project: cloudbreak   File: CooldownCheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testIsNotCool() {
    Stack stack = UserSyncTestUtils.createStack();
    UserSyncStatus userSyncStatus = UserSyncTestUtils.createUserSyncStatus(stack);
    Instant cooldownExpiration = Instant.now();
    long lastStartTime = cooldownExpiration.toEpochMilli() + 1L;
    Operation lastRequestedOperation = new Operation();
    lastRequestedOperation.setStartTime(lastStartTime);
    userSyncStatus.setLastStartedFullSync(lastRequestedOperation);

    assertFalse(underTest.isCooldownExpired(userSyncStatus, cooldownExpiration));
}
 
Example 9
Source Project: intellij   File: TargetIdeInfo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Updates this target's {@link #syncTimeMillis}. Returns this same {@link TargetIdeInfo} instance
 * if the sync time is unchanged.
 */
public TargetIdeInfo updateSyncTime(Instant syncTime) {
  long syncTimeMillis = syncTime.toEpochMilli();
  if (Objects.equals(syncTimeMillis, this.syncTimeMillis)) {
    return this;
  }
  return new TargetIdeInfo(
      key,
      kind,
      buildFile,
      dependencies,
      tags,
      sources,
      cIdeInfo,
      cToolchainIdeInfo,
      javaIdeInfo,
      androidIdeInfo,
      androidSdkIdeInfo,
      androidAarIdeInfo,
      androidInstrumentationInfo,
      pyIdeInfo,
      goIdeInfo,
      jsIdeInfo,
      tsIdeInfo,
      dartIdeInfo,
      testIdeInfo,
      javaToolchainIdeInfo,
      kotlinToolchainIdeInfo,
      syncTimeMillis);
}
 
Example 10
Source Project: kaif   File: AccountServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private AccountAuth createAccountAuth(Account account) {
  Instant now = Instant.now(clock);
  Instant expireTime = now.plus(ACCOUNT_TOKEN_EXPIRE);
  String accessToken = new AccountAccessToken(account.getAccountId(),
      account.getPasswordHash(),
      account.getAuthorities()).encode(expireTime, accountSecret);
  return new AccountAuth(account.getUsername(),
      accessToken,
      expireTime.toEpochMilli(),
      now.toEpochMilli());
}
 
Example 11
private static Long computeLastAffectingPenalty(
        Instant submissionTime,
        Optional<Instant> contestantStartTime,
        Instant contestBeginTime) {

    return submissionTime.toEpochMilli() - contestantStartTime.orElse(contestBeginTime).toEpochMilli();
}
 
Example 12
public static void main(String[] args) throws Throwable {

        int N = 10000;
        long t1970 = new java.util.Date(70, 0, 01).getTime();
        Random r = new Random();
        for (int i = 0; i < N; i++) {
            int days  = r.nextInt(50) * 365 + r.nextInt(365);
            long secs = t1970 + days * 86400 + r.nextInt(86400);
            int nanos = r.nextInt(NANOS_PER_SECOND);
            int nanos_ms = nanos / 1000000 * 1000000; // millis precision
            long millis = secs * 1000 + r.nextInt(1000);
            LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
            LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
            Instant inst = Instant.ofEpochSecond(secs, nanos);
            Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
            ///////////// java.util.Date /////////////////////////
            Date jud = new java.util.Date(millis);
            Instant inst0 = jud.toInstant();
            if (jud.getTime() != inst0.toEpochMilli() ||
                !jud.equals(Date.from(inst0))) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
            }
            // roundtrip only with millis precision
            Date jud0 = Date.from(inst_ms);
            if (jud0.getTime() != inst_ms.toEpochMilli() ||
                !inst_ms.equals(jud0.toInstant())) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
            }
            //////////// java.util.GregorianCalendar /////////////
            GregorianCalendar cal = new GregorianCalendar();
            // non-roundtrip of tz name between j.u.tz and j.t.zid
            cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
            cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            cal.setMinimalDaysInFirstWeek(4);
            cal.setTimeInMillis(millis);
            ZonedDateTime zdt0 = cal.toZonedDateTime();
            if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() ||
                !cal.equals(GregorianCalendar.from(zdt0))) {
                System.out.println("cal:" + cal);
                System.out.println("zdt:" + zdt0);
                System.out.println("calNew:" + GregorianCalendar.from(zdt0));
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
            }
            inst0 = cal.toInstant();
            if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: gcal -> zdt");
            }
            ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
            GregorianCalendar cal0 = GregorianCalendar.from(zdt);
            if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() ||
                !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
            }
        }

        ///////////// java.util.TimeZone /////////////////////////
        for (String zidStr : TimeZone.getAvailableIDs()) {
            // TBD: tzdt intergration
            if (zidStr.startsWith("SystemV") ||
                zidStr.contains("Riyadh8") ||
                zidStr.equals("US/Pacific-New") ||
                zidStr.equals("EST") ||
                zidStr.equals("HST") ||
                zidStr.equals("MST")) {
                continue;
            }
            ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
            if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
                throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
            }
            TimeZone tz = TimeZone.getTimeZone(zidStr);
            // no round-trip for alias and "GMT"
            if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) &&
                !ZoneId.SHORT_IDS.containsKey(zidStr) &&
                !zidStr.startsWith("GMT")) {
                throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
            }
        }
        System.out.println("Passed!");
    }
 
Example 13
public static void main(String[] args) throws Throwable {

        int N = 10000;
        long t1970 = new java.util.Date(70, 0, 01).getTime();
        Random r = new Random();
        for (int i = 0; i < N; i++) {
            int days  = r.nextInt(50) * 365 + r.nextInt(365);
            long secs = t1970 + days * 86400 + r.nextInt(86400);
            int nanos = r.nextInt(NANOS_PER_SECOND);
            int nanos_ms = nanos / 1000000 * 1000000; // millis precision
            long millis = secs * 1000 + r.nextInt(1000);
            LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
            LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
            Instant inst = Instant.ofEpochSecond(secs, nanos);
            Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
            ///////////// java.util.Date /////////////////////////
            Date jud = new java.util.Date(millis);
            Instant inst0 = jud.toInstant();
            if (jud.getTime() != inst0.toEpochMilli() ||
                !jud.equals(Date.from(inst0))) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
            }
            // roundtrip only with millis precision
            Date jud0 = Date.from(inst_ms);
            if (jud0.getTime() != inst_ms.toEpochMilli() ||
                !inst_ms.equals(jud0.toInstant())) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
            }
            //////////// java.util.GregorianCalendar /////////////
            GregorianCalendar cal = new GregorianCalendar();
            // non-roundtrip of tz name between j.u.tz and j.t.zid
            cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
            cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            cal.setMinimalDaysInFirstWeek(4);
            cal.setTimeInMillis(millis);
            ZonedDateTime zdt0 = cal.toZonedDateTime();
            if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() ||
                !cal.equals(GregorianCalendar.from(zdt0))) {
                System.out.println("cal:" + cal);
                System.out.println("zdt:" + zdt0);
                System.out.println("calNew:" + GregorianCalendar.from(zdt0));
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
            }
            inst0 = cal.toInstant();
            if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: gcal -> zdt");
            }
            ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
            GregorianCalendar cal0 = GregorianCalendar.from(zdt);
            if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() ||
                !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
            }
        }

        ///////////// java.util.TimeZone /////////////////////////
        for (String zidStr : TimeZone.getAvailableIDs()) {
            // TBD: tzdt intergration
            if (zidStr.startsWith("SystemV") ||
                zidStr.contains("Riyadh8") ||
                zidStr.equals("US/Pacific-New") ||
                zidStr.equals("EST") ||
                zidStr.equals("HST") ||
                zidStr.equals("MST")) {
                continue;
            }
            ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
            if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
                throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
            }
            TimeZone tz = TimeZone.getTimeZone(zidStr);
            // no round-trip for alias and "GMT"
            if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) &&
                !ZoneId.SHORT_IDS.containsKey(zidStr) &&
                !zidStr.startsWith("GMT")) {
                throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
            }
        }
        System.out.println("Passed!");
    }
 
Example 14
Source Project: morpheus-core   File: LongCoding.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public final long getCode(Instant value) {
    return value == null ? Long.MIN_VALUE : value.toEpochMilli();
}
 
Example 15
public static void main(String[] args) throws Throwable {
    int N = 10000;
    long t1970 = new java.util.Date(70, 0, 01).getTime();
    Random r = new Random();
    for (int i = 0; i < N; i++) {
        int days  = r.nextInt(50) * 365 + r.nextInt(365);
        long secs = t1970 + days * 86400 + r.nextInt(86400);
        int nanos = r.nextInt(NANOS_PER_SECOND);
        int nanos_ms = nanos / 1000000 * 1000000; // millis precision
        long millis = secs * 1000 + r.nextInt(1000);

        LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
        LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
        Instant inst = Instant.ofEpochSecond(secs, nanos);
        Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
        //System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);

        /////////// Timestamp ////////////////////////////////
        Timestamp ta = new Timestamp(millis);
        ta.setNanos(nanos);
        if (!isEqual(ta.toLocalDateTime(), ta)) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(ta.toLocalDateTime(), ta);
            throw new RuntimeException("FAILED: j.s.ts -> ldt");
        }
        if (!isEqual(ldt, Timestamp.valueOf(ldt))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(ldt, Timestamp.valueOf(ldt));
            throw new RuntimeException("FAILED: ldt -> j.s.ts");
        }
        Instant inst0 = ta.toInstant();
        if (ta.getTime() != inst0.toEpochMilli() ||
            ta.getNanos() != inst0.getNano() ||
            !ta.equals(Timestamp.from(inst0))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            throw new RuntimeException("FAILED: j.s.ts -> instant -> j.s.ts");
        }
        inst = Instant.ofEpochSecond(secs, nanos);
        Timestamp ta0 = Timestamp.from(inst);
        if (ta0.getTime() != inst.toEpochMilli() ||
            ta0.getNanos() != inst.getNano() ||
            !inst.equals(ta0.toInstant())) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            throw new RuntimeException("FAILED: instant -> timestamp -> instant");
        }

        ////////// java.sql.Date /////////////////////////////
        // j.s.d/t uses j.u.d.equals() !!!!!!!!
        java.sql.Date jsd = new java.sql.Date(millis);
        if (!isEqual(jsd.toLocalDate(), jsd)) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(jsd.toLocalDate(), jsd);
            throw new RuntimeException("FAILED: j.s.d -> ld");
        }
        LocalDate ld = ldt.toLocalDate();
        if (!isEqual(ld, java.sql.Date.valueOf(ld))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(ld, java.sql.Date.valueOf(ld));
            throw new RuntimeException("FAILED: ld -> j.s.d");
        }
        ////////// java.sql.Time /////////////////////////////
        java.sql.Time jst = new java.sql.Time(millis);
        if (!isEqual(jst.toLocalTime(), jst)) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(jst.toLocalTime(), jst);
            throw new RuntimeException("FAILED: j.s.t -> lt");
        }
        // millis precision
        LocalTime lt = ldt_ms.toLocalTime();
        if (!isEqual(lt, java.sql.Time.valueOf(lt))) {
            System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
            print(lt, java.sql.Time.valueOf(lt));
            throw new RuntimeException("FAILED: lt -> j.s.t");
        }
    }
    System.out.println("Passed!");
}
 
Example 16
public static void main(String[] args) throws Throwable {

        int N = 10000;
        long t1970 = new java.util.Date(70, 0, 01).getTime();
        Random r = new Random();
        for (int i = 0; i < N; i++) {
            int days  = r.nextInt(50) * 365 + r.nextInt(365);
            long secs = t1970 + days * 86400 + r.nextInt(86400);
            int nanos = r.nextInt(NANOS_PER_SECOND);
            int nanos_ms = nanos / 1000000 * 1000000; // millis precision
            long millis = secs * 1000 + r.nextInt(1000);
            LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
            LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
            Instant inst = Instant.ofEpochSecond(secs, nanos);
            Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
            ///////////// java.util.Date /////////////////////////
            Date jud = new java.util.Date(millis);
            Instant inst0 = jud.toInstant();
            if (jud.getTime() != inst0.toEpochMilli() ||
                !jud.equals(Date.from(inst0))) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
            }
            // roundtrip only with millis precision
            Date jud0 = Date.from(inst_ms);
            if (jud0.getTime() != inst_ms.toEpochMilli() ||
                !inst_ms.equals(jud0.toInstant())) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
            }
            //////////// java.util.GregorianCalendar /////////////
            GregorianCalendar cal = new GregorianCalendar();
            // non-roundtrip of tz name between j.u.tz and j.t.zid
            cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
            cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            cal.setMinimalDaysInFirstWeek(4);
            cal.setTimeInMillis(millis);
            ZonedDateTime zdt0 = cal.toZonedDateTime();
            if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() ||
                !cal.equals(GregorianCalendar.from(zdt0))) {
                System.out.println("cal:" + cal);
                System.out.println("zdt:" + zdt0);
                System.out.println("calNew:" + GregorianCalendar.from(zdt0));
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
            }
            inst0 = cal.toInstant();
            if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: gcal -> zdt");
            }
            ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
            GregorianCalendar cal0 = GregorianCalendar.from(zdt);
            if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() ||
                !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
                System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
                throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
            }
        }

        ///////////// java.util.TimeZone /////////////////////////
        for (String zidStr : TimeZone.getAvailableIDs()) {
            // TBD: tzdt intergration
            if (zidStr.startsWith("SystemV") ||
                zidStr.contains("Riyadh8") ||
                zidStr.equals("US/Pacific-New") ||
                zidStr.equals("EST") ||
                zidStr.equals("HST") ||
                zidStr.equals("MST")) {
                continue;
            }
            ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
            if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
                throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
            }
            TimeZone tz = TimeZone.getTimeZone(zidStr);
            // no round-trip for alias and "GMT"
            if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) &&
                !ZoneId.SHORT_IDS.containsKey(zidStr) &&
                !zidStr.startsWith("GMT")) {
                throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
            }
        }
        System.out.println("Passed!");
    }
 
Example 17
private static void testMatching(XMLFormatter formatter,
        LogRecord record,  Instant instant, long expectedNanos,
        boolean useInstant) {

    ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
    int zdtNanos = zdt.getNano();
    assertEquals(expectedNanos, zdtNanos, "ZonedDateTime.getNano()");

    String str = formatter.format(record);

    String match = "."+expectedNanos;
    if (str.contains(match) != useInstant) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string does not contain expected nanos: "
                + "\n\texpected match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    System.out.println("Found expected match for '"+match+"' in \n"+str);

    match = "<millis>"+instant.toEpochMilli()+"</millis>";
    if (!str.contains(match)) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string does not contain expected millis: "
                + "\n\texpected match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    System.out.println("Found expected match for '"+match+"' in \n"+str);

    match = "<nanos>";
    if (str.contains(match) != useInstant) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string "
                + (useInstant
                        ? "does not contain expected nanos: "
                        : "contains unexpected nanos: ")
                + "\n\t" + (useInstant ? "expected" : "unexpected")
                + " match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    match = "<nanos>"+getNanoAdjustment(record)+"</nanos>";
    if (str.contains(match) != useInstant) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string "
                + (useInstant
                        ? "does not contain expected nanos: "
                        : "contains unexpected nanos: ")
                + "\n\t" + (useInstant ? "expected" : "unexpected")
                + " match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    if (useInstant) {
        System.out.println("Found expected match for '"+match+"' in \n"+str);
    } else {
        System.out.println("As expected '"+match+"' is not present in \n"+str);
    }

    match = useInstant ? DateTimeFormatter.ISO_INSTANT.format(instant)
            : zdt.truncatedTo(ChronoUnit.SECONDS)
                    .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    match = "<date>"+match+"</date>";
    if (!str.contains(match)) {
        throw new RuntimeException(formatter.getClass().getSimpleName()
                + ".format()"
                + " string does not contain expected date: "
                + "\n\texpected match for: '" + match + "'"
                + "\n\tin: \n" + str);
    }
    System.out.println("Found expected match for '"+match+"' in \n"+str);

}
 
Example 18
Source Project: bucket4j   File: Refill.java    License: Apache License 2.0 3 votes vote down vote up
/**
    * Creates the {@link Refill} that does refill of tokens in intervally manner.
    * "Intervally" in opposite to "greedy"  will wait until whole {@code period} will be elapsed before regenerate {@code tokens}.
    * <br>
    * In additional to {@link #intervally(long, Duration)} it is possible to specify the time when first refill should happen via {@code timeOfFirstRefill}.
    * This option can be used to configure clear interval boundary i.e. start of second, minute, hour, day.
    *
    * <p>
*     <strong>Special notes about useAdaptiveInitialTokens:</strong>
    * <br>If {@code useAdaptiveInitialTokens == true} and timeOfFirstRefill is a moment in the future, then initial amount of tokens in the bandwidth will be calculated by following formula:
    * <br><pre>{@code
    *     Math.min(capacity, Math.max(0, bandwidthCapacity - refillTokens) + (timeOfFirstRefillMillis - nowMillis)/refillPeriod * refillTokens)
    * }</pre>
    * <br>Bellow the list of examples of how does this formula can be applied:
    * <pre>
    * {@code
    *         // imagine that wall clock is 16:20, the first refill will happen at 17:00
    *         // first refill will happen in the beginning of next hour
    *         Instant firstRefillTime = ZonedDateTime.now()
    *                 .truncatedTo(ChronoUnit.HOURS)
    *                 .plus(1, ChronoUnit.HOURS)
    *                 .toInstant();
    *
    *        // initial tokens 266 will be
    *        Bandwidth.classic(400, Refill.intervallyAligned(400, Duration.ofHours(1), firstRefillTime, true));
    *        // calculated by formula min(400, max(0, 400 - 400) +  40/60*400) = min(400, 0 + 266) = 266
    *
    *        // initial tokens will be 300
    *        Bandwidth.classic(400, Refill.intervallyAligned(300, Duration.ofHours(1), firstRefillTime, true));
    *        // calculated by formula min(400, max(0, 400 - 300) +  40/60*300) = min(400, 100 + 200) = 300
    *
    *        // initial tokens will be 333
    *        Bandwidth.classic(400, Refill.intervallyAligned(200, Duration.ofHours(1), firstRefillTime, true));
    *        // calculated by formula min(400, max(0, 400 - 200) +  40/60*200) = min(400, 200 + 133) = 333
    *
    *        // initial tokens will be 366
    *        Bandwidth.classic(400, Refill.intervallyAligned(100, Duration.ofHours(1), firstRefillTime, true));
    *        // calculated by formula min(400, max(0, 400 - 100) +  40/60*100) = min(400, 300 + 66) = 366
    * }</pre>
    *
    *
    *     <strong>Restrictions:</strong>
    *     <ul>
    *         <li>
    *             If {@code useAdaptiveInitialTokens} is {@code true} then any attempt to explicitly specify initial amount of tokens via {@link Bandwidth#withInitialTokens(long)}
    *             will fail with exception, because it is impossible at the same time to specify tokens in explicitly and adaptively manners.
    *         </li>
    *         <li>
    *             It is impossible to use this method together with nanoTime based clock {@link LocalBucketBuilder#withNanosecondPrecision()}, because we need in {@link System#currentTimeMillis()} based clock
    *             in order to properly measure the distance from {@code timeOfFirstRefill}
    *         </li>
    *     </ul>
    *
    *
    * @param tokens amount of tokens
    * @param period the period within {@code tokens} will be fully regenerated
    * @param timeOfFirstRefill the time of first refill, typically it should be a moment in the future
    * @param useAdaptiveInitialTokens if {@code true} then initialTokens may be reduced
    *
    * @return the {@link Refill} that does refill of tokens in intervally manner
    */
   public static Refill intervallyAligned(long tokens, Duration period, Instant timeOfFirstRefill, boolean useAdaptiveInitialTokens) {
       long timeOfFirstRefillMillis = timeOfFirstRefill.toEpochMilli();
       if (timeOfFirstRefillMillis < 0) {
           throw BucketExceptions.nonPositiveTimeOfFirstRefill(timeOfFirstRefill);
       }
       return new Refill(tokens, period, true, timeOfFirstRefillMillis, useAdaptiveInitialTokens);
   }
 
Example 19
Source Project: jdk8u-jdk   File: Date.java    License: GNU General Public License v2.0 3 votes vote down vote up
/**
 * Obtains an instance of {@code Date} from an {@code Instant} object.
 * <p>
 * {@code Instant} uses a precision of nanoseconds, whereas {@code Date}
 * uses a precision of milliseconds.  The conversion will trancate any
 * excess precision information as though the amount in nanoseconds was
 * subject to integer division by one million.
 * <p>
 * {@code Instant} can store points on the time-line further in the future
 * and further in the past than {@code Date}. In this scenario, this method
 * will throw an exception.
 *
 * @param instant  the instant to convert
 * @return a {@code Date} representing the same point on the time-line as
 *  the provided instant
 * @exception NullPointerException if {@code instant} is null.
 * @exception IllegalArgumentException if the instant is too large to
 *  represent as a {@code Date}
 * @since 1.8
 */
public static Date from(Instant instant) {
    try {
        return new Date(instant.toEpochMilli());
    } catch (ArithmeticException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
Example 20
/**
 * Sets the instant that the event occurred.
 * <p>
 * If the given {@code instant} represents a point on the time-line too
 * far in the future or past to fit in a {@code long} milliseconds and
 * nanoseconds adjustment, then an {@code ArithmeticException} will be
 * thrown.
 *
 * @param instant the instant that the event occurred.
 *
 * @throws NullPointerException if {@code instant} is null.
 * @throws ArithmeticException if numeric overflow would occur while
 *         calling {@link Instant#toEpochMilli() instant.toEpochMilli()}.
 *
 * @since 9
 */
public void setInstant(Instant instant) {
    instant.toEpochMilli();
    this.instant = instant;
}