Example usage for java.time Duration getSeconds

List of usage examples for java.time Duration getSeconds

Introduction

In this page you can find the example usage for java.time Duration getSeconds.

Prototype

public long getSeconds() 

Source Link

Document

Gets the number of seconds in this duration.

Usage

From source file:org.ulyssis.ipp.reader.Reader.java

/**
 * Run the reader. Reader implements runnable, so that we can
 * do this in its own thread./*w w  w.ja  v a 2s. co m*/
 */
@Override
public void run() {
    LOG.info("Spinning up reader!");
    ReaderConfig.Type type = Config.getCurrentConfig().getReader(options.getId()).getType();
    if (type == ReaderConfig.Type.LLRP) {
        initSpeedway();
        if (!speedwayInitialized) {
            shutdownHook();
            return;
        }
    } else if (type == ReaderConfig.Type.SIMULATOR) {
        initSimulator();
    }
    Thread commandThread = new Thread(commandProcessor);
    commandThread.start();
    statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.STARTED_UP,
            String.format("Started up reader %s!", options.getId())));
    try {
        while (!Thread.currentThread().isInterrupted()) {
            Duration maxUpdateInterval = Duration.ofMillis(Config.getCurrentConfig().getMaxUpdateInterval());
            if (maxUpdateInterval.minus(Duration.between(lastUpdate, Instant.now())).isNegative()) {
                lastUpdate = Instant.now();
                LOG.warn("No update received in {} seconds!", maxUpdateInterval.getSeconds());
                statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.NO_UPDATES,
                        String.format("No update received in %s seconds!", maxUpdateInterval.getSeconds())));
            }
            Thread.sleep(1000L);
        }
    } catch (InterruptedException e) {
        // We don't care about this exception
    }
    commandProcessor.stop();
    commandThread.interrupt();
    try {
        commandThread.join();
    } catch (InterruptedException ignored) {
    }
    shutdownHook();
}

From source file:me.ryanhamshire.griefprevention.command.CommandHelper.java

public static Consumer<CommandSource> createBankTransactionsConsumer(CommandSource src, GPClaim claim,
        boolean checkTown, boolean returnToClaimInfo) {
    return settings -> {
        final String name = "Bank Transactions";
        List<String> bankTransactions = new ArrayList<>(
                claim.getData().getEconomyData().getBankTransactionLog());
        Collections.reverse(bankTransactions);
        List<Text> textList = new ArrayList<>();
        textList.add(//from  w w w . j a v  a  2  s  .  c o  m
                Text.builder().append(Text.of(TextColors.WHITE, "\n[", TextColors.AQUA, "Return to bank info",
                        TextColors.WHITE, "]\n")).onClick(TextActions.executeCallback(consumer -> {
                            displayClaimBankInfo(src, claim, checkTown, returnToClaimInfo);
                        })).build());
        Gson gson = new Gson();
        for (String transaction : bankTransactions) {
            GPBankTransaction bankTransaction = gson.fromJson(transaction, GPBankTransaction.class);
            final Duration duration = Duration.between(bankTransaction.timestamp,
                    Instant.now().truncatedTo(ChronoUnit.SECONDS));
            final long s = duration.getSeconds();
            final User user = GriefPreventionPlugin.getOrCreateUser(bankTransaction.source);
            final String timeLeft = String.format("%dh %02dm %02ds", s / 3600, (s % 3600) / 60, (s % 60))
                    + " ago";
            textList.add(Text.of(getTransactionColor(bankTransaction.type), bankTransaction.type.name(),
                    TextColors.BLUE, " | ", TextColors.WHITE, bankTransaction.amount, TextColors.BLUE, " | ",
                    TextColors.GRAY, timeLeft, user == null ? ""
                            : Text.of(TextColors.BLUE, " | ", TextColors.LIGHT_PURPLE, user.getName())));
        }
        textList.add(Text.builder()
                .append(Text.of(TextColors.WHITE, "\n[", TextColors.AQUA, "Return to bank info",
                        TextColors.WHITE, "]\n"))
                .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claimbank", "")))
                .build());
        PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
        PaginationList.Builder paginationBuilder = paginationService.builder()
                .title(Text.of(TextColors.AQUA, name)).padding(Text.of(TextStyles.STRIKETHROUGH, "-"))
                .contents(textList);
        paginationBuilder.sendTo(src);
    };
}

