Example usage for java.util.stream Collectors toSet

List of usage examples for java.util.stream Collectors toSet

Introduction

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

Prototype

public static <T> Collector<T, ?, Set<T>> toSet() 

Source Link

Document

Returns a Collector that accumulates the input elements into a new Set .

Usage

From source file:com.thoughtworks.go.server.service.AdminsConfigService.java

private BulkUpdateAdminsResult validateUsersAndRolesForBulkUpdate(List<String> usersToRemove,
        List<String> rolesToRemove, Set<Admin> existingAdmins) {
    Set<CaseInsensitiveString> existingAdminNames = existingAdmins.stream().map(Admin::getName)
            .collect(Collectors.toSet());
    Sets.SetView<CaseInsensitiveString> invalidUsersToRemove = Sets.difference(caseInsensitive(usersToRemove),
            existingAdminNames);/*  w w w.j  av a2 s . com*/
    Sets.SetView<CaseInsensitiveString> invalidRolesToRemove = Sets.difference(caseInsensitive(rolesToRemove),
            existingAdminNames);
    BulkUpdateAdminsResult result = new BulkUpdateAdminsResult();
    if (invalidUsersToRemove.size() > 0) {
        result.setNonExistentUsers(invalidUsersToRemove);
        result.unprocessableEntity(
                "Update failed because some users or roles do not exist under super admins.");
    }
    if (invalidRolesToRemove.size() > 0) {
        result.setNonExistentRoles(invalidRolesToRemove);
        result.unprocessableEntity(
                "Update failed because some users or roles do not exist under super admins.");
    }
    return result;
}

From source file:com.devicehive.handler.notification.NotificationSubscribeInsertIntegrationTest.java

