reactor.rx.Streams Java Examples

The following examples show how to use reactor.rx.Streams. 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: CodecSample.java    From reactive-ipc-jvm with Apache License 2.0 6 votes vote down vote up
private static void echoJsonStreamDecoding() {

        TcpServer<Person, Person> transport = Netty4TcpServer.<Person, Person>create(
                0,
                new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addFirst(
                                new JsonObjectDecoder(),
                                new JacksonJsonCodec());
                    }
                });

        ReactorTcpServer.create(transport)
                .start(connection -> {
                    connection.log("input")
                            .observeComplete(v -> LOG.info("Connection input complete"))
                            .capacity(1)
                            .consume(person -> {
                                person = new Person(person.getLastName(), person.getFirstName());
                                Streams.wrap(connection.writeWith(Streams.just(person))).consume();
                            });
                    return Streams.never();
                });

    }
 
Example #2
Source File: RepositoryStatisticsUpdatedReactor.java    From mojito with Apache License 2.0 5 votes vote down vote up
@PostConstruct
private void createProcessor() {
    processor = RingBufferProcessor.create();
    Stream stream = Streams.wrap(processor);
    stream.buffer(1, TimeUnit.SECONDS).consume(new Consumer<List<Long>>() {
        @Override
        public void accept(List<Long> repositoryIds) {
            for (Long repositoryId : Sets.newHashSet(repositoryIds)) {
                repositoryStatisticsJobScheduler.schedule(repositoryId);
            }
        }
    });
}
 
Example #3
Source File: ReactorTcpServerTests.java    From reactive-ipc-jvm with Apache License 2.0 5 votes vote down vote up
@Test
public void writeMultipleValues() throws IOException {
    Promise<ByteBuf> chunk1 = Promises.success(Unpooled.buffer().writeBytes("This is".getBytes()));
    Promise<ByteBuf> chunk2 = Promises.success(Unpooled.buffer().writeBytes(" a test!".getBytes()));
    reactorServer.start(connection -> connection.writeWith(Streams.concat(chunk1, chunk2)));
    assertEquals("This is a test!", SocketTestUtils.read("localhost", reactorServer.getPort()));
}
 
Example #4
Source File: ReactorTcpServerSample.java    From reactive-ipc-jvm with Apache License 2.0 5 votes vote down vote up
/**
 * Keep echoing until the client goes away.
 */
private static void echo(TcpServer<ByteBuf, ByteBuf> transport) {
    ReactorTcpServer.create(transport)
        .startAndAwait(connection -> {
            connection.flatMap(inByteBuf -> {
                String text = "Hello " + inByteBuf.toString(Charset.defaultCharset());
                ByteBuf outByteBuf = Unpooled.buffer().writeBytes(text.getBytes());
                return connection.writeWith(Streams.just(outByteBuf));
            }).consume();
            return Streams.never();
        });
}
 
Example #5
Source File: ReactorTcpServerSample.java    From reactive-ipc-jvm with Apache License 2.0 5 votes vote down vote up
/**
 * Keep echoing until the client sends "quit".
 */
private static void echoWithQuitCommand(TcpServer<ByteBuf, ByteBuf> transport) {
    ReactorTcpServer.create(transport)
        .start(connection -> connection
                .map(byteBuf -> byteBuf.toString(Charset.defaultCharset()))
                .takeWhile(input -> !"quit".equalsIgnoreCase(input.trim()))
                .filter(input -> !"quit".equalsIgnoreCase(input.trim()))
                .map(input -> "Hello " + input)
                .flatMap(text -> connection.writeWith(
                        Streams.just(Unpooled.buffer().writeBytes(text.getBytes()))
                    )
                )
                .after()
        );
}
 
Example #6
Source File: CodecSample.java    From reactive-ipc-jvm with Apache License 2.0 5 votes vote down vote up
private static void runLineBasedFrameDecoder() {

        TcpServer<String, String> transport = Netty4TcpServer.<String, String>create(
                0,
                new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        int bufferSize = 1;
                        ChannelConfig config = channel.config();
                        config.setOption(ChannelOption.SO_RCVBUF, bufferSize);
                        config.setOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(bufferSize));
                        channel.pipeline().addFirst(
                                new LineBasedFrameDecoder(256),
                                new StringDecoder(CharsetUtil.UTF_8),
                                new StringEncoder(CharsetUtil.UTF_8));
                    }
                });

        ReactorTcpServer.create(transport).start(connection -> {
            connection.log("input")
                    .observeComplete(v -> LOG.info("Connection input complete"))
                    .capacity(1)
                    .consume(line -> {
                        String response = "Hello " + line + "\n";
                        Streams.wrap(connection.writeWith(Streams.just(response))).consume();
                    });
            return Streams.never();
        });
    }
 
