Java Code Examples for reactor.core.publisher.Flux#merge()

The following examples show how to use reactor.core.publisher.Flux#merge() . 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: CtrlFullSyncResponseApiCallHandler.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
private Flux<?> fullSyncSuccessInScope(Peer satellitePeerRef, ResponseContext context)
{
    satellitePeerRef.setConnectionStatus(ApiConsts.ConnectionStatus.ONLINE);
    satellitePeerRef.fullSyncApplied();

    Node localNode = satellitePeerRef.getNode();

    List<Flux<?>> fluxes = new ArrayList<>();

    try
    {
        Iterator<Resource> localRscIter = localNode.iterateResources(apiCtx);
        while (localRscIter.hasNext())
        {
            Resource localRsc = localRscIter.next();
            fluxes.add(ctrlSatelliteConnectionNotifier.resourceConnected(localRsc, context));
        }
    }
    catch (AccessDeniedException exc)
    {
        throw new ImplementationError(exc);
    }

    return Flux.merge(fluxes);
}
 
Example 2
Source File: FluxSpecTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
	public void aDifferentWayOfConsuming() {
//		"A different way of consuming"
//		given: "source composables to merge, buffer and tap"
		Flux<Integer> odds = Flux.just(1, 3, 5, 7, 9);
		Flux<Integer> even = Flux.just(2, 4, 6);

//		when: "the sources are zipped"
		Flux<Integer> mergedFlux = Flux.merge(odds, even);
		List<String> res = new ArrayList<>();

		mergedFlux.subscribe(
				it -> {
					res.add("" + it);
					System.out.println(it);
				},
				Throwable::printStackTrace,
				() -> {
					Collections.sort(res);
					res.add("done");
					System.out.println("completed!");
				});

//		then: "the values are all collected from source1 and source2 flux"
		assertThat(res).containsExactly("1", "2", "3", "4", "5", "6", "7", "9", "done");
	}
 
Example 3
Source File: R044_Merge.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void mergingMonos() throws Exception {
	//given
	final Mono<BigDecimal> fast = Mono
			.just(BigDecimal.valueOf(1))
			.delayElement(ofMillis(200));

	final Mono<BigDecimal> slow = Mono
			.just(BigDecimal.valueOf(2))
			.delayElement(ofMillis(100));

	//when
	final Flux<BigDecimal> merged = Flux.merge(
			fast,
			slow
	);

	//then
	merged.subscribe(d -> log.info("Received {}", d));
	TimeUnit.SECONDS.sleep(2);
}
 
Example 4
Source File: Context.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
public Flux<CommandPermission> getPermissions() {
    // The author is a bot's owner
    final Mono<CommandPermission> ownerPerm = Mono.just(this.getAuthorId())
            .filter(Shadbot.getOwnerId()::equals)
            .map(ignored -> CommandPermission.OWNER);

    // The member is an administrator or it's a private message
    final Mono<CommandPermission> adminPerm = this.getChannel()
            .filterWhen(channel -> BooleanUtils.or(
                    DiscordUtils.hasPermission(channel, this.getAuthorId(), Permission.ADMINISTRATOR),
                    Mono.just(channel.getType() == Channel.Type.DM)))
            .map(ignored -> CommandPermission.ADMIN);

    return Flux.merge(ownerPerm, adminPerm, Mono.just(CommandPermission.USER));
}
 
Example 5
Source File: MultipleInputOutputFunctionTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Bean
public Function<Tuple2<Flux<Person>, Flux<Employee>>, Flux<String>> multiInputSingleOutput() {
	return tuple -> {
		Flux<String> stringStream = tuple.getT1().map(p -> p.getName().toUpperCase());
		Flux<String> intStream = tuple.getT2().map(p -> p.getName().toUpperCase());
		return Flux.merge(stringStream, intStream);
	};
}
 
Example 6
Source File: MultipleInputOutputFunctionTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Bean
public  Function<Tuple2<Flux<String>, Flux<Integer>>, Flux<String>> multiInputSingleOutput() {
	return tuple -> {
		Flux<String> stringStream = tuple.getT1();
		Flux<String> intStream = tuple.getT2().map(i -> String.valueOf(i));
		return Flux.merge(stringStream, intStream);
	};
}
 
