Example usage for java.util Comparator comparingLong

List of usage examples for java.util Comparator comparingLong

Introduction

In this page you can find the example usage for java.util Comparator comparingLong.

Prototype

public static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) 

Source Link

Document

Accepts a function that extracts a long sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:io.pravega.controller.task.Stream.StreamMetadataTasks.java

/**
 * Method to check retention policy and generate new periodic cuts and/or truncate stream at an existing stream cut.
 * // www  .  j av a 2  s  . c o  m
 * @param scope scope
 * @param stream stream
 * @param policy retention policy
 * @param recordingTime time of recording
 * @param contextOpt operation context
 * @return future.
 */
public CompletableFuture<Void> retention(final String scope, final String stream, final RetentionPolicy policy,
        final long recordingTime, final OperationContext contextOpt) {
    Preconditions.checkNotNull(policy);
    final OperationContext context = contextOpt == null ? streamMetadataStore.createContext(scope, stream)
            : contextOpt;

    return streamMetadataStore.getStreamCutsFromRetentionSet(scope, stream, context, executor)
            .thenCompose(retentionSet -> {
                StreamCutRecord latestCut = retentionSet.stream()
                        .max(Comparator.comparingLong(StreamCutRecord::getRecordingTime)).orElse(null);
                return checkGenerateStreamCut(scope, stream, context, policy, latestCut, recordingTime)
                        .thenCompose(
                                x -> truncate(scope, stream, policy, context, retentionSet, recordingTime));
            });

}

From source file:com.mycompany.wolf.Room.java

private void notifyWitchSave() {
    ScheduledFuture[] holder = new ScheduledFuture[1];
    holder[0] = scheduledExecutorService.schedule(() -> {
        holder[0].cancel(true);// w w w.j  av  a2  s  .  c o  m
        notifyHunterKillIfDead();
    }, WITCH_SAVE_DURATION, TimeUnit.MILLISECONDS);

    /*
     *  
     */
    List<Map.Entry<String, Long>> top2 = wolfVotings.values().stream()
            .collect(Collectors.groupingBy(wolfVoting -> wolfVoting.playerId, Collectors.counting())).entrySet()
            .stream()
            .sorted(Comparator.comparingLong((Map.Entry<String, Long> entry) -> entry.getValue()).reversed())
            .limit(2).collect(Collectors.toList());
    if (top2.size() == 1 || (top2.size() > 1 && top2.get(0).getValue().compareTo(top2.get(1).getValue()) > 0)) {
        theVoted = top2.get(0).getKey();
    } else if (top2.size() > 1) {
        theVoted = top2.get(0).getKey();
    } else {
        List<String> undead = sessions.stream()
                .filter(session -> !WOLF.equals(session.getUserProperties().get("role")))
                .map(session -> getPlayerId(session)).filter(((Predicate<String>) dead::contains).negate())
                .collect(Collectors.toList());
        theVoted = undead.get(new Random().nextInt(undead.size()));
    }
    newlyDead.add(theVoted);

    /*
     * ? 
     */
    witchPoisonings.values().stream().map(witchPoisoning -> witchPoisoning.playerId).forEach(newlyDead::add);

    Map<String, Object> notifyWolfVoted = ImmutableMap.of("code", "notifyWolfVoted", "properties",
            ImmutableMap.of("playerId", theVoted));
    String jsonText = JsonUtils.toString(notifyWolfVoted);
    sessions.stream().forEach(s -> {
        s.getAsyncRemote().sendText(jsonText);
    });
}

From source file:com.github.ambry.store.DiskReformatter.java

/**
 * Uses {@link StoreCopier} to convert all the partitions on the given disk (D).
 * 1. Copies one partition on D to a scratch space
 * 2. Using {@link StoreCopier}, performs copies of all other partitions on D using D as a staging area. When a
 * partition is completely copied and verified, the original is replaced by the copy.
 * 3. Copies the partition in the scratch space back onto D.
 * 4. Deletes the folder in the scratch space
 * @param diskMountPath the mount path of the disk to reformat
 * @param scratch the scratch space to use
 * @throws Exception/*from   w  ww  .j a v  a 2s.  co m*/
 */
