Example usage for java.util Comparator reverseOrder

List of usage examples for java.util Comparator reverseOrder

Introduction

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

Prototype

public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() 

Source Link

Document

Returns a comparator that imposes the reverse of the natural ordering.

Usage

From source file:org.apache.metron.integration.components.FluxTopologyComponent.java

public static void cleanupWorkerDir() {
    if (new File("logs/workers-artifacts").exists()) {
        Path rootPath = Paths.get("logs");
        Path destPath = Paths.get("target/logs");
        try {/*w w w .  j  a  v a  2 s.  c  om*/
            Files.move(rootPath, destPath);
            Files.walk(destPath).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}

From source file:org.ballerinalang.composer.service.fs.LocalFileSystem.java

@Override
public void delete(String path) throws IOException {
    Path ioPath = Paths.get(path);
    if (ioPath.toFile().isDirectory()) {
        Files.walk(ioPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()).map(Path::toFile)
                .forEach(File::delete);
    } else {// w ww  . j  a  v  a 2  s. c  om
        Files.delete(ioPath);
    }
}

From source file:com.haulmont.cuba.web.widgets.CubaTimeField.java

protected Stream<TimeResolution> getResolutionsHigherOrEqualTo(TimeResolution resolution) {
    return Stream.of(TimeResolution.values()).skip(resolution.ordinal()).sorted(Comparator.reverseOrder());
}

From source file:org.tightblog.rendering.requests.WeblogSearchRequest.java

@Override
public WeblogEntryListGenerator.WeblogEntryListData getWeblogEntriesPager() {
    if (pager == null) {
        Map<LocalDate, List<WeblogEntry>> entriesByDateMap = Collections.emptyMap();

        if (searchPhrase != null) {

            // setup the search
            SearchTask searchTask = new SearchTask(searchModel.getLuceneIndexer());
            searchTask.setTerm(searchPhrase);

            if (!searchModel.getThemeManager().getSharedTheme(weblog.getTheme()).isSiteWide()) {
                searchTask.setWeblogHandle(getWeblogHandle());
            }/*from w w  w . j  a v  a  2  s.  c o  m*/

            if (StringUtils.isNotEmpty(category)) {
                searchTask.setCategory(category);
            }

            // execute search
            searchModel.getLuceneIndexer().executeIndexOperationNow(searchTask);

            // -1 indicates a parsing/IO error
            if (searchTask.getResultsCount() >= 0) {
                TopFieldDocs docs = searchTask.getResults();
                ScoreDoc[] hitsArr = docs.scoreDocs;
                this.resultCount = searchTask.getResultsCount();

                // Convert hits into WeblogEntry instances.  Results are mapped by Day -> Set of entries
                // to eliminate any duplicates and then converted into Day -> List map used by pagers
                entriesByDateMap = convertHitsToEntries(hitsArr, searchTask).entrySet().stream().collect(
                        Collectors.toMap(Map.Entry::getKey, e -> new ArrayList<>(e.getValue()), (v1, v2) -> {
                            throw new RuntimeException(
                                    String.format("Duplicate key for values %s and %s", v1, v2));
                        }, () -> new TreeMap<LocalDate, List<WeblogEntry>>(Comparator.reverseOrder())));
            }
        }
        pager = searchModel.getWeblogEntryListGenerator().getSearchPager(weblog, searchPhrase, category,
                getPageNum(), entriesByDateMap, resultCount > (offset + limit));
    }
    return pager;
}

From source file:org.apache.james.mailbox.quota.mailing.subscribers.QuotaThresholdNotice.java

private QuotaThreshold mostSignificantThreshold() {
    return Stream.of(countThreshold, sizeThreshold).flatMap(OptionalUtils::toStream)
            .min(Comparator.reverseOrder()).get();
}

From source file:pt.ist.fenix.ui.spring.PagesAdminService.java

private MenuItem getLastBuiltinContent(Menu menu) {
    return menu.getToplevelItemsSorted().sorted(Comparator.reverseOrder()).filter(isStaticPage.negate())
            .findFirst().orElse(null);//from www .j a  v  a2  s .  c  o m
}

From source file:org.hyperledger.fabric.sdk.helper.SDKUtil.java

/**
 * Delete a file or directory/* w ww.j  ava2  s.  c o m*/
 * @param file {@link File} representing file or directory
 * @throws IOException
 */
public static void deleteFileOrDirectory(File file) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            Path rootPath = Paths.get(file.getAbsolutePath());

            Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                    .map(Path::toFile).forEach(File::delete);
        } else {
            file.delete();
        }
    } else {
        throw new RuntimeException("File or directory does not exist");
    }
}

From source file:com.mesosphere.dcos.cassandra.executor.tasks.RestoreSnapshot.java

