io.reactivex.netty.RxNetty Java Examples

The following examples show how to use io.reactivex.netty.RxNetty. 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: StartMockService.java    From WSPerfLab with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    int port = 8989;
    if (args.length > 0) {
        port = Integer.parseInt(args[0]);
    }
    System.out.println("Starting mock service on port " + port + "...");
    startMonitoring();
    RxNetty.<ByteBuf, ByteBuf>newHttpServerBuilder(port, (request, response) -> {
        try {
            long startTime = System.currentTimeMillis();
            counter.increment(CounterEvent.REQUESTS);
            return handleRequest(request, response)
                    .doOnCompleted(() ->  {
                        counter.increment(CounterEvent.SUCCESS);
                        latency.addValue((int)(System.currentTimeMillis() - startTime));
                    })
                    .doOnError(t -> counter.increment(CounterEvent.NETTY_ERROR));
        } catch (Throwable e) {
            System.err.println("Server => Error [" + request.getPath() + "] => " + e);
            response.setStatus(HttpResponseStatus.BAD_REQUEST);
            counter.increment(CounterEvent.HTTP_ERROR);
            return response.writeStringAndFlush("Error 500: Bad Request\n" + e.getMessage() + '\n');
        }
    }).build().startAndWait();
}
 
Example #2
Source File: HealthCheckHandler.java    From Prana with Apache License 2.0 6 votes vote down vote up
private Observable<HttpClientResponse<ByteBuf>> getResponse(String externalHealthCheckURL) {
    String host = "localhost";
    int port = DEFAULT_APPLICATION_PORT;
    String path = "/healthcheck";
    try {
        URL url = new URL(externalHealthCheckURL);
        host = url.getHost();
        port = url.getPort();
        path = url.getPath();
    } catch (MalformedURLException e) {
        //continue
    }
    Integer timeout = DynamicProperty.getInstance("prana.host.healthcheck.timeout").getInteger(DEFAULT_CONNECTION_TIMEOUT);
    HttpClient<ByteBuf, ByteBuf> httpClient = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder(host, port)
            .pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpClientConfigurator())
            .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout)
            .build();
    return httpClient.submit(HttpClientRequest.createGet(path));

}
 
Example #3
Source File: ClientServer.java    From ReactiveLab with Apache License 2.0 6 votes vote down vote up
public static HttpServer<ByteBuf, ByteBuf> startServer(int port) {

        /**
         * Creates an HTTP server which returns "Hello World!" responses.
         */
        return RxNetty.createHttpServer(port,
                                        /*
                                         * HTTP Request handler for RxNetty where you control what you write as the
                                         * response for each and every request the server receives.
                                         */
                                        (request, response) -> {
                                            /**
                                             * In a real server, you would be writing different responses based on the
                                             * URI of the request.
                                             * This example just returns a "Hello World!!" string unconditionally.
                                             */
                                            return response.writeStringAndFlush("Hello World!!");
                                        })
                      .start();
    }
 
Example #4
Source File: LoadBalancingTcpClient.java    From ribbon with Apache License 2.0 6 votes vote down vote up
@Override
protected RxClient<I, O> createRxClient(Server server) {
    ClientBuilder<I, O> builder = RxNetty.newTcpClientBuilder(server.getHost(), server.getPort());
    if (pipelineConfigurator != null) {
        builder.pipelineConfigurator(pipelineConfigurator);
    }
    Integer connectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT);
    builder.channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    if (isPoolEnabled()) {
        builder.withConnectionPoolLimitStrategy(poolStrategy)
        .withIdleConnectionsTimeoutMillis(idleConnectionEvictionMills)
        .withPoolIdleCleanupScheduler(poolCleanerScheduler);
    } else {
        builder.withNoConnectionPooling();
    }
    RxClient<I, O> client = builder.build();
    return client;
}
 
