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:info.archinnov.achilles.internals.apt.processors.meta.AchillesProcessor.java

private List<EntityMetaSignature> discoverAndValidateTablesAndViews(Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv, GlobalParsingContext parsingContext) {
    final List<TypeElement> tableTypes = annotations.stream()
            .filter(annotation -> isAnnotationOfType(annotation, Table.class))
            .flatMap(annotation -> roundEnv.getElementsAnnotatedWith(annotation).stream())
            .map(MoreElements::asType).collect(toList());

    final List<TypeElement> viewTypes = annotations.stream()
            .filter(annotation -> isAnnotationOfType(annotation, MaterializedView.class))
            .flatMap(annotation -> roundEnv.getElementsAnnotatedWith(annotation).stream())
            .map(MoreElements::asType).collect(toList());

    final List<TypeElement> types = CollectionsHelper.appendAll(tableTypes, viewTypes);

    validateEntityNames(types);//  w w w.j  a  v a2 s  .  c  o  m

    final List<EntityMetaSignature> tableSignatures = tableTypes.stream()
            .map(x -> entityParser.parseEntity(x, parsingContext)).collect(toList());

    final List<EntityMetaSignature> viewSignatures = viewTypes.stream()
            .map(x -> entityParser.parseView(x, parsingContext)).collect(toList());

    final List<EntityMetaSignature> tableAndViewSignatures = CollectionsHelper.appendAll(tableSignatures,
            viewSignatures);

    validateViewsAgainstBaseTable(aptUtils, viewSignatures, tableSignatures);
    return tableAndViewSignatures;
}

From source file:org.artifactory.ui.rest.service.artifacts.browse.treebrowser.tabs.general.licenses.ScanArtifactForLicensesService.java

@Override
public void execute(ArtifactoryRestRequest request, RestResponse response) {
    RepoPath path = RequestUtils.getPathFromRequest(request);
    if (!authService.canAnnotate(path)) {
        response.error("Insufficient permissions for operation").responseCode(HttpStatus.SC_UNAUTHORIZED);
        return;/*from  ww w .  j a  va  2 s  .c o m*/
    }
    Set<LicenseInfo> foundLicenses = addonsManager.addonByType(LicensesAddon.class).scanPathForLicenses(path);
    if (foundLicenses.isEmpty()
            || (foundLicenses.size() == 1 && foundLicenses.iterator().next().isNotFound())) {
        //Don't send "not found" object - UI gets empty array and handles
        response.iModelList(Lists.newArrayList());
    } else {
        response.iModel(foundLicenses.stream().map(GeneralTabLicenseModel::new).collect(Collectors.toList()));
    }
}

From source file:com.capitalone.dashboard.evaluator.LibraryPolicyEvaluator.java

/**
 * Reusable method for constructing the LibraryPolicyAuditResponse object
 *
 * @param collectorItem Collector item/*from   w w w.  j  a v  a 2  s . co  m*/
 * @param beginDate     Begin Date
 * @param endDate       End Date
 * @return SecurityReviewAuditResponse
 */
private LibraryPolicyAuditResponse getLibraryPolicyAuditResponse(CollectorItem collectorItem, long beginDate,
        long endDate) {
    List<LibraryPolicyResult> libraryPolicyResults = libraryPolicyResultsRepository
            .findByCollectorItemIdAndEvaluationTimestampIsBetweenOrderByTimestampDesc(collectorItem.getId(),
                    beginDate - 1, endDate + 1);

    LibraryPolicyAuditResponse libraryPolicyAuditResponse = new LibraryPolicyAuditResponse();

    if (CollectionUtils.isEmpty(libraryPolicyResults)) {
        libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_AUDIT_MISSING);
        return libraryPolicyAuditResponse;
    }

    LibraryPolicyResult returnPolicyResult = libraryPolicyResults.get(0);
    libraryPolicyAuditResponse.setLibraryPolicyResult(returnPolicyResult);
    libraryPolicyAuditResponse.setLastExecutionTime(returnPolicyResult.getEvaluationTimestamp());

    //threats by type
    Set<LibraryPolicyResult.Threat> securityThreats = !MapUtils.isEmpty(returnPolicyResult.getThreats())
            ? returnPolicyResult.getThreats().get(LibraryPolicyType.Security)
            : SetUtils.EMPTY_SET;
    Set<LibraryPolicyResult.Threat> licenseThreats = !MapUtils.isEmpty(returnPolicyResult.getThreats())
            ? returnPolicyResult.getThreats().get(LibraryPolicyType.License)
            : SetUtils.EMPTY_SET;

    boolean isOk = true;
    //License Threats
    if (licenseThreats.stream()
            .anyMatch(threat -> Objects.equals(threat.getLevel(), LibraryPolicyThreatLevel.Critical)
                    && hasViolations(threat))) {
        libraryPolicyAuditResponse
                .addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_FOUND_CRITICAL_LICENSE);
        isOk = false;
    }

    if (licenseThreats.stream()
            .anyMatch(threat -> Objects.equals(threat.getLevel(), LibraryPolicyThreatLevel.High)
                    && hasViolations(threat))) {
        libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_FOUND_HIGH_LICENSE);
        isOk = false;
    }

    //Security Threats
    if (securityThreats.stream()
            .anyMatch(threat -> Objects.equals(threat.getLevel(), LibraryPolicyThreatLevel.Critical)
                    && hasViolations(threat))) {
        libraryPolicyAuditResponse
                .addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_FOUND_CRITICAL_SECURITY);
        isOk = false;
    }

    if (securityThreats.stream()
            .anyMatch(threat -> Objects.equals(threat.getLevel(), LibraryPolicyThreatLevel.High)
                    && hasViolations(threat))) {
        libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_FOUND_HIGH_SECURITY);
        isOk = false;
    }

    if (isOk) {
        libraryPolicyAuditResponse.addAuditStatus(LibraryPolicyAuditStatus.LIBRARY_POLICY_AUDIT_OK);
    }

    return libraryPolicyAuditResponse;
}

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

