Example usage for java.time.temporal ChronoUnit MILLIS

List of usage examples for java.time.temporal ChronoUnit MILLIS

Introduction

In this page you can find the example usage for java.time.temporal ChronoUnit MILLIS.

Prototype

ChronoUnit MILLIS

To view the source code for java.time.temporal ChronoUnit MILLIS.

Click Source Link

Document

Unit that represents the concept of a millisecond.

Usage

From source file:msi.gama.util.GamaDate.java

public GamaDate plus(final IScope scope, final IExpression period) {
    // This is where #month and the others will be reduced
    // The period evaluation should return a Period and a Duration that will
    // be applied to the date. i.e.
    // Amount a = new Amount();
    // period.evaluateAsTemporalExpression(scope, a);
    // return this.plus(a.d).plus(a.p);
    final long p = (long) (Cast.asFloat(scope, period.value(scope)) * 1000);
    if (p == 0) {
        return this;
    }//from   www . j  a  v a2  s.c  o  m
    return plus(p, ChronoUnit.MILLIS);
}

From source file:net.resheim.eclipse.timekeeper.ui.Activator.java

private void installTaxameter() {

    switch (Platform.getOS()) {
    case Platform.OS_MACOSX:
        detector = new MacIdleTimeDetector();
        break;/* ww  w .  java2 s  . co m*/
    case Platform.OS_LINUX:
        detector = new X11IdleTimeDetector();
        break;
    case Platform.OS_WIN32:
        detector = new WindowsIdleTimeDetector();
        break;
    default:
        detector = new GenericIdleTimeDetector();
        break;
    }

    Timer timer = new Timer("Timekeeper", true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (!PlatformUI.getWorkbench().isClosing()) {
                long idleTimeMillis = detector.getIdleTimeMillis();
                ITask task = TasksUi.getTaskActivityManager().getActiveTask();
                if (null != task) {
                    if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
                        // Was idle on last check, reactivate
                        Display.getDefault().syncExec(() -> handleReactivation(idleTimeMillis));
                    } else if (lastIdleTime < IDLE_INTERVAL) {
                        String tickString = Activator.getValue(task, Activator.TICK);
                        LocalDateTime now = LocalDateTime.now();
                        LocalDateTime ticked = LocalDateTime.parse(tickString);
                        // Currently not idle so accumulate spent time
                        accumulateTime(task, now.toLocalDate().toString(),
                                ticked.until(now, ChronoUnit.MILLIS));
                        Activator.setValue(task, Activator.TICK, now.toString());
                    }
                }
                lastIdleTime = idleTimeMillis;
            }
        }
    }, SHORT_INTERVAL, SHORT_INTERVAL);

    // Immediately run the idle handler if the system has been idle and
    // the user has pressed a key or mouse button _inside_ the running
    // application.
    reactivationListener = new Listener() {
        public void handleEvent(Event event) {
            long idleTimeMillis = detector.getIdleTimeMillis();
            if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
                handleReactivation(idleTimeMillis);
            }
            lastIdleTime = idleTimeMillis;
        }
    };
    final Display display = PlatformUI.getWorkbench().getDisplay();
    display.addFilter(SWT.KeyUp, reactivationListener);
    display.addFilter(SWT.MouseUp, reactivationListener);
}

From source file:msi.gama.util.GamaDate.java

public double getDuration(final IScope scope, final TimeUnitConstantExpression exp, final Double number) {
    final String name = exp.getName();
    // final boolean isTimeDependent = !exp.isConst();
    final boolean month = name.startsWith("m");
    final GamaDate next = this.plus(number, month ? ChronoUnit.MONTHS : ChronoUnit.YEARS);
    final double result = this.until(next, ChronoUnit.MILLIS) / 1000d;
    // DEBUG.LOG("Computation of " + number + " " + exp.getName() + " = " + result + "s or "
    // + this.until(next, ChronoUnit.DAYS) + " days");

    return result;
}

From source file:org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration.java

