Example usage for io.netty.channel ReflectiveChannelFactory ReflectiveChannelFactory

List of usage examples for io.netty.channel ReflectiveChannelFactory ReflectiveChannelFactory

Introduction

In this page you can find the example usage for io.netty.channel ReflectiveChannelFactory ReflectiveChannelFactory.

Prototype

public ReflectiveChannelFactory(Class<? extends T> clazz) 

Source Link

Usage

From source file:chat.viska.xmpp.Connection.java

License:Apache License

private static Single<List<DnsRecord>> lookupDnsUsingNetty(final String query, final DnsRecordType type,
        @Nullable final Iterable<String> dns) {
    final NioEventLoopGroup threadPool = new NioEventLoopGroup();
    final DnsNameResolverBuilder builder = new DnsNameResolverBuilder(threadPool.next());
    builder.channelFactory(new ReflectiveChannelFactory<>(NioDatagramChannel.class));
    builder.decodeIdn(true);/*ww  w.java2s .  com*/
    if (dns != null) {
        builder.searchDomains(dns);
    }
    return Single.fromFuture(builder.build().query(new DefaultDnsQuestion(query, type)))
            .map(AddressedEnvelope::content).map(message -> {
                final int recordsSize = message.count(DnsSection.ANSWER);
                final List<DnsRecord> records = new ArrayList<>(recordsSize);
                for (int it = 0; it < recordsSize; ++it) {
                    records.add(message.recordAt(DnsSection.ANSWER, it));
                }
                return records;
            }).doFinally(threadPool::shutdownGracefully);
}

From source file:io.grpc.netty.NettyChannelBuilder.java

License:Apache License

/**
 * Specifies the channel type to use, by default we use {@code EpollSocketChannel} if available,
 * otherwise using {@link NioSocketChannel}.
 *
 * <p>You either use this or {@link #channelFactory(io.netty.channel.ChannelFactory)} if your
 * {@link Channel} implementation has no no-args constructor.
 *
 * <p>It's an optional parameter. If the user has not provided an Channel type or ChannelFactory
 * when the channel is built, the builder will use the default one which is static.
 *
 * <p>You must also provide corresponding {@link #eventLoopGroup(EventLoopGroup)}. For example,
 * {@link NioSocketChannel} must use {@link io.netty.channel.nio.NioEventLoopGroup}, otherwise
 * your application won't start./*ww  w  .  j  av a  2s .c om*/
 */
public NettyChannelBuilder channelType(Class<? extends Channel> channelType) {
    checkNotNull(channelType, "channelType");
    return channelFactory(new ReflectiveChannelFactory<>(channelType));
}

From source file:io.grpc.netty.NettyClientTransportTest.java

License:Apache License

@Test
public void setSoLingerChannelOption() throws IOException {
    startServer();/*from ww w.  jav  a 2  s.  c o m*/
    Map<ChannelOption<?>, Object> channelOptions = new HashMap<>();
    // set SO_LINGER option
    int soLinger = 123;
    channelOptions.put(ChannelOption.SO_LINGER, soLinger);
    NettyClientTransport transport = new NettyClientTransport(address,
            new ReflectiveChannelFactory<>(NioSocketChannel.class), channelOptions, group, newNegotiator(),
            DEFAULT_WINDOW_SIZE, DEFAULT_MAX_MESSAGE_SIZE, GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE,
            KEEPALIVE_TIME_NANOS_DISABLED, 1L, false, authority, null /* user agent */, tooManyPingsRunnable,
            new TransportTracer(), Attributes.EMPTY, new SocketPicker(), new FakeChannelLogger());
    transports.add(transport);
    callMeMaybe(transport.start(clientTransportListener));

    // verify SO_LINGER has been set
    ChannelConfig config = transport.channel().config();
    assertTrue(config instanceof SocketChannelConfig);
    assertEquals(soLinger, ((SocketChannelConfig) config).getSoLinger());
}

From source file:io.grpc.netty.NettyClientTransportTest.java

License:Apache License

