List of usage examples for io.netty.channel ChannelHandlerContext fireChannelRead
@Override ChannelHandlerContext fireChannelRead(Object msg);
From source file:io.reactivesocket.transport.tcp.ReactiveSocketFrameCodec.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { try {/*from ww w . j a va 2s . co m*/ buffer.wrap((ByteBuf) msg); frame.wrap(buffer, 0); ctx.fireChannelRead(frame); } finally { ReferenceCountUtil.release(msg); } } else { super.channelRead(ctx, msg); } }
From source file:io.reactivex.netty.pipeline.ByteArrayPipelineConfigurator.java
License:Apache License
@Override public void configureNewPipeline(ChannelPipeline pipeline) { pipeline.addLast(new ChannelDuplexHandler() { @Override//from w ww . ja va 2 s . co m public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { boolean handled = false; if (ByteBuf.class.isAssignableFrom(msg.getClass())) { ByteBuf byteBuf = (ByteBuf) msg; if (byteBuf.isReadable()) { int readableBytes = byteBuf.readableBytes(); byte[] msgToPass = new byte[readableBytes]; byteBuf.readBytes(msgToPass); handled = true; ctx.fireChannelRead(msgToPass); } } if (!handled) { super.channelRead(ctx, msg); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof byte[]) { byte[] msgAsBytes = (byte[]) msg; ByteBuf byteBuf = ctx.alloc().buffer(msgAsBytes.length).writeBytes(msgAsBytes); super.write(ctx, byteBuf, promise); } else { super.write(ctx, msg, promise); // pass-through } } }); }
From source file:io.reactivex.netty.protocol.http.sse.SseChannelHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse) { /**//from w ww . ja v a 2 s .co m * Since SSE is an endless stream, we can never reuse a connection and hence as soon as SSE traffic is * received, the connection is marked as discardable on close. */ ctx.channel().attr(ClientRequestResponseConverter.DISCARD_CONNECTION).set(true); // SSE traffic should always discard connection on close. ChannelPipeline pipeline = ctx.channel().pipeline(); if (!HttpHeaders.isTransferEncodingChunked((HttpResponse) msg)) { pipeline.addFirst(SSE_DECODER_HANDLER_NAME, new ServerSentEventDecoder()); /* * If there are buffered messages in the previous handler at the time this message is read, we would * not be able to convert the content into an SseEvent. For this reason, we also add the decoder after * this handler, so that we can handle the buffered messages. * See the class level javadoc for more details. */ pipeline.addAfter(NAME, SSE_DECODER_POST_INBOUND_HANDLER, new ServerSentEventDecoder()); } else { pipeline.addAfter(NAME, SSE_DECODER_HANDLER_NAME, new ServerSentEventDecoder()); } ctx.fireChannelRead(msg); } else if (msg instanceof LastHttpContent) { LastHttpContent lastHttpContent = (LastHttpContent) msg; /** * The entire pipeline is set based on the assumption that LastHttpContent signals the end of the stream. * Since, here we are only passing the content to the rest of the pipeline, it becomes imperative to * also pass LastHttpContent as such. * For this reason, we send the LastHttpContent again in the pipeline. For this event sent, the content * buffer will already be read and hence will not be read again. This message serves as only containing * the trailing headers. * However, we need to increment the ref count of the content so that the assumptions down the line of the * ByteBuf always being released by the last pipeline handler will not break (as ServerSentEventDecoder releases * the ByteBuf after read). */ lastHttpContent.content().retain(); // pseudo retain so that the last handler of the pipeline can release it. if (lastHttpContent.content().isReadable()) { ctx.fireChannelRead(lastHttpContent.content()); } ctx.fireChannelRead(msg); // Since the content is already consumed above (by the SSEDecoder), this is just // as sending just trailing headers. This is critical to mark the end of stream. } else if (msg instanceof HttpContent) { ctx.fireChannelRead(((HttpContent) msg).content()); } else { ctx.fireChannelRead(msg); } }
From source file:io.reactivex.netty.protocol.http.sse.SSEInboundHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse) { ChannelPipeline pipeline = ctx.channel().pipeline(); if (!HttpHeaders.isTransferEncodingChunked((HttpResponse) msg)) { pipeline.addFirst(SSE_DECODER_HANDLER_NAME, new ServerSentEventDecoder()); /*//from w w w . j a va 2 s. c o m * If there are buffered messages in the previous handler at the time this message is read, we would * not be able to convert the content into an SseEvent. For this reason, we also add the decoder after * this handler, so that we can handle the buffered messages. * See the class level javadoc for more details. */ pipeline.addAfter(NAME, SSE_DECODER_POST_INBOUND_HANDLER, new ServerSentEventDecoder()); } else { pipeline.addAfter(NAME, SSE_DECODER_HANDLER_NAME, new ServerSentEventDecoder()); } ctx.fireChannelRead(msg); } else if (msg instanceof LastHttpContent) { LastHttpContent lastHttpContent = (LastHttpContent) msg; /** * The entire pipeline is set based on the assumption that LastHttpContent signals the end of the stream. * Since, here we are only passing the content to the rest of the pipeline, it becomes imperative to * also pass LastHttpContent as such. * For this reason, we send the LastHttpContent again in the pipeline. For this event sent, the content * buffer will already be read and hence will not be read again. This message serves as only containing * the trailing headers. * However, we need to increment the ref count of the content so that the assumptions down the line of the * ByteBuf always being released by the last pipeline handler will not break (as ServerSentEventDecoder releases * the ByteBuf after read). */ lastHttpContent.content().retain(); // pseudo retain so that the last handler of the pipeline can release it. if (lastHttpContent.content().isReadable()) { ctx.fireChannelRead(lastHttpContent.content()); } ctx.fireChannelRead(msg); // Since the content is already consumed above (by the SSEDecoder), this is just // as sending just trailing headers. This is critical to mark the end of stream. } else if (msg instanceof HttpContent) { ctx.fireChannelRead(((HttpContent) msg).content()); } else { ctx.fireChannelRead(msg); } }
From source file:io.reactivex.netty.protocol.http.websocket.WebSocketClientHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel();//from ww w. j a va 2 s. c o m if (!handshaker.isHandshakeComplete()) { finishHandshake(ctx, (FullHttpResponse) msg, ch); } else { ctx.fireChannelRead(msg); } }
From source file:io.reactivex.netty.protocol.http.websocket.WebSocketServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { ChannelFuture upgradeFuture = handleHttpRequest(ctx, (FullHttpRequest) msg); if (upgradeFuture != null) { updatePipeline(ctx);// w ww .j a v a 2 s. co m upgradeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { handshakeFuture.setSuccess(); eventsSubject.onEvent(WebSocketServerMetricsEvent.HANDSHAKE_PROCESSED); } else { handshakeFuture.setFailure(future.cause()); eventsSubject.onEvent(WebSocketServerMetricsEvent.HANDSHAKE_FAILURE); } } }); } } else { ctx.fireChannelRead(msg); } }
From source file:io.reactivex.netty.RxEventPipelineConfigurator.java
License:Apache License
@Override public void configureNewPipeline(ChannelPipeline pipeline) { pipeline.addLast(new ChannelDuplexHandler() { @Override/* www . j a v a 2s . c o m*/ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { boolean handled = false; if (ByteBuf.class.isAssignableFrom(msg.getClass())) { ByteBuf byteBuf = (ByteBuf) msg; if (byteBuf.isReadable()) { int protocolVersion = byteBuf.readByte(); if (protocolVersion != PROTOCOL_VERSION) { throw new RuntimeException("Unsupported protocol version: " + protocolVersion); } int observableNameLength = byteBuf.readByte(); String observableName = null; if (observableNameLength > 0) { // read name observableName = new String(byteBuf.readBytes(observableNameLength).array()); } int operation = byteBuf.readByte(); RemoteRxEvent.Type type = null; Map<String, String> subscribeParams = null; byte[] valueData = null; if (operation == 1) { logger.debug("READ request for RemoteRxEvent: next"); type = RemoteRxEvent.Type.next; valueData = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(valueData); } else if (operation == 2) { logger.debug("READ request for RemoteRxEvent: error"); type = RemoteRxEvent.Type.error; valueData = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(valueData); } else if (operation == 3) { logger.debug("READ request for RemoteRxEvent: completed"); type = RemoteRxEvent.Type.completed; } else if (operation == 4) { logger.debug("READ request for RemoteRxEvent: subscribed"); type = RemoteRxEvent.Type.subscribed; // read subscribe parameters int subscribeParamsLength = byteBuf.readInt(); if (subscribeParamsLength > 0) { // read byte into map byte[] subscribeParamsBytes = new byte[subscribeParamsLength]; byteBuf.readBytes(subscribeParamsBytes); subscribeParams = fromBytesToMap(subscribeParamsBytes); } } else if (operation == 5) { logger.debug("READ request for RemoteRxEvent: unsubscribed"); type = RemoteRxEvent.Type.unsubscribed; } else { throw new RuntimeException("operation: " + operation + " not support."); } handled = true; byteBuf.release(); ctx.fireChannelRead(new RemoteRxEvent(observableName, type, valueData, subscribeParams)); } } if (!handled) { super.channelRead(ctx, msg); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof RemoteRxEvent) { ByteBuf buf = ctx.alloc().buffer(); buf.writeByte(PROTOCOL_VERSION); RemoteRxEvent event = (RemoteRxEvent) msg; String observableName = event.getName(); if (observableName != null && !observableName.isEmpty()) { // write length int nameLength = observableName.length(); if (nameLength < 127) { buf.writeByte(nameLength); buf.writeBytes(observableName.getBytes()); } else { throw new RuntimeException( "observableName " + observableName + " exceeds max limit of 127 characters"); } } else { // no name provided, write 0 bytes for name length buf.writeByte(0); } if (event.getType() == RemoteRxEvent.Type.next) { logger.debug("WRITE request for RemoteRxEvent: next"); buf.writeByte(1); buf.writeBytes(event.getData()); super.write(ctx, buf, promise); } else if (event.getType() == RemoteRxEvent.Type.error) { logger.debug("WRITE request for RemoteRxEvent: error"); buf.writeByte(2); buf.writeBytes(event.getData()); super.write(ctx, buf, promise); } else if (event.getType() == RemoteRxEvent.Type.completed) { logger.debug("WRITE request for RemoteRxEvent: completed"); buf.writeByte(3); super.write(ctx, buf, promise); super.flush(ctx); // TODO why do I need to explicitly call flush for this to work??? empty data?? } else if (event.getType() == RemoteRxEvent.Type.subscribed) { logger.debug("WRITE request for RemoteRxEvent: subscribed"); buf.writeByte(4); Map<String, String> subscribeParameters = event.getSubscribeParameters(); if (subscribeParameters != null && !subscribeParameters.isEmpty()) { byte[] subscribeBytes = fromMapToBytes(subscribeParameters); buf.writeInt(subscribeBytes.length); // write int for length buf.writeBytes(subscribeBytes); // write data } else { buf.writeInt(0); // no data } super.write(ctx, buf, promise); super.flush(ctx); } else if (event.getType() == RemoteRxEvent.Type.unsubscribed) { logger.debug("WRITE request for RemoteRxEvent: unsubscribed"); buf.writeByte(5); super.write(ctx, buf, promise); super.flush(ctx); // TODO why do I need to explicitly call flush for this to work??? empty data?? } } else { super.write(ctx, msg, promise); } } }); }
From source file:io.scalecube.socketio.pipeline.DisconnectHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { final HttpRequest req = (HttpRequest) msg; final HttpMethod requestMethod = req.getMethod(); final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); final String requestPath = queryDecoder.path(); boolean disconnect = queryDecoder.parameters().containsKey(DISCONNECT); if (disconnect) { if (log.isDebugEnabled()) log.debug("Received HTTP disconnect request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel()); final String sessionId = PipelineUtils.getSessionId(requestPath); final Packet disconnectPacket = new Packet(PacketType.DISCONNECT, sessionId); disconnectPacket.setOrigin(PipelineUtils.getOrigin(req)); ctx.fireChannelRead(disconnectPacket); ReferenceCountUtil.release(msg); return; }/*from w w w .j a v a2s. com*/ } ctx.fireChannelRead(msg); }
From source file:io.scalecube.socketio.pipeline.FlashPolicyHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // ?//w ww .ja v a2s .c om if (msg instanceof ByteBuf) { ByteBuf message = (ByteBuf) msg; if (message.readableBytes() >= policyRequestBuffer.readableBytes()) { ByteBuf data = message.slice(0, policyRequestBuffer.readableBytes()); if (data.equals(policyRequestBuffer)) { // Remove SSL handler from pipeline otherwise on channel close SSL handler // will fail all pending writes instead of flushing them and as a result // client won't get flash policy file. if (ctx.pipeline().get(SocketIOChannelInitializer.SSL_HANDLER) != null) { ctx.pipeline().remove(SocketIOChannelInitializer.SSL_HANDLER); } // Send flash policy file and close connection ByteBuf response = PipelineUtils.copiedBuffer(ctx.alloc(), policyResponse); ChannelFuture f = ctx.writeAndFlush(response); f.addListener(ChannelFutureListener.CLOSE); if (log.isDebugEnabled()) log.debug("Sent flash policy file to channel: {}", ctx.channel()); message.release(); return; } } ctx.pipeline().remove(this); } ctx.fireChannelRead(msg); }
From source file:io.scalecube.socketio.pipeline.JsonpPollingHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // ?/* ww w. j a v a 2s .com*/ if (msg instanceof FullHttpRequest) { final FullHttpRequest req = (FullHttpRequest) msg; final HttpMethod requestMethod = req.getMethod(); final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); final String requestPath = queryDecoder.path(); if (requestPath.startsWith(connectPath)) { if (log.isDebugEnabled()) log.debug("Received HTTP JSONP-Polling request: {} {} from channel: {}", requestMethod, requestPath, ctx.channel()); final String sessionId = PipelineUtils.getSessionId(requestPath); final String origin = PipelineUtils.getOrigin(req); if (HttpMethod.GET.equals(requestMethod)) { // Process polling request from client SocketAddress clientIp = PipelineUtils.getHeaderClientIPParamValue(req, remoteAddressHeader); String jsonpIndexParam = PipelineUtils.extractParameter(queryDecoder, "i"); final ConnectPacket packet = new ConnectPacket(sessionId, origin); packet.setTransportType(TransportType.JSONP_POLLING); packet.setJsonpIndexParam(jsonpIndexParam); packet.setRemoteAddress(clientIp); ctx.fireChannelRead(packet); } else if (HttpMethod.POST.equals(requestMethod)) { // Process message request from client ByteBuf buffer = req.content(); String content = buffer.toString(CharsetUtil.UTF_8); if (content.startsWith("d=")) { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(content, CharsetUtil.UTF_8, false); content = PipelineUtils.extractParameter(queryStringDecoder, "d"); content = preprocessJsonpContent(content); ByteBuf buf = PipelineUtils.copiedBuffer(ctx.alloc(), content); List<Packet> packets = PacketFramer.decodePacketsFrame(buf); buf.release(); for (Packet packet : packets) { packet.setSessionId(sessionId); packet.setOrigin(origin); ctx.fireChannelRead(packet); } } else { log.warn( "Can't process HTTP JSONP-Polling message. Incorrect content format: {} from channel: {}", content, ctx.channel()); } } else { log.warn( "Can't process HTTP JSONP-Polling request. Unknown request method: {} from channel: {}", requestMethod, ctx.channel()); } ReferenceCountUtil.release(msg); return; } } super.channelRead(ctx, msg); }