@Override public void send(final FileChannel channel) throws Exception { long len = channel.size(); DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status); if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { headers.remove(HttpHeaderNames.TRANSFER_ENCODING); headers.set(HttpHeaderNames.CONTENT_LENGTH, len); } if (keepAlive) { headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // dump headers rsp.headers().set(headers); ChannelHandlerContext ctx = this.ctx; ctx.attr(NettyRequest.NEED_FLUSH).set(false); ctx.channel() .eventLoop() .execute( () -> { // send headers ctx.write(rsp); ctx.write(new DefaultFileRegion(channel, 0, len)); keepAlive(ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)); }); committed = true; }
@Override protected boolean handleProxyProtocol(ChannelHandlerContext ctx, Object msg) throws Exception { Socks4CommandRequest req = (Socks4CommandRequest) msg; boolean authzSuccess = authenticate(ctx, req); Socks4CommandResponse res; boolean sendGreeting = false; if (!authzSuccess) { res = new DefaultSocks4CommandResponse(Socks4CommandStatus.IDENTD_AUTH_FAILURE); } else if (!req.dstAddr().equals(destination.getHostString()) || req.dstPort() != destination.getPort()) { res = new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED); } else { res = new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS); sendGreeting = true; } ctx.write(res); ctx.pipeline().remove(Socks4ServerDecoder.class); ctx.pipeline().remove(Socks4ServerEncoder.class); if (sendGreeting) { ctx.write(Unpooled.copiedBuffer("0\n", CharsetUtil.US_ASCII)); } return true; }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (logger.isLoggable(Level.FINE)) { logger.fine( String.format( "Channel %s received %s", ctx.channel().hashCode(), frame.getClass().getSimpleName())); } if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content())); } else if (frame instanceof TextWebSocketFrame) { ctx.write(frame); } else if (frame instanceof BinaryWebSocketFrame) { ctx.write(frame); } else if (frame instanceof ContinuationWebSocketFrame) { ctx.write(frame); } else if (frame instanceof PongWebSocketFrame) { frame.release(); // Ignore } else { throw new UnsupportedOperationException( String.format("%s frame types not supported", frame.getClass().getName())); } }
@Override public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception { long curtime = System.currentTimeMillis(); long size = calculateSize(msg); if (size > -1 && trafficCounter != null) { trafficCounter.bytesWriteFlowControl(size); if (writeLimit == 0) { ctx.write(msg, promise); return; } // compute the number of ms to wait before continue with the // channel long wait = getTimeToWait( writeLimit, trafficCounter.currentWrittenBytes(), trafficCounter.lastTime(), curtime); if (wait >= MINIMAL_WAIT) { ctx.executor() .schedule( new Runnable() { @Override public void run() { ctx.write(msg, promise); } }, wait, TimeUnit.MILLISECONDS); return; } } ctx.write(msg, promise); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Send greeting for a new connection. ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n"); ctx.write("It is " + new Date() + " now.\r\n"); ctx.flush(); }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof Invocation) { Invocation invocation = (Invocation) msg; FullHttpRequest request = convertToHttpRequest(invocation); waitsHolder.put(invocation, request); ctx.write(request, promise); } else { ctx.write(msg, promise); } }
@Override public @Nullable FullHttpResponse handleRequest(ChannelHandlerContext ctx, HttpRequest request) throws Exception { QueryStringDecoder decoder = new QueryStringDecoder(request.uri()); List<String> agentIds = decoder.parameters().get("agent-id"); if (agentIds == null) { agentIds = ImmutableList.of(""); } String agentId = agentIds.get(0); List<String> traceIds = decoder.parameters().get("trace-id"); checkNotNull(traceIds, "Missing trace id in query string: %s", request.uri()); String traceId = traceIds.get(0); // check-live-traces is an optimization so glowroot server only has to check with remote // agents when necessary List<String> checkLiveTracesParams = decoder.parameters().get("check-live-traces"); boolean checkLiveTraces = false; if (checkLiveTracesParams != null && !checkLiveTracesParams.isEmpty()) { checkLiveTraces = Boolean.parseBoolean(checkLiveTracesParams.get(0)); } logger.debug( "handleRequest(): agentId={}, traceId={}, checkLiveTraces={}", agentId, traceId, checkLiveTraces); TraceExport traceExport = traceCommonService.getExport(agentId, traceId, checkLiveTraces); if (traceExport == null) { logger.warn("no trace found for id: {}", traceId); return new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); } ChunkedInput<HttpContent> in = getExportChunkedInput(traceExport); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); response.headers().set(HttpHeaderNames.CONTENT_TYPE, MediaType.ZIP.toString()); response .headers() .set("Content-Disposition", "attachment; filename=" + traceExport.fileName() + ".zip"); boolean keepAlive = HttpUtil.isKeepAlive(request); if (keepAlive && !request.protocolVersion().isKeepAliveDefault()) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } HttpServices.preventCaching(response); ctx.write(response); ChannelFuture future = ctx.write(in); HttpServices.addErrorListener(future); if (!keepAlive) { HttpServices.addCloseListener(future); } // return null to indicate streaming return null; }
@Override public void send(final InputStream stream) throws Exception { byte[] chunk = new byte[bufferSize]; int count = ByteStreams.read(stream, chunk, 0, bufferSize); if (count <= 0) { return; } ByteBuf buffer = Unpooled.wrappedBuffer(chunk, 0, count); if (count < bufferSize) { send(buffer); } else { DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status); if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { headers.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); } else { if (keepAlive) { headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } } // dump headers rsp.headers().set(headers); ChannelHandlerContext ctx = this.ctx; ctx.attr(NettyRequest.NEED_FLUSH).set(false); // add chunker ChannelPipeline pipeline = ctx.pipeline(); if (pipeline.get("chunker") == null) { pipeline.addAfter("encoder", "chunker", new ChunkedWriteHandler()); } // group all write ctx.channel() .eventLoop() .execute( () -> { // send headers ctx.write(rsp); // send head chunk ctx.write(buffer); // send tail ctx.write(new ChunkedStream(stream, bufferSize)); keepAlive(ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)); }); } committed = true; }
@Override public void write(final ChannelHandlerContext ctx, final Object msg, ChannelPromise promise) throws Exception { if (msg instanceof ByteBuf) { ByteBuf buf = (ByteBuf) msg; FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "", buf); httpRequest .headers() .add(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes())); ctx.write(httpRequest, promise); } else { ctx.write(msg, promise); } }
private void send(final ByteBuf buffer) throws Exception { DefaultFullHttpResponse rsp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer); if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { headers .remove(HttpHeaderNames.TRANSFER_ENCODING) .set(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes()); } if (keepAlive) { headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // dump headers rsp.headers().set(headers); Attribute<Boolean> async = ctx.attr(NettyRequest.ASYNC); boolean isAsync = async != null && async.get() == Boolean.TRUE; if (isAsync) { // we need flush, from async keepAlive(ctx.writeAndFlush(rsp)); } else { keepAlive(ctx.write(rsp)); } committed = true; }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf readMessage = (ByteBuf) msg; System.out.println("channelRead : " + readMessage.toString(Charset.defaultCharset())); // ctx.writeAndFlush(msg); ctx.write(msg); }
@SuppressWarnings("argument.type.incompatible") private void sendFullResponse( ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse response) throws Exception { boolean keepAlive = HttpUtil.isKeepAlive(request); if (httpSessionManager.getSessionId(request) != null && httpSessionManager.getAuthenticatedUser(request) == null && !response.headers().contains("Set-Cookie")) { httpSessionManager.deleteSessionCookie(response); } response.headers().add("Glowroot-Layout-Version", layoutService.getLayoutVersion()); if (response.headers().contains("Glowroot-Port-Changed")) { // current connection is the only open channel on the old port, keepAlive=false will add // the listener below to close the channel after the response completes // // remove the hacky header, no need to send it back to client response.headers().remove("Glowroot-Port-Changed"); response.headers().add("Connection", "close"); keepAlive = false; } response.headers().add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); if (keepAlive && !request.protocolVersion().isKeepAliveDefault()) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ChannelFuture f = ctx.write(response); if (!keepAlive) { f.addListener(ChannelFutureListener.CLOSE); } }
@Override public void flush(ChannelHandlerContext ctx) throws Exception { // Do not encrypt the first write request if this handler is // created with startTLS flag turned on. if (startTls && !sentFirstMessage) { sentFirstMessage = true; for (; ; ) { PendingWrite pendingWrite = pendingUnencryptedWrites.poll(); if (pendingWrite == null) { break; } ctx.write(pendingWrite.msg(), (ChannelPromise) pendingWrite.recycleAndGet()); } ctx.flush(); return; } if (pendingUnencryptedWrites.isEmpty()) { pendingUnencryptedWrites.add(PendingWrite.newInstance(Unpooled.EMPTY_BUFFER, null)); } if (!handshakePromise.isDone()) { flushedBeforeHandshakeDone = true; } wrap(ctx, false); ctx.flush(); }
/** * 发送消息 * * @param m */ public void send(Msg m) { if (chtx != null && chtx.channel().isOpen()) { logger.info("client发送消息:" + m); chtx.write(m); chtx.flush(); } }
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String body = (String) msg; System.out.print("Receive Order: " + body); ByteBuf resp = Unpooled.copiedBuffer(body.getBytes()); // 发送给客户端 ctx.write(resp); }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof org.vertx.java.core.http.impl.ws.WebSocketFrame) { org.vertx.java.core.http.impl.ws.WebSocketFrame frame = (org.vertx.java.core.http.impl.ws.WebSocketFrame) msg; ByteBuf buf = ((org.vertx.java.core.http.impl.ws.WebSocketFrame) msg).getBinaryData(); if (buf != Unpooled.EMPTY_BUFFER) { buf = safeBuffer(buf); } switch (frame.getType()) { case BINARY: msg = new BinaryWebSocketFrame(buf); break; case TEXT: msg = new TextWebSocketFrame(buf); break; case CLOSE: msg = new CloseWebSocketFrame(true, 0, buf); break; case CONTINUATION: msg = new ContinuationWebSocketFrame(buf); break; case PONG: msg = new PongWebSocketFrame(buf); break; case PING: msg = new PingWebSocketFrame(buf); break; default: throw new IllegalStateException("Unsupported websocket msg " + msg); } } ctx.write(msg, promise); }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof WebSocketFrameInternal) { WebSocketFrameInternal frame = (WebSocketFrameInternal) msg; ByteBuf buf = frame.getBinaryData(); if (buf != Unpooled.EMPTY_BUFFER) { buf = safeBuffer(buf, ctx.alloc()); } switch (frame.type()) { case BINARY: msg = new BinaryWebSocketFrame(frame.isFinal(), 0, buf); break; case TEXT: msg = new TextWebSocketFrame(frame.isFinal(), 0, buf); break; case CLOSE: msg = new CloseWebSocketFrame(true, 0, buf); break; case CONTINUATION: msg = new ContinuationWebSocketFrame(frame.isFinal(), 0, buf); break; case PONG: msg = new PongWebSocketFrame(buf); break; case PING: msg = new PingWebSocketFrame(buf); break; default: throw new IllegalStateException("Unsupported websocket msg " + msg); } } ctx.write(msg, promise); }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof FMLProxyPacket) { if (side == Side.CLIENT) { // Client to server large packets are not supported to prevent client being bad. ctx.write(((FMLProxyPacket) msg).toC17Packet(), promise); } else { List<Packet> parts = ((FMLProxyPacket) msg).toS3FPackets(); for (Packet pkt : parts) { ctx.write(pkt, promise); } } } else { ctx.write(msg, promise); } }
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { final ZMTPMessage message = (ZMTPMessage) msg; meter.inc(); message.release(); ctx.write(req()); flusher.flush(); }
private void wrapNonAppData(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException { ByteBuf out = null; try { for (; ; ) { if (out == null) { out = ctx.alloc().buffer(maxPacketBufferSize); } SSLEngineResult result = wrap(engine, Unpooled.EMPTY_BUFFER, out); if (result.bytesProduced() > 0) { ctx.write(out); if (inUnwrap) { needsFlush = true; } out = null; } switch (result.getHandshakeStatus()) { case FINISHED: setHandshakeSuccess(); break; case NEED_TASK: runDelegatedTasks(); break; case NEED_UNWRAP: if (!inUnwrap) { unwrapNonApp(ctx); } break; case NEED_WRAP: break; case NOT_HANDSHAKING: setHandshakeSuccessIfStillHandshaking(); // Workaround for TLS False Start problem reported at: // https://github.com/netty/netty/issues/1108#issuecomment-14266970 if (!inUnwrap) { unwrapNonApp(ctx); } break; default: throw new IllegalStateException( "Unknown handshake status: " + result.getHandshakeStatus()); } if (result.bytesProduced() == 0) { break; } } } catch (SSLException e) { setHandshakeFailure(e); throw e; } finally { if (out != null) { out.release(); } } }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (timeoutNanos > 0) { promise = promise.unvoid(); scheduleTimeout(ctx, promise); } ctx.write(msg, promise); }
@Override protected ChannelFuture doOnWrite(Object data, ChannelHandlerContext ctx) { if (data.getClass().equals(Buffer.class)) { body.append((Buffer) data); return null; } else { return ctx.write(data); } }
@Override public void write(ChannelHandlerContext ctx, Object msg) throws Exception { Assert.assertSame(t, Thread.currentThread()); int actual = (Integer) msg; int expected = outCnt++; Assert.assertEquals(expected, actual); ctx.write(msg); }
@Override public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception { if (evt instanceof ZMTPHandshakeSuccess) { for (int i = 0; i < CONCURRENCY; i++) { ctx.write(req()); } flusher.flush(); } }
@Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { File file = new File(msg); if (file.exists()) { if (!file.isFile()) { ctx.writeAndFlush("Not a file : " + file + CR); return; } ctx.write(file + " " + file.length() + CR); RandomAccessFile randomAccessFile = new RandomAccessFile(msg, "r"); FileRegion region = new DefaultFileRegion(randomAccessFile.getChannel(), 0, randomAccessFile.length()); ctx.write(region); ctx.writeAndFlush(CR); randomAccessFile.close(); } else { ctx.writeAndFlush("File not found: " + file + CR); } }
private void finishWrap( ChannelHandlerContext ctx, ByteBuf out, ChannelPromise promise, boolean inUnwrap) { if (out == null) { out = Unpooled.EMPTY_BUFFER; } else if (!out.isReadable()) { out.release(); out = Unpooled.EMPTY_BUFFER; } if (promise != null) { ctx.write(out, promise); } else { ctx.write(out); } if (inUnwrap) { needsFlush = true; } }
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpHeaderConstants.CONTENT_TYPE, "text/plain; charset=UTF-8"); // Close the connection as soon as the error message is sent. ctx.write(response).addListener(ChannelFutureListener.CLOSE); }
@Override public void write(ChannelHandlerContext ctx, MessageList<Object> msgs, ChannelPromise promise) throws Exception { promise.addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { getActivityTracker().activity(); } }); ctx.write(msgs, promise); }
@Override public void write(ChannelHandlerContext ctx, Object msg) throws Exception { Assert.assertSame(t, Thread.currentThread()); ByteBuf out = ctx.alloc().buffer(4); int m = (Integer) msg; int expected = outCnt++; Assert.assertEquals(expected, m); out.writeInt(m); ctx.write(out); }
private void writeResponse(HttpObject msg, ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, msg.decoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(_buf.toString(), CharsetUtil.UTF_8)); if (HttpHeaderUtil.isKeepAlive(_request)) { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } }