Example usage for java.time.temporal ChronoUnit SECONDS

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

Introduction

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

Prototype

ChronoUnit SECONDS

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

Click Source Link

Document

Unit that represents the concept of a second.

Usage

From source file:com.eventsourcing.repository.RepositoryTest.java

@Test
@SneakyThrows// w  ww.  ja va2  s . co  m
public void initialTimestamp() {
    HybridTimestamp t = repository.getTimestamp();
    long ts = t.timestamp();
    TimeStamp soon = new TimeStamp(new Date(new Date().toInstant().plus(1, ChronoUnit.SECONDS).toEpochMilli()));
    TimeStamp t1 = new TimeStamp(ts);
    assertTrue(HybridTimestamp.compare(t1, startTime) > 0);
    assertTrue(HybridTimestamp.compare(t1, soon) < 0);
}

From source file:com.netflix.genie.web.jobs.workflow.impl.JobKickoffTask.java

/**
 * {@inheritDoc}/*from w w w  .jav  a  2s  .c om*/
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    final Set<Tag> tags = Sets.newHashSet();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final JobRequest jobRequest = jobExecEnv.getJobRequest();
        final String user = jobRequest.getUser();
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        final String jobId = jobRequest.getId()
                .orElseThrow(() -> new GeniePreconditionException("No job id found. Unable to continue."));
        log.info("Starting Job Kickoff Task for job {}", jobId);

        // At this point all contents are written to the run script and we call an explicit flush and close to write
        // the contents to the file before we execute it.
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new GenieServerException("Failed to execute job", e);
        }
        // Create user, if enabled
        if (isUserCreationEnabled) {
            createUser(user, jobRequest.getGroup().orElse(null));
        }
        final List<String> command = new ArrayList<>();

        // If the OS is linux use setsid to launch the process so that the entire process tree
        // is launched in process group id which is the same as the pid of the parent process
        if (SystemUtils.IS_OS_LINUX) {
            command.add("setsid");
        }

        // Set the ownership to the user and run as the user, if enabled
        if (isRunAsUserEnabled) {
            changeOwnershipOfDirectory(jobWorkingDirectory, user);

            // This is needed because the genie.log file is still generated as the user running Genie system.
            makeDirGroupWritable(jobWorkingDirectory + "/genie/logs");
            command.add("sudo");
            command.add("-u");
            command.add(user);
        }

        final String runScript = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER
                + JobConstants.GENIE_JOB_LAUNCHER_SCRIPT;
        command.add(runScript);

        // Cannot convert to executor because it does not provide an api to get process id.
        final ProcessBuilder pb = new ProcessBuilder(command).directory(jobExecEnv.getJobWorkingDir())
                .redirectOutput(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH))
                .redirectError(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH));

        //
        // Check if file can be executed. This is to fix issue where execution of the run script fails because
        // the file may be used by some other program
        //
        canExecute(runScript);
        try {
            final Process process = pb.start();
            final int processId = this.getProcessId(process);
            final Instant timeout = Instant.now().plus(
                    jobRequest.getTimeout().orElse(JobRequest.DEFAULT_TIMEOUT_DURATION), ChronoUnit.SECONDS);
            final JobExecution jobExecution = new JobExecution.Builder(this.hostname).withId(jobId)
                    .withProcessId(processId).withCheckDelay(jobExecEnv.getCommand().getCheckDelay())
                    .withTimeout(timeout).withMemory(jobExecEnv.getMemory()).build();
            context.put(JobConstants.JOB_EXECUTION_DTO_KEY, jobExecution);
        } catch (final IOException ie) {
            throw new GenieServerException("Unable to start command " + String.valueOf(command), ie);
        }
        log.info("Finished Job Kickoff Task for job {}", jobId);
        MetricsUtils.addSuccessTags(tags);
    } catch (final Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.getRegistry().timer(JOB_KICKOFF_TASK_TIMER_NAME, tags).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);
    }
}

From source file:com.otway.picasasync.syncutil.ImageSync.java