Example #7
Source File: Reactor2TcpConnection.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableFuture<Void> send(Message<P> message) {
	Promise<Void> afterWrite = Promises.prepare();
	this.channelStream.writeWith(Streams.just(message)).subscribe(afterWrite);
	return new PassThroughPromiseToListenableFutureAdapter<Void>(afterWrite);
}
 
Example #8
Source File: GpfdistServer.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
private HttpServer<Buffer, Buffer> createProtocolListener()
		throws Exception {

	final Stream<Buffer> stream = Streams
	.wrap(processor)
	.window(flushCount, flushTime, TimeUnit.SECONDS)
	.flatMap(new Function<Stream<Buffer>, Publisher<Buffer>>() {

		@Override
		public Publisher<Buffer> apply(Stream<Buffer> t) {

			return t.reduce(new Buffer(), new BiFunction<Buffer, Buffer, Buffer>() {

				@Override
				public Buffer apply(Buffer prev, Buffer next) {
					return prev.append(next);
				}
			});
		}
	})
	.process(RingBufferWorkProcessor.<Buffer>create("gpfdist-sink-worker", 8192, false));

	HttpServer<Buffer, Buffer> httpServer = NetStreams
			.httpServer(new Function<HttpServerSpec<Buffer, Buffer>, HttpServerSpec<Buffer, Buffer>>() {

				@Override
				public HttpServerSpec<Buffer, Buffer> apply(HttpServerSpec<Buffer, Buffer> server) {
					return server
							.codec(new GpfdistCodec())
							.listen(port);
				}
			});

	httpServer.get("/data", new ReactorChannelHandler<Buffer, Buffer, HttpChannel<Buffer,Buffer>>() {

		@Override
		public Publisher<Void> apply(HttpChannel<Buffer, Buffer> request) {
			request.responseHeaders().removeTransferEncodingChunked();
			request.addResponseHeader("Content-type", "text/plain");
			request.addResponseHeader("Expires", "0");
			request.addResponseHeader("X-GPFDIST-VERSION", "Spring Dataflow");
			request.addResponseHeader("X-GP-PROTO", "1");
			request.addResponseHeader("Cache-Control", "no-cache");
			request.addResponseHeader("Connection", "close");

			return request.writeWith(stream
					.take(batchCount)
					.timeout(batchTimeout, TimeUnit.SECONDS, Streams.<Buffer>empty())
					.concatWith(Streams.just(Buffer.wrap(new byte[0]))))
					.capacity(1l);
		}
	});

	httpServer.start().awaitSuccess();
	log.info("Server running using address=[" + httpServer.getListenAddress() + "]");
	localPort = httpServer.getListenAddress().getPort();
	return httpServer;
}
 
Example #9
Source File: PassportService.java    From building-microservices with Apache License 2.0 4 votes vote down vote up
public Stream<Bookmark> getBookmarks(String userId) {
	return Streams.<Bookmark>create(subscriber -> {
		this.bookmarkClient.getBookmarks(userId).forEach(subscriber::onNext);
		subscriber.onComplete();
	}).dispatchOn(this.environment, Environment.cachedDispatcher()).log("bookmarks");
}
 
Example #10
Source File: PassportService.java    From building-microservices with Apache License 2.0 4 votes vote down vote up
public Stream<Contact> getContacts(String userId) {
	return Streams.<Contact>create(subscriber -> {
		this.contactClient.getContacts(userId).forEach(subscriber::onNext);
		subscriber.onComplete();
	}).dispatchOn(this.environment, Environment.cachedDispatcher()).log("contacts");
}
 
Example #11
Source File: PassportService.java    From building-microservices with Apache License 2.0 4 votes vote down vote up
public Stream<Passport> getPassport(String userId, Stream<Contact> contacts,
		Stream<Bookmark> bookmarks) {
	return Streams.zip(contacts.buffer(), bookmarks.buffer(),
			tuple -> new Passport(userId, tuple.getT1(), tuple.getT2()));
}
 
Example #12
Source File: ReactorTcpServerTests.java    From reactive-ipc-jvm with Apache License 2.0 4 votes vote down vote up
@Test
public void writeSingleValue() throws IOException {
    reactorServer.start(connection -> connection.writeWith(Streams.just(Unpooled.buffer().writeBytes("test".getBytes()))));
    assertEquals("test", SocketTestUtils.read("localhost", reactorServer.getPort()));
}