reactor.core.publisher.Flux Java Examples

The following examples show how to use reactor.core.publisher.Flux. 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: DataBufferUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Write the given stream of {@link DataBuffer DataBuffers} to the given {@code AsynchronousFileChannel}.
 * Does <strong>not</strong> close the channel when the flux is terminated, and does
 * <strong>not</strong> {@linkplain #release(DataBuffer) release} the data buffers in the
 * source. If releasing is required, then subscribe to the returned {@code Flux} with a
 * {@link #releaseConsumer()}.
 * <p>Note that the writing process does not start until the returned {@code Flux} is subscribed to.
 * @param source the stream of data buffers to be written
 * @param channel the channel to write to
 * @param position the file position at which the write is to begin; must be non-negative
 * @return a flux containing the same buffers as in {@code source}, that starts the writing
 * process when subscribed to, and that publishes any writing errors and the completion signal
 */
public static Flux<DataBuffer> write(
		Publisher<DataBuffer> source, AsynchronousFileChannel channel, long position) {

	Assert.notNull(source, "'source' must not be null");
	Assert.notNull(channel, "'channel' must not be null");
	Assert.isTrue(position >= 0, "'position' must be >= 0");

	Flux<DataBuffer> flux = Flux.from(source);
	return Flux.create(sink -> {
		AsynchronousFileChannelWriteCompletionHandler completionHandler =
				new AsynchronousFileChannelWriteCompletionHandler(sink, channel, position);
		sink.onDispose(completionHandler);
		flux.subscribe(completionHandler);
	});
}
 
Example #2
Source File: CloudFoundryAppSchedulerTests.java    From spring-cloud-deployer-cloudfoundry with Apache License 2.0 6 votes vote down vote up
private void mockAppResultsInAppList() {
	givenRequestListApplications(Flux.just(ApplicationSummary.builder()
					.diskQuota(0)
					.id("test-application-id-1")
					.instances(1)
					.memoryLimit(0)
					.name("test-application-1")
					.requestedState("RUNNING")
					.runningInstances(1)
					.build(),
			ApplicationSummary.builder()
					.diskQuota(0)
					.id("test-application-id-2")
					.instances(1)
					.memoryLimit(0)
					.name("test-application-2")
					.requestedState("RUNNING")
					.runningInstances(1)
					.build()));
}
 
Example #3
Source File: RedissonReactiveListCommands.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<ByteBufferResponse<BRPopLPushCommand>> bRPopLPush(Publisher<BRPopLPushCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKey(), "Key must not be null!");
        Assert.notNull(command.getDestination(), "Destination key must not be null!");
        Assert.notNull(command.getTimeout(), "Timeout must not be null!");
        
        byte[] keyBuf = toByteArray(command.getKey());
        byte[] destinationBuf = toByteArray(command.getDestination());
        
        Mono<byte[]> m = write(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.BRPOPLPUSH, 
                                keyBuf, destinationBuf, command.getTimeout().getSeconds());
        return m.map(v -> new ByteBufferResponse<>(command, ByteBuffer.wrap(v)));
    });
}
 
Example #4
Source File: SmokeTest.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleGet_success() throws JsonProcessingException {

  wireMockRule.stubFor(get(urlEqualTo("/icecream/flavors"))
      .willReturn(aResponse().withStatus(200)
          .withHeader("Content-Type", "application/json")
          .withBody(TestUtils.MAPPER.writeValueAsString(Flavor.values()))));

  wireMockRule.stubFor(get(urlEqualTo("/icecream/mixins"))
      .willReturn(aResponse().withStatus(200)
          .withHeader("Content-Type", "application/json")
          .withBody(TestUtils.MAPPER.writeValueAsString(Mixin.values()))));

  Flux<Flavor> flavors = client.getAvailableFlavors();
  Flux<Mixin> mixins = client.getAvailableMixins();

  StepVerifier.create(flavors)
      .expectNextSequence(asList(Flavor.values()))
      .verifyComplete();
  StepVerifier.create(mixins)
      .expectNextSequence(asList(Mixin.values()))
      .verifyComplete();

}
 
Example #5
Source File: RedissonReactiveStringCommands.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override

