private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", StandardCharsets.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
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 FullHttpResponse createResponseByByteBuf(Response response, ByteBuf byteBuf) { Map<String, String> headers = response.headers(); var httpResponse = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.valueOf(response.statusCode()), byteBuf); httpResponse.headers().set(CONTENT_LENGTH, httpResponse.content().readableBytes()); setDefaultHeaders(httpResponse.headers()); if (response.cookiesRaw().size() > 0) { this.appendCookie(response, httpResponse); } for (Map.Entry<String, String> next : headers.entrySet()) { httpResponse.headers().set(HttpConst.getAsciiString(next.getKey()), next.getValue()); } return httpResponse; }
@Override public FullHttpResponse replace(ByteBuf content) { FullHttpResponse response = new DefaultFullHttpResponse(protocolVersion(), status(), content, headers().copy(), trailingHeaders().copy()); response.setDecoderResult(decoderResult()); return response; }
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { var response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpConst.CONTENT_TYPE, Const.CONTENT_TYPE_TEXT); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
/** * Creates the 101 Switching Protocols response message. */ private static FullHttpResponse createUpgradeResponse(CharSequence upgradeProtocol) { DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS, Unpooled.EMPTY_BUFFER, false); res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE); res.headers().add(HttpHeaderNames.UPGRADE, upgradeProtocol); return res; }
protected void sendHttp1Response0(HttpResponseStatus status, boolean error, ByteBuf content) { FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, status, content); HttpHeaders headers = httpResponse.headers(); headers.setInt(CONTENT_LENGTH, httpResponse.content().readableBytes()); if (request.getSerializeType() > 0) { String serialization = SerializerFactory.getAliasByCode(request.getSerializeType()); headers.set(RemotingConstants.HEAD_SERIALIZE_TYPE, serialization); } else { headers.set(CONTENT_TYPE, "text/plain; charset=" + RpcConstants.DEFAULT_CHARSET.displayName()); } if (error) { headers.set(RemotingConstants.HEAD_RESPONSE_ERROR, "true"); } if (!keepAlive) { ctx.write(httpResponse).addListener(ChannelFutureListener.CLOSE); } else { httpResponse.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(httpResponse); } } }
private static final FullHttpResponse http200(String result) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(result.getBytes())); HttpHeaders httpHeaders = response.headers(); httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); return response; }
@Override public final void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { LOG.error("Exception caught", cause); HttpResponseStatus status; if (cause instanceof BadRequestException) { status = BAD_REQUEST; } else { status = INTERNAL_SERVER_ERROR; } String content = cause.getMessage(); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); ChannelFuture future = ctx.writeAndFlush(response); future.addListener(ChannelFutureListener.CLOSE); ctx.close(); } }
protected int sendHttp1Response(ChannelHandlerContext ctx, HttpResponseStatus status, String resultStr, boolean isKeepAlive) { ByteBuf content = Unpooled.copiedBuffer(resultStr, RpcConstants.DEFAULT_CHARSET); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content); res.headers().set(CONTENT_TYPE, "text/html; charset=" + RpcConstants.DEFAULT_CHARSET.displayName()); HttpUtil.setContentLength(res, content.readableBytes()); try { ChannelFuture f = ctx.channel().writeAndFlush(res); if (isKeepAlive) { HttpUtil.setKeepAlive(res, true); } else { HttpUtil.setKeepAlive(res, false); //set keepalive closed f.addListener(ChannelFutureListener.CLOSE); } } catch (Exception e2) { LOGGER.warn("Failed to send HTTP response to remote, cause by:", e2); } return content.readableBytes(); }
private static void sendListing(ChannelHandlerContext ctx, String uri, List<FileMeta> listFiles, String dirPath) { var response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(HttpConst.CONTENT_TYPE, "text/html; charset=UTF-8"); StringBuilder buf = new StringBuilder() .append("<!DOCTYPE html>\r\n") buf.append("</body></html>"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
private void outputContent(ChannelHandlerContext ctx, FullHttpRequest request, int code, String content, String mimeType) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), Unpooled.wrappedBuffer(content.getBytes(Charset.forName("UTF-8")))); response.headers().set(Names.CONTENT_TYPE, mimeType); response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(Names.SERVER, SERVER_VS); ChannelFuture future = ctx.writeAndFlush(response); if (!HttpHeaders.isKeepAlive(request)) { future.addListener(ChannelFutureListener.CLOSE); } }
public final void sendHttpResponse(HttpRequest req, ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, status); resp.headers().add("Content-Length", "0"); final boolean closeConn = ((status != OK) || (! HttpUtil.isKeepAlive(req))); if (closeConn) { resp.headers().add(HttpHeaderNames.CONNECTION, "Close"); } final ChannelFuture cf = ctx.channel().writeAndFlush(resp); if (closeConn) { cf.addListener(ChannelFutureListener.CLOSE); } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Exception e = cause instanceof Exception ? (Exception) cause : new Exception(cause); final String output = JsonUtil.toJsonString(e); ByteBuf content = Unpooled.wrappedBuffer(output.getBytes(Charsets.UTF_8)); final DefaultFullHttpResponse resp = new DefaultFullHttpResponse( HTTP_1_1, INTERNAL_SERVER_ERROR, content); resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8); if (e instanceof IllegalArgumentException) { resp.setStatus(BAD_REQUEST); } else if (e instanceof FileNotFoundException) { resp.setStatus(NOT_FOUND); } else if (e instanceof IOException) { resp.setStatus(FORBIDDEN); } resp.headers().set(CONTENT_LENGTH, resp.content().readableBytes()); resp.headers().set(CONNECTION, CLOSE); ctx.write(resp).addListener(ChannelFutureListener.CLOSE); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (!(msg instanceof HttpRequest)) return; HttpRequest req = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(HELLO_WORLD)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } }
private static void sendListing(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
@Override public void failure(Throwable error) { ctx.writeAndFlush(new DefaultFullHttpResponse(req.protocolVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR)) .addListener(ChannelFutureListener.CLOSE); }
if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; if (request.headers().contains(io.vertx.core.http.HttpHeaders.UPGRADE, Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, true)) { String connection = request.headers().get(io.vertx.core.http.HttpHeaders.CONNECTION); int found = 0; if (connection != null && connection.length() > 0) { String settingsHeader = request.headers().get(Http2CodecUtil.HTTP_UPGRADE_SETTINGS_HEADER); if (settingsHeader != null) { Http2Settings settings = HttpUtils.decodeSettings(settingsHeader); if (settings != null) { HandlerHolder<HttpHandlers> reqHandler = httpHandlerMgr.chooseHandler(ctx.channel().eventLoop()); if (reqHandler != null && reqHandler.context.isEventLoopContext()) { ChannelPipeline pipeline = ctx.pipeline(); DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS, Unpooled.EMPTY_BUFFER, false); res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE); res.headers().add(HttpHeaderNames.UPGRADE, Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME); res.headers().add(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO); ctx.writeAndFlush(res); pipeline.remove("httpEncoder"); pipeline.remove("handler"); DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, Unpooled.EMPTY_BUFFER, false); res.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); ctx.writeAndFlush(res);
if (!req.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true) || !HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(req.headers().get(HttpHeaderNames.UPGRADE))) { throw new WebSocketHandshakeException("not a WebSocket handshake request: missing upgrade"); boolean isHixie76 = req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY1) && req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY2); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, new HttpResponseStatus(101, isHixie76 ? "WebSocket Protocol Handshake" : "Web Socket Protocol Handshake")); if (headers != null) { res.headers().add(headers); res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET); res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE); int b = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key2).replaceAll("")) / BEGINNING_SPACE.matcher(key2).replaceAll("").length()); long c = req.content().readLong(); ByteBuf input = Unpooled.buffer(16); input.writeInt(a); input.writeInt(b); input.writeLong(c); res.content().writeBytes(WebSocketUtil.md5(input.array()));
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof WebSocketHandshakeException) { FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, HttpResponseStatus.BAD_REQUEST, Unpooled.wrappedBuffer(cause.getMessage().getBytes())); ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { ctx.fireExceptionCaught(cause); ctx.close(); } }