io.rsocket.SocketAcceptor Java Examples

The following examples show how to use io.rsocket.SocketAcceptor. 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: ResumeIntegrationTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
void serverMissingResume() {
  CloseableChannel closeableChannel =
      RSocketServer.create(SocketAcceptor.with(new TestResponderRSocket()))
          .bind(serverTransport(SERVER_HOST, SERVER_PORT))
          .block();

  RSocket rSocket =
      RSocketConnector.create()
          .resume(new Resume())
          .connect(clientTransport(closeableChannel.address()))
          .block();

  StepVerifier.create(rSocket.onClose().doFinally(s -> closeableChannel.dispose()))
      .expectErrorMatches(
          err ->
              err instanceof UnsupportedSetupException
                  && "resume not supported".equals(err.getMessage()))
      .verify(Duration.ofSeconds(5));

  Assertions.assertThat(rSocket.isDisposed()).isTrue();
}
 
Example #2
Source File: TestingStreaming.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRangeOfConsumers() {
  Closeable server = null;
  try {
    server =
        RSocketServer.create(
                SocketAcceptor.forRequestStream(
                    payload ->
                        Flux.range(1, 1000)
                            .map(l -> DefaultPayload.create("l -> " + l))
                            .cast(Payload.class)))
            .bind(serverTransport)
            .block();

    Flux.range(1, 6).flatMap(i -> consumer("connection number -> " + i)).blockLast();
    System.out.println("here");

  } finally {
    server.dispose();
  }
}
 
Example #3
Source File: ReservationServiceApplication.java    From bootiful-reactive-microservices with Apache License 2.0 6 votes vote down vote up
@EventListener(ApplicationReadyEvent.class)
public void serve() throws Exception {

	var abstractRSocket = new AbstractRSocket() {

		@Override
		public Flux<Payload> requestStream(Payload payload) {
			return reservationRepository.findAll()
				.map(RsocketServer.this::toJson)
				.map(DefaultPayload::create);
		}
	};

	SocketAcceptor socketAcceptor = (connectionSetupPayload, rSocket) -> Mono.just(abstractRSocket);

	RSocketFactory
		.receive()
		.acceptor(socketAcceptor)
		.transport(this.tcp)
		.start()
		.subscribe();

}
 
Example #4
Source File: ClientStreamingToServer.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  RSocketServer.create(
          SocketAcceptor.forRequestStream(
              payload ->
                  Flux.interval(Duration.ofMillis(100))
                      .map(aLong -> DefaultPayload.create("Interval: " + aLong))))
      .bind(TcpServerTransport.create("localhost", 7000))
      .subscribe();

  RSocket socket =
      RSocketConnector.connectWith(TcpClientTransport.create("localhost", 7000)).block();

  socket
      .requestStream(DefaultPayload.create("Hello"))
      .map(Payload::getDataUtf8)
      .doOnNext(logger::debug)
      .take(10)
      .then()
      .doFinally(signalType -> socket.dispose())
      .then()
      .block();
}
 
Example #5
Source File: BrokerActuatorHandlerRegistration.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
	if (this.running.compareAndSet(false, true)) {
		ConnectionSetupPayload connectionSetupPayload = getConnectionSetupPayload();
		SocketAcceptor responder = this.messageHandler.responder();
		responder.accept(connectionSetupPayload, new AbstractRSocket() {
		}).subscribe(rSocket -> {
			TagsMetadata tagsMetadata = TagsMetadata.builder()
					.routeId(properties.getRouteId().toString())
					.serviceName(properties.getServiceName())
					// TODO: move to well known implementation key
					.with("proxy", Boolean.FALSE.toString()).build();
			routingTable.register(tagsMetadata, rSocket);
		});
	}
}
 