Example #5
Source File: HelloUdpServer.java    From ribbon with Apache License 2.0 6 votes vote down vote up
public UdpServer<DatagramPacket, DatagramPacket> createServer() {
    UdpServer<DatagramPacket, DatagramPacket> server = RxNetty.createUdpServer(port, new ConnectionHandler<DatagramPacket, DatagramPacket>() {
        @Override
        public Observable<Void> handle(final ObservableConnection<DatagramPacket, DatagramPacket> newConnection) {
            return newConnection.getInput().flatMap(new Func1<DatagramPacket, Observable<Void>>() {
                @Override
                public Observable<Void> call(final DatagramPacket received) {
                    return Observable.interval(delay, TimeUnit.MILLISECONDS).take(1).flatMap(new Func1<Long, Observable<Void>>() {
                        @Override
                        public Observable<Void> call(Long aLong) {
                            InetSocketAddress sender = received.sender();
                            System.out.println("Received datagram. Sender: " + sender);
                            ByteBuf data = newConnection.getChannel().alloc().buffer(WELCOME_MSG_BYTES.length);
                            data.writeBytes(WELCOME_MSG_BYTES);
                            return newConnection.writeAndFlush(new DatagramPacket(data, sender));
                        }
                    });
                }
            });
        }
    });
    System.out.println("UDP hello server started at port: " + port);
    return server;
}
 
Example #6
Source File: RxMovieServer.java    From ribbon with Apache License 2.0 6 votes vote down vote up
public HttpServer<ByteBuf, ByteBuf> createServer() {
    HttpServer<ByteBuf, ByteBuf> server = RxNetty.newHttpServerBuilder(port, new RequestHandler<ByteBuf, ByteBuf>() {
        @Override
        public Observable<Void> handle(HttpServerRequest<ByteBuf> request, final HttpServerResponse<ByteBuf> response) {
            if (request.getPath().contains("/users")) {
                if (request.getHttpMethod().equals(HttpMethod.GET)) {
                    return handleRecommendationsByUserId(request, response);
                } else {
                    return handleUpdateRecommendationsForUser(request, response);
                }
            }
            if (request.getPath().contains("/recommendations")) {
                return handleRecommendationsBy(request, response);
            }
            if (request.getPath().contains("/movies")) {
                return handleRegisterMovie(request, response);
            }
            response.setStatus(HttpResponseStatus.NOT_FOUND);
            return response.close();
        }
    }).pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpServerConfigurator()).enableWireLogging(LogLevel.ERROR).build();

    System.out.println("RxMovie server started...");
    return server;
}
 
Example #7
Source File: MesosServerSimulationTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@NotNull
private static HttpClientResponse<ByteBuf> sendCall(final URI uri, final String call) {
    final HttpClient<ByteBuf, ByteBuf> httpClient = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder(uri.getHost(), uri.getPort())
        .pipelineConfigurator(new HttpClientPipelineConfigurator<>())
        .build();

    final byte[] data = call.getBytes(StandardCharsets.UTF_8);
    final HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost(uri.getPath())
        .withHeader("Content-Type", StringMessageCodec.UTF8_STRING.mediaType())
        .withHeader("Accept", StringMessageCodec.UTF8_STRING.mediaType())
        .withContent(data);

    return httpClient.submit(request)
        .toBlocking()
        .last();
}
 
Example #8
Source File: MesosServerSimulationTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void server400_emptyBody() throws Exception {
    final URI uri = URI.create(String.format("http://localhost:%d/api/v1/scheduler", serverPort));
    final HttpClient<ByteBuf, ByteBuf> httpClient = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder(uri.getHost(), uri.getPort())
        .pipelineConfigurator(new HttpClientPipelineConfigurator<>())
        .build();

    final HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost(uri.getPath())
        .withHeader("Content-Type", StringMessageCodec.UTF8_STRING.mediaType())
        .withHeader("Accept", StringMessageCodec.UTF8_STRING.mediaType())
        .withContent(new byte[]{});

    final HttpClientResponse<ByteBuf> response = httpClient.submit(request)
        .toBlocking()
        .last();

    assertThat(response.getStatus()).isEqualTo(HttpResponseStatus.BAD_REQUEST);
    final HttpResponseHeaders headers = response.getHeaders();
    assertThat(headers.getHeader("Accept")).isEqualTo(StringMessageCodec.UTF8_STRING.mediaType());

    assertThat(mesosServerSimulation.getCallsReceived()).hasSize(0);
}
 
