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:org.apache.tinkerpop.gremlin.driver.handler.WebSocketClientHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    final Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        // web socket client connected
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        handshakeFuture.setSuccess();//from  ww w.ja  v  a  2s  .c o  m
        return;
    }

    if (msg instanceof FullHttpResponse) {
        final FullHttpResponse response = (FullHttpResponse) msg;
        throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content="
                + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    // a close frame doesn't mean much here.  errors raised from closed channels will mark the host as dead
    final WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        ctx.fireChannelRead(frame.retain(2));
    } else if (frame instanceof PongWebSocketFrame) {
        logger.debug("Received response from keep-alive request");
    } else if (frame instanceof BinaryWebSocketFrame) {
        ctx.fireChannelRead(frame.retain(2));
    } else if (frame instanceof CloseWebSocketFrame)
        ch.close();

}

From source file:org.apache.tinkerpop.gremlin.server.handler.HttpBasicAuthenticationHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof FullHttpMessage) {
        final FullHttpMessage request = (FullHttpMessage) msg;
        if (!request.headers().contains("Authorization")) {
            sendError(ctx, msg);//from   w ww. j  a  v a  2s.  co  m
            return;
        }

        // strip off "Basic " from the Authorization header (RFC 2617)
        final String basic = "Basic ";
        final String authorizationHeader = request.headers().get("Authorization");
        if (!authorizationHeader.startsWith(basic)) {
            sendError(ctx, msg);
            return;
        }
        byte[] decodedUserPass = null;
        try {
            final String encodedUserPass = authorizationHeader.substring(basic.length());
            decodedUserPass = decoder.decode(encodedUserPass);
        } catch (IndexOutOfBoundsException iae) {
            sendError(ctx, msg);
            return;
        } catch (IllegalArgumentException iae) {
            sendError(ctx, msg);
            return;
        }
        final String authorization = new String(decodedUserPass, Charset.forName("UTF-8"));
        final String[] split = authorization.split(":");
        if (split.length != 2) {
            sendError(ctx, msg);
            return;
        }

        final Map<String, String> credentials = new HashMap<>();
        credentials.put(PROPERTY_USERNAME, split[0]);
        credentials.put(PROPERTY_PASSWORD, split[1]);

        try {
            authenticator.authenticate(credentials);
            ctx.fireChannelRead(request);
        } catch (AuthenticationException ae) {
            sendError(ctx, msg);
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.SaslAndHttpBasicAuthenticationHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) throws Exception {
    if (obj instanceof HttpMessage && !WebSocketHandlerUtil.isWebSocket((HttpMessage) obj)) {
        if (null == ctx.pipeline().get(HTTP_AUTH)) {
            ctx.pipeline().addAfter(PIPELINE_AUTHENTICATOR, HTTP_AUTH,
                    new HttpBasicAuthenticationHandler(authenticator, this.authenticationSettings));
        }/*from   w  w  w  .  j av  a2  s. c o m*/
        ctx.fireChannelRead(obj);
    } else {
        super.channelRead(ctx, obj);
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.SaslAuthenticationHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    if (msg instanceof RequestMessage) {
        final RequestMessage requestMessage = (RequestMessage) msg;

        final Attribute<Authenticator.SaslNegotiator> negotiator = ctx.attr(StateKey.NEGOTIATOR);
        final Attribute<RequestMessage> request = ctx.attr(StateKey.REQUEST_MESSAGE);
        if (negotiator.get() == null) {
            // First time through so save the request and send an AUTHENTICATE challenge with no data
            negotiator.set(authenticator.newSaslNegotiator(getRemoteInetAddress(ctx)));
            request.set(requestMessage);
            final ResponseMessage authenticate = ResponseMessage.build(requestMessage)
                    .code(ResponseStatusCode.AUTHENTICATE).create();
            ctx.writeAndFlush(authenticate);
        } else {/*from  w  ww .j  a v  a  2  s . co  m*/
            if (requestMessage.getOp().equals(Tokens.OPS_AUTHENTICATION)
                    && requestMessage.getArgs().containsKey(Tokens.ARGS_SASL)) {

                final Object saslObject = requestMessage.getArgs().get(Tokens.ARGS_SASL);
                final byte[] saslResponse;

                if (saslObject instanceof byte[]) {
                    saslResponse = (byte[]) saslObject;
                } else if (saslObject instanceof String) {
                    saslResponse = BASE64_DECODER.decode((String) saslObject);
                } else {
                    final ResponseMessage error = ResponseMessage.build(request.get())
                            .statusMessage("Incorrect type for : " + Tokens.ARGS_SASL
                                    + " - byte[] or base64 encoded String is expected")
                            .code(ResponseStatusCode.REQUEST_ERROR_MALFORMED_REQUEST).create();
                    ctx.writeAndFlush(error);
                    return;
                }

                try {
                    final byte[] saslMessage = negotiator.get().evaluateResponse(saslResponse);
                    if (negotiator.get().isComplete()) {
                        // todo: do something with this user
                        final AuthenticatedUser user = negotiator.get().getAuthenticatedUser();

                        // If we have got here we are authenticated so remove the handler and pass
                        // the original message down the pipeline for processing
                        ctx.pipeline().remove(this);
                        final RequestMessage original = request.get();
                        ctx.fireChannelRead(original);
                    } else {
                        // not done here - send back the sasl message for next challenge. note that we send back
                        // the base64 encoded sasl as well as the byte array. the byte array will eventually be
                        // phased out, but is present now for backward compatibility in 3.2.x
                        final Map<String, Object> metadata = new HashMap<>();
                        metadata.put(Tokens.ARGS_SASL, BASE64_ENCODER.encodeToString(saslMessage));
                        final ResponseMessage authenticate = ResponseMessage.build(requestMessage)
                                .statusAttributes(metadata).code(ResponseStatusCode.AUTHENTICATE)
                                .result(saslMessage).create();
                        ctx.writeAndFlush(authenticate);
                    }
                } catch (AuthenticationException ae) {
                    final ResponseMessage error = ResponseMessage.build(request.get())
                            .statusMessage(ae.getMessage()).code(ResponseStatusCode.UNAUTHORIZED).create();
                    ctx.writeAndFlush(error);
                }
            } else {
                final ResponseMessage error = ResponseMessage.build(requestMessage)
                        .statusMessage("Failed to authenticate").code(ResponseStatusCode.UNAUTHORIZED).create();
                ctx.writeAndFlush(error);
            }
        }
    } else {
        logger.warn("{} only processes RequestMessage instances - received {} - channel closing",
                this.getClass().getSimpleName(), msg.getClass());
        ctx.close();
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.WsAndHttpChannelizerHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) {
    final ChannelPipeline pipeline = ctx.pipeline();
    if (obj instanceof HttpMessage && !WebSocketHandlerUtil.isWebSocket((HttpMessage) obj)) {
        if (null != pipeline.get(PIPELINE_AUTHENTICATOR)) {
            pipeline.remove(PIPELINE_REQUEST_HANDLER);
            final ChannelHandler authenticator = pipeline.get(PIPELINE_AUTHENTICATOR);
            pipeline.remove(PIPELINE_AUTHENTICATOR);
            pipeline.addAfter(PIPELINE_HTTP_RESPONSE_ENCODER, PIPELINE_AUTHENTICATOR, authenticator);
            pipeline.addAfter(PIPELINE_AUTHENTICATOR, PIPELINE_REQUEST_HANDLER,
                    this.httpGremlinEndpointHandler);
        } else {/*from   w  w  w  .  j  a va2s . co m*/
            pipeline.remove(PIPELINE_REQUEST_HANDLER);
            pipeline.addAfter(PIPELINE_HTTP_RESPONSE_ENCODER, PIPELINE_REQUEST_HANDLER,
                    this.httpGremlinEndpointHandler);
        }
    }
    ctx.fireChannelRead(obj);
}

From source file:org.artJava.protocol.client.handlers.HeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Message message = (Message) msg;/*from w  w w . ja va  2 s .co  m*/
    // ?????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 50000,
                TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        System.out.println("Client receive server heart beat message : ---> " + message);
    } else
        ctx.fireChannelRead(msg);
}

From source file:org.artJava.protocol.server.handlers.HeartBeatRespHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    Message message = (Message) msg;/*from  w  w  w .  j  a  v a 2s  .co m*/
    // ?
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {
        System.out.println("Receive client heart beat message : ---> " + message);
        Message heartBeat = buildHeatBeat();
        System.out.println("Send heart beat response message to client : ---> " + heartBeat);
        ctx.writeAndFlush(heartBeat);
    } else
        ctx.fireChannelRead(msg);
}