@Test
public void failingToConstructChannelShouldFailGracefully() throws Exception {
    address = TestUtils.testServerAddress(new InetSocketAddress(12345));
    authority = GrpcUtil.authorityFromHostAndPort(address.getHostString(), address.getPort());
    NettyClientTransport transport = new NettyClientTransport(address,
            new ReflectiveChannelFactory<>(CantConstructChannel.class), new HashMap<ChannelOption<?>, Object>(),
            group, newNegotiator(), DEFAULT_WINDOW_SIZE, DEFAULT_MAX_MESSAGE_SIZE,
            GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, KEEPALIVE_TIME_NANOS_DISABLED, 1, false, authority, null,
            tooManyPingsRunnable, new TransportTracer(), Attributes.EMPTY, new SocketPicker(),
            new FakeChannelLogger());
    transports.add(transport);//from   w w  w .ja  v  a2  s . c  om

    // Should not throw
    callMeMaybe(transport.start(clientTransportListener));

    // And RPCs and PINGs should fail cleanly, reporting the failure
    Rpc rpc = new Rpc(transport);
    try {
        rpc.waitForResponse();
        fail("Expected exception");
    } catch (Exception ex) {
        if (!(getRootCause(ex) instanceof CantConstructChannelError)) {
            throw new AssertionError("Could not find expected error", ex);
        }
    }

    final SettableFuture<Object> pingResult = SettableFuture.create();
    FakeClock clock = new FakeClock();
    ClientTransport.PingCallback pingCallback = new ClientTransport.PingCallback() {
        @Override
        public void onSuccess(long roundTripTimeNanos) {
            pingResult.set(roundTripTimeNanos);
        }

        @Override
        public void onFailure(Throwable cause) {
            pingResult.setException(cause);
        }
    };
    transport.ping(pingCallback, clock.getScheduledExecutorService());
    assertFalse(pingResult.isDone());
    clock.runDueTasks();
    assertTrue(pingResult.isDone());
    try {
        pingResult.get();
        fail("Expected exception");
    } catch (Exception ex) {
        if (!(getRootCause(ex) instanceof CantConstructChannelError)) {
            throw new AssertionError("Could not find expected error", ex);
        }
    }
}

From source file:io.grpc.netty.NettyClientTransportTest.java

License:Apache License

@Test
public void channelFactoryShouldSetSocketOptionKeepAlive() throws Exception {
    startServer();/*from w w  w.j a  va2  s.c o m*/
    NettyClientTransport transport = newTransport(newNegotiator(), DEFAULT_MAX_MESSAGE_SIZE,
            GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, "testUserAgent", true, TimeUnit.SECONDS.toNanos(10L),
            TimeUnit.SECONDS.toNanos(1L), new ReflectiveChannelFactory<>(NioSocketChannel.class), group);

    callMeMaybe(transport.start(clientTransportListener));

    assertThat(transport.channel().config().getOption(ChannelOption.SO_KEEPALIVE)).isTrue();
}

From source file:io.grpc.netty.NettyClientTransportTest.java

License:Apache License

@Test
public void channelFactoryShouldNNotSetSocketOptionKeepAlive() throws Exception {
    startServer();//  w  ww . j a v a2  s.  co  m
    NettyClientTransport transport = newTransport(newNegotiator(), DEFAULT_MAX_MESSAGE_SIZE,
            GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, "testUserAgent", true, TimeUnit.SECONDS.toNanos(10L),
            TimeUnit.SECONDS.toNanos(1L), new ReflectiveChannelFactory<>(LocalChannel.class), group);

    callMeMaybe(transport.start(clientTransportListener));

    assertThat(transport.channel().config().getOption(ChannelOption.SO_KEEPALIVE)).isNull();
}

From source file:io.grpc.netty.NettyClientTransportTest.java

License:Apache License