public Flux<NumericResponse<BitCountCommand, Long>> bitCount(Publisher<BitCountCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKey(), "Key must not be null!");

        Range<Long> range = command.getRange();
        if (range == null) {
            range = Range.unbounded();
        }
        
        byte[] keyBuf = toByteArray(command.getKey());
        Mono<Long> m;
        if (range == Range.<Long>unbounded()) {
            m = write(keyBuf, StringCodec.INSTANCE, RedisCommands.BITCOUNT, keyBuf); 
        } else {
            m = write(keyBuf, StringCodec.INSTANCE, RedisCommands.BITCOUNT, 
                    keyBuf, range.getLowerBound().getValue().orElse(0L), 
                    range.getUpperBound().getValue().get());
        }
        return m.map(v -> new NumericResponse<>(command, v));
    });
}
 
Example #6
Source File: StepVerifierTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void expectNextCountErrorIsSuppressed() {
	assertThatExceptionOfType(AssertionError.class)
			.isThrownBy(() -> StepVerifier.create(Flux.just("foo")
			.flatMap(r -> { throw new ArrayIndexOutOfBoundsException();}))
                .expectNextCount(1)
                .verifyError())
			.satisfies(error -> {
				assertThat(error)
						.hasMessageStartingWith("expectation \"expectNextCount(1)\" failed")
						.hasMessageContaining("signal: onError(java.lang.ArrayIndexOutOfBoundsException)");
				assertThat(error.getSuppressed())
						.hasSize(1)
						.allMatch(spr -> spr instanceof ArrayIndexOutOfBoundsException);
			});
}
 
Example #7
Source File: PingPongApp.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("Duplicates")
RSocket accept(RSocket rSocket) {
	RSocket pong = new RSocketProxy(rSocket) {

		@Override
		public Flux<Payload> requestChannel(Publisher<Payload> payloads) {
			return Flux.from(payloads).map(Payload::getDataUtf8).doOnNext(str -> {
				int received = pingsReceived.incrementAndGet();
				log.info("received " + str + "(" + received + ") in Pong");
			}).map(PingPongApp::reply).map(reply -> {
				ByteBuf data = ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT,
						reply);
				ByteBuf routingMetadata = getForwardingMetadata(strategies,
						"ping", 1L);
				return DefaultPayload.create(data, routingMetadata);
			});
		}
	};
	return pong;
}
 
Example #8
Source File: ReactorUtilsTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void contextShouldCombineMDCs() {
    String value1 = "value1";
    String value2 = "value2";
    String key1 = "key1";
    String key2 = "key2";

    Flux.just(1)
        .doOnEach(ReactorUtils.log(() -> {
            assertThat(MDC.get(key1)).isEqualTo(value1);
            assertThat(MDC.get(key2)).isEqualTo(value2);
        }))
        .subscriberContext(ReactorUtils.context("test1", MDCBuilder.of(key1, value1)))
        .subscriberContext(ReactorUtils.context("test2", MDCBuilder.of(key2, value2)))
        .blockLast();
}
 
Example #9
Source File: ClientController.java    From tutorials with MIT License 5 votes vote down vote up
@Async
public void consumeSSE() {
    ParameterizedTypeReference<ServerSentEvent<String>> type = new ParameterizedTypeReference<ServerSentEvent<String>>() {
    };

    Flux<ServerSentEvent<String>> eventStream = client.get()
        .uri("/stream-sse")
        .retrieve()
        .bodyToFlux(type);

    eventStream.subscribe(content -> logger.info("Current time: {} - Received SSE: name[{}], id [{}], content[{}] ", LocalTime.now(), content.event(), content.id(), content.data()), error -> logger.error("Error receiving SSE: {}", error),
        () -> logger.info("Completed!!!"));
}
 
Example #10
Source File: FluxToRSPublisherTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
protected Optional<Flux> createInstanceEmittingAMultipleValuesAndFailure(String v1, String v2, RuntimeException e) {
    Flux<String> stream = Flux.create(emitter -> {
        emitter.next(v1);
        emitter.next(v2);
        emitter.error(e);
    });
    return Optional.of(stream);
}
 
Example #11
Source File: DopplerLogStreamPublisher.java    From spring-cloud-app-broker with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<Envelope> getLogStream(String serviceInstanceId) {
	return this.applicationIdsProvider
		.getApplicationIds(serviceInstanceId)
		.doOnNext(id -> LOG.debug("Starting log streaming for app with ID {}", id))
		.flatMap(this::createApplicationStreamer);
}
 
