Example usage for java.util List sort

List of usage examples for java.util List sort

Introduction

In this page you can find the example usage for java.util List sort.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
default void sort(Comparator<? super E> c) 

Source Link

Document

Sorts this list according to the order induced by the specified Comparator .

Usage

From source file:org.codice.ddf.catalog.content.monitor.DavAlterationObserver.java

/**
 * List the contents of a directory//from   www .  j  a  v  a 2  s . c  o  m
 *
 * @param file The file to list the contents of
 * @return the directory contents or a zero length array if the empty or the file is not a
 *     directory
 */
private DavResource[] listFiles(final String file) {
    DavResource[] children = null;
    try {
        List<DavResource> list = sardine.list(file);
        // the returned list includes the parent
        if (list.size() > 1 && list.get(0).isDirectory()) {
            List<DavResource> resourceList = list.subList(1, list.size());
            // lexicographical sorting
            resourceList.sort(Comparator.comparing(DavResource::getName));
            children = resourceList.toArray(new DavResource[resourceList.size()]);
        }
    } catch (IOException e) {
        // if it doesn't exist it can't have children
        children = EMPTY_RESOURCES;
    }
    if (children == null) {
        children = EMPTY_RESOURCES;
    }
    return children;
}

From source file:io.undertow.servlet.test.listener.request.async.AsyncListenerExceptionTest.java

