Java Code Examples for java.time.Duration#getSeconds()

The following examples show how to use java.time.Duration#getSeconds() . 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 File: Report.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
public long calculateDelayInSeconds() throws IllegalCommandBodyException {
    DailyReport basePeriodicReportType = (DailyReport) reportType;

    ZonedDateTime zonedNow = ZonedDateTime.now(tzName);
    ZonedDateTime zonedStartAt = basePeriodicReportType.getNextTriggerTime(zonedNow, tzName);
    if (basePeriodicReportType.isExpired(zonedStartAt, tzName)) {
        throw new IllegalCommandBodyException("Report is expired.");
    }

    Duration duration = Duration.between(zonedNow, zonedStartAt);
    long initialDelaySeconds = duration.getSeconds();

    if (initialDelaySeconds < 0) {
        throw new IllegalCommandBodyException("Initial delay in less than zero.");
    }

    return initialDelaySeconds;
}
 
Example 2
Source File: OAuth2TokenKeyServiceWithCache.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
private TokenKeyCacheConfiguration getCheckedConfiguration(CacheConfiguration cacheConfiguration) {
	Assertions.assertNotNull(cacheConfiguration, "CacheConfiguration must not be null!");
	int size = cacheConfiguration.getCacheSize();
	Duration duration = cacheConfiguration.getCacheDuration();
	if (size < 1000) {
		int currentSize = getCacheConfiguration().getCacheSize();
		LOGGER.error("Tried to set cache size to {} but the cache size must be 1000 or more."
				+ " Cache size will remain at: {}", size, currentSize);
		size = currentSize;
	}
	if (duration.getSeconds() < 600) {
		Duration currentDuration = getCacheConfiguration().getCacheDuration();
		LOGGER.error(
				"Tried to set cache duration to {} seconds but the cache duration must be at least 600 seconds."
						+ " Cache duration will remain at: {} seconds",
				duration.getSeconds(), currentDuration.getSeconds());
		duration = currentDuration;
	}
	return TokenKeyCacheConfiguration.getInstance(duration, size);
}
 
Example 3
Source File: RecordingInfo.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
RecordingInfo(Recording recording) {
    id = recording.getId();
    name = recording.getName();
    state = recording.getState().toString();
    dumpOnExit = recording.getDumpOnExit();
    size = recording.getSize();
    disk = recording.isToDisk();

    Duration d = recording.getMaxAge();
    if (d == null) {
        maxAge = 0;
    } else {
        maxAge = d.getSeconds();
    }
    maxSize = recording.getMaxSize();
    Instant s = recording.getStartTime();
    startTime = s == null ? 0L : s.toEpochMilli();
    Instant st = recording.getStopTime();
    stopTime = st == null ? 0L : st.toEpochMilli();
    Path p = recording.getDestination();
    destination = p == null ? null : p.toString();
    Duration duration = recording.getDuration();
    durationInSeconds = duration == null ? 0 : duration.getSeconds();
    settings = recording.getSettings();
}
 
Example 4
Source File: IssuesReportListener.java    From pitest-descartes with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String getStringTime() {
    //TODO: Is there a way to have this code in the template?

    Duration elapsed = Duration.ofMillis(System.currentTimeMillis() - arguments.getStartTime());
    String[] units = {"day", "hour", "minute", "second"};
    long[] parts = { elapsed.toDays(), elapsed.toHours() % 24, elapsed.toMinutes() % 60, elapsed.getSeconds() % 60};
    StringBuilder result = new StringBuilder();
    for(int i=0; i < parts.length; i++) {
        if(parts[i] == 0) continue;
        result.append(parts[i]).append(" ").append(units[i]);
        if(parts[i] > 1)
            result.append("s");
        result.append(" ");
    }
    if(result.length() == 0)
        return "less than one second";
    return result.substring(0, result.length() - 1);
}
 
Example 5
Source File: JobsManagerImpl.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private long parseJobLifetime(String expr) {
    if(StringUtils.hasText(expr)) {
        try {
            Duration duration = Duration.parse(expr);
            return duration.getSeconds();
        } catch (Exception e) {
           log.warn("Can not parse: {} ", expr, e);
        }
    }
    return TimeUnit.DAYS.toSeconds(1L);
}
 
Example 6
Source File: AppUtils.java    From OEE-Designer with MIT License 5 votes vote down vote up
public static String stringFromDuration(Duration duration, boolean withSeconds) {
	long totalSeconds = duration.getSeconds();
	long hours = totalSeconds / 3600;
	long minutes = (totalSeconds - hours * 3600) / 60;
	long seconds = totalSeconds - (hours * 3600) - (minutes * 60);

	String value = String.format("%02d", hours) + ":" + String.format("%02d", minutes);

	if (withSeconds) {
		value += ":" + String.format("%02d", seconds);
	}
	return value;
}
 