From source file:org.asynchttpclient.netty.handler.AsyncHttpClientHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

    Channel channel = ctx.channel();
    Object attribute = Channels.getAttribute(channel);

    try {/*from   w  w  w .  j  av a 2 s.co m*/
        if (attribute instanceof Callback) {
            Callback ac = (Callback) attribute;
            if (msg instanceof LastHttpContent) {
                ac.call();
            } else if (!(msg instanceof HttpContent)) {
                logger.info("Received unexpected message while expecting a chunk: " + msg);
                ac.call();
                Channels.setDiscard(channel);
            }

        } else if (attribute instanceof NettyResponseFuture) {
            NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;
            handleRead(channel, future, msg);

        } else if (attribute instanceof StreamedResponsePublisher) {

            StreamedResponsePublisher publisher = (StreamedResponsePublisher) attribute;

            if (msg instanceof HttpContent) {
                ByteBuf content = ((HttpContent) msg).content();
                // Republish as a HttpResponseBodyPart
                if (content.readableBytes() > 0) {
                    HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(content,
                            false);
                    ctx.fireChannelRead(part);
                }
                if (msg instanceof LastHttpContent) {
                    // Remove the handler from the pipeline, this will trigger
                    // it to finish
                    ctx.pipeline().remove(publisher);
                    // Trigger a read, just in case the last read complete
                    // triggered no new read
                    ctx.read();
                    // Send the last content on to the protocol, so that it can
                    // conclude the cleanup
                    handleRead(channel, publisher.future(), msg);
                }
            } else {
                logger.info("Received unexpected message while expecting a chunk: " + msg);
                ctx.pipeline().remove(publisher);
                Channels.setDiscard(channel);
            }
        } else if (attribute != DiscardEvent.INSTANCE) {
            // unhandled message
            logger.debug("Orphan channel {} with attribute {} received message {}, closing", channel, attribute,
                    msg);
            Channels.silentlyCloseChannel(channel);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:org.beaconmc.network.socket.pipeline.PacketLegacy.java

License:Open Source License

@Override
protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {

    byteBuf.markReaderIndex();/*  www  . ja va  2  s  . c  om*/
    boolean repliedPing = true;

    try {
        short packetId = byteBuf.readUnsignedByte();
        if (packetId == 254) {
            int length = byteBuf.readableBytes();
            AsyncServerPingEvent asyncServerPingEvent = EventFactory
                    .callAsyncServerPingEvent(this.server.createServerPing());
            if (asyncServerPingEvent.getPing() != null) {
                switch (length) {
                case 0:
                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("%s%d%d",
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                case 1:
                    if (byteBuf.readUnsignedByte() != 1) {
                        return;
                    }
                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("1\0%d\0%s\0%s\0%d\0%d", 127,
                                    asyncServerPingEvent.getPing().getVersion().getName(),
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                default:
                    boolean checkFlag = byteBuf.readUnsignedByte() == 1;
                    checkFlag &= byteBuf.readUnsignedByte() == 250;
                    checkFlag &= "MC|PingHost".equals(
                            new String(byteBuf.readBytes(byteBuf.readShort() * 2).array(), Charsets.UTF_16));

                    int checkShort = byteBuf.readShort();

                    checkFlag &= byteBuf.readUnsignedByte() >= 73;
                    checkFlag &= 3 + byteBuf.readBytes(byteBuf.readShort() * 2).array().length
                            + 4 == checkShort;
                    checkFlag &= byteBuf.readInt() <= '\uffff';
                    checkFlag &= byteBuf.readableBytes() == 0;

                    if (!checkFlag) {
                        return;
                    }

                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("1\0%d\0%s\0%s\0%d\0%d", 127,
                                    asyncServerPingEvent.getPing().getVersion().getName(),
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                }
            } else {
                this.close(channelHandlerContext);
            }
            repliedPing = false;
        } else if (packetId == 0x02 && byteBuf.isReadable()) {
            this.sendPingAndClose(channelHandlerContext, this.toArray(ChatColor.RED + "Outdated Client"));
            repliedPing = false;
        }
    } catch (Exception e) {
        return;
    } finally {
        if (repliedPing) {
            byteBuf.resetReaderIndex();
            channelHandlerContext.channel().pipeline().remove("legacy_ping");
            channelHandlerContext.fireChannelRead(byteBuf.retain());
        }
    }
}

From source file:org.betawares.jorre.handlers.client.ClientMessageInspector.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.info(msg);//w ww . j a v  a2s  . c  om
    ctx.fireChannelRead(msg);
}