List of usage examples for java.util.stream Collectors toSet
public static <T> Collector<T, ?, Set<T>> toSet()
From source file:de.ks.idnadrev.information.chart.ChartDataEditor.java
private TextField createCategoryEditor(ChartRow chartRow, int rowNum) { TextField categoryEditor = new TextField(); categoryEditor.textProperty().bindBidirectional(chartRow.getCategory()); categoryEditor.focusedProperty().addListener(getEditorFocusListener(rowNum, categoryEditor)); categoryEditor.textProperty().addListener((p, o, n) -> { categoryEditor.setUserData(true); });/*from ww w. j a v a 2 s .c o m*/ BiFunction<Integer, Integer, TextField> nextCategoryField = (row, column) -> { if (categoryEditors.size() > row) { return categoryEditors.get(row); } else { return null; } }; BiConsumer<Integer, Integer> clipBoardHandler = (row, col) -> { String string = Clipboard.getSystemClipboard().getString(); if (StringUtils.containsWhitespace(string)) { List<String> datas = Arrays.asList(StringUtils.split(string, "\n")); int missingRows = (row + datas.size()) - rows.size(); if (missingRows > 0) { for (int i = 0; i < missingRows; i++) { rows.add(new ChartRow()); } } for (int i = row; i < row + datas.size(); i++) { ChartRow currentChartRow = rows.get(i); String data = datas.get(i - row); currentChartRow.setCategory(data); } } }; categoryEditor.setOnKeyReleased(getInputKeyHandler(rowNum, -1, nextCategoryField, clipBoardHandler)); validationRegistry.registerValidator(categoryEditor, (control, value) -> { if (value != null) { Set<String> values = categoryEditors.stream()// .filter(e -> e != categoryEditor)// .map(e -> e.textProperty().getValueSafe())// .filter(v -> !v.isEmpty())// .collect(Collectors.toSet()); if (values.contains(value)) { ValidationMessage message = new ValidationMessage("validation.noDuplicates", control, value); return ValidationResult.fromMessages(message); } } return null; }); categoryEditors.add(categoryEditor); return categoryEditor; }
From source file:de.mirkosertic.desktopsearch.SearchPhraseSuggester.java
private String highlight(String aPhrase, List<String> aTokens) { String theResult = aPhrase;/*from w ww .ja va 2s.com*/ Set<String> theTokens = aTokens.stream().map(String::toLowerCase).collect(Collectors.toSet()); for (String theToken : theTokens) { Pattern thePattern = Pattern.compile("(" + theToken + ")", Pattern.CASE_INSENSITIVE); Matcher theMatcher = thePattern.matcher(aPhrase); Set<String> theReplacements = new HashSet<>(); while (theMatcher.find()) { theReplacements.add(theMatcher.group()); } for (String theReplacement : theReplacements) { theResult = theResult.replace(theReplacement, "<b>" + theReplacement + "</b>"); } } return theResult; }
From source file:com.bitbreeds.webrtc.sctp.impl.SendService.java
/** * * @param cumulativeTsnAck lowest ack we are sure everything below has been acknowledged * @param gaps the acknowledged groups offset from cumulativeTsnAck * * <a href=https://tools.ietf.org/html/rfc4960#section-3.3.4>SACK spec</a> *//*w ww.java 2 s .c o m*/ protected void removeAllAcknowledged(long cumulativeTsnAck, List<SackUtil.GapAck> gaps) { gaps.forEach(i -> { Collection<Long> ls = sentTSNS.keySet().stream() .filter(j -> j >= (cumulativeTsnAck + i.start) && j <= (cumulativeTsnAck + i.end)) .collect(Collectors.toSet()); synchronized (dataMutex) { sentTSNS = sentTSNS.minusAll(ls); } }); }
From source file:ddf.catalog.source.solr.DynamicSchemaResolver.java
public DynamicSchemaResolver() { this.schemaFields = new SchemaFields(); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED + SchemaFields.HAS_CASE); fieldsCache.add(Metacard.TAGS + SchemaFields.TEXT_SUFFIX); anyTextFieldsCache.add(Metacard.METADATA + SchemaFields.TEXT_SUFFIX); Set<String> basicTextAttributes = BasicTypes.BASIC_METACARD.getAttributeDescriptors().stream() .filter(descriptor -> BasicTypes.STRING_TYPE.equals(descriptor.getType())) .map(stringDescriptor -> stringDescriptor.getName() + SchemaFields.TEXT_SUFFIX) .collect(Collectors.toSet()); anyTextFieldsCache.addAll(basicTextAttributes); fieldsCache.add(BasicTypes.VALIDATION_ERRORS + SchemaFields.TEXT_SUFFIX); fieldsCache.add(BasicTypes.VALIDATION_WARNINGS + SchemaFields.TEXT_SUFFIX); }
From source file:com.netflix.conductor.dao.dynomite.RedisMetadataDAOTest.java
@Test public void testTaskDefOperations() throws Exception { TaskDef def = new TaskDef("taskA"); def.setDescription("description"); def.setCreatedBy("unit_test"); def.setCreateTime(1L);/* w ww. java 2 s.c om*/ def.setInputKeys(Arrays.asList("a", "b", "c")); def.setOutputKeys(Arrays.asList("01", "o2")); def.setOwnerApp("ownerApp"); def.setRetryCount(3); def.setRetryDelaySeconds(100); def.setRetryLogic(RetryLogic.FIXED); def.setTimeoutPolicy(TimeoutPolicy.ALERT_ONLY); def.setUpdatedBy("unit_test2"); def.setUpdateTime(2L); dao.createTaskDef(def); TaskDef found = dao.getTaskDef(def.getName()); assertTrue(EqualsBuilder.reflectionEquals(def, found)); def.setDescription("updated description"); dao.updateTaskDef(def); found = dao.getTaskDef(def.getName()); assertTrue(EqualsBuilder.reflectionEquals(def, found)); assertEquals("updated description", found.getDescription()); for (int i = 0; i < 9; i++) { TaskDef tdf = new TaskDef("taskA" + i); dao.createTaskDef(tdf); } List<TaskDef> all = dao.getAllTaskDefs(); assertNotNull(all); assertEquals(10, all.size()); Set<String> allnames = all.stream().map(TaskDef::getName).collect(Collectors.toSet()); assertEquals(10, allnames.size()); List<String> sorted = allnames.stream().sorted().collect(Collectors.toList()); assertEquals(def.getName(), sorted.get(0)); for (int i = 0; i < 9; i++) { assertEquals(def.getName() + i, sorted.get(i + 1)); } for (int i = 0; i < 9; i++) { dao.removeTaskDef(def.getName() + i); } all = dao.getAllTaskDefs(); assertNotNull(all); assertEquals(1, all.size()); assertEquals(def.getName(), all.get(0).getName()); }
From source file:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticle.java
private Set<RunRightFastHealthCheck> oDatabaseDocumentTxHealthChecks() { ServiceUtils.awaitRunning(service);/*from www.java 2 s . c o m*/ return service.getDatabaseNames().stream().map(name -> { final ODatabaseDocumentTxSupplier oDatabaseDocumentTxSupplier = service .getODatabaseDocumentTxSupplier(name).get(); final ODatabaseDocumentTxHealthCheckBuilder healthcheckBuilder = ODatabaseDocumentTxHealthCheck .builder().oDatabaseDocumentTxSupplier(oDatabaseDocumentTxSupplier).databaseName(name); final Set<Class<? extends DocumentObject>> classes = databaseClassesForHealthCheck.get(name); if (CollectionUtils.isNotEmpty(classes)) { classes.stream().forEach(healthcheckBuilder::documentObject); } else { warning.log("oDatabaseDocumentTxHealthChecks", () -> { return Json.createObjectBuilder().add("database", name) .add("message", "No OrientDB classes are configured for the healthcheck").build(); }); } return healthcheckBuilder.build(); }).map(healthcheck -> { return RunRightFastHealthCheck.builder().config( healthCheckConfigBuilder().name("EmbeddedOrientDBServiceHealthCheck").severity(FATAL).build()) .healthCheck(healthcheck).build(); }).collect(Collectors.toSet()); }
From source file:com.devicehive.service.DeviceEquipmentServiceTest.java
@Test public void should_refresh_equipment() throws Exception { DeviceUpdate du = new DeviceUpdate(); du.setGuid(Optional.ofNullable(RandomStringUtils.randomAlphabetic(10))); du.setName(Optional.ofNullable(RandomStringUtils.randomAlphabetic(10))); DeviceClassUpdate dc = new DeviceClassUpdate(); dc.setName(Optional.ofNullable(RandomStringUtils.randomAlphabetic(10))); du.setDeviceClass(Optional.ofNullable(dc)); deviceService.deviceSave(du, Collections.<DeviceClassEquipmentVO>emptySet()); DeviceVO device = deviceService.findByGuidWithPermissionsCheck(du.getGuid().orElse(null), null); DeviceEquipmentVO devo = new DeviceEquipmentVO(); devo.setCode(RandomStringUtils.randomAlphabetic(10)); deviceEquipmentService.createDeviceEquipment(devo, device); DeviceNotification notification = new DeviceNotification(); notification.setNotification(SpecialNotifications.EQUIPMENT); notification.setParameters(new JsonStringWrapper("{\"equipment\": \"some_code\"}")); deviceEquipmentService.refreshDeviceEquipment(notification, device); List<DeviceEquipmentVO> equipments = deviceEquipmentService.findByFK(device); assertThat(equipments, notNullValue()); assertThat(equipments, hasSize(2));/*from ww w.j av a2s. c om*/ assertThat(equipments.stream().map(DeviceEquipmentVO::getCode).collect(Collectors.toSet()), hasItems("some_code", devo.getCode())); }
From source file:com.b2international.snowowl.snomed.importer.rf2.util.SnomedRefSetNameCollector.java
private void useGeneralLabelForExistingRefsets(Set<String> unlabeledRefSetIds) { Set<String> existingConceptIds = SnomedRequests.prepareSearchConcept().setLimit(unlabeledRefSetIds.size()) .filterByActive(true).filterByIds(unlabeledRefSetIds) .build(SnomedDatastoreActivator.REPOSITORY_UUID, configuration.getBranchPath()) .execute(ApplicationContext.getServiceForClass(IEventBus.class)) .then(concepts -> concepts.stream().map(SnomedConcept::getId).collect(Collectors.toSet())) .getSync();/*from www .j av a2s . c om*/ fillGeneralLabels(existingConceptIds); unlabeledRefSetIds.removeAll(existingConceptIds); }
From source file:dk.dma.msinm.user.UserService.java
/** * When creating a new user, check the roles assigned to the user. * <p>/*from ww w . ja v a2 s.c om*/ * A new user can always get the "user" role, e.g.via self-registration * on the website. * <p> * When an editor or administrator updates a user, they can only assign * roles they hold themselves. * * @param roles the roles to check */ private void validateRoleAssignment(String... roles) { // The "user" role can always be assigned if (roles.length == 1 && roles[0].equals("user")) { return; } // All other role assignments require a calling user with compatible roles User caller = findByPrincipal(ctx.getCallerPrincipal()); if (caller == null) { throw new SecurityException("Invalid caller " + ctx.getCallerPrincipal()); } Set<String> callerRoles = caller.getRoles().stream().map(Role::getName).collect(Collectors.toSet()); for (String role : roles) { if (!callerRoles.contains(role)) { throw new SecurityException( "Calling user " + ctx.getCallerPrincipal() + " cannot assign role " + role); } } }
From source file:com.netflix.spinnaker.clouddriver.ecs.services.EcsCloudMetricService.java
private void deregisterScalableTargets(Set<String> resources, String account, String region) { NetflixAmazonCredentials credentials = (NetflixAmazonCredentials) accountCredentialsProvider .getCredentials(account);//from www . j ava2 s .c om AWSApplicationAutoScaling autoScaling = amazonClientProvider.getAmazonApplicationAutoScaling(credentials, region, false); Map<String, Set<String>> resourceMap = new HashMap<>(); for (String resource : resources) { String namespace = StringUtils.substringBefore(resource, "/"); String service = StringUtils.substringAfter(resource, "/"); if (resourceMap.containsKey(namespace)) { resourceMap.get(namespace).add(service); } else { Set<String> serviceSet = new HashSet<>(); serviceSet.add(service); resourceMap.put(namespace, serviceSet); } } Set<DeregisterScalableTargetRequest> deregisterRequests = new HashSet<>(); for (String namespace : resourceMap.keySet()) { String nextToken = null; do { DescribeScalableTargetsRequest request = new DescribeScalableTargetsRequest() .withServiceNamespace(namespace).withResourceIds(resourceMap.get(namespace)); if (nextToken != null) { request.setNextToken(nextToken); } DescribeScalableTargetsResult result = autoScaling.describeScalableTargets(request); deregisterRequests.addAll(result.getScalableTargets().stream() .map(scalableTarget -> new DeregisterScalableTargetRequest() .withResourceId(scalableTarget.getResourceId()) .withScalableDimension(scalableTarget.getScalableDimension()) .withServiceNamespace(scalableTarget.getServiceNamespace())) .collect(Collectors.toSet())); nextToken = result.getNextToken(); } while (nextToken != null && nextToken.length() != 0); } for (DeregisterScalableTargetRequest request : deregisterRequests) { autoScaling.deregisterScalableTarget(request); } }