public void reformat(String diskMountPath, File scratch) throws Exception {
    if (!scratch.exists()) {
        throw new IllegalArgumentException("Scratch space " + scratch + " does not exist");
    }
    List<ReplicaId> replicasOnDisk = new ArrayList<>();
    // populate the replicas on disk
    List<? extends ReplicaId> replicaIds = clusterMap.getReplicaIds(dataNodeId);
    for (ReplicaId replicaId : replicaIds) {
        if (replicaId.getDiskId().getMountPath().equals(diskMountPath)) {
            replicasOnDisk.add(replicaId);
        }
    }
    if (replicasOnDisk.size() == 0) {
        throw new IllegalArgumentException("There are no replicas on " + diskMountPath + " of " + dataNodeId);
    }
    replicasOnDisk.sort(Comparator.comparingLong(ReplicaId::getCapacityInBytes));
    logger.info("Found {} on {}", replicasOnDisk, diskMountPath);

    // move the last replica id (the largest one) to scratch space
    ReplicaId toMove = replicasOnDisk.get(replicasOnDisk.size() - 1);
    String partIdString = toMove.getPartitionId().toString();
    File scratchSrc = new File(toMove.getReplicaPath());
    File scratchTmp = new File(scratch, partIdString + RELOCATION_IN_PROGRESS_SUFFIX);
    File scratchTgt = new File(scratch, partIdString + RELOCATED_DIR_NAME_SUFFIX);
    if (scratchTmp.exists()) {
        throw new IllegalStateException(scratchTmp + " already exists");
    }
    if (scratchTgt.exists()) {
        throw new IllegalStateException(scratchTgt + " already exists");
    }
    ensureNotInUse(scratchSrc, toMove.getCapacityInBytes());
    logger.info("Moving {} to {}", scratchSrc, scratchTgt);
    FileUtils.moveDirectory(scratchSrc, scratchTmp);
    if (!scratchTmp.renameTo(scratchTgt)) {
        throw new IllegalStateException("Could not rename " + scratchTmp + " to " + scratchTgt);
    }

    // reformat each store, except the one moved, one by one
    for (int i = 0; i < replicasOnDisk.size() - 1; i++) {
        ReplicaId replicaId = replicasOnDisk.get(i);
        partIdString = replicaId.getPartitionId().toString();
        File src = new File(replicaId.getReplicaPath());
        File tgt = new File(replicaId.getMountPath(), partIdString + UNDER_REFORMAT_DIR_NAME_SUFFIX);
        logger.info("Copying {} to {}", src, tgt);
        copy(partIdString, src, tgt, replicaId.getCapacityInBytes());
        logger.info("Deleting {}", src);
        Utils.deleteFileOrDirectory(src);
        logger.info("Renaming {} to {}", tgt, src);
        if (!tgt.renameTo(src)) {
            throw new IllegalStateException("Could not rename " + tgt + " to " + src);
        }
        logger.info("Done reformatting {}", replicaId);
    }

    // reformat the moved store
    logger.info("Copying {} to {}", scratchTgt, scratchSrc);
    copy(toMove.getPartitionId().toString(), scratchTgt, scratchSrc, toMove.getCapacityInBytes());
    logger.info("Deleting {}", scratchTgt);
    Utils.deleteFileOrDirectory(scratchTgt);
    logger.info("Done reformatting {}", toMove);
    logger.info("Done reformatting disk {}", diskMountPath);
}

From source file:io.pravega.controller.task.Stream.StreamMetadataTasks.java

private Optional<StreamCutRecord> findTruncationRecord(RetentionPolicy policy,
        List<StreamCutRecord> retentionSet, long recordingTime) {
    switch (policy.getRetentionType()) {
    case TIME:/* w  ww . j  a  v a  2 s  . c o m*/
        return retentionSet.stream()
                .filter(x -> x.getRecordingTime() < recordingTime - policy.getRetentionParam())
                .max(Comparator.comparingLong(StreamCutRecord::getRecordingTime));
    case SIZE:
    default:
        throw new NotImplementedException("Size based retention");
    }
}

From source file:com.mycompany.wolf.Room.java

private void notifySomeoneBeVoted() {
    Collection<String> newlyDead = new LinkedHashSet<>();

    List<Map.Entry<String, Long>> top2 = playerVotings.values().stream()
            .collect(Collectors.groupingBy(playerVoting -> playerVoting.playerId, Collectors.counting()))
            .entrySet().stream()//from  w ww  .  j  av a 2 s.  c o m
            .sorted(Comparator.comparingLong((Map.Entry<String, Long> entry) -> entry.getValue()).reversed())
            .limit(2).collect(Collectors.toList());
    if (top2.size() == 1
            || (top2.size() == 2 && top2.get(0).getValue().compareTo(top2.get(1).getValue()) > 0)) {
        newlyDead.add(top2.get(0).getKey());
        this.dead.add(top2.get(0).getKey());

        if (sessions.stream().noneMatch(session -> WOLF.equals(session.getUserProperties().get("role")))) {
            wolvesLose();
        }
    }

    Map<String, Object> notifyDead = ImmutableMap.of("code", "notifyDead", "properties", newlyDead);
    String jsonText = JsonUtils.toString(notifyDead);
    sessions.stream().forEach(s -> s.getAsyncRemote().sendText(jsonText));

    notifyWolvesKillVillagers();
}

From source file:com.gnadenheimer.mg.utils.Utils.java