Example #9
Source File: MesosServerSimulationTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void server400_invalidContentType() throws Exception {
    final URI uri = URI.create(String.format("http://localhost:%d/api/v1/scheduler", serverPort));
    final HttpClient<ByteBuf, ByteBuf> httpClient = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder(uri.getHost(), uri.getPort())
        .pipelineConfigurator(new HttpClientPipelineConfigurator<>())
        .build();

    final byte[] data = StringMessageCodec.UTF8_STRING.encode("decline");
    final HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost(uri.getPath())
        .withHeader("Content-Type", "application/octet-stream")
        .withHeader("Accept", "application/octet-stream")
        .withContent(data);

    final HttpClientResponse<ByteBuf> response = httpClient.submit(request)
        .toBlocking()
        .last();

    assertThat(response.getStatus()).isEqualTo(HttpResponseStatus.BAD_REQUEST);
    final HttpResponseHeaders headers = response.getHeaders();
    assertThat(headers.getHeader("Accept")).isEqualTo(StringMessageCodec.UTF8_STRING.mediaType());

    assertThat(mesosServerSimulation.getCallsReceived()).hasSize(0);
}
 
Example #10
Source File: MesosServerSimulationTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void server400_nonPost() throws Exception {
    final URI uri = URI.create(String.format("http://localhost:%d/api/v1/scheduler", serverPort));
    final HttpClient<ByteBuf, ByteBuf> httpClient = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder(uri.getHost(), uri.getPort())
        .pipelineConfigurator(new HttpClientPipelineConfigurator<>())
        .build();

    final HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(uri.getPath())
        .withHeader("Accept", StringMessageCodec.UTF8_STRING.mediaType());

    final HttpClientResponse<ByteBuf> response = httpClient.submit(request)
        .toBlocking()
        .last();

    assertThat(response.getStatus()).isEqualTo(HttpResponseStatus.BAD_REQUEST);
    final HttpResponseHeaders headers = response.getHeaders();
    assertThat(headers.getHeader("Accept")).isEqualTo(StringMessageCodec.UTF8_STRING.mediaType());

    assertThat(mesosServerSimulation.getCallsReceived()).hasSize(0);
}
 
Example #11
Source File: WebSocketsRxServerProvider.java    From karyon with Apache License 2.0 6 votes vote down vote up
@Inject
@SuppressWarnings("unchecked")
public void setInjector(Injector injector) {
    KaryonWebSocketsModule.WebSocketsServerConfig config = (KaryonWebSocketsModule.WebSocketsServerConfig) injector.getInstance(serverConfigKey);

    ConnectionHandler<I, O> connectionHandler = injector.getInstance(connectionHandlerKey);

    WebSocketServerBuilder<I, O> builder = RxNetty.newWebSocketServerBuilder(config.getPort(), connectionHandler)
            .withMessageAggregator(config.isMessageAggregator());

    if (injector.getExistingBinding(pipelineConfiguratorKey) != null) {
        builder.appendPipelineConfigurator(injector.getInstance(pipelineConfiguratorKey));
    }

    if (injector.getExistingBinding(metricEventsListenerFactoryKey) != null) {
        builder.withMetricEventsListenerFactory(injector.getInstance(metricEventsListenerFactoryKey));
    }

    server = builder.build().start();
    logger.info("Starting WebSockets server {} on port {}...", nameAnnotation.value(), server.getServerPort());
}
 
Example #12
Source File: MesosClientIntegrationTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void testStreamDoesNotRunWhenSubscribeFails_mismatchContentType() throws Throwable {
    final RequestHandler<ByteBuf, ByteBuf> handler = (request, response) -> {
        response.setStatus(HttpResponseStatus.OK);
        response.getHeaders().setHeader("Content-Type", "application/json");
        return response.close();
    };
    final HttpServer<ByteBuf, ByteBuf> server = RxNetty.createHttpServer(0, handler);
    server.start();
    final URI uri = URI.create(String.format("http://localhost:%d/api/v1/scheduler", server.getServerPort()));
    final MesosClient<String, String> client = createClient(uri);

    try {
        client.openStream().await();
        fail("Expect an exception to be propagated up because of content type mismatch");
    } catch (MesosException e) {
        // expected
        final MesosClientErrorContext ctx = e.getContext();
        assertThat(ctx.getStatusCode()).isEqualTo(200);
        assertThat(ctx.getMessage()).isEqualTo("Response had Content-Type \"application/json\" expected \"text/plain;charset=utf-8\"");
    } finally {
        server.shutdown();
    }
}
 
