List of usage examples for java.util.stream StreamSupport stream
public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel)
From source file:com.devicehive.websockets.handlers.NotificationHandlers.java
@PreAuthorize("isAuthenticated() and hasPermission(null, 'CREATE_DEVICE_NOTIFICATION')") public WebSocketResponse processNotificationInsert(JsonObject request, WebSocketSession session) { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();//www . jav a2 s . c o m final String deviceGuid = Optional.ofNullable(request.get(Constants.DEVICE_GUID)) .map(JsonElement::getAsString).orElse(null); DeviceNotificationWrapper notificationSubmit = gson.fromJson(request.get(Constants.NOTIFICATION), DeviceNotificationWrapper.class); logger.debug("notification/insert requested. Session {}. Guid {}", session, deviceGuid); if (notificationSubmit == null || notificationSubmit.getNotification() == null) { logger.debug("notification/insert proceed with error. Bad notification: notification is required."); throw new HiveException(Messages.NOTIFICATION_REQUIRED, SC_BAD_REQUEST); } Set<DeviceVO> devices = new HashSet<>(); if (deviceGuid == null) { for (String guid : principal.getDeviceGuids()) { devices.add(deviceService.findByGuidWithPermissionsCheck(guid, principal)); } } else { devices.add(deviceService.findByGuidWithPermissionsCheck(deviceGuid, principal)); } if (devices.isEmpty() || StreamSupport.stream(devices.spliterator(), true).allMatch(o -> o == null)) { logger.debug("notification/insert canceled for session: {}. Guid is not provided", session); throw new HiveException(Messages.DEVICE_GUID_REQUIRED, SC_FORBIDDEN); } WebSocketResponse response = new WebSocketResponse(); for (DeviceVO device : devices) { if (device.getNetwork() == null) { logger.debug("notification/insert. No network specified for device with guid = {}", deviceGuid); throw new HiveException(String.format(Messages.DEVICE_IS_NOT_CONNECTED_TO_NETWORK, deviceGuid), SC_FORBIDDEN); } DeviceNotification message = notificationService.convertWrapperToNotification(notificationSubmit, device); notificationService.insert(message, device).thenApply(notification -> { logger.debug("notification/insert proceed successfully. Session {}. Guid {}", session, deviceGuid); response.addValue(NOTIFICATION, new InsertNotification(message.getId(), message.getTimestamp()), NOTIFICATION_TO_DEVICE); return response; }).exceptionally(ex -> { logger.warn("Unable to insert notification.", ex); throw new HiveException(Messages.INTERNAL_SERVER_ERROR, SC_INTERNAL_SERVER_ERROR); }).join(); } return response; }
From source file:io.logspace.hq.core.solr.event.SolrEventService.java
private List<String> createFilterQueries(EventFilter filter) { if (filter == null) { return Collections.emptyList(); }//from w w w . j ava 2s . co m Stream<EventFilterElement> filterStream = StreamSupport.stream(filter.spliterator(), false); Collection<List<EventFilterElement>> groupedFilters = filterStream .collect(groupingBy(EventFilterElement::getProperty)).values(); List<String> result = new ArrayList<>(groupedFilters.size()); for (List<EventFilterElement> eachPropertyFilters : groupedFilters) { result.add(eachPropertyFilters.stream().map(this::createFilterQuery).collect(joining(" OR "))); } return result; }
From source file:io.divolte.server.hdfs.HdfsFlusherTest.java
private void verifyAvroFile(List<Record> expected, Schema schema, Path avroFile) { final List<Record> result = StreamSupport .stream(readAvroFile(schema, avroFile.toFile()).spliterator(), false).collect(Collectors.toList()); assertEquals(expected, result);//from w ww . j ava 2 s . c o m }
From source file:com.intuit.wasabi.repository.cassandra.impl.CassandraPagesRepository.java
@Override public ExperimentPageList getExperimentPages(Experiment.ID experimentID) { ExperimentPageList experimentPageList = new ExperimentPageList(); try {/*from w w w .j a v a 2 s . co m*/ Result<PageExperimentByAppNamePage> result = experimentPageAccessor.selectBy(experimentID.getRawID()); Stream<PageExperimentByAppNamePage> resultList = StreamSupport .stream(Spliterators.spliteratorUnknownSize(result.iterator(), Spliterator.ORDERED), false); List<ExperimentPage> experimentPages = resultList .map(t -> ExperimentPage.withAttributes(Page.Name.valueOf(t.getPage()), t.isAssign()).build()) .collect(Collectors.toList()); experimentPageList.setPages(experimentPages); } catch (ReadTimeoutException | UnavailableException | NoHostAvailableException e) { throw new RepositoryException("Could not retrieve the pages for experiment: \"" + experimentID + "\"", e); } return experimentPageList; }
From source file:org.apache.metron.stellar.common.utils.StellarProcessorUtils.java
public static void runWithArguments(String function, List<Object> arguments, Object expected) { Supplier<Stream<Map.Entry<String, Object>>> kvStream = () -> StreamSupport .stream(new XRange(arguments.size()), false) .map(i -> new AbstractMap.SimpleImmutableEntry<>("var" + i, arguments.get(i))); String args = kvStream.get().map(kv -> kv.getKey()).collect(Collectors.joining(",")); Map<String, Object> variables = kvStream.get() .collect(Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue())); String stellarStatement = function + "(" + args + ")"; String reason = stellarStatement + " != " + expected + " with variables: " + variables; if (expected instanceof Double) { Assert.assertEquals(reason, (Double) expected, (Double) run(stellarStatement, variables), 1e-6); } else {/*from ww w . j a v a2s . c o m*/ Assert.assertEquals(reason, expected, run(stellarStatement, variables)); } }
From source file:org.cyclop.service.cassandra.intern.QueryServiceImpl.java
protected ImmutableMap<String, CqlColumnType> createTypeMap(CqlQuery query) { Optional<CqlTable> table = extractTableName(CqlKeyword.Def.FROM.value, query); if (!table.isPresent()) { LOG.warn("Could not extract table name from: {}. Column type information is not available."); return ImmutableMap.of(); }/*from w w w . j av a 2 s . com*/ Optional<ResultSet> result = executeSilent("select column_name, type from system.schema_columns where " + "columnfamily_name='" + table.get().part + "' allow filtering"); if (!result.isPresent()) { LOG.warn("Could not readIdentifier types for columns of table: " + table); return ImmutableMap.of(); } ImmutableMap<String, CqlColumnType> typesMap = StreamSupport.stream(result.get().spliterator(), false) .map(r -> new TypeTransfer(r.getString("type"), r.getString("column_name"))) .filter(TypeTransfer::isCorrect) .collect(toImmutableMap(t -> t.name.toLowerCase(), t -> extractType(t.type))); return typesMap; }
From source file:org.obiba.mica.core.upgrade.Mica310Upgrade.java
private void addLostMethods(Study study) { Iterable<CommitInfo> commitInfos = individualStudyService.getCommitInfos(study); List<JSONObject> history = StreamSupport.stream(commitInfos.spliterator(), false) .map(commit -> individualStudyService.getFromCommitAsJson(study, commit.getCommitId())) .collect(toList());//from w w w . ja va2 s .c o m addRecruitmentsIfMissing(study, history); addMethodsIfMissing(study, history, "otherDesign"); addMethodsIfMissing(study, history, "followUpInfo"); addMethodsIfMissing(study, history, "otherRecruitment"); addMethodsIfMissing(study, history, "info"); }
From source file:org.talend.dataprep.preparation.service.PreparationControllerTest.java
/** * Check that the folder search is correct. * * @param folderId the folder to search. * @param expectedIds the expected preparations id. * @throws IOException if an error occurs. */// w ww . jav a 2 s .c om private void checkSearchFolder(final String folderId, final List<String> expectedIds, String sort) throws IOException { // when final Response response = given() // .queryParam("folderId", folderId) // .queryParam("sort", sort) // .queryParam("order", "asc") // .when().expect().statusCode(200).log().ifError() // .get("/preparations/search"); // then assertThat(response.getStatusCode(), is(200)); final JsonNode rootNode = mapper.reader().readTree(response.asInputStream()); assertTrue(rootNode.isArray()); assertEquals(expectedIds.size(), rootNode.size()); final List<String> actualIds = StreamSupport.stream(rootNode.spliterator(), false) .map(n -> n.get("id").asText()).collect(Collectors.toList()); assertEquals(expectedIds, actualIds); }
From source file:com.ikanow.aleph2.data_import_manager.harvest.modules.LocalHarvestTestModule.java
private static DataBucketBean createBucketFromSource(JsonNode src_json) throws Exception { @SuppressWarnings("unused") final String _id = safeJsonGet(JsonUtils._ID, src_json).asText(); // (think we'll use key instead of _id?) final String key = safeJsonGet("key", src_json).asText(); final String created = safeJsonGet("created", src_json).asText(); final String modified = safeJsonGet("modified", src_json).asText(); final String title = safeJsonGet("title", src_json).asText(); final String description = safeJsonGet("description", src_json).asText(); final String owner_id = safeJsonGet("ownerId", src_json).asText(); final JsonNode tags = safeJsonGet("tags", src_json); // collection of strings //TODO (ALEPH-19): need to convert the DB authentication across to the Aleph2 format @SuppressWarnings("unused") final JsonNode comm_ids = safeJsonGet("communityIds", src_json); // collection of strings final JsonNode px_pipeline = safeJsonGet("processingPipeline", src_json); // collection of JSON objects, first one should have data_bucket final JsonNode px_pipeline_first_el = px_pipeline.get(0); final JsonNode data_bucket = safeJsonGet("data_bucket", px_pipeline_first_el); final DataBucketBean bucket = BeanTemplateUtils.build(data_bucket, DataBucketBean.class) .with(DataBucketBean::_id, key).with(DataBucketBean::created, parseJavaDate(created)) .with(DataBucketBean::modified, parseJavaDate(modified)).with(DataBucketBean::display_name, title) .with(DataBucketBean::description, description).with(DataBucketBean::owner_id, owner_id) .with(DataBucketBean::tags, StreamSupport.stream(tags.spliterator(), false).map(jt -> jt.asText()) .collect(Collectors.toSet())) .done().get();/* www. j a v a 2 s . c om*/ return bucket; }
From source file:com.epam.ta.reportportal.core.item.UpdateTestItemHandlerImpl.java
@Override public List<OperationCompletionRS> addExternalIssues(String projectName, AddExternalIssueRQ rq, String userName) {//from w w w . j av a2s . co m List<String> errors = new ArrayList<>(); ExternalSystem extSystem = externalSystemRepository.findOne(rq.getExternalSystemId()); expect(extSystem, notNull()).verify(EXTERNAL_SYSTEM_NOT_FOUND, rq.getExternalSystemId()); Iterable<TestItem> testItems = testItemRepository.findAll(rq.getTestItemIds()); List<TestItem> before = SerializationUtils.clone(Lists.newArrayList(testItems)); StreamSupport.stream(testItems.spliterator(), false).forEach(testItem -> { try { verifyTestItem(testItem, testItem.getId()); Set<TestItemIssue.ExternalSystemIssue> tiIssues = rq.getIssues().stream() .filter(issue -> !issue.getTicketId().trim().isEmpty()) .map(TestItemUtils.externalIssueDtoConverter(rq.getExternalSystemId(), userName)) .collect(toSet()); if (null == testItem.getIssue().getExternalSystemIssues()) { testItem.getIssue().setExternalSystemIssues(tiIssues); } else { tiIssues.addAll(testItem.getIssue().getExternalSystemIssues()); testItem.getIssue().setExternalSystemIssues(tiIssues); } } catch (BusinessRuleViolationException e) { errors.add(e.getMessage()); } }); expect(!errors.isEmpty(), equalTo(FALSE)).verify(FAILED_TEST_ITEM_ISSUE_TYPE_DEFINITION, errors.toString()); testItemRepository.save(testItems); eventPublisher.publishEvent( new TicketAttachedEvent(before, Lists.newArrayList(testItems), userName, projectName)); return StreamSupport.stream(testItems.spliterator(), false).map(testItem -> new OperationCompletionRS( "TestItem with ID = '" + testItem.getId() + "' successfully updated.")).collect(toList()); }