public void backUpIfOld() {
    try {/*  w ww  .j  a  v a  2 s.  co  m*/
        Path dir = Paths.get(getPersistenceMap().get("backUpDir")); // specify your directory

        Optional<Path> lastFilePath = Files.list(dir) // here we get the stream with full directory listing
                .filter(f -> Files.isDirectory(f)) // exclude files from listing
                .max(Comparator.comparingLong(f -> f.toFile().lastModified())); // finally get the last file using simple comparator by lastModified field

        if (lastFilePath.isPresent()) // your folder may be empty
        {
            FileTime fileTime = Files.getLastModifiedTime(lastFilePath.get());
            Long age = DAYS.between(LocalDateTime.ofInstant(fileTime.toInstant(), ZoneOffset.UTC),
                    LocalDateTime.now());
            if (age > 7) {
                exectueBackUp(getPersistenceMap().get("backUpDir"));
            }
        } else {
            exectueBackUp(getPersistenceMap().get("backUpDir"));
        }
    } catch (Exception ex) {
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
    }
}

From source file:com.gnadenheimer.mg.utils.Utils.java

/**
 * Delete AutoBackUps if older than 60 days
 *///w  w  w.  jav  a 2 s.c  o  m
public void deleteOldBackUps() {
    try {
        Path dir = Paths.get(getPersistenceMap().get("backUpDir")); // specify your directory

        Optional<Path> lastFilePath = Files.list(dir) // here we get the stream with full directory listing
                .filter(f -> Files.isDirectory(f)) // exclude files from listing
                .min(Comparator.comparingLong(f -> f.toFile().lastModified())); // finally get the last file using simple comparator by lastModified field

        if (lastFilePath.isPresent()) // your folder may be empty
        {
            FileTime fileTime = Files.getLastModifiedTime(lastFilePath.get());
            Long age = DAYS.between(LocalDateTime.ofInstant(fileTime.toInstant(), ZoneOffset.UTC),
                    LocalDateTime.now());
            if (age > 30) {
                Files.walk(lastFilePath.get(), FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(Path::toFile).peek(System.out::println).forEach(File::delete);
                deleteOldBackUps();
            }
        }
    } catch (Exception ex) {
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
    }
}

From source file:enumj.EnumerableTest.java

@Test
public void testZipAll() {
    System.out.println("zipAll");
    EnumerableGenerator.generators().limit(100)
            .map(gen -> Enumerator//from w w w .java2s.  c o m
                    .on((Enumerable) gen.repeatable(), gen.repeatable(), gen.repeatable(), gen.repeatable())
                    .toArray(Enumerable.class))
            .map(arr -> {
                final Enumerable<Double> first = arr[0];
                final Enumerable<Double> second = arr[1];
                final Enumerable<Double> third = arr[2];
                final Enumerable<Double> fourth = arr[3];
                final Enumerable[] result = new Enumerable[5];

                result[0] = first;
                result[1] = second;
                result[2] = third;
                result[3] = fourth;
                result[4] = first.zipAll(second, third, fourth);

                return result;
            })
            .forEach(arr -> assertEquals("", arr[4].enumerator().count(),
                    Enumerator.on(arr[0].enumerator().count(), arr[1].enumerator().count(),
                            arr[2].enumerator().count()).max(Comparator.comparingLong(x -> x)).get(),
                    0.000001));
}

From source file:org.apache.gobblin.util.PullFileLoader.java

private List<Config> getSortedConfigs(List<ConfigWithTimeStamp> configsWithTimeStamps) {
    List<Config> sortedConfigs = Lists.newArrayList();
    Collections.sort(configsWithTimeStamps, Comparator.comparingLong(o -> o.timeStamp));
    for (ConfigWithTimeStamp configWithTimeStamp : configsWithTimeStamps) {
        sortedConfigs.add(configWithTimeStamp.config);
    }/*from  w  ww .  j  av  a  2 s. c om*/
    return sortedConfigs;
}

From source file:org.cloudsimplus.migration.VmMigrationWhenCpuMetricIsViolatedExampleWithSelectedVm.java

/**
 * Selects a VM to run a Cloudlet that will minimize the Cloudlet response
 * time./*  www  .  ja v a2s  .  com*/
 *
 * @param cloudlet the Cloudlet to select a VM to
 * @return the selected Vm
 */
private Vm selectVmForCloudlet(Cloudlet cloudlet) {
    List<Vm> createdVms = cloudlet.getBroker().getVmsCreatedList();
    Log.printLine("\t\tCreated VMs: " + createdVms);
    Comparator<Vm> sortByNumberOfFreePes = Comparator.comparingLong(vm -> getExpectedNumberOfFreeVmPes(vm));
    Comparator<Vm> sortByExpectedCloudletResponseTime = Comparator
            .comparingDouble(vm -> getExpectedCloudletResponseTime(cloudlet, vm));
    createdVms.sort(sortByNumberOfFreePes.thenComparing(sortByExpectedCloudletResponseTime).reversed());
    Vm mostFreePesVm = createdVms.stream().findFirst().orElse(Vm.NULL);

    Vm selectedVm = createdVms.stream()
            .filter(vm -> getExpectedNumberOfFreeVmPes(vm) >= cloudlet.getNumberOfPes())
            .filter(vm -> getExpectedCloudletResponseTime(cloudlet, vm) <= responseTimeSlaContract).findFirst()
            .orElse(mostFreePesVm);

    return selectedVm;
}