From source file:me.ryanhamshire.griefprevention.command.CommandHelper.java

public static void displayClaimBankInfo(CommandSource src, GPClaim claim, boolean checkTown,
        boolean returnToClaimInfo) {
    final EconomyService economyService = GriefPreventionPlugin.instance.economyService.orElse(null);
    if (economyService == null) {
        GriefPreventionPlugin.sendMessage(src,
                GriefPreventionPlugin.instance.messageData.economyNotInstalled.toText());
        return;/*  w w  w  . j a va2  s .  co  m*/
    }

    if (checkTown && !claim.isInTown()) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.townNotIn.toText());
        return;
    }

    if (!checkTown && (claim.isSubdivision() || claim.isAdminClaim())) {
        return;
    }

    final GPClaim town = claim.getTownClaim();
    Account bankAccount = checkTown ? town.getEconomyAccount().orElse(null)
            : claim.getEconomyAccount().orElse(null);
    if (bankAccount == null) {
        GriefPreventionPlugin.sendMessage(src,
                GriefPreventionPlugin.instance.messageData.economyVirtualNotSupported.toText());
        return;
    }

    final GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getPlayerData(claim.getWorld(),
            claim.getOwnerUniqueId());
    final double claimBalance = bankAccount.getBalance(economyService.getDefaultCurrency()).doubleValue();
    double taxOwed = -1;
    final double playerTaxRate = GPOptionHandler.getClaimOptionDouble(playerData.getPlayerSubject(), claim,
            GPOptions.Type.TAX_RATE, playerData);
    if (checkTown) {
        if (!town.getOwnerUniqueId().equals(playerData.playerID)) {
            for (Claim playerClaim : playerData.getInternalClaims()) {
                GPClaim playerTown = (GPClaim) playerClaim.getTown().orElse(null);
                if (!playerClaim.isTown() && playerTown != null
                        && playerTown.getUniqueId().equals(claim.getUniqueId())) {
                    taxOwed += (playerTown.getClaimBlocks() / 256) * playerTaxRate;
                }
            }
        } else {
            taxOwed = town.getClaimBlocks() * playerTaxRate;
        }
    } else {
        taxOwed = claim.getClaimBlocks() * playerTaxRate;
    }

    final GriefPreventionConfig<?> activeConfig = GriefPreventionPlugin
            .getActiveConfig(claim.getWorld().getProperties());
    final ZonedDateTime withdrawDate = TaskUtils
            .getNextTargetZoneDate(activeConfig.getConfig().claim.taxApplyHour, 0, 0);
    Duration duration = Duration.between(Instant.now().truncatedTo(ChronoUnit.SECONDS),
            withdrawDate.toInstant());
    final long s = duration.getSeconds();
    final String timeLeft = String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));
    final Text message = GriefPreventionPlugin.instance.messageData.claimBankInfo
            .apply(ImmutableMap.of("balance", claimBalance, "amount", taxOwed, "time_remaining", timeLeft,
                    "tax_balance", claim.getData().getEconomyData().getTaxBalance()))
            .build();
    Text transactions = Text.builder().append(Text.of(TextStyles.ITALIC, TextColors.AQUA, "Bank Transactions"))
            .onClick(TextActions
                    .executeCallback(createBankTransactionsConsumer(src, claim, checkTown, returnToClaimInfo)))
            .onHover(TextActions.showText(Text.of("Click here to view bank transactions"))).build();
    List<Text> textList = new ArrayList<>();
    if (returnToClaimInfo) {
        textList.add(Text.builder()
                .append(Text.of(TextColors.WHITE, "\n[", TextColors.AQUA, "Return to claim info",
                        TextColors.WHITE, "]\n"))
                .onClick(TextActions.executeCallback(CommandHelper.createCommandConsumer(src, "claiminfo", "")))
                .build());
    }
    textList.add(message);
    textList.add(transactions);
    PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
    PaginationList.Builder paginationBuilder = paginationService.builder()
            .title(Text.of(TextColors.AQUA, "Bank Info")).padding(Text.of(TextStyles.STRIKETHROUGH, "-"))
            .contents(textList);
    paginationBuilder.sendTo(src);
}