Example 7
Source File: TaskUtil.java    From GriefDefender with MIT License 5 votes vote down vote up
public static long computeDelay(int targetHour, int targetMin, int targetSec) 
{
    LocalDateTime localNow = LocalDateTime.now();
    ZoneId currentZone = ZoneId.systemDefault();
    ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
    ZonedDateTime zonedNextTarget = zonedNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec);
    if(zonedNow.compareTo(zonedNextTarget) > 0) {
        zonedNextTarget = zonedNextTarget.plusDays(1);
    }

    Duration duration = Duration.between(zonedNow, zonedNextTarget);
    return duration.getSeconds();
}
 
Example 8
Source File: TaskUtil.java    From GriefDefender with MIT License 5 votes vote down vote up
public static long computeDelay(int targetHour, int targetMin, int targetSec) 
{
    LocalDateTime localNow = LocalDateTime.now();
    ZoneId currentZone = ZoneId.systemDefault();
    ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
    ZonedDateTime zonedNextTarget = zonedNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec);
    if(zonedNow.compareTo(zonedNextTarget) > 0) {
        zonedNextTarget = zonedNextTarget.plusDays(1);
    }

    Duration duration = Duration.between(zonedNow, zonedNextTarget);
    return duration.getSeconds();
}
 
Example 9
Source File: PinCodeService.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean canSendPinCode(CreatePinCodeRequest request) {
    List<PinCodeTracking> results = repository.query("SELECT t FROM PinCodeTracking t WHERE t.ip=?0", request.ip).sort("createdTime", true).limit(1, options.dailyRate).find();
    if (results.isEmpty()) {
        return true;
    }
    Duration lastCreated = Duration.between(results.get(0).createdTime, OffsetDateTime.now());
    return lastCreated.getSeconds() >= 60 || results.size() < options.dailyRate || Duration.between(results.get(results.size() - 1).createdTime, OffsetDateTime.now()).toHours() > 24;
}
 
Example 10
Source File: DocumentQueueDrainer.java    From extract with MIT License 5 votes vote down vote up
/**
 * Poll the queue for a new file.
 *
 * Will wait for the duration set by {@link #setPollTimeout} or until a file becomes available if no timeout
 * is set.
 *
 * If a {@link SealableLatch} is set, this method will await on that latch before polling and stop when the
 * latch is sealed and signalled. Note that even if a signal is received, there is no guarantee that this
 * method will not return {@code null} if a shared queue is being used.
 *
 * @throws InterruptedException if interrupted while polling
 */
private Path poll() throws InterruptedException {

	// Store the latch and timeout in local constants so that they be used in a thread-safe way.
	final Duration pollTimeout = getPollTimeout();
	final SealableLatch latch = getLatch();

	Path path;

	if (null != latch) {
		path = queue.poll();

		// Wait for a signal from the latch before polling again, but if a signal has been received and the
		// latch has been sealed in the meantime, break.
		while (null == path && !latch.isSealed()) {
			latch.await();
			path = queue.poll();
		}
	} else if (null == pollTimeout) {
		logger.info("Polling the queue, waiting indefinitely.");
		path = queue.take();
	} else if (pollTimeout.getSeconds() > 0) {
		logger.debug(String.format("Polling the queue, waiting up to \"%s\".", pollTimeout));
		path = queue.poll(pollTimeout.getSeconds(), TimeUnit.SECONDS);
	} else {
		logger.debug("Polling the queue without waiting.");
		path = queue.poll();
	}

	return path;
}
 
Example 11
Source File: TimePeriod.java    From java-timeseries with MIT License 5 votes vote down vote up
/**
 * The total amount of time in this time period measured in seconds, the base SI unit of time.
 *
 * @return the total amount of time in this time period measured in seconds.
 */
public double totalSeconds() {
  final double nanoSecondsPerSecond = 1E9;
  Duration thisDuration = this.timeUnit.getDuration();
  double seconds = thisDuration.getSeconds() * this.length;
  double nanos = thisDuration.getNano();
  nanos = (nanos * this.length);
  nanos = (nanos / nanoSecondsPerSecond);
  return seconds + nanos;
}
 