private boolean localCopyNeedsUpdating(PhotoEntry photo, File localPath)
        throws ImageReadException, IOException, ServiceException {
    boolean updateLocal = false;
    if (localPath.exists()) {

        LocalDateTime localMod = getTimeFromMS(localPath.lastModified());
        LocalDateTime remoteMod = getTimeFromMS(photo.getUpdated().getValue());
        long seconds = ChronoUnit.SECONDS.between(localMod, remoteMod);
        if (Math.abs(seconds) > 1)
            return true;

        long localFileSize = localPath.length();
        long remoteFileSize = photo.getSize();
        if (localFileSize != remoteFileSize) {
            log.info(String.format(
                    "File sizes are different: (local %s vs remote %s). Local file will be updated.",
                    FileUtils.byteCountToDisplaySize(localFileSize),
                    FileUtils.byteCountToDisplaySize(remoteFileSize)));
            return true;
        }/* w ww . j av a  2  s.c om*/

        ImageInformation localInfo = ImageInformation.safeReadImageInformation(localPath);

        if (localInfo != null) {

            Integer rotation = photo.getRotation();
            if (rotation != null)
                log.info("PhotoEntry rotation was set!");

            // Make sure we take into account the rotation of the image when comparing width/height
            long localWidth = localInfo.getWidthHeightTransposed() ? localInfo.getHeight()
                    : localInfo.getWidth();
            long localHeight = localInfo.getWidthHeightTransposed() ? localInfo.getWidth()
                    : localInfo.getHeight();

            if (localWidth != photo.getWidth() || localHeight != photo.getHeight()) {
                log.info(String.format(
                        "Image dimensions are different: (local %dx%d vs remote %dx%d). Local file will be updated.",
                        localInfo.getWidth(), localInfo.getHeight(), photo.getWidth(), photo.getHeight()));

                return true;
            }
        } else {
            log.warn("Local file was not image! Renaming before overwrite. (" + localPath.getName() + ")");

            File renamed = new File(localPath + ".old");
            if (!localPath.renameTo(renamed))
                log.warn("Unable to rename file");

            updateLocal = true;
        }

    } else {
        log.debug("No local file existed: " + localPath);
        // Nothing here, so always write
        updateLocal = true;
    }

    return updateLocal;
}

From source file:org.ulyssis.ipp.snapshot.TestSnapshot.java

@Test
public void testPredictedSpeedWhenStartedThenFirstEvent() throws Exception {
    TagId tag = new TagId("DCBA");
    Snapshot snapshot = new Snapshot(Instant.EPOCH);
    AddTagEvent addTagEvent = new AddTagEvent(Instant.EPOCH, tag, 3);
    snapshot = addTagEvent.doApply(snapshot);
    StartEvent startEvent = new StartEvent(Instant.EPOCH);
    snapshot = startEvent.doApply(snapshot);
    TagSeenEvent tagSeenEvent = new TagSeenEvent(Instant.EPOCH.plus(10, ChronoUnit.SECONDS), tag, 0, 0L);
    snapshot = tagSeenEvent.doApply(snapshot);
    TagSeenEvent tagSeenEvent2 = new TagSeenEvent(Instant.EPOCH.plus(50, ChronoUnit.SECONDS), tag, 1, 1L);
    snapshot = tagSeenEvent2.doApply(snapshot);
    double speedShouldBe = 100D / (50D - 10D);
    MatcherAssert.assertThat(snapshot.getTeamStates().getStateForTeam(3).get().getPredictedSpeed(),
            Matchers.equalTo(speedShouldBe));
    MatcherAssert.assertThat(snapshot.getTeamStates().getStateForTeam(3).get().getSpeed(),
            Matchers.equalTo(speedShouldBe));
}

From source file:org.ulyssis.ipp.snapshot.TestSnapshot.java

@Test
public void testPredictedSpeedWhenFirstEventThenStarted() throws Exception {
    TagId tag = new TagId("DCBA");
    Snapshot snapshot = new Snapshot(Instant.EPOCH);
    AddTagEvent addTagEvent = new AddTagEvent(Instant.EPOCH, tag, 3);
    snapshot = addTagEvent.doApply(snapshot);
    TagSeenEvent tagSeenEvent = new TagSeenEvent(Instant.EPOCH.minus(10, ChronoUnit.SECONDS), tag, 0, 0L);
    snapshot = tagSeenEvent.doApply(snapshot);
    StartEvent startEvent = new StartEvent(Instant.EPOCH);
    snapshot = startEvent.doApply(snapshot);
    TagSeenEvent tagSeenEvent2 = new TagSeenEvent(Instant.EPOCH.plus(50, ChronoUnit.SECONDS), tag, 1, 1L);
    snapshot = tagSeenEvent2.doApply(snapshot);
    double speedShouldBe = 100D / 50D;
    MatcherAssert.assertThat(snapshot.getTeamStates().getStateForTeam(3).get().getPredictedSpeed(),
            Matchers.equalTo(speedShouldBe));
    MatcherAssert.assertThat(snapshot.getTeamStates().getStateForTeam(3).get().getSpeed(),
            Matchers.equalTo(speedShouldBe));
}

