Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

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

Prototype

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

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

Usage

From source file:com.netflix.spinnaker.clouddriver.artifacts.helm.IndexParser.java

private String findLatestVersion(List<EntryConfig> configs) {
    return configs.stream().max(Comparator.comparing(EntryConfig::getVersion)).get().getVersion();
}

From source file:nc.noumea.mairie.appock.services.impl.ExportExcelServiceImpl.java

@Override
public void genereExcelFournisseur(Commande commande) throws IOException {
    List<String> listeMessageErreurAdresseService = construitMessageErreurAdresseService(commande);
    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(listeMessageErreurAdresseService)) {
        Messagebox.show(StringUtils.join(listeMessageErreurAdresseService, "\n"), "Erreur d'adresse",
                Messagebox.OK, Messagebox.ERROR);
        return;/*w ww. j  a v a 2s  .co m*/
    }

    Map<AbstractEntity, Map<Service, List<ArticleDemande>>> map = commandeService
            .construitMapFournisseurServiceListeArticleDemande(commande);
    List<AbstractEntity> listeAbstractEntity = new ArrayList(map.keySet());
    Comparator abstractEntityComparator = Comparator
            .comparing((AbstractEntity abstractEntity) -> abstractEntity.getLibelleCourt());
    Collections.sort(listeAbstractEntity, abstractEntityComparator);

    File result = File.createTempFile(UUID.randomUUID().toString(), ".zip");
    FileOutputStream fos = new FileOutputStream(result);
    ZipOutputStream zos = new ZipOutputStream(fos);

    for (AbstractEntity abstractEntity : listeAbstractEntity) {
        String nomFichierSansExtension = construitNomFichier(abstractEntity);
        File tempFile = createExcelTempFile(map, abstractEntity, nomFichierSansExtension);
        addToZipFile(tempFile, nomFichierSansExtension + ".xlsx", zos);
        tempFile.delete();
    }

    zos.close();
    fos.close();

    downloadService.downloadToUser(result, "Fichiers fournisseurs.zip");
    result.delete();
}

From source file:org.mortbay.jetty.load.generator.jenkins.LoadGeneratorProjectAction.java

public String getAllLatencyInformations() throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();

    List<RunInformations> datas = new ArrayList<>();

    for (Run run : this.builds) {
        LoadGeneratorBuildAction buildAction = run.getAction(LoadGeneratorBuildAction.class);
        if (buildAction != null) {
            if (buildAction.getGlobalLatencyTimeInformations() != null) {
                RunInformations runInformations = new RunInformations(run.getId(),
                        buildAction.getGlobalLatencyTimeInformations(), buildAction.getTransport());
                datas.add(runInformations);
            }//from w  w w .j  a v a2s .c  o m
        }
    }

    // order by buildId

    Collections.sort(datas, Comparator.comparing(RunInformations::getBuildId));

    StringWriter stringWriter = new StringWriter();

    objectMapper.writeValue(stringWriter, datas);

    return stringWriter.toString();
}

From source file:jease.Registry.java

private void initDomainTypes(Set<String> domainClasses) {
    List<Content> contentList = new ArrayList<>();
    TreeSet<Property> propertyList = new TreeSet<>(Comparator.comparing(Property::getType));

    for (String domainClass : domainClasses) {
        Object obj = Reflections.newInstance(domainClass);
        if (Content.class.isInstance(obj)) {
            contentList.add((Content) obj);
        }/*from   ww w  . ja  va 2  s . c  o  m*/
        if (Property.class.isInstance(obj)) {
            propertyList.add((Property) obj);
        }
    }
    contentList.sort(Comparator.comparing(Content::getType));
    contents = contentList.toArray(new Content[contentList.size()]);
    properties = propertyList;
}

From source file:com.webtide.jetty.load.generator.jenkins.LoadGeneratorProjectAction.java

public String getAllLatencyInformations() throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();

    List<RunInformations> datas = new ArrayList<>();

    for (Run run : this.builds) {
        LoadGeneratorBuildAction buildAction = run.getAction(LoadGeneratorBuildAction.class);
        if (buildAction != null) {
            if (buildAction.getGlobalLatencyTimeInformations() != null) {
                RunInformations runInformations = new RunInformations(run.getId(),
                        buildAction.getGlobalLatencyTimeInformations());
                datas.add(runInformations);
            }//from   www . j  av  a 2s  .  co m
        }
    }

    // order by buildId

    Collections.sort(datas, Comparator.comparing(RunInformations::getBuildId));

    StringWriter stringWriter = new StringWriter();

    objectMapper.writeValue(stringWriter, datas);

    return stringWriter.toString();

}