private void doTest(String urlTail, boolean timeout) throws IOException, InterruptedException {
    TestHttpClient client = new TestHttpClient();
    try {/*from   ww  w  . j a  v  a  2s.c  o  m*/
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/" + urlTail);
        if (timeout) {
            get.addHeader("timeout", "true");
        }
        HttpResponse result = client.execute(get);
        Assert.assertEquals(timeout ? 500 : 200, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        List<String> expected = new LinkedList<>();
        expected.add("onComplete");
        expected.add("onComplete");
        if (timeout) {
            expected.add("onTimeout");
            expected.add("onTimeout");
        }
        List<String> actual = new LinkedList<>();
        for (int i = 0; i < expected.size(); i++) {
            actual.add(AbstractAsyncServlet.QUEUE.poll(10, TimeUnit.SECONDS));
        }
        actual.sort(Comparator.naturalOrder());
        Assert.assertEquals(expected, actual);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.apache.metamodel.elasticsearch.rest.ElasticSearchRestDataContexFactoryIT.java

@Test
public void testCreateContextAndBulkScript() throws Exception {
    final DataContextPropertiesImpl properties = new DataContextPropertiesImpl();
    properties.setDataContextType("es-rest");
    properties.put(DataContextPropertiesImpl.PROPERTY_URL, "http://" + dockerHostAddress + ":9200");
    properties.put(DataContextPropertiesImpl.PROPERTY_DATABASE, INDEX_NAME);

    assertTrue(factory.accepts(properties, null));

    final ElasticSearchRestDataContext dataContext = (ElasticSearchRestDataContext) factory.create(properties,
            null);//from   w w  w .  ja v  a2  s . co  m

    dataContext.executeUpdate(new BatchUpdateScript() {
        @Override
        public void run(UpdateCallback callback) {
            callback.createTable(INDEX_NAME, "persons").withColumn("name").ofType(ColumnType.STRING)
                    .withColumn("age").ofType(ColumnType.INTEGER).execute();
        }
    });

    dataContext.executeUpdate(new BatchUpdateScript() {
        @Override
        public void run(UpdateCallback callback) {
            callback.insertInto("persons").value("name", "John Doe").value("age", 42).execute();
            callback.insertInto("persons").value("name", "Jane Doe").value("age", 41).execute();
        }
    });

    dataContext.refreshSchemas();

    final DataSet persons = dataContext.executeQuery("SELECT name, age FROM persons");
    final List<Row> personData = persons.toRows();

    assertEquals(2, personData.size());

    // Sort person data, so we can validate each row's values.
    Column ageColumn = dataContext.getSchemaByName(INDEX_NAME).getTableByName("persons").getColumnByName("age");
    personData.sort((row1, row2) -> ((Integer) row1.getValue(ageColumn))
            .compareTo(((Integer) row2.getValue(ageColumn))));

    assertThat(Arrays.asList(personData.get(0).getValues()), containsInAnyOrder("Jane Doe", 41));
    assertThat(Arrays.asList(personData.get(1).getValues()), containsInAnyOrder("John Doe", 42));
}

From source file:com.netflix.spinnaker.igor.jenkins.JenkinsCache.java

public List<String> getTypeaheadResults(String search) {
    List<String> results = new ArrayList<>();
    redisClientDelegate.withKeyScan(prefix() + ":*:*" + search.toUpperCase() + "*:*", 1000,
            page -> results.addAll(page.getResults().stream().map(JenkinsCache::extractTypeaheadResult)
                    .collect(Collectors.toList())));
    results.sort(Comparator.naturalOrder());
    return results;
}

From source file:arxiv.xml.XMLParser.java

/**
 * Parse the XML response from the arXiv OAI repository.
 *
 * @throws NullPointerException if xmlData is null
 * @throws ParseException if parsing fails
 * @throws RepositoryError if the repository's response was parseable but invalid
 * @throws BadArgumentException if the repository's response contains a BadArgument error
 * @throws BadResumptionTokenException if the repository's response contains a BadResumptionToken error
 *///w w w .  j  a va2 s. co m
public ParsedXmlResponse parse(String xmlData) {

    OAIPMHtype unmarshalledResponse;
    try {
        StringReader reader = new StringReader(xmlData);
        JAXBElement<OAIPMHtype> jaxbElement = (JAXBElement<OAIPMHtype>) unmarshaller.unmarshal(reader);

        unmarshalledResponse = jaxbElement.getValue();
    } catch (Exception e) {
        throw new ParseException("Error unmarshalling XML response from repository", e);
    }

    ZonedDateTime responseDate = parseResponseDate(unmarshalledResponse.getResponseDate());

    // Parse any errors returned by the repository
    List<OAIPMHerrorType> errors = Lists.newArrayList(unmarshalledResponse.getError());
    if (!errors.isEmpty()) {
        errors.sort(repositoryErrorSeverityComparator);

        // ID_DOES_NOT_EXIST and NO_RECORDS_MATCH are not considered errors, and simply result in an empty result set
        if (errors.get(0).getCode() == OAIPMHerrorcodeType.ID_DOES_NOT_EXIST
                || errors.get(0).getCode() == OAIPMHerrorcodeType.NO_RECORDS_MATCH) {
            return ParsedXmlResponse.builder().responseDate(responseDate).records(Lists.newArrayList()).build();
        }

        // Produce error report
        StringBuilder errorStringBuilder = new StringBuilder("Received error from repository: \n");
        errors.stream().forEach(error -> errorStringBuilder.append(error.getCode().value()).append(" : ")
                .append(normalizeSpace(error.getValue())).append("\n"));
        String errorString = errorStringBuilder.toString();

        // Throw an exception corresponding to the most severe error
        switch (errors.get(0).getCode()) {
        case BAD_ARGUMENT:
            throw new BadArgumentException(errorString);
        case BAD_RESUMPTION_TOKEN:
            throw new BadResumptionTokenException(errorString);
        case BAD_VERB:
        case CANNOT_DISSEMINATE_FORMAT:
        case NO_METADATA_FORMATS:
        case NO_SET_HIERARCHY:
        default:
            throw new RepositoryError(errorString);
        }
    }

    // Handle the GetRecord response
    if (unmarshalledResponse.getGetRecord() != null) {
        ArticleMetadata record = parseRecord(unmarshalledResponse.getGetRecord().getRecord(), responseDate);

        return ParsedXmlResponse.builder().responseDate(responseDate).records(Lists.newArrayList(record))
                .build();
    }

    // Handle the ListRecords response
    if (unmarshalledResponse.getListRecords() != null) {
        ParsedXmlResponse.ParsedXmlResponseBuilder responseBuilder = ParsedXmlResponse.builder()
                .responseDate(responseDate).records(unmarshalledResponse.getListRecords().getRecord().stream()
                        .map(xmlRecord -> parseRecord(xmlRecord, responseDate)).collect(Collectors.toList()));

        ResumptionTokenType resumptionToken = unmarshalledResponse.getListRecords().getResumptionToken();
        if (resumptionToken != null) {
            responseBuilder.resumptionToken(normalizeSpace(resumptionToken.getValue()))
                    .cursor(resumptionToken.getCursor())
                    .completeListSize(resumptionToken.getCompleteListSize());
        }

        return responseBuilder.build();
    }

    // Handling of other response types is undefined
    throw new RepositoryError("Response from repository was not an error, GetRecord, or ListRecords response");
}

From source file:org.haiku.haikudepotserver.pkg.PkgScreenshotServiceImpl.java

private void reorderPkgScreenshotsByHashSha256s(Pkg pkg, List<String> hashSha256s) {

    List<PkgScreenshot> screenshots = new ArrayList<>(pkg.getPkgScreenshots());

    screenshots.sort((o1, o2) -> {
        int o1i = hashSha256s.indexOf(o1.getHashSha256());
        int o2i = hashSha256s.indexOf(o2.getHashSha256());

        if (-1 == o1i && -1 == o2i) {
            return o1.getCode().compareTo(o2.getCode());
        }/* w  w  w  .  ja  va  2  s.com*/

        if (-1 == o1i) {
            o1i = Integer.MAX_VALUE;
        }

        if (-1 == o2i) {
            o2i = Integer.MAX_VALUE;
        }

        return Integer.compare(o1i, o2i);
    });

    for (int i = 0; i < screenshots.size(); i++) {
        PkgScreenshot pkgScreenshot = screenshots.get(i);
        pkgScreenshot.setOrdering(i + 1);
    }
}

From source file:com.netflix.spinnaker.igor.build.BuildCache.java

public List<String> getJobNames(String master) {
    List<String> jobs = new ArrayList<>();
    redisClientDelegate.withKeyScan(baseKey() + ":completed:" + master + ":*", 1000, page -> jobs
            .addAll(page.getResults().stream().map(BuildCache::extractJobName).collect(Collectors.toList())));
    jobs.sort(Comparator.naturalOrder());
    return jobs;/*from w w  w  .j a  va  2  s.  com*/
}

From source file:com.netflix.spinnaker.igor.build.BuildCache.java

public List<String> getDeprecatedJobNames(String master) {
    List<String> jobs = new ArrayList<>();
    redisClientDelegate.withKeyScan(baseKey() + ":" + master + ":*", 1000, page -> jobs.addAll(
            page.getResults().stream().map(BuildCache::extractDeprecatedJobName).collect(Collectors.toList())));
    jobs.sort(Comparator.naturalOrder());
    return jobs;/*from ww  w  .ja va 2 s  . c om*/
}

From source file:org.apache.streams.util.schema.SchemaStoreImpl.java

@Override
public Iterator<Schema> getSchemaIterator() {
    List<Schema> schemaList = new ArrayList<>(schemas.values());
    schemaList.sort(this);
    return schemaList.iterator();
}

From source file:com.nike.cerberus.service.CloudFormationService.java

/**
 * Blocking call that waits for a stack change to complete.  Times out if waiting more than 30 minutes.
 *
 * @param endStatuses Status to end on//from w ww .j av  a2  s  .c  o m
 * @return The final status
 */
public StackStatus waitForStatus(final String stackId, final HashSet<StackStatus> endStatuses) {
    DateTime now = DateTime.now(DateTimeZone.UTC).minusSeconds(10);
    DateTime timeoutDateTime = now.plusMinutes(90);
    Set<String> recordedStackEvents = Sets.newHashSet();
    boolean isRunning = true;
    StackStatus stackStatus = null;

    while (isRunning) {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            logger.warn("Thread sleep interrupted. Continuing...", e);
        }
        stackStatus = getStackStatus(stackId);

        if (endStatuses.contains(stackStatus) || stackStatus == null) {
            isRunning = false;
        }

        if (stackStatus != null) {
            List<StackEvent> stackEvents = getStackEvents(stackId);
            stackEvents.sort((o1, o2) -> o1.getTimestamp().compareTo(o2.getTimestamp()));

            for (StackEvent stackEvent : stackEvents) {
                DateTime eventTime = new DateTime(stackEvent.getTimestamp());
                if (!recordedStackEvents.contains(stackEvent.getEventId()) && now.isBefore(eventTime)) {
                    logger.info(String.format("TS: %s, Status: %s, Type: %s, Reason: %s",
                            Chalk.on(stackEvent.getTimestamp().toString()).yellow(),
                            getStatusColor(stackEvent.getResourceStatus()),
                            Chalk.on(stackEvent.getResourceType()).yellow(),
                            Chalk.on(stackEvent.getResourceStatusReason()).yellow()));

                    recordedStackEvents.add(stackEvent.getEventId());
                }
            }
        }

        if (timeoutDateTime.isBeforeNow()) {
            logger.error("Timed out waiting for CloudFormation completion status.");
            isRunning = false;
        }
    }

    return stackStatus;
}