Example usage for io.netty.channel ChannelFuture addListener

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

Introduction

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

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:io.termd.core.http.netty.HttpRequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (wsUri.equalsIgnoreCase(request.getUri())) {
        ctx.fireChannelRead(request.retain());
    } else {/*from  w  w  w.java2s . c o  m*/
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);
        }

        HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(),
                HttpResponseStatus.INTERNAL_SERVER_ERROR);

        String path = request.getUri();
        if ("/".equals(path)) {
            path = "/index.html";
        }
        URL res = HttpTtyConnection.class.getResource("/io/termd/core/http" + path);
        try {
            if (res != null) {
                DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(),
                        HttpResponseStatus.OK);
                InputStream in = res.openStream();
                byte[] tmp = new byte[256];
                for (int l = 0; l != -1; l = in.read(tmp)) {
                    fullResp.content().writeBytes(tmp, 0, l);
                }
                int li = path.lastIndexOf('.');
                if (li != -1 && li != path.length() - 1) {
                    String ext = path.substring(li + 1, path.length());
                    String contentType;
                    switch (ext) {
                    case "html":
                        contentType = "text/html";
                        break;
                    case "js":
                        contentType = "application/javascript";
                        break;
                    default:
                        contentType = null;
                        break;
                    }
                    if (contentType != null) {
                        fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
                    }
                }
                response = fullResp;
            } else {
                response.setStatus(HttpResponseStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ctx.write(response);
            ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:io.termd.core.http.netty.NettyWebsocketTtyBootstrap.java

License:Apache License

public void start(Consumer<TtyConnection> handler, Consumer<Throwable> doneHandler) {
    group = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();
    b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new TtyServerInitializer(channelGroup, handler));

    ChannelFuture f = b.bind(host, port);
    f.addListener(abc -> {
        if (abc.isSuccess()) {
            channel = f.channel();/*w  w w.  j a v  a  2  s.  c  o m*/
            doneHandler.accept(null);
        } else {
            doneHandler.accept(abc.cause());
        }
    });
}

From source file:io.urmia.proxy.HttpProxyFrontendHandler.java

License:Open Source License

private Channel openOutboundChannel(final ChannelHandlerContext ctx, String remoteHost, int remotePort,
        final int index) {

    log.info("proxy opening outbound channel to({}): {}:{}", index, remoteHost, remotePort);

    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new HttpProxyBackendInitializer(ctx, index, directWriteBack))
            .option(ChannelOption.AUTO_READ, false);

    ChannelFuture f = b.connect(remoteHost, remotePort);
    Channel outboundChannel = f.channel();
    f.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override/*from ww  w. j a va  2s .c  o m*/
        public void operationComplete(ChannelFuture futureC) throws Exception {
            if (futureC.isSuccess()) {
                futureC.channel().writeAndFlush(initHttpRequest)
                        .addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(ChannelFuture futureW) throws Exception {
                                if (futureW.isSuccess())
                                    onSuccessfulWrite(ctx, index);
                                else {
                                    log.info("unable to write http request: {}", futureW.cause());
                                    ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index));
                                }
                            }
                        });
            } else {
                ctx.fireUserEventTriggered(new ProxyUserEvent(OUTBOUND_ERROR, index));
            }
        }
    });

    return outboundChannel;
}

From source file:io.urmia.st.StorageServerHandler.java

License:Open Source License

private void listDirectory(ChannelHandlerContext ctx, File file) throws IOException {

    log.info("listDirectory: {}", file);

    File[] files = file.listFiles();

    if (files == null) {
        ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        return;//  ww w  . j a v  a 2 s  .  co  m
    }

    List<String> jsons = new ArrayList<String>(files.length);

    for (File f : files) {
        log.debug("found: {}", f);
        jsons.add(toJson(f));
    }

    String result = LINE_JOINER.join(jsons);

    log.info("writing back: {}", result);

    HttpResponseStatus status = HttpResponseStatus.OK;

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer(result, CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/x-json-stream; type=directory");
    response.headers().set(CONTENT_LENGTH, result.length());
    response.headers().set("result-set-size", files.length);

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(response);

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }

    access.success(ctx, "LIST", file.getAbsolutePath(), requestStartMS);

}

From source file:io.urmia.st.StorageServerHandler.java

License:Open Source License

private void downloadFile(ChannelHandlerContext ctx, File file) throws IOException {

    final RandomAccessFile raf;
    try {//w  w  w .  j ava  2 s .  c  o  m
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        log.warn("no file at: {}", file.getPath());
        access.fail(ctx, "GET", file.getAbsolutePath(), requestStartMS);
        sendError(ctx, NOT_FOUND);
        return;
    }
    final long fileLength = raf.length();

    log.info("downloading file: {} of len: {}", file, fileLength);

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    //setDateAndCacheHeaders(response, file);

    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    final ChannelFuture sendFileFuture;

    sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
            ctx.newProgressivePromise());

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.err.println("Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    access.success(ctx, "GET", file.getAbsolutePath(), requestStartMS);

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }

}

From source file:io.urmia.st.StorageServerHandler.java