Example #13
Source File: MesosClientIntegrationTest.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
@Test
public void testStreamDoesNotRunWhenSubscribeFails_mesos5xxResponse() throws Throwable {
    final RequestHandler<ByteBuf, ByteBuf> handler = (request, response) -> {
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        return response.close();
    };
    final HttpServer<ByteBuf, ByteBuf> server = RxNetty.createHttpServer(0, handler);
    server.start();
    final URI uri = URI.create(String.format("http://localhost:%d/api/v1/scheduler", server.getServerPort()));
    final MesosClient<String, String> client = createClient(uri);

    try {
        client.openStream().await();
        fail("Expect an exception to be propagated up because subscribe will 500");
    } catch (Mesos5xxException e) {
        // expected
        final MesosClientErrorContext ctx = e.getContext();
        assertThat(ctx.getStatusCode()).isEqualTo(500);
    } finally {
        server.shutdown();
    }
}
 
Example #14
Source File: KaryonTcpModuleTest.java    From karyon with Apache License 2.0 6 votes vote down vote up
@Test
public void testGovernatedTcpServer() throws Exception {
    String message = RxNetty.createTcpClient("localhost", server.getServerPort()).connect()
            .flatMap(new Func1<ObservableConnection<ByteBuf, ByteBuf>, Observable<String>>() {
                @Override
                public Observable<String> call(ObservableConnection<ByteBuf, ByteBuf> connection) {
                    return connection.getInput().map(new Func1<ByteBuf, String>() {
                        @Override
                        public String call(ByteBuf byteBuf) {
                            return byteBuf.toString(Charset.defaultCharset());
                        }
                    });
                }
            }).single().toBlocking().toFuture().get(60, TimeUnit.SECONDS);

    assertEquals("Invalid message received from server", SERVER_MESSAGE, message);
}
 
Example #15
Source File: MesosClient.java    From mesos-rxjava with Apache License 2.0 6 votes vote down vote up
/**
 * The Mesos HTTP Scheduler API will send a redirect to a client if it is not the leader. The client that is
 * constructed during {@link #openStream} is bound to a specific host and port, due to this behavior
 * we "probe" Mesos to try and find out where it's "master" is before we configure the client.
 *
 * This method will attempt to send a simple GET to {@code mesosUri}, however instead of going to the path
 * specified, it will go to {@code /redirect} and construct a uri relative to mesosUri using the host and port
 * returned in the Location header of the response.
 */
@NotNull
private static URI resolveMesosUri(final @NotNull URI mesosUri) {
    final String redirectUri = createRedirectUri(mesosUri);
    LOGGER.info("Probing Mesos server at {}", redirectUri);

    // When sending an individual request (rather than creating a client) RxNetty WILL follow redirects,
    // so here we tell it not to do that for this request by creating the config object below.
    final HttpClient.HttpClientConfig config =
        HttpClient.HttpClientConfig.Builder.fromDefaultConfig()
            .setFollowRedirect(false)
            .build();
    final HttpClientResponse<ByteBuf> redirectResponse =
        RxNetty.createHttpRequest(HttpClientRequest.createGet(redirectUri), config)
            .toBlocking()
            .first();

    return getUriFromRedirectResponse(mesosUri, redirectResponse);
}
 
Example #16
Source File: TcpRxServerProvider.java    From karyon with Apache License 2.0 6 votes vote down vote up
@Inject
public void setInjector(Injector injector) {
    ServerConfig config = injector.getInstance(serverConfigKey);

    ConnectionHandler<I, O> connectionHandler = injector.getInstance(connectionHandlerKey);

    ServerBuilder<I, O> builder = RxNetty.newTcpServerBuilder(config.getPort(), connectionHandler);

    if (injector.getExistingBinding(pipelineConfiguratorKey) != null) {
        builder.appendPipelineConfigurator(injector.getInstance(pipelineConfiguratorKey));
    }

    if (injector.getExistingBinding(metricEventsListenerFactoryKey) != null) {
        builder.withMetricEventsListenerFactory(injector.getInstance(metricEventsListenerFactoryKey));
    }

    server = builder.build().start();
    logger.info("Starting server {} on port {}...", nameAnnotation.value(), server.getServerPort());
}
 