@Test
public void shouldSubscribeToDeviceNotifications() throws Exception {
    String device1 = randomUUID().toString();
    String device2 = randomUUID().toString();

    String subscriber1 = randomUUID().toString();
    String subscriber2 = randomUUID().toString();
    String subscriber3 = randomUUID().toString();

    NotificationSubscribeRequest sr1 = new NotificationSubscribeRequest(subscriber1, device1, null, null);
    Request r1 = Request.newBuilder().withBody(sr1).withSingleReply(false).build();
    TestCallback c1 = new TestCallback();
    client.call(r1, c1);/*w w  w .  j  ava 2  s  . co m*/

    NotificationSubscribeRequest sr2 = new NotificationSubscribeRequest(subscriber1, device2,
            Collections.singleton("temperature"), null);
    Request r2 = Request.newBuilder().withBody(sr2).withSingleReply(false).build();
    TestCallback c2 = new TestCallback();
    client.call(r2, c2);

    NotificationSubscribeRequest sr3 = new NotificationSubscribeRequest(subscriber2, device2, null, null);
    Request r3 = Request.newBuilder().withBody(sr3).withSingleReply(false).build();
    TestCallback c3 = new TestCallback();
    client.call(r3, c3);

    NotificationSubscribeRequest sr4 = new NotificationSubscribeRequest(subscriber2, device1,
            Collections.singleton("vibration"), null);
    Request r4 = Request.newBuilder().withBody(sr4).withSingleReply(false).build();
    TestCallback c4 = new TestCallback();
    client.call(r4, c4);

    NotificationSubscribeRequest sr5 = new NotificationSubscribeRequest(subscriber3, randomUUID().toString(),
            null, null);
    Request r5 = Request.newBuilder().withBody(sr5).withSingleReply(false).build();
    TestCallback c5 = new TestCallback();
    client.call(r5, c5);

    //wait subsribers to subscribe
    Stream.of(c1.subscribeFuture, c2.subscribeFuture, c3.subscribeFuture, c4.subscribeFuture,
            c5.subscribeFuture).forEach(CompletableFuture::join);

    //devices send notifications
    List<CompletableFuture<Response>> futures = Stream.of(device1, device2).flatMap(device -> {
        List<CompletableFuture<Response>> list = Stream.of("temperature", "vibration").map(name -> {
            DeviceNotification notification = new DeviceNotification();
            notification.setId(0);
            notification.setNotification(name);
            notification.setDeviceGuid(device);
            NotificationInsertRequest event = new NotificationInsertRequest(notification);
            CompletableFuture<Response> f = new CompletableFuture<>();
            client.call(Request.newBuilder().withBody(event).build(), f::complete);
            return f;
        }).collect(Collectors.toList());
        return list.stream();
    }).collect(Collectors.toList());

    //wait notifications delivered
    futures.forEach(CompletableFuture::join);

    assertThat(c1.notifications, hasSize(2));
    c1.notifications.forEach(event -> {
        assertNotNull(event.getNotification());
        assertEquals(event.getNotification().getDeviceGuid(), device1);
        assertEquals(event.getNotification().getId(), Long.valueOf(0));
    });
    Set<String> names = c1.notifications.stream().map(n -> n.getNotification().getNotification())
            .collect(Collectors.toSet());
    assertThat(names, containsInAnyOrder("temperature", "vibration"));

    assertThat(c2.notifications, hasSize(1));
    NotificationEvent e = c2.notifications.stream().findFirst().get();
    assertNotNull(e.getNotification());
    assertEquals(e.getNotification().getDeviceGuid(), device2);
    assertEquals(e.getNotification().getId(), Long.valueOf(0));
    assertEquals(e.getNotification().getNotification(), "temperature");

    assertThat(c3.notifications, hasSize(2));
    c3.notifications.forEach(event -> {
        assertNotNull(event.getNotification());
        assertEquals(event.getNotification().getDeviceGuid(), device2);
        assertEquals(event.getNotification().getId(), Long.valueOf(0));
    });
    names = c3.notifications.stream().map(n -> n.getNotification().getNotification())
            .collect(Collectors.toSet());
    assertThat(names, containsInAnyOrder("temperature", "vibration"));

    assertThat(c4.notifications, hasSize(1));
    e = c4.notifications.stream().findFirst().get();
    assertNotNull(e.getNotification());
    assertEquals(e.getNotification().getDeviceGuid(), device1);
    assertEquals(e.getNotification().getId(), Long.valueOf(0));
    assertEquals(e.getNotification().getNotification(), "vibration");

    assertThat(c5.notifications, is(empty()));
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.vm.AzureVMsProvider.java

@Override
public Set<Instance> createInstance(Infrastructure infrastructure, Instance instance) {

    Azure azureService = azureServiceCache.getService(infrastructure);
    String instanceTag = Optional.ofNullable(instance.getTag()).orElseThrow(
            () -> new RuntimeException("ERROR missing instance tag/name from instance: '" + instance + "'"));

    // Check for Image by name first and then by id
    String imageNameOrId = Optional.ofNullable(instance.getImage()).orElseThrow(
            () -> new RuntimeException("ERROR missing Image name/id from instance: '" + instance + "'"));

    VirtualMachineCustomImage image = getImageByName(azureService, imageNameOrId)
            .orElseGet(() -> getImageById(azureService, imageNameOrId).orElseThrow(() -> new RuntimeException(
                    "ERROR unable to find custom Image: '" + instance.getImage() + "'")));

    // Get the options (Optional by design)
    Optional<Options> options = Optional.ofNullable(instance.getOptions());

    // Try to retrieve the resourceGroup from provided name, otherwise get it from image
    ResourceGroup resourceGroup = azureProviderUtils
            .searchResourceGroupByName(azureService,
                    options.map(Options::getResourceGroup).orElseGet(image::resourceGroupName))
            .orElseThrow(() -> new RuntimeException(
                    "ERROR unable to find a suitable resourceGroup from instance: '" + instance + "'"));

    // Try to get region from provided name, otherwise get it from image
    Region region = options.map(presentOptions -> Region.findByLabelOrName(presentOptions.getRegion()))
            .orElseGet(image::region);/*ww w.  ja v  a2 s  .  c o  m*/

    // Prepare the VM(s)
    Optional<Boolean> optionalStaticPublicIP = options.map(Options::getStaticPublicIP);
    List<Creatable<VirtualMachine>> creatableVirtualMachines = prepareCreatableVirtualMachines(azureService,
            options, region, resourceGroup, instanceTag, instance, image, optionalStaticPublicIP);

    // Create all VMs in parallel and collect IDs
    return azureService.virtualMachines().create(creatableVirtualMachines).values().stream()
            .map(vm -> instance.withTag(vm.name()).withId(vm.vmId()).withNumber(SINGLE_INSTANCE_NUMBER))
            .collect(Collectors.toSet());
}

From source file:com.yodle.vantage.functional.config.VantageFunctionalTest.java

protected void compareResolvedDependencies(Set<Dependency> expected, Set<Dependency> actual) {
    Set<Dependency> sanitized = expected.stream().map(this::sanitizeDependency).collect(Collectors.toSet());
    assertEquals(sanitized, actual);/*from w  w  w. jav a2  s .c  o m*/
}

From source file:com.thinkbiganalytics.metadata.modeshape.security.role.JcrAbstractRoleMembership.java

@Override
public void setMemebers(GroupPrincipal... principals) {
    Set<GroupPrincipal> newMembers = Arrays.stream(principals).collect(Collectors.toSet());
    Set<GroupPrincipal> oldMembers = streamGroups().collect(Collectors.toSet());

    newMembers.stream().filter(u -> !oldMembers.contains(u)).forEach(this::addMember);

    oldMembers.stream().filter(u -> !newMembers.contains(u)).forEach(this::removeMember);
}

From source file:se.uu.it.cs.recsys.service.preference.ConstraintSolverPreferenceBuilder.java

private Set<Integer> getInterestedCourseIdCollection(Set<CourseSchedule> scheduleInfo) {

    Set<String> codes = this.apiPref.getInterestedCourseCodeCollection();

    final Set<Integer> totalIdSet = new HashSet<>();

    if (codes == null || codes.isEmpty()) {

        totalIdSet.addAll(this.courseRepository.findAll().stream().filter(inPlanYearPredicate(scheduleInfo))
                .map(c -> c.getAutoGenId()).collect(Collectors.toSet()));

    } else {/*from   w  w  w  . ja  v a 2s .co m*/
        codes.forEach(code -> {
            Set<Integer> partIds = this.courseRepository.findByCode(code).stream()
                    .filter(inPlanYearPredicate(scheduleInfo)).map(c -> c.getAutoGenId())
                    .collect(Collectors.toSet());

            if (!partIds.isEmpty()) {
                totalIdSet.addAll(partIds);
            }
        });
    }

    return totalIdSet;
}

From source file:org.hsweb.concureent.cache.monitor.RedisMonitorCache.java

@Override
public Set<Object> keySet() {
    return (Set<Object>) redisOperations.execute((RedisCallback) connection -> connection.sMembers(keySetKey)
            .stream().map(String::new).collect(Collectors.toSet()));
}

From source file:pl.edu.icm.comac.vis.server.service.SearchService.java

protected void updateResultsWithTypes(List<SearchResult> searchResults) throws OpenRDFException {
    Set<String> ids = searchResults.stream().map(x -> x.getId()).collect(Collectors.toSet());
    try {//from   www  . j a  v  a2  s . co m
        Map<String, NodeType> types = typeService.identifyTypes(ids);
        searchResults.parallelStream().forEachOrdered(x -> x.setType(types.get(x.getId())));
    } catch (UnknownNodeException ex) {
        log.error("Unexpected inconsistency in data, no type defined for node", ex);
    }
    return;

}

From source file:org.openlmis.fulfillment.web.util.StockEventBuilder.java

private List<StockEventLineItemDto> getLineItems(Shipment shipment, Profiler profiler) {
    profiler.start("GET_ORDERABLE_IDS");
    Set<UUID> orderableIds = shipment.getLineItems().stream().map(ShipmentLineItem::getOrderableId)
            .collect(Collectors.toSet());

    profiler.start("GET_ORDERABLES_BY_IDS");
    Map<UUID, OrderableDto> orderables = getOrderables(orderableIds);

    profiler.start("GET_DESTINATION_ID");
    UUID destinationId = getDestinationId(shipment.getSupplyingFacilityId(), shipment.getReceivingFacilityId(),
            shipment.getProgramId());//from   w  ww . ja  va  2  s .c om

    profiler.start("CREATE_STOCK_EVENT_LINE_ITEMS");
    return shipment.getLineItems().stream().map(lineItem -> createLineItem(lineItem, orderables, destinationId))
            .collect(Collectors.toList());
}

From source file:it.serverSystem.LogsTest.java

private Collection<String> logLevelsOf(File webLogs) {
    return Files.linesOf(webLogs, "UTF-8").stream().filter(str -> str.length() >= 25)
            .map(str -> str.substring(20, 25)).map(String::trim).collect(Collectors.toSet());
}