@Override
public <O> O get(String key, Class<O> datatype) {
    if (!config.containsKey(key))
        return null;

    if (datatype.isArray()) {
        Preconditions.checkArgument(datatype.getComponentType() == String.class,
                "Only string arrays are supported: %s", datatype);
        return (O) config.getStringArray(key);
    } else if (Number.class.isAssignableFrom(datatype)) {
        // A properties file configuration returns Strings even for numeric
        // values small enough to fit inside Integer (e.g. 5000). In-memory
        // configuration impls seem to be able to store and return actual
        // numeric types rather than String
        ///*from   www  .  j a  va2s  . co m*/
        // We try to handle either case here
        Object o = config.getProperty(key);
        if (datatype.isInstance(o)) {
            return (O) o;
        } else {
            return constructFromStringArgument(datatype, o.toString());
        }
    } else if (datatype == String.class) {
        return (O) config.getString(key);
    } else if (datatype == Boolean.class) {
        return (O) new Boolean(config.getBoolean(key));
    } else if (datatype.isEnum()) {
        Enum[] constants = (Enum[]) datatype.getEnumConstants();
        Preconditions.checkState(null != constants && 0 < constants.length, "Zero-length or undefined enum");

        String estr = config.getProperty(key).toString();
        for (Enum ec : constants)
            if (ec.toString().equals(estr))
                return (O) ec;
        throw new IllegalArgumentException("No match for string \"" + estr + "\" in enum " + datatype);
    } else if (datatype == Object.class) {
        return (O) config.getProperty(key);
    } else if (Duration.class.isAssignableFrom(datatype)) {
        // This is a conceptual leak; the config layer should ideally only handle standard library types
        Object o = config.getProperty(key);
        if (Duration.class.isInstance(o)) {
            return (O) o;
        } else {
            String[] comps = o.toString().split("\\s");
            TemporalUnit unit = null;
            if (comps.length == 1) {
                //By default, times are in milli seconds
                unit = ChronoUnit.MILLIS;
            } else if (comps.length == 2) {
                unit = Durations.parse(comps[1]);
            } else {
                throw new IllegalArgumentException("Cannot parse time duration from: " + o.toString());
            }
            return (O) Duration.of(Long.valueOf(comps[0]), unit);
        }
        // Lists are deliberately not supported.  List's generic parameter
        // is subject to erasure and can't be checked at runtime.  Someone
        // could create a ConfigOption<List<Number>>; we would instead return
        // a List<String> like we always do at runtime, and it wouldn't break
        // until the client tried to use the contents of the list.
        //
        // We could theoretically get around this by adding a type token to
        // every declaration of a List-typed ConfigOption, but it's just
        // not worth doing since we only actually use String[] anyway.
        //        } else if (List.class.isAssignableFrom(datatype)) {
        //            return (O) config.getProperty(key);
    } else
        throw new IllegalArgumentException("Unsupported data type: " + datatype);
}

From source file:org.janusgraph.diskstorage.configuration.CommonConfigTest.java

@Test
public void testDateParsing() {
    BaseConfiguration base = new BaseConfiguration();
    CommonsConfiguration config = new CommonsConfiguration(base);

    for (ChronoUnit unit : Arrays.asList(ChronoUnit.NANOS, ChronoUnit.MICROS, ChronoUnit.MILLIS,
            ChronoUnit.SECONDS, ChronoUnit.MINUTES, ChronoUnit.HOURS, ChronoUnit.DAYS)) {
        base.setProperty("test", "100 " + unit.toString());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(unit)), d.toNanos());
    }//  ww w  .j  av  a2  s  . co m

    Map<ChronoUnit, String> mapping = ImmutableMap.of(ChronoUnit.MICROS, "us", ChronoUnit.DAYS, "d");
    for (Map.Entry<ChronoUnit, String> entry : mapping.entrySet()) {
        base.setProperty("test", "100 " + entry.getValue());
        Duration d = config.get("test", Duration.class);
        assertEquals(TimeUnit.NANOSECONDS.convert(100, Temporals.timeUnit(entry.getKey())), d.toNanos());
    }

}

From source file:org.janusgraph.graphdb.berkeleyje.BerkeleyGraphTest.java

@Test
public void testIDBlockAllocationTimeout() {
    config.set("ids.authority.wait-time", Duration.of(0L, ChronoUnit.NANOS));
    config.set("ids.renew-timeout", Duration.of(1L, ChronoUnit.MILLIS));
    close();//from  w ww .  java  2  s . c  o  m
    JanusGraphCleanup.clear(graph);
    open(config);
    try {
        graph.addVertex();
        fail();
    } catch (JanusGraphException e) {

    }

    assertTrue(graph.isOpen());

    close(); // must be able to close cleanly

    // Must be able to reopen
    open(config);

    assertEquals(0L, (long) graph.traversal().V().count().next());
}

From source file:org.lanternpowered.server.world.pregen.LanternChunkPreGenerateTask.java

@Override
public Duration getTotalTime() {
    return Duration.of(
            (isCancelled() ? this.generationEndTime : System.currentTimeMillis()) - this.generationStartTime,
            ChronoUnit.MILLIS);
}

From source file:org.openhab.binding.amazonechocontrol.internal.handler.EchoHandler.java

public void updateNotifications(ZonedDateTime currentTime, ZonedDateTime now,
        @Nullable JsonCommandPayloadPushNotificationChange pushPayload,
        JsonNotificationResponse[] notifications) {
    Device device = this.device;
    if (device == null) {
        return;//from   w  w  w  .  j a  v a  2 s.  co m
    }

    ZonedDateTime nextReminder = null;
    ZonedDateTime nextAlarm = null;
    ZonedDateTime nextMusicAlarm = null;
    ZonedDateTime nextTimer = null;
    for (JsonNotificationResponse notification : notifications) {
        if (StringUtils.equals(notification.deviceSerialNumber, device.serialNumber)) {
            // notification for this device
            if (StringUtils.equals(notification.status, "ON")) {
                if ("Reminder".equals(notification.type)) {
                    String offset = ZoneId.systemDefault().getRules().getOffset(Instant.now()).toString();
                    ZonedDateTime alarmTime = ZonedDateTime
                            .parse(notification.originalDate + "T" + notification.originalTime + offset);
                    if (StringUtils.isNotBlank(notification.recurringPattern) && alarmTime.isBefore(now)) {
                        continue; // Ignore recurring entry if alarm time is before now
                    }
                    if (nextReminder == null || alarmTime.isBefore(nextReminder)) {
                        nextReminder = alarmTime;
                    }
                } else if ("Timer".equals(notification.type)) {
                    // use remaining time
                    ZonedDateTime alarmTime = currentTime.plus(notification.remainingTime, ChronoUnit.MILLIS);
                    if (nextTimer == null || alarmTime.isBefore(nextTimer)) {
                        nextTimer = alarmTime;
                    }
                } else if ("Alarm".equals(notification.type)) {
                    String offset = ZoneId.systemDefault().getRules().getOffset(Instant.now()).toString();
                    ZonedDateTime alarmTime = ZonedDateTime
                            .parse(notification.originalDate + "T" + notification.originalTime + offset);
                    if (StringUtils.isNotBlank(notification.recurringPattern) && alarmTime.isBefore(now)) {
                        continue; // Ignore recurring entry if alarm time is before now
                    }
                    if (nextAlarm == null || alarmTime.isBefore(nextAlarm)) {
                        nextAlarm = alarmTime;
                    }
                } else if ("MusicAlarm".equals(notification.type)) {
                    String offset = ZoneId.systemDefault().getRules().getOffset(Instant.now()).toString();
                    ZonedDateTime alarmTime = ZonedDateTime
                            .parse(notification.originalDate + "T" + notification.originalTime + offset);
                    if (StringUtils.isNotBlank(notification.recurringPattern) && alarmTime.isBefore(now)) {
                        continue; // Ignore recurring entry if alarm time is before now
                    }
                    if (nextMusicAlarm == null || alarmTime.isBefore(nextMusicAlarm)) {
                        nextMusicAlarm = alarmTime;
                    }
                }
            }
        }
    }

    updateState(CHANNEL_NEXT_REMINDER, nextReminder == null ? UnDefType.UNDEF : new DateTimeType(nextReminder));
    updateState(CHANNEL_NEXT_ALARM, nextAlarm == null ? UnDefType.UNDEF : new DateTimeType(nextAlarm));
    updateState(CHANNEL_NEXT_MUSIC_ALARM,
            nextMusicAlarm == null ? UnDefType.UNDEF : new DateTimeType(nextMusicAlarm));
    updateState(CHANNEL_NEXT_TIMER, nextTimer == null ? UnDefType.UNDEF : new DateTimeType(nextTimer));
}

From source file:systems.composable.dropwizard.cassandra.cli.CommandInfo.java

@Override
void run(Namespace namespace, CassandraMigration cassandraMigration, Session session) throws Exception {
    final MigrationInfo[] migrationInfos = cassandraMigration.info(session).all();
    if (migrationInfos.length == 0)
        throw new IllegalStateException("No migration scripts found");

    final Map<String, Integer> widths = new HashMap<>();
    final List<Map<String, String>> rows = new LinkedList<>();

    INFOS.forEach(col -> widths.compute(col, (k, v) -> k.length()));
    Arrays.stream(migrationInfos).forEach(migrationInfo -> {
        final Map<String, String> row = new HashMap<>();
        INFOS.forEach(col -> {//  ww  w . j a v a2  s  . c o m
            final String cell;
            switch (col) {
            case INFO_TYPE:
                cell = migrationInfo.getType().toString();
                break;
            case INFO_STATE:
                cell = migrationInfo.getState().getDisplayName();
                break;
            case INFO_VERSION:
                cell = migrationInfo.getVersion().toString();
                break;
            case INFO_DESC:
                cell = migrationInfo.getDescription();
                break;
            case INFO_SCRIPT:
                cell = migrationInfo.getScript();
                break;
            case INFO_CHKSUM:
                cell = String.valueOf(migrationInfo.getChecksum());
                break;
            case INFO_INST_ON:
                final Date d = migrationInfo.getInstalledOn();
                cell = d != null ? d.toInstant().toString() : "";
                break;
            case INFO_EXEC_MS:
                final Integer ms = migrationInfo.getExecutionTime();
                cell = ms != null ? Duration.of(ms, ChronoUnit.MILLIS).toString() : "";
                break;
            default:
                cell = "";
            }
            row.put(col, cell);
            widths.compute(col, (k, v) -> Math.max(cell.length(), v));
        });
        rows.add(row);
    });

    final String separator = "+"
            + INFOS.stream().map(col -> repeat('-', widths.get(col) + 2)).collect(Collectors.joining("+")) + "+"
            + System.lineSeparator();

    final StringBuilder sb = new StringBuilder().append(separator).append('|')
            .append(INFOS.stream().map(col -> " " + center(col, widths.get(col)) + " ")
                    .collect(Collectors.joining("|")))
            .append('|').append(System.lineSeparator()).append(separator);
    rows.forEach(row -> sb.append('|').append(INFOS.stream()
            .map(col -> " " + leftPad(row.get(col), widths.get(col)) + " ").collect(Collectors.joining("|")))
            .append('|').append(System.lineSeparator()));
    sb.append(separator);
    System.out.print(sb.toString());
}