Example #17
Source File: KaryonWebSocketsModuleTest.java    From karyon with Apache License 2.0 6 votes vote down vote up
@Test
public void testGovernatedTcpServer() throws Exception {
    String message = RxNetty.<TextWebSocketFrame, TextWebSocketFrame>newWebSocketClientBuilder("localhost", server.getServerPort())
            .build()
            .connect()
            .flatMap(new Func1<ObservableConnection<TextWebSocketFrame, TextWebSocketFrame>, Observable<String>>() {
                @Override
                public Observable<String> call(ObservableConnection<TextWebSocketFrame, TextWebSocketFrame> connection) {
                    return connection.getInput().map(new Func1<TextWebSocketFrame, String>() {
                        @Override
                        public String call(TextWebSocketFrame frame) {
                            return frame.text();
                        }
                    });
                }
            }).single().toBlocking().toFuture().get(60, TimeUnit.SECONDS);

    assertEquals("Invalid message received from server", SERVER_MESSAGE, message);
}
 
Example #18
Source File: HelloUdpServerExternalResource.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public void start() {
    int port;
    try {
        port = choosePort();
    } catch (SocketException e) {
        throw new RuntimeException("Error choosing point", e);
    }
    
    server = RxNetty.createUdpServer(port, new ConnectionHandler<DatagramPacket, DatagramPacket>() {
        @Override
        public Observable<Void> handle(final ObservableConnection<DatagramPacket, DatagramPacket> newConnection) {
            return newConnection.getInput().flatMap(new Func1<DatagramPacket, Observable<Void>>() {
                @Override
                public Observable<Void> call(final DatagramPacket received) {
                    return Observable.interval(timeout, TimeUnit.MILLISECONDS).take(1).flatMap(new Func1<Long, Observable<Void>>() {
                        @Override
                        public Observable<Void> call(Long aLong) {
                            InetSocketAddress sender = received.sender();
                            LOG.info("Received datagram. Sender: " + sender);
                            ByteBuf data = newConnection.getChannel().alloc().buffer(WELCOME_MSG_BYTES.length);
                            data.writeBytes(WELCOME_MSG_BYTES);
                            return newConnection.writeAndFlush(new DatagramPacket(data, sender));
                        }
                    });
                }
            });
        }
    });
    
    server.start();
    
    LOG.info("UDP hello server started at port: " + port);
}
 
Example #19
Source File: StartGatewayServer.java    From ReactiveLab with Apache License 2.0 5 votes vote down vote up
private static void startHystrixMetricsStream() {
    HystrixMetricsStreamHandler<ByteBuf, ByteBuf> hystrixMetricsStreamHandler = new HystrixMetricsStreamHandler<>("/", 1000);
    RxNetty.createHttpServer(9999, (request, response) -> {
        System.out.println("Server => Start Hystrix Stream at http://localhost:9999");
        return hystrixMetricsStreamHandler.handle(request, response);
    }).start();
}
 
Example #20
Source File: TestRouteBasic.java    From ReactiveLab with Apache License 2.0 5 votes vote down vote up
private static Observable<BackendResponse> getDataFromBackend(String url) {
    return RxNetty.createHttpClient("localhost", 9100)
            .submit(HttpClientRequest.createGet(url))
            .flatMap((HttpClientResponse<ByteBuf> r) -> {
                Observable<BackendResponse> bytesToJson = r.getContent().map(b -> {
                    return BackendResponse.fromJson(new ByteBufInputStream(b));
                });
                return bytesToJson;
            });
}
 
Example #21
Source File: HealthCheckHandlerTest.java    From Prana with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    super.setUp();
    externalServer = RxNetty.newHttpServerBuilder(0, new ExternalServerHandler())
            .pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpServerConfigurator()).build();
    externalServer.start();
    this.externalServerPort = externalServer.getServerPort();
}
 
Example #22
Source File: AbstractIntegrationTest.java    From Prana with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    server = RxNetty.newHttpServerBuilder(0, getHandler())
            .pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpServerConfigurator()).build();
    server.start();
    client = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder("localhost", server.getServerPort())
            .pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpClientConfigurator())
            .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000)
            .build();

}
 
