List of usage examples for java.util.stream Collectors toSet
public static <T> Collector<T, ?, Set<T>> toSet()
From source file:se.uu.it.cs.recsys.constraint.util.ConstraintResultConverter.java
public List<Course> convert(Domain[] solution) { List<Course> result = new ArrayList<>(); if (solution == null || solution.length == 0) { LOGGER.debug("Input result is empty!"); return result; }//from www. j a va2 s. c o m for (Domain var : solution) { LOGGER.debug("Solution domain to be converted: " + var.toString()); SetDomainValueEnumeration ve = (SetDomainValueEnumeration) (var.valueEnumeration()); Set<Integer> courseIds = new HashSet<>(); while (ve.hasMoreElements()) { int[] elemArray = ve.nextSetElement().toIntArray(); for (int elem : elemArray) { courseIds.add(elem); } } Set<se.uu.it.cs.recsys.persistence.entity.Course> courseEntities = this.courseRepository .findByAutoGenIds(courseIds); Set<Course> courseInfoSet = courseEntities.stream().map(course -> CourseConverter.convert(course)) .collect(Collectors.toSet()); result.addAll(courseInfoSet); } return result; }
From source file:com.devicehive.service.NetworkService.java
@Transactional(propagation = Propagation.NOT_SUPPORTED) public NetworkWithUsersAndDevicesVO getWithDevicesAndDeviceClasses(@NotNull Long networkId, @NotNull HiveAuthentication hiveAuthentication) { HivePrincipal principal = (HivePrincipal) hiveAuthentication.getPrincipal(); Set<Long> permittedNetworks = principal.getNetworkIds(); Set<String> permittedDevices = principal.getDeviceGuids(); Optional<NetworkWithUsersAndDevicesVO> result = of(principal).flatMap(pr -> { if (pr.getUser() != null) return of(pr.getUser()); else// www . ja v a 2 s . co m return empty(); }).flatMap(user -> { Long idForFiltering = user.isAdmin() ? null : user.getId(); List<NetworkWithUsersAndDevicesVO> found = networkDao.getNetworksByIdsAndUsers(idForFiltering, Collections.singleton(networkId), permittedNetworks); return found.stream().findFirst(); }).map(network -> { //fixme - important, restore functionality once permission evaluator is switched to jwt /*if (principal.getKey() != null) { Set<AccessKeyPermissionVO> permissions = principal.getKey().getPermissions(); Set<AccessKeyPermissionVO> filtered = CheckPermissionsHelper .filterPermissions(principal.getKey(), permissions, AccessKeyAction.GET_DEVICE, details.getClientInetAddress(), details.getOrigin()); if (filtered.isEmpty()) { network.setDevices(Collections.emptySet()); } }*/ if (permittedDevices != null && !permittedDevices.isEmpty()) { Set<DeviceVO> allowed = network.getDevices().stream() .filter(device -> permittedDevices.contains(device.getGuid())).collect(Collectors.toSet()); network.setDevices(allowed); } return network; }); return result.orElse(null); }
From source file:com.mgmtp.perfload.perfalyzer.workflow.MeasuringWorkflow.java
@Override public List<Runnable> getNormalizationTasks(final File inputDir, final File outputDir) { Runnable task = () -> {// www . j a v a2 s. c o m List<File> inputFiles = DirectoryLister.listFiles(inputDir); Set<File> fileSet = inputFiles.stream().filter(fileNameContains("measuring")) .map(makeAbsolute(inputDir)).collect(Collectors.toSet()); final File sortMergeOutputDir = createTempDir(); File mergedMeasuringLog = new File("global/measuring-logs/measuring.csv"); try { log.info("Merging measuring logs to '{}'", mergedMeasuringLog); CsvFileSortMerger merger = new CsvFileSortMerger(fileSet, new File(sortMergeOutputDir, mergedMeasuringLog.getPath()), new CsvTimestampColumnComparator(';', 3)); merger.mergeFiles(); MeasuringNormalizingStrategy strat = new MeasuringNormalizingStrategy(timestampNormalizer); Normalizer normalizer = new Normalizer(sortMergeOutputDir, outputDir, strat); log.info("Normalizing '{}'", mergedMeasuringLog); normalizer.normalize(mergedMeasuringLog); } catch (Exception ex) { throw new PerfAlyzerException("Error normalizing file: " + mergedMeasuringLog, ex); } finally { deleteQuietly(sortMergeOutputDir); } }; return ImmutableList.of(task); }
From source file:org.keycloak.testsuite.saml.IdpInitiatedLoginTest.java
@Test public void testTwoConsequentIdpInitiatedLogins() { new SamlClientBuilder().idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build() .login().user(bburkeUser).build().processSamlResponse(Binding.POST).transformObject(ob -> { assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS)); ResponseType resp = (ResponseType) ob; assertThat(resp.getDestination(), is(SAML_ASSERTION_CONSUMER_URL_SALES_POST)); return null; }).build()//ww w. j ava 2 s. co m .idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post2").build().login().sso(true) .build().processSamlResponse(Binding.POST).transformObject(ob -> { assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS)); ResponseType resp = (ResponseType) ob; assertThat(resp.getDestination(), is(SAML_ASSERTION_CONSUMER_URL_SALES_POST2)); return null; }).build() .execute(); final UsersResource users = adminClient.realm(REALM_NAME).users(); final ClientsResource clients = adminClient.realm(REALM_NAME).clients(); UserRepresentation bburkeUserRepresentation = users.search(bburkeUser.getUsername()).stream().findFirst() .get(); List<UserSessionRepresentation> userSessions = users.get(bburkeUserRepresentation.getId()) .getUserSessions(); assertThat(userSessions, hasSize(1)); Map<String, String> clientSessions = userSessions.get(0).getClients(); Set<String> clientIds = clientSessions.values().stream().flatMap(c -> clients.findByClientId(c).stream()) .map(ClientRepresentation::getClientId).collect(Collectors.toSet()); assertThat(clientIds, containsInAnyOrder(SAML_CLIENT_ID_SALES_POST, SAML_CLIENT_ID_SALES_POST2)); }
From source file:com.netflix.spinnaker.clouddriver.ecs.services.EcsCloudMetricService.java
private Set<String> buildResourceList(List<String> metricAlarmArn, String serviceName) { return metricAlarmArn.stream().filter(arn -> arn.contains(serviceName)).map(arn -> { String resource = StringUtils.substringAfterLast(arn, ":resource/"); resource = StringUtils.substringBeforeLast(resource, ":policyName"); return resource; }).collect(Collectors.toSet()); }
From source file:com.thinkbiganalytics.metadata.modeshape.security.role.JcrAbstractRoleMembership.java
@Override public Set<Principal> getMembers() { Stream<? extends Principal> groups = streamGroups(); Stream<? extends Principal> users = streamUsers(); return Stream.concat(groups, users).collect(Collectors.toSet()); }
From source file:eu.tripledframework.eventstore.infrastructure.ReflectionObjectConstructor.java
private Method getEventHandlerMethods(DomainEvent event) { Set<Method> methods = Arrays.stream(targetClass.getMethods()) .filter(constructor -> constructor.isAnnotationPresent(ConstructionHandler.class)) .collect(Collectors.toSet()); for (Method method : methods) { ConstructionHandler annotation = method.getAnnotation(ConstructionHandler.class); if (annotation.value().equals(event.getClass())) { return method; }/*from w w w . ja va 2s .c o m*/ } return null; }
From source file:org.obiba.mica.web.model.NetworkDtos.java
@NotNull Mica.NetworkDto.Builder asDtoBuilder(@NotNull Network network, boolean asDraft) { Mica.NetworkDto.Builder builder = Mica.NetworkDto.newBuilder(); if (network.hasModel()) builder.setContent(JSONUtils.toJSON(network.getModel())); builder.setId(network.getId()) // .addAllName(localizedStringDtos.asDto(network.getName())) // .addAllDescription(localizedStringDtos.asDto(network.getDescription())) // .addAllAcronym(localizedStringDtos.asDto(network.getAcronym())); Mica.PermissionsDto permissionsDto = permissionsDtos.asDto(network); NetworkState networkState = networkService.getEntityState(network.getId()); builder.setPublished(networkState.isPublished()); if (asDraft) { builder.setTimestamps(TimestampsDtos.asDto(network)) // .setPublished(networkState.isPublished()) // .setExtension(Mica.EntityStateDto.state, entityStateDtos.asDto(networkState).setPermissions(permissionsDto).build()); }//from w ww . j a v a2 s . c o m builder.setPermissions(permissionsDto); List<String> roles = micaConfigService.getConfig().getRoles(); if (network.getMemberships() != null) { List<Mica.MembershipsDto> memberships = network.getMemberships().entrySet().stream() .filter(e -> roles.contains(e.getKey())) .map(e -> Mica.MembershipsDto.newBuilder().setRole(e.getKey()).addAllMembers(e.getValue() .stream().map(m -> personDtos.asDto(m.getPerson(), asDraft)).collect(toList())).build()) .collect(toList()); builder.addAllMemberships(memberships); } List<BaseStudy> publishedStudies = publishedStudyService.findByIds(network.getStudyIds()); Set<String> publishedStudyIds = publishedStudies.stream().map(AbstractGitPersistable::getId) .collect(Collectors.toSet()); Sets.SetView<String> unpublishedStudyIds = Sets.difference(ImmutableSet.copyOf(network.getStudyIds() .stream() .filter(sId -> asDraft && subjectAclService.isPermitted("/draft/individual-study", "VIEW", sId) || subjectAclService.isAccessible("/individual-study", sId)) .collect(toList())), publishedStudyIds); if (!publishedStudies.isEmpty()) { Map<String, Long> datasetVariableCounts = asDraft ? null : datasetVariableService.getCountByStudyIds(Lists.newArrayList(publishedStudyIds)); publishedStudies.forEach(study -> { builder.addStudyIds(study.getId()); builder.addStudySummaries(studySummaryDtos.asDtoBuilder(study, true, datasetVariableCounts == null ? 0 : datasetVariableCounts.get(study.getId()))); }); } unpublishedStudyIds.forEach(studyId -> { try { builder.addStudySummaries(studySummaryDtos.asDto(studyId)); builder.addStudyIds(studyId); } catch (NoSuchEntityException e) { log.warn("Study not found in network {}: {}", network.getId(), studyId); // ignore } }); if (network.getLogo() != null) { builder.setLogo(attachmentDtos.asDto(network.getLogo())); } network.getNetworkIds().stream() .filter(nId -> asDraft && subjectAclService.isPermitted("/draft/network", "VIEW", nId) || subjectAclService.isAccessible("/network", nId)) .forEach(nId -> { try { builder.addNetworkSummaries(networkSummaryDtos.asDtoBuilder(nId, asDraft)); builder.addNetworkIds(nId); } catch (NoSuchEntityException e) { log.warn("Network not found in network {}: {}", network.getId(), nId); // ignore } }); return builder; }
From source file:com.devicehive.websockets.handlers.NotificationHandlers.java
@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_NOTIFICATION')") public WebSocketResponse processNotificationSubscribe(JsonObject request, WebSocketSession session) throws InterruptedException { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();/*from w w w. j a v a2 s . c o m*/ Date timestamp = gson.fromJson(request.get(Constants.TIMESTAMP), Date.class); Set<String> devices = gson.fromJson(request.get(Constants.DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); Set<String> names = gson.fromJson(request.get(Constants.NAMES), JsonTypes.STRING_SET_TYPE); String deviceId = Optional.ofNullable(request.get(Constants.DEVICE_GUID)).map(JsonElement::getAsString) .orElse(null); logger.debug("notification/subscribe requested for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session.getId()); 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<DeviceNotification, String> callback = (notification, subscriptionId) -> { JsonObject json = ServerResponsesFactory.createNotificationInsertMessage(notification, subscriptionId); sendMessage(json, session); }; Pair<String, CompletableFuture<List<DeviceNotification>>> pair = notificationService.subscribe(devices, names, timestamp, callback); pair.getRight().thenAccept(collection -> collection.forEach(notification -> { JsonObject json = ServerResponsesFactory.createNotificationInsertMessage(notification, pair.getLeft()); sendMessage(json, session); })); logger.debug("notification/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.pscnlab.member.services.impl.MemberSeviceImpl.java
@Override public Page<MemberPageDTO> findPage(MemberPageQueryDTO query, Integer offset, Integer size) { Page<Member> page = memberDao.findPage(query, offset, size); List<Member> results = page.getResults(); if (CollectionUtils.isEmpty(results)) { return Page.build(new ArrayList<>(), page.getTotalCount()); }/* w w w. ja va2 s . c om*/ //? Set<Integer> roleIds = results.stream().map(Member::getUuidRole).collect(Collectors.toSet()); Map<Integer, Role> roleMap = roleService.findMapByRoleIds(roleIds); List<MemberPageDTO> memberPageDTOS = new ArrayList<>(); for (Member result : results) { MemberPageDTO memberPageDTO = new MemberPageDTO(); memberPageDTO.setMember(result); memberPageDTO.setRole(roleMap.get(result.getUuidRole())); memberPageDTOS.add(memberPageDTO); } return Page.build(memberPageDTOS, page.getTotalCount()); }