org.springframework.data.util.Streamable Java Examples

The following examples show how to use org.springframework.data.util.Streamable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OrderController.java    From sos with Apache License 2.0 6 votes vote down vote up
@PostMapping("/orders/new")
HttpEntity<?> createOrder() {

	Iterable<ProductInfo> infos = productInfos.findAll(Sort.by("createdDate").descending());

	ProductInfo info = Streamable.of(infos).stream() //
			.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();
}
 
Example #2
Source File: ExecutionUtils.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the given {@link ConsumerWithException} for each element in the given {@link Iterable} in parallel waiting for
 * all executions to complete before returning. Exceptions being thrown in the {@link ConsumerWithException} will be
 * converted into {@link RuntimeException}s.
 *
 * @param executor must not be {@literal null}.
 * @param streamable must not be {@literal null}.
 * @param consumer must not be {@literal null}.
 */
public static <T> void run(Executor executor, Streamable<T> streamable, ConsumerWithException<T> consumer) {

	Assert.notNull(executor, "Executor must not be null!");
	Assert.notNull(streamable, "Streamable must not be null!");
	Assert.notNull(consumer, "Consumer must not be null!");

	streamable.stream().//
			map(it -> CompletableFuture.runAsync(() -> {
				try {
					consumer.accept(it);
				} catch (Exception o_O) {
					log.error(o_O.getMessage(), o_O);
					throw new RuntimeException(o_O);
				}
			}, executor)).collect(Collectors.toList()).forEach(CompletableFuture::join);
}
 
Example #3
Source File: OrderCompletionReport.java    From salespoint with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link OrderCompletionReport} for the given {@link Order} and {@link OrderLineCompletion}s.
 * 
 * @param order must not be {@literal null}.
 * @param completions must not be {@literal null}.
 * @return will never be {@literal null}.
 */
static OrderCompletionReport forCompletions(Order order, Streamable<OrderLineCompletion> completions) {

	return new OrderCompletionReport(order, completions.stream().anyMatch(OrderLineCompletion::isFailure) //
			? CompletionStatus.FAILED //
			: CompletionStatus.SUCCEEDED //
			, completions);
}
 
Example #4
Source File: PersistentOrderManager.java    From salespoint with Apache License 2.0 5 votes vote down vote up
@Override
public Streamable<T> findBy(UserAccount userAccount, Interval interval) {

	Assert.notNull(userAccount, "UserAccount must not be null");
	Assert.notNull(interval, "Interval must not be null!");

	return orderRepository.findByUserAccountAndDateCreatedBetween(userAccount, interval.getStart(), interval.getEnd());
}
 
Example #5
Source File: CatalogIntegrationTests.java    From salespoint with Apache License 2.0 5 votes vote down vote up
@Test // #232
void findsByAllCategories() {

	Cookie first = createCookie();

	Cookie second = createCookie();
	second.addCategory("special");

	Streamable<Product> result = catalog.findByAllCategories("chocolate", "special");

	assertThat(result) //
			.containsExactly(second) //
			.doesNotContain(first);
}
 
Example #6
Source File: AccountancyPeriodTests.java    From salespoint with Apache License 2.0 5 votes vote down vote up
@Test
void periodSetTest() {

	Interval interval = Interval.from(from).to(to);

	Map<Interval, Streamable<AccountancyEntry>> m = a.find(interval, Duration.ofMillis(200));
	for (Entry<Interval, Streamable<AccountancyEntry>> e : m.entrySet()) {
		for (AccountancyEntry p : e.getValue()) {}
	}
}
 
Example #7
Source File: FriendRepository.java    From event-sourcing-microservices-example with GNU General Public License v3.0 5 votes vote down vote up
@Query("MATCH (me:User {userId: {0}})-[:FRIEND]-(friends),\n" +
        "\t(nonFriend:User)-[:FRIEND]-(friends)\n" +
        "WHERE NOT (me)-[:FRIEND]-(nonFriend)\n" +
        "WITH nonFriend, count(nonFriend) as mutualFriends\n" +
        "RETURN nonFriend as User, mutualFriends as Weight\n" +
        "ORDER BY Weight DESC")
Streamable<RankedUser> recommendedFriends(Long userId);
 
