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 void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
@Override public int getRawStatusCode() throws IOException { return this.nettyResponse.getStatus().code(); }
private static final FullHttpResponse http404() { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); HttpHeaders httpHeaders = response.headers(); httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); return response; }
public Netty4ClientHttpResponse(ChannelHandlerContext context, FullHttpResponse nettyResponse) { Assert.notNull(context, "ChannelHandlerContext must not be null"); Assert.notNull(nettyResponse, "FullHttpResponse must not be null"); this.context = context; this.nettyResponse = nettyResponse; this.body = new ByteBufInputStream(this.nettyResponse.content()); this.nettyResponse.retain(); }
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); } }
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); }
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(); }
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 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(); } }
private void sendHttpResponse(final ChannelHandlerContext ctx, final FullHttpRequest req, final FullHttpResponse res) { // Generate an error page if response status code is not OK (200). if (res.getStatus().code() != 200) { final ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. final ChannelFuture f = ctx.channel().write(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.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);
res.headers().add("Access-Control-Allow-Origin", CORS_ALLOWED_ORIGINS); if (res.content() != null) { setContentLength(res, res.content().readableBytes()); boolean isKeepAlive = isKeepAlive(req); if (isKeepAlive) { res.headers().add(CONNECTION, KEEP_ALIVE); res.headers().add(KEEP_ALIVE, KEEP_ALIVE_TIMEOUT_STR + httpConnIdleTimeout); ctx.channel().write(res); if (req == null || !isKeepAlive) { log.debug("Closing channel. isKeepAlive:" + isKeepAlive + " on channel: " + ctx.channel().toString()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.INVALID_STREAM); ctx.writeAndFlush(spdyRstStreamFrame); return; SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.PROTOCOL_ERROR); ctx.writeAndFlush(spdyRstStreamFrame); return; SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.INTERNAL_ERROR); ctx.writeAndFlush(spdyRstStreamFrame); return; httpRequestWithEntity.headers().setInt(Names.STREAM_ID, streamId); httpRequestWithEntity.headers().setInt(Names.ASSOCIATED_TO_STREAM_ID, associatedToStreamId); httpRequestWithEntity.headers().setInt(Names.PRIORITY, spdySynStreamFrame.priority()); httpResponseWithEntity.headers().setInt(Names.STREAM_ID, streamId); HttpUtil.setContentLength(fullHttpMessage, fullHttpMessage.content().readableBytes()); removeMessage(streamId); out.add(fullHttpMessage); if (content.readableBytes() > maxContentLength - spdyDataFrame.content().readableBytes()) { removeMessage(streamId); throw new TooLongFrameException(
static void sendError(Channel ch, HttpResponseStatus status, CharSequence err) { FullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, status); if (status.code() == METHOD_NOT_ALLOWED.code()) { // SockJS requires this resp.headers().set(io.vertx.core.http.HttpHeaders.ALLOW, io.vertx.core.http.HttpHeaders.GET); } if (err != null) { resp.content().writeBytes(err.toString().getBytes(CharsetUtil.UTF_8)); HttpUtil.setContentLength(resp, err.length()); } else { HttpUtil.setContentLength(resp, 0); } ch.writeAndFlush(resp); }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) { Channel ch = ctx.channel(); if (msg instanceof FullHttpResponse) { FullHttpResponse httpResponse = (FullHttpResponse) msg; final SettableFuture<String> registrationFuture = ch.attr(REGISTRATION_FUTURE).get(); if (httpResponse.headers().contains(UPGRADE, WEBSOCKET, true) && !handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, httpResponse); final String clientRegistrationId = httpResponse.headers().get("X-CLIENT-REGISTRATION-ID"); registrationFuture.set(clientRegistrationId); mockServerLogger.trace("web socket client " + clientRegistrationId + " connected!"); } else if (httpResponse.status().equals(HttpResponseStatus.NOT_IMPLEMENTED)) { String message = readRequestBody(httpResponse); registrationFuture.setException(new WebSocketException(message)); mockServerLogger.warn(message); } else { registrationFuture.setException(new WebSocketException("Unsupported web socket message " + new FullHttpResponseToMockServerResponse().mapMockServerResponseToFullHttpResponse(httpResponse))); } } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { webSocketClient.receivedTextWebSocketFrame((TextWebSocketFrame) frame); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); } else if (frame instanceof CloseWebSocketFrame) { mockServerLogger.trace("web socket client received request to close"); ch.close(); } } }
@Override public boolean delete(Object key) { DefaultHttpRequest delete = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, keyToUri(key)); try { HttpResponseHandler handler = new HttpResponseHandler(true); Channel ch = bootstrap.connect(configuration.host(), configuration.port()).awaitUninterruptibly().channel().pipeline().addLast(new HttpObjectAggregator(maxContentLength), handler).channel(); ch.writeAndFlush(delete).sync().channel().closeFuture().sync(); try { return isSuccessful(handler.getResponse().status().code()); } finally { handler.getResponse().release(); } } catch (Exception e) { throw new PersistenceException(e); } }
try { ByteBuf buf = httpRequest.content(); final byte[] contentBytes = new byte[buf.readableBytes()]; buf.getBytes(0, contentBytes); YarRequest yarRequest = new AttachmentRequest(YarProtocol.buildRequest(contentBytes), attachments); yarRequest.setRequestPath(requestPath); new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(responseBytes)); httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); httpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, httpResponse.content().readableBytes()); if (HttpHeaders.isKeepAlive(httpRequest)) { httpResponse.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE); } else { httpResponse.headers().set(HttpHeaders.Names.CONNECTION, Values.CLOSE);
private String readRequestBody(FullHttpResponse fullHttpResponse) { if (fullHttpResponse.content().readableBytes() > 0) { byte[] bodyBytes = new byte[fullHttpResponse.content().readableBytes()]; fullHttpResponse.content().readBytes(bodyBytes); Charset requestCharset = ContentTypeMapper.getCharsetFromContentTypeHeader(fullHttpResponse.headers().get(CONTENT_TYPE)); return new String(bodyBytes, requestCharset); } return ""; }