List of usage examples for java.util Comparator comparing
public static <T, U extends Comparable<? super U>> Comparator<T> comparing( Function<? super T, ? extends U> keyExtractor)
From source file:com.netflix.spinnaker.clouddriver.google.controllers.GoogleNamedImageLookupController.java
@RequestMapping(value = "/find", method = RequestMethod.GET) public List<NamedImage> list(@RequestParam(required = false) String q, @RequestParam(required = false) String account, HttpServletRequest request) { Map<String, List<Image>> imageMap = listImagesByAccount(); // Set of accounts for which we should return images: either the supplied account, or default // to all accounts Set<String> accounts; if (StringUtils.isNotEmpty(account)) { accounts = new HashSet<>(); if (imageMap.containsKey(account)) { accounts.add(account);/* w ww .j a v a 2 s . com*/ } } else { accounts = imageMap.keySet(); } List<NamedImage> results = new ArrayList<>(); for (String imageAccount : accounts) { for (Image i : imageMap.get(imageAccount)) { Map<String, Object> attributes = new HashMap<>(); attributes.put("creationDate", i.get("creationTimestamp")); NamedImage newImage = new NamedImage(imageAccount, i.getName(), attributes, buildTagsMap(i)); results.add(newImage); } } Predicate<NamedImage> queryFilter = i -> true; if (q != null && q.trim().length() > 0) { String glob = q.trim(); // Wrap in '*' if there are no glob-style characters in the query string. if (!glob.contains("*") && !glob.contains("?") && !glob.contains("[") && !glob.contains("\\")) { glob = "*" + glob + "*"; } Pattern pattern = new InMemoryCache.Glob(glob).toPattern(); queryFilter = i -> pattern.matcher(i.imageName).matches(); } return results.stream().filter(queryFilter) .filter(namedImage -> matchesTagFilters(namedImage, extractTagFilters(request))) .sorted(Comparator.comparing(image -> image.imageName)).collect(Collectors.toList()); }
From source file:org.matsim.contrib.drt.optimizer.rebalancing.mincostflow.AggregatedMinCostRelocationCalculator.java
private Vehicle findNearestVehicle(List<Vehicle> rebalancableVehicles, Link destinationLink) { Coord toCoord = destinationLink.getFromNode().getCoord(); return rebalancableVehicles.stream().min(Comparator.comparing(v -> DistanceUtils.calculateSquaredDistance(// Schedules.getLastLinkInSchedule(v).getToNode().getCoord(), toCoord))).get(); }
From source file:org.apache.storm.daemon.logviewer.utils.DirectoryCleaner.java
/** * If totalSize of files exceeds the either the per-worker quota or global quota, * Logviewer deletes oldest inactive log files in a worker directory or in all worker dirs. * We use the parameter forPerDir to switch between the two deletion modes. * * @param dirs the list of directories to be scanned for deletion * @param quota the per-dir quota or the total quota for the all directories * @param forPerDir if true, deletion happens for a single dir; otherwise, for all directories globally * @param activeDirs only for global deletion, we want to skip the active logs in activeDirs * @return number of files deleted//from w w w .ja v a 2s . c om */ public DeletionMeta deleteOldestWhileTooLarge(List<Path> dirs, long quota, boolean forPerDir, Set<Path> activeDirs) throws IOException { long totalSize = 0; for (Path dir : dirs) { try (DirectoryStream<Path> stream = getStreamForDirectory(dir)) { for (Path path : stream) { totalSize += Files.size(path); } } } LOG.debug("totalSize: {} quota: {}", totalSize, quota); long toDeleteSize = totalSize - quota; if (toDeleteSize <= 0) { return DeletionMeta.EMPTY; } int deletedFiles = 0; long deletedSize = 0; // the oldest pq_size files in this directory will be placed in PQ, with the newest at the root PriorityQueue<Pair<Path, FileTime>> pq = new PriorityQueue<>(PQ_SIZE, Comparator.comparing((Pair<Path, FileTime> p) -> p.getRight()).reversed()); int round = 0; final Set<Path> excluded = new HashSet<>(); while (toDeleteSize > 0) { LOG.debug("To delete size is {}, start a new round of deletion, round: {}", toDeleteSize, round); for (Path dir : dirs) { try (DirectoryStream<Path> stream = getStreamForDirectory(dir)) { for (Path path : stream) { if (!excluded.contains(path)) { if (isFileEligibleToSkipDelete(forPerDir, activeDirs, dir, path)) { excluded.add(path); } else { Pair<Path, FileTime> p = Pair.of(path, Files.getLastModifiedTime(path)); if (pq.size() < PQ_SIZE) { pq.offer(p); } else if (p.getRight().toMillis() < pq.peek().getRight().toMillis()) { pq.poll(); pq.offer(p); } } } } } } if (!pq.isEmpty()) { // need to reverse the order of elements in PQ to delete files from oldest to newest Stack<Pair<Path, FileTime>> stack = new Stack<>(); while (!pq.isEmpty()) { stack.push(pq.poll()); } while (!stack.isEmpty() && toDeleteSize > 0) { Pair<Path, FileTime> pair = stack.pop(); Path file = pair.getLeft(); final String canonicalPath = file.toAbsolutePath().normalize().toString(); final long fileSize = Files.size(file); final long lastModified = pair.getRight().toMillis(); //Original implementation doesn't actually check if delete succeeded or not. try { Utils.forceDelete(file.toString()); LOG.info("Delete file: {}, size: {}, lastModified: {}", canonicalPath, fileSize, lastModified); toDeleteSize -= fileSize; deletedSize += fileSize; deletedFiles++; } catch (IOException e) { excluded.add(file); } } pq.clear(); round++; if (round >= MAX_ROUNDS) { if (forPerDir) { LOG.warn( "Reach the MAX_ROUNDS: {} during per-dir deletion, you may have too many files in " + "a single directory : {}, will delete the rest files in next interval.", MAX_ROUNDS, dirs.get(0).toAbsolutePath().normalize()); } else { LOG.warn("Reach the MAX_ROUNDS: {} during global deletion, you may have too many files, " + "will delete the rest files in next interval.", MAX_ROUNDS); } break; } } else { LOG.warn("No more files able to delete this round, but {} is over quota by {} MB", forPerDir ? "this directory" : "root directory", toDeleteSize * 1e-6); } } return new DeletionMeta(deletedSize, deletedFiles); }
From source file:com.evolveum.midpoint.web.page.admin.certification.dto.CertDefinitionDto.java
public CertDefinitionDto(AccessCertificationDefinitionType definition, PageBase page, PrismContext prismContext) throws SchemaException { this.oldDefinition = definition.clone(); this.definition = definition; owner = loadOwnerReference(definition.getOwnerRef()); definitionScopeDto = createDefinitionScopeDto(definition.getScopeDefinition(), page.getPrismContext()); stageDefinition = new ArrayList<>(); for (AccessCertificationStageDefinitionType stageDef : definition.getStageDefinition()) { stageDefinition.add(createStageDefinitionDto(stageDef, prismContext)); }//from w ww. j a v a2 s. com stageDefinition.sort(Comparator.comparing(StageDefinitionDto::getNumber)); if (definition.getRemediationDefinition() != null) { remediationStyle = definition.getRemediationDefinition().getStyle(); revokeOn = new ArrayList<>(definition.getRemediationDefinition().getRevokeOn()); } else { remediationStyle = AccessCertificationRemediationStyleType.AUTOMATED; // TODO consider the default... revokeOn = new ArrayList<>(); } if (definition.getReviewStrategy() != null) { outcomeStrategy = definition.getReviewStrategy().getOutcomeStrategy(); } else { outcomeStrategy = AccessCertificationCaseOutcomeStrategyType.ONE_DENY_DENIES; // TODO consider the default... } }
From source file:com.thoughtworks.go.apiv2.environments.EnvironmentsControllerV2.java
public String index(Request request, Response response) throws IOException { List<EnvironmentConfig> environmentViewModelList = environmentConfigService.getEnvironments().stream() .sorted(Comparator.comparing(EnvironmentConfig::name)).collect(Collectors.toList()); setEtagHeader(response, calculateEtag(environmentViewModelList)); return writerForTopLevelObject(request, response, outputWriter -> EnvironmentsRepresenter.toJSON(outputWriter, environmentViewModelList)); }
From source file:src.agent.CiudadAgent.java
private void aguaSuciaCiudad(MasaDeAgua aguaSucia) { // acceder al tramo OntModel model = ontoManager.getModel(); String namingContext = ontoManager.getNamingContext(); OntProperty tramoProperty = model.getOntProperty(namingContext + Constants.TRAMO_ORIGEN); Resource tramoResource = individual.getPropertyResourceValue(tramoProperty); Individual tramo = tramoResource.as(Individual.class); // acceder al agua OntProperty aguaTramoProperty = model.getOntProperty(namingContext + Constants.AGUA_TRAMO); RDFNode aguaTramoNode = tramo.getPropertyValue(aguaTramoProperty); Individual aguaTramo = aguaTramoNode.as(Individual.class); MasaDeAgua agua = (MasaDeAgua) ReflectionUtils.castIndividual(aguaTramo, MasaDeAgua.class); // hemos vaciado el rio? if (agua.Volumen < aguaSucia.Volumen) { System.out.println("Rio vaco: No se puede eliminar la suciedad y la industria estalla!"); return;// w w w .j a v a 2s. c om } // quitar el volumen de agua del tramo model.remove(tramoResource, aguaTramoProperty, aguaTramoNode); ontoManager.dropIndividual(aguaTramo); // crear el agua nueva agua.Volumen -= aguaSucia.Volumen; Individual aguaNuevaTramo = ontoManager.createIndividual(agua); model.add(tramoResource, aguaTramoProperty, aguaNuevaTramo); // pillar la funcion de calculo de coste List<String> funcCosteNames = getFuncNames(Constants.COSTE_LIMPIAR_AGUA); String funcCosteName = funcCosteNames.get(0); // ensuciar el agua pillada del rio List<String> funcEnsuciaNames = getFuncNames(Constants.ENSUCIA_AGUAS); String funcEnsuciaName = funcEnsuciaNames.get(0); ReflectionUtils.callFunction(new MasaDeAguaAgent(), funcEnsuciaName, agua, aguaSucia); // imprimir aguaSucia.showData(); System.out.println(" Volumen: " + aguaSucia.Volumen + " litros"); // acceder a las depuradoras asignadas List<Pair<Float, Individual>> costesPorDepuradora = new ArrayList<>(); OntProperty depuradoraAsignadaProperty = model .getOntProperty(namingContext + Constants.DEPURADORA_ASIGNADA); NodeIterator depuradorasIt = individual.listPropertyValues(depuradoraAsignadaProperty); while (depuradorasIt.hasNext()) { RDFNode depuradoraNode = depuradorasIt.next(); Individual depuradora = depuradoraNode.as(Individual.class); // calcular el coste DepuradoraAgent depuradoraAgent = new DepuradoraAgent(depuradora); float costeDepurar = (float) ReflectionUtils.callFunction(depuradoraAgent, funcCosteName, aguaSucia); if (costeDepurar >= 0f) costesPorDepuradora.add(Pair.of(costeDepurar, depuradora)); } // si no hay opciones, avisar al usuario if (costesPorDepuradora.isEmpty()) { System.out.println( "Ninguna depuradora acepta el agua sucia: No se puede eliminar y se devuelve al ro!"); // devolver el agua sucia al rio tramoResource = individual.getPropertyResourceValue(tramoProperty); tramo = tramoResource.as(Individual.class); new MasaDeAguaAgent(tramo, aguaSucia).action(); return; } // ordenar por coste, y quedarsela mas barata Collections.sort(costesPorDepuradora, Comparator.comparing(coste -> coste.getLeft())); Individual depuradoraSeleccionada = costesPorDepuradora.get(0).getRight(); // pillar la funcion de llenado de tanques List<String> funcLlenarNames = getFuncNames(Constants.LLENAR_TANQUES); String funcLlenarName = funcLlenarNames.get(0); // llenar los tanques ReflectionUtils.callFunction(new DepuradoraAgent(depuradoraSeleccionada), funcLlenarName, aguaSucia); }
From source file:src.agent.IndustriaAgent.java
private void aguaSuciaIndustria(MasaDeAgua aguaSucia) { // acceder al tramo OntModel model = ontoManager.getModel(); String namingContext = ontoManager.getNamingContext(); OntProperty tramoProperty = model.getOntProperty(namingContext + Constants.TRAMO_ORIGEN); Resource tramoResource = individual.getPropertyResourceValue(tramoProperty); Individual tramo = tramoResource.as(Individual.class); // acceder al agua OntProperty aguaTramoProperty = model.getOntProperty(namingContext + Constants.AGUA_TRAMO); RDFNode aguaTramoNode = tramo.getPropertyValue(aguaTramoProperty); Individual aguaTramo = aguaTramoNode.as(Individual.class); MasaDeAgua agua = (MasaDeAgua) ReflectionUtils.castIndividual(aguaTramo, MasaDeAgua.class); // hemos vaciado el rio? if (agua.Volumen < aguaSucia.Volumen) { System.out.println("Rio vaco: No se puede eliminar la suciedad y la industria estalla!"); return;/* w w w . ja va 2s .com*/ } // quitar el volumen de agua del tramo model.remove(tramoResource, aguaTramoProperty, aguaTramoNode); ontoManager.dropIndividual(aguaTramo); // crear el agua nueva agua.Volumen -= aguaSucia.Volumen; Individual aguaNuevaTramo = ontoManager.createIndividual(agua); model.add(tramoResource, aguaTramoProperty, aguaNuevaTramo); // pillar la funcion de calculo de coste List<String> funcCosteNames = getFuncNames(Constants.COSTE_LIMPIAR_AGUA); String funcCosteName = funcCosteNames.get(0); // ensuciar el agua pillada del rio List<String> funcEnsuciaNames = getFuncNames(Constants.ENSUCIA_AGUAS); String funcEnsuciaName = funcEnsuciaNames.get(0); ReflectionUtils.callFunction(new MasaDeAguaAgent(), funcEnsuciaName, agua, aguaSucia); // imprimir aguaSucia.showData(); System.out.println(" Volumen: " + aguaSucia.Volumen + " litros"); // acceder a las depuradoras asignadas List<Pair<Float, Individual>> costesPorDepuradora = new ArrayList<>(); OntProperty depuradoraAsignadaProperty = model .getOntProperty(namingContext + Constants.DEPURADORA_ASIGNADA); NodeIterator depuradorasIt = individual.listPropertyValues(depuradoraAsignadaProperty); while (depuradorasIt.hasNext()) { RDFNode depuradoraNode = depuradorasIt.next(); Individual depuradora = depuradoraNode.as(Individual.class); // calcular el coste DepuradoraAgent depuradoraAgent = new DepuradoraAgent(depuradora); float costeDepurar = (float) ReflectionUtils.callFunction(depuradoraAgent, funcCosteName, aguaSucia); if (costeDepurar >= 0f) costesPorDepuradora.add(Pair.of(costeDepurar, depuradora)); } // si no hay opciones, avisar al usuario if (costesPorDepuradora.isEmpty()) { System.out.println( "Ninguna depuradora acepta el agua sucia: No se puede eliminar y se devuelve al ro!"); // devolver el agua sucia al rio tramoResource = individual.getPropertyResourceValue(tramoProperty); tramo = tramoResource.as(Individual.class); new MasaDeAguaAgent(tramo, aguaSucia).action(); return; } // ordenar por coste, y quedarsela mas barata Collections.sort(costesPorDepuradora, Comparator.comparing(coste -> coste.getLeft())); Individual depuradoraSeleccionada = costesPorDepuradora.get(0).getRight(); // pillar la funcion de llenado de tanques List<String> funcLlenarNames = getFuncNames(Constants.LLENAR_TANQUES); String funcLlenarName = funcLlenarNames.get(0); // llenar los tanques ReflectionUtils.callFunction(new DepuradoraAgent(depuradoraSeleccionada), funcLlenarName, aguaSucia); }
From source file:com.epam.ngb.cli.manager.command.handler.http.DatasetListHandler.java
/** * Performs a dataset list request to NGB server and its result to * StdOut. The performed request varies according to the presence of 'parent' option. * @return 0 if request completed successfully *///from w w w. j av a 2s . c o m @Override public int runCommand() { HttpRequestBase request = parentId == null ? createListingRequest() : createTreeRequest(parentId); String result = RequestManager.executeRequest(request); ResponseResult<List<Project>> responseResult; try { responseResult = getMapper().readValue(result, getMapper().getTypeFactory().constructParametrizedType( ResponseResult.class, ResponseResult.class, getMapper().getTypeFactory().constructParametrizedType(List.class, List.class, Project.class))); } catch (IOException e) { throw new ApplicationException(e.getMessage(), e); } if (ERROR_STATUS.equals(responseResult.getStatus())) { throw new ApplicationException(responseResult.getMessage()); } if (responseResult.getPayload() == null || responseResult.getPayload().isEmpty()) { LOGGER.info("No datasets registered on the server."); } else { List<Project> items = responseResult.getPayload(); items.sort(Comparator.comparing(Project::getId)); AbstractResultPrinter printer = AbstractResultPrinter.getPrinter(printTable, items.get(0).getFormatString(items)); printer.printHeader(items.get(0)); items.forEach(printer::printItem); } return 0; }
From source file:org.mitre.mpf.wfm.service.component.TestStartupComponentRegistrationService.java
@Before public void init() throws IOException, ComponentRegistrationException { _componentUploadDir.newFolder("test"); _componentUploadDir.newFile("bad.bad"); _mockPropertiesUtil = mock(PropertiesUtil.class); when(_mockPropertiesUtil.getUploadedComponentsDirectory()).thenReturn(_componentUploadDir.getRoot()); when(_mockPropertiesUtil.getPluginDeploymentPath()).thenReturn(_pluginDeploymentDir.getRoot()); when(_mockPropertiesUtil.isStartupAutoRegistrationSkipped()).thenReturn(false); MockitoAnnotations.initMocks(this); when(_mockAddComponentSvc.registerComponent(anyNonNull())).thenAnswer(invocation -> { String arg = invocation.getArgumentAt(0, String.class); String componentName = componentPackageToName(arg); RegisterComponentModel result = new RegisterComponentModel(); result.setComponentState(ComponentState.REGISTERED); result.setComponentName(componentName); return result; });/*from w w w. j av a2 s . c o m*/ //noinspection unchecked when(_mockDependencyFinder.getRegistrationOrder(anyNonNull())) .thenAnswer(invocation -> invocation.getArgumentAt(0, Collection.class).stream() .sorted(Comparator.comparing(p -> ((Path) p).getFileName().toString().toLowerCase())) .collect(toList())); }
From source file:au.com.addstar.SpigotUpdater.java
private static Comparator<Plugin> getComparator() { return Comparator.comparing(Plugin::getName); }