/**
 * Gets the info about course id collection representing the same course.
 * E.g a course with code "1DL301" can be planned in year 2015 and 2016 and
 * it will have different ids in DB in this case.
 *
 * @param scheduleInfo the info regarding which years are planned, e.g 2015;
 * non-empty input.//w  w w.java2  s . c  o  m
 * @return non-null collection regarding id set for same course.
 * @throws IllegalArgumentException if input is null or empty
 */
public Set<Set<Integer>> getIdCollectionForSameCourse(Set<CourseSchedule> scheduleInfo) {

    if (scheduleInfo == null || scheduleInfo.isEmpty()) {
        throw new IllegalArgumentException("Schedule input must be non-empty");
    }

    List<Course> allCourses = this.courseRepository.findAll();

    // find the first plan year, e.g 2015
    int firstPlanYear = scheduleInfo.stream().sorted(
            (schedule1, schedule2) -> Short.compare(schedule1.getTaughtYear(), schedule2.getTaughtYear()))
            .findFirst().get().getTaughtYear();

    // only get the course ids for plan year, e.g 2015, 2016
    Set<Course> planYearCourseSet = allCourses.stream()
            .filter(course -> course.getTaughtYear() >= firstPlanYear).collect(Collectors.toSet());

    Map<String, Set<Integer>> codeToIdSet = CourseFlattener.flattenToCodeAndIdSet(planYearCourseSet);

    Set<Set<Integer>> idCollectionForSameCourse = new HashSet<>();

    codeToIdSet.entrySet().stream().filter(entry -> entry.getValue().size() > 1).forEach(entry -> {
        idCollectionForSameCourse.add(entry.getValue());
    });

    return idCollectionForSameCourse;
}

From source file:com.dbi.jmmerge.MapController.java

private String tryToGuessBaseDir(Set<String> filenames) {
    final String baseDirGuess = filenames.iterator().next().split("/")[0];
    if (filenames.stream().allMatch(name -> name.split("/")[0].equals(baseDirGuess)))
        return baseDirGuess;
    return null;/*  ww w  . ja va 2 s .  c om*/
}

From source file:com.thoughtworks.go.agent.common.util.JarUtilTest.java

@Test
public void shouldExtractJars() throws Exception {
    File sourceFile = new File(PATH_WITH_HASHES + "test-agent.jar");
    File outputTmpDir = temporaryFolder.newFolder();
    Set<File> files = new HashSet<>(JarUtil.extractFilesInLibDirAndReturnFiles(sourceFile,
            jarEntry -> jarEntry.getName().endsWith(".class"), outputTmpDir));

    Set<File> actualFiles = Files.list(outputTmpDir.toPath()).map(Path::toFile).collect(Collectors.toSet());

    assertEquals(files, actualFiles);//  www. j a  va 2  s  .  co  m
    assertEquals(files.size(), 2);
    Set<String> fileNames = files.stream().map(File::getName).collect(Collectors.toSet());
    assertEquals(fileNames,
            new HashSet<>(Arrays.asList("ArgPrintingMain.class", "HelloWorldStreamWriter.class")));
}