Example 7
Source File: EvaluationStrategyImpl.java    From semagrow with Apache License 2.0 5 votes vote down vote up
public Flux<BindingSet> evaluateReactorInternal(Union expr, BindingSet bindings)
        throws QueryEvaluationException
{
    return Flux.merge(
            this.evaluateReactorInternal(expr.getLeftArg(), bindings),
            this.evaluateReactorInternal(expr.getRightArg(), bindings));
}
 
Example 8
Source File: RedissonKeysReactive.java    From redisson with Apache License 2.0 5 votes vote down vote up
public Flux<String> getKeysByPattern(String pattern, int count) {
    List<Publisher<String>> publishers = new ArrayList<Publisher<String>>();
    for (MasterSlaveEntry entry : commandExecutor.getConnectionManager().getEntrySet()) {
        publishers.add(createKeysIterator(entry, pattern, count));
    }
    return Flux.merge(publishers);
}
 
Example 9
Source File: MessageFastViewFactory.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Flux<MessageFastView> gatherMessageViews(Set<MessageId> messageIds, MailboxSession mailboxSession,
                                                 Map<MessageId, MessageFastViewPrecomputedProperties> fastProjections) {
    Set<MessageId> withProjectionEntry = fastProjections.keySet();
    Set<MessageId> withoutProjectionEntry = Sets.difference(messageIds, withProjectionEntry);
    return Flux.merge(
        Helpers.toMessageViews(fetch(withProjectionEntry, FetchGroup.HEADERS, mailboxSession),
            new FromMessageResultAndPreview(blobManager, fastProjections)),
        Helpers.toMessageViews(fetch(withoutProjectionEntry, FetchGroup.FULL_CONTENT, mailboxSession),
            messageFullViewFactory::fromMessageResults));
}
 
Example 10
Source File: CtrlNodeApiCallHandler.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
public Flux<ApiCallRc> setGlobalConfig(SatelliteConfigApi config) throws AccessDeniedException, IOException
{
    ArrayList<Flux<ApiCallRc>> answers = new ArrayList<Flux<ApiCallRc>>();

    for (NodeName nodeName : nodeRepository.getMapForView(peerAccCtx.get()).keySet())
    {
        answers.add(setConfig(nodeName.getName(), config));
    }
    ApiCallRc rc = ApiCallRcImpl.singleApiCallRc(
        ApiConsts.MODIFIED | ApiConsts.MASK_CTRL_CONF,
        "Successfully updated controller config"
    );
    answers.add(Flux.just(rc));
    return Flux.merge(answers);
}
 
Example 11
Source File: CtrlSatelliteConnectionNotifier.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
public Flux<?> resourceConnected(Resource rsc, ResponseContext context)
{
    ResourceDefinition rscDfn = rsc.getDefinition();

    return Flux.merge(
        checkResourceDefinitionConnected(rsc.getDefinition(), context),
        notifyListeners(
            "connecting to node '" + rsc.getNode().getName() + "' for resource '" + rscDfn.getName() + "'",
            connectionListener -> connectionListener.resourceConnected(rsc)
        )
    );
}
 
Example 12
Source File: InfoResource.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 4 votes vote down vote up
@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<?> stream() {
 return Flux.merge(messagesStream, statisticStream);
}
 