From source file:io.pravega.segmentstore.server.host.ZKSegmentContainerMonitor.java

@VisibleForTesting
@SneakyThrows(Exception.class)
public void initialize(Duration monitorInterval) {
    Exceptions.checkNotClosed(closed.get(), this);

    // Start loading the segment container to node assigment map from zookeeper.
    this.hostContainerMapNode.start();

    // There are two triggers for the segment container monitor.
    // 1. On any segment container ownership changes notified via zookeeper. We will ensure the local containers
    //      are stopped/started according to the new ownership mapping.
    // 2. At scheduled intervals to perform retries on local segment container start failures.
    this.assigmentTask.set(this.executor.scheduleWithFixedDelay(this::checkAssignment, 0L,
            monitorInterval.getSeconds(), TimeUnit.SECONDS));
    this.hostContainerMapNode.getListenable().addListener(this::checkAssignment, this.executor);
}

From source file:com.vmware.vchs.base.DbaasApi.java

protected int loadDataBySize(MsSqlDataLoader msSqlDataLoader, String dbName, String tableName,
        long totalSizeInMB) throws Exception {
    msSqlDataLoader.useDatabase(dbName);
    msSqlDataLoader.createTable(tableName);
    int i = 1;//from  w  w w  .  ja va 2 s  .c  o m
    Instant totalStart = Instant.now();
    while (msSqlDataLoader.getDBSize() * 8 / 1024 < totalSizeInMB) {
        Instant start = Instant.now();
        msSqlDataLoader.insert(tableName, configuration.getTestFile());
        Duration duration = Duration.between(start, Instant.now());
        logger.info("Blob " + i + " took " + duration.getSeconds() + " seconds.");
        i++;
    }
    Duration totalDuration = Duration.between(totalStart, Instant.now());
    logger.info("Totally took " + totalDuration.getSeconds() + " seconds.");
    return i;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java

@Override
public void registerRenewer(X509MaterialParameter parameter) {
    if (!isHopsTLSEnabled()) {
        return;/*from w ww  . j  a va2s .  c  o m*/
    }
    if (!renewalTasks.containsKey(parameter.getApplicationId())) {
        LocalDateTime now = DateUtils.getNow();
        LocalDateTime expirationDate = DateUtils.unixEpoch2LocalDateTime(parameter.getExpiration());

        Duration validityPeriod = Duration.between(now, expirationDate);
        Duration delay = validityPeriod.minus(amountOfTimeToSubstractFromExpiration, renewalUnitOfTime);

        ScheduledFuture renewTask = renewalExecutorService
                .schedule(createCertificateRenewerTask(parameter.getApplicationId(), parameter.appUser,
                        parameter.cryptoMaterialVersion), delay.getSeconds(), TimeUnit.SECONDS);
        renewalTasks.put(parameter.getApplicationId(), renewTask);
    }
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private byte[] createThumbnail(final String videoFilePath) throws IOException, InterruptedException {
    Duration videoDuration = null;

    try {//from w  w  w  .j a  v  a 2 s  .c  om
        videoDuration = getVideoDuration(videoFilePath);
    } catch (Exception e) {
        LOGGER.warn("Couldn't get video duration from FFmpeg output.", e);
    }

    /* Realistically, to get good thumbnails by dividing a video into segments, the video
     should be at least 10 seconds long. This is because FFmpeg looks for thumbnails in
     batches of 100 frames each, and these frames usually come from the portion of the
     video immediately following the seek position. If the video isn't long enough,
     the regions of the video FFmpeg will pick thumbnails from will likely overlap,
     causing the same thumbnail to be generated for multiple segments. */
    if (videoDuration != null && videoDuration.getSeconds() > ROUGH_MINIMUM_SECONDS_FOR_MULTIPLE_THUMBNAILS) {
        return createGifThumbnailWithDuration(videoFilePath, videoDuration);
    } else {
        return createThumbnailWithoutDuration(videoFilePath);
    }
}

From source file:com.publictransitanalytics.scoregenerator.output.TimeQualifiedPointAccessibility.java

public TimeQualifiedPointAccessibility(final PathScoreCard scoreCard, final Grid grid, final Center center,
        final LocalDateTime time, final Duration tripDuration, final boolean backward,
        final Duration inServiceTime) throws InterruptedException {
    type = AccessibilityType.TIME_QUALIFIED_POINT_ACCESSIBILITY;
    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    this.center = new Point(center.getLogicalCenter().getPointRepresentation());
    this.time = time.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));

    this.tripDuration = DurationFormatUtils.formatDurationWords(tripDuration.toMillis(), true, true);
    final ImmutableMap.Builder<Bounds, FullSectorReachInformation> builder = ImmutableMap.builder();

    final TaskIdentifier task = new TaskIdentifier(time, center);

    final Set<Sector> sectors = grid.getAllSectors();
    for (final Sector sector : sectors) {
        final MovementPath sectorPath = scoreCard.getBestPath(sector, task);
        if (sectorPath != null) {
            final Bounds sectorBounds = new Bounds(sector);

            builder.put(sectorBounds, new FullSectorReachInformation(sectorPath));
        }/*from  w w  w.jav a  2  s  . com*/
    }
    sectorPaths = builder.build();
    totalSectors = grid.getReachableSectors().size();
    inServiceSeconds = inServiceTime.getSeconds();
}

