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:com.match_tracker.twitter.TwitterSearch.java

protected long calculateSearchDelay(ZonedDateTime startTime) {
    long searchDelay = 0;

    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime offsetStartTime = startTime.plusSeconds(SEARCH_START_DELAY_SECONDS);

    if (now.isBefore(offsetStartTime)) {
        searchDelay = now.until(offsetStartTime, ChronoUnit.MILLIS);
    }//from   w ww .  j  a va 2s . c o m

    return searchDelay;
}

From source file:com.netflix.genie.web.tasks.node.DiskCleanupTaskTest.java

/**
 * Make sure we can run successfully when runAsUser is false for the system.
 *
 * @throws IOException    on error/*from   ww  w.ja  v  a 2 s .  c o  m*/
 * @throws GenieException on error
 */
@Test
public void canRunWithoutSudo() throws IOException, GenieException {
    final JobsProperties jobsProperties = JobsProperties.getJobsPropertiesDefaults();
    jobsProperties.getUsers().setRunAsUserEnabled(false);

    // Create some random junk file that should be ignored
    this.tmpJobDir.newFile(UUID.randomUUID().toString());
    final DiskCleanupProperties properties = new DiskCleanupProperties();
    final Instant threshold = TaskUtils.getMidnightUTC().minus(properties.getRetention(), ChronoUnit.DAYS);

    final String job1Id = UUID.randomUUID().toString();
    final String job2Id = UUID.randomUUID().toString();
    final String job3Id = UUID.randomUUID().toString();
    final String job4Id = UUID.randomUUID().toString();
    final String job5Id = UUID.randomUUID().toString();

    final Job job1 = Mockito.mock(Job.class);
    Mockito.when(job1.getStatus()).thenReturn(JobStatus.INIT);
    final Job job2 = Mockito.mock(Job.class);
    Mockito.when(job2.getStatus()).thenReturn(JobStatus.RUNNING);
    final Job job3 = Mockito.mock(Job.class);
    Mockito.when(job3.getStatus()).thenReturn(JobStatus.SUCCEEDED);
    Mockito.when(job3.getFinished()).thenReturn(Optional.of(threshold.minus(1, ChronoUnit.MILLIS)));
    final Job job4 = Mockito.mock(Job.class);
    Mockito.when(job4.getStatus()).thenReturn(JobStatus.FAILED);
    Mockito.when(job4.getFinished()).thenReturn(Optional.of(threshold));

    this.createJobDir(job1Id);
    this.createJobDir(job2Id);
    this.createJobDir(job3Id);
    this.createJobDir(job4Id);
    this.createJobDir(job5Id);

    final TaskScheduler scheduler = Mockito.mock(TaskScheduler.class);
    final Resource jobDir = Mockito.mock(Resource.class);
    Mockito.when(jobDir.exists()).thenReturn(true);
    Mockito.when(jobDir.getFile()).thenReturn(this.tmpJobDir.getRoot());
    final JobSearchService jobSearchService = Mockito.mock(JobSearchService.class);

    Mockito.when(jobSearchService.getJob(job1Id)).thenReturn(job1);
    Mockito.when(jobSearchService.getJob(job2Id)).thenReturn(job2);
    Mockito.when(jobSearchService.getJob(job3Id)).thenReturn(job3);
    Mockito.when(jobSearchService.getJob(job4Id)).thenReturn(job4);
    Mockito.when(jobSearchService.getJob(job5Id)).thenThrow(new GenieServerException("blah"));

    final DiskCleanupTask task = new DiskCleanupTask(properties, scheduler, jobDir, jobSearchService,
            jobsProperties, Mockito.mock(Executor.class), new SimpleMeterRegistry());
    task.run();
    Assert.assertTrue(new File(jobDir.getFile(), job1Id).exists());
    Assert.assertTrue(new File(jobDir.getFile(), job2Id).exists());
    Assert.assertFalse(new File(jobDir.getFile(), job3Id).exists());
    Assert.assertTrue(new File(jobDir.getFile(), job4Id).exists());
    Assert.assertTrue(new File(jobDir.getFile(), job5Id).exists());
}

From source file:ch.algotrader.service.algo.VWAPOrderService.java