From source file:com.netflix.metacat.connector.mysql.MySqlConnectorDatabaseService.java

/**
 * {@inheritDoc}/*from   w  w  w.  j  ava2s.c  o  m*/
 */
@Override
public List<QualifiedName> listNames(@Nonnull final ConnectorRequestContext context,
        @Nonnull final QualifiedName name, @Nullable final QualifiedName prefix, @Nullable final Sort sort,
        @Nullable final Pageable pageable) {
    // Overrides the super class due to MySQL using catalog instead of schemas when trying to list database names
    final String catalogName = name.getCatalogName();
    log.debug("Beginning to list database names for catalog {} for request {}", catalogName, context);

    try (final Connection connection = this.getDataSource().getConnection();
            final ResultSet schemas = connection.getMetaData().getCatalogs()) {
        final List<QualifiedName> names = Lists.newArrayList();
        while (schemas.next()) {
            final String schemaName = schemas.getString("TABLE_CAT").toLowerCase(Locale.ENGLISH);
            // skip internal schemas
            if (!schemaName.equals("information_schema") && !schemaName.equals("mysql")) {
                if (prefix == null) {
                    names.add(QualifiedName.ofDatabase(name.getCatalogName(), schemaName));
                } else if (StringUtils.isNotBlank(prefix.getDatabaseName())
                        && schemaName.startsWith(prefix.getDatabaseName())) {
                    names.add(QualifiedName.ofDatabase(name.getCatalogName(), schemaName));
                }
            }
        }

        // Does user want sorting?
        if (sort != null) {
            // We can only really sort by the database name at this level so ignore SortBy field
            final Comparator<QualifiedName> comparator = Comparator.comparing(QualifiedName::getDatabaseName);
            JdbcConnectorUtils.sort(names, sort, comparator);
        }

        // Does user want pagination?
        final List<QualifiedName> results = JdbcConnectorUtils.paginate(names, pageable);

        log.debug("Finished listing database names for catalog {} for request {}", catalogName, context);
        return results;
    } catch (final SQLException se) {
        log.debug("An exception occurred listing database names for catalog {} for request {}", catalogName,
                context, se);
        throw this.getExceptionMapper().toConnectorException(se, name);
    }
}

From source file:org.apache.usergrid.persistence.qakka.api.PerformanceTest.java