From source file:com.vmware.vchs.base.DbaasApi.java

protected long getCycleAsSeconds(String cycle) {
    checkNotNull(cycle);//from www  .j a v  a  2s.c  o  m
    String[] cycleValues = cycle.split(":");
    int length = cycleValues.length;
    Duration seconds;
    if (length == 4) {
        Duration days = Duration.ofDays(Long.parseLong(cycleValues[length - 4]));
        Duration hours = days.plusHours(Long.parseLong(cycleValues[length - 3]));
        Duration minutes = hours.plusMinutes(Long.parseLong(cycleValues[length - 2]));
        seconds = minutes.plusSeconds(Long.parseLong(cycleValues[length - 1]));
    } else {
        throw new FailException("Invalid cycle value" + cycle);
    }
    return seconds.getSeconds();
}

From source file:com.publictransitanalytics.scoregenerator.output.NetworkAccessibility.java

public NetworkAccessibility(final int taskCount, final ScoreCard scoreCard, final Grid grid,
        final Set<Sector> centerSectors, final LocalDateTime startTime, final LocalDateTime endTime,
        final Duration tripDuration, final Duration samplingInterval, final boolean backward,
        final Duration inServiceTime) throws InterruptedException {
    type = AccessibilityType.NETWORK_ACCESSIBILITY;

    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    boundsCenter = new Point(grid.getBounds().getCenter());
    this.startTime = startTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.endTime = endTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.samplingInterval = DurationFormatUtils.formatDurationWords(samplingInterval.toMillis(), true, true);

    this.tripDuration = DurationFormatUtils.formatDurationWords(tripDuration.toMillis(), true, true);

    this.taskCount = taskCount;

    final Set<Sector> sectors = grid.getAllSectors();
    totalSectors = grid.getReachableSectors().size();

    final ImmutableMap.Builder<Bounds, Integer> countBuilder = ImmutableMap.builder();
    for (final Sector sector : sectors) {
        if (scoreCard.hasPath(sector)) {
            final Bounds bounds = new Bounds(sector);
            countBuilder.put(bounds, scoreCard.getReachedCount(sector));
        }/* w  w  w .  j a  v  a 2s.c o m*/
    }
    sectorCounts = countBuilder.build();

    this.centerPoints = centerSectors.stream().map(sector -> new Point(sector.getBounds().getCenter()))
            .collect(Collectors.toSet());
    sampleCount = centerPoints.size();

    inServiceSeconds = inServiceTime.getSeconds();
}