Refine search
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { /*Both these handlers always run in the same executor, so it's safe to access this variable.*/ bytesWriteInterceptor.messageReceived = false; /*reset flag for this write*/ ctx.write(msg, promise); if (!bytesWriteInterceptor.messageReceived) { bytesWriteInterceptor.requestMoreIfWritable(ctx.channel()); } } }
private void send(final ByteBuf buffer) throws Exception { DefaultFullHttpResponse rsp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer); headers.remove(HttpHeaderNames.TRANSFER_ENCODING) .set(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes()); ChannelPromise promise; if (keepAlive) { promise = ctx.voidPromise(); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } else { promise = ctx.newPromise(); } // dump headers rsp.headers().set(headers); Attribute<Boolean> async = ctx.channel().attr(NettyRequest.ASYNC); boolean flush = async != null && async.get() == Boolean.TRUE; final ChannelFuture future; if (flush) { future = ctx.writeAndFlush(rsp, promise); } else { future = ctx.write(rsp, promise); } if (!keepAlive) { future.addListener(CLOSE); } committed = true; }
private static void syncSpecificPins(ChannelHandlerContext ctx, String messageBody, int msgId, Profile profile, DashBoard dash, int deviceId) { String[] bodyParts = messageBody.split(StringUtils.BODY_SEPARATOR_STRING); if (bodyParts.length < 2 || bodyParts[0].isEmpty()) { ctx.writeAndFlush(illegalCommand(msgId), ctx.voidPromise()); return; } PinType pinType = PinType.getPinType(bodyParts[0].charAt(0)); if (StringUtils.isReadOperation(bodyParts[0])) { for (int i = 1; i < bodyParts.length; i++) { short pin = NumberUtil.parsePin(bodyParts[i]); Widget widget = dash.findWidgetByPin(deviceId, pin, pinType); if (ctx.channel().isWritable()) { if (widget == null) { PinStorageValue pinStorageValue = profile.pinsStorage.get(new DashPinStorageKey(dash.id, deviceId, pinType, pin)); if (pinStorageValue != null) { for (String value : pinStorageValue.values()) { String body = DataStream.makeHardwareBody(pinType, pin, value); ctx.write(makeUTF8StringMessage(HARDWARE, msgId, body), ctx.voidPromise()); } } } else if (widget instanceof HardwareSyncWidget) { ((HardwareSyncWidget) widget).sendHardSync(ctx, msgId, deviceId); } } } ctx.flush(); } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception { // handle the case of to big requests. if (e.getCause() instanceof TooLongFrameException) { DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, REQUEST_ENTITY_TOO_LARGE); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { if (ctx.channel().isActive()) { // 连接已断开就不打印了 logger.warn("Exception caught by request handler", e); } ctx.close(); } } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception { // handle the case of to big requests. if (e.getCause() instanceof TooLongFrameException) { DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, REQUEST_ENTITY_TOO_LARGE); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { if (ctx.channel().isActive()) { // 连接已断开就不打印了 logger.warn("Exception caught by request handler", e); } ctx.close(); } } }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (msg instanceof NetworkMessage) { NetworkMessage message = (NetworkMessage) msg; if (ctx.channel() instanceof DatagramChannel) { InetSocketAddress recipient = (InetSocketAddress) message.getRemoteAddress(); InetSocketAddress sender = (InetSocketAddress) ctx.channel().localAddress(); ctx.write(new DatagramPacket((ByteBuf) message.getMessage(), recipient, sender), promise); } else { ctx.write(message.getMessage(), promise); } } else { ctx.write(msg, promise); } }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) throws Exception { String uri = ctx.channel().attr(URI_ATTRIBUTE).get(); if (uri == null) { ctx.write(msg, prm); return; } if ("/unsampled".equals(uri)) { unsampled.write(ctx, msg, prm); } else if ("/traced".equals(uri)) { traced.write(ctx, msg, prm); } else if ("/traced128".equals(uri)) { traced128.write(ctx, msg, prm); } else { ctx.write(msg, prm); } } }
private void handleWebSocketFrame(final ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); } else if (frame instanceof TextWebSocketFrame) { webSocketClientRegistry.receivedTextWebSocketFrame(((TextWebSocketFrame) frame)); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } }
@Override public void end() { if (ctx != null) { Attribute<NettyWebSocket> ws = ctx.channel().attr(NettyWebSocket.KEY); if (ws != null && ws.get() != null) { status = HttpResponseStatus.SWITCHING_PROTOCOLS; ws.get().hankshake(); ctx = null; committed = true; return; } if (!committed) { DefaultHttpResponse rsp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status); headers.set(HttpHeaderNames.CONTENT_LENGTH, 0); // dump headers rsp.headers().set(headers); if (keepAlive) { ctx.write(rsp, ctx.voidPromise()); } else { ctx.write(rsp).addListener(CLOSE); } ctx.flush(); committed = true; } ctx = null; } }
private void writeMoreResults(final PostgreSQLQueryCommandPacket queryCommandPacket) throws SQLException { if (!context.channel().isActive()) { return; } int count = 0; int proxyFrontendFlushThreshold = GlobalRegistry.getInstance().getShardingProperties().<Integer>getValue(ShardingPropertiesConstant.PROXY_FRONTEND_FLUSH_THRESHOLD); while (queryCommandPacket.next()) { count++; while (!context.channel().isWritable() && context.channel().isActive()) { context.flush(); synchronized (frontendHandler) { try { frontendHandler.wait(); } catch (final InterruptedException ignored) { } } } DatabasePacket resultValue = queryCommandPacket.getResultValue(); context.write(resultValue); if (proxyFrontendFlushThreshold == count) { context.flush(); count = 0; } } } }
private void writeMoreResults(final QueryCommandPacket queryCommandPacket, final int headPacketsCount) throws SQLException { if (!context.channel().isActive()) { return; } currentSequenceId = headPacketsCount; int count = 0; int proxyFrontendFlushThreshold = GlobalRegistry.getInstance().getShardingProperties().<Integer>getValue(ShardingPropertiesConstant.PROXY_FRONTEND_FLUSH_THRESHOLD); while (queryCommandPacket.next()) { count++; while (!context.channel().isWritable() && context.channel().isActive()) { context.flush(); synchronized (frontendHandler) { try { frontendHandler.wait(); } catch (final InterruptedException ignored) { } } } DatabasePacket resultValue = queryCommandPacket.getResultValue(); currentSequenceId = resultValue.getSequenceId(); context.write(resultValue); if (proxyFrontendFlushThreshold == count) { context.flush(); count = 0; } } context.write(new EofPacket(++currentSequenceId)); } }
private void writeMoreResults(final QueryCommandPacket queryCommandPacket, final int headPacketsCount) throws SQLException { if (!context.channel().isActive()) { return; } currentSequenceId = headPacketsCount; int count = 0; int proxyFrontendFlushThreshold = GlobalRegistry.getInstance().getShardingProperties().<Integer>getValue(ShardingPropertiesConstant.PROXY_FRONTEND_FLUSH_THRESHOLD); while (queryCommandPacket.next()) { count++; while (!context.channel().isWritable() && context.channel().isActive()) { context.flush(); synchronized (frontendHandler) { try { frontendHandler.wait(); } catch (final InterruptedException ignored) { } } } DatabasePacket resultValue = queryCommandPacket.getResultValue(); currentSequenceId = resultValue.getSequenceId(); context.write(resultValue); if (proxyFrontendFlushThreshold == count) { context.flush(); count = 0; } } context.write(new EofPacket(++currentSequenceId)); } }
@Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); Integer key = channel.hashCode(); PerChannel perChannel = channelQueues.remove(key); perChannel.queueSize -= size; queuesSize.addAndGet(-size); ctx.write(toSend.toSend, toSend.promise);
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) { Span span = ctx.channel().attr(NettyHttpTracing.SPAN_ATTRIBUTE).get(); if (span == null || !(msg instanceof HttpResponse)) { ctx.write(msg, prm); return; } HttpResponse response = (HttpResponse) msg; // Guard re-scoping the same span SpanInScope spanInScope = ctx.channel().attr(NettyHttpTracing.SPAN_IN_SCOPE_ATTRIBUTE).get(); if (spanInScope == null) spanInScope = tracer.withSpanInScope(span); try { ctx.write(msg, prm); parser.response(adapter, response, null, span.customizer()); } catch (RuntimeException | Error e) { span.error(e); throw e; } finally { spanInScope.close(); // clear scope before reporting span.finish(); } } }
@Override public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { promise = promise.unvoid(); // Avoid NotYetConnectedException if (!ctx.channel().isActive()) { ctx.close(promise); return; } // If the user has already sent a GO_AWAY frame they may be attempting to do a graceful shutdown which requires // sending multiple GO_AWAY frames. We should only send a GO_AWAY here if one has not already been sent. If // a GO_AWAY has been sent we send a empty buffer just so we can wait to close until all other data has been // flushed to the OS. // https://github.com/netty/netty/issues/5307 final ChannelFuture future = connection().goAwaySent() ? ctx.write(EMPTY_BUFFER) : goAway(ctx, null); ctx.flush(); doGracefulShutdown(ctx, future, promise); }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { NetworkMessage networkMessage = (NetworkMessage) msg; if (networkMessage.getMessage() instanceof Command) { Command command = (Command) networkMessage.getMessage(); Object encodedCommand = encodeCommand(ctx.channel(), command); StringBuilder s = new StringBuilder(); s.append("[").append(ctx.channel().id().asShortText()).append("] "); s.append("id: ").append(getUniqueId(command.getDeviceId())).append(", "); s.append("command type: ").append(command.getType()).append(" "); if (encodedCommand != null) { s.append("sent"); } else { s.append("not sent"); } LOGGER.info(s.toString()); ctx.write(new NetworkMessage(encodedCommand, networkMessage.getRemoteAddress()), promise); } else { super.write(ctx, msg, promise); } }