All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.reactivex.netty.RxNetty Maven / Gradle / Ivy

There is a newer version: 0.3.18
Show newest version
/*
 * Copyright 2014 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.reactivex.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.logging.LogLevel;
import io.reactivex.netty.channel.ConnectionHandler;
import io.reactivex.netty.channel.ContentTransformer;
import io.reactivex.netty.channel.RxEventLoopProvider;
import io.reactivex.netty.channel.SingleNioLoopProvider;
import io.reactivex.netty.client.ClientBuilder;
import io.reactivex.netty.client.RxClient;
import io.reactivex.netty.metrics.MetricEventsListenerFactory;
import io.reactivex.netty.pipeline.PipelineConfigurator;
import io.reactivex.netty.protocol.http.client.CompositeHttpClient;
import io.reactivex.netty.protocol.http.client.CompositeHttpClientBuilder;
import io.reactivex.netty.protocol.http.client.HttpClient;
import io.reactivex.netty.protocol.http.client.HttpClientBuilder;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import io.reactivex.netty.protocol.http.server.HttpServer;
import io.reactivex.netty.protocol.http.server.HttpServerBuilder;
import io.reactivex.netty.protocol.http.server.HttpServerRequest;
import io.reactivex.netty.protocol.http.server.HttpServerResponse;
import io.reactivex.netty.protocol.http.server.RequestHandler;
import io.reactivex.netty.protocol.http.websocket.WebSocketClientBuilder;
import io.reactivex.netty.protocol.http.websocket.WebSocketServerBuilder;
import io.reactivex.netty.protocol.udp.client.UdpClientBuilder;
import io.reactivex.netty.protocol.udp.server.UdpServer;
import io.reactivex.netty.protocol.udp.server.UdpServerBuilder;
import io.reactivex.netty.server.RxServer;
import io.reactivex.netty.server.ServerBuilder;
import rx.Observable;

import java.net.URI;
import java.net.URISyntaxException;

import static io.reactivex.netty.client.MaxConnectionsBasedStrategy.DEFAULT_MAX_CONNECTIONS;

public final class RxNetty {

    private static volatile RxEventLoopProvider rxEventLoopProvider =
            new SingleNioLoopProvider(1, Runtime.getRuntime().availableProcessors());

    private static final CompositeHttpClient globalClient =
            new CompositeHttpClientBuilder().withMaxConnections(DEFAULT_MAX_CONNECTIONS).build();
    private static MetricEventsListenerFactory metricEventsListenerFactory;

    private RxNetty() {
    }

    public static  UdpServerBuilder newUdpServerBuilder(int port, ConnectionHandler connectionHandler) {
        UdpServerBuilder builder = new UdpServerBuilder(port, connectionHandler)
                .enableWireLogging(LogLevel.DEBUG);
        if (null != metricEventsListenerFactory) {
            builder.withMetricEventsListenerFactory(metricEventsListenerFactory);
        }
        return builder;
    }

    public static  UdpClientBuilder newUdpClientBuilder(String host, int port) {
        UdpClientBuilder builder =
                new UdpClientBuilder(host, port).channel(NioDatagramChannel.class)
                                                      .enableWireLogging(LogLevel.DEBUG)
                                                      .eventloop(getRxEventLoopProvider().globalClientEventLoop());
        if (null != metricEventsListenerFactory) {
            builder.withMetricEventsListenerFactory(metricEventsListenerFactory);
        }
        return builder;
    }

    public static  UdpServer createUdpServer(final int port, PipelineConfigurator pipelineConfigurator,
                                                         ConnectionHandler connectionHandler) {
        return newUdpServerBuilder(port, connectionHandler).pipelineConfigurator(pipelineConfigurator).build();
    }

    public static  RxClient createUdpClient(String host, int port,
                                                        PipelineConfigurator pipelineConfigurator) {
        return RxNetty.newUdpClientBuilder(host, port).pipelineConfigurator(pipelineConfigurator).build();
    }

    public static UdpServer createUdpServer(final int port,
                                                                            ConnectionHandler connectionHandler) {
        return new UdpServerBuilder(port, connectionHandler).build();
    }

    public static RxClient createUdpClient(String host, int port) {
        return RxNetty.newUdpClientBuilder(host, port).build();
    }

    public static  ServerBuilder newTcpServerBuilder(int port, ConnectionHandler connectionHandler) {
        ServerBuilder builder =
                new ServerBuilder(port, connectionHandler).enableWireLogging(LogLevel.DEBUG);
        if (null != metricEventsListenerFactory) {
            builder.withMetricEventsListenerFactory(metricEventsListenerFactory);
        }
        return builder;
    }

    public static  RxServer createTcpServer(final int port, PipelineConfigurator pipelineConfigurator,
                                                        ConnectionHandler connectionHandler) {
        return newTcpServerBuilder(port, connectionHandler).pipelineConfigurator(pipelineConfigurator).build();
    }

    public static  ClientBuilder newTcpClientBuilder(String host, int port) {
        ClientBuilder builder = new ClientBuilder(host, port).enableWireLogging(LogLevel.DEBUG);
        if (null != metricEventsListenerFactory) {
            builder.withMetricEventsListenerFactory(metricEventsListenerFactory);
        }
        return builder;
    }

    public static  RxClient createTcpClient(String host, int port, PipelineConfigurator configurator) {
        return RxNetty.newTcpClientBuilder(host, port).pipelineConfigurator(configurator).build();
    }

    public static RxServer createTcpServer(final int port,
                                                             ConnectionHandler connectionHandler) {
        return new ServerBuilder(port, connectionHandler).build();
    }

    public static RxClient createTcpClient(String host, int port) {
        return RxNetty.newTcpClientBuilder(host, port).build();
    }

    public static  HttpServerBuilder newHttpServerBuilder(int port, RequestHandler requestHandler) {
        HttpServerBuilder builder =
                new HttpServerBuilder(port, requestHandler).enableWireLogging(LogLevel.DEBUG);
        if (null != metricEventsListenerFactory) {
            builder.withMetricEventsListenerFactory(metricEventsListenerFactory);
        }
        return builder;
    }

    public static  HttpClientBuilder newHttpClientBuilder(String host, int port) {
        HttpClientBuilder builder =
                new HttpClientBuilder(host, port).withMaxConnections(DEFAULT_MAX_CONNECTIONS)
                                                       .enableWireLogging(LogLevel.DEBUG);
        if (null != metricEventsListenerFactory) {
            builder.withMetricEventsListenerFactory(metricEventsListenerFactory);
        }
        return builder;
    }

    public static HttpServer createHttpServer(int port, RequestHandler requestHandler) {
        return newHttpServerBuilder(port, requestHandler).build();
    }

    public static HttpClient createHttpClient(String host, int port) {
        return RxNetty.newHttpClientBuilder(host, port).build();
    }

    public static  HttpServer createHttpServer(int port,
                                                           RequestHandler requestHandler,
                                                           PipelineConfigurator, HttpServerResponse> configurator) {
        return newHttpServerBuilder(port, requestHandler).pipelineConfigurator(configurator).build();
    }

    public static  HttpClient createHttpClient(String host, int port,
                                                           PipelineConfigurator,
                                                           HttpClientRequest> configurator) {
        return RxNetty.newHttpClientBuilder(host, port).pipelineConfigurator(configurator).build();
    }

    public static Observable> createHttpRequest(HttpClientRequest request) {
        RxClient.ServerInfo serverInfo;
        try {
            serverInfo = getServerInfoFromRequest(request);
        } catch (URISyntaxException e) {
            return Observable.error(e);
        }
        return globalClient.submit(serverInfo, request);
    }

    public static Observable> createHttpRequest(HttpClientRequest request,
                                                                             HttpClient.HttpClientConfig config) {
        RxClient.ServerInfo serverInfo;
        try {
            serverInfo = getServerInfoFromRequest(request);
        } catch (URISyntaxException e) {
            return Observable.error(e);
        }
        return globalClient.submit(serverInfo, request, config);
    }

    public static Observable> createHttpGet(String uri) {
        return createHttpRequest(HttpClientRequest.createGet(uri));
    }

    public static Observable> createHttpPost(String uri, Observable content) {
        return createHttpRequest(HttpClientRequest.createPost(uri).withContentSource(content));
    }

    public static Observable> createHttpPut(String uri, Observable content) {
        return createHttpRequest(HttpClientRequest.createPut(uri).withContentSource(content));
    }

    public static  Observable> createHttpPost(String uri, Observable content,
                                                                             ContentTransformer transformer) {
        return createHttpRequest(HttpClientRequest.createPost(uri).withRawContentSource(content, transformer));
    }

    public static  Observable> createHttpPut(String uri, Observable content,
                                                                            ContentTransformer transformer) {
        return createHttpRequest(HttpClientRequest.createPut(uri).withRawContentSource(content, transformer));
    }

    public static Observable> createHttpDelete(String uri) {
        return createHttpRequest(HttpClientRequest.createDelete(uri));
    }

    public static  WebSocketClientBuilder newWebSocketClientBuilder(String host, int port) {
        return new WebSocketClientBuilder(host, port).enableWireLogging(LogLevel.DEBUG);
    }

    public static  WebSocketServerBuilder
    newWebSocketServerBuilder(int port, ConnectionHandler connectionHandler) {
        return new WebSocketServerBuilder(port, connectionHandler).enableWireLogging(LogLevel.DEBUG);
    }

    /**
     * An implementation of {@link RxEventLoopProvider} to be used by all clients and servers created after this call.
     *
     * @param provider New provider to use.
     *
     * @return Existing provider.
     */
    public static RxEventLoopProvider useEventLoopProvider(RxEventLoopProvider provider) {
        RxEventLoopProvider oldProvider = rxEventLoopProvider;
        rxEventLoopProvider = provider;
        return oldProvider;
    }

    public static void useMetricListenersFactory(MetricEventsListenerFactory factory) {
        metricEventsListenerFactory = factory;
    }

    public static RxEventLoopProvider getRxEventLoopProvider() {
        return rxEventLoopProvider;
    }

    private static RxClient.ServerInfo getServerInfoFromRequest(HttpClientRequest request)
            throws URISyntaxException {
        URI uri = new URI(request.getUri());
        final String host = uri.getHost();
        if (null != host) {
            int port = uri.getPort();
            if (port < 0) {
                String scheme = uri.getScheme();
                if (null != scheme) {
                    if ("http".equals(scheme)) {
                        port = 80;
                    } else if ("https".equals(scheme)) {
                        port = 443;
                    }
                }
            }
            return new RxClient.ServerInfo(host, port);
        }
        return globalClient.getDefaultServer();
    }
}