List of usage examples for java.util.stream Collectors toSet
public static <T> Collector<T, ?, Set<T>> toSet()
From source file:com.devicehive.resource.impl.DeviceCommandResourceImpl.java
private void poll(final long timeout, final String deviceGuidsCsv, final String namesCsv, final String timestamp, final AsyncResponse asyncResponse) throws InterruptedException { final HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();/*from w w w.j av a2s .co m*/ final Date ts = TimestampQueryParamParser .parse(timestamp == null ? timestampService.getDateAsString() : timestamp); final Response response = ResponseFactory.response(Response.Status.OK, Collections.emptyList(), JsonPolicyDef.Policy.COMMAND_LISTED); asyncResponse.setTimeoutHandler(asyncRes -> asyncRes.resume(response)); Set<String> availableDevices; if (deviceGuidsCsv == null) { availableDevices = deviceService.findByGuidWithPermissionsCheck(Collections.emptyList(), principal) .stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); } else { availableDevices = Optional.ofNullable(StringUtils.split(deviceGuidsCsv, ',')).map(Arrays::asList) .map(list -> deviceService.findByGuidWithPermissionsCheck(list, principal)) .map(list -> list.stream().map(DeviceVO::getGuid).collect(Collectors.toSet())) .orElse(Collections.emptySet()); } Set<String> names = Optional.ofNullable(StringUtils.split(namesCsv, ',')).map(Arrays::asList) .map(list -> list.stream().collect(Collectors.toSet())).orElse(Collections.emptySet()); BiConsumer<DeviceCommand, String> callback = (command, subscriptionId) -> { if (!asyncResponse.isDone()) { asyncResponse.resume(ResponseFactory.response(Response.Status.OK, Collections.singleton(command), Policy.COMMAND_LISTED)); } }; if (!availableDevices.isEmpty()) { Pair<String, CompletableFuture<List<DeviceCommand>>> pair = commandService .sendSubscribeRequest(availableDevices, names, ts, callback); pair.getRight().thenAccept(collection -> { if (!collection.isEmpty() && !asyncResponse.isDone()) { asyncResponse.resume( ResponseFactory.response(Response.Status.OK, collection, Policy.COMMAND_LISTED)); } if (timeout == 0) { asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause // the thread to suspend indefinitely, see AsyncResponse docs } else { asyncResponse.setTimeout(timeout, TimeUnit.SECONDS); } }); asyncResponse.register(new CompletionCallback() { @Override public void onComplete(Throwable throwable) { commandService.sendUnsubscribeRequest(pair.getLeft(), null); } }); } else { if (!asyncResponse.isDone()) { asyncResponse.resume(response); } } }
From source file:org.thevortex.lighting.jinks.client.PubNubServiceNotifier.java
/** * Sets up client and subscribes to channels. * * @param serviceSubscription service level * @param itemSubscriptions all the bits *///from w ww . ja v a 2 s. co m synchronized void init(Subscription serviceSubscription, Set<Subscription> itemSubscriptions) { // if nothing's changed and already running, ignore this if (pnClient != null && Objects.equals(this.serviceSubscription, serviceSubscription) && Objects.equals(this.itemSubscriptions, itemSubscriptions)) { logger.debug("Client for {} already initialized.", serviceType); return; } close(); this.serviceSubscription = serviceSubscription; this.itemSubscriptions = itemSubscriptions; logger.info("Starting notification client for {}", serviceType); // subscribe with appropriate call-backs if (start()) { try { // over-all service listening if (serviceSubscription == null) { logger.warn("No type subscriptions for {}", serviceType); } else { String serviceChannel = serviceSubscription.getPubnub().getChannel(); logger.debug("Subscribing to {}", serviceChannel); pnClient.subscribe(serviceChannel, typeCallback); } // item subscriptions if (itemSubscriptions == null || itemSubscriptions.isEmpty()) { logger.warn("No item subscriptions for {}", serviceType); } else { Set<String> itemChannels = itemSubscriptions.stream() .map(subscription -> subscription.getPubnub().getChannel()).collect(Collectors.toSet()); String[] channels = itemChannels.toArray(new String[itemChannels.size()]); logger.debug("Subscribing to {}", itemChannels); pnClient.subscribe(channels, itemCallback); } } catch (Exception e) { close(); throw new SubscriptionException("Cannot subscribe to channels", e); } } }
From source file:com.devicehive.dao.NetworkDaoTest.java
@Test public void shouldFindByName() throws Exception { String name = RandomStringUtils.randomAlphabetic(10); int count = 0; for (int i = 0; i < 100; i++) { NetworkVO network = new NetworkVO(); network.setKey(RandomStringUtils.randomAlphabetic(20)); network.setDescription(RandomStringUtils.randomAlphabetic(20)); if (i % 2 == 0) { network.setName(name);/*from ww w . j a v a2 s . c om*/ count++; } else { network.setName(RandomStringUtils.randomAlphabetic(10)); } networkDao.persist(network); } List<NetworkVO> networks = networkDao.findByName(name); assertThat(networks, hasSize(count)); Set<String> names = networks.stream().map(NetworkVO::getName).collect(Collectors.toSet()); assertThat(names, hasSize(1)); assertThat(names, hasItem(name)); }
From source file:oauth2.authentication.UserAuthenticationProvider.java
protected Set<GrantedAuthority> mapAuthorities(User user) { Set<GrantedAuthority> authorities; if (user.isPasswordExpired()) { LOGGER.debug("User {}: Credentials have expired", user.getUserId()); authorities = ImmutableSet.of(new SimpleGrantedAuthority("ROLE_" + Roles.MUST_CHANGE_PASSWORD)); } else {/*from www .jav a 2s .c om*/ authorities = user.getEntries().stream() // .filter(entry -> Objects.equal("AUTHORITY", entry.getName())) // .map(entry -> new SimpleGrantedAuthority(entry.getData())) // .collect(Collectors.toSet()); } return authorities; }
From source file:edu.zipcloud.cloudstreetmarket.core.services.StockProductServiceOfflineImpl.java
@Override @Transactional/*from w ww .j a v a 2s . c o m*/ public Page<StockProduct> gather(String userId, String indexId, String exchangeId, MarketId marketId, String startWith, Specification<StockProduct> spec, Pageable pageable) { Page<StockProduct> stocks = get(indexId, exchangeId, marketId, startWith, spec, pageable, false); if (AuthenticationUtil.userHasRole(Role.ROLE_OAUTH2)) { updateStocksAndQuotesFromYahoo(stocks.getContent().stream().collect(Collectors.toSet())); return get(indexId, exchangeId, marketId, startWith, spec, pageable, false); } return stocks; }
From source file:tds.assessment.services.impl.SegmentServiceImpl.java
@Override @Cacheable(CacheType.LONG_TERM)//from ww w .jav a2s . com public Optional<SegmentItemInformation> findSegmentItemInformation(final String segmentKey) { //This method is a port of ItemSelectionDLL.AA_GetSegment2_SP Optional<Assessment> maybeAssessment = assessmentService.findAssessmentBySegmentKey(segmentKey); if (!maybeAssessment.isPresent()) { return Optional.empty(); } Assessment assessment = maybeAssessment.get(); Segment segment = assessment.getSegment(segmentKey); List<ContentLevelSpecification> specifications = strandQueryRepository .findContentLevelSpecificationsBySegmentKey(segmentKey); List<ItemGroup> itemGroups = itemGroupQueryRepository.findItemGroupsBySegment(segmentKey); List<Item> segmentItems = segment.getItems(); List<Item> siblingItems = new ArrayList<>(); if (assessment.isSegmented()) { Set<String> segmentItemIds = segment.getItems().stream().map(Item::getId).collect(Collectors.toSet()); for (Segment seg : assessment.getSegments()) { if (seg.getKey().equals(segment.getKey())) continue; List<Item> items = seg.getItems().stream().filter(item -> !segmentItemIds.contains(item.getId())) .collect(Collectors.toList()); siblingItems.addAll(items); } } List<ItemMeasurement> itemMeasurements = itemMeasurementQueryRepository.findItemMeasurements(segmentKey, assessment.getKey()); List<ItemControlParameter> controlParameters = itemControlParametersQueryRepository .findControlParametersForSegment(segmentKey); List<ItemProperty> properties = itemQueryRepository.findActiveItemsProperties(segmentKey); List<ItemProperty> segmentProperties = properties.stream() .filter(itemProperty -> itemProperty.getValue().startsWith(OFF_GRADE_PROP_VALUE_PREFIX) && PROP_NAME_TYPE.equals(itemProperty.getName())) .collect(Collectors.toList()); return Optional.of(new SegmentItemInformation.Builder().withSegment(segment).withItemGroups(itemGroups) .withSiblingItems(siblingItems).withSegmentItems(segmentItems) .withItemMeasurements(itemMeasurements).withControlParameters(controlParameters) .withPoolFilterProperties(segmentProperties).withContentLevelSpecifications(specifications) .build()); }
From source file:com.devicehive.websockets.handlers.CommandHandlers.java
@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_COMMAND')") public WebSocketResponse processCommandSubscribe(JsonObject request, WebSocketSession session) throws InterruptedException { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();//from w w w. jav a2s .c o m final Date timestamp = gson.fromJson(request.get(TIMESTAMP), Date.class); final String deviceId = Optional.ofNullable(request.get(Constants.DEVICE_GUID)) .map(JsonElement::getAsString).orElse(null); final Set<String> names = gson.fromJson(request.getAsJsonArray(NAMES), JsonTypes.STRING_SET_TYPE); Set<String> devices = gson.fromJson(request.getAsJsonArray(DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); logger.debug("command/subscribe requested for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session); devices = prepareActualList(devices, deviceId); List<DeviceVO> actualDevices; if (devices != null) { actualDevices = deviceService.findByGuidWithPermissionsCheck(devices, principal); if (actualDevices.size() != devices.size()) { throw new HiveException(String.format(Messages.DEVICES_NOT_FOUND, devices), SC_FORBIDDEN); } } else { actualDevices = deviceService .list(null, null, null, null, null, null, null, true, null, null, principal).join(); devices = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); } BiConsumer<DeviceCommand, String> callback = (command, subscriptionId) -> { JsonObject json = ServerResponsesFactory.createCommandInsertMessage(command, subscriptionId); sendMessage(json, session); }; Pair<String, CompletableFuture<List<DeviceCommand>>> pair = commandService.sendSubscribeRequest(devices, names, timestamp, callback); pair.getRight().thenAccept(collection -> collection .forEach(cmd -> sendMessage(ServerResponsesFactory.createCommandInsertMessage(cmd, pair.getLeft()), session))); logger.debug("command/subscribe done for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session.getId()); ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).add(pair.getLeft()); WebSocketResponse response = new WebSocketResponse(); response.addValue(SUBSCRIPTION_ID, pair.getLeft(), null); return response; }
From source file:com.wrmsr.wava.yen.translation.UnitTranslation.java
public static Module translateModule(Name name, YModule module) { YMemory ymemory = module.getMemory(); Memory memory = new Memory(ymemory.getInitial(), ymemory.getMax() >= 0 ? OptionalInt.of(ymemory.getMax()) : OptionalInt.empty(), ymemory .getSegments().stream().map( s -> new Segment(s.getOffset(), s.getData().length == s.getSize() ? s.getData() : Arrays.copyOf(s.getData(), s.getSize()))) .collect(toImmutableList())); Table table = new Table(module.getTable().getNames()); Map<Name, Signature> functionSignatures = ImmutableMap.<Name, Signature>builder() .putAll(module.getFunctions().stream() .map(f -> ImmutablePair.of(f.getName().get(), new Signature(f.getResult(), f.getParams()))) .collect(toImmutableList())) .putAll(module.getImports().stream() .map(i -> ImmutablePair.of(i.getName().get(), new Signature(i.getType().getResult(), i.getType().getParams()))) .collect(toImmutableList())) .build();//w w w . ja v a 2 s.c o m Map<Name, Import> imports = module.getImports().stream() .map(i -> ImmutablePair.of(i.getName().get(), new Import(i.getName().get(), i.getModule(), i.getBase(), new Signature(i.getType().getResult(), i.getType().getParams())))) .collect(toImmutableMap()); Map<Name, Export> exports = module.getExports().stream() .map(e -> ImmutablePair.of(e.getName().get(), new Export(e.getName().get(), e.getValue()))) .collect(toImmutableMap()); Map<Name, Function> functions = module.getFunctions().stream().parallel() // FIXME boo this man .map(f -> ImmutablePair.of(f.getName().get(), translateFunction(f, functionSignatures))) .sequential().collect(toImmutableMap()); Set<Signature> declaredSignatures = module.getNamedFunctionTypes().stream() .map(i -> new Signature(i.getResult(), i.getParams())).collect(Collectors.toSet()); return new Module(name, memory, table, declaredSignatures, imports, exports, functions); }
From source file:org.ow2.proactive.connector.iaas.cloud.provider.vmware.VMWareProvider.java
@Override public Set<Instance> createInstance(Infrastructure infrastructure, Instance instance) { String image = instance.getImage(); Folder rootFolder = vmWareServiceInstanceCache.getServiceInstance(infrastructure).getRootFolder(); String instanceImageId = getInstanceIdFromImage(image); VirtualMachineRelocateSpec relocateSpecs = inferRelocateSpecsFromImageArgument(image, rootFolder); Folder destinationFolder = getDestinationFolderFromImage(image, rootFolder); VirtualMachine vmToClone = getVirtualMachineByNameOrUUID(instanceImageId, rootFolder); return IntStream.rangeClosed(1, Integer.valueOf(instance.getNumber())) .mapToObj(instanceIndexStartAt1 -> cloneVM(vmToClone, createUniqInstanceTag(instance.getTag(), instanceIndexStartAt1), instance, rootFolder, createVirtualMachineCloneSpec(instanceIndexStartAt1, vmToClone, relocateSpecs, instance), destinationFolder))/*w w w. j a v a 2s .c om*/ .map(vm -> instance.withId(vm.getConfig().getUuid())).collect(Collectors.toSet()); }
From source file:se.uu.it.cs.recsys.constraint.builder.ScheduleDomainBuilder.java
private Map<CourseSchedule, Set<Integer>> getTaughtYearAndStartPeriodToIdMapping(Set<CourseSchedule> schedule) { Map<CourseSchedule, Set<Integer>> taughtYearAndStartPeriodToIdMapping = new HashMap<>(); schedule.forEach(sch -> {// w ww . j a v a 2 s . com Set<Course> courseSet = this.courseRepository.findByTaughtYearAndStartPeriod(sch.getTaughtYear(), sch.getStartPeriod()); Set<Integer> idSet = courseSet.stream().map(c -> c.getAutoGenId()).collect(Collectors.toSet()); taughtYearAndStartPeriodToIdMapping.put(sch, idSet); }); return taughtYearAndStartPeriodToIdMapping; }