Example #12
Source File: RestTemplateFakeReactiveHttpClient.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ReactiveHttpResponse> executeRequest(ReactiveHttpRequest request) {

  Mono<Object> bodyMono;
  if (request.body() instanceof Mono) {
    bodyMono = ((Mono<Object>) request.body());
  } else if (request.body() instanceof Flux) {
    bodyMono = ((Flux) request.body()).collectList();
  } else {
    bodyMono = Mono.just(request.body());
  }
  bodyMono = bodyMono.switchIfEmpty(Mono.just(new byte[0]));

  return bodyMono.<ReactiveHttpResponse>flatMap(body -> {
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(request.headers());
    if (acceptGzip) {
      headers.add("Accept-Encoding", "gzip");
    }

    ResponseEntity response =
            restTemplate.exchange(request.uri().toString(), HttpMethod.valueOf(request.method()),
                    new HttpEntity<>(body, headers), responseType());

    return Mono.just(new FakeReactiveHttpResponse(response, returnPublisherType));
  })
          .onErrorMap(ex -> ex instanceof ResourceAccessException
                              && ex.getCause() instanceof SocketTimeoutException,
                  ReadTimeoutException::new)
          .onErrorResume(HttpStatusCodeException.class,
                  ex -> Mono.just(new ErrorReactiveHttpResponse(ex)));
}
 
Example #13
Source File: SimpleReactorExample.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 5 votes vote down vote up
@Test
public void testHotPublisher(){
  UnicastProcessor<String> hotSource = UnicastProcessor.create();
  Flux<Category> hotPublisher = hotSource.publish()
      .autoConnect().map((String t) -> Category.builder().name(t).build());
  hotPublisher.subscribe(category -> System.out.println("Subscriber 1: "+ category.getName()));
  hotSource.onNext("sports");
  hotSource.onNext("cars");
  hotPublisher.subscribe(category -> System.out.println("Subscriber 2: "+category.getName()));
  hotSource.onNext("games");
  hotSource.onNext("electronics");
  hotSource.onComplete();
}
 
Example #14
Source File: DevicePropertiesMeasurement.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<MeasurementValue> getValue(MeasurementParameter parameter) {
    return Mono.justOrEmpty(parameter.getString("deviceId"))
        .flatMapMany(deviceId -> {
            int history = parameter.getInt("history").orElse(1);
            //合并历史数据和实时数据
            return fromHistory(deviceId, history);
        });
}
 
Example #15
Source File: MailboxManagerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void searchForMessageShouldReturnMessagesFromMyDelegatedMailboxes() throws Exception {
    assumeTrue(mailboxManager.hasCapability(MailboxCapabilities.ACL));

    session = mailboxManager.createSystemSession(USER_1);
    MailboxSession sessionFromDelegater = mailboxManager.createSystemSession(USER_2);
    MailboxPath delegatedMailboxPath = MailboxPath.forUser(USER_2, "SHARED");
    MailboxId delegatedMailboxId = mailboxManager.createMailbox(delegatedMailboxPath, sessionFromDelegater).get();
    MessageManager delegatedMessageManager = mailboxManager.getMailbox(delegatedMailboxId, sessionFromDelegater);

    MessageId messageId = delegatedMessageManager
        .appendMessage(AppendCommand.from(message), sessionFromDelegater)
        .getId().getMessageId();

    mailboxManager.setRights(delegatedMailboxPath,
        MailboxACL.EMPTY.apply(MailboxACL.command()
            .forUser(USER_1)
            .rights(MailboxACL.Right.Read, MailboxACL.Right.Lookup)
            .asAddition()),
        sessionFromDelegater);

    MultimailboxesSearchQuery multiMailboxesQuery = MultimailboxesSearchQuery
        .from(SearchQuery.matchAll())
        .build();

    assertThat(Flux.from(mailboxManager.search(multiMailboxesQuery, session, DEFAULT_MAXIMUM_LIMIT))
        .collectList().block())
        .containsOnly(messageId);
}
 
Example #16
Source File: R043_Zip.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void zipTwoStreams() throws Exception {
	//given
	final Flux<Integer> nums = Flux.just(1, 2, 3);
	final Flux<String> strs = Flux.just("a", "b");

	//when
	final Flux<Tuple2<Integer, String>> pairs = nums.zipWith(strs);
	final Flux<Tuple2<Integer, String>> pairs2 = Flux.zip(nums, strs);  //same thing

	//then
	pairs.subscribe(p -> log.info("Pair: {}", p));
}
 
