Example usage for java.util Set stream

List of usage examples for java.util Set stream

Introduction

In this page you can find the example usage for java.util Set stream.

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:com.netflix.genie.web.data.repositories.jpa.specifications.JpaJobSpecs.java

/**
 * Generate a criteria query predicate for a where clause based on the given parameters.
 *
 * @param root             The root to use
 * @param cb               The criteria builder to use
 * @param id               The job id//from   w ww  .ja va 2  s  . c  om
 * @param name             The job name
 * @param user             The user who created the job
 * @param statuses         The job statuses
 * @param tags             The tags for the jobs to find
 * @param clusterName      The cluster name
 * @param cluster          The cluster the job should have been run on
 * @param commandName      The command name
 * @param command          The command the job should have been run with
 * @param minStarted       The time which the job had to start after in order to be return (inclusive)
 * @param maxStarted       The time which the job had to start before in order to be returned (exclusive)
 * @param minFinished      The time which the job had to finish after in order to be return (inclusive)
 * @param maxFinished      The time which the job had to finish before in order to be returned (exclusive)
 * @param grouping         The job grouping to search for
 * @param groupingInstance The job grouping instance to search for
 * @return The specification
 */
@SuppressWarnings("checkstyle:parameternumber")
public static Predicate getFindPredicate(final Root<JobEntity> root, final CriteriaBuilder cb,
        @Nullable final String id, @Nullable final String name, @Nullable final String user,
        @Nullable final Set<JobStatus> statuses, @Nullable final Set<String> tags,
        @Nullable final String clusterName, @Nullable final ClusterEntity cluster,
        @Nullable final String commandName, @Nullable final CommandEntity command,
        @Nullable final Instant minStarted, @Nullable final Instant maxStarted,
        @Nullable final Instant minFinished, @Nullable final Instant maxFinished,
        @Nullable final String grouping, @Nullable final String groupingInstance) {
    final List<Predicate> predicates = new ArrayList<>();
    if (StringUtils.isNotBlank(id)) {
        predicates.add(
                JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.uniqueId), id));
    }
    if (StringUtils.isNotBlank(name)) {
        predicates
                .add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.name), name));
    }
    if (StringUtils.isNotBlank(user)) {
        predicates
                .add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.user), user));
    }
    if (statuses != null && !statuses.isEmpty()) {
        final List<Predicate> orPredicates = statuses.stream()
                .map(status -> cb.equal(root.get(JobEntity_.status), status)).collect(Collectors.toList());
        predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()])));
    }
    if (tags != null && !tags.isEmpty()) {
        predicates.add(
                cb.like(root.get(JobEntity_.tagSearchString), JpaSpecificationUtils.getTagLikeString(tags)));
    }
    if (cluster != null) {
        predicates.add(cb.equal(root.get(JobEntity_.cluster), cluster));
    }
    if (StringUtils.isNotBlank(clusterName)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.clusterName),
                clusterName));
    }
    if (command != null) {
        predicates.add(cb.equal(root.get(JobEntity_.command), command));
    }
    if (StringUtils.isNotBlank(commandName)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.commandName),
                commandName));
    }
    if (minStarted != null) {
        predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.started), minStarted));
    }
    if (maxStarted != null) {
        predicates.add(cb.lessThan(root.get(JobEntity_.started), maxStarted));
    }
    if (minFinished != null) {
        predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.finished), minFinished));
    }
    if (maxFinished != null) {
        predicates.add(cb.lessThan(root.get(JobEntity_.finished), maxFinished));
    }
    if (grouping != null) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.grouping),
                grouping));
    }
    if (groupingInstance != null) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb,
                root.get(JobEntity_.groupingInstance), groupingInstance));
    }
    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}

From source file:uk.ac.ebi.ep.ebeye.EbeyeRestServiceTest.java

/**
 * Test of queryEbeyeForAccessions method, of class EbeyeRestService.
 *//*from   w  w  w . j  a  v a 2s  .c  o  m*/