Example #8
Source File: ExecutionUtils.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
public static <T, S, R> R runAndReturn(Executor executor, Streamable<T> streamable, Function<T, S> function,
		Collector<? super S, ?, R> collector) {

	Assert.notNull(streamable, "Iterable must not be null!");
	Assert.notNull(function, "Function must not be null!");

	return streamable.stream().//
			map(it -> CompletableFuture.supplyAsync(() -> function.apply(it), executor)).//
			filter(Objects::nonNull).//
			collect(Collectors.toList()).//
			stream().//
			map(CompletableFuture::join).//
			collect(collector);
}
 
Example #9
Source File: SaganOperations.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
Map<Project, MaintainedVersions> findVersions(List<Train> trains) {

		Assert.notNull(trains, "Trains must not be null!");

		return ExecutionUtils.runAndReturn(executor, Streamable.of(trains), train -> {
			return ExecutionUtils.runAndReturn(executor,
					Streamable.of(() -> train.stream().filter(module -> !TO_FILTER.contains(module.getProject()))), module -> {
						return getLatestVersion(module, train);
					});
		}).stream().flatMap(Collection::stream).collect(
				Collectors.groupingBy(MaintainedVersion::getProject, ListWrapperCollector.collectInto(MaintainedVersions::of)));
	}
 
Example #10
Source File: QueryUtils.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the query string to execute an exists query for the given id attributes.
 *
 * @param entityName        the name of the entity to create the query for, must not be {@literal null}.
 * @param cntQryPlaceHolder the placeholder for the count clause, must not be {@literal null}.
 * @param idAttrs           the id attributes for the entity, must not be {@literal null}.
 * @return the exists query string
 */
public static String getExistsQueryString(String entityName,
    String cntQryPlaceHolder,
    Iterable<String> idAttrs) {
    String whereClause = Streamable.of(idAttrs).stream() //
        .map(idAttribute -> String.format(EQUALS_CONDITION_STRING, "x", idAttribute,
            idAttribute)) //
        .collect(Collectors.joining(" AND ", " WHERE ", ""));

    return String.format(COUNT_QUERY_STRING, cntQryPlaceHolder, entityName) + whereClause;
}
 
Example #11
Source File: QueryUtils.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the query string to execute an exists query for the given id attributes.
 *
 * @param entityName        the name of the entity to create the query for, must not be {@literal null}.
 * @param cntQryPlaceHolder the placeholder for the count clause, must not be {@literal null}.
 * @param idAttrs           the id attributes for the entity, must not be {@literal null}.
 * @return the exists query string
 */
public static String getExistsQueryString(String entityName,
    String cntQryPlaceHolder,
    Iterable<String> idAttrs) {
    String whereClause = Streamable.of(idAttrs).stream() //
        .map(idAttribute -> String.format(EQUALS_CONDITION_STRING, "x", idAttribute,
            idAttribute)) //
        .collect(Collectors.joining(" AND ", " WHERE ", ""));

    return String.format(COUNT_QUERY_STRING, cntQryPlaceHolder, entityName) + whereClause;
}
 
Example #12
Source File: AccountancyOrderEventListenerTests.java    From salespoint with Apache License 2.0 5 votes vote down vote up
@Test // #230
void createsRollingBackEntryOnOrderCancellation() {

	listener.on(OrderPaid.of(order));
	listener.on(OrderCancelled.of(order, "Testing"));

	Streamable<AccountancyEntry> entries = accountancy.findAll();

	assertThat(entries).hasSize(2);
	assertThat(entries.stream() //
			.map(AccountancyEntry::getValue) //
			.reduce(ZERO_EURO, MonetaryAmount::add)//
	).isEqualTo(ZERO_EURO);
}
 
Example #13
Source File: PersistentAccountancy.java    From salespoint with Apache License 2.0 5 votes vote down vote up
@Override
public final Map<Interval, Streamable<AccountancyEntry>> find(Interval interval, TemporalAmount duration) {

	Assert.notNull(interval, "Interval must not be null");
	Assert.notNull(duration, "TemporalAmount must not be null");

	return Intervals.divide(interval, duration).stream() //
			.collect(toMap(identity(), this::find));
}
 