Example #6
Source File: RSocketShellClient.java    From spring-rsocket-demo with GNU General Public License v3.0 6 votes vote down vote up
@ShellMethod("Login with your username and password.")
public void login(String username, String password) {
    log.info("Connecting using client ID: {} and username: {}", CLIENT_ID, username);
    SocketAcceptor responder = RSocketMessageHandler.responder(rsocketStrategies, new ClientHandler());
    UsernamePasswordMetadata user = new UsernamePasswordMetadata(username, password);
    this.rsocketRequester = rsocketRequesterBuilder
            .setupRoute("shell-client")
            .setupData(CLIENT_ID)
            .setupMetadata(user, SIMPLE_AUTH)
            .rsocketStrategies(builder ->
                    builder.encoder(new SimpleAuthenticationEncoder()))
            .rsocketConnector(connector -> connector.acceptor(responder))
            .connectTcp("localhost", 7000)
            .block();

    this.rsocketRequester.rsocket()
            .onClose()
            .doOnError(error -> log.warn("Connection CLOSED"))
            .doFinally(consumer -> log.info("Client DISCONNECTED"))
            .subscribe();
}
 
Example #7
Source File: RSocketClientToServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 6 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());
    credentials = new UsernamePasswordMetadata("user", "pass");
    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

    requester = builder
            .setupRoute("shell-client")
            .setupData(UUID.randomUUID().toString())
            .setupMetadata(credentials, mimeType)
            .rsocketStrategies(b ->
                    b.encoder(new SimpleAuthenticationEncoder()))
            .rsocketConnector(connector -> connector.acceptor(responder))
            .connectTcp("localhost", port)
            .block();
}
 
Example #8
Source File: RSocketClientToSecuredServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 6 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());
    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

    // *******  The user 'test' is NOT in the required 'USER' role! **********
    credentials = new UsernamePasswordMetadata("test", "pass");

    requester = builder
            .setupRoute("shell-client")
            .setupData(UUID.randomUUID().toString())
            .setupMetadata(credentials, mimeType)
            .rsocketStrategies(b ->
                    b.encoder(new SimpleAuthenticationEncoder()))

            .rsocketConnector(connector -> connector.acceptor(responder))
            .connectTcp("localhost", port)
            .block();
}
 
Example #9
Source File: DemoApplication.java    From spring-boot-rsocket with Apache License 2.0 5 votes vote down vote up
@Bean
public SocketAcceptor socketAcceptor(GreeterServer greeter,
		BlockingGreeterServer blockingGreeterServer) {
	return ((setup, sendingSocket) -> Mono.just(new RequestHandlingRSocket(
		greeter, blockingGreeterServer
	)));
}
 
Example #10
Source File: WebSocketTransportIntegrationTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void sendStreamOfDataWithExternalHttpServerTest() {
  ServerTransport.ConnectionAcceptor acceptor =
      RSocketServer.create(
              SocketAcceptor.forRequestStream(
                  payload ->
                      Flux.range(0, 10).map(i -> DefaultPayload.create(String.valueOf(i)))))
          .asConnectionAcceptor();

  DisposableServer server =
      HttpServer.create()
          .host("localhost")
          .route(router -> router.ws("/test", WebsocketRouteTransport.newHandler(acceptor)))
          .bindNow();

  RSocket rsocket =
      RSocketConnector.connectWith(
              WebsocketClientTransport.create(
                  URI.create("ws://" + server.host() + ":" + server.port() + "/test")))
          .block();

  StepVerifier.create(rsocket.requestStream(EmptyPayload.INSTANCE))
      .expectSubscription()
      .expectNextCount(10)
      .expectComplete()
      .verify(Duration.ofMillis(1000));
}
 
Example #11
Source File: ReservationServiceApplication.java    From bootiful-reactive-microservices with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {

	SocketAcceptor sa =
		(connectionSetupPayload, rSocket) -> Mono.just(new AbstractRSocket() {
			@Override
			public Flux<Payload> requestStream(Payload payload) {
				return
					reservationRepository
						.findAll()
						.map(x -> {
							try {
								return mapper.writeValueAsString(x);
							}
							catch (JsonProcessingException e) {
								throw new RuntimeException(e);
							}
						})
						.map(DefaultPayload::create);
			}
		});

	RSocketFactory
		.receive()
		.acceptor(sa)
		.transport(TcpServerTransport.create("localhost", 7000))
		.start()
		.onTerminateDetach()
		.subscribe();
}
 