@Test
public void testQueryEbeyeForAccessions_String() {
    try {
        LOGGER.info("queryEbeyeForAccessions");

        String url = ebeyeIndexUrl.getDefaultSearchIndexUrl() + "?format=json&size=100&query=";

        String json = getJsonFile(ebeyeJsonFile);

        mockRestServer.expect(requestTo(url)).andExpect(method(HttpMethod.GET))
                .andRespond(withSuccess(json, MediaType.APPLICATION_JSON));

        EbeyeSearchResult searchResult = restTemplate.getForObject(url.trim(), EbeyeSearchResult.class);

        Set<String> accessions = new LinkedHashSet<>();

        for (Entry entry : searchResult.getEntries()) {
            accessions.add(entry.getUniprotAccession());
        }

        List<String> expResult = accessions.stream().distinct().collect(Collectors.toList());

        String accession = expResult.stream().findAny().get();

        List<String> result = ebeyeRestService.queryEbeyeForAccessions(query);

        mockRestServer.verify();

        assertThat(result.stream().findAny().get(), containsString(accession));

        assertEquals(expResult, result);
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }

}

From source file:com.github.horrorho.inflatabledonkey.cloud.Donkey.java

public void apply(HttpClient httpClient, Optional<ForkJoinPool> aux, Set<Asset> assets,
        FileAssembler consumer) {// ww w .j ava  2 s.  com
    logger.trace("<< apply() - assets: {}", assets.size());
    if (assets.isEmpty()) {
        return;
    }

    if (logger.isDebugEnabled()) {
        int bytes = assets.stream().mapToInt(u -> u.size().map(Long::intValue).orElse(0)).sum();
        logger.debug("-- apply() - assets total: {} size (bytes): {}", assets.size(), bytes);
    }

    AssetPool pool = new AssetPool(assets);

    while (true) {
        try {
            if (assets.size() > fragmentationThreshold && aux.isPresent()) {
                processConcurrent(httpClient, aux.get(), pool, consumer);
            } else {
                process(httpClient, pool, consumer);
            }
            break;
        } catch (IllegalStateException ex) {
            // Our StorageHostChunkLists have expired.
            // TOFIX potentially unsafe. Use a more specific exception.
            logger.debug("-- apply() - IllegalStateException: {}", ex.getMessage());
        } catch (IllegalArgumentException | IOException ex) {
            logger.warn("-- apply() - {} {}", ex.getClass().getCanonicalName(), ex.getMessage());
            break;
        }
    }
    logger.trace(">> apply() - pool empty: {}", pool.isEmpty());
}

From source file:uk.ac.ebi.ep.ebeye.EbeyeRestServiceTest.java

/**
 * Test of queryEbeyeForAccessions method, of class EbeyeRestService.
 *//*  w  w  w .  j a  v  a 2s  . c om*/
@Test
public void testQueryEbeyeForAccessions_String_boolean() {
    LOGGER.info("queryEbeyeForAccessions paginate:false");

    try {

        boolean paginate = false;

        String url = ebeyeIndexUrl.getDefaultSearchIndexUrl() + "?format=json&size=100&query=";

        String json = getJsonFile(ebeyeJsonFile);

        mockRestServer.expect(requestTo(url)).andExpect(method(HttpMethod.GET))
                .andRespond(withSuccess(json, MediaType.APPLICATION_JSON));

        EbeyeSearchResult searchResult = restTemplate.getForObject(url.trim(), EbeyeSearchResult.class);

        Set<String> accessions = new LinkedHashSet<>();

        for (Entry entry : searchResult.getEntries()) {
            accessions.add(entry.getUniprotAccession());
        }

        List<String> expResult = accessions.stream().distinct().collect(Collectors.toList());

        String accession = expResult.stream().findAny().get();

        List<String> result = ebeyeRestService.queryEbeyeForAccessions(query, paginate);

        mockRestServer.verify();

        assertThat(result.stream().findAny().get(), containsString(accession));

        assertEquals(expResult, result);
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }

}

From source file:uk.ac.ebi.ep.ebeye.EbeyeRestServiceTest.java

/**
 * Test of queryEbeyeForAccessions method, of class EbeyeRestService.
 *//*ww  w  .  j av a2s  .  c om*/