From source file:org.fenixedu.academic.thesis.ui.service.ExportThesisProposalsService.java

private void fillGroups(List<Set<StudentThesisCandidacy>> studentCandidacies, Spreadsheet spreadsheet) {
    for (Set<StudentThesisCandidacy> stc : studentCandidacies) {
        if (stc.isEmpty()) {
            continue;
        }//from ww  w .j  a va2 s  .com
        final Row row = spreadsheet.addRow();
        row.setCell(stc.iterator().next().getRegistration().getNumber());
        row.setCell(stc.stream().sorted(StudentThesisCandidacy.COMPARATOR_BY_PREFERENCE_NUMBER)
                .filter(cand -> cand.getAcceptedByAdvisor() == true).findFirst()
                .map(s -> s.getThesisProposal().getIdentifier()).orElse(""));
        stc.stream().sorted(StudentThesisCandidacy.COMPARATOR_BY_PREFERENCE_NUMBER).forEach(cand -> {
            row.setCell(cand.getThesisProposal().getIdentifier());
        });
    }
}

From source file:at.christophwurst.orm.consoleclient.ProjectCommands.java

public void registerCommands(Client client) {
    client.registerCommand("project:list", (consoleInterface) -> {
        System.out.println("# Projects");
        projectService.getAllProjects().forEach(p -> {
            System.out.println(" - " + p.getId() + ": " + p);
            System.out.println("   - Owner: " + p.getOwner());
        });//from   w ww  .  ja  v a  2  s.  c  o  m
    });

    client.registerCommand("project:show", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        Project pro = projectService.getProjectById(id);
        System.out.println(pro);
    });

    client.registerCommand("project:create", (consoleInterface) -> {
        String name = consoleInterface.getStringValue("name");

        Project project = new Project(name);

        projectService.saveProject(project);
    });

    client.registerCommand("project:owner", (consoleInterface) -> {
        Long projectId = consoleInterface.getLongValue("project id");
        Long employeeId = consoleInterface.getLongValue("employee id");

        Project project = projectService.getProjectById(projectId);
        Employee employee = null;
        if (employeeId != null) {
            employee = employeeService.getById(employeeId);
        }

        project.setOwner(employee);
        projectService.saveProject(project);
    });

    client.registerCommand("project:employees", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        projectService.getProjectById(id).getEmployees().forEach(e -> {
            System.out.println(" - " + e.getId() + ": " + e);
        });
    });

    client.registerCommand("project:employee:add", (consoleInterface) -> {
        Long projectId = consoleInterface.getLongValue("project id");
        Long employeeId = consoleInterface.getLongValue("employee id");

        Project project = projectService.getProjectById(projectId);
        Employee employee = employeeService.getById(employeeId);

        project.addMember(employee);
        projectService.saveProject(project);
    });

    client.registerCommand("project:employee:remove", (consoleInterface) -> {
        Long projectId = consoleInterface.getLongValue("project id");
        Long employeeId = consoleInterface.getLongValue("employee id");

        Project project = projectService.getProjectById(projectId);
        Employee employee = employeeService.getById(employeeId);

        project.removeMember(employee);
        projectService.saveProject(project);
    });

    client.registerCommand("project:requirements", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        Project project = projectService.getProjectById(id);

        project.getRequirements().forEach(r -> {
            System.out.println(" - " + r.getId() + ": " + r);
        });
    });

    client.registerCommand("project:requirement:add", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        String shortDesc = consoleInterface.getStringValue("short description");

        Project project = projectService.getProjectById(id);
        Requirement requirement = new Requirement(shortDesc);

        project.addRequirement(requirement);
        projectService.saveProject(project);
    });

    client.registerCommand("project:requirements", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        Project project = projectService.getProjectById(id);

        project.getRequirements().forEach(r -> {
            System.out.println(" - " + r.getId() + ": " + r);
        });
    });

    client.registerCommand("project:requirement:tasks", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("requirement id");
        Requirement requirement = projectService.getRequirementById(id);

        requirement.getTasks().forEach(t -> {
            System.out.println(" - " + t.getId() + ": " + t);
        });
    });

    client.registerCommand("project:requirement:task:add", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("requirement id");
        String shortDescription = consoleInterface.getStringValue("short description");

        Requirement requirement = projectService.getRequirementById(id);
        Task task = new Task(shortDescription);

        requirement.addTask(task);
        projectService.saveRequirement(requirement);
    });

    client.registerCommand("project:requirement:task:delete", (consoleInterface) -> {
        Long requirementId = consoleInterface.getLongValue("requirement id");
        Long taskId = consoleInterface.getLongValue("task id");

        Requirement requirement = projectService.getRequirementById(requirementId);
        Task task = projectService.getTaskById(taskId);

        requirement.removeTask(task);
        projectService.saveRequirement(requirement);
    });

    client.registerCommand("project:costs", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        System.out.println(projectService.getProjectCosts(id));
    });

    client.registerCommand("project:sprints", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        Project p = projectService.getProjectById(id);
        Set<Sprint> sprints = p.getSprints();
        if (sprints == null) {
            System.out.println("no sprints");
        } else {
            sprints.stream().forEach((s) -> {
                System.out.println(" - " + s);
            });
        }
    });
}

