List of usage examples for java.util.stream Collectors toSet
public static <T> Collector<T, ?, Set<T>> toSet()
From source file:cc.kave.commons.pointsto.evaluation.ProjectTrainValidateEvaluation.java
private Set<ICoReTypeName> getStoreTypes(Collection<? extends UsageStore> stores) { Set<ICoReTypeName> storeTypes = new HashSet<>(); for (UsageStore store : stores) { Set<ICoReTypeName> types = store.getAllTypes().stream().filter(usageFilter::test) .collect(Collectors.toSet()); if (storeTypes.isEmpty()) { storeTypes.addAll(types);/* w w w . j av a 2s . com*/ } else { storeTypes.retainAll(types); } } return storeTypes; }
From source file:com.abixen.platform.service.businessintelligence.multivisualisation.application.service.DataFileManagementService.java
public DataFileForm updateDataFile(final DataFileForm dataFileForm) { log.debug("updateDataFile() - dataFileForm: {}", dataFileForm); final DataFile dataFile = dataFileService.find(dataFileForm.getId()); dataFile.changeDetails(dataFileForm.getName(), dataFileForm.getDescription()); dataFile.changeColumns(dataFileForm.getColumns().stream() .map(dataFileColumnDto -> (DataFileColumn) DataFileColumn.builder() .dataValueType(dataFileColumnDto.getDataValueType()).name(dataFileColumnDto.getName()) .values(dataFileColumnDto.getValues().stream() .map(dataValueDto -> getObjForValue(dataValueDto.getValue().toString().trim())) .collect(Collectors.toList())) .position(dataFileColumnDto.getPosition()).build()) .collect(Collectors.toSet())); dataFile.getColumns().forEach(dataFileColumn -> { dataFileColumn.changeDataFile(dataFile); dataFileColumn.getValues().forEach(dataValue -> dataValue.setDataColumn(dataFileColumn)); });/*from w w w . j a va 2 s. c o m*/ final DataFile updatedDataFile = dataFileService.update(dataFile); final DataFileDto updatedDataFileDto = dataFileToDataFileDtoConverter.convert(updatedDataFile); return new DataFileForm(updatedDataFileDto); }
From source file:com.kantenkugel.discordbot.jdocparser.JDoc.java
/** * Searches the whole JavaDocs based on input string and options * * @param input The text to search for./* w ww .ja v a 2 s. com*/ * @param options Options refining the search. Valid options are: * <ul> * <li>cs - makes matching case-sensitive</li> * <li>f - only methods are searched. Can't be used together with other type-specific filters.</li> * <li>c - only classes are searched. Can't be used together with other type-specific filters.</li> * <li>var - only values are searched. Can't be used together with other type-specific filters.</li> * </ul> * @return Pairs of the form: Text-representation - Documentation * @throws PatternSyntaxException if regex was used and the regex is not valid */ public static Set<Pair<String, ? extends Documentation>> search(String input, String... options) throws PatternSyntaxException { Set<String> opts = Arrays.stream(options).map(String::toLowerCase).collect(Collectors.toSet()); final boolean isCaseSensitive = opts.contains("cs"); String key = input.toLowerCase(); if (opts.contains("f")) { return docs.values().stream() .flatMap(cls -> cls.methodDocs.entrySet().stream().filter(mds -> mds.getKey().contains(key)) .map(Map.Entry::getValue).flatMap(Collection::stream)) .filter(md -> !isCaseSensitive || md.functionName.contains(input)) .map(md -> Pair.of(md.parent.className + " " + md.functionSig, md)).collect(Collectors.toSet()); } else if (opts.contains("c")) { return docs.values().stream() .filter(cls -> isCaseSensitive ? cls.className.contains(input) : cls.className.toLowerCase().contains(key)) .map(cls -> Pair.of("Class " + cls.className, cls)).collect(Collectors.toSet()); } else if (opts.contains("var")) { return docs.values().stream() .flatMap(cls -> cls.classValues.entrySet().stream().filter(val -> val.getKey().contains(key)) .map(Map.Entry::getValue)) .filter(val -> !isCaseSensitive || val.name.contains(input)) .map(val -> Pair.of(val.parent.className + " " + val.sig, val)).collect(Collectors.toSet()); } else { //search all categories Set<Pair<String, ? extends Documentation>> results = new HashSet<>(); for (JDocParser.ClassDocumentation classDoc : docs.values()) { if (isCaseSensitive ? classDoc.className.contains(input) : classDoc.className.toLowerCase().contains(key)) results.add(Pair.of("Class " + classDoc.className, classDoc)); for (Set<JDocParser.MethodDocumentation> mdcs : classDoc.methodDocs.values()) { for (JDocParser.MethodDocumentation mdc : mdcs) { if (isCaseSensitive ? mdc.functionName.contains(input) : mdc.functionName.toLowerCase().contains(key)) results.add(Pair.of(mdc.parent.className + " " + mdc.functionSig, mdc)); } } for (JDocParser.ValueDocumentation valueDoc : classDoc.classValues.values()) { if (isCaseSensitive ? valueDoc.name.contains(input) : valueDoc.name.toLowerCase().contains(key)) results.add(Pair.of(valueDoc.parent.className + " " + valueDoc.sig, valueDoc)); } } return results; } }
From source file:pt.ist.fenixedu.delegates.ui.services.DelegateService.java
public List<DelegateCurricularCourseBean> getCurricularCourses(Delegate delegate) { return getCurricularCoursesBeans(delegate, delegate.getDelegateCourses().stream().collect(Collectors.toSet())); }
From source file:de.richtercloud.validation.tools.ValidationToolsTest.java
@Property public void testBuildConstraintVioloationMessage(@ForAll boolean bean2Null, @ForAll int bean2Property0, @ForAll boolean bean1Null, @ForAll boolean bean1Bean2sNull, @ForAll boolean bean1bean2sEmpty, @ForAll @WithNull(0.5) String bean0Property0, @ForAll boolean bean0Valid, @ForAll boolean bean2Valid) throws Exception { LOGGER.info("testBuildConstraintVioloationMessage"); LOGGER.trace("testBuildConstraintVioloationMessage bean2Null: {}", bean2Null); LOGGER.trace("testBuildConstraintVioloationMessage bean2Property0: {}", bean2Property0); LOGGER.trace("testBuildConstraintVioloationMessage bean1Null: {}", bean1Null); LOGGER.trace("testBuildConstraintVioloationMessage bean1Bean2sNull: {}", bean1Bean2sNull); LOGGER.trace("testBuildConstraintVioloationMessage bean1bean2sEmpty: {}", bean1bean2sEmpty); LOGGER.trace("testBuildConstraintVioloationMessage bean0Property0: {}", bean0Property0); LOGGER.trace("testBuildConstraintVioloationMessage bean0Valid: {}", bean0Valid); LOGGER.trace("testBuildConstraintVioloationMessage bean2Valid: {}", bean2Valid); Bean0Validator.retValue = bean0Valid; Bean2Validator.retValue = bean2Valid; Bean2 bean2;//from ww w . j a va 2 s .c o m if (bean2Null) { bean2 = null; } else { bean2 = new Bean2(bean2Property0); } Bean1 bean1; if (bean1Null) { bean1 = null; } else { List<Bean2> bean1Bean2s; if (bean1Bean2sNull) { bean1Bean2s = null; } else { //Bean1.bean2s has @Min(1) bean1Bean2s = new ArrayList<>(); if (!bean1bean2sEmpty) { bean1Bean2s.add(bean2); } } bean1 = new Bean1(bean1Bean2s); } Bean0 bean0 = new Bean0(bean1, bean0Property0); Set<ConstraintViolation<Object>> violations = Validation.buildDefaultValidatorFactory().getValidator() .validate(bean0); FieldRetriever fieldRetriever = new CachedFieldRetriever(); FieldNameLambda fieldNameLambda = field -> "+++" + field.getName() + ",,,"; Map<Path, String> pathDescriptionMap = new HashMap<>(); OutputMode outputMode = OutputMode.PLAIN_TEXT; LOGGER.debug("validations.size: {}", violations.size()); if (violations.isEmpty()) { Assertions.assertThrows(IllegalArgumentException.class, () -> ValidationTools.buildConstraintVioloationMessage(violations, bean0, fieldRetriever, pathDescriptionMap, fieldNameLambda, false, //skipPathes outputMode)); return; } Set<String> messages = new HashSet<>(); if (!bean0Valid) { messages.add("invalid Bean0"); } if (bean0Property0 == null) { messages.add("+++property0,,,: darf nicht null sein"); } if (bean1Null) { messages.add("+++bean1,,,: darf nicht null sein"); } else { if (!bean1Bean2sNull) { //bean1bean2sNull is valid if (!bean1bean2sEmpty) { if (!bean2Null) { if (!bean2Valid) { messages.add("+++bean1,,,: +++bean2s,,,: invalid Bean2"); } if (bean2Property0 < 1) { messages.add( "+++bean1,,,: +++bean2s,,,: +++property0,,,: muss grer oder gleich 1 sein"); } } } else { messages.add("+++bean1,,,: +++bean2s,,,: Bean1.bean2s mustn't be empty"); } } } Set<List<String>> permutations = new HashSet<>(); PermutationIterator<String> textsPermutationIterator = new PermutationIterator<>(messages); textsPermutationIterator.forEachRemaining(permutation -> permutations.add(permutation)); Matcher<String> expResult = anyOf(permutations.stream() .map(permutation -> equalTo( StreamEx.of(permutation).joining("\n", "The following constraints are violated:\n", "\nFix the corresponding values in the components."))) .collect(Collectors.toSet())); String result = ValidationTools.buildConstraintVioloationMessage(violations, bean0, fieldRetriever, pathDescriptionMap, fieldNameLambda, false, //skipPathes outputMode); assertTrue(String.format("result was: %s; expResult was: %s", result, expResult), expResult.matches(result)); }
From source file:com.netflix.spinnaker.halyard.config.config.v1.HalconfigParser.java
/** * Deletes all files in the staging directory that are not referenced in the hal config. *///from w ww .j a v a 2s .co m public void cleanLocalFiles(Path stagingDirectoryPath) { if (!GlobalApplicationOptions.getInstance().isUseRemoteDaemon()) { return; } Halconfig halconfig = getHalconfig(); Set<String> referencedFiles = new HashSet<String>(); Consumer<Node> fileFinder = n -> referencedFiles.addAll(n.localFiles().stream().map(f -> { try { f.setAccessible(true); return (String) f.get(n); } catch (IllegalAccessException e) { throw new RuntimeException("Failed to clean staging directory: " + e.getMessage(), e); } finally { f.setAccessible(false); } }).filter(Objects::nonNull).collect(Collectors.toSet())); halconfig.recursiveConsume(fileFinder); Set<String> existingStagingFiles = ((List<File>) FileUtils.listFiles(stagingDirectoryPath.toFile(), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)).stream().map(f -> f.getAbsolutePath()) .collect(Collectors.toSet()); existingStagingFiles.removeAll(referencedFiles); try { for (String f : existingStagingFiles) { FileUtils.forceDelete(new File(f)); } } catch (IOException e) { throw new HalException(FATAL, "Failed to clean staging directory: " + e.getMessage(), e); } }
From source file:com.oneops.cms.dj.domain.CmsDeployment.java
public void setAutoPauseExecOrdersVal(String autoPauseExecOrdersVal, boolean updateCollection) { this.autoPauseExecOrdersVal = autoPauseExecOrdersVal; if (updateCollection) { if (StringUtils.isNotBlank(autoPauseExecOrdersVal)) { autoPauseExecOrders = Arrays.stream(autoPauseExecOrdersVal.split(",")) .map(val -> Integer.parseInt(val.trim())).collect(Collectors.toSet()); }/*from www .j av a2 s . c o m*/ } }
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.ja v a2s .c o 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:com.devicehive.websockets.handlers.CommandHandlers.java
@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_COMMAND')") public WebSocketResponse processCommandUnsubscribe(JsonObject request, WebSocketSession session) { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();//from w w w . j a v a 2 s . com final Optional<String> subscriptionId = Optional.ofNullable(request.get(SUBSCRIPTION_ID)) .map(JsonElement::getAsString); Set<String> guids = gson.fromJson(request.getAsJsonArray(DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); logger.debug("command/unsubscribe action. Session {} ", session.getId()); if (!subscriptionId.isPresent() && guids == null) { List<DeviceVO> actualDevices = deviceService .list(null, null, null, null, null, null, null, true, null, null, principal).join(); guids = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); commandService.sendUnsubscribeRequest(null, guids); } else if (subscriptionId.isPresent()) { commandService.sendUnsubscribeRequest(subscriptionId.get(), guids); } else { commandService.sendUnsubscribeRequest(null, guids); } ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).remove(subscriptionId); return new WebSocketResponse(); }
From source file:com.blackducksoftware.integration.hub.detect.workflow.codelocation.BdioCodeLocationCreator.java
/** * Attempts to map the given Code Location Types to Detector Types with EnumUtils. * @param bdioCodeLocations the final bdio code locations * @return the set of detector types/*from www.ja v a 2 s . c o m*/ */ private Set<DetectorType> getDetectorTypes(final List<BdioCodeLocation> bdioCodeLocations) { return bdioCodeLocations.stream() .map(bdioCodeLocation -> bdioCodeLocation.codeLocation.getCodeLocationType().toString()) .map(codeLocationType -> DetectEnumUtil.getValueOf(DetectorType.class, codeLocationType)) .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toSet()); }