@Test
public void keepAliveEnabled_shouldSetTcpUserTimeout() throws Exception {
    assume().that(Utils.isEpollAvailable()).isTrue();

    startServer();//ww  w  .  j a  v  a2 s . co m
    EventLoopGroup epollGroup = Utils.DEFAULT_WORKER_EVENT_LOOP_GROUP.create();
    int keepAliveTimeMillis = 12345670;
    int keepAliveTimeoutMillis = 1234567;
    try {
        NettyClientTransport transport = newTransport(newNegotiator(), DEFAULT_MAX_MESSAGE_SIZE,
                GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, null /* user agent */, true /* keep alive */,
                TimeUnit.MILLISECONDS.toNanos(keepAliveTimeMillis),
                TimeUnit.MILLISECONDS.toNanos(keepAliveTimeoutMillis),
                new ReflectiveChannelFactory<>(Utils.DEFAULT_CLIENT_CHANNEL_TYPE), epollGroup);

        callMeMaybe(transport.start(clientTransportListener));

        ChannelOption<Integer> tcpUserTimeoutOption = Utils.maybeGetTcpUserTimeoutOption();
        assertThat(tcpUserTimeoutOption).isNotNull();
        // on some linux based system, the integer value may have error (usually +-1)
        assertThat((double) transport.channel().config().getOption(tcpUserTimeoutOption)).isWithin(5.0)
                .of((double) keepAliveTimeoutMillis);
    } finally {
        epollGroup.shutdownGracefully();
    }
}

From source file:io.grpc.netty.NettyClientTransportTest.java

License:Apache License

@Test
public void keepAliveDisabled_shouldNotSetTcpUserTimeout() throws Exception {
    assume().that(Utils.isEpollAvailable()).isTrue();

    startServer();/*  ww  w  .j  a  va  2 s.c o m*/
    EventLoopGroup epollGroup = Utils.DEFAULT_WORKER_EVENT_LOOP_GROUP.create();
    int keepAliveTimeMillis = 12345670;
    try {
        long keepAliveTimeNanos = TimeUnit.MILLISECONDS.toNanos(keepAliveTimeMillis);
        NettyClientTransport transport = newTransport(newNegotiator(), DEFAULT_MAX_MESSAGE_SIZE,
                GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, null /* user agent */, false /* keep alive */,
                keepAliveTimeNanos, keepAliveTimeNanos,
                new ReflectiveChannelFactory<>(Utils.DEFAULT_CLIENT_CHANNEL_TYPE), epollGroup);

        callMeMaybe(transport.start(clientTransportListener));

        ChannelOption<Integer> tcpUserTimeoutOption = Utils.maybeGetTcpUserTimeoutOption();
        assertThat(tcpUserTimeoutOption).isNotNull();
        // default TCP_USER_TIMEOUT=0 (use the system default)
        assertThat(transport.channel().config().getOption(tcpUserTimeoutOption)).isEqualTo(0);
    } finally {
        epollGroup.shutdownGracefully();
    }
}

From source file:io.grpc.netty.NettyClientTransportTest.java

License:Apache License

private NettyClientTransport newTransport(ProtocolNegotiator negotiator, int maxMsgSize, int maxHeaderListSize,
        String userAgent, boolean enableKeepAlive) {
    return newTransport(negotiator, maxMsgSize, maxHeaderListSize, userAgent, enableKeepAlive,
            TimeUnit.SECONDS.toNanos(10L), TimeUnit.SECONDS.toNanos(1L),
            new ReflectiveChannelFactory<>(NioSocketChannel.class), group);
}

From source file:io.grpc.netty.NettyClientTransportTest.java

License:Apache License

private void startServer(int maxStreamsPerConnection, int maxHeaderListSize) throws IOException {
    server = new NettyServer(TestUtils.testServerAddress(new InetSocketAddress(0)),
            new ReflectiveChannelFactory<>(NioServerSocketChannel.class),
            new HashMap<ChannelOption<?>, Object>(), new FixedObjectPool<>(group), new FixedObjectPool<>(group),
            negotiator, Collections.<ServerStreamTracer.Factory>emptyList(),
            TransportTracer.getDefaultFactory(), maxStreamsPerConnection, DEFAULT_WINDOW_SIZE,
            DEFAULT_MAX_MESSAGE_SIZE, maxHeaderListSize, DEFAULT_SERVER_KEEPALIVE_TIME_NANOS,
            DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS, MAX_CONNECTION_IDLE_NANOS_DISABLED,
            MAX_CONNECTION_AGE_NANOS_DISABLED, MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE, true, 0, channelz);
    server.start(serverListener);/*from   w  w w  . jav  a  2s  .c om*/
    address = TestUtils.testServerAddress((InetSocketAddress) server.getListenSocketAddress());
    authority = GrpcUtil.authorityFromHostAndPort(address.getHostString(), address.getPort());
}