Example #17
Source File: ReactiveCredHubCredentialTemplate.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<CredentialSummary> findByPath(final String path) {
	Assert.notNull(path, "credential path must not be null");

	return this.credHubOperations.doWithWebClient((webClient) -> webClient.get().uri(PATH_URL_QUERY, path)
			.retrieve().onStatus(HttpStatus::isError, ExceptionUtils::buildError)
			.bodyToMono(CredentialSummaryData.class)
			.flatMapMany((data) -> Flux.fromIterable(data.getCredentials())));
}
 
Example #18
Source File: CtrlRscDfnDeleteApiCallHandler.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
private Flux<ApiCallRc> deleteRemainingInTransaction(ResourceName rscName)
{
    ResourceDefinition rscDfn = ctrlApiDataLoader.loadRscDfn(rscName, false);

    Flux<ApiCallRc> flux;

    if (rscDfn == null)
    {
        flux = Flux.empty();
    }
    else
    {
        for (Resource rsc : getRscStreamPrivileged(rscDfn).collect(Collectors.toList()))
        {
            if (isDisklessPrivileged(rsc))
            {
                deletePrivileged(rsc);
            }
            else
            {
                markDeletedPrivileged(rsc);
            }
        }
        ctrlTransactionHelper.commit();

        Flux<ApiCallRc> nextStep = deleteData(rscName);
        flux = ctrlSatelliteUpdateCaller.updateSatellites(rscDfn, nextStep)
            .transform(updateResponses -> CtrlResponseUtils.combineResponses(
                updateResponses,
                rscName,
                "Resource {1} on {0} deleted"
            ))
            .concatWith(nextStep)
            .onErrorResume(CtrlResponseUtils.DelayedApiRcException.class, ignored -> Flux.empty());
    }

    return flux;
}
 
Example #19
Source File: GaugeSample.java    From micrometer with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();
    AtomicLong n = new AtomicLong();
    registry.gauge("gauge", Tags.of("k", "v"), n);
    registry.gauge("gauge", Tags.of("k", "v1"), n, n2 -> n2.get() - 1);

    RandomEngine r = new MersenneTwister64(0);
    Normal dist = new Normal(0, 10, r);

    Flux.interval(Duration.ofSeconds(5))
            .doOnEach(d -> n.set(Math.abs(dist.nextInt())))
            .blockLast();
}
 
Example #20
Source File: ServerHttpResponseTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-14952
public void writeAndFlushWithFluxOfDefaultDataBuffer() throws Exception {
	TestServerHttpResponse response = new TestServerHttpResponse();
	Flux<Flux<DefaultDataBuffer>> flux = Flux.just(Flux.just(wrap("foo")));
	response.writeAndFlushWith(flux).block();

	assertTrue(response.statusCodeWritten);
	assertTrue(response.headersWritten);
	assertTrue(response.cookiesWritten);

	assertEquals(1, response.body.size());
	assertEquals("foo", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8));
}
 
Example #21
Source File: DashboardController.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "/{dashboard}/{object}/{measurement}/{dimension}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@Authorize(merge = false)
public Flux<MeasurementValue> getMeasurementValue(@PathVariable String dashboard,
                                                  @PathVariable String object,
                                                  @PathVariable String dimension,
                                                  @PathVariable String measurement,
                                                  @RequestParam Map<String, Object> params) {
    return dashboardManager
        .getDashboard(dashboard)
        .flatMap(dash -> dash.getObject(object))
        .flatMap(obj -> obj.getMeasurement(measurement))
        .flatMap(meas -> meas.getDimension(dimension))
        .switchIfEmpty(Mono.error(() -> new NotFoundException("不支持的仪表盘")))
        .flatMapMany(dim -> dim.getValue(MeasurementParameter.of(params)));
}
 
Example #22
Source File: CredentialProviderService.java    From spring-cloud-app-broker with Apache License 2.0 5 votes vote down vote up
public Mono<List<BackingApplication>> addCredentials(List<BackingApplication> backingApplications,
	String serviceInstanceGuid) {
	return Flux.fromIterable(backingApplications)
		.flatMap(backingApplication -> {
			List<CredentialProviderSpec> specs = getSpecsForApplication(backingApplication);

			return Flux.fromIterable(specs)
				.flatMap(spec -> {
					CredentialProvider provider = locator.getByName(spec.getName(), spec.getArgs());
					return provider.addCredentials(backingApplication, serviceInstanceGuid);
				})
				.then(Mono.just(backingApplication));
		})
		.collectList();
}
 