Example #14
Source File: Priced.java    From salespoint with Apache License 2.0 5 votes vote down vote up
/**
 * Sums up the prices of all given {@link Priced} instances.
 * 
 * @param priced must not be {@literal null}.
 * @return
 */
static MonetaryAmount sumUp(Iterable<? extends Priced> priced) {

	Assert.notNull(priced, "Iterable must not be null!");

	return Streamable.of(priced).stream()//
			.map(Priced::getPrice)//
			.reduce((left, right) -> left.add(right)) //
			.orElse(Currencies.ZERO_EURO);
}
 
Example #15
Source File: Order.java    From salespoint with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all {@link OrderLine} instances that refer to the given {@link Product}.
 *
 * @param product must not be {@literal null}.
 * @return
 * @since 7.1
 */
public Totalable<OrderLine> getOrderLines(Product product) {

	Assert.notNull(product, "Product must not be null!");

	return Totalable.of(Streamable.of(() -> orderLines.stream() //
			.filter(it -> it.refersTo(product))));
}
 
Example #16
Source File: Order.java    From salespoint with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all {@link AttachedChargeLine}s for the given {@link OrderLine}.
 *
 * @param orderLine must not be {@literal null}.
 * @return
 * @since 7.1
 */
public Totalable<AttachedChargeLine> getChargeLines(OrderLine orderLine) {

	List<AttachedChargeLine> foo = attachedChargeLines;

	return Totalable.of(Streamable.of(() -> foo.stream() //
			.filter(it -> it.belongsTo(orderLine))));
}
 
Example #17
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<ExtensionReview> findActiveReviews(Extension extension, UserData user) {
    return extensionReviewRepo.findByExtensionAndUserAndActiveTrue(extension, user);
}
 
Example #18
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<ExtensionVersion> findAllExtensionVersions() {
    return extensionVersionRepo.findAll();
}
 
Example #19
Source File: FriendRepository.java    From event-sourcing-microservices-example with GNU General Public License v3.0 4 votes vote down vote up
@Query("MATCH (userA:User), (userB:User)\n" +
        "WHERE userA.userId={0} AND userB.userId={1}\n" +
        "MATCH (userA)-[:FRIEND]-(fof:User)-[:FRIEND]-(userB)\n" +
        "RETURN DISTINCT fof")
Streamable<User> mutualFriends(Long fromId, Long toId);
 
Example #20
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<PersistedLog> findPersistedLogsAfter(LocalDateTime dateTime) {
    return persistedLogRepo.findByTimestampAfterOrderByTimestampAsc(dateTime);
}
 
Example #21
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<ExtensionVersion> findDependenciesReference(Extension extension) {
    return extensionVersionRepo.findByDependencies(extension);
}
 
Example #22
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<ExtensionVersion> findBundledExtensionsReference(Extension extension) {
    return extensionVersionRepo.findByBundledExtensions(extension);
}
 
Example #23
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<ExtensionVersion> findVersions(Extension extension, boolean preview) {
     return extensionVersionRepo.findByExtensionAndPreview(extension, preview);
}
 
Example #24
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<ExtensionVersion> findVersions(Extension extension) {
     return extensionVersionRepo.findByExtension(extension);
}
 
Example #25
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<Extension> findAllExtensions() {
    return extensionRepo.findAll();
}
 
Example #26
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<Extension> findExtensions(Namespace namespace) {
    return extensionRepo.findByNamespaceOrderByNameAsc(namespace);
}
 
Example #27
Source File: PersistentUserAccountManager.java    From salespoint with Apache License 2.0 4 votes vote down vote up
@Override
public Streamable<UserAccount> findAll() {
	return repository.findAll();
}
 
Example #28
Source File: PersistentUserAccountManager.java    From salespoint with Apache License 2.0 4 votes vote down vote up
@Override
public Streamable<UserAccount> findDisabled() {
	return repository.findByEnabledFalse();
}
 
Example #29
Source File: PersistentOrderManager.java    From salespoint with Apache License 2.0 4 votes vote down vote up
@Override
public Streamable<T> findBy(Interval interval) {
	return orderRepository.findByDateCreatedBetween(interval.getStart(), interval.getEnd());
}
 
Example #30
Source File: RepositoryService.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
public Streamable<ExtensionReview> findAllReviews(Extension extension) {
    return extensionReviewRepo.findByExtension(extension);
}