From source file:com.github.aptd.simulation.elements.train.CTrain.java

@Override
protected final synchronized boolean updatestate() {
    final List<IDoor<?>> l_doorsclosedlocked = m_input.get(EMessageType.DOOR_TO_TRAIN_CLOSED_LOCKED).stream()
            .map(msg -> (IDoor<?>) msg.sender()).collect(Collectors.toList());
    if (!l_doorsclosedlocked.isEmpty()) {
        if (m_state != ETrainState.WAITING_TO_DRIVE)
            throw new RuntimeException("door locked although not waiting to drive: " + m_id);
        m_doorsnotclosedlocked.removeAll(l_doorsclosedlocked);
        m_doorsclosedlocked.addAll(l_doorsclosedlocked);
    }//from   ww  w .  ja v a 2s.c  o  m

    final List<IMessage> l_subscribingpassengers = m_input.get(EMessageType.PASSENGER_TO_TRAIN_SUBSCRIBE);
    final List<IMessage> l_unsubscribingpassengers = m_input.get(EMessageType.PASSENGER_TO_TRAIN_UNSUBSCRIBE);
    if (!l_subscribingpassengers.isEmpty() || !l_unsubscribingpassengers.isEmpty()) {
        if (m_doorsnotclosedlocked.isEmpty())
            throw new RuntimeException(
                    "passengers subscribing/unsubscribing although all doors locked:" + m_id);
        l_subscribingpassengers.stream().forEach(msg -> m_passengers.add((IPassenger<?>) msg.sender()));
        l_unsubscribingpassengers.stream().forEach(msg -> m_passengers.remove(msg.sender()));
    }

    final boolean l_timedchange = !m_nextstatechange.isAfter(m_time.current());
    // if ( l_timedchange )
    //    System.out.println( m_id + " - timer transition at " + m_time.current().toString() + " from state " + m_state + " (ttindex = " + m_ttindex + ")" );
    switch (m_state) {
    case ARRIVED:
        if (!l_timedchange)
            break;
        // proceed to next timetable entry
        m_ttindex++;
        m_positionontrack = 0.0;
        m_state = ETrainState.WAITING_TO_DRIVE;
        m_doorsnotclosedlocked
                .forEach(d -> output(new CMessage(this, d.id(), EMessageType.TRAIN_TO_DOOR_LOCK, "")));
        // debugPrintState();
        return true;
    case DRIVING:
        // @todo: react to "red signal" here
        if (!l_timedchange)
            break;
        m_state = ETrainState.ARRIVED;
        Logger.info(m_id + " - arrival at " + m_timetable.get(m_ttindex).m_stationid + " at "
                + m_time.current().toString() + " which was planned for "
                + m_timetable.get(m_ttindex).m_publishedarrival + "["
                + m_timetable.get(m_ttindex).m_publishedarrival.until(m_time.current(), ChronoUnit.SECONDS)
                + "]");
        m_doorsclosedlocked.forEach(d -> output(new CMessage(this, d.id(), EMessageType.TRAIN_TO_DOOR_UNLOCK,
                m_timetable.get(m_ttindex).m_stationid, m_timetable.get(m_ttindex).m_platformid)));
        m_doorsnotclosedlocked.addAll(m_doorsclosedlocked);
        m_doorsclosedlocked.clear();
        m_passengers.forEach(p -> output(new CMessage(this, p.id(), EMessageType.TRAIN_TO_PASSENGER_ARRIVING,
                m_timetable.get(m_ttindex).m_stationid, m_timetable.get(m_ttindex).m_platformid,
                m_doorsnotclosedlocked.toArray())));
        output(new CMessage(this, m_timetable.get(m_ttindex).m_platformid,
                EMessageType.TRAIN_TO_PLATFORM_ARRIVING, m_doorsnotclosedlocked.toArray()));
        // debugPrintState();
        return true;
    case WAITING_TO_DRIVE:
        if (!m_doorsnotclosedlocked.isEmpty())
            break;
        Logger.info(m_id + " - departure from " + m_timetable.get(m_ttindex - 1).m_stationid + " at "
                + m_time.current().toString() + " which was planned for "
                + m_timetable.get(m_ttindex - 1).m_publisheddeparture + " ["
                + m_timetable.get(m_ttindex - 1).m_publisheddeparture.until(m_time.current(),
                        ChronoUnit.SECONDS)
                + "]");
        output(new CMessage(this, m_timetable.get(m_ttindex - 1).m_platformid,
                EMessageType.TRAIN_TO_PLATFORM_DEPARTING));
        m_state = ETrainState.DRIVING;
        return true;
    default:
        // making checkstyle happy
    }
    return false;
}

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 w w  .  j a  v a  2s  .  co  m
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:org.jboss.pnc.buildagent.client.BuildAgentClient.java

