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

The following examples show how to use reactor.core.publisher.Flux#just() . 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: DefaultServerRequestTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void bodyToMonoParameterizedTypeReference() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.setContentType(MediaType.TEXT_PLAIN);
	MockServerHttpRequest mockRequest = MockServerHttpRequest
			.method(HttpMethod.GET, "http://example.com?foo=bar")
			.headers(httpHeaders)
			.body(body);
	DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), messageReaders);

	ParameterizedTypeReference<String> typeReference = new ParameterizedTypeReference<String>() {};
	Mono<String> resultMono = request.bodyToMono(typeReference);
	assertEquals("foo", resultMono.block());
}
 
Example 2
Source File: DefaultServerRequestTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void bodyUnacceptable() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.setContentType(MediaType.TEXT_PLAIN);
	MockServerHttpRequest mockRequest = MockServerHttpRequest
			.method(HttpMethod.GET, "http://example.com?foo=bar")
			.headers(httpHeaders)
			.body(body);
	DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());

	Flux<String> resultFlux = request.bodyToFlux(String.class);
	StepVerifier.create(resultFlux)
			.expectError(UnsupportedMediaTypeStatusException.class)
			.verify();
}
 
Example 3
Source File: Jackson2JsonEncoderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void encodeNonStream() {
	Flux<Pojo> input = Flux.just(
			new Pojo("foo", "bar"),
			new Pojo("foofoo", "barbar"),
			new Pojo("foofoofoo", "barbarbar")
	);

	testEncode(input, Pojo.class, step -> step
			.consumeNextWith(expectString("[" +
					"{\"foo\":\"foo\",\"bar\":\"bar\"}," +
					"{\"foo\":\"foofoo\",\"bar\":\"barbar\"}," +
					"{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}]")
					.andThen(DataBufferUtils::release))
			.verifyComplete());
}
 
Example 4
Source File: BodyExtractorsTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void toFlux() {
	BodyExtractor<Flux<String>, ReactiveHttpInputMessage> extractor = BodyExtractors.toFlux(String.class);

	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	MockServerHttpRequest request = MockServerHttpRequest.post("/").body(body);
	Flux<String> result = extractor.extract(request, this.context);

	StepVerifier.create(result)
			.expectNext("foo")
			.expectComplete()
			.verify();
}
 
Example 5
Source File: WebSocketSampleApplicationTest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testWebSocket() {
    Flux<String> originalMessages = Flux.just("first", "second");
    List<String> responseMessages = new CopyOnWriteArrayList<>();

    disposable = client.execute(serviceUri, session -> {
        // Convert strings to WebSocket messages and send them
        Mono<Void> outputMono = session.send(originalMessages.map(session::textMessage));

        Mono<Void> inputMono = session.receive() // Receive a messages stream
            .map(WebSocketMessage::getPayloadAsText) // Extract a payload from each message
            .doOnNext(responseMessages::add) // Store the payload to a collection
            .then();

        return outputMono.then(inputMono); // Start receiving messages after sending.
    }).subscribe(); // Subscribe to the socket. Original messages will be sent and then we'll start receiving responses.

    await()
        .atMost(2, SECONDS)
        .until(() -> responseMessages, contains("FIRST", "SECOND"));
}
 
Example 6
Source File: BodyExtractorsTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void toFormData() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	String text = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3";
	DefaultDataBuffer dataBuffer = factory.wrap(ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8)));
	Flux<DataBuffer> body = Flux.just(dataBuffer);

	MockServerHttpRequest request = MockServerHttpRequest.post("/")
			.contentType(MediaType.APPLICATION_FORM_URLENCODED)
			.body(body);

	Mono<MultiValueMap<String, String>> result = BodyExtractors.toFormData().extract(request, this.context);

	StepVerifier.create(result)
			.consumeNextWith(form -> {
				assertEquals("Invalid result", 3, form.size());
				assertEquals("Invalid result", "value 1", form.getFirst("name 1"));
				List<String> values = form.get("name 2");
				assertEquals("Invalid result", 2, values.size());
				assertEquals("Invalid result", "value 2+1", values.get(0));
				assertEquals("Invalid result", "value 2+2", values.get(1));
				assertNull("Invalid result", form.getFirst("name 3"));
			})
			.expectComplete()
			.verify();
}
 
Example 7
Source File: StepVerifierTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void cancelInvalid() {
	Flux<String> flux = Flux.just("bar", "baz");

	assertThatExceptionOfType(AssertionError.class)
			.isThrownBy(() -> StepVerifier.create(flux)
	            .expectNext("foo")
	            .thenCancel()
	            .verify())
            .withMessage("expectation \"expectNext(foo)\" failed (expected value: foo; actual value: bar)");
}
 
Example 8
Source File: MicrometerDuplexConnectionTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("receive gathers metrics")
@Test
void receive() {
  Flux<ByteBuf> frames =
      Flux.just(
          createTestCancelFrame(),
          createTestErrorFrame(),
          createTestKeepaliveFrame(),
          createTestLeaseFrame(),
          createTestMetadataPushFrame(),
          createTestPayloadFrame(),
          createTestRequestChannelFrame(),
          createTestRequestFireAndForgetFrame(),
          createTestRequestNFrame(),
          createTestRequestResponseFrame(),
          createTestRequestStreamFrame(),
          createTestSetupFrame());

  when(delegate.receive()).thenReturn(frames);

  new MicrometerDuplexConnection(
          CLIENT, delegate, meterRegistry, Tag.of("test-key", "test-value"))
      .receive()
      .as(StepVerifier::create)
      .expectNextCount(12)
      .verifyComplete();

  assertThat(findCounter(CLIENT, CANCEL).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, COMPLETE).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, ERROR).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, KEEPALIVE).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, LEASE).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, METADATA_PUSH).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, REQUEST_CHANNEL).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, REQUEST_FNF).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, REQUEST_N).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, REQUEST_RESPONSE).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, REQUEST_STREAM).count()).isEqualTo(1);
  assertThat(findCounter(CLIENT, SETUP).count()).isEqualTo(1);
}
 
Example 9
Source File: RestServiceController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@GetMapping(path = "/fluxAddEmp") 
public Flux<String> addMonoEmp(){
	Employee newEmp = new Employee();
   	newEmp.setEmpid(56758);
   	newEmp.setAge(43);
   	newEmp.setBirthday(new Date(88, 10,10));
   	newEmp.setDeptid(362);
   	newEmp.setEmail("[email protected]");
   	newEmp.setFirstname("John");
   	newEmp.setLastname("Lowell");
	employeeServiceImpl.saveEmployeeRec(newEmp);
	Flux<String> status = Flux.just("OK");
	return status;
}
 
Example 10
Source File: Jackson2SmileEncoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void encodeAsStream() throws Exception {
	Pojo pojo1 = new Pojo("foo", "bar");
	Pojo pojo2 = new Pojo("foofoo", "barbar");
	Pojo pojo3 = new Pojo("foofoofoo", "barbarbar");
	Flux<Pojo> input = Flux.just(pojo1, pojo2, pojo3);
	ResolvableType type = ResolvableType.forClass(Pojo.class);

	testEncodeAll(input, type, step -> step
			.consumeNextWith(expect(pojo1, Pojo.class))
			.consumeNextWith(expect(pojo2, Pojo.class))
			.consumeNextWith(expect(pojo3, Pojo.class))
			.verifyComplete(),
	STREAM_SMILE_MIME_TYPE, null);
}
 
Example 11
Source File: ServerHttpResponseTests.java    From java-technology-stack 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 12
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromDirectCallableFluxCallsAssemblyHook() {
	final Flux<Integer> source = Flux.just(1);

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.fromDirect(source);
	Assertions.assertThat(wrappedCount).hasValue(1);
}
 
Example 13
Source File: R011_LetsMeetFlux.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void helloFlux() throws Exception {
	//given
	final Flux<String> reactor = Flux.just("Reactor");

	//when
	final List<String> value = reactor.collectList().block();

	//then
	assertThat(value).containsExactly("Reactor");
}
 
Example 14
Source File: StepVerifierTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyRecordMatchesError2() {
	Flux<String> flux = Flux.just("foo", "bar", "foobar");

	assertThatExceptionOfType(AssertionError.class)
			.isThrownBy(() -> StepVerifier.create(flux)
	            .expectNext("foo", "bar", "foobar")
	            .expectRecordedMatches(c -> c.size() == 3)
	            .expectComplete()
	            .verify())
			.withMessage("expectation \"expectRecordedMatches\" failed (expected record collector; actual record is [null])");
}
 
Example 15
Source File: SourceToFunctionsSupportTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@PollableBean(splittable = true)
public Supplier<Flux<Message<?>>> messageStreamSupplier() {
	return () -> {
		Message<String> m1 = new GenericMessage<>(String.valueOf(counter.incrementAndGet()));
		Message<String> m2 = new GenericMessage<>(String.valueOf(counter.incrementAndGet()));
		Message<String> m3 = new GenericMessage<>(String.valueOf(counter.incrementAndGet()));
		return Flux.just(m1, m2, m3);
	};
}
 
Example 16
Source File: ReactiveTestServiceImpl.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<String> findNames() {
    return Flux.just("first", "second");
}
 
Example 17
Source File: FreeCapacityFetcherProto.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
private Flux<Tuple2<StorPool.Key, Tuple2<SpaceInfo, List<ApiCallRc>>>> parseFreeSpacesInTransaction(
    Tuple2<NodeName, ByteArrayInputStream> freeSpaceAnswer
)
{
    List<Tuple2<Key, Tuple2<SpaceInfo, List<ApiCallRc>>>> ret = new ArrayList<>();
    try
    {
        NodeName nodeName = freeSpaceAnswer.getT1();
        ByteArrayInputStream freeSpaceMsgDataIn = freeSpaceAnswer.getT2();

        MsgIntFreeSpace freeSpaces = MsgIntFreeSpace.parseDelimitedFrom(freeSpaceMsgDataIn);
        for (StorPoolFreeSpace freeSpaceInfo : freeSpaces.getFreeSpacesList())
        {
            List<ApiCallRc> apiCallRcs = new ArrayList<>();
            if (freeSpaceInfo.getErrorsCount() > 0)
            {
                ApiCallRcImpl apiCallRc = new ApiCallRcImpl();
                for (ApiCallResponse msgApiCallResponse : freeSpaceInfo.getErrorsList())
                {
                    apiCallRc.addEntry(
                        ProtoDeserializationUtils.parseApiCallRc(
                            msgApiCallResponse,
                            "Node: '" + nodeName + "', storage pool: '" + freeSpaceInfo.getStorPoolName() +
                                "' - "
                        )
                    );
                }
                apiCallRcs.add(apiCallRc);
            }

            StorPoolName storPoolName = new StorPoolName(freeSpaceInfo.getStorPoolName());
            long freeCapacity = freeSpaceInfo.getFreeCapacity();
            long totalCapacity = freeSpaceInfo.getTotalCapacity();

            ret.add(
                Tuples.of(
                    new StorPool.Key(nodeName, storPoolName),
                    Tuples.of(
                        new SpaceInfo(totalCapacity, freeCapacity),
                        apiCallRcs
                    )
                )
            );

            // also update storage pool's freespacemanager
            StorPool storPool = nodeRepository.get(apiCtx, nodeName).getStorPool(apiCtx, storPoolName);
            storPool.getFreeSpaceTracker().setCapacityInfo(apiCtx, freeCapacity, totalCapacity);

            ctrlTransactionHelper.commit();
        }
    }
    catch (IOException | InvalidNameException | AccessDeniedException exc)
    {
        throw new ImplementationError(exc);
    }
    return Flux.just(ret.toArray(new Tuple2[0]));
}
 
Example 18
Source File: OpenWhiskActionHandler.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
private Flux<?> extract(Object input) {
	if (input instanceof Collection) {
		return Flux.fromIterable((Iterable<?>) input);
	}
	return Flux.just(input);
}
 
Example 19
Source File: CtrlRscDfnDeleteApiCallHandler.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
private Flux<ApiCallRc> deleteResourceDefinitionInTransaction(String rscNameStr)
{
    requireRscDfnMapChangeAccess();

    ResourceDefinition rscDfn = ctrlApiDataLoader.loadRscDfn(rscNameStr, false);

    if (rscDfn == null)
    {
        throw new ApiRcException(ApiCallRcImpl.simpleEntry(
            ApiConsts.WARN_NOT_FOUND,
            getRscDfnDescription(rscNameStr) + " not found."
        ));
    }

    if (hasSnapshotsPrivileged(rscDfn))
    {
        throw new ApiRcException(ApiCallRcImpl.simpleEntry(
            ApiConsts.FAIL_EXISTS_SNAPSHOT_DFN,
            "Cannot delete " + getRscDfnDescriptionInline(rscNameStr) + " because it has snapshots."
        ));
    }

    Optional<Resource> rscInUse = null;
    rscInUse = anyResourceInUsePrivileged(rscDfn);
    if (rscInUse.isPresent())
    {
        NodeName nodeName = rscInUse.get().getNode().getName();
        throw new ApiRcException(ApiCallRcImpl
            .entryBuilder(
                ApiConsts.FAIL_IN_USE,
                String.format("Resource '%s' on node '%s' is still in use.", rscNameStr, nodeName.displayValue)
            )
            .setCause("Resource is mounted/in use.")
            .setCorrection(String.format("Un-mount resource '%s' on the node '%s'.",
                rscNameStr,
                nodeName.displayValue))
            .build()
        );
    }

    Flux<ApiCallRc> flux;

    ResourceName rscName = rscDfn.getName();
    UUID rscDfnUuid = rscDfn.getUuid();
    String descriptionFirstLetterCaps = firstLetterCaps(getRscDfnDescriptionInline(rscNameStr));
    if (rscDfn.getResourceCount() > 0)
    {
        markDeleted(rscDfn);

        ctrlTransactionHelper.commit();

        ApiCallRc responses = ApiCallRcImpl.singletonApiCallRc(
            ApiCallRcImpl.entryBuilder(ApiConsts.DELETED, descriptionFirstLetterCaps + " marked for deletion.")
                .setDetails(descriptionFirstLetterCaps + " UUID is: " + rscDfnUuid).build()
        );

        flux = Flux
            .just(responses)
            // first delete diskless resources, because DRBD raises an error if all peers with disks are
            // removed from a diskless resource
            .concatWith(deleteDiskless(rscName));
    }
    else
    {
        flux = Flux.just(commitDeleteRscDfnData(rscDfn));
    }

    return flux;
}
 
Example 20
Source File: HttpGetIntegrationTests.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Bean
public Supplier<Flux<Foo>> foos() {
	return () -> Flux.just(new Foo("foo"), new Foo("bar"));
}