Example #12
Source File: ChannelEchoClient.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

    SocketAcceptor echoAcceptor =
        SocketAcceptor.forRequestChannel(
            payloads ->
                Flux.from(payloads)
                    .map(Payload::getDataUtf8)
                    .map(s -> "Echo: " + s)
                    .map(DefaultPayload::create));

    RSocketServer.create(echoAcceptor)
        .bind(TcpServerTransport.create("localhost", 7000))
        .subscribe();

    RSocket socket =
        RSocketConnector.connectWith(TcpClientTransport.create("localhost", 7000)).block();

    socket
        .requestChannel(
            Flux.interval(Duration.ofMillis(1000)).map(i -> DefaultPayload.create("Hello")))
        .map(Payload::getDataUtf8)
        .doOnNext(logger::debug)
        .take(10)
        .doFinally(signalType -> socket.dispose())
        .then()
        .block();
  }
 
Example #13
Source File: HelloWorldClient.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

    RSocket rsocket =
        new RSocket() {
          boolean fail = true;

          @Override
          public Mono<Payload> requestResponse(Payload p) {
            if (fail) {
              fail = false;
              return Mono.error(new Throwable("Simulated error"));
            } else {
              return Mono.just(p);
            }
          }
        };

    RSocketServer.create(SocketAcceptor.with(rsocket))
        .bind(TcpServerTransport.create("localhost", 7000))
        .subscribe();

    RSocket socket =
        RSocketConnector.connectWith(TcpClientTransport.create("localhost", 7000)).block();

    for (int i = 0; i < 3; i++) {
      socket
          .requestResponse(DefaultPayload.create("Hello"))
          .map(Payload::getDataUtf8)
          .onErrorReturn("error")
          .doOnNext(logger::debug)
          .block();
    }

    socket.dispose();
  }
 
Example #14
Source File: RSocketClientExample.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

    RSocketServer.create(
            SocketAcceptor.forRequestResponse(
                p -> {
                  String data = p.getDataUtf8();
                  logger.info("Received request data {}", data);

                  Payload responsePayload = DefaultPayload.create("Echo: " + data);
                  p.release();

                  return Mono.just(responsePayload);
                }))
        .bind(TcpServerTransport.create("localhost", 7000))
        .delaySubscription(Duration.ofSeconds(5))
        .doOnNext(cc -> logger.info("Server started on the address : {}", cc.address()))
        .subscribe();

    RSocketClient rSocketClient =
        RSocketConnector.create()
            .reconnect(Retry.backoff(50, Duration.ofMillis(500)))
            .toRSocketClient(TcpClientTransport.create("localhost", 7000));

    rSocketClient
        .requestResponse(Mono.just(DefaultPayload.create("Test Request")))
        .doOnSubscribe(s -> logger.info("Executing Request"))
        .doOnNext(
            d -> {
              logger.info("Received response data {}", d.getDataUtf8());
              d.release();
            })
        .repeat(10)
        .blockLast();
  }
 
Example #15
Source File: InteractionsLoadTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
@SlowTest
public void channel() {
  CloseableChannel server =
      RSocketServer.create(SocketAcceptor.with(new EchoRSocket()))
          .bind(TcpServerTransport.create("localhost", 0))
          .block(Duration.ofSeconds(10));

  RSocket clientRSocket =
      RSocketConnector.connectWith(TcpClientTransport.create(server.address()))
          .block(Duration.ofSeconds(10));

  int concurrency = 16;
  Flux.range(1, concurrency)
      .flatMap(
          v ->
              clientRSocket
                  .requestChannel(
                      input().onBackpressureDrop().map(iv -> DefaultPayload.create("foo")))
                  .limitRate(10000),
          concurrency)
      .timeout(Duration.ofSeconds(5))
      .doOnNext(
          p -> {
            String data = p.getDataUtf8();
            if (!data.equals("bar")) {
              throw new IllegalStateException("Channel Client Bad message: " + data);
            }
          })
      .window(Duration.ofSeconds(1))
      .flatMap(Flux::count)
      .doOnNext(d -> System.out.println("Got: " + d))
      .take(Duration.ofMinutes(1))
      .doOnTerminate(server::dispose)
      .subscribe();

  server.onClose().block();
}
 
Example #16
Source File: TestingStreaming.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = ApplicationErrorException.class)
public void testRangeButThrowException() {
  Closeable server = null;
  try {
    server =
        RSocketServer.create(
                SocketAcceptor.forRequestStream(
                    payload ->
                        Flux.range(1, 1000)
                            .doOnNext(
                                i -> {
                                  if (i > 3) {
                                    throw new RuntimeException("BOOM!");
                                  }
                                })
                            .map(l -> DefaultPayload.create("l -> " + l))
                            .cast(Payload.class)))
            .bind(serverTransport)
            .block();

    Flux.range(1, 6).flatMap(i -> consumer("connection number -> " + i)).blockLast();
    System.out.println("here");

  } finally {
    server.dispose();
  }
}
 
