Example usage for io.netty.channel ChannelHandlerContext fireChannelRead

List of usage examples for io.netty.channel ChannelHandlerContext fireChannelRead

Introduction

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

Prototype

@Override
    ChannelHandlerContext fireChannelRead(Object msg);

Source Link

Usage

From source file:io.airlift.drift.transport.netty.ThriftClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext context, Object message) throws Exception {
    if (message instanceof ByteBuf && ((ByteBuf) message).isReadable()) {
        ByteBuf response = (ByteBuf) message;
        if (response.isReadable()) {
            messageReceived(context, response);
            return;
        }//ww  w. j av  a 2s .co m
    }
    context.fireChannelRead(message);
}

From source file:io.aos.netty5.socksproxy.SocksServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception {
    switch (socksRequest.protocolVersion()) {
    case SOCKS4a:
        Socks4CmdRequest socksV4CmdRequest = (Socks4CmdRequest) socksRequest;
        if (socksV4CmdRequest.cmdType() == Socks4CmdType.CONNECT) {
            ctx.pipeline().addLast(new SocksServerConnectHandler());
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(socksRequest);
        } else {// w  w w .  j  av a  2 s . co m
            ctx.close();
        }
        break;
    case SOCKS5:
        switch (((Socks5Request) socksRequest).requestType()) {
        case INIT: {
            // auth support example
            //ctx.pipeline().addFirst(new SocksV5AuthRequestDecoder());
            //ctx.write(new SocksV5InitResponse(SocksV5AuthScheme.AUTH_PASSWORD));
            ctx.pipeline().addFirst(new Socks5CmdRequestDecoder());
            ctx.write(new Socks5InitResponse(Socks5AuthScheme.NO_AUTH));
            break;
        }
        case AUTH:
            ctx.pipeline().addFirst(new Socks5CmdRequestDecoder());
            ctx.write(new Socks5AuthResponse(Socks5AuthStatus.SUCCESS));
            break;
        case CMD:
            Socks5CmdRequest socks5CmdRequest = (Socks5CmdRequest) socksRequest;
            if (socks5CmdRequest.cmdType() == Socks5CmdType.CONNECT) {
                ctx.pipeline().addLast(new SocksServerConnectHandler());
                ctx.pipeline().remove(this);
                ctx.fireChannelRead(socksRequest);
            } else {
                ctx.close();
            }
            break;
        case UNKNOWN:
            ctx.close();
            break;
        }
        break;
    case UNKNOWN:
        ctx.close();
        break;
    }
}

From source file:io.blobkeeper.server.handler.FileDeleteHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception {
    setContext();/*from   ww w.  j a v a  2s  . co m*/

    if (request.getMethod() == POST) {
        context.fireChannelRead(request.copy());
        return;
    }

    addWriterBack(context);

    if (log.isTraceEnabled()) {
        log.trace("Request is: {}", request);
    }

    if (request.getUri().equals("/favicon.ico")) {
        sendError(context, NOT_FOUND, createError(INVALID_REQUEST, "No favorite icon here"));
        return;
    }

    if (!request.getDecoderResult().isSuccess()) {
        sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "Strange request given"));
        return;
    }

    if (request.getMethod() != DELETE) {
        sendError(context, METHOD_NOT_ALLOWED,
                createError(INVALID_REQUEST, "Only DELETE requests are acceptable"));
        return;
    }

    handleApiRequest(context, request);
}

From source file:io.blobkeeper.server.handler.FileReaderHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception {
    setContext();//from   w w w  .j a  va  2 s  . c o  m

    if (request.getMethod() == POST) {
        context.fireChannelRead(request.copy());
        return;
    }

    if (request.getMethod() == DELETE) {
        context.fireChannelRead(request.copy());
        return;
    }

    addWriterBack(context);

    if (log.isTraceEnabled()) {
        log.trace("Request is: {}", request);
    }

    if (request.getUri().equals("/favicon.ico")) {
        sendError(context, HttpResponseStatus.NOT_FOUND, createError(INVALID_REQUEST, "No favorite icon here"));
        return;
    }

    if (!request.getDecoderResult().isSuccess()) {
        sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "Strange request given"));
        return;
    }

    if (request.getMethod() != GET) {
        sendError(context, METHOD_NOT_ALLOWED,
                createError(INVALID_REQUEST, "Only GET requests are acceptable"));
        return;
    }

    String uri = request.getUri();
    final long fileId = getId(uri);
    final int typeId = getType(uri);

    if (NOT_FOUND == fileId) {
        if (tryHandleApiRequest(context, request)) {
            return;
        } else {
            log.error("No id");
            sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "No id"));
            return;
        }
    }

    if (NOT_FOUND == typeId) {
        log.error("No type id");
        sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "No type id"));
        return;
    }

    File readerFile = null;
    IndexElt indexElt;
    boolean modified;
    try {
        log.debug("Id {}", fileId);

        indexElt = indexService.getById(fileId, typeId);
        log.debug("Index elt is {}", indexElt);

        if (null != indexElt) {
            if (indexElt.isDeleted()) {
                sendError(context, GONE, createError(DELETED, "File was deleted"));
                return;
            }

            if (indexElt.isAuthRequired()) {
                String authToken = MetadataParser.getAuthToken(request);
                if (authToken == null || !indexElt.isAllowed(authToken)) {
                    log.error("You have no permission to see this file {} : token {}", indexElt.getId(),
                            authToken);
                    sendError(context, HttpResponseStatus.FORBIDDEN,
                            createError(ErrorCode.FORBIDDEN, "You have no permission to see this file"));
                    return;
                }
            }

            modified = isModified(indexElt, request);

            if (modified) {
                readerFile = fileStorage.getFile(indexElt);
            }
        } else {
            log.error("Index elt not found");
            sendError(context, HttpResponseStatus.NOT_FOUND,
                    createError(INVALID_REQUEST, "Index elt not found"));
            return;
        }
    } catch (Exception e) {
        log.error("Unknown error", e);
        sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, "Unknown error"));
        return;
    }

    if (!modified) {
        sendNotModified(context, indexElt, request);
        return;
    }

    if (null == readerFile) {
        log.error("Can't find reader file");
        sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, "No reader file"));
        return;
    }

    if (readerFile.getLength() - indexElt.getOffset() < indexElt.getLength()) {
        String errorMessage = String.format("Reader file length less than index elt %s < %s",
                readerFile.getLength() - indexElt.getOffset(), indexElt.getLength());
        log.error(errorMessage);
        sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, errorMessage));
        return;
    }

    if (FileUtils.isFileEmpty(readerFile, indexElt)) {
        String errorMessage = String.format("File %s is empty", indexElt);
        log.error(errorMessage);
        sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, errorMessage));
        return;
    }

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    MetadataParser.copyMetadata(indexElt.getHeaders(), response);

    addCacheHeaders(response, indexElt);

    setContentLength(response, indexElt.getLength());

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

    context.write(response);

    // Write the content.
    context.write(
            new UnClosableFileRegion(readerFile.getFileChannel(), indexElt.getOffset(), indexElt.getLength()),
            context.voidPromise());

    // Write the end marker
    ChannelFuture lastContentFuture = context.writeAndFlush(EMPTY_LAST_CONTENT);

    if (!isKeepAlive(request)) {
        lastContentFuture.addListener(CLOSE);
    }
}