Example 13
Source File: CtrlRscAutoHelper.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
public AutoHelperResult manage(
    ApiCallRcImpl apiCallRcImpl,
    ResponseContext context,
    ResourceDefinition rscDfn
)
{
    AutoHelperResult result = new AutoHelperResult();
    AutoHelperInternalState autoHelperInternalState = new AutoHelperInternalState();

    for (AutoHelper autohelper : autohelperList)
    {
        autohelper.manage(apiCallRcImpl, rscDfn, autoHelperInternalState);
    }

    if (!autoHelperInternalState.resourcesToCreate.isEmpty())
    {
        autoHelperInternalState.additionalFluxList.add(
            rscCrtHelper.deployResources(
                context,
                autoHelperInternalState.resourcesToCreate
            )
        );
        autoHelperInternalState.fluxUpdateApplied = true;
    }

    if (!autoHelperInternalState.nodeNamesForDelete.isEmpty())
    {
        autoHelperInternalState.additionalFluxList.add(
            rscDelHelper.updateSatellitesForResourceDelete(
                autoHelperInternalState.nodeNamesForDelete,
                rscDfn.getName()
            )
        );
        autoHelperInternalState.fluxUpdateApplied = true;
    }

    if (autoHelperInternalState.requiresUpdateFlux && !autoHelperInternalState.fluxUpdateApplied)
    {
        autoHelperInternalState.additionalFluxList.add(
            ctrlSatelliteUpdateCaller.updateSatellites(rscDfn, Flux.empty())
                .transform(
                    updateResponses -> CtrlResponseUtils.combineResponses(
                        updateResponses,
                        rscDfn.getName(),
                        "Resource {1} updated on node {0}"
                    )
                )
        );
    }

    result.flux = Flux.merge(autoHelperInternalState.additionalFluxList);
    result.preventUpdateSatellitesForResourceDelete = autoHelperInternalState.preventUpdateSatellitesForResourceDelete;
    return result;
}
 
Example 14
Source File: CompositeJobExecutableGenerator.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
public CompositeJobExecutableGenerator(List<JobExecutableGenerator> jobExecutableGenerators) {
    this.mergedPlans = Flux.merge(
            jobExecutableGenerators.stream().map(JobExecutableGenerator::executionPlans).collect(Collectors.toList())
    );
    this.jobExecutableGenerators = jobExecutableGenerators;
}
 
Example 15
Source File: EventBroker.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Add a watch and send initial state for all relevant events.
 */
public void createWatch(Peer peer, Watch watch)
{
    errorReporter.logTrace("Create watch for: %s", watch.getEventIdentifier());
    watchLock.lock();
    try
    {
        Collection<String> eventNames = getMatchingEventNames(watch.getEventIdentifier().getEventName());

        List<Flux<byte[]>> watchStreams = new ArrayList<>();

        for (String eventName : eventNames)
        {
            EventSerializer eventSerializer = eventSerializers.get(eventName);
            EventSerializerDescriptor eventSerializerDescriptor = eventSerializerDescriptors.get(eventName);

            if (eventSerializer == null || eventSerializerDescriptor == null)
            {
                throw new UnknownEventException(eventName);
            }

            watchStreams.add(
                createWatchForEvent(watch, eventSerializer.get(), eventSerializerDescriptor.getEventName()));
        }

        Flux<byte[]> mergedStreams = Flux.merge(watchStreams);

        Disposable disposable = mergedStreams
            .subscribe(
                peer::sendMessage,
                exception -> errorReporter.reportError(exception, null, null, "Uncaught exception sending event")
            );

        watchStore.addWatch(watch, disposable);
    }
    catch (LinStorDataAlreadyExistsException exc)
    {
        errorReporter.logError(
            "Watch already exists for peer " + watch.getPeerId() + ", id " + watch.getPeerWatchId());
    }
    finally
    {
        watchLock.unlock();
    }
    errorReporter.logTrace("Create watch done");
}
 
Example 16
Source File: RequestSender.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
public Flux<String> getAll() {
	LOGGER.info("Before merge");
	Flux<String> merge = Flux.merge(get(1), get(2), get(3));
	LOGGER.info("after merge");
	return merge;
}
 
Example 17
Source File: CtrlRscCrtApiHelper.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Deploy at least one resource of a resource definition to the satellites and wait for them to be ready.
 */