Example #17
Source File: RSocketAutoConfiguration.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Bean
public RSocketRequesterSupport rsocketRequesterSupport(@Autowired RSocketProperties properties,
                                                       @Autowired Environment environment,
                                                       @Autowired SocketAcceptor socketAcceptor,
                                                       @Autowired ObjectProvider<RSocketRequesterSupportCustomizer> customizers) {
    RSocketRequesterSupportBuilderImpl builder = new RSocketRequesterSupportBuilderImpl(properties, new EnvironmentProperties(environment), socketAcceptor);
    customizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
    return builder.build();
}
 
Example #18
Source File: RSocketWebServerFactoryAutoConfiguration.java    From spring-boot-rsocket with Apache License 2.0 5 votes vote down vote up
@Bean
public RSocketNettyReactiveWebServerFactory rSocketNettyReactiveWebServerFactory(
		ReactorResourceFactory resourceFactory,
		RSocketServerProperties rSocketServerProperties,
		SocketAcceptor socketAcceptor,
		Collection<RSocketReceiverCustomizer> customizers
) {
	RSocketNettyReactiveWebServerFactory serverFactory = new RSocketNettyReactiveWebServerFactory();
	serverFactory.setResourceFactory(resourceFactory);
	serverFactory.setSocketAcceptor(socketAcceptor);
	serverFactory.setPath(rSocketServerProperties.getPath());
	serverFactory.setRSocketCustomizers(customizers);
	return serverFactory;
}
 
Example #19
Source File: GatewayRSocketAutoConfigurationTests.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
@Bean
RSocketServerFactory rSocketServerFactory() {
	RSocketServerFactory serverFactory = mock(RSocketServerFactory.class);
	when(serverFactory.create(any(SocketAcceptor.class)))
			.thenReturn(mock(RSocketServer.class));
	return serverFactory;
}
 
Example #20
Source File: RSocketRequesterSupportImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public RSocketRequesterSupportImpl(RSocketProperties properties, Properties env,
                                   SocketAcceptor socketAcceptor) {
    this.properties = properties;
    this.env = env;
    this.appName = env.getProperty("spring.application.name", env.getProperty("application.name"));
    this.jwtToken = env.getProperty("rsocket.jwt-token", "").toCharArray();
    this.socketAcceptor = socketAcceptor;
}
 
Example #21
Source File: ClusterJoinListener.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
/**
 * For incoming requests to this broker node, the RSocketRequester needs an acceptor
 * that is able to hand out GatewayRSocket instances. So here is a very simple one
 * that just constructs tags metadata and creates a GatewayRSocket.
 * @return A SocketAcceptor that creates a GatewayRSocket.
 */
SocketAcceptor brokerSocketAcceptor() {
	return (setup, sendingSocket) -> {
		TagsMetadata.Builder builder = TagsMetadata.builder();
		// TODO: other tags.
		builder.serviceName(properties.getServiceName())
				.routeId(properties.getRouteId().toString());
		return Mono.just(gatewayRSocketFactory.create(builder.build()));
	};
}
 
Example #22
Source File: RSocketServerToClientITest.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This private method is used to establish a connection to our fake RSocket server.
 * It also controls the state of our test controller. This method is reusable by many tests.
 *
 * @param connectionRoute
 */
private void connectAndRunTest(String connectionRoute) {

    ServerController controller = context.getBean(ServerController.class);
    RSocketStrategies strategies = context.getBean(RSocketStrategies.class);
    RSocketRequester requester = null;

    try {
        controller.reset();

        // Add our ClientHandler as a responder
        SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());

        // Create an RSocket requester that includes our responder
        requester = RSocketRequester.builder()
                .setupRoute(connectionRoute)
                .setupData(clientId)
                .rsocketStrategies(strategies)
                .rsocketConnector(connector -> connector.acceptor(responder))
                .connectTcp("localhost", server.address().getPort())
                .block();

        // Give the test time to run, wait for the server's call.
        controller.await(Duration.ofSeconds(10));
    } finally {
        if (requester != null) {
            requester.rsocket().dispose();
        }
    }
}
 