From source file:io.blobkeeper.server.handler.FileWriterHandler.java

License:Apache License

private void jumpToDeleter(ChannelHandlerContext context, HttpObject object) {
    context.pipeline().addBefore("deleter", "aggregator", new HttpObjectAggregator(65536));
    context.pipeline().remove(FileWriterHandler.class);
    context.fireChannelRead(object);
}

From source file:io.blobkeeper.server.handler.FileWriterHandler.java

License:Apache License

private void jumpToReader(ChannelHandlerContext context, HttpObject object) {
    context.pipeline().addBefore("reader", "aggregator", new HttpObjectAggregator(65536));
    context.pipeline().remove(this);
    context.fireChannelRead(object);
}

From source file:io.cettia.asity.bridge.netty4.AsityServerCodec.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        if (!accept(req)) {
            ctx.fireChannelRead(msg);
            return;
        }/*from   ww  w. ja va 2 s . c o  m*/
        if (req.getMethod() == HttpMethod.GET
                && req.headers().contains(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET, true)) {
            // Because WebSocketServerHandshaker requires FullHttpRequest
            FullHttpRequest wsRequest = new DefaultFullHttpRequest(req.getProtocolVersion(), req.getMethod(),
                    req.getUri());
            wsRequest.headers().set(req.headers());
            wsReqMap.put(ctx.channel(), wsRequest);
            // Set timeout to avoid memory leak
            ctx.pipeline().addFirst(new ReadTimeoutHandler(5));
        } else {
            NettyServerHttpExchange http = new NettyServerHttpExchange(ctx, req);
            httpMap.put(ctx.channel(), http);
            httpActions.fire(http);
        }
    } else if (msg instanceof HttpContent) {
        FullHttpRequest wsReq = wsReqMap.get(ctx.channel());
        if (wsReq != null) {
            wsReq.content().writeBytes(((HttpContent) msg).content());
            if (msg instanceof LastHttpContent) {
                wsReqMap.remove(ctx.channel());
                // Cancel timeout
                ctx.pipeline().remove(ReadTimeoutHandler.class);
                WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(
                        getWebSocketLocation(ctx.pipeline(), wsReq), null, true);
                WebSocketServerHandshaker handshaker = factory.newHandshaker(wsReq);
                if (handshaker == null) {
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                } else {
                    handshaker.handshake(ctx.channel(), wsReq);
                    NettyServerWebSocket ws = new NettyServerWebSocket(ctx, wsReq, handshaker);
                    wsMap.put(ctx.channel(), ws);
                    wsActions.fire(ws);
                }
            }
        } else {
            NettyServerHttpExchange http = httpMap.get(ctx.channel());
            if (http != null) {
                http.handleChunk((HttpContent) msg);
            }
        }
    } else if (msg instanceof WebSocketFrame) {
        NettyServerWebSocket ws = wsMap.get(ctx.channel());
        if (ws != null) {
            ws.handleFrame((WebSocketFrame) msg);
        }
    }
}

From source file:io.crate.mqtt.netty.ClientNettyMQTTHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
    if (callback != null) {
        callback.set((MqttMessage) message);
    }/*from   w w w  .ja  va  2  s. co  m*/
    ctx.fireChannelRead(message);
}

From source file:io.crate.mqtt.netty.MqttMessageLogger.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
    logMQTTMessage(ctx, message, DIRECTION_READ);
    ctx.fireChannelRead(message);
}

From source file:io.crate.protocols.http.HttpAuthUpstreamHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        handleHttpRequest(ctx, (HttpRequest) msg);
    } else if (msg instanceof HttpContent) {
        handleHttpChunk(ctx, ((HttpContent) msg));
    } else {//ww  w .  j a v  a 2  s.  co m
        // neither http request nor http chunk - send upstream and see ...
        ctx.fireChannelRead(msg);
    }
}