public Flux<ApiCallRc> deployResources(ResponseContext context, Set<Resource> deployedResources)
{
    long rscDfnCount = deployedResources.stream()
        .map(Resource::getDefinition)
        .map(ResourceDefinition::getName)
        .distinct()
        .count();
    if (rscDfnCount != 1)
    {
        throw new IllegalArgumentException("Resources belonging to precisely one resource definition expected");
    }

    ResourceDefinition rscDfn = deployedResources.iterator().next().getDefinition();
    ResourceName rscName = rscDfn.getName();

    Set<NodeName> nodeNames = deployedResources.stream()
        .map(Resource::getNode)
        .map(Node::getName)
        .collect(Collectors.toSet());

    String nodeNamesStr = nodeNames.stream()
        .map(NodeName::getDisplayName)
        .map(displayName -> "''" + displayName + "''")
        .collect(Collectors.joining(", "));

    Publisher<ApiCallRc> readyResponses;
    if (getVolumeDfnCountPrivileged(rscDfn) == 0)
    {
        // No DRBD resource is created when no volumes are present, so do not wait for it to be ready
        readyResponses = Mono.just(responseConverter.addContextAll(
            makeNoVolumesMessage(rscName), context, false));
    }
    else
    if (allDiskless(rscDfn))
    {
        readyResponses = Mono.just(makeAllDisklessMessage(rscName));
    }
    else
    {
        List<Mono<ApiCallRc>> resourceReadyResponses = new ArrayList<>();
        for (Resource rsc : deployedResources)
        {
            if (
                AccessUtils.execPrivileged(
                    () -> DrbdLayerUtils.isAnyDrbdResourceExpected(apiCtx, rsc)
                )
            )
            {
                NodeName nodeName = rsc.getNode().getName();
                if (containsDrbdLayerData(rsc))
                {
                    resourceReadyResponses.add(
                        eventWaiter
                            .waitForStream(
                                resourceStateEvent.get(),
                                // TODO if anything is allowed above DRBD, this resource-name must be adjusted
                                ObjectIdentifier.resource(nodeName, rscName)
                            )
                            .skipUntil(UsageState::getResourceReady)
                            .next()
                            .thenReturn(makeResourceReadyMessage(context, nodeName, rscName))
                            .onErrorResume(
                                PeerNotConnectedException.class, ignored -> Mono.just(
                                    ApiCallRcImpl.singletonApiCallRc(ResponseUtils.makeNotConnectedWarning(nodeName))
                                )
                            )
                    );
                }
            }
        }
        readyResponses = Flux.merge(resourceReadyResponses);
    }

    return ctrlSatelliteUpdateCaller.updateSatellites(
        rscDfn,
        Flux.empty() // if failed, there is no need for the retry-task to wait for readyState
        // this is only true as long as there is no other flux concatenated after readyResponses
    )
        .transform(updateResponses -> CtrlResponseUtils.combineResponses(
            updateResponses,
            rscName,
            nodeNames,
            "Created resource {1} on {0}",
            "Added peer(s) " + nodeNamesStr + " to resource {1} on {0}"
            )
        )
        .concatWith(readyResponses);
}
 
Example 18
Source File: Fluxs.java    From cyclops with Apache License 2.0 3 votes vote down vote up
public static <T> Flux<Mono<T>> sequence(final Publisher<? extends Flux<T>> fts) {

        Flux<Mono<T>> identity = Flux.just();

        BiFunction<Flux<Mono<T>>,Flux<T>,Flux<Mono<T>>> combineToStream = (acc,next) ->Flux.merge(acc,next.map(Mono::just));


        Flux<Flux<Mono<T>>> x = Flux.from(fts).reduce(identity, combineToStream).flatMapMany(Flux::just);
        return x.flatMap(i->i);
    }
 
Example 19
Source File: EventFlowRegistry.java    From spring-cloud-open-service-broker with Apache License 2.0 2 votes vote down vote up
/**
 * Merges the initialization flows into a Flux
 *
 * @return a Flux of initialization flows
 */
protected Flux<I> getInitializationFlowsInternal() {
	return Flux.merge(this.initializationFlows);
}
 
Example 20
Source File: EventFlowRegistry.java    From spring-cloud-open-service-broker with Apache License 2.0 2 votes vote down vote up
/**
 * Merges the completion flows into a Flux
 *
 * @return a Flux of completion flows
 */
protected Flux<C> getCompletionFlowsInternal() {
	return Flux.merge(this.completionFlows);
}