Example #23
Source File: RSocketListenerAutoConfiguration.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Bean
public RSocketListenerCustomizer defaultRSocketListenerCustomizer(@Autowired SocketAcceptor socketAcceptor, @Autowired RSocketProperties properties) {
    return builder -> {
        builder.acceptor(socketAcceptor);
        builder.listen(properties.getSchema(), properties.getPort());
    };
}
 
Example #24
Source File: RSocketNettyReactiveWebServerFactory.java    From spring-boot-rsocket with Apache License 2.0 4 votes vote down vote up
/**
 * Add {@link SocketAcceptor}s that should handle incoming RSocket clients.
 * @param socketAcceptor the socket acceptor
 */
public void setSocketAcceptor(SocketAcceptor socketAcceptor) {
	Assert.notNull(socketAcceptor, "SocketAcceptor must not be null");
	this.socketAcceptor = socketAcceptor;
}
 
Example #25
Source File: WebsocketPingPongIntegrationTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("provideServerTransport")
void webSocketPingPong(ServerTransport<Closeable> serverTransport) {
  server =
      RSocketServer.create(SocketAcceptor.forRequestResponse(Mono::just))
          .bind(serverTransport)
          .block();

  String expectedData = "data";
  String expectedPing = "ping";

  PingSender pingSender = new PingSender();

  HttpClient httpClient =
      HttpClient.create()
          .tcpConfiguration(
              tcpClient ->
                  tcpClient
                      .doOnConnected(b -> b.addHandlerLast(pingSender))
                      .host(host)
                      .port(port));

  RSocket rSocket =
      RSocketConnector.connectWith(WebsocketClientTransport.create(httpClient, "/")).block();

  rSocket
      .requestResponse(DefaultPayload.create(expectedData))
      .delaySubscription(pingSender.sendPing(expectedPing))
      .as(StepVerifier::create)
      .expectNextMatches(p -> expectedData.equals(p.getDataUtf8()))
      .expectComplete()
      .verify(Duration.ofSeconds(5));

  pingSender
      .receivePong()
      .as(StepVerifier::create)
      .expectNextMatches(expectedPing::equals)
      .expectComplete()
      .verify(Duration.ofSeconds(5));

  rSocket
      .requestResponse(DefaultPayload.create(expectedData))
      .delaySubscription(pingSender.sendPong())
      .as(StepVerifier::create)
      .expectNextMatches(p -> expectedData.equals(p.getDataUtf8()))
      .expectComplete()
      .verify(Duration.ofSeconds(5));
}
 
Example #26
Source File: RSocketFactoryNettyTransportFragmentationTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
private SocketAcceptor mockAcceptor() {
  SocketAcceptor mock = Mockito.mock(SocketAcceptor.class);
  Mockito.when(mock.accept(Mockito.any(), Mockito.any()))
      .thenReturn(Mono.just(Mockito.mock(RSocket.class)));
  return mock;
}
 
Example #27
Source File: InitializingInterceptorRegistry.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public SocketAcceptor initSocketAcceptor(SocketAcceptor acceptor) {
  for (SocketAcceptorInterceptor interceptor : getSocketAcceptorInterceptors()) {
    acceptor = interceptor.apply(acceptor);
  }
  return acceptor;
}
 
Example #28
Source File: RSocketRequesterSupportImpl.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
@Override
public SocketAcceptor socketAcceptor() {
    return this.socketAcceptor;
}
 
Example #29
Source File: RSocketRequesterSupportBuilderImpl.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
public RSocketRequesterSupportBuilderImpl(RSocketProperties properties,
                                          Properties env,
                                          SocketAcceptor socketAcceptor) {
    this.requesterSupport = new RSocketRequesterSupportImpl(properties, env, socketAcceptor);
}
 
Example #30
Source File: RSocketRequesterBySubBroker.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
@Override
public SocketAcceptor socketAcceptor() {
    return (connectionSetupPayload, rsocket) -> Mono.just(new UpstreamForwardRSocket(this.serviceRoutingSelector, rsocket, this.filterChain, this.handlerRegistry, this.upstreamBrokerCluster));
}