Example usage for io.netty.channel ChannelFuture isSuccess

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

Introduction

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

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

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  a  va  2  s  .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}.
 *///from   w  w  w  .  j  a  v a2s.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 {//  w w  w  .  ja  v a  2 s  . c  o  m
            sessionPromise.setFailure(future.cause());
        }
    });
}

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

License:Apache License

private void initSession(SessionProtocol protocol, ChannelFuture connectFuture,
        Promise<Channel> sessionPromise) {
    assert connectFuture.isSuccess();

    final Channel ch = connectFuture.channel();
    final EventLoop eventLoop = ch.eventLoop();
    assert eventLoop.inEventLoop();

    final ScheduledFuture<?> timeoutFuture = eventLoop.schedule(() -> {
        if (sessionPromise.tryFailure(new SessionProtocolNegotiationException(protocol,
                "connection established, but session creation timed out: " + ch))) {
            ch.close();//w  w w  .j a  va  2 s . c  o m
        }
    }, options.connectTimeoutMillis(), TimeUnit.MILLISECONDS);

    ch.pipeline().addLast(new HttpSessionHandler(this, ch, sessionPromise, timeoutFuture));
}

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

License:Apache License

/**
 * Invoked on each write of an {@link HttpObject}.
 *//*from  ww  w .  j  a  v a 2 s.  co m*/
@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.client.HttpSessionChannelFactory.java

License:Apache License

private void initSession(SessionProtocol protocol, ChannelFuture connectFuture,
        Promise<Channel> sessionPromise) {
    assert connectFuture.isSuccess();

    final Channel ch = connectFuture.channel();
    final EventLoop eventLoop = ch.eventLoop();
    assert eventLoop.inEventLoop();

    final ScheduledFuture<?> timeoutFuture = eventLoop.schedule(() -> {
        if (sessionPromise.tryFailure(new SessionProtocolNegotiationException(protocol,
                "connection established, but session creation timed out: " + ch))) {
            ch.close();//from  w w w .  j  a v a  2  s .  c  om
        }
    }, connectTimeoutMillis, TimeUnit.MILLISECONDS);

    ch.pipeline().addLast(new HttpSessionHandler(this, ch, sessionPromise, timeoutFuture));
}

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  av  a 2 s . c om
        }
        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;/*from w  ww . j  av a2  s.  c o  m*/
        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 ww  .  j  av a  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());
    }
}

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

License:Open Source License

/**
 * Stop proxy server//w ww  . j  av a 2s  .c  om
 * */
public void stop() {
    ChannelGroupFuture future = _allChannels.close().awaitUninterruptibly();
    if (!future.isSuccess()) {
        final Iterator<ChannelFuture> iter = future.iterator();
        while (iter.hasNext()) {
            final ChannelFuture cf = iter.next();
            if (!cf.isSuccess()) {
                LOG.warn(String.format("Failed to close channel %s because %s", cf.channel(), cf.cause()));
            }
        }
    }
    _acceptorGroup.shutdownGracefully();
    _upstreamWorkerGroup.shutdownGracefully();
    _downstreamWorkerGroup.shutdownGracefully();
}