@Override
public void run() {
    try {//from   w w w .j a v  a 2 s .c o m
        // Send TASK_RUNNING
        sendStatus(driver, Protos.TaskState.TASK_RUNNING, "Started restoring snapshot");

        if (Objects.equals(context.getRestoreType(), new String("new"))) {
            final String keyspaceDirectory = context.getLocalLocation() + File.separator + context.getName()
                    + File.separator + context.getNodeId();

            final String ssTableLoaderBinary = CassandraPaths.create(version).bin().resolve("sstableloader")
                    .toString();
            final String cassandraYaml = CassandraPaths.create(version).cassandraConfig().toString();

            final File keyspacesDirectory = new File(keyspaceDirectory);
            LOGGER.info("Keyspace Directory {} exists: {}", keyspaceDirectory, keyspacesDirectory.exists());

            final File[] keyspaces = keyspacesDirectory.listFiles();

            String libProcessAddress = System.getenv("LIBPROCESS_IP");
            libProcessAddress = StringUtils.isBlank(libProcessAddress)
                    ? InetAddress.getLocalHost().getHostAddress()
                    : libProcessAddress;

            for (File keyspace : keyspaces) {
                final File[] columnFamilies = keyspace.listFiles();

                final String keyspaceName = keyspace.getName();
                if (keyspaceName.equals(StorageUtil.SCHEMA_FILE))
                    continue;
                LOGGER.info("Going to bulk load keyspace: {}", keyspaceName);

                for (File columnFamily : columnFamilies) {
                    final String columnFamilyName = columnFamily.getName();
                    if (columnFamilyName.equals(StorageUtil.SCHEMA_FILE))
                        continue;
                    LOGGER.info("Bulk loading... keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);

                    final String columnFamilyPath = columnFamily.getAbsolutePath();
                    final List<String> command = Arrays.asList(ssTableLoaderBinary, "-d", libProcessAddress,
                            "-u", context.getUsername(), "-pw", context.getPassword(), "-f", cassandraYaml,
                            columnFamilyPath);
                    LOGGER.info("Executing command: {}", command);

                    final ProcessBuilder processBuilder = new ProcessBuilder(command);
                    processBuilder.redirectErrorStream(true);
                    Process process = processBuilder.start();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        LOGGER.info(line);
                    }

                    int exitCode = process.waitFor();
                    LOGGER.info("Command exit code: {}", exitCode);

                    // Send TASK_ERROR
                    if (exitCode != 0) {
                        final String errMessage = String.format("Error restoring snapshot. Exit code: %s",
                                (exitCode + ""));
                        LOGGER.error(errMessage);
                        sendStatus(driver, Protos.TaskState.TASK_ERROR, errMessage);
                    }

                    LOGGER.info("Done bulk loading! keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);
                }
                LOGGER.info("Successfully bulk loaded keyspace: {}", keyspaceName);
            }
            // cleanup downloaded snapshot directory recursively.
            Path rootPath = Paths.get(context.getLocalLocation() + File.separator + context.getName());
            if (rootPath.toFile().exists()) {
                Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(Path::toFile).forEach(File::delete);
            }
        } else {
            // run nodetool refresh rather than SSTableLoader, as on performance test
            // I/O stream was pretty slow between mesos container processes
            final String localLocation = context.getLocalLocation();
            final List<String> keyspaces = cassandra.getNonSystemKeySpaces();
            for (String keyspace : keyspaces) {
                final String keySpaceDirPath = localLocation + "/" + keyspace;
                File keySpaceDir = new File(keySpaceDirPath);
                File[] cfNames = keySpaceDir
                        .listFiles((current, name) -> new File(current, name).isDirectory());
                for (File cfName : cfNames) {
                    String columnFamily = cfName.getName().substring(0, cfName.getName().indexOf("-"));
                    cassandra.getProbe().loadNewSSTables(keyspace, columnFamily);
                    LOGGER.info("Completed nodetool refresh for keyspace {} & columnfamily {}", keyspace,
                            columnFamily);
                }
            }
        }

        final String message = "Finished restoring snapshot";
        LOGGER.info(message);
        sendStatus(driver, Protos.TaskState.TASK_FINISHED, message);
    } catch (Throwable t) {
        // Send TASK_FAILED
        final String errorMessage = "Failed restoring snapshot. Reason: " + t;
        LOGGER.error(errorMessage, t);
        sendStatus(driver, Protos.TaskState.TASK_FAILED, errorMessage);
    }
}

From source file:api.wiki.WikiGenerator.java

private void removeAllMarkdownFiles(Path wikiDirectory) throws IOException {
    Files.walk(wikiDirectory).sorted(Comparator.reverseOrder()).filter(WikiGenerator::isMarkdownFile)
            .map(Path::toFile).forEach(File::delete);
}

From source file:org.silverpeas.core.util.file.FileFolderManager.java

/**
 * Deletes the specified directory recursively and quietly.
 * @param path the path of a directory//  ww  w.j av  a  2 s .co  m
 */
public static void deleteFolder(final String path) {
    try (final Stream<Path> paths = Files.walk(Paths.get(path))) {
        paths.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
    } catch (IOException e) {
        SilverLogger.getLogger(FileFolderManager.class).warn(e);
    }
}