License:Open Source License

private void writeResponse(ChannelHandlerContext ctx, FullHttpResponse response, boolean forceClose) {

    // Decide whether to close the connection or not.
    boolean close = forceClose
            || HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(HttpHeaders.Names.CONNECTION))
            || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE
                    .equalsIgnoreCase(request.headers().get(HttpHeaders.Names.CONNECTION));

    log.debug("writeResponse close: {}, data: {}", close, response);

    ChannelFuture future = ctx.writeAndFlush(response);
    // Close the connection after the write operation is done if necessary.
    if (close) {//from  w ww .j a  v  a  2 s.c om
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:io.vertx.core.dns.HostnameResolutionTest.java

License:Open Source License

@Test
public void testAsyncResolveConnectIsNotifiedOnChannelEventLoop() throws Exception {
    CountDownLatch listenLatch = new CountDownLatch(1);
    NetServer server = vertx.createNetServer().connectHandler(so -> {
    });//from w w w  .  jav  a 2s .c o  m
    try {
        server.listen(1234, "localhost", onSuccess(v -> listenLatch.countDown()));
        awaitLatch(listenLatch);
        AtomicReference<Thread> channelThread = new AtomicReference<>();
        CountDownLatch connectLatch = new CountDownLatch(1);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channelFactory(((VertxInternal) vertx).transport().channelFactory(false));
        bootstrap.group(vertx.nettyEventLoopGroup());
        bootstrap.resolver(((VertxInternal) vertx).nettyAddressResolverGroup());
        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                channelThread.set(Thread.currentThread());
                connectLatch.countDown();
            }
        });
        ChannelFuture channelFut = bootstrap.connect("localhost", 1234);
        awaitLatch(connectLatch);
        channelFut.addListener(v -> {
            assertTrue(v.isSuccess());
            assertEquals(channelThread.get(), Thread.currentThread());
            testComplete();
        });
        await();
    } finally {
        server.close();
    }
}

From source file:io.vertx.core.dns.impl.fix.DnsQueryContext.java

License:Apache License

private void writeQuery(final DnsQuery query) {
    final ChannelFuture writeFuture = parent.ch.writeAndFlush(query);
    if (writeFuture.isDone()) {
        onQueryWriteCompletion(writeFuture);
    } else {//  w w  w  .  j a  v  a2 s  .c  o  m
        writeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                onQueryWriteCompletion(writeFuture);
            }
        });
    }
}

From source file:io.vertx.core.http.impl.FileStreamChannel.java

License:Open Source License

FileStreamChannel(Handler<AsyncResult<Long>> resultHandler, VertxHttp2Stream stream, long offset, long length) {
    super(null, Id.INSTANCE);

    pipeline().addLast(new ChannelInitializer<Channel>() {
        @Override/*from   w w  w  . j a v a  2 s  . co m*/
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new ChunkedWriteHandler());
            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof RandomAccessFile) {
                        ChannelFuture fut = ctx.writeAndFlush(new ChunkedFile((RandomAccessFile) evt, offset,
                                length, 8192 /* default chunk size */ ));
                        fut.addListener(f -> {
                            if (resultHandler != null) {
                                if (f.isSuccess()) {
                                    resultHandler.handle(Future.succeededFuture(bytesWritten));
                                } else {
                                    resultHandler.handle(Future.failedFuture(f.cause()));
                                }
                            }
                            fut.addListener(ChannelFutureListener.CLOSE);
                        });
                    }
                }
            });
        }
    });

    this.stream = stream;
}

From source file:io.vertx.core.http.impl.HttpClientImpl.java

License:Open Source License

private void internalConnect(ContextImpl context, int port, String host,
        Handler<ClientConnection> connectHandler, Handler<Throwable> connectErrorHandler,
        ConnectionLifeCycleListener listener) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(context.eventLoop());
    bootstrap.channelFactory(new VertxNioSocketChannelFactory());
    sslHelper.validate(vertx);/*from ww  w.  java  2s .c  o  m*/
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (options.isSsl()) {
                pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, true, host, port));
            }

            pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false));
            if (options.isTryUseCompression()) {
                pipeline.addLast("inflater", new HttpContentDecompressor(true));
            }
            if (options.getIdleTimeout() > 0) {
                pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
            }
            pipeline.addLast("handler", new ClientHandler(vertx, context));
        }
    });
    applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener((ChannelFuture channelFuture) -> {
        Channel ch = channelFuture.channel();
        if (channelFuture.isSuccess()) {
            if (options.isSsl()) {
                // TCP connected, so now we must do the SSL handshake

                SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
                fut.addListener(fut2 -> {
                    if (fut2.isSuccess()) {
                        connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
                    } else {
                        connectionFailed(context, ch, connectErrorHandler,
                                new SSLHandshakeException("Failed to create SSL connection"), listener);
                    }
                });
            } else {
                connected(context, port, host, ch, connectHandler, connectErrorHandler, listener);
            }
        } else {
            connectionFailed(context, ch, connectErrorHandler, channelFuture.cause(), listener);
        }
    });
}