List of usage examples for java.time Duration of
public static Duration of(long amount, TemporalUnit unit)
From source file:Main.java
public static void main(String[] args) { Duration duration = Duration.of(10, ChronoUnit.DAYS); System.out.println(duration); }
From source file:com.przemo.projectmanagementweb.services.TimeLogService.java
public Duration getTimeLoggedForTask(int taskId) { List<Double> t = HibernateUtil.runQuery("select sum(tl.time) from TimeLog tl where tl.task=" + taskId); if (t != null && !t.isEmpty() && t.get(0) != null) { return Duration.of((int) ((t.get(0)) * 60), ChronoUnit.MINUTES); } else {// ww w . j a v a2s . co m return Duration.ZERO; } }
From source file:com.teradata.benchto.driver.graphite.GraphiteProperties.java
public Duration getGraphiteMetricsDelay() { return Duration.of(graphiteMetricsDelaySeconds, ChronoUnit.SECONDS); }
From source file:com.netflix.spinnaker.echo.pipelinetriggers.health.MonitoredPollerHealth.java
private void polledRecently(Health.Builder builder) { Instant lastPollTimestamp = poller.getLastPollTimestamp(); if (lastPollTimestamp == null) { builder.unknown();/*w w w . ja va 2 s . c o m*/ } else { val timeSinceLastPoll = Duration.between(lastPollTimestamp, now()); builder.withDetail("last.polled", formatDurationWords(timeSinceLastPoll.toMillis(), true, true) + " ago"); builder.withDetail("last.polled.at", ISO_LOCAL_DATE_TIME.format(lastPollTimestamp.atZone(ZoneId.systemDefault()))); if (timeSinceLastPoll.compareTo(Duration.of(poller.getPollingIntervalSeconds() * 2, SECONDS)) <= 0) { builder.up(); } else { builder.down(); } } }
From source file:com.netflix.genie.web.configs.GenieApiAutoConfiguration.java
/** * Get RestTemplate for calling between Genie nodes. * * @param httpProperties The properties related to Genie's HTTP client configuration * @param restTemplateBuilder The Spring REST template builder to use * @return The rest template to use//from w ww. j ava2 s . c om */ @Bean @ConditionalOnMissingBean(name = "genieRestTemplate") public RestTemplate genieRestTemplate(final HttpProperties httpProperties, final RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder .setConnectTimeout(Duration.of(httpProperties.getConnect().getTimeout(), ChronoUnit.MILLIS)) .setReadTimeout(Duration.of(httpProperties.getRead().getTimeout(), ChronoUnit.MILLIS)).build(); }
From source file:com.teradata.benchto.driver.listeners.BenchmarkServiceExecutionListener.java
private void checkClocksSync() { long timeBefore = System.currentTimeMillis(); long serviceTime = benchmarkServiceClient.getServiceCurrentTime().toEpochMilli(); long timeAfter = System.currentTimeMillis(); long driftApproximation = Math.abs(LongMath.mean(timeBefore, timeAfter) - serviceTime); long approximationPrecision = timeAfter - LongMath.mean(timeBefore, timeAfter); Duration driftLowerBound = Duration.of(driftApproximation - approximationPrecision, ChronoUnit.MILLIS); if (driftLowerBound.compareTo(MAX_CLOCK_DRIFT) > 1) { throw new RuntimeException( format("Detected driver and service clocks drift of at least %s, assumed sane maximum is %s", driftLowerBound, MAX_CLOCK_DRIFT)); }//from w w w.ja va 2s . c o m }
From source file:onl.area51.httpd.action.Request.java
default Request expiresIn(long v, ChronoUnit unit) { return expiresIn(Duration.of(v, unit)); }
From source file:onl.area51.httpd.action.Request.java
default Request maxAge(long v, ChronoUnit unit) { return maxAge(Duration.of(v, unit)); }
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 *//* w ww . 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:de.perdoctus.ebikeconnect.gui.ActivitiesOverviewController.java
@FXML public void initialize() { logger.info("Init!"); NUMBER_FORMAT.setMaximumFractionDigits(2); webEngine = webView.getEngine();/* w ww.j a va 2 s. c o m*/ 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); } }); }