Example usage for io.netty.channel ChannelFuture cause

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

Introduction

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

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

From source file:com.king.platform.net.http.netty.ChannelManager.java

License:Apache License

private void sendOnNewChannel(final HttpRequestContext httpRequestContext,
        final RequestEventBus requestEventBus) {
    final ServerInfo serverInfo = httpRequestContext.getServerInfo();

    ChannelFuture channelFuture = connect(serverInfo);

    channelFuture.addListener(new ChannelFutureListener() {

        @Override/*www .ja v a2  s . com*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {

                requestEventBus.triggerEvent(Event.CREATED_CONNECTION, serverInfo);

                requestEventBus.triggerEvent(Event.onConnected);

                Channel channel = future.channel();
                channel.attr(ServerInfo.ATTRIBUTE_KEY).set(serverInfo);
                logger.trace("Opened a new channel {}, for request {}", channel, httpRequestContext);
                sendOnChannel(channel, httpRequestContext, requestEventBus);

            } else {
                logger.trace("Failed to opened a new channel for request {}", httpRequestContext);
                Throwable cause = future.cause();
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, cause);
            }
        }
    });
}

From source file:com.king.platform.net.http.netty.request.HttpClientRequestHandler.java

License:Apache License

private void writeHeaders(ChannelHandlerContext ctx, final HttpRequestContext httpRequestContext,
        HttpRequest httpRequest, final RequestEventBus requestEventBus) {
    httpRequestContext.getTimeRecorder().startWriteHeaders();
    ChannelFuture channelFuture = ctx.write(httpRequest);
    channelFuture.addListener(new ChannelFutureListener() {
        @Override/*from   ww w. j a va  2 s.  c o m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                logger.trace("Wrote headers operation completed, future: {}", future);
                requestEventBus.triggerEvent(Event.onWroteHeaders);
                requestEventBus.triggerEvent(Event.TOUCH);
                httpRequestContext.getTimeRecorder().completedWriteHeaders();

            } else {
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
            }

        }
    });
}

From source file:com.king.platform.net.http.netty.request.HttpClientRequestHandler.java

License:Apache License

private void writeLastHttpContent(ChannelHandlerContext ctx, final HttpRequestContext httpRequestContext,
        final RequestEventBus requestEventBus) {
    ChannelFuture future = ctx.writeAndFlush(new DefaultLastHttpContent());
    future.addListener(new ChannelFutureListener() {
        @Override/*from www .j  a  v a 2  s.  com*/
        public void operationComplete(ChannelFuture future) throws Exception {
            logger.trace("writeLastHttpContent operation completed, future: {}", future);

            if (future.isSuccess()) {
                requestEventBus.triggerEvent(Event.onWroteContentCompleted);
                requestEventBus.triggerEvent(Event.TOUCH);
                httpRequestContext.getTimeRecorder().completedWriteLastBody();

            } else {
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
            }

        }
    });
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java

License:Open Source License

protected void sendFile(final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest,
        SyncFile syncFile) throws Exception {

    Path path = Paths.get(syncFile.getFilePathName());

    if (Files.notExists(path)) {
        _syncTrafficShapingHandler.decrementConnectionsCount();

        if (_logger.isTraceEnabled()) {
            Channel channel = channelHandlerContext.channel();

            _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path);
        }/*from w  w w .j  av  a  2s. c  o m*/

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    if (_logger.isDebugEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path);
    }

    long modifiedTime = syncFile.getModifiedTime();
    long previousModifiedTime = syncFile.getPreviousModifiedTime();

    if (OSDetector.isApple()) {
        modifiedTime = modifiedTime / 1000 * 1000;
        previousModifiedTime = previousModifiedTime / 1000 * 1000;
    }

    FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);

    long currentTime = currentFileTime.toMillis();

    if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) {

        _syncTrafficShapingHandler.decrementConnectionsCount();

        Channel channel = channelHandlerContext.channel();

        _logger.error(
                "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}",
                channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime);

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);

    long size = Files.size(path);

    HttpUtil.setContentLength(httpResponse, size);

    HttpHeaders httpHeaders = httpResponse.headers();

    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName()));

    if (HttpUtil.isKeepAlive(fullHttpRequest)) {
        httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    channelHandlerContext.write(httpResponse);

    SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime);

    ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpChunkedInput(syncChunkedFile),
            channelHandlerContext.newProgressivePromise());

    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            _syncTrafficShapingHandler.decrementConnectionsCount();

            if (channelFuture.isSuccess()) {
                return;
            }

            Throwable exception = channelFuture.cause();

            Channel channel = channelHandlerContext.channel();

            _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception);

            channelHandlerContext.close();
        }

    });

    if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.linecorp.armeria.client.http.HttpRequestSubscriber.java

License:Apache License