@Test
public void testQueryEbeyeForAccessions_3args() {
    LOGGER.info("queryEbeyeForAccessions paginate :true:limit:yes");

    try {

        int limit = 2;
        boolean paginate = true;

        String url = ebeyeIndexUrl.getDefaultSearchIndexUrl() + "?format=json&size=100&query=";

        String json = getJsonFile(ebeyeJsonFile);

        mockRestServer.expect(requestTo(url)).andExpect(method(HttpMethod.GET))
                .andRespond(withSuccess(json, MediaType.APPLICATION_JSON));

        EbeyeSearchResult searchResult = restTemplate.getForObject(url.trim(), EbeyeSearchResult.class);

        Set<String> accessions = new LinkedHashSet<>();

        for (Entry entry : searchResult.getEntries()) {
            accessions.add(entry.getUniprotAccession());
        }

        List<String> expResult = accessions.stream().distinct().collect(Collectors.toList());

        String accession = expResult.stream().findAny().get();

        List<String> result = ebeyeRestService.queryEbeyeForAccessions(query, paginate, limit);

        mockRestServer.verify();

        assertThat(result.stream().findAny().get(), containsString(accession));

        assertEquals(expResult, result);
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }

}

From source file:com.epam.ta.reportportal.core.launch.impl.UpdateLaunchHandler.java

/**
 * Update test-items of specified launches with new LaunchID
 *
 * @param launchId//from  w  ww  .  ja v  a  2s.  co  m
 */
private List<TestItem> updateChildrenOfLaunch(String launchId, Set<String> launches,
        boolean extendDescription) {
    List<TestItem> testItems = launches.stream().map(id -> {
        Launch launch = launchRepository.findOne(id);
        return testItemRepository.findByLaunch(launch).stream().map(item -> {
            item.setLaunchRef(launchId);
            if (item.getPath().size() == 0) {
                // Add launch reference description for top level items
                Supplier<String> newDescription = Suppliers.formattedSupplier(
                        ((null != item.getItemDescription()) ? item.getItemDescription() : "")
                                + (extendDescription ? "\r\n@launch '{} #{}'" : ""),
                        launch.getName(), launch.getNumber());
                item.setItemDescription(newDescription.get());
            }
            return item;
        }).collect(toList());
    }).flatMap(List::stream).collect(toList());
    testItemRepository.save(testItems);
    return testItems.stream().filter(item -> item.getPath().size() == 0).collect(toList());
}

From source file:pt.ist.fenixedu.delegates.ui.services.DelegateService.java

public DelegateSearchBean generateNewBean(DelegateSearchBean delegateSearchBean) {
    ExecutionYear executionYear = delegateSearchBean.getExecutionYear();
    Degree degree = delegateSearchBean.getDegree();
    DegreeType degreeType = delegateSearchBean.getDegreeType();
    delegateSearchBean.setExecutionYears(Bennu.getInstance().getExecutionYearsSet().stream()
            .sorted(ExecutionYear.REVERSE_COMPARATOR_BY_YEAR).collect(Collectors.toList()));
    Set<DegreeType> aux = executionYear.getExecutionDegreesSet().stream()
            .map(d -> d.getDegree().getDegreeType()).collect(Collectors.toSet());
    delegateSearchBean.setDegreeTypes(aux.stream().collect(Collectors.toList()));
    if (degreeType == null && (degree == null || EmptyDegree.class.isInstance(degree))) {
        delegateSearchBean.setDegrees(executionYear.getExecutionDegreesSet().stream().map(d -> d.getDegree())
                .sorted(Degree.COMPARATOR_BY_NAME).collect(Collectors.toList()));
        delegateSearchBean.setDegree(delegateSearchBean.getDegrees().iterator().next());
        delegateSearchBean.setDegreeType(delegateSearchBean.getDegree().getDegreeType());
        return delegateSearchBean;
    }//from   w ww . j a v  a2s  . c  o  m
    if (degree == null || EmptyDegree.class.isInstance(degree)) {
        delegateSearchBean.setDegrees(executionYear.getExecutionDegreesSet().stream()
                .filter(d -> d.getDegree().getDegreeType().equals(degreeType)).map(d -> d.getDegree())
                .sorted(Degree.COMPARATOR_BY_NAME).collect(Collectors.toList()));
        delegateSearchBean.setDegree(delegateSearchBean.getDegrees().iterator().next());
        return delegateSearchBean;
    }
    delegateSearchBean.setDegrees(executionYear.getExecutionDegreesSet().stream()
            .filter(d -> d.getDegree().getDegreeType().equals(degreeType)).map(d -> d.getDegree())
            .sorted(Degree.COMPARATOR_BY_NAME).collect(Collectors.toList()));
    return delegateSearchBean;
}