Example #23
Source File: WebSocketEchoServer.java    From karyon with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) {
    RxServer<TextWebSocketFrame, TextWebSocketFrame> webSocketServer = RxNetty.newWebSocketServerBuilder(
            8888,
            new ConnectionHandler<TextWebSocketFrame, TextWebSocketFrame>() {
                @Override
                public Observable<Void> handle(final ObservableConnection<TextWebSocketFrame, TextWebSocketFrame> connection) {
                    return connection.getInput().flatMap(new Func1<WebSocketFrame, Observable<Void>>() {
                        @Override
                        public Observable<Void> call(WebSocketFrame wsFrame) {
                            TextWebSocketFrame textFrame = (TextWebSocketFrame) wsFrame;
                            System.out.println("Got message: " + textFrame.text());
                            return connection.writeAndFlush(new TextWebSocketFrame(textFrame.text().toUpperCase()));
                        }
                    });
                }
            }
    ).build();
    Karyon.forWebSocketServer(
            webSocketServer,
            new KaryonBootstrapModule(),
            new ArchaiusBootstrapModule("websocket-echo-server"),
            // KaryonEurekaModule.asBootstrapModule(), /* Uncomment if you need eureka */
            Karyon.toBootstrapModule(KaryonWebAdminModule.class),
            ShutdownModule.asBootstrapModule(),
            KaryonServoModule.asBootstrapModule())
            .startAndWaitTillShutdown();
}
 
Example #24
Source File: LoadBalancingUdpClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Override
protected RxClient<I, O> createRxClient(Server server) {
    UdpClientBuilder<I, O> builder = RxNetty.newUdpClientBuilder(server.getHost(), server.getPort());
    if (pipelineConfigurator != null) {
        builder.pipelineConfigurator(pipelineConfigurator);
    }
    return builder.build();
}
 
Example #25
Source File: KaryonHttpModuleTest.java    From karyon with Apache License 2.0 5 votes vote down vote up
private HttpResponseStatus sendRequest(String path, RxServer server) throws Exception {
    return (HttpResponseStatus) RxNetty.createHttpGet("http://localhost:" + server.getServerPort() + path)
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<?>>() {
                @Override
                public Observable<HttpResponseStatus> call(HttpClientResponse<ByteBuf> httpClientResponse) {
                    return Observable.just(httpClientResponse.getStatus());
                }
            }).single().toBlocking().toFuture().get(60, TimeUnit.SECONDS);
}
 
Example #26
Source File: RxMovieServerTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testMovieRegistration() {
    String movieFormatted = ORANGE_IS_THE_NEW_BLACK.toString();

    HttpResponseStatus statusCode = RxNetty.createHttpPost(baseURL + "/movies", Observable.just(movieFormatted), new StringTransformer())
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<HttpResponseStatus>>() {
                @Override
                public Observable<HttpResponseStatus> call(HttpClientResponse<ByteBuf> httpClientResponse) {
                    return Observable.just(httpClientResponse.getStatus());
                }
            }).toBlocking().first();

    assertEquals(HttpResponseStatus.CREATED, statusCode);
    assertEquals(ORANGE_IS_THE_NEW_BLACK, movieServer.movies.get(ORANGE_IS_THE_NEW_BLACK.getId()));
}
 
Example #27
Source File: RxMovieServerTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpateRecommendations() {
    movieServer.movies.put(ORANGE_IS_THE_NEW_BLACK.getId(), ORANGE_IS_THE_NEW_BLACK);
    HttpResponseStatus statusCode = RxNetty.createHttpPost(baseURL + "/users/" + TEST_USER_ID + "/recommendations", Observable.just(ORANGE_IS_THE_NEW_BLACK.getId()), new StringTransformer())
            .flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<HttpResponseStatus>>() {
                @Override
                public Observable<HttpResponseStatus> call(HttpClientResponse<ByteBuf> httpClientResponse) {
                    return Observable.just(httpClientResponse.getStatus());
                }
            }).toBlocking().first();

    assertEquals(HttpResponseStatus.OK, statusCode);
    assertTrue(movieServer.userRecommendations.get(TEST_USER_ID).contains(ORANGE_IS_THE_NEW_BLACK.getId()));
}
 
