@Test public void IsOrderListReturned() { try { Iterable<Order> orders = orderRepository.findAll(); assertTrue(StreamSupport.stream(orders.spliterator(), false) .noneMatch(o -> (o.getCustomerId() == customer.getCustomerId()))); ResponseEntity<String> resultEntity = restTemplate.getForEntity(orderURL(), String.class); assertTrue(resultEntity.getStatusCode().is2xxSuccessful()); String orderList = resultEntity.getBody(); assertFalse(orderList.contains("Eberhard")); Order order = new Order(customer.getCustomerId()); order.addLine(42, item.getItemId()); orderRepository.save(order); orderList = restTemplate.getForObject(orderURL(), String.class); assertTrue(orderList.contains("Eberhard")); } finally { orderRepository.deleteAll(); } }
private void addDefaultParams(SolrQuery solrQuery, SolrEndpointConfiguration config) { if(MapUtils.isNotEmpty(config.getDefaults())){ config.getDefaults().entrySet().stream() .filter(e -> StringUtils.isNoneBlank(e.getKey()) && e.getValue() != null) .forEach(e -> { String param = e.getKey(); Collection<?> values; if(e.getValue() instanceof Collection){ values = (Collection<?>)e.getValue(); } else if(e.getValue().getClass().isArray()) { values = Arrays.asList((Object[])e.getValue()); } else { values = Collections.singleton(e.getValue()); } Collection<String> strValues = StreamSupport.stream(values.spliterator(), false) .map(Objects::toString) //convert values to strings .filter(StringUtils::isNoneBlank) //filter blank values .collect(Collectors.toList()); if(!strValues.isEmpty()){ solrQuery.add(param, strValues.toArray(new String[strValues.size()])); } }); } }
@Override public void saveEvents(Iterable<? extends BaseModel> reviews, EventType type) { LOGGER.info("Saving list of events"); try{ List<Event> eventList = StreamSupport.stream(reviews.spliterator(), false) .map(review -> { Event platformEvent = new Event(); platformEvent.setEventType(type); platformEvent.setEventTypeCollectionId(review.getId()); platformEvent.setTimestamp(System.currentTimeMillis()); return platformEvent; }).collect(Collectors.toList()); eventRepository.save(eventList); } catch (Exception e){ LOGGER.error("Error while saving event", e); } }
/** * Fork a new compilation task; if possible the compilation context from previous executions is * retained (see comments in ReusableContext as to when it's safe to do so); otherwise a brand * new context is created. */ public JavacTask getTask() { if (task == null) { ReusableContext context = env.context(); String opts = options == null ? "" : StreamSupport.stream(options.spliterator(), false).collect(Collectors.joining()); context.clear(); if (!context.polluted && (context.opts == null || context.opts.equals(opts))) { //we can reuse former context env.info().ctxReusedCount++; } else { env.info().ctxDroppedCount++; //it's not safe to reuse context - create a new one context = env.setContext(new ReusableContext()); } context.opts = opts; JavacTask javacTask = ((JavacTool)env.javaCompiler()).getTask(out, env.fileManager(), diagsCollector, options, null, sources, context); javacTask.setTaskListener(context); for (TaskListener l : listeners) { javacTask.addTaskListener(l); } task = javacTask; } return task; }
private CompletionProvider fileCompletions(Predicate<Path> accept) { return (code, cursor, anchor) -> { int lastSlash = code.lastIndexOf('/'); String path = code.substring(0, lastSlash + 1); String prefix = lastSlash != (-1) ? code.substring(lastSlash + 1) : code; Path current = toPathResolvingUserHome(path); List<Suggestion> result = new ArrayList<>(); try (Stream<Path> dir = Files.list(current)) { dir.filter(f -> accept.test(f) && f.getFileName().toString().startsWith(prefix)) .map(f -> new ArgSuggestion(f.getFileName() + (Files.isDirectory(f) ? "/" : ""))) .forEach(result::add); } catch (IOException ex) { //ignore... } if (path.isEmpty()) { StreamSupport.stream(FileSystems.getDefault().getRootDirectories().spliterator(), false) .filter(root -> accept.test(root) && root.toString().startsWith(prefix)) .map(root -> new ArgSuggestion(root.toString())) .forEach(result::add); } anchor[0] = path.length(); return result; }; }
private static boolean shouldApplyRegisteredServiceMultifactorPolicy(final RegisteredServiceMultifactorPolicy policy, final Principal principal) { final String attrName = policy.getPrincipalAttributeNameTrigger(); final String attrValue = policy.getPrincipalAttributeValueToMatch(); // Principal attribute name and/or value is not defined if (!StringUtils.hasText(attrName) || !StringUtils.hasText(attrValue)) { return true; } // no Principal, we should enforce policy if (principal == null) { return true; } // check to see if any of the specified attributes match the attrValue pattern final Predicate<String> attrValuePredicate = Pattern.compile(attrValue).asPredicate(); return StreamSupport.stream(ATTR_NAMES.split(attrName).spliterator(), false) .map(principal.getAttributes()::get) .filter(Objects::nonNull) .map(CollectionUtils::toCollection) .flatMap(Set::stream) .filter(String.class::isInstance) .map(String.class::cast) .anyMatch(attrValuePredicate); }
/** * GET /imageCompletionSolutions -> get all the imageCompletionSolutions. */ @RequestMapping(value = "/imageCompletionSolutions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public List<ImageCompletionSolution> getAllImageCompletionSolutions(@RequestParam(required = false) String filter) { if ("imagecompletionexercise-is-null".equals(filter)) { log.debug("REST request to get all ImageCompletionSolutions where imageCompletionExercise is null"); return StreamSupport .stream(imageCompletionSolutionRepository.findAll().spliterator(), false) .filter(imageCompletionSolution -> imageCompletionSolution.getImageCompletionExercise() == null) .collect(Collectors.toList()); } log.debug("REST request to get all ImageCompletionSolutions"); return imageCompletionSolutionRepository.findAll(); }
/** * GET /photoLocationBeacons -> get all the photoLocationBeacons. */ @RequestMapping(value = "/photoLocationBeacons", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public List<PhotoLocationBeacon> getAllPhotoLocationBeacons(@RequestParam(required = false) String filter) { if ("exercise-is-null".equals(filter)) { log.debug("REST request to get all PhotoLocationBeacons where exercise is null"); return StreamSupport .stream(photoLocationBeaconRepository.findAll().spliterator(), false) .filter(photoLocationBeacon -> photoLocationBeacon.getExercise() == null) .collect(Collectors.toList()); } log.debug("REST request to get all PhotoLocationBeacons"); return photoLocationBeaconRepository.findAll(); }
private static CompletionProvider fileCompletions(Predicate<Path> accept) { return (code, cursor, anchor) -> { int lastSlash = code.lastIndexOf('/'); String path = code.substring(0, lastSlash + 1); String prefix = lastSlash != (-1) ? code.substring(lastSlash + 1) : code; Path current = toPathResolvingUserHome(path); List<Suggestion> result = new ArrayList<>(); try (Stream<Path> dir = Files.list(current)) { dir.filter(f -> accept.test(f) && f.getFileName().toString().startsWith(prefix)) .map(f -> new ArgSuggestion(f.getFileName() + (Files.isDirectory(f) ? "/" : ""))) .forEach(result::add); } catch (IOException ex) { //ignore... } if (path.isEmpty()) { StreamSupport.stream(FileSystems.getDefault().getRootDirectories().spliterator(), false) .filter(root -> Files.exists(root)) .filter(root -> accept.test(root) && root.toString().startsWith(prefix)) .map(root -> new ArgSuggestion(root.toString())) .forEach(result::add); } anchor[0] = path.length(); return result; }; }
@PostMapping("/orders/new") HttpEntity<?> createOrder() { Iterable<ProductInfo> infos = productInfos.findAll(Sort.by("createdDate").descending()); ProductInfo info = StreamSupport.stream(infos.spliterator(), false) // .findFirst() // .orElseThrow(() -> new IllegalStateException("No ProductInfo found!")); Order order = Order.newOrder(); order.add(info, 2); orders.save(order.complete()); return ResponseEntity // .created(links.linkForSingleResource(Order.class, order.getId()).toUri()) // .build(); }
/** * コンストラクタ * * @param connectionSupplier コネクションサプライヤ * @param loadPath SQLファイルの読み込みルートパス */ private DefaultSqlConfig(final ConnectionSupplier connectionSupplier, final String loadPath) { super(); this.connectionSupplier = connectionSupplier; this.sqlManager = new SqlManagerImpl(loadPath); this.sqlFilterManager = new SqlFilterManagerImpl(); this.sqlContextFactory = new SqlContextFactoryImpl(); this.entityHandler = new DefaultEntityHandler(); this.dialect = StreamSupport.stream(ServiceLoader.load(Dialect.class).spliterator(), false).filter(d -> d.accept(connectionSupplier)).findFirst().orElseGet(DefaultDialect::new); this.sqlAgentFactory = new SqlAgentFactoryImpl(this); initialize(); }
@Test public void resolveAttributeReference_WithNonExistingProductReferenceSetAttribute_ShouldNotResolveReferences() { when(productService.fetchCachedProductId(anyString())) .thenReturn(CompletableFuture.completedFuture(Optional.empty())); final ObjectNode productReference = getProductReferenceWithRandomId(); final AttributeDraft productReferenceAttribute = getProductReferenceSetAttributeDraft("foo", productReference); final AttributeDraft resolvedAttributeDraft = referenceResolver.resolveAttributeReference(productReferenceAttribute) .toCompletableFuture().join(); assertThat(resolvedAttributeDraft).isNotNull(); assertThat(resolvedAttributeDraft.getValue()).isNotNull(); final Spliterator<JsonNode> attributeReferencesIterator = resolvedAttributeDraft.getValue().spliterator(); assertThat(attributeReferencesIterator).isNotNull(); final Set<JsonNode> resolvedSet = StreamSupport.stream(attributeReferencesIterator, false) .collect(Collectors.toSet()); assertThat(resolvedSet).containsExactly(productReference); }
/** * Reads the specified configuration directory * * @param dir Path to config dir * @return List of all configuration files * @throws IOException on any errors when deserializing {@link Configuration}s */ List<String> getAllConfigurationsFromDisk(String dir) throws IOException { // nothing to do if configuration not passed if (isNull(dir)) { logger.warn("Null configuration dir passed, returning empty configuration list"); return Collections.emptyList(); } try (DirectoryStream<Path> configurationsDirectory = Files.newDirectoryStream(Paths.get(dir))) { return StreamSupport.stream(configurationsDirectory.spliterator(), true) .filter(ConfigurationIntake::isJsonFile) .map(Path::toAbsolutePath) .map(Path::toString) .collect(Collectors.toList()); } }
public static PlatformDescription lookupPlatformDescription(String platformString) { int separator = platformString.indexOf(":"); String platformProviderName = separator != (-1) ? platformString.substring(0, separator) : platformString; String platformOptions = separator != (-1) ? platformString.substring(separator + 1) : ""; Iterable<PlatformProvider> providers = ServiceLoader.load(PlatformProvider.class, Arguments.class.getClassLoader()); return StreamSupport.stream(providers.spliterator(), false) .filter(provider -> StreamSupport.stream(provider.getSupportedPlatformNames() .spliterator(), false) .anyMatch(platformProviderName::equals)) .findFirst() .flatMap(provider -> { try { return Optional.of(provider.getPlatform(platformProviderName, platformOptions)); } catch (PlatformNotSupported pns) { return Optional.empty(); } }) .orElse(null); }
@GetMapping("/employees") ResponseEntity<Resources<Resource<Employee>>> findAll() { List<Resource<Employee>> employeeResources = StreamSupport.stream(repository.findAll().spliterator(), false) .map(employee -> new Resource<>(employee, linkTo(methodOn(EmployeeController.class).findOne(employee.getId())).withSelfRel() .andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, employee.getId()))) .andAffordance(afford(methodOn(EmployeeController.class).deleteEmployee(employee.getId()))), linkTo(methodOn(EmployeeController.class).findAll()).withRel("employees") )) .collect(Collectors.toList()); return ResponseEntity.ok(new Resources<>(employeeResources, linkTo(methodOn(EmployeeController.class).findAll()).withSelfRel() .andAffordance(afford(methodOn(EmployeeController.class).newEmployee(null))))); }
public static <T> Stream<T> of(Iterable<T> iterable) { if(iterable instanceof Collection) { return ((Collection<T>) iterable).stream(); } else { return StreamSupport.stream(iterable.spliterator(), false); } }
private void processExamQuestionOptions(Question question, ExamSectionQuestion esq, ArrayNode node) { // esq.options Set<Long> persistedIds = question.getOptions().stream() .map(MultipleChoiceOption::getId) .collect(Collectors.toSet()); Set<Long> providedIds = StreamSupport.stream(node.spliterator(), false) .map(n -> n.get("option")) .filter(n -> SanitizingHelper.parse("id", n, Long.class).isPresent()) .map(n -> SanitizingHelper.parse("id", n, Long.class).get()) .collect(Collectors.toSet()); // Updates StreamSupport.stream(node.spliterator(), false) .map(n -> n.get("option")) .filter(o -> { Optional<Long> id = SanitizingHelper.parse("id", o, Long.class); return id.isPresent() && persistedIds.contains(id.get()); }).forEach(o -> updateOption(o, true)); // Removals question.getOptions().stream() .filter(o -> !providedIds.contains(o.getId())) .forEach(this::deleteOption); // Additions StreamSupport.stream(node.spliterator(), false) .filter(o -> SanitizingHelper.parse("id", o, Long.class) == null) .forEach(o -> createOptionBasedOnExamQuestion(question, esq, o)); // Finally update own option scores: for (JsonNode option : node) { SanitizingHelper.parse("id", option, Long.class).ifPresent(id -> { ExamSectionQuestionOption esqo = Ebean.find(ExamSectionQuestionOption.class, id); if (esqo != null) { esqo.setScore(round( SanitizingHelper.parse("score", option, Double.class).orElse(null))); esqo.update(); } }); } }
public static <T> Stream<T> filterEvenLine(Stream<T> src) { Spliterator<T> iter = src.spliterator(); Spliterator<T> res = new AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED ) { @Override public boolean tryAdvance(Consumer<? super T> action) { return iter.tryAdvance(item -> {}) ? iter.tryAdvance(action) : false; } }; return StreamSupport.stream(res, false); }
/** * Gets load statistics for all links or for a specific link. * * @onos.rsModel StatisticsFlowsLink * @param deviceId (optional) device ID for a specific link * @param port (optional) port number for a specified link * @return 200 OK with JSON encoded array of Load objects */ @GET @Path("flows/link") @Produces(MediaType.APPLICATION_JSON) public Response getLoads(@QueryParam("device") String deviceId, @QueryParam("port") String port) { Iterable<Link> links; if (deviceId == null || port == null) { links = get(LinkService.class).getLinks(); } else { ConnectPoint connectPoint = new ConnectPoint(deviceId(deviceId), portNumber(port)); links = get(LinkService.class).getLinks(connectPoint); } ObjectNode result = mapper().createObjectNode(); ArrayNode loads = mapper().createArrayNode(); JsonCodec<Load> loadCodec = codec(Load.class); StatisticService statsService = getService(StatisticService.class); StreamSupport.stream(Spliterators.spliteratorUnknownSize( links.iterator(), Spliterator.ORDERED), false) .forEach(link -> { ObjectNode loadNode = loadCodec.encode(statsService.load(link), this); UriBuilder locationBuilder = uriInfo.getBaseUriBuilder() .path("links") .queryParam("device", link.src().deviceId().toString()) .queryParam("port", link.src().port().toString()); loadNode.put("link", locationBuilder.build().toString()); loads.add(loadNode); }); result.set("loads", loads); return ok(result).build(); }
@Override public void deserializeNBT(NBTTagCompound nbt) { this.packID = new UUID(nbt.getLong("idMost"), nbt.getLong("idLeast")); this.leaderUUID = new UUID(nbt.getLong("leaderMost"), nbt.getLong("leaderLeast")); this.entitiesSet.clear(); Iterator<NBTBase> iter = nbt.getTagList("entities", Constants.NBT.TAG_LONG).iterator(); while (iter.hasNext()) { this.entitiesSet.add(new UUID(((NBTTagLong)iter.next()).getLong(), ((NBTTagLong)iter.next()).getLong())); } this.playerReps.clear(); StreamSupport.stream(nbt.getTagList("playerReps", Constants.NBT.TAG_COMPOUND).spliterator(), false).map(n -> (NBTTagCompound)n).forEach(tag -> this.playerReps.put(new UUID(tag.getLong("keyMost"), tag.getLong("keyLeast")), tag.getFloat("value"))); }
@ResponseBody @GetMapping(path = "/product", produces = MediaType.APPLICATION_JSON_VALUE) public List<ProductDto> getAllProducts() { List<Product> products = StreamSupport.stream(productRepository.findAll().spliterator(), false) .collect(Collectors.toList()); log.info("getAllProducts() : {}", products); return productMapper.toProductDtoList(products); }
/** * Get all users. * * @return */ @GET @Produces(MediaType.APPLICATION_JSON) @PreAuthorize("hasAuthority('ADMIN')") public Response getUsers() { Iterable<User> iterable = userService.findAllUsers(); List<QueryUserResult> queryDetailsList = StreamSupport.stream(iterable.spliterator(), false) .map(this::toQueryResult) .collect(Collectors.toList()); return Response.ok(queryDetailsList).build(); }
/** * Returns a stream of indices for which this {@code BitSet} * contains a bit in the set state. The indices are returned * in order, from lowest to highest. The size of the stream * is the number of bits in the set state, equal to the value * returned by the {@link #cardinality()} method. * * <p>The bit set must remain constant during the execution of the * terminal stream operation. Otherwise, the result of the terminal * stream operation is undefined. * * @return a stream of integers representing set indices * @since 1.8 */ public IntStream stream() { class BitSetIterator implements PrimitiveIterator.OfInt { int next = nextSetBit(0); @Override public boolean hasNext() { return next != -1; } @Override public int nextInt() { if (next != -1) { int ret = next; next = nextSetBit(next+1); return ret; } else { throw new NoSuchElementException(); } } } return StreamSupport.intStream( () -> Spliterators.spliterator( new BitSetIterator(), cardinality(), Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED), Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED, false); }
@Procedure(value = "graph.versioner.get.all", mode = DEFAULT) @Description("graph.versioner.get.all(entity) - Get all the State nodes for the given Entity.") public Stream<PathOutput> getAllState( @Name("entity") Node entity) { PathValueBuilder builder = new PathValueBuilder(); builder.addNode(entity); builder.addOutgoingRelationship(entity.getSingleRelationship(RelationshipType.withName(Utility.CURRENT_TYPE), Direction.OUTGOING)); StreamSupport.stream(entity.getRelationships(RelationshipType.withName(Utility.HAS_STATE_TYPE), Direction.OUTGOING).spliterator(), false) //.sorted((a, b) -> -1 * Long.compare((long)a.getProperty(START_DATE_PROP), (long)b.getProperty(START_DATE_PROP))) .forEach(rel -> Optional.ofNullable(rel.getEndNode().getSingleRelationship(RelationshipType.withName(Utility.PREVIOUS_TYPE), Direction.OUTGOING)) .map(builder::addOutgoingRelationship) ); return Stream.of(new PathOutput(builder.result())); }
/** * Returns a stream in which each element is the result of passing the corresponding elementY of * each of {@code streamA} and {@code streamB} to {@code function}. * * <p>For example: * * <pre>{@code * Streams.zip( * Stream.of("foo1", "foo2", "foo3"), * Stream.of("bar1", "bar2"), * (arg1, arg2) -> arg1 + ":" + arg2) * }</pre> * * <p>will return {@code Stream.of("foo1:bar1", "foo2:bar2")}. * * <p>The resulting stream will only be as long as the shorter of the two input streams; if one * stream is longer, its extra elements will be ignored. * * <p>Note that if you are calling {@link Stream#forEach} on the resulting stream, you might want * to consider using {@link #forEachPair} instead of this method. * * <p><b>Performance note:</b> The resulting stream is not <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>. * This may harm parallel performance. */ public static <A, B, R> Stream<R> zip( Stream<A> streamA, Stream<B> streamB, BiFunction<? super A, ? super B, R> function) { checkNotNull(streamA); checkNotNull(streamB); checkNotNull(function); boolean isParallel = streamA.isParallel() || streamB.isParallel(); // same as Stream.concat Spliterator<A> splitrA = streamA.spliterator(); Spliterator<B> splitrB = streamB.spliterator(); int characteristics = splitrA.characteristics() & splitrB.characteristics() & (Spliterator.SIZED | Spliterator.ORDERED); Iterator<A> itrA = Spliterators.iterator(splitrA); Iterator<B> itrB = Spliterators.iterator(splitrB); return StreamSupport.stream( new AbstractSpliterator<R>( Math.min(splitrA.estimateSize(), splitrB.estimateSize()), characteristics) { @Override public boolean tryAdvance(Consumer<? super R> action) { if (itrA.hasNext() && itrB.hasNext()) { action.accept(function.apply(itrA.next(), itrB.next())); return true; } return false; } }, isParallel); }
/** * @return a randomly picked element which is not the given element. */ static <T> T random(final T given, Iterable<T> iteration) { Objects.requireNonNull(given, "given == null"); Objects.requireNonNull(iteration, "iteration == null"); Preconditions.assertTrue(iteration.iterator().hasNext(), "iteration is empty"); final List<T> list = StreamSupport.stream(iteration.spliterator(), false) .filter(e -> !given.equals(e)) .collect(Collectors.toList()); final int size = list.size(); return size == 0? null: list.get(ThreadLocalRandom.current().nextInt(size)); }
@Test public void addNonExistingSubjectToStudyPlanFailureTest() throws Exception { //given study plan and a subject which is already part of it Subject subject = new Subject("Operating Systems", new BigDecimal(4.0)); subject.setId(1337L); //studyPlan1.addSubjects(new SubjectForStudyPlan(subject, studyPlan1, true)); StudyPlan studyPlan = studyPlanRepository.save(studyPlan1); //when this mandatory subject is added to the study plan mockMvc.perform( post("/admin/studyplans/addSubject") .with(user("admin").roles(Role.ADMIN.name())) .param("subjectId", subject.getId().toString()) .param("studyPlanId", studyPlan.getId().toString()) .param("semester", "1") .param("mandatory", "true") .with(csrf()) ).andExpect( (redirectedUrl("/admin/studyplans/?id="+studyPlan.getId())) ); //the subject should not be part of the mandatory subjects of the study plan List<SubjectForStudyPlan> subjectsForStudyPlan = StreamSupport .stream(subjectForStudyPlanRepository.findByStudyPlanIdOrderBySemesterRecommendation(studyPlan.getId()) .spliterator(), false).collect(Collectors.toList()); List<Subject> usedSubjects = subjectsForStudyPlan.stream() .filter(SubjectForStudyPlan::getMandatory) .map(s -> subjectRepository.findById(s.getSubject().getId())).collect(Collectors.toList()); assertFalse(usedSubjects.contains(subject)); }
@Test public void resolveAttributeReference_WithNullReferenceInSetAttribute_ShouldResolveReferences() { final ObjectNode productReference = getProductReferenceWithRandomId(); final AttributeDraft productReferenceAttribute = getProductReferenceSetAttributeDraft("foo", productReference, null); final AttributeDraft resolvedAttributeDraft = referenceResolver.resolveAttributeReference(productReferenceAttribute) .toCompletableFuture().join(); assertThat(resolvedAttributeDraft).isNotNull(); assertThat(resolvedAttributeDraft.getValue()).isNotNull(); final Spliterator<JsonNode> attributeReferencesIterator = resolvedAttributeDraft.getValue().spliterator(); assertThat(attributeReferencesIterator).isNotNull(); final Set<JsonNode> resolvedSet = StreamSupport.stream(attributeReferencesIterator, false) .collect(Collectors.toSet()); assertThat(resolvedSet).isNotEmpty(); final ObjectNode resolvedReference = JsonNodeFactory.instance.objectNode(); resolvedReference.put("typeId", "product"); resolvedReference.put("id", PRODUCT_ID); assertThat(resolvedSet).containsExactly(resolvedReference); }
@Override public Stream<JarEntry> stream() { return StreamSupport.stream(Spliterators.spliterator( new JarEntryIterator(), size(), Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.IMMUTABLE | Spliterator.NONNULL), false); }
private String[] fetchHashedTrytes(String processor) { return StreamSupport.stream(databaseProvider.getProcessorTransactions(processor).spliterator(), false) .map(processorTransaction -> { String trytes = processorTransaction.getHashedTrytes(); if (trytes == null) throw new RuntimeException("Sending loop found transaction with unhashed trytes!"); return trytes; }).toArray(String[]::new); }
@Override public List<UserMetricDTO> saveMetrics(Iterable<UserMetricDTO> metrics) { List<UserMetric> toSave = StreamSupport.stream(metrics.spliterator(), false) .map(UserMetricMapper::map) .collect(Collectors.toList()); userMetricsRepository.save(toSave); return toSave.stream().map(UserMetricMapper::map).collect(Collectors.toList()); }
public void testList() throws IOException { //Source level 9, broken jar ModuleFileManager fm = new ModuleFileManager( CachingArchiveProvider.getDefault(), bCp, (u)->Collections.singleton(u), Source.JDK1_9, StandardLocation.MODULE_PATH, false); JavaFileManager.Location l = StreamSupport.stream(fm.listLocationsForModules(StandardLocation.MODULE_PATH).spliterator(), true) .flatMap((s)->s.stream()) .findFirst() .orElse(null); assertNotNull(l); Iterable<JavaFileObject> res = fm.list(l, "org.me", EnumSet.of(JavaFileObject.Kind.CLASS), false); //NOI18N assertEquals(Arrays.asList("A Base","B Base"), toContent(res)); //NOI18N assertEquals(Arrays.asList("org.me.A","org.me.B"), toInferedName(fm, res)); //NOI18N //Source level 9, multi release jar fm = new ModuleFileManager( CachingArchiveProvider.getDefault(), mvCp, (u)->Collections.singleton(u), Source.JDK1_9, StandardLocation.MODULE_PATH, false); l = StreamSupport.stream(fm.listLocationsForModules(StandardLocation.MODULE_PATH).spliterator(), true) .flatMap((s)->s.stream()) .findFirst() .orElse(null); assertNotNull(l); res = fm.list(l, "org.me", EnumSet.of(JavaFileObject.Kind.CLASS), false); //NOI18N assertEquals(Arrays.asList("A 9","B Base"), toContent(res)); //NOI18N assertEquals(Arrays.asList("org.me.A","org.me.B"), toInferedName(fm, res)); //NOI18N }
/** * SEARCH /_search/contents?query=:query : search for the content corresponding * to the query. * * @param query the query of the content search * @return the result of the search */ @GetMapping("/_search/contents") @Timed public List<Content> searchContents(@RequestParam String query) { log.debug("REST request to search Contents for query {}", query); return StreamSupport .stream(contentSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); }
public List<Schema> loadSchemas(Database database) { Optional<Node> databaseNode = neo4jVersionerCore.findStateNode(database); if(databaseNode.isPresent()) { return StreamSupport.stream(databaseNode.get().getRelationships(Direction.OUTGOING, RelationshipType.withName("HAS_SCHEMA")).spliterator(), false) .map(Relationship::getEndNode) .filter(node -> node.hasLabel(Label.label("Schema"))) .map(Schema::new) .collect(Collectors.toList()); } else { return newArrayList(); } }
SortedTestData(List<T> coll) { super("SortedTestData", coll, c -> StreamSupport.stream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED), false), c -> StreamSupport.stream(Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED), true), c -> Spliterators.spliterator(c.toArray(), Spliterator.ORDERED | Spliterator.SORTED), List::size); }
@ActionMethod @Override public Result answerMultiChoice(String hash, Long qid) { User user = getLoggedUser(); return getEnrolmentError(hash, user).orElseGet(() -> { Optional<ExternalExam> optional = getExternalExam(hash, user); if (!optional.isPresent()) { return forbidden(); } ExternalExam ee = optional.get(); ArrayNode node = (ArrayNode) request().body().asJson().get("oids"); List<Long> optionIds = StreamSupport.stream(node.spliterator(), false) .map(JsonNode::asLong) .collect(Collectors.toList()); Optional<ExamSectionQuestion> question; Exam content; try { content = ee.deserialize(); question = findQuestion(qid, content); } catch (IOException e) { return internalServerError(); } return question .map(q -> processOptions(optionIds, q, ee, content)) .orElseGet(Results::forbidden); }); }
@Override public Stream<ResolvedEvent> readAllForwards(Position positionExclusive) { MergedEventReaderPosition mergedPosition = (MergedEventReaderPosition) positionExclusive; Instant snapTimestamp = clock.instant().minus(mergingStrategy.delay()); List<Stream<ResolvedEvent>> data = range(0, readers.size()) .mapToObj(i -> readers.get(i).reader.readAllForwards(mergedPosition.inputPositions[i])).collect(toList()); List<Iterator<ResolvedEvent>> snappedData = data.stream() .map(eventStream -> takeWhileBefore(snapTimestamp, eventStream.iterator())) .collect(toList()); return StreamSupport.stream(new MergingSpliterator<>(mergingStrategy, mergedPosition, snappedData), false) .onClose(() -> data.forEach(Stream::close)); }
@Procedure(value = "graph.versioner.get.by.date", mode = DEFAULT) @Description("graph.versioner.get.by.date(entity, date) - Get State node by the given Entity node, created at the given date") public Stream<NodeOutput> getStateByDate( @Name("entity") Node entity, @Name("date") long date) { return StreamSupport.stream(entity.getRelationships(RelationshipType.withName(Utility.HAS_STATE_TYPE), Direction.OUTGOING).spliterator(), false) .filter(relationship -> relationship.getProperty(Utility.START_DATE_PROP).equals(date)) .map(Relationship::getEndNode) .map(NodeOutput::new); }
@Override protected T consumeFrames() { checkState(OPEN); Stream<StackFrame> stream = StreamSupport.stream(this, false); if (function != null) { return function.apply(stream); } else throw new UnsupportedOperationException(); }
private Http.Request sanitize(Http.Context ctx, JsonNode body) throws SanitizingException { if (body.has("params") && body.get("params").has("childIds")) { JsonNode node = body.get("params").get("childIds"); Collection<Long> ids = StreamSupport.stream(node.spliterator(), false) .map(JsonNode::asLong) .collect(Collectors.toList()); return ctx.request().addAttr(Attrs.ID_COLLECTION, ids); } throw new SanitizingException("no ids"); }