From source file:com.devicehive.service.DeviceNotificationService.java

public Pair<String, CompletableFuture<List<DeviceNotification>>> subscribe(final Set<String> devices,
        final Set<String> names, final Date timestamp, final BiConsumer<DeviceNotification, String> callback) {

    final String subscriptionId = UUID.randomUUID().toString();
    Set<NotificationSubscribeRequest> subscribeRequests = devices.stream()
            .map(device -> new NotificationSubscribeRequest(subscriptionId, device, names, timestamp))
            .collect(Collectors.toSet());
    Collection<CompletableFuture<Collection<DeviceNotification>>> futures = new ArrayList<>();
    for (NotificationSubscribeRequest sr : subscribeRequests) {
        CompletableFuture<Collection<DeviceNotification>> future = new CompletableFuture<>();
        Consumer<Response> responseConsumer = response -> {
            String resAction = response.getBody().getAction();
            if (resAction.equals(Action.NOTIFICATION_SUBSCRIBE_RESPONSE.name())) {
                NotificationSubscribeResponse r = response.getBody().cast(NotificationSubscribeResponse.class);
                future.complete(r.getNotifications());
            } else if (resAction.equals(Action.NOTIFICATION_EVENT.name())) {
                NotificationEvent event = response.getBody().cast(NotificationEvent.class);
                callback.accept(event.getNotification(), subscriptionId);
            } else {
                logger.warn("Unknown action received from backend {}", resAction);
            }//from ww w .  j  a  v a 2s.  co m
        };
        futures.add(future);
        Request request = Request.newBuilder().withBody(sr).withPartitionKey(sr.getDevice())
                .withSingleReply(false).build();
        rpcClient.call(request, responseConsumer);
    }

    CompletableFuture<List<DeviceNotification>> future = CompletableFuture
            .allOf(futures.toArray(new CompletableFuture[futures.size()])).thenApply(v -> futures.stream()
                    .map(CompletableFuture::join).flatMap(Collection::stream).collect(Collectors.toList()));
    return Pair.of(subscriptionId, future);
}

From source file:info.archinnov.achilles.internals.apt.processors.meta.AchillesProcessor.java

private FunctionsContext parseAndValidateFunctionRegistry(GlobalParsingContext context,
        Set<? extends TypeElement> annotations, RoundEnvironment roundEnv,
        List<EntityMetaSignature> tableAndViewSignatures) {
    final List<FunctionSignature> udfSignatures = annotations.stream()
            .filter(annotation -> isAnnotationOfType(annotation, FunctionRegistry.class))
            .flatMap(annotation -> roundEnv.getElementsAnnotatedWith(annotation).stream())
            .map(MoreElements::asType)//from ww  w .ja  v  a 2  s  .c o  m
            .flatMap(x -> FunctionParser.parseFunctionRegistryAndValidateTypes(aptUtils, x, context).stream())
            .collect(toList());

    FunctionParser.validateNoDuplicateDeclaration(aptUtils, udfSignatures);

    final Set<TypeName> functionParameterTypes = udfSignatures.stream()
            .flatMap(x -> x.sourceParameterTypes.stream().map(TypeName::box)).collect(toSet());

    final Set<TypeName> functionReturnTypes = udfSignatures.stream().map(x -> x.sourceReturnType.box())
            .collect(toSet());

    final Set<TypeName> entityColumnTargetTypes = tableAndViewSignatures.stream()
            .filter(EntityMetaSignature::isTable).flatMap(x -> x.fieldMetaSignatures.stream())
            .map(x -> x.sourceType)
            //.map(TypeUtils::mapToNativeCassandraType)
            .collect(toSet());

    return new FunctionsContext(udfSignatures, CollectionsHelper.appendAll(functionParameterTypes,
            functionReturnTypes, entityColumnTargetTypes, NATIVE_TYPES));
}