From source file:com.marand.thinkmed.medications.business.MedicationsFinderImpl.java

@Override
public List<TreeNodeData> findSimilarMedications(final long medicationId, @Nonnull final List<Long> routeIds,
        @Nonnull final DateTime when) {
    Preconditions.checkNotNull(routeIds, "routeIds must not be null");
    Preconditions.checkNotNull(when, "when must not be null");

    final Set<Long> similarMedicationsIds = medicationsDao.findSimilarMedicationsIds(medicationId, routeIds,
            when);/*from  w w w.  j a  va2  s  .c  o m*/

    final Map<Long, MedicationHolderDto> similarMedicationsMap = similarMedicationsIds.stream()
            .map(i -> medicationsValueHolder.getValue().get(i)).filter(m -> m != null)
            .collect(Collectors.toMap(MedicationHolderDto::getId, m -> m));

    return buildMedicationsTree(similarMedicationsMap);
}

From source file:com.netflix.conductor.dao.dynomite.RedisMetadataDAOTest.java

@Test
public void testTaskDefOperations() throws Exception {

    TaskDef def = new TaskDef("taskA");
    def.setDescription("description");
    def.setCreatedBy("unit_test");
    def.setCreateTime(1L);//w  ww. j a  v  a  2s.c om
    def.setInputKeys(Arrays.asList("a", "b", "c"));
    def.setOutputKeys(Arrays.asList("01", "o2"));
    def.setOwnerApp("ownerApp");
    def.setRetryCount(3);
    def.setRetryDelaySeconds(100);
    def.setRetryLogic(RetryLogic.FIXED);
    def.setTimeoutPolicy(TimeoutPolicy.ALERT_ONLY);
    def.setUpdatedBy("unit_test2");
    def.setUpdateTime(2L);

    dao.createTaskDef(def);

    TaskDef found = dao.getTaskDef(def.getName());
    assertTrue(EqualsBuilder.reflectionEquals(def, found));

    def.setDescription("updated description");
    dao.updateTaskDef(def);
    found = dao.getTaskDef(def.getName());
    assertTrue(EqualsBuilder.reflectionEquals(def, found));
    assertEquals("updated description", found.getDescription());

    for (int i = 0; i < 9; i++) {
        TaskDef tdf = new TaskDef("taskA" + i);
        dao.createTaskDef(tdf);
    }

    List<TaskDef> all = dao.getAllTaskDefs();
    assertNotNull(all);
    assertEquals(10, all.size());
    Set<String> allnames = all.stream().map(TaskDef::getName).collect(Collectors.toSet());
    assertEquals(10, allnames.size());
    List<String> sorted = allnames.stream().sorted().collect(Collectors.toList());
    assertEquals(def.getName(), sorted.get(0));

    for (int i = 0; i < 9; i++) {
        assertEquals(def.getName() + i, sorted.get(i + 1));
    }

    for (int i = 0; i < 9; i++) {
        dao.removeTaskDef(def.getName() + i);
    }
    all = dao.getAllTaskDefs();
    assertNotNull(all);
    assertEquals(1, all.size());
    assertEquals(def.getName(), all.get(0).getName());
}

From source file:io.gravitee.management.service.impl.ApplicationServiceImpl.java

@Override
public Set<ApplicationEntity> findByApi(String apiId) {
    try {//from   ww w  .  jav  a 2s .c  o  m
        LOGGER.debug("Find applications for api {}", apiId);
        final Set<ApiKey> applications = apiKeyRepository.findByApi(apiId);
        return applications.stream().map(application -> findById(application.getApplication()))
                .collect(Collectors.toSet());
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to get applications for api {}", apiId, ex);
        throw new TechnicalManagementException(
                "An error occurs while trying to get applications for api " + apiId, ex);
    }
}