Example usage for io.netty.channel ChannelFuture sync

List of usage examples for io.netty.channel ChannelFuture sync

Introduction

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

Prototype

@Override
    ChannelFuture sync() throws InterruptedException;

Source Link

Usage

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

License:Apache License

@Test
public void handlerRemovedFailuresPropagated() throws Exception {
    WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelHandlerAdapter() {
                @Override//from w w  w  .  java2  s  .c o m
                public void handlerRemoved(ChannelHandlerContext ctx) {
                    ctx.pipeline()
                            .remove(ctx.pipeline().context(WriteBufferingAndExceptionHandler.class).name());
                }
            });
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    chan.connect(addr);
    ChannelFuture wf = chan.writeAndFlush(new Object());
    chan.pipeline().removeFirst();

    try {
        wf.sync();
        fail();
    } catch (Exception e) {
        Status status = Status.fromThrowable(e);
        assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
        assertThat(status.getDescription()).contains("Buffer removed");
    }
}

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

License:Apache License

@Test
public void writesBuffered() throws Exception {
    final AtomicBoolean handlerAdded = new AtomicBoolean();
    final AtomicBoolean flush = new AtomicBoolean();
    final AtomicReference<Object> write = new AtomicReference<>();
    final WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelOutboundHandlerAdapter() {
                @Override/*  w  w  w .  j  ava  2 s  .  c  o  m*/
                public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                    assertFalse(handlerAdded.getAndSet(true));
                    super.handlerAdded(ctx);
                }

                @Override
                public void flush(ChannelHandlerContext ctx) throws Exception {
                    assertFalse(flush.getAndSet(true));
                    super.flush(ctx);
                }

                @Override
                public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
                    assertNull(write.getAndSet(msg));
                    promise.setSuccess();
                }
            });
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    assertTrue(handlerAdded.get());

    chan.write(new Object());
    chan.connect(addr).sync();
    assertNull(write.get());

    chan.flush();
    assertNull(write.get());
    assertFalse(flush.get());

    assertThat(chan.pipeline().context(handler)).isNotNull();
    chan.eventLoop().submit(new Runnable() {
        @Override
        public void run() {
            handler.writeBufferedAndRemove(chan.pipeline().context(handler));
        }
    }).sync();

    assertThat(chan.pipeline().context(handler)).isNull();
    assertThat(write.get().getClass()).isSameInstanceAs(Object.class);
    assertTrue(flush.get());
    assertThat(chan.pipeline()).doesNotContain(handler);
}

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

License:Apache License

@Test
public void uncaughtReadFails() throws Exception {
    WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler(
            new ChannelHandlerAdapter() {
            });/*from w  w  w . ja v a 2 s  .  c o m*/
    LocalAddress addr = new LocalAddress("local");
    ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register();
    chan = cf.channel();
    cf.sync();
    ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class)
            .childHandler(new ChannelHandlerAdapter() {
            }).group(group).bind(addr);
    server = sf.channel();
    sf.sync();

    ChannelFuture wf = chan.writeAndFlush(new Object());
    chan.connect(addr);
    chan.pipeline().fireChannelRead(Unpooled.copiedBuffer(new byte[] { 'a' }));

    try {
        wf.sync();
        fail();
    } catch (Exception e) {
        Status status = Status.fromThrowable(e);
        assertThat(status.getCode()).isEqualTo(Code.INTERNAL);
        assertThat(status.getDescription()).contains("channelRead() missed");
    }
}

From source file:io.liveoak.container.server.AbstractServer.java

License:Open Source License

/**
 * Synchronously start the network listener.
 *
 * @throws InterruptedException If interrupted before completely starting.
 *///  www  . j a  v a2  s . c  o  m
public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.channel(channelClass()).group(eventLoopGroup()).localAddress(localAddress())
            //.handler( new DebugHandler( "server-handler" ) )
            .childHandler(createChildHandler());
    ChannelFuture future = serverBootstrap.bind();
    future.sync();
}

From source file:io.liveoak.stomp.server.SimpleStompServer.java

License:Open Source License

public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.channel(NioServerSocketChannel.class).group(this.group).localAddress(this.host, this.port)
            .childHandler(createChildHandler());
    ChannelFuture future = serverBootstrap.bind();
    future.sync();
}

From source file:io.moquette.server.netty.NettyAcceptor.java

License:Open Source License

private void initFactory(String host, int port, final PipelineInitializer pipeliner) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from  w  w  w .ja  v  a2  s  .c o m
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    try {
                        pipeliner.init(pipeline);
                    } catch (Throwable th) {
                        LOG.error("Severe error during pipeline creation", th);
                        throw th;
                    }
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(host, port);
        LOG.info("Server binded host: {}, port: {}", host, port);
        f.sync();
    } catch (InterruptedException ex) {
        LOG.error(null, ex);
    }
}

From source file:io.syncframework.netty.ServerImpl.java

License:Apache License