Example #23
Source File: TransportTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("makes 100 requestResponse requests")
@Test
default void largePayloadRequestResponse100() {
  Flux.range(1, 100)
      .flatMap(i -> getClient().requestResponse(LARGE_PAYLOAD).map(Payload::getDataUtf8))
      .as(StepVerifier::create)
      .expectNextCount(100)
      .expectComplete()
      .verify(getTimeout());
}
 
Example #24
Source File: CtrlVlmDfnModifyApiCallHandler.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
private Flux<ApiCallRc> resizeDrbdInTransaction(ResourceName rscName, VolumeNumber vlmNr)
{
    VolumeDefinition vlmDfn = ctrlApiDataLoader.loadVlmDfn(rscName, vlmNr, false);

    Flux<ApiCallRc> flux;

    if (vlmDfn == null)
    {
        flux = Flux.empty();
    }
    else
    {
        Optional<Volume> drbdResizeVlm = streamVolumesPrivileged(vlmDfn)
            .filter(this::isDrbdDiskful)
            .findAny();
        drbdResizeVlm.ifPresent(this::markVlmDrbdResize);

        ctrlTransactionHelper.commit();

        Flux<ApiCallRc> nextStep = finishResize(rscName, vlmNr);

        flux = ctrlSatelliteUpdateCaller.updateSatellites(vlmDfn.getResourceDefinition(), nextStep)
            .transform(
                updateResponses -> CtrlResponseUtils.combineResponses(
                    updateResponses,
                    rscName,
                    getNodeNames(drbdResizeVlm),
                    "Resized DRBD resource {1} on {0}",
                    null
                )
            )
            .concatWith(nextStep);
    }

    return flux;
}
 
Example #25
Source File: FluxWindowConsistencyTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void windowWhileComplete() throws Exception {
	Flux<Flux<Integer>> windows = source.windowWhile(i -> i % 3 != 0);
	subscribe(windows);
	generateAndComplete(1, 5);
	verifyMainComplete(Arrays.asList(1, 2), Arrays.asList(4, 5));
}
 
Example #26
Source File: RestEntityRetriever.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Flux<Member> getGuildMembers(Snowflake guildId) {
    Function<Map<String, Object>, Flux<MemberData>> doRequest = params ->
            rest.getGuildService().getGuildMembers(guildId.asLong(), params);

   return PaginationUtil.paginateAfter(doRequest, data -> Snowflake.asLong(data.user().id()), 0, 100)
                    .map(data -> new Member(gateway, data, guildId.asLong()));
}
 
Example #27
Source File: ReactiveEmployeeRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenRecordsAreInserted_whenDbIsQueried_thenShouldIncludeNewRecords() {

	Mono<Long> saveAndCount = repository.count()
			.doOnNext(System.out::println)
			.thenMany(repository.saveAll(Flux.just(new Employee(325, "Kim Jones", "Florida", "[email protected]", 42),
					new Employee(654, "Tom Moody", "New Hampshire", "[email protected]", 44))))
			.last()
			.flatMap(v -> repository.count())
			.doOnNext(System.out::println);

	StepVerifier.create(saveAndCount).expectNext(6L).verifyComplete();
}
 
Example #28
Source File: IntAuthResponse.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Flux<byte[]> executeReactive(InputStream msgDataIn)
    throws IOException
{
    return executeReactive(peerProvider.get(), msgDataIn, false)
        .thenMany(Flux.<byte[]>empty());
}
 
Example #29
Source File: ReactorSnippets.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@Test
public void findingMissingLetter() {
    Flux<String> manyLetters = Flux
            .fromIterable(words)
            .flatMap(word -> Flux.fromArray(word.split("")))
            .distinct()
            .sort()
            .zipWith(Flux.range(1, Integer.MAX_VALUE),
                    (string, count) -> String.format("%2d. %s", count, string));

    manyLetters.subscribe(System.out::println);
}
 
Example #30
Source File: KinesisStreamReactorEx.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Because a Flux is also a publisher, the publisherTransformer method integrates nicely with Reactor. Notice that
 * you must adapt to an SdkPublisher.
 */
private static CompletableFuture<Void> responseHandlerBuilder_OnEventStream_Reactor(KinesisAsyncClient client, SubscribeToShardRequest request) {
    SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler
        .builder()
        .onError(t -> System.err.println("Error during stream - " + t.getMessage()))
        .publisherTransformer(p -> Flux.from(p).limitRate(100).as(SdkPublisher::adapt))
        .build();
    return client.subscribeToShard(request, responseHandler);
}