List of usage examples for java.util Comparator reverseOrder
public static <T extends Comparable<? super T>> Comparator<T> reverseOrder()
From source file:org.eclipse.jdt.ls.core.internal.JDTUtilsTest.java
@Test public void testFakeCompilationUnit() throws Exception { String tempDir = System.getProperty("java.io.tmpdir"); File dir = new File(tempDir, "/test/src/org/eclipse"); dir.mkdirs();//from w ww. j a va2s . c o m File file = new File(dir, "Test.java"); file.createNewFile(); URI uri = file.toURI(); JDTUtils.resolveCompilationUnit(uri); IProject project = WorkspaceHelper.getProject(ProjectsManager.DEFAULT_PROJECT_NAME); IFile iFile = project.getFile("/src/org/eclipse/Test.java"); assertTrue(iFile.getFullPath().toString() + " doesn't exist.", iFile.exists()); Path path = Paths.get(tempDir + "/test"); Files.walk(path, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()).map(Path::toFile) .forEach(File::delete); }
From source file:dk.dma.dmiweather.service.FTPLoader.java
private static void deleteRecursively(File lastTempDir) throws IOException { Path rootPath = lastTempDir.toPath(); //noinspection ResultOfMethodCallIgnored Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) // flips the tree so leefs are deleted first .map(Path::toFile).peek(f -> log.debug("deleting file " + f.getAbsolutePath())) .forEach(File::delete); }
From source file:net.dv8tion.jda.core.entities.impl.GuildImpl.java
@Override public List<TextChannel> getTextChannels() { ArrayList<TextChannel> channels = new ArrayList<>(textChannels.valueCollection()); channels.sort(Comparator.reverseOrder()); return Collections.unmodifiableList(channels); }
From source file:it.greenvulcano.configuration.BaseConfigurationManager.java
@Override public void deploy(String name) throws XMLConfigException, FileNotFoundException { Path configurationArchivePath = getConfigurationPath(name); Path current = Paths.get(XMLConfig.getBaseConfigPath()); Path staging = current.getParent().resolve("deploy"); Path destination = current.getParent().resolve(name); if (LOCK.tryLock()) { if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) { try { ZipInputStream configurationArchive = new ZipInputStream( Files.newInputStream(configurationArchivePath, StandardOpenOption.READ)); LOG.debug("Starting deploy of configuration " + name); ZipEntry zipEntry = null; for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) { if (!Files.isDirectory(cfgFile)) { Path target = staging.resolve(current.relativize(cfgFile)); Files.createDirectories(target); Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING); }/*from w w w . ja v a2 s .c o m*/ } LOG.debug("Staging new config " + name); while ((zipEntry = configurationArchive.getNextEntry()) != null) { Path entryPath = staging.resolve(zipEntry.getName()); LOG.debug("Adding resource: " + entryPath); if (zipEntry.isDirectory()) { entryPath.toFile().mkdirs(); } else { Path parent = entryPath.getParent(); if (!Files.exists(parent)) { Files.createDirectories(parent); } Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING); } } //**** Deleting old config dir LOG.debug("Removing old config: " + current); Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); LOG.debug("Deploy new config " + name + " in path " + destination); Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE); setXMLConfigBasePath(destination.toString()); LOG.debug("Deploy complete"); deployListeners.forEach(l -> l.onDeploy(destination)); } catch (Exception e) { if (Objects.nonNull(staging) && Files.exists(staging)) { LOG.error("Deploy failed, rollback to previous configuration", e); try { Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); setXMLConfigBasePath(current.toString()); } catch (IOException | InvalidSyntaxException rollbackException) { LOG.error("Failed to delete old configuration", e); } } else { LOG.error("Deploy failed", e); } throw new XMLConfigException("Deploy failed", e); } finally { LOCK.unlock(); } } else { throw new FileNotFoundException(configurationArchivePath.toString()); } } else { throw new IllegalStateException("A deploy is already in progress"); } }
From source file:net.dv8tion.jda.core.entities.impl.GuildImpl.java
@Override public List<VoiceChannel> getVoiceChannels() { List<VoiceChannel> channels = new ArrayList<>(voiceChannels.valueCollection()); channels.sort(Comparator.reverseOrder()); return Collections.unmodifiableList(channels); }
From source file:org.silverpeas.core.util.file.FileUtil.java
/** * Forces the deletion of the specified file. If the write property of the file to delete isn't * set, this property is then set before deleting. * * @param fileToDelete file to delete./*from w w w . j a va 2s. c om*/ * @throws IOException if the deletion failed or if the file doesn't exist. */ public static void forceDeletion(File fileToDelete) throws IOException { if (fileToDelete.exists() && !fileToDelete.canWrite()) { fileToDelete.setWritable(true); } try (Stream<Path> paths = Files.walk(fileToDelete.toPath())) { paths.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); } }
From source file:net.dv8tion.jda.core.entities.impl.GuildImpl.java
@Override public List<Role> getRoles() { List<Role> list = new ArrayList<>(roles.valueCollection()); list.sort(Comparator.reverseOrder()); return Collections.unmodifiableList(list); }
From source file:net.di2e.ecdr.describe.generator.DescribeGeneratorImpl.java
protected Describe createDescribeRecord(String sourceId, Map<String, String> resultProperties) { Describe describe = new Describe(); boolean hasMoreRecords = true; Date startDate = StringUtils.isBlank(generatorConfig.getStartDate()) ? null : formatter.parseDateTime(generatorConfig.getStartDate()).toDate(); Date endDate = new Date(); String queryKeywords = generatorConfig.getKeywords(); Collection collection = new Collection(); describe.getCollection().add(collection); ContentCollectionType contentCollection = new ContentCollectionType(); collection.setContentCollection(contentCollection); contentCollection.setOriginator(this.generatorConfig.getCollectionOriginator()); contentCollection//from w ww .j a v a2 s . c o m .setClassification(CVEnumISMClassificationAll.fromValue(this.generatorConfig.getClassification())); contentCollection.setOwnerProducer(this.generatorConfig.getOwnerProducer()); ResourceType resource = new ResourceType(); collection.setResource(resource); CompoundResourceIdentifierType identifier = new CompoundResourceIdentifierType(); identifier.setQualifier("GUIDE"); identifier.setValue("guide://999715/" + UUID.randomUUID()); resource.getIdentifier().add(identifier); TitleType title = new TitleType(); title.setValue("Describe Record: " + sourceId); resource.setTitle(Arrays.asList(new TitleType[] { title })); DescriptionType descType = new DescriptionType(); descType.setValue("Generated CDR Describe record for site \'" + sourceId + "\' - generated by " + this.generatorConfig.getCollectionOriginator()); resource.setDescription(descType); LOGGER.debug("Generating Content Colleciton details for site {}", sourceId); HashMap<String, TemporalCoverageHolder> timeMap = new HashMap<>(); Envelope geoEnvelope = new Envelope(); int maxRecordCount = this.generatorConfig.getMaxRecordsPerPoll(); ConcurrentHashMap<String, Long> keywordCounter = new ConcurrentHashMap<>(); ConcurrentHashMap<QualifierValueHolder, Long> sourceCounter = new ConcurrentHashMap<>(); ConcurrentHashMap<SecurityType, Long> secCounter = new ConcurrentHashMap<>(); ConcurrentHashMap<CompoundCategoryIdentifierType, Long> categoryCounter = new ConcurrentHashMap<>(); ConcurrentHashMap<CompoundTypeIdentifierType, Long> typeCounter = new ConcurrentHashMap<>(); ConcurrentHashMap<String, Long> mimeCounter = new ConcurrentHashMap<>(); ConcurrentHashMap<String, Long> contentTypeCounter = new ConcurrentHashMap<>(); try { while (hasMoreRecords) { QueryImpl query = new QueryImpl(this.getFilter(startDate, endDate, queryKeywords), 1, maxRecordCount, this.getSortBy(), true, 300000L); QueryRequestImpl queryRequest = new QueryRequestImpl(query, Arrays.asList(new String[] { sourceId })); queryRequest.setProperties(this.requestProperties); QueryResponse response = this.framework.query(queryRequest); contentCollection.setUpdated(dtf.newXMLGregorianCalendar(new GregorianCalendar())); MetricsType metrics = new MetricsType(); contentCollection.setMetrics(metrics); if (metrics.getCount() == 0) { metrics.setCount(response.getHits()); } List<Result> results = response.getResults(); hasMoreRecords = (results.size() == maxRecordCount) && startDate != null; LOGGER.debug( "Adding details from query results for {} records from site {} in the Content Collection date range [{} - {}] and keywords[{}]", Integer.valueOf(results.size()), sourceId, startDate, endDate, queryKeywords); for (Result result : results) { try { Metacard metacard = result.getMetacard(); populateTemporalCoverage(timeMap, metacard); populateGeoCoverage(geoEnvelope, metacard); populateContentType(contentTypeCounter, metacard); String metadata = metacard.getMetadata(); if (StringUtils.isNotBlank(metadata)) { // Populate MIME Types XPathHelper xpathHelper = new XPathHelper(metadata); populateMIMEType(sourceId, mimeCounter, result, metacard, xpathHelper); // populate source populateSource(sourceId, sourceCounter, result, metacard, xpathHelper); // Populate Keywords populateKeywords(sourceId, keywordCounter, metacard, xpathHelper); // Populate Category populateCategory(sourceId, categoryCounter, metacard, xpathHelper); // Populate Type populateType(sourceId, typeCounter, metacard, xpathHelper); // Populate Security populateSecurityCoverage(sourceId, secCounter, metacard, xpathHelper); } TemporalCoverageHolder tch = (TemporalCoverageHolder) timeMap .get(generatorConfig.getDateType()); if (tch != null) { startDate = tch.getEndDate(); } } catch (Exception e) { LOGGER.error("Error handling result {} ", result.getMetacard().getId(), e); } } } if (!geoEnvelope.isNull()) { resultProperties.put(RESULT_WKT, (new WKTWriter()).write((new GeometryFactory()).toGeometry(geoEnvelope))); } List<Entry<String, Long>> keywords = keywordCounter.entrySet().stream() .sorted(Entry.comparingByValue(Comparator.reverseOrder())) .limit((long) this.generatorConfig.getMaxKeywords()).collect(Collectors.toList()); this.setKeywords(keywords, resource.getSubjectCoverage()); this.setGeospatialCoverage(resource.getGeospatialCoverage(), geoEnvelope); this.setTemporalCoverage(resource.getTemporalCoverage(), timeMap); this.setRecordRate(contentCollection.getMetrics(), timeMap); List<Entry<String, Long>> contentTypeDetails = contentTypeCounter.entrySet().stream() .sorted(Entry.comparingByValue(Comparator.reverseOrder())) .limit((long) this.generatorConfig.getMaxContentTypes()).collect(Collectors.toList()); this.setContentTypes(resource, contentTypeDetails); List<Entry<String, Long>> mimeTypeDetails = mimeCounter.entrySet().stream() .sorted(Entry.comparingByValue(Comparator.reverseOrder())) .limit((long) this.generatorConfig.getMaxMimeTypes()).collect(Collectors.toList()); this.setMimeTypes(contentCollection, mimeTypeDetails); List<Entry<CompoundCategoryIdentifierType, Long>> categoryDetails = categoryCounter.entrySet().stream() .sorted(Entry.comparingByValue(Comparator.reverseOrder())) .limit((long) this.generatorConfig.getMaxCategories()).collect(Collectors.toList()); this.setCategoryDetails(resource, categoryDetails); List<Entry<CompoundTypeIdentifierType, Long>> typeDetails = typeCounter.entrySet().stream() .sorted(Entry.comparingByValue(Comparator.reverseOrder())) .limit((long) this.generatorConfig.getMaxTypes()).collect(Collectors.toList()); this.setTypeDetails(resource, typeDetails); List<Entry<QualifierValueHolder, Long>> sources = sourceCounter.entrySet().stream() .sorted(Entry.comparingByValue(Comparator.reverseOrder())) .limit((long) this.generatorConfig.getMaxSources()).collect(Collectors.toList()); this.setSourceTypes(resource, sources); List<Entry<SecurityType, Long>> securityDetails = secCounter.entrySet().stream() .sorted(Entry.comparingByValue(Comparator.reverseOrder())) .limit((long) this.generatorConfig.getMaxSecurity()).collect(Collectors.toList()); this.setSecurityDetails(contentCollection, securityDetails); } catch (Exception arg34) { LOGGER.warn("Query failed against source {}", sourceId, arg34); } return describe; }
From source file:com.gnadenheimer.mg.utils.Utils.java
/** * Delete AutoBackUps if older than 60 days *//*from w w w .j av a 2s. 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:blusunrize.immersiveengineering.client.ClientProxy.java
public void addChangelogToManual() { FontRenderer fr = ManualHelper.getManual().fontRenderer; boolean isUnicode = fr.getUnicodeFlag(); fr.setUnicodeFlag(true);/*from w w w .java 2 s . com*/ SortedMap<ComparableVersion, Pair<String, IManualPage[]>> allChanges = new TreeMap<>( Comparator.reverseOrder()); ComparableVersion currIEVer = new ComparableVersion(ImmersiveEngineering.VERSION); //Included changelog try (InputStream in = Minecraft.getMinecraft().getResourceManager() .getResource(new ResourceLocation(ImmersiveEngineering.MODID, "changelog.json")).getInputStream()) { JsonElement ele = new JsonParser().parse(new InputStreamReader(in)); JsonObject upToCurrent = ele.getAsJsonObject(); for (Entry<String, JsonElement> entry : upToCurrent.entrySet()) { ComparableVersion version = new ComparableVersion(entry.getKey()); Pair<String, IManualPage[]> manualEntry = addVersionToManual(currIEVer, version, entry.getValue().getAsString(), false); if (manualEntry != null) allChanges.put(version, manualEntry); } } catch (IOException x) { x.printStackTrace(); } //Changelog from update JSON CheckResult result = ForgeVersion.getResult(Loader.instance().activeModContainer()); if (result.status != Status.PENDING && result.status != Status.FAILED) for (Entry<ComparableVersion, String> e : result.changes.entrySet()) allChanges.put(e.getKey(), addVersionToManual(currIEVer, e.getKey(), e.getValue(), true)); for (Pair<String, IManualPage[]> entry : allChanges.values()) ManualHelper.addEntry(entry.getLeft(), ManualHelper.CAT_UPDATE, entry.getRight()); fr.setUnicodeFlag(isUnicode); }