@Test
@Ignore("needs exernal Tomcat an Cassandra")
public void testSendAndGetMessagePerformance() throws URISyntaxException, JsonProcessingException {

    Client client = ClientBuilder.newClient();

    WebTarget target = client.target("http://macsnoopdave2013:8080/api/");

    // create a queue

    String queueName = "pt_queue_" + RandomStringUtils.randomAlphanumeric(10);
    Map<String, Object> queueMap = new HashMap<String, Object>() {
        {/*from  w w  w . j  a  va  2 s.c om*/
            put("name", queueName);
        }
    };
    target.path("queues").request().post(Entity.entity(queueMap, MediaType.APPLICATION_JSON_TYPE));

    // send some messages
    int numMessages = 20000;

    {
        ObjectMapper mapper = new ObjectMapper();
        List<Long> times = new ArrayList<>(numMessages);
        int errorCount = 0;
        int counter = 0;

        for (int i = 0; i < numMessages; i++) {

            final int number = i;
            Map<String, Object> messageMap = new HashMap<String, Object>() {
                {
                    put("message", "this is message #" + number);
                    put("valid", true);
                }
            };
            String body = mapper.writeValueAsString(messageMap);

            long startTime = System.currentTimeMillis();
            Response post = target.path("queues").path(queueName).path("messages").request()
                    .post(Entity.entity(body, MediaType.APPLICATION_OCTET_STREAM_TYPE));
            long stopTime = System.currentTimeMillis();
            times.add(stopTime - startTime);

            if (post.getStatus() != 200) {
                errorCount++;
            }

            if (++counter % 500 == 0) {
                logger.debug("Sent {} messages with error count {}", counter, errorCount);
            }

            try {
                Thread.sleep(5);
            } catch (Exception intentionallyIgnored) {
            }
            ;
        }

        Long total = times.stream().mapToLong(time -> time).sum();
        Long max = times.stream().max(Comparator.comparing(time -> time)).get();
        Long min = times.stream().min(Comparator.comparing(time -> time)).get();
        Double average = times.stream().mapToLong(time -> time).average().getAsDouble();

        logger.debug("\n>>>>>>> Total send time {}ms, min {}ms, max {}ms, average {}ms errors {}\n\n", total,
                min, max, average, errorCount);
    }

    // get all messages, checking for dups

    {
        Set<UUID> messageIds = new HashSet<>();
        List<Long> times = new ArrayList<>(numMessages);
        int errorCount = 0;
        int counter = 0;

        for (int j = 0; j < numMessages; j++) {

            long startTime = System.currentTimeMillis();
            Response response = target.path("queues").path(queueName).path("messages").request().get();
            long stopTime = System.currentTimeMillis();
            times.add(stopTime - startTime);

            if (++counter % 500 == 0) {
                logger.debug("Got {} messages with error count {}", counter, errorCount);
            }

            if (response.getStatus() != 200) {
                errorCount++;
                continue;
            }

            ApiResponse apiResponse = response.readEntity(ApiResponse.class);
            QueueMessage queueMessage = apiResponse.getQueueMessages().iterator().next();

            if (messageIds.contains(queueMessage.getQueueMessageId())) {
                Assert.fail("Message fetched twice: " + queueMessage.getQueueMessageId());
            } else {
                messageIds.add(queueMessage.getQueueMessageId());
            }
        }
        Assert.assertEquals(numMessages, messageIds.size());

        Long total = times.stream().mapToLong(time -> time).sum();
        Long max = times.stream().max(Comparator.comparing(time -> time)).get();
        Long min = times.stream().min(Comparator.comparing(time -> time)).get();
        Double average = times.stream().mapToLong(time -> time).average().getAsDouble();

        logger.debug("\n>>>>>>> Total get time {}ms, min {}ms, max {}ms, average {}ms errors {}\n\n", total,
                min, max, average, errorCount);
    }
}

From source file:com.epam.ngb.cli.manager.command.handler.http.ReferenceListHandler.java

@Override
public int runCommand() {
    HttpRequestBase request = getRequest(getRequestUrl());
    setDefaultHeader(request);/*from   w  ww. j a v  a 2s. c o  m*/
    if (isSecure()) {
        addAuthorizationToRequest(request);
    }
    String result = RequestManager.executeRequest(request);
    ResponseResult<List<BiologicalDataItem>> responseResult;
    try {
        responseResult = getMapper().readValue(result,
                getMapper().getTypeFactory().constructParametrizedType(ResponseResult.class,
                        ResponseResult.class, getMapper().getTypeFactory().constructParametrizedType(List.class,
                                List.class, BiologicalDataItem.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 references registered on the server.");
    } else {
        List<BiologicalDataItem> items = responseResult.getPayload();
        items.sort(Comparator.comparing(BiologicalDataItem::getBioDataItemId));
        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.apache.james.mailbox.backup.ZipAssert.java

public ZipAssert containsOnlyEntriesMatching(EntryChecks... entryChecks) throws Exception {
    isNotNull();//from  ww  w.  j  ava 2  s  .  c  om
    List<EntryChecks> sortedEntryChecks = Arrays.stream(entryChecks)
            .sorted(Comparator.comparing(checks -> checks.name)).collect(Guavate.toImmutableList());
    List<ZipArchiveEntry> entries = Collections.list(zipFile.getEntries()).stream()
            .sorted(Comparator.comparing(ZipArchiveEntry::getName)).collect(Guavate.toImmutableList());
    if (entries.size() != entryChecks.length) {
        throwAssertionError(shouldHaveSize(zipFile, entryChecks.length, entries.size()));
    }
    for (int i = 0; i < entries.size(); i++) {
        sortedEntryChecks.get(i).check.test(assertThatZipEntry(zipFile, entries.get(i)));
    }
    return myself;
}