/**
 * Invoked on each write of an {@link HttpObject}.
 *//* w  w w  .j  a  va2 s. co  m*/
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isSuccess()) {
        if (state != State.DONE) {
            subscription.request(1);
        }
        return;
    }

    fail(future.cause());

    final Throwable cause = future.cause();
    if (!(cause instanceof ClosedPublisherException)) {
        final Channel ch = future.channel();
        Exceptions.logIfUnexpected(logger, ch, HttpSession.get(ch).protocol(), cause);
        ch.close();
    }
}

From source file:com.linecorp.armeria.client.http.HttpSessionChannelFactory.java

License:Apache License

void connect(SocketAddress remoteAddress, SessionProtocol protocol, Promise<Channel> sessionPromise) {
    final Bootstrap bootstrap = bootstrap(protocol);
    final ChannelFuture connectFuture = bootstrap.connect(remoteAddress);

    connectFuture.addListener((ChannelFuture future) -> {
        if (future.isSuccess()) {
            initSession(protocol, future, sessionPromise);
        } else {/*www.j  a v  a 2 s .c om*/
            sessionPromise.setFailure(future.cause());
        }
    });
}

From source file:com.linecorp.armeria.client.HttpRequestSubscriber.java

License:Apache License

/**
 * Invoked on each write of an {@link HttpObject}.
 */// w  ww.jav  a 2 s. com
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isSuccess()) {
        if (state == State.DONE) {
            // Successfully sent the request; schedule the response timeout.
            response.scheduleTimeout(ctx);
        } else {
            assert subscription != null;
            subscription.request(1);
        }
        return;
    }

    fail(future.cause());

    final Throwable cause = future.cause();
    if (!(cause instanceof ClosedPublisherException)) {
        final Channel ch = future.channel();
        Exceptions.logIfUnexpected(logger, ch, HttpSession.get(ch).protocol(), cause);
        ch.close();
    }
}

From source file:com.linecorp.armeria.server.http.HttpResponseSubscriber.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isSuccess()) {
        if (state != State.DONE) {
            subscription.request(1);//from   w w  w .  j  a  v  a  2s .co m
        }
        return;
    }

    fail(future.cause());
    HttpServerHandler.CLOSE_ON_FAILURE.operationComplete(future);
}

From source file:com.linecorp.armeria.server.HttpResponseSubscriber.java

License:Apache License

private void write0(HttpObject o, boolean endOfStream) {
    final ChannelFuture future;
    final boolean wroteEmptyData;
    if (o instanceof HttpData) {
        final HttpData data = (HttpData) o;
        wroteEmptyData = data.isEmpty();
        future = responseEncoder.writeData(ctx, req.id(), req.streamId(), data, endOfStream);
        logBuilder().increaseResponseLength(data.length());
    } else if (o instanceof HttpHeaders) {
        wroteEmptyData = false;/*www.ja  va2  s . c  om*/
        future = responseEncoder.writeHeaders(ctx, req.id(), req.streamId(), (HttpHeaders) o, endOfStream);
    } else {
        // Should never reach here because we did validation in onNext().
        throw new Error();
    }

    future.addListener((ChannelFuture f) -> {
        final boolean isSuccess;
        if (f.isSuccess()) {
            isSuccess = true;
        } else {
            // If 1) the last chunk we attempted to send was empty,
            //    2) the connection has been closed,
            //    3) and the protocol is HTTP/1,
            // it is very likely that a client closed the connection after receiving the complete content,
            // which is not really a problem.
            isSuccess = endOfStream && wroteEmptyData && f.cause() instanceof ClosedChannelException
                    && responseEncoder instanceof Http1ObjectEncoder;
        }

        // Write an access log if:
        // - every message has been sent successfully.
        // - any write operation is failed with a cause.
        if (isSuccess) {
            if (endOfStream && tryComplete()) {
                logBuilder().endResponse();
                reqCtx.log().addListener(accessLogWriter::accept, RequestLogAvailability.COMPLETE);
            }
            if (state != State.DONE) {
                subscription.request(1);
            }
            return;
        }

        if (tryComplete()) {
            setDone();
            logBuilder().endResponse(f.cause());
            subscription.cancel();
            reqCtx.log().addListener(accessLogWriter::accept, RequestLogAvailability.COMPLETE);
        }
        HttpServerHandler.CLOSE_ON_FAILURE.operationComplete(f);
    });

    ctx.flush();
}

From source file:com.linkedin.mitm.proxy.ProxyServer.java

License:Open Source License

/**
 * Start proxy server//w  w  w.  ja va 2 s . c  o m
 * */
public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(_acceptorGroup, _upstreamWorkerGroup);
    serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() {
        @Override
        public ServerChannel newChannel() {
            return new NioServerSocketChannel();
        }
    });
    serverBootstrap.childHandler(new ProxyInitializer(this));

    //bind
    ChannelFuture future = serverBootstrap.bind(_host, _port);

    //wait for the future
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        future.channel().closeFuture().awaitUninterruptibly();
        throw new ChannelException(String.format("Failed to bind to: %s:%d", _host, _port), future.cause());
    } else {
        _allChannels.add(future.channel());
    }
}