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

The following examples show how to use reactor.core.publisher.Flux#merge() . These examples are extracted from open source projects. 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
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
@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 3
Source Project: reactor-core   File: FluxSpecTests.java    License: 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 4
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 5
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 6
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 7
Source Project: redisson   File: RedissonKeysReactive.java    License: 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 8
Source Project: Shadbot   File: Context.java    License: 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 9
Source Project: semagrow   File: EvaluationStrategyImpl.java    License: 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 10
@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 11
@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 12
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 13
/**
 * 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 14
/**
 * 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 15
@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<?> stream() {
 return Flux.merge(messagesStream, statisticStream);
}
 
Example 16
public CompositeJobExecutableGenerator(List<JobExecutableGenerator> jobExecutableGenerators) {
    this.mergedPlans = Flux.merge(
            jobExecutableGenerators.stream().map(JobExecutableGenerator::executionPlans).collect(Collectors.toList())
    );
    this.jobExecutableGenerators = jobExecutableGenerators;
}
 
Example 17
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 18
Source Project: cyclops   File: Fluxs.java    License: 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
/**
 * Merges the initialization flows into a Flux
 *
 * @return a Flux of initialization flows
 */
protected Flux<I> getInitializationFlowsInternal() {
	return Flux.merge(this.initializationFlows);
}
 
Example 20
/**
 * Merges the completion flows into a Flux
 *
 * @return a Flux of completion flows
 */
protected Flux<C> getCompletionFlowsInternal() {
	return Flux.merge(this.completionFlows);
}