Example #28
Source File: TcpSocketProxyTest.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionTerminatedOnClose() throws Exception {
    final TcpSocketProxy proxy = new TcpSocketProxy(
        new InetSocketAddress("localhost", 0),
        new InetSocketAddress("localhost", server.getServerPort())
    );
    proxy.start();

    final int listenPort = proxy.getListenPort();
    final HttpClient<ByteBuf, ByteBuf> client = RxNetty.createHttpClient("localhost", listenPort);

    final String first = client.submit(HttpClientRequest.createGet("/"))
        .flatMap(AbstractHttpContentHolder::getContent)
        .map(bb -> bb.toString(StandardCharsets.UTF_8))
        .toBlocking()
        .first();

    assertThat(first).isEqualTo("Hello World");
    LOGGER.info("first request done");
    proxy.shutdown();
    if (proxy.isShutdown()) {
        proxy.close();
    } else {
        fail("proxy should have been shutdown");
    }

    try {
        final URI uri = URI.create(String.format("http://localhost:%d/", listenPort));
        uri.toURL().getContent();
        fail("Shouldn't have been able to get content");
    } catch (IOException e) {
        // expected
    }
}
 
Example #29
Source File: MesosClientIntegrationTest.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamDoesNotRunWhenSubscribeFails_mesos4xxResponse() throws Throwable {
    final String errorMessage = "Error message that should come from the server";
    final RequestHandler<ByteBuf, ByteBuf> handler = (request, response) -> {
        response.setStatus(HttpResponseStatus.BAD_REQUEST);
        final byte[] msgBytes = errorMessage.getBytes(StandardCharsets.UTF_8);
        response.getHeaders().setHeader("Content-Length", msgBytes.length);
        response.getHeaders().setHeader("Content-Type", "text/plain;charset=utf-8");
        response.writeBytes(msgBytes);
        return response.close();
    };
    final HttpServer<ByteBuf, ByteBuf> server = RxNetty.createHttpServer(0, handler);
    server.start();
    final URI uri = URI.create(String.format("http://localhost:%d/api/v1/scheduler", server.getServerPort()));
    final MesosClient<String, String> client = createClient(uri);

    try {
        client.openStream().await();
        fail("Expect an exception to be propagated up because subscribe will 400");
    } catch (Mesos4xxException e) {
        // expected
        final MesosClientErrorContext ctx = e.getContext();
        assertThat(ctx.getStatusCode()).isEqualTo(400);
        assertThat(ctx.getMessage()).isEqualTo(errorMessage);
    } finally {
        server.shutdown();
    }
}
 
Example #30
Source File: MesosClient.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the subscribe call to Mesos and starts processing the stream of {@code Receive} events.
 * The {@code streamProcessor} function provided to the constructor will be applied to the stream of events
 * received from Mesos.
 * <p>
 * The stream processing will then process any {@link SinkOperation} that should be sent to Mesos.
 * @return The subscription representing the processing of the event stream. This subscription can then be used
 * to block the invoking thread using {@link AwaitableSubscription#await()} (For example to block a main thread
 * from exiting while events are being processed.)
 */
@NotNull
public AwaitableSubscription openStream() {

    final URI uri = resolveMesosUri(mesosUri);

    final HttpClient<ByteBuf, ByteBuf> httpClient = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder(uri.getHost(), getPort(uri))
        .withName(userAgent.getEntries().get(0).getName())
        .pipelineConfigurator(new HttpClientPipelineConfigurator<>())
        .build();

    final Observable<Receive> receives = createPost.call(subscribe)
        .flatMap(httpClient::submit)
        .subscribeOn(Rx.io())
        .flatMap(verifyResponseOk(subscribe, mesosStreamId, receiveCodec.mediaType()))
        .lift(new RecordIOOperator())
        .compose(backpressureTransformer)
        .observeOn(Rx.compute())
        /* Begin temporary back-pressure */
        .buffer(250, TimeUnit.MILLISECONDS)
        .flatMap(Observable::from)
        /* end temporary back-pressure */
        .map(receiveCodec::decode)
        ;

    final Observable<SinkOperation<Send>> sends = streamProcessor.apply(receives)
        .filter(Optional::isPresent)
        .map(Optional::get);

    final Subscriber<SinkOperation<Send>> subscriber = new SinkSubscriber<>(httpClient, createPost);
    final SubscriberDecorator<SinkOperation<Send>> decorator = new SubscriberDecorator<>(subscriber);
    final Subscription subscription = sends
        .subscribeOn(Rx.compute())
        .observeOn(Rx.compute())
        .subscribe(decorator);

    return new ObservableAwaitableSubscription(Observable.from(exec.submit(decorator)), subscription);
}