private void waitCommandPromptReady() throws TimeoutException, InterruptedException {
    log.trace("Waiting for commandPromptReady ... ");
    Wait.forCondition(() -> isCommandPromptReady.get(), 15, ChronoUnit.SECONDS,
            "Command prompt was not ready.");
    log.debug("CommandPromptReady.");
}

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

/**
 * Cvt temporal unit.//from  w  w  w  .  j a v a  2  s.  c  om
 *
 * @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:de.perdoctus.ebikeconnect.gui.ActivitiesOverviewController.java

@FXML
public void initialize() {
    logger.info("Init!");

    NUMBER_FORMAT.setMaximumFractionDigits(2);

    webEngine = webView.getEngine();//from   w w  w  .  ja  v  a 2 s  .com
    webEngine.load(getClass().getResource("/html/googleMap.html").toExternalForm());

    // Activity Headers
    activityDaysHeaderService.setOnSucceeded(event -> {
        activitiesTable.setItems(FXCollections.observableArrayList(activityDaysHeaderService.getValue()));
        activitiesTable.getSortOrder().add(tcDate);
        tcDate.setSortable(true);
    });
    activityDaysHeaderService.setOnFailed(
            event -> logger.error("Failed to obtain ActivityList!", activityDaysHeaderService.getException()));
    final ProgressDialog activityHeadersProgressDialog = new ProgressDialog(activityDaysHeaderService);
    activityHeadersProgressDialog.initModality(Modality.APPLICATION_MODAL);

    // Activity Details
    activityDetailsGroupService.setOnSucceeded(
            event -> this.currentActivityDetailsGroup.setValue(activityDetailsGroupService.getValue()));
    activityDetailsGroupService.setOnFailed(event -> logger.error("Failed to obtain ActivityDetails!",
            activityDaysHeaderService.getException()));
    final ProgressDialog activityDetailsProgressDialog = new ProgressDialog(activityDetailsGroupService);
    activityDetailsProgressDialog.initModality(Modality.APPLICATION_MODAL);

    // Gpx Export
    gpxExportService.setOnSucceeded(event -> gpxExportFinished());
    gpxExportService
            .setOnFailed(event -> handleError("Failed to generate GPX File", gpxExportService.getException()));

    tcxExportService.setOnSucceeded(event -> gpxExportFinished());
    tcxExportService
            .setOnFailed(event -> handleError("Failed to generate TCX File", tcxExportService.getException()));

    // ActivityTable
    tcDate.setCellValueFactory(param -> new SimpleObjectProperty<>(param.getValue().getDate()));
    tcDate.setCellFactory(param -> new LocalDateCellFactory());
    tcDate.setSortType(TableColumn.SortType.DESCENDING);

    tcDistance.setCellValueFactory(param -> new SimpleObjectProperty<>(param.getValue().getDistance() / 1000));
    tcDistance.setCellFactory(param -> new NumberCellFactory(1, "km"));

    tcDuration.setCellValueFactory(param -> new SimpleObjectProperty<>(param.getValue().getDrivingTime()));
    tcDuration.setCellFactory(param -> new DurationCellFactory());

    activitiesTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    activitiesTable.getSelectionModel().getSelectedItems()
            .addListener((ListChangeListener<ActivityHeaderGroup>) c -> {
                while (c.next()) {
                    if (c.wasRemoved()) {
                        for (ActivityHeaderGroup activityHeaderGroup : c.getRemoved()) {
                            lstSegments.getItems().removeAll(activityHeaderGroup.getActivityHeaders());
                        }

                    }
                    if (c.wasAdded()) {
                        for (ActivityHeaderGroup activityHeaderGroup : c.getAddedSubList()) {
                            if (activityHeaderGroup != null) { // WTF? Why can this be null!?
                                lstSegments.getItems().addAll(activityHeaderGroup.getActivityHeaders());
                            }
                        }
                    }

                }
                lstSegments.getItems().sort((o1, o2) -> o1.getStartTime().isAfter(o2.getStartTime()) ? 1 : 0);
            });

    activitiesTable.setOnMouseClicked(event -> {
        if (event.getClickCount() == 2) {
            lstSegments.getCheckModel().checkAll();
            openSelectedSections();
        }
    });

    // Segment List
    lstSegments
            .setCellFactory(listView -> new CheckBoxListCell<>(item -> lstSegments.getItemBooleanProperty(item),
                    new StringConverter<ActivityHeader>() {

                        @Override
                        public ActivityHeader fromString(String arg0) {
                            return null;
                        }

                        @Override
                        public String toString(ActivityHeader activityHeader) {
                            final String startTime = activityHeader.getStartTime().format(DATE_TIME_FORMATTER);
                            final String endTime = activityHeader.getEndTime().format(TIME_FORMATTER);
                            final double distance = activityHeader.getDistance() / 1000;
                            return startTime + " - " + endTime + " (" + NUMBER_FORMAT.format(distance) + " km)";
                        }

                    }));

    // -- Chart
    chartRangeSlider.setLowValue(0);
    chartRangeSlider.setHighValue(chartRangeSlider.getMax());

    xAxis.setAutoRanging(false);
    xAxis.lowerBoundProperty().bind(chartRangeSlider.lowValueProperty());
    xAxis.upperBoundProperty().bind(chartRangeSlider.highValueProperty());
    xAxis.tickUnitProperty().bind(
            chartRangeSlider.highValueProperty().subtract(chartRangeSlider.lowValueProperty()).divide(20));
    xAxis.setTickLabelFormatter(new StringConverter<Number>() {
        @Override
        public String toString(Number object) {
            final Duration duration = Duration.of(object.intValue(), ChronoUnit.SECONDS);
            return String.valueOf(DurationFormatter.formatHhMmSs(duration));
        }

        @Override
        public Number fromString(String string) {
            return null;
        }
    });

    chart.getChart().setOnScroll(event -> {
        final double scrollAmount = event.getDeltaY();
        chartRangeSlider.setLowValue(chartRangeSlider.getLowValue() + scrollAmount);
        chartRangeSlider.setHighValue(chartRangeSlider.getHighValue() - scrollAmount);
    });

    xAxis.setOnMouseMoved(event -> {
        if (getCurrentActivityDetailsGroup() == null) {
            return;
        }

        final Number valueForDisplay = xAxis.getValueForDisplay(event.getX());
        final List<Coordinate> trackpoints = getCurrentActivityDetailsGroup().getJoinedTrackpoints();
        final int index = valueForDisplay.intValue();
        if (index >= 0 && index < trackpoints.size()) {
            final Coordinate coordinate = trackpoints.get(index);
            if (coordinate.isValid()) {
                final LatLng latLng = new LatLng(coordinate);
                try {
                    webEngine.executeScript(
                            "updateMarkerPosition(" + objectMapper.writeValueAsString(latLng) + ");");
                } catch (JsonProcessingException e) {
                    e.printStackTrace(); //TODO clean up ugly code!!!!--------------
                }
            }
        }
    });

    // -- Current ActivityDetails
    this.currentActivityDetailsGroup.addListener((observable, oldValue, newValue) -> {
        if (newValue != null) {
            activityGroupChanged(newValue);
        }
    });
}