Example 12
Source File: TimeWheel.java    From JavaBase with MIT License 5 votes vote down vote up
private boolean insertWheel(String id, Duration delay) {
  long days = delay.toDays();
  if (days > 30) {
    log.warn("out of timeWheel max delay bound");
    return false;
  }

  long current = System.currentTimeMillis();
  long delayMills = delay.toMillis();
  TaskNode node = new TaskNode(id, null, current, delayMills);
  if (days > 0) {
    return insertWheel(ChronoUnit.DAYS, this.currentDay.get() + days, node);
  }

  long hours = delay.toHours();
  if (hours > 0) {
    return insertWheel(ChronoUnit.HOURS, this.currentHour.get() + hours, node);
  }

  long minutes = delay.toMinutes();
  if (minutes > 0) {
    return insertWheel(ChronoUnit.MINUTES, this.currentMinute.get() + minutes, node);
  }

  long seconds = delay.getSeconds();
  // TODO expire too long time
  if (seconds >= -10 && seconds <= 1) {
    return insertWheel(ChronoUnit.SECONDS, this.currentSecond.get() + 1, node);
  }
  if (seconds > 1) {
    return insertWheel(ChronoUnit.SECONDS, this.currentSecond.get() + seconds, node);
  }

  log.warn("task is expire: id={} delay={}", id, delay);
  return false;
}
 
Example 13
Source File: LagMonitor.java    From LagMonitor with MIT License 5 votes vote down vote up
public static String formatDuration(Duration duration) {
    long seconds = duration.getSeconds();
    return String.format("'%d' days '%d' hours '%d' minutes '%d' seconds'",
            duration.toDays(),
            duration.toHours() % HOURS_PER_DAY,
            duration.toMinutes() % MINUTES_PER_HOUR,
            duration.getSeconds() % SECONDS_PER_MINUTE);
}
 
Example 14
Source File: PackedLocalTime.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
public static int truncatedTo(TemporalUnit unit, int packedTime) {
  if (unit == ChronoUnit.NANOS || unit == ChronoUnit.MILLIS) {
    return packedTime;
  }
  Duration unitDur = unit.getDuration();
  if (unitDur.getSeconds() > SECONDS_PER_DAY) {
    throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation");
  }

  int hour = PackedLocalTime.getHour(packedTime);
  int minute = PackedLocalTime.getMinute(packedTime);
  int second = PackedLocalTime.getSecond(packedTime);
  int milli = 0;

  if (unit == ChronoUnit.DAYS) {
    hour = 0;
    minute = 0;
    second = 0;
  } else if (unit == ChronoUnit.HALF_DAYS) {
    if (hour >= 12) {
      hour = 12;
    } else {
      hour = 0;
    }
    minute = 0;
    second = 0;
  } else if (unit == ChronoUnit.HOURS) {
    minute = 0;
    second = 0;
  } else if (unit == ChronoUnit.MINUTES) {
    second = 0;
  }
  return PackedLocalTime.create(hour, minute, second, milli);
}
 
Example 15
Source File: SawtoothWavePV.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public double[] compute()
{
    final Duration dist = Duration.between(start, Instant.now());
    final double t = dist.getSeconds() + dist.getNano()*1e-9;
    final double x0 = period > 0 ? t / period : 0.0;

    final double[] value = new double[size];
    for (int i=0; i<size; ++i)
    {
        final double x = x0 + i / wavelength;
        value[i] = min + (x - (long)x) * range;
    }
    return value;
}
 
Example 16
Source File: OAuth2AccessToken.java    From okta-sdk-java with Apache License 2.0 4 votes vote down vote up
public boolean hasExpired() {
    Duration duration = Duration.between(this.getIssuedAt(), Instant.now());
    return duration.getSeconds() >= this.getExpiresIn();
}
 
Example 17
Source File: DashboardController.java    From OEE-Designer with MIT License 4 votes vote down vote up
private Float convertDuration(Duration duration, float divisor) {
	float time = ((float) duration.getSeconds()) / divisor;
	return new Float(time);
}
 
Example 18
Source File: CompositeStrokeBar.java    From java-trader with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    Duration dur= DateUtil.between(begin.toLocalDateTime(), end.toLocalDateTime());
    return "CStroke[ "+direction+", B "+DateUtil.date2str(begin.toLocalDateTime())+", "+dur.getSeconds()+"S, O "+open+" C "+close+" H "+high+" L "+low+" ]";
}
 
Example 19
Source File: StrictTransportSecurityHttpHeadersWriter.java    From spring-security-reactive with Apache License 2.0 4 votes vote down vote up
public void setMaxAge(Duration maxAge) {
	this.maxAge = "max-age=" + maxAge.getSeconds();
	updateDelegate();
}
 
Example 20
Source File: DurationTool.java    From axelor-open-suite with GNU Affero General Public License v3.0 2 votes vote down vote up
public static long getSecondsDuration(Duration duration) {

    return duration.getSeconds();
  }