/**
* Returns a full HTTP response with the specified status, content type, and custom headers.
*
* <p>Headers should be specified as a map of strings. For example, to allow CORS, add the
* following key and value: "access-control-allow-origin", "http://foo.example"
*
* <p>If content type or content length are passed in as custom headers, they will be ignored.
* Instead, content type will be as specified by the parameter contentType and content length will
* be the length of the parameter contentLength.
*/
public static FullHttpResponse newResponse(
HttpResponseStatus status,
ByteBuf payload,
ContentType contentType,
Map<String, String> customHeaders) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, payload);
if (customHeaders != null) {
for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
response.headers().set(entry.getKey(), entry.getValue());
}
}
response.headers().set(CONTENT_TYPE, contentType.value);
response.headers().setInt(CONTENT_LENGTH, payload.readableBytes());
return response;
}
java类io.netty.handler.codec.http.HttpVersion的实例源码
Recipes.java 文件源码
项目:xrpc
阅读 27
收藏 0
点赞 0
评论 0
Http1BackendHandlerTest.java 文件源码
项目:nitmproxy
阅读 21
收藏 0
点赞 0
评论 0
@Test
public void shouldHandlerRequestAndResponse() {
inboundChannel.pipeline().addLast(handler);
DefaultFullHttpRequest req = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
inboundChannel.write(req);
assertEquals(1, inboundChannel.outboundMessages().size());
Object outboundReq = inboundChannel.outboundMessages().poll();
assertTrue(outboundReq instanceof ByteBuf);
assertEquals("GET / HTTP/1.1\r\n\r\n", new String(readBytes((ByteBuf) outboundReq)));
DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
assertFalse(inboundChannel.writeInbound(resp));
assertEquals(1, outboundChannel.outboundMessages().size());
assertEquals(resp, outboundChannel.outboundMessages().poll());
resp.release();
}
Http1BackendHandlerTest.java 文件源码
项目:nitmproxy
阅读 24
收藏 0
点赞 0
评论 0
@Test
public void shouldPendingRequests() {
inboundChannel.pipeline().addLast(handler);
DefaultFullHttpRequest req = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
// First request
inboundChannel.write(req.retain());
assertEquals(1, inboundChannel.outboundMessages().size());
assertTrue(inboundChannel.outboundMessages().poll() instanceof ByteBuf);
// Second request
inboundChannel.write(req);
// Should pending second request
assertTrue(inboundChannel.outboundMessages().isEmpty());
}
Http1BackendHandlerTest.java 文件源码
项目:nitmproxy
阅读 21
收藏 0
点赞 0
评论 0
@Test
public void shouldClearPendingRequests() {
inboundChannel.pipeline().addLast(handler);
DefaultFullHttpRequest req = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
// First request
inboundChannel.write(req.retain());
assertEquals(1, req.refCnt());
assertEquals(1, inboundChannel.outboundMessages().size());
assertTrue(inboundChannel.outboundMessages().poll() instanceof ByteBuf);
// Second request
inboundChannel.write(req);
assertEquals(1, req.refCnt());
assertTrue(inboundChannel.outboundMessages().isEmpty());
inboundChannel.close();
assertEquals(0, req.refCnt());
}
Netty4HttpChannelTests.java 文件源码
项目:elasticsearch_my
阅读 24
收藏 0
点赞 0
评论 0
public void testReleaseOnSendToClosedChannel() {
final Settings settings = Settings.builder().build();
final NamedXContentRegistry registry = xContentRegistry();
try (Netty4HttpServerTransport httpServerTransport =
new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, registry, new NullDispatcher())) {
final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
final EmbeddedChannel embeddedChannel = new EmbeddedChannel();
final Netty4HttpRequest request = new Netty4HttpRequest(registry, httpRequest, embeddedChannel);
final HttpPipelinedRequest pipelinedRequest = randomBoolean() ? new HttpPipelinedRequest(request.request(), 1) : null;
final Netty4HttpChannel channel =
new Netty4HttpChannel(httpServerTransport, request, pipelinedRequest, randomBoolean(), threadPool.getThreadContext());
final TestResponse response = new TestResponse(bigArrays);
assertThat(response.content(), instanceOf(Releasable.class));
embeddedChannel.close();
channel.sendResponse(response);
// ESTestCase#after will invoke ensureAllArraysAreReleased which will fail if the response content was not released
}
}
Netty4HttpChannelTests.java 文件源码
项目:elasticsearch_my
阅读 29
收藏 0
点赞 0
评论 0
private FullHttpResponse executeRequest(final Settings settings, final String originValue, final String host) {
// construct request and send it over the transport layer
try (Netty4HttpServerTransport httpServerTransport =
new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(),
new NullDispatcher())) {
httpServerTransport.start();
final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
if (originValue != null) {
httpRequest.headers().add(HttpHeaderNames.ORIGIN, originValue);
}
httpRequest.headers().add(HttpHeaderNames.HOST, host);
final WriteCapturingChannel writeCapturingChannel = new WriteCapturingChannel();
final Netty4HttpRequest request = new Netty4HttpRequest(xContentRegistry(), httpRequest, writeCapturingChannel);
Netty4HttpChannel channel =
new Netty4HttpChannel(httpServerTransport, request, null, randomBoolean(), threadPool.getThreadContext());
channel.sendResponse(new TestResponse());
// get the response
List<Object> writtenObjects = writeCapturingChannel.getWrittenObjects();
assertThat(writtenObjects.size(), is(1));
return (FullHttpResponse) writtenObjects.get(0);
}
}
NonSslRedirectHandler.java 文件源码
项目:qonduit
阅读 21
收藏 0
点赞 0
评论 0
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
return new ChannelInboundHandlerAdapter() {
private HttpResponseEncoder encoder = new HttpResponseEncoder();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
LOG.trace("Received non-SSL request, returning redirect");
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
response.headers().set(Names.LOCATION, redirectAddress);
LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
encoder.write(ctx, response, ctx.voidPromise());
ctx.flush();
}
};
}
BasicAuthLoginRequestHandlerTest.java 文件源码
项目:qonduit
阅读 19
收藏 0
点赞 0
评论 0
@Test
public void testBasicAuthenticationFailure() throws Exception {
Configuration config = TestConfiguration.createMinimalConfigurationForTest();
BasicAuthLogin auth = new BasicAuthLogin();
auth.setUsername("test");
auth.setPassword("test2");
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login");
request.content().writeBytes(JsonSerializer.getObjectMapper().writeValueAsBytes(auth));
TestHttpQueryDecoder decoder = new TestHttpQueryDecoder(config);
decoder.decode(null, request, results);
Assert.assertEquals(1, results.size());
Object result = results.iterator().next();
Assert.assertEquals(BasicAuthLoginRequest.class, result.getClass());
BasicAuthLoginRequestHandler handler = new BasicAuthLoginRequestHandler(config);
CaptureChannelHandlerContext ctx = new CaptureChannelHandlerContext();
handler.channelRead(ctx, result);
Assert.assertNotNull(ctx.msg);
Assert.assertTrue(ctx.msg instanceof DefaultFullHttpResponse);
DefaultFullHttpResponse response = (DefaultFullHttpResponse) ctx.msg;
Assert.assertEquals(HttpResponseStatus.UNAUTHORIZED, response.getStatus());
Assert.assertTrue(response.headers().contains(Names.CONTENT_TYPE));
Assert.assertEquals(Constants.JSON_TYPE, response.headers().get(Names.CONTENT_TYPE));
}
NettyRequestProxyFilter.java 文件源码
项目:ServiceCOLDCache
阅读 24
收藏 0
点赞 0
评论 0
protected HttpResponse handleNonProxyRequest(FullHttpRequest req) {
String uri = req.getUri();
if ("/version".equals(uri)) {
if (HttpMethod.GET.equals(req.getMethod())) {
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("name", m_appConfig.getAppName());
jsonObj.addProperty("version", m_appConfig.getAppVersion());
byte[] content = jsonObj.toString().getBytes(CharsetUtil.UTF_8);
DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(content));
HttpHeaders.setKeepAlive(resp, false);
HttpHeaders.setHeader(resp, HttpHeaders.Names.CONTENT_TYPE,
"application/json");
HttpHeaders.setContentLength(resp, content.length);
return resp;
}
}
return RESPONSE_404;
}
DebugClientHandlerTest.java 文件源码
项目:ServiceCOLDCache
阅读 22
收藏 0
点赞 0
评论 0
@Test
public void testChannelRead0_debugOnResponse() {
Mockito.when(LOGGER.isDebugEnabled()).thenReturn(true);
Mockito.when(response.getStatus()).thenReturn(HttpResponseStatus.OK);
Mockito.when(response.getProtocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
Mockito.when(headers.isEmpty()).thenReturn(false);
Set<String> headersSet = new HashSet<>();
headersSet.add("no-cache");
Mockito.when(headers.names()).thenReturn(headersSet);
List<String> noCacheValues = new ArrayList<>();
noCacheValues.add("private");
Mockito.when(headers.getAll("no-cache")).thenReturn(noCacheValues);
PowerMockito.mockStatic(HttpHeaders.class);
BDDMockito.given(HttpHeaders.isTransferEncodingChunked(response)).willReturn(true);
handler.channelRead0(ctx, response);
Mockito.verify(LOGGER, Mockito.times(1)).debug("STATUS: " + HttpResponseStatus.OK);
Mockito.verify(LOGGER, Mockito.times(1)).debug("VERSION: " + HttpVersion.HTTP_1_1);
Mockito.verify(LOGGER, Mockito.times(1)).debug("HEADER: no-cache = private");
Mockito.verify(LOGGER, Mockito.times(1)).debug("CHUNKED CONTENT {");
BDDMockito.given(HttpHeaders.isTransferEncodingChunked(response)).willReturn(false);
handler.channelRead0(ctx, response);
Mockito.verify(LOGGER, Mockito.times(1)).debug("CONTENT {");
}
WebSocketServerHandler.java 文件源码
项目:java_learn
阅读 28
收藏 0
点赞 0
评论 0
private void handleHttpRequest(ChannelHandlerContext ctx,
FullHttpRequest req) {
if (!req.getDecoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
"ws://localhost:7777/websocket", null, false);
socketServerHandshaker = wsFactory.newHandshaker(req);
if (socketServerHandshaker == null) {
WebSocketServerHandshakerFactory
.sendUnsupportedWebSocketVersionResponse(ctx.channel());
} else {
socketServerHandshaker.handshake(ctx.channel(), req);
}
}
Netty4ClientHttpRequest.java 文件源码
项目:spring4-understanding
阅读 24
收藏 0
点赞 0
评论 0
private FullHttpRequest createFullHttpRequest(HttpHeaders headers) {
io.netty.handler.codec.http.HttpMethod nettyMethod =
io.netty.handler.codec.http.HttpMethod.valueOf(this.method.name());
FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
nettyMethod, this.uri.toString(), this.body.buffer());
nettyRequest.headers().set(HttpHeaders.HOST, uri.getHost());
nettyRequest.headers().set(HttpHeaders.CONNECTION, io.netty.handler.codec.http.HttpHeaders.Values.CLOSE);
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
nettyRequest.headers().add(entry.getKey(), entry.getValue());
}
return nettyRequest;
}
ClientToProxyConnection.java 文件源码
项目:little_mitm
阅读 19
收藏 0
点赞 0
评论 0
private void writeAuthenticationRequired(String realm) {
String body = "<!DOCTYPE HTML \"-//IETF//DTD HTML 2.0//EN\">\n"
+ "<html><head>\n"
+ "<title>407 Proxy Authentication Required</title>\n"
+ "</head><body>\n"
+ "<h1>Proxy Authentication Required</h1>\n"
+ "<p>This server could not verify that you\n"
+ "are authorized to access the document\n"
+ "requested. Either you supplied the wrong\n"
+ "credentials (e.g., bad password), or your\n"
+ "browser doesn't understand how to supply\n"
+ "the credentials required.</p>\n" + "</body></html>\n";
DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1,
HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED, body);
HttpHeaders.setDate(response, new Date());
response.headers().set("Proxy-Authenticate",
"Basic realm=\"" + (realm == null ? "Restricted Files" : realm) + "\"");
write(response);
}
HttpSuggestRequestHandler.java 文件源码
项目:timely
阅读 24
收藏 0
点赞 0
评论 0
@Override
protected void channelRead0(ChannelHandlerContext ctx, SuggestRequest msg) throws Exception {
byte[] buf = null;
try {
buf = JsonUtil.getObjectMapper().writeValueAsBytes(dataStore.suggest(msg));
} catch (TimelyException e) {
LOG.error(e.getMessage(), e);
this.sendHttpError(ctx, e);
return;
}
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(buf));
response.headers().set(Names.CONTENT_TYPE, Constants.JSON_TYPE);
response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
sendResponse(ctx, response);
}
HttpSearchLookupRequestHandler.java 文件源码
项目:timely
阅读 21
收藏 0
点赞 0
评论 0
@Override
protected void channelRead0(ChannelHandlerContext ctx, SearchLookupRequest msg) throws Exception {
byte[] buf = null;
try {
buf = JsonUtil.getObjectMapper().writeValueAsBytes(dataStore.lookup(msg));
} catch (TimelyException e) {
LOG.error(e.getMessage(), e);
this.sendHttpError(ctx, e);
return;
}
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(buf));
response.headers().set(Names.CONTENT_TYPE, Constants.JSON_TYPE);
response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
sendResponse(ctx, response);
}
HttpQueryRequestHandler.java 文件源码
项目:timely
阅读 21
收藏 0
点赞 0
评论 0
@Override
protected void channelRead0(ChannelHandlerContext ctx, QueryRequest msg) throws Exception {
byte[] buf;
try {
buf = JsonUtil.getObjectMapper().writeValueAsBytes(dataStore.query(msg));
} catch (TimelyException e) {
if (e.getMessage().contains("No matching tags")) {
LOG.trace(e.getMessage());
} else {
LOG.error(e.getMessage(), e);
}
this.sendHttpError(ctx, e);
return;
}
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(buf));
response.headers().set(Names.CONTENT_TYPE, Constants.JSON_TYPE);
response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
sendResponse(ctx, response);
}
NonSslRedirectHandler.java 文件源码
项目:timely
阅读 29
收藏 0
点赞 0
评论 0
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
return new ChannelInboundHandlerAdapter() {
private HttpResponseEncoder encoder = new HttpResponseEncoder();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
LOG.trace("Received non-SSL request, returning redirect");
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
response.headers().set(Names.LOCATION, redirectAddress);
LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
encoder.write(ctx, response, ctx.voidPromise());
ctx.flush();
}
};
}
HttpRequestDecoderTest.java 文件源码
项目:timely
阅读 25
收藏 0
点赞 0
评论 0
@Test
public void testLookupPostWithNoLimit() throws Exception {
// @formatter:off
String content =
"{\n" +
" \"metric\": \"sys.cpu.user\"\n" +
"}";
// @formatter:on
decoder = new TestHttpQueryDecoder(config);
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
"/api/search/lookup");
request.content().writeBytes(content.getBytes());
addCookie(request);
decoder.decode(null, request, results);
Assert.assertEquals(1, results.size());
Assert.assertEquals(SearchLookupRequest.class, results.iterator().next().getClass());
SearchLookupRequest lookup = (SearchLookupRequest) results.iterator().next();
Assert.assertEquals("sys.cpu.user", lookup.getQuery());
Assert.assertEquals(25, lookup.getLimit());
Assert.assertEquals(0, lookup.getTags().size());
}
HttpRequestDecoderTest.java 文件源码
项目:timely
阅读 22
收藏 0
点赞 0
评论 0
@Test
public void testLookupPostWithLimit() throws Exception {
// @formatter:off
String content =
"{\n" +
" \"metric\": \"sys.cpu.user\",\n" +
" \"limit\": 3000\n" +
"}";
// @formatter:on
decoder = new TestHttpQueryDecoder(config);
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
"/api/search/lookup");
request.content().writeBytes(content.getBytes());
addCookie(request);
decoder.decode(null, request, results);
Assert.assertEquals(1, results.size());
Assert.assertEquals(SearchLookupRequest.class, results.iterator().next().getClass());
SearchLookupRequest lookup = (SearchLookupRequest) results.iterator().next();
Assert.assertEquals("sys.cpu.user", lookup.getQuery());
Assert.assertEquals(3000, lookup.getLimit());
Assert.assertEquals(0, lookup.getTags().size());
}
HttpRequestDecoderTest.java 文件源码
项目:timely
阅读 22
收藏 0
点赞 0
评论 0
@Test
public void testLookupURIWithLimitAndTags() throws Exception {
decoder = new TestHttpQueryDecoder(config);
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"/api/search/lookup?m=sys.cpu.user{host=*}&limit=3000");
addCookie(request);
decoder.decode(null, request, results);
Assert.assertEquals(1, results.size());
Assert.assertEquals(SearchLookupRequest.class, results.iterator().next().getClass());
SearchLookupRequest lookup = (SearchLookupRequest) results.iterator().next();
Assert.assertEquals("sys.cpu.user", lookup.getQuery());
Assert.assertEquals(3000, lookup.getLimit());
Assert.assertEquals(1, lookup.getTags().size());
Tag tag = lookup.getTags().iterator().next();
Assert.assertEquals("host", tag.getKey());
Assert.assertEquals("*", tag.getValue());
}
HttpClientOperations.java 文件源码
项目:reactor-netty
阅读 27
收藏 0
点赞 0
评论 0
HttpClientOperations(Channel channel,
BiFunction<? super HttpClientResponse, ? super HttpClientRequest, ? extends Publisher<Void>> handler,
ContextHandler<?> context) {
super(channel, handler, context);
this.isSecure = channel.pipeline()
.get(NettyPipeline.SslHandler) != null;
String[] redirects = channel.attr(REDIRECT_ATTR_KEY)
.get();
this.redirectedFrom = redirects == null ? EMPTY_REDIRECTIONS : redirects;
this.nettyRequest =
new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
this.requestHeaders = nettyRequest.headers();
this.requestHeaders.set(HttpHeaderNames.USER_AGENT, HttpClient.USER_AGENT);
this.inboundPrefetch = 16;
chunkedTransfer(true);
}
HttpRequestDecoderTest.java 文件源码
项目:timely
阅读 21
收藏 0
点赞 0
评论 0
@Test
public void testSuggestPostWithValidType() throws Exception {
// @formatter:off
String content =
"{\n" +
" \"type\": \"metrics\"\n" +
"}";
// @formatter:on
decoder = new TestHttpQueryDecoder(config);
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
"/api/suggest");
request.content().writeBytes(content.getBytes());
addCookie(request);
decoder.decode(null, request, results);
Assert.assertEquals(1, results.size());
Assert.assertEquals(SuggestRequest.class, results.iterator().next().getClass());
SuggestRequest suggest = (SuggestRequest) results.iterator().next();
Assert.assertEquals("metrics", suggest.getType());
Assert.assertFalse(suggest.getQuery().isPresent());
Assert.assertEquals(25, suggest.getMax());
suggest.validate();
}
NettyUseRawHttpResponseTest.java 文件源码
项目:Camel
阅读 19
收藏 0
点赞 0
评论 0
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("netty4-http:http://0.0.0.0:{{port}}/foo")
.to("mock:input")
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
NettyConverter.toByteBuffer("Bye World".getBytes()));
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 9);
exchange.getOut().setBody(response);
}
});
}
};
}
HttpRequestDecoderTest.java 文件源码
项目:timely
阅读 20
收藏 0
点赞 0
评论 0
@Test
public void testSuggestPostWithValidTypeAndQueryAndMax() throws Exception {
// @formatter:off
String content =
"{\n" +
" \"type\": \"metrics\",\n" +
" \"q\": \"sys.cpu.user\",\n" +
" \"max\": 30\n" +
"}";
// @formatter:on
decoder = new TestHttpQueryDecoder(config);
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
"/api/suggest");
request.content().writeBytes(content.getBytes());
addCookie(request);
decoder.decode(null, request, results);
Assert.assertEquals(1, results.size());
Assert.assertEquals(SuggestRequest.class, results.iterator().next().getClass());
SuggestRequest suggest = (SuggestRequest) results.iterator().next();
Assert.assertEquals("metrics", suggest.getType());
Assert.assertEquals("sys.cpu.user", suggest.getQuery().get());
Assert.assertEquals(30, suggest.getMax());
suggest.validate();
}
RecordedHttpRequestBuilderTest.java 文件源码
项目:flashback
阅读 20
收藏 0
点赞 0
评论 0
@Test
public void testBuildContent()
throws Exception {
HttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "www.google.com");
RecordedHttpRequestBuilder recordedHttpRequestBuilder = new RecordedHttpRequestBuilder(nettyRequest);
String charset = "UTF-8";
String str1 = "first content";
HttpContent httpContent1 = new DefaultHttpContent(Unpooled.copiedBuffer(str1.getBytes(charset)));
recordedHttpRequestBuilder.appendHttpContent(httpContent1);
String str2 = "second content";
HttpContent httpContent2 = new DefaultHttpContent(Unpooled.copiedBuffer(str2.getBytes(charset)));
recordedHttpRequestBuilder.appendHttpContent(httpContent2);
String lastStr = "Last chunk";
HttpContent lastContent = new DefaultLastHttpContent(Unpooled.copiedBuffer(lastStr.getBytes(charset)));
recordedHttpRequestBuilder.appendHttpContent(lastContent);
RecordedHttpRequest recordedHttpRequest = recordedHttpRequestBuilder.build();
Assert
.assertEquals((str1 + str2 + lastStr).getBytes(charset), recordedHttpRequest.getHttpBody().getContent(charset));
}
HttpContext.java 文件源码
项目:nesty
阅读 32
收藏 0
点赞 0
评论 0
public static HttpContext build(HttpRequestVisitor visitor) {
HttpContext context = new HttpContext();
context.remoteAddress = visitor.visitRemoteAddress();
context.uri = visitor.visitURI();
context.terms = visitor.visitTerms();
context.requestMethod = visitor.visitHttpMethod();
context.httpHeaders = visitor.visitHttpHeaders();
context.httpParams = visitor.visitHttpParams();
// TODO : if exclude GET or not ?
//
context.httpBody = visitor.visitHttpBody();
if (visitor.visitHttpVersion() == HttpVersion.HTTP_1_1 &&
HttpConstants.HEADER_CONNECTION_CLOSE.equals(context.httpHeaders.get(HttpConstants.HEADER_CONNECTION)))
context.isKeepAlive = false;
if (visitor.visitHttpVersion() == HttpVersion.HTTP_1_0 &&
!HttpConstants.HEADER_CONNECTION_KEEPALIVE.equalsIgnoreCase(context.httpHeaders.get(HttpConstants.HEADER_CONNECTION)))
context.isKeepAlive = false;
return context;
}
NoMatchResponseGenerator.java 文件源码
项目:flashback
阅读 19
收藏 0
点赞 0
评论 0
public static FullHttpResponse generateNoMatchResponse(RecordedHttpRequest recordedHttpRequest) {
StringBuilder bodyTextBuilder = new StringBuilder();
bodyTextBuilder.append("No Matching Request\n").append("Incoming Request Method: ")
.append(recordedHttpRequest.getMethod()).append("\n").append("Incoming Request URI: ")
.append(recordedHttpRequest.getUri()).append("\n").append("Incoming Request Headers: ")
.append(recordedHttpRequest.getHeaders()).append("\n");
RecordedHttpBody incomingBody = recordedHttpRequest.getHttpBody();
if (incomingBody != null) {
if (incomingBody instanceof RecordedEncodedHttpBody) {
incomingBody = ((RecordedEncodedHttpBody) incomingBody).getDecodedBody();
}
if (incomingBody instanceof RecordedStringHttpBody) {
bodyTextBuilder.append("Incoming Request Body: ").append(((RecordedStringHttpBody) incomingBody).getContent());
} else {
bodyTextBuilder.append("Incoming Request Body: (binary content)");
}
}
ByteBuf badRequestBody = Unpooled.wrappedBuffer(bodyTextBuilder.toString().getBytes(Charset.forName("UTF-8")));
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, badRequestBody);
}
HttpServerHandler.java 文件源码
项目:yar-java
阅读 25
收藏 0
点赞 0
评论 0
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
ByteBuf buf = msg.content();
byte[] bytes = new byte[buf.readableBytes()];
buf.getBytes(0, bytes);
YarRequest yarRequest = YarProtocol.buildRequest(bytes);
YarResponse yarResponse = process(yarRequest);
FullHttpResponse response =
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(YarProtocol
.toProtocolBytes(yarResponse)));
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
if (HttpHeaders.isKeepAlive(msg)) {
response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
}
ctx.write(response);
ctx.flush();
ctx.close();
}
RequestInfoImplTest.java 文件源码
项目:riposte
阅读 26
收藏 0
点赞 0
评论 0
@Test
public void getMultipartParts_works_as_expected_with_known_valid_data() throws IOException {
// given
RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
Whitebox.setInternalState(requestInfo, "isMultipart", true);
Whitebox.setInternalState(requestInfo, "contentCharset", CharsetUtil.UTF_8);
Whitebox.setInternalState(requestInfo, "protocolVersion", HttpVersion.HTTP_1_1);
Whitebox.setInternalState(requestInfo, "method", HttpMethod.POST);
requestInfo.isCompleteRequestWithAllChunks = true;
requestInfo.rawContentBytes = KNOWN_MULTIPART_DATA_BODY.getBytes(CharsetUtil.UTF_8);
requestInfo.getHeaders().set("Content-Type", KNOWN_MULTIPART_DATA_CONTENT_TYPE_HEADER);
// when
List<InterfaceHttpData> result = requestInfo.getMultipartParts();
// then
assertThat(result, notNullValue());
assertThat(result.size(), is(1));
InterfaceHttpData data = result.get(0);
assertThat(data, instanceOf(FileUpload.class));
FileUpload fileUploadData = (FileUpload)data;
assertThat(fileUploadData.getName(), is(KNOWN_MULTIPART_DATA_NAME));
assertThat(fileUploadData.getFilename(), is(KNOWN_MULTIPART_DATA_FILENAME));
assertThat(fileUploadData.getString(CharsetUtil.UTF_8), is(KNOWN_MULTIPART_DATA_ATTR_UUID));
}
RequestInfoImplTest.java 文件源码
项目:riposte
阅读 22
收藏 0
点赞 0
评论 0
@Test
public void getMultipartParts_works_as_expected_with_known_empty_data() throws IOException {
// given
RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
Whitebox.setInternalState(requestInfo, "isMultipart", true);
Whitebox.setInternalState(requestInfo, "contentCharset", CharsetUtil.UTF_8);
Whitebox.setInternalState(requestInfo, "protocolVersion", HttpVersion.HTTP_1_1);
Whitebox.setInternalState(requestInfo, "method", HttpMethod.POST);
requestInfo.isCompleteRequestWithAllChunks = true;
requestInfo.rawContentBytes = null;
requestInfo.getHeaders().set("Content-Type", KNOWN_MULTIPART_DATA_CONTENT_TYPE_HEADER);
// when
List<InterfaceHttpData> result = requestInfo.getMultipartParts();
// then
assertThat(result, notNullValue());
assertThat(result.isEmpty(), is(true));
}