List of usage examples for java.util Set stream
default Stream<E> stream()
From source file:com.netflix.genie.common.internal.dto.v4.ExecutionEnvironment.java
/** * Constructor.//from w w w.j a va 2s . co m * * @param configs Any configuration files needed for a resource at execution time. 1024 characters max for * each. Optional. Any blanks will be removed * @param dependencies Any dependency files needed for a resource at execution time. 1024 characters max for each. * Optional. Any blanks will be removed * @param setupFile Any file that should be run to setup a resource at execution time. 1024 characters max. * Optional */ @JsonCreator public ExecutionEnvironment(@JsonProperty("configs") @Nullable final Set<String> configs, @JsonProperty("dependencies") @Nullable final Set<String> dependencies, @JsonProperty("setupFile") @Nullable final String setupFile) { this.configs = configs == null ? ImmutableSet.of() : ImmutableSet.copyOf(configs.stream().filter(StringUtils::isNotBlank).collect(Collectors.toSet())); this.dependencies = dependencies == null ? ImmutableSet.of() : ImmutableSet .copyOf(dependencies.stream().filter(StringUtils::isNotBlank).collect(Collectors.toSet())); this.setupFile = StringUtils.isBlank(setupFile) ? null : setupFile; }
From source file:com.openshift.internal.restclient.model.v1.ReplicationControllerTest.java
@Test public void testAddSecretVolumeToPodSpec() throws JSONException { IVolumeMount volumeMount = new IVolumeMount() { public String getName() { return "my-secret"; }//from ww w .ja v a 2 s . c o m public String getMountPath() { return "/path/to/my/secret/"; } public boolean isReadOnly() { return true; } public void setName(String name) { } public void setMountPath(String path) { } public void setReadOnly(boolean readonly) { } }; SecretVolumeSource source = new SecretVolumeSource(volumeMount.getName()); source.setSecretName("the-secret"); rc.addVolume(source); Set<IVolumeSource> podSpecVolumes = rc.getVolumes(); Optional vol = podSpecVolumes.stream().filter(v -> v.getName().equals(volumeMount.getName())).findFirst(); assertTrue("Expected to find secret volume in pod spec", vol.isPresent()); }
From source file:edu.zipcloud.cloudstreetmarket.core.services.CommunityServiceImpl.java
@Override @Secured({ ADMIN, SYSTEM })//from ww w . j a va2 s . c o m public User getUserByEmail(String email) { Set<User> result = userRepository.findByEmail(email); return result != null ? result.stream().findFirst().orElse(null) : null; }
From source file:com.devicehive.auth.JwtCheckPermissionsHelper.java
private boolean checkDeviceGuidsAllowed(HivePrincipal principal, Object targetDomainObject) { if (targetDomainObject instanceof String) { Set<Long> networks = principal.getNetworkIds(); Set<String> devices = principal.getDeviceGuids(); if (principal.areAllDevicesAvailable() && principal.areAllNetworksAvailable()) { return true; } else if (networks != null && principal.areAllDevicesAvailable()) { return networks.stream() .flatMap(n -> deviceService .list(null, null, n, null, null, null, null, false, null, null, null) .thenApply(Collection::stream).join()) .anyMatch(deviceVO -> deviceVO.getGuid().equals(targetDomainObject)); } else/* w w w .ja v a 2s . com*/ return networks != null && devices != null && devices.contains(targetDomainObject); } return true; }
From source file:com.netflix.spinnaker.fiat.roles.ldap.LdapUserRolesProvider.java
@Override public List<Role> loadRoles(String userId) { log.debug("loadRoles for user " + userId); if (StringUtils.isEmpty(configProps.getGroupSearchBase())) { return new ArrayList<>(); }// w w w. j ava 2s.co m String[] params = new String[] { getUserFullDn(userId), userId }; if (log.isDebugEnabled()) { log.debug(new StringBuilder("Searching for groups using ").append("\ngroupSearchBase: ") .append(configProps.getGroupSearchBase()).append("\ngroupSearchFilter: ") .append(configProps.getGroupSearchFilter()).append("\nparams: ") .append(StringUtils.join(params, " :: ")).append("\ngroupRoleAttributes: ") .append(configProps.getGroupRoleAttributes()).toString()); } // Copied from org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator. Set<String> userRoles = ldapTemplate.searchForSingleAttributeValues(configProps.getGroupSearchBase(), configProps.getGroupSearchFilter(), params, configProps.getGroupRoleAttributes()); log.debug("Got roles for user " + userId + ": " + userRoles); return userRoles.stream().map(role -> new Role(role).setSource(Role.Source.LDAP)) .collect(Collectors.toList()); }
From source file:io.mandrel.data.extract.ExtractorService.java
public Pair<Set<Link>, Set<Link>> extractAndFilterOutlinks(Spider spider, Uri uri, Map<String, Instance<?>> cachedSelectors, Blob blob, OutlinkExtractor ol) { // Find outlinks in page Set<Link> outlinks = extractOutlinks(cachedSelectors, blob, ol); log.trace("Finding outlinks for url {}: {}", uri, outlinks); // Filter outlinks Set<Link> filteredOutlinks = null; if (outlinks != null) { Stream<Link> stream = outlinks.stream().filter(l -> l != null && l.getUri() != null); if (spider.getFilters() != null && CollectionUtils.isNotEmpty(spider.getFilters().getLinks())) { stream = stream//w w w . j a v a 2 s .com .filter(link -> spider.getFilters().getLinks().stream().allMatch(f -> f.isValid(link))); } filteredOutlinks = stream.collect(Collectors.toSet()); } Set<Link> allFilteredOutlinks = null; if (filteredOutlinks != null) { Set<Uri> res = MetadataStores.get(spider.getId()) .deduplicate(filteredOutlinks.stream().map(l -> l.getUri()).collect(Collectors.toList())); allFilteredOutlinks = filteredOutlinks.stream().filter(f -> res.contains(f.getUri())) .collect(Collectors.toSet()); } log.trace("And filtering {}", allFilteredOutlinks); return Pair.of(outlinks, allFilteredOutlinks); }
From source file:jp.co.opentone.bsol.linkbinder.view.admin.module.dataimport.MasterDataImportModule.java
/** * ???./*from w ww . j a va 2 s.co m*/ * @param file ? * @param list ????. * @return ? * @throws IOException */ protected List<ValidationErrorInfo> validate(String file, List<T> list, MasterDataImportProcessType processType) throws IOException { List<ValidationErrorInfo> result = new ArrayList<>(); // CsvConfig config = createCsvConfig(); List<String[]> lines = Csv.load(newInputStream(file), SystemConfig.getValue(Constants.KEY_CSV_ENCODING), config, new StringArrayListHandler()); int expectedCount = getCsvColumnCount(); String msgInvalidColumnCount = Messages.getMessage(ApplicationMessageCode.ERROR_INVALID_COLUMN_COUNT) .getMessage(); IntStream.range(0, lines.size()).forEach(i -> { int rowNum = i + 1; if (lines.get(i).length != expectedCount) { result.add(new ValidationErrorInfo(rowNum, null, null, msgInvalidColumnCount)); } }); if (!result.isEmpty()) { return result; } // ?? Class<?>[] validationGroups; switch (processType) { case CREATE_OR_UPDATE: validationGroups = new Class<?>[] { Default.class, CreateGroup.class }; break; case DELETE: validationGroups = new Class<?>[] { Default.class }; break; default: validationGroups = new Class<?>[] { Default.class }; } ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); IntStream.range(0, list.size()).forEach(i -> { int rowNum = i + 1; Set<ConstraintViolation<T>> violations = validator.validate(list.get(i), validationGroups); List<ValidationErrorInfo> infoList = violations.stream().map(v -> new ValidationErrorInfo(rowNum, toViewName(v.getPropertyPath().toString()), v.getInvalidValue(), v.getMessage())) .collect(Collectors.toList()); result.addAll(infoList); }); return result; }
From source file:se.uu.it.cs.recsys.ruleminer.datastructure.builder.FPTreeBuilder.java
public void buildTreeBodyFromDB(FPTree theTree) { List<Integer> orderedFrequentItemIds = HeaderTableUtil.getOrderedItemId(theTree.getHeaderTable()); int i = 1;//from w w w.java 2 s . c o m final int maxStudentID = this.courseSelectionNormalizedRepository .findMaxCourseSelectionNormalizedPKStudentId(); while (i <= maxStudentID) { Set<CourseSelectionNormalized> courseSet = this.courseSelectionNormalizedRepository .findByCourseSelectionNormalizedPKStudentId(i); List<Integer> attendedCourseIds = courseSet.stream() .map(course -> course.getCourseSelectionNormalizedPK().getNormalizedCourseId()) .collect(Collectors.toList()); // LOGGER.debug("Normalized attened courses: {}", attendedCourseIds); List<Integer> orderedCourseIds = Util.reorderListAccordingToRef(attendedCourseIds, orderedFrequentItemIds); // LOGGER.debug("Recordered normalized attened courses: {}", attendedCourseIds); insertTransData(theTree.getHeaderTable(), theTree.getRoot(), orderedCourseIds); i++; } }
From source file:co.runrightfast.vertx.core.verticles.verticleManager.RunRightFastVerticleManager.java
private List<HealthCheckResult> runVerticleHealthChecks(final RunRightFastVerticleDeployment deployment) { final VerticleId verticleId = toVerticleId(deployment.getRunRightFastVerticleId()); final Set<RunRightFastHealthCheck> healthChecks = deployment.getHealthChecks(); return healthChecks.stream().map(healthCheck -> { final HealthCheckResult.Builder result = HealthCheckResult.newBuilder(); final HealthCheckConfig config = healthCheck.getConfig(); HealthCheck.Result healthCheckResult; try {// ww w . j av a2 s. c o m healthCheckResult = healthCheck.getHealthCheck().execute(); } catch (final Exception e) { healthCheckResult = HealthCheck.Result.unhealthy(e); } result.setHealthCheckName(config.getName()); result.setHealthy(healthCheckResult.isHealthy()); if (StringUtils.isNotBlank(healthCheckResult.getMessage())) { result.setMessage(healthCheckResult.getMessage()); } if (healthCheckResult.getError() != null) { result.setExceptionStacktrace(ExceptionUtils.getStackTrace(healthCheckResult.getError())); } result.setVerticleId(verticleId); return result.build(); }).collect(Collectors.toList()); }
From source file:com.devicehive.service.DeviceCommandServiceTest.java
@Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) public void testFindCommandsByGuidAndName() throws Exception { final List<String> names = IntStream.range(0, 5).mapToObj(i -> RandomStringUtils.randomAlphabetic(10)) .collect(Collectors.toList()); final Date timestampSt = timestampService.getDate(); final Date timestampEnd = timestampService.getDate(); final String parameters = "{\"param1\":\"value1\",\"param2\":\"value2\"}"; final String guid = UUID.randomUUID().toString(); final Set<String> namesForSearch = new HashSet<>(Arrays.asList(names.get(0), names.get(2), names.get(3))); final List<DeviceCommand> commandList = namesForSearch.stream().map(name -> { DeviceCommand command = new DeviceCommand(); command.setId(System.nanoTime()); command.setDeviceGuid(guid);//from w w w. ja v a 2 s .c om command.setCommand(name); command.setTimestamp(timestampService.getDate()); command.setParameters(new JsonStringWrapper(parameters)); command.setStatus(DEFAULT_STATUS); return command; }).collect(Collectors.toList()); when(requestHandler.handle(any(Request.class))).then(invocation -> { CommandSearchResponse response = new CommandSearchResponse(); response.setCommands(commandList); return Response.newBuilder().withBody(response).buildSuccess(); }); deviceCommandService.find(Collections.singleton(guid), names, timestampSt, timestampEnd, DEFAULT_STATUS) .thenAccept(commands -> { assertEquals(3, commands.size()); assertEquals(new HashSet<>(commandList), new HashSet<>(commands)); }).get(15, TimeUnit.SECONDS); verify(requestHandler, times(1)).handle(argument.capture()); }