@Override
public void init() {
    String basedir = System.getProperty(Globals.SYNC_BASE);

    ///* w  ww  . j  a  va2  s.  c  o m*/
    // configure & initialize logging subsystem with logback
    //
    File logbackfile = new File(basedir, "logback.xml");
    if (logbackfile.exists() && logbackfile.isFile()) {
        try {
            LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            context.reset();
            configurator.doConfigure(logbackfile);
        } catch (JoranException je) {
            System.err.println(this + " has failed to configure logback: " + je.getMessage());
            je.printStackTrace();
            System.exit(1);
        }
    }

    if (log.isInfoEnabled())
        log.info("{} initializing using directory {}", this, basedir);

    File mimesfile = new File(basedir, "conf" + File.separator + "mime.types");
    if (mimesfile.exists()) {
        if (log.isTraceEnabled())
            log.trace("{} loading mimes from {}", this, mimesfile.getAbsolutePath());
        try {
            MimeUtils.init(mimesfile);
        } catch (Exception e) {
            log.error("{} has failed to initialize mimes.type file: {}", this, mimesfile, e);
            System.exit(1);
        }
    } else {
        if (log.isTraceEnabled())
            log.trace("{} loading default/known mime types.", this);
        MimeUtils.init();
    }

    // init configuration
    File configFile = new File(basedir, Globals.SERVER_PROPERTIES);
    try {
        FileInputStream fis = new FileInputStream(configFile);
        config.load(fis);
    } catch (FileNotFoundException e) {
        log.error("{} has failed to locate {}", this, configFile);
        System.exit(1);
    } catch (IOException e) {
        log.error("{} has failed to read configuration file {}", this, configFile);
        System.exit(1);
    }

    File appdir = new File(basedir, Globals.APPLICATIONS_DIRNAME);
    if (!appdir.isDirectory()) {
        System.err.println("directory " + appdir.getAbsolutePath() + " does not exist");
        System.exit(1);
    }
    // scan for .sar files
    File files[] = appdir.listFiles(new FileFilter() {
        public boolean accept(File f) {
            if (f.getName().endsWith(".sar"))
                return true;
            return false;
        }
    });
    // unpacking sar files...
    for (File sar : files) {
        try {
            if (log.isInfoEnabled())
                log.info("deploying SAR {}", sar.getName());
            SarUtils.unpack(sar, appdir);
        } catch (Exception e) {
            log.error("failed to uncompress sar file {}: {}", sar.getName(), e);
        }
    }
    // scan for directories
    files = appdir.listFiles(new FileFilter() {
        public boolean accept(File f) {
            if (f.isDirectory())
                return true;
            return false;
        }
    });
    applications = new LinkedList<Application>();
    for (File dir : files) {
        Application application = new Application(dir);
        try {
            application.start();
            ApplicationManager.register(application);
            applications.add(application);
        } catch (Throwable t) {
            log.error("{} has failed to initialize application: {}", this, application);
            log.error("exception caught: ", t);
            log.error("invalidating {} until the problem is fixed", application);
        }
    }

    Runtime.getRuntime().addShutdownHook(new Thread("shutdown") {
        public void run() {
            if (log.isInfoEnabled())
                log.info("{} is initializing graceful shutdown", this);

            // stopping process
            for (Application application : applications) {
                try {
                    if (log.isInfoEnabled())
                        log.info("stopping {}", application);
                    application.stop();
                } catch (Exception e) {
                    log.error("{} failed to stop {}: ", this, application, e);
                }
            }

            if (log.isInfoEnabled())
                log.info("@Applications stopped. Goodbye!");
        }
    });

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ServerInitializer(this));
        try {
            ChannelFuture chf = null;
            if (config.getListenAddress() != null)
                chf = b.bind(config.getListenAddress(), config.getListenPort());
            else
                chf = b.bind(config.getListenPort());
            Channel ch = chf.sync().channel();
            ch.closeFuture().sync();
        } catch (Exception e) {
            log.error("{} has failed to bind to socket: ", this, e);
            System.exit(1);
        }
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:io.termd.core.ssh.netty.NettyIoAcceptor.java

License:Apache License

@Override
public void bind(SocketAddress address) throws IOException {
    InetSocketAddress inetAddress = (InetSocketAddress) address;
    ChannelFuture f = bootstrap.bind(inetAddress);
    Channel channel = f.channel();
    channelGroup.add(channel);//from   w ww . j  av a2 s .c o m
    try {
        f.sync();
        SocketAddress bound = channel.localAddress();
        boundAddresses.put(bound, channel);
        channel.closeFuture().addListener(fut -> {
            boundAddresses.remove(bound);
        });
    } catch (Exception e) {
        throw Helper.toIOException(e);
    }
}

From source file:io.termd.core.ssh.netty.NettyIoAcceptor.java

License:Apache License

@Override
public void unbind(SocketAddress address) {
    Channel channel = boundAddresses.get(address);
    if (channel != null) {
        ChannelFuture fut;
        if (channel.isOpen()) {
            fut = channel.close();/*from  ww w  .  j a  v a  2 s . c  o m*/
        } else {
            fut = channel.closeFuture();
        }
        try {
            fut.sync();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:io.vertx.core.EventLoopGroupTest.java

License:Open Source License

@Test
public void testNettyServerUsesContextEventLoop() throws Exception {
    ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
    AtomicReference<Thread> contextThread = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    context.runOnContext(v -> {/* ww w.  j  a  v  a2s  .c o  m*/
        contextThread.set(Thread.currentThread());
        latch.countDown();
    });
    awaitLatch(latch);
    ServerBootstrap bs = new ServerBootstrap();
    bs.group(context.nettyEventLoop());
    bs.channelFactory(((VertxInternal) vertx).transport().serverChannelFactory(false));
    bs.option(ChannelOption.SO_BACKLOG, 100);
    bs.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            assertSame(contextThread.get(), Thread.currentThread());
            context.executeFromIO(v -> {
                assertSame(contextThread.get(), Thread.currentThread());
                assertSame(context, Vertx.currentContext());
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(v -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf buf = (ByteBuf) msg;
                        assertEquals("hello", buf.toString(StandardCharsets.UTF_8));
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(v -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(v -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        });
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(v -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            testComplete();
                        });
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        fail(cause.getMessage());
                    }
                });
            });
        }
    });
    ChannelFuture fut = bs.bind("localhost", 1234);
    try {
        fut.sync();
        vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> {
            assertTrue(ar.succeeded());
            NetSocket so = ar.result();
            so.write(Buffer.buffer("hello"));
        });
        await();
    } finally {
        fut.channel().close().sync();
    }
}