VWAPOrderStateVO createAlgoOrderState(final VWAPOrder algoOrder, final Date dateTime)
        throws OrderValidationException {

    Validate.notNull(algoOrder, "vwapOrder missing");

    Security security = algoOrder.getSecurity();
    SecurityFamily family = security.getSecurityFamily();
    Exchange exchange = family.getExchange();

    HistoricalDataService historicalDataService = this.applicationContext.getBean(HistoricalDataService.class);

    List<Bar> bars = historicalDataService.getHistoricalBars(security.getId(), //
            DateUtils.truncate(new Date(), Calendar.DATE), //
            algoOrder.getLookbackPeriod(), //
            TimePeriod.DAY, //
            algoOrder.getBucketSize(), //
            MarketDataEventType.TRADES, //
            Collections.emptyMap());

    TreeMap<LocalTime, Long> buckets = new TreeMap<>();
    Set<LocalDate> tradingDays = new HashSet<>();
    for (Bar bar : bars) {
        int vol = bar.getVol();
        LocalTime time = DateTimeLegacy.toLocalTime(bar.getDateTime());
        tradingDays.add(DateTimeLegacy.toLocalDate(bar.getDateTime()));
        if (buckets.containsKey(time)) {
            buckets.put(time, buckets.get(time) + vol);
        } else {/* www.  j a v a2 s .  c  o  m*/
            buckets.put(time, (long) vol);
        }
    }

    // verify start and end time
    if (algoOrder.getStartTime() == null) {
        if (this.calendarService.isOpen(exchange.getId())) {
            algoOrder.setStartTime(dateTime);
        } else {
            Date nextOpenTime = this.calendarService.getNextOpenTime(exchange.getId());
            algoOrder.setStartTime(nextOpenTime);
        }
    }

    Date closeTime = this.calendarService.getNextCloseTime(exchange.getId());
    if (algoOrder.getEndTime() == null) {
        algoOrder.setEndTime(closeTime);
    }

    if (algoOrder.getStartTime().compareTo(dateTime) < 0) {
        throw new OrderValidationException("startTime needs to be in the future " + algoOrder);
    } else if (algoOrder.getEndTime().compareTo(dateTime) <= 0) {
        throw new OrderValidationException("endTime needs to be in the future " + algoOrder);
    } else if (algoOrder.getEndTime().compareTo(closeTime) > 0) {
        throw new OrderValidationException("endTime needs to be before next market closeTime for " + algoOrder);
    } else if (algoOrder.getEndTime().compareTo(algoOrder.getStartTime()) <= 0) {
        throw new OrderValidationException("endTime needs to be after startTime for " + algoOrder);
    }

    int historicalVolume = 0;
    LocalTime startTime = DateTimeLegacy.toLocalTime(algoOrder.getStartTime());
    LocalTime endTime = DateTimeLegacy.toLocalTime(algoOrder.getEndTime());
    LocalTime firstBucketStart = buckets.floorKey(startTime);
    LocalTime lastBucketStart = buckets.floorKey(endTime);

    SortedMap<LocalTime, Long> subBuckets = buckets.subMap(firstBucketStart, true, lastBucketStart, true);
    for (Map.Entry<LocalTime, Long> bucket : subBuckets.entrySet()) {

        long vol = bucket.getValue() / tradingDays.size();
        bucket.setValue(vol);

        if (bucket.getKey().equals(firstBucketStart)) {
            LocalTime firstBucketEnd = firstBucketStart.plus(algoOrder.getBucketSize().getValue(),
                    ChronoUnit.MILLIS);
            double fraction = (double) ChronoUnit.MILLIS.between(startTime, firstBucketEnd)
                    / algoOrder.getBucketSize().getValue();
            historicalVolume += vol * fraction;
        } else if (bucket.getKey().equals(lastBucketStart)) {
            double fraction = (double) ChronoUnit.MILLIS.between(lastBucketStart, endTime)
                    / algoOrder.getBucketSize().getValue();
            historicalVolume += vol * fraction;
        } else {
            historicalVolume += vol;
        }
    }

    double participation = algoOrder.getQuantity() / (double) historicalVolume;

    if (participation > MAX_PARTICIPATION) {
        throw new OrderValidationException("participation rate " + twoDigitFormat.format(participation * 100.0)
                + "% is above 50% of historical market volume for " + algoOrder);
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.debug("participation of {} is {}%", algoOrder.getDescription(),
                twoDigitFormat.format(participation * 100.0));
    }

    return new VWAPOrderStateVO(participation, buckets);
}

From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java

/** Attempts to parse a (typically recurring) time  
 * @param human_readable_duration - Uses some simple regexes (1h,d, 1month etc), and Natty (try examples http://natty.joestelmach.com/try.jsp#)
 * @param base_date - for relative date, locks the date to this origin (mainly for testing in this case?)
 * @return the machine readable duration, or an error
 *//*from w ww  .  j a v a 2 s  .c om*/
public static Validation<String, Duration> getDuration(final String human_readable_duration,
        Optional<Date> base_date) {
    // There's a few different cases:
    // - the validation from getTimePeriod
    // - a slightly more complicated version <N><p> where <p> == period from the above
    // - use Natty for more complex expressions

    final Validation<String, ChronoUnit> first_attempt = getTimePeriod(human_readable_duration);
    if (first_attempt.isSuccess()) {
        return Validation
                .success(Duration.of(first_attempt.success().getDuration().getSeconds(), ChronoUnit.SECONDS));
    } else { // Slightly more complex version
        final Matcher m = date_parser.matcher(human_readable_duration);
        if (m.matches()) {
            final Validation<String, Duration> candidate_ret = getTimePeriod(m.group(2)).map(cu -> {
                final LocalDateTime now = LocalDateTime.now();
                return Duration.between(now, now.plus(Integer.parseInt(m.group(1)), cu));
            });

            if (candidate_ret.isSuccess())
                return candidate_ret;
        }
    }
    // If we're here then try Natty
    final Date now = base_date.orElse(new Date());
    return getSchedule(human_readable_duration, Optional.of(now)).map(d -> {
        final long duration = d.getTime() - now.getTime();
        return Duration.of(duration, ChronoUnit.MILLIS);
    });
}

From source file:com.simiacryptus.util.Util.java

/**
 * Cvt temporal unit.//from w  ww. j  av  a 2 s . co m
 *
 * @param units the units
 * @return the temporal unit
 */
@javax.annotation.Nonnull
public static TemporalUnit cvt(@javax.annotation.Nonnull final TimeUnit units) {
    switch (units) {
    case DAYS:
        return ChronoUnit.DAYS;
    case HOURS:
        return ChronoUnit.HOURS;
    case MINUTES:
        return ChronoUnit.MINUTES;
    case SECONDS:
        return ChronoUnit.SECONDS;
    case NANOSECONDS:
        return ChronoUnit.NANOS;
    case MICROSECONDS:
        return ChronoUnit.MICROS;
    case MILLISECONDS:
        return ChronoUnit.MILLIS;
    default:
        throw new IllegalArgumentException(units.toString());
    }
}

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

/**
 * Must be called by the UI-thread/*w w w  .  ja v a 2 s  . co m*/
 *
 * @param idleTimeMillis
 */
private void handleReactivation(long idleTimeMillis) {
    // We want only one dialog open.
    if (dialogIsOpen) {
        return;
    }
    synchronized (this) {
        if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
            // If we have an active task
            ITask task = TasksUi.getTaskActivityManager().getActiveTask();
            if (task != null && Activator.getValue(task, Activator.START) != null) {
                dialogIsOpen = true;
                String tickString = Activator.getValue(task, Activator.TICK);
                LocalDateTime started = getActiveSince();
                LocalDateTime ticked = LocalDateTime.parse(tickString);
                LocalDateTime lastTick = ticked;
                // Subtract the IDLE_INTERVAL time the computer _was_
                // idle while counting up to the threshold. During this
                // period fields were updated. Thus must be adjusted for.
                ticked = ticked.minusNanos(IDLE_INTERVAL);
                String time = DurationFormatUtils.formatDuration(lastIdleTime, "H:mm:ss", true);

                StringBuilder sb = new StringBuilder();
                if (task.getTaskKey() != null) {
                    sb.append(task.getTaskKey());
                    sb.append(": ");
                }
                sb.append(task.getSummary());
                MessageDialog md = new MessageDialog(Display.getCurrent().getActiveShell(),
                        "Disregard idle time?", null,
                        MessageFormat.format(
                                "The computer has been idle since {0}, more than {1}. The active task \"{2}\" was started on {3}. Deactivate the task and disregard the idle time?",
                                ticked.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US)), time,
                                sb.toString(),
                                started.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US))),
                        MessageDialog.QUESTION, new String[] { "No", "Yes" }, 1);
                int open = md.open();
                dialogIsOpen = false;
                if (open == 1) {
                    // Stop task, subtract initial idle time
                    TasksUi.getTaskActivityManager().deactivateTask(task);
                    reduceTime(task, ticked.toLocalDate().toString(), IDLE_INTERVAL / 1000);
                } else {
                    // Continue task, add idle time
                    LocalDateTime now = LocalDateTime.now();
                    long seconds = lastTick.until(now, ChronoUnit.MILLIS);
                    accumulateTime(task, ticked.toLocalDate().toString(), seconds);
                    Activator.setValue(task, Activator.TICK, now.toString());
                }
            }
        }
    }
}

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

/**
 * Returns the number of milliseconds the active task has been active
 *
 * @return the active milliseconds or "0"
 *///from w w  w.  j  av  a 2 s  . c  om
public long getActiveTime() {
    LocalDateTime activeSince = getActiveSince();
    if (activeSince != null) {
        LocalDateTime now = LocalDateTime.now();
        return activeSince.until(now, ChronoUnit.MILLIS);
    }
    return 0;
}

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

public GamaDate plusMillis(final double duration) {
    return plus((long) duration, ChronoUnit.MILLIS);
}

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

public GamaDate minusMillis(final double duration) {
    return minus((long) duration, ChronoUnit.MILLIS);
}

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

public boolean isIntervalReached(final IScope scope, final IExpression period) {
    // We get the current date from the model
    final GamaDate current = scope.getClock().getCurrentDate();
    // Exact date ?
    if (this.equals(current)) {
        return true;
    }/*ww w. j  a  v  a 2  s . c  om*/
    // Not yet reached ?
    if (isGreaterThan(current, true)) {
        return false;
    }
    GamaDate nextByPeriod = plus(scope, period);
    // Null period ?
    if (nextByPeriod.equals(this)) {
        return false;
    }
    // Exactly reached ?
    if (nextByPeriod.equals(current)) {
        return true;
    }
    while (nextByPeriod.isSmallerThan(current, true)) {
        nextByPeriod = nextByPeriod.plus(scope, period);
    }

    final long stepInMillis = scope.getClock().getStepInMillis();
    final GamaDate nextByStep = current.plus(stepInMillis, ChronoUnit.MILLIS);

    return nextByStep.isGreaterThan(nextByPeriod, true);

}