@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(); }
@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()); }
@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()); }
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 } }
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); } }
@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)); }
@Test public void testIsProxyRequest() throws IOException{ AppConfiguration appConfig = new AppConfiguration(new ConfigLoader(), null); appConfig.init(); PolicyManager policyManager = mock(PolicyManager.class); NettyRequestProxyFilter filter = new NettyRequestProxyFilter( policyManager, appConfig); DefaultFullHttpRequest req = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, "/version"); assertTrue(filter.isProxyRequest(req)); assertRequest(filter, req, false, "localhost:32876"); assertRequest(filter, req, false, "127.0.0.1:32876"); assertRequest(filter, req, true, "localhost:32877"); assertRequest(filter, req, true, "localhost"); assertRequest(filter, req, true, "127.0.0.1"); assertRequest(filter, req, true, "trace.vip.ebay.com"); assertRequest(filter, req, true, ""); }
@Test public void test() throws InterruptedException, ExecutionException { int streamId = 3; FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); request.headers().add(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), streamId); Promise<FullHttpResponse> promise = CHANNEL.eventLoop().newPromise(); synchronized (RESPONSE_HANDLER) { CHANNEL.writeAndFlush(request); RESPONSE_HANDLER.put(streamId, promise); } assertEquals(HttpResponseStatus.OK, promise.get().status()); ByteBuf content = promise.get().content(); assertEquals("HTTP/2 DTP", content.toString(StandardCharsets.UTF_8)); }
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; }
@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()); }
@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()); }
@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()); }
@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(); }
@Test public void testSuggestPostWithValidTypeAndQuery() throws Exception { // @formatter:off String content = "{\n" + " \"type\": \"metrics\",\n" + " \"q\": \"sys.cpu.user\"\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(25, suggest.getMax()); suggest.validate(); }
@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(); }
@Test public void testPutMetricPost() throws Exception { // @formatter:off Metric m = Metric.newBuilder() .name("sys.cpu.user") .value(TEST_TIME, 1.0D) .tag(new Tag("tag1", "value1")) .tag(new Tag("tag2", "value2")) .build(); // @formatter:on byte[] buf = JsonUtil.getObjectMapper().writeValueAsBytes(m); decoder = new TestHttpQueryDecoder(config); DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/api/put"); request.content().writeBytes(buf); decoder.decode(null, request, results); Assert.assertEquals(1, results.size()); Assert.assertEquals(MetricRequest.class, results.iterator().next().getClass()); }
/** * {@inheritDoc} */ @Override public synchronized List<InterfaceHttpData> getMultipartParts() { if (!isMultipartRequest() || !isCompleteRequestWithAllChunks()) return null; if (multipartData == null) { byte[] contentBytes = getRawContentBytes(); HttpRequest fullHttpRequestForMultipartDecoder = (contentBytes == null) ? new DefaultFullHttpRequest(getProtocolVersion(), getMethod(), getUri()) : new DefaultFullHttpRequest(getProtocolVersion(), getMethod(), getUri(), Unpooled.wrappedBuffer(contentBytes)); fullHttpRequestForMultipartDecoder.headers().add(getHeaders()); multipartData = new HttpPostMultipartRequestDecoder( new DefaultHttpDataFactory(false), fullHttpRequestForMultipartDecoder, getContentCharset() ); } return multipartData.getBodyHttpDatas(); }
@Test public void testAddNewViaHeaderToExistingViaHeader() { String hostname = "hostname"; HttpMessage httpMessage = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/endpoint"); httpMessage.headers().add(HttpHeaders.Names.VIA, "1.1 otherproxy"); ProxyUtils.addVia(httpMessage, hostname); List<String> viaHeaders = httpMessage.headers().getAll(HttpHeaders.Names.VIA); assertThat(viaHeaders, hasSize(2)); assertEquals("1.1 otherproxy", viaHeaders.get(0)); String expectedViaHeader = "1.1 " + hostname; assertEquals(expectedViaHeader, viaHeaders.get(1)); }
public boolean sendAsyncRequest(ResponseListener listener, String url, OneM2mRequest reqMessage) { try { URI uri = new URI(url); String host = uri.getHost() == null? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if(port == -1) port = 80; DefaultFullHttpRequest request = makeHttpMessage(host, reqMessage); log.debug("sendAsyncRequest"); bootstrap.connect(host, port).addListener(new ConnectListner(request, mHttpClientListener, listener)); return true; } catch (Exception e) { log.error("sendAsyncRequest", e); } return false; }
@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)); }
private void buildRequestHeaders(DefaultFullHttpRequest request) { // config request header request.headers().set(HttpHeaders.Names.HOST, this.uri.getHost()); // 添加压缩头 request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, "gzip, deflate"); // added user agent if (userAgent != null && !userAgent.isEmpty()) request.headers().set(HttpHeaders.Names.USER_AGENT, userAgent); else request.headers().remove(HttpHeaders.Names.USER_AGENT); // add custom if (this.headers != null) { for (Entry<String, String> item : this.headers.entrySet()) { request.headers().set(item.getKey(), item.getValue()); } } // add cookie if (this.cookies != null) { String cookieValue = ClientCookieEncoder.STRICT.encode(cookies); request.headers().set(HttpHeaders.Names.COOKIE, cookieValue); } }
@Test public void testFilenameContainingSemicolon() throws Exception { final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost"); req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); // Force to use memory-based data. final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false); final String data = "asdf"; final String filename = "tmp;0.txt"; final String body = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n" + "Content-Type: image/gif\r\n" + "\r\n" + data + "\r\n" + "--" + boundary + "--\r\n"; req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8.name())); // Create decoder instance to test. final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req); assertFalse(decoder.getBodyHttpDatas().isEmpty()); decoder.destroy(); }
public FullHttpRequest build() { FullHttpRequest req = new DefaultFullHttpRequest(httpVersion, method, uri); HttpHeaders headers = req.headers(); if (host != null) { headers.set(Names.HOST, host); } if (upgrade != null) { headers.set(Names.UPGRADE, upgrade); } if (connection != null) { headers.set(Names.CONNECTION, connection); } if (key != null) { headers.set(Names.SEC_WEBSOCKET_KEY, key); } if (origin != null) { headers.set(Names.SEC_WEBSOCKET_ORIGIN, origin); } if (version != null) { headers.set(Names.SEC_WEBSOCKET_VERSION, version.toHttpHeaderValue()); } return req; }
public static void main(String[] args) { PropertyConfigurator.configure("conf/log4j.properties"); AsyncHttpClient client = new AsyncHttpClient(); DefaultFullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, "/AsyncHttpClient"); client.sendRequest("127.0.0.1", 8888, request, new Callback() { public void onResponse(FullHttpResponse response) { // TODO Auto-generated method stub System.out.println("AsyncHttpClient onResponse"); } public void onTimeout() { // TODO Auto-generated method stub System.out.println("AsyncHttpClient onTimeout"); } public void onConnectFail() { // TODO Auto-generated method stub System.out.println("AsyncHttpClient onConnectFail"); } }); }
@Test public void testSelectModuleDocs() { Map<String, Module> modules = new LinkedHashMap<String, Module>(); ForwardingModule expectedModule = new ForwardingModule("theChosen", 8080, new NoOperationProcessor(), new NoOperationProcessor()); modules.put("/fake/deeper", new ForwardingModule("notImportant3", 8080, new NoOperationProcessor(), new NoOperationProcessor())); modules.put("/fake", new ForwardingModule("notImportant2", 8080, new NoOperationProcessor(), new NoOperationProcessor())); modules.put("/docs/deeper1", new ForwardingModule("notImportant4", 8080, new NoOperationProcessor(), new NoOperationProcessor())); modules.put("/docs/deeper2", new ForwardingModule("notImportant5", 8080, new NoOperationProcessor(), new NoOperationProcessor())); modules.put("/docs", expectedModule); modules.put("/", new ForwardingModule("notImportant1", 8080, new NoOperationProcessor(), new NoOperationProcessor())); DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/docs"); ModuleSelector moduleSelector = new ModuleSelector(modules); Module module = moduleSelector.selectModule(httpRequest); Assert.assertSame(expectedModule, module); }
@Test public void testSelectModuleDocsDeeper1() { Map<String, Module> modules = new LinkedHashMap<String, Module>(); ForwardingModule expectedModule = new ForwardingModule("theChosen", 8080, new NoOperationProcessor(), new NoOperationProcessor()); modules.put("/fake", new ForwardingModule("notImportant2", 8080, new NoOperationProcessor(), new NoOperationProcessor())); modules.put("/docs", new ForwardingModule("notImportant3", 8080, new NoOperationProcessor(), new NoOperationProcessor())); modules.put("/docs/deeper1", expectedModule); modules.put("/docs/deeper2", new ForwardingModule("notImportant4", 8080, new NoOperationProcessor(), new NoOperationProcessor())); modules.put("/", new ForwardingModule("notImportant1", 8080, new NoOperationProcessor(), new NoOperationProcessor())); DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/docs/deeper1"); ModuleSelector moduleSelector = new ModuleSelector(modules); Module module = moduleSelector.selectModule(httpRequest); Assert.assertSame(expectedModule, module); }
@Test public void testFullRequest() throws Exception { outputReceived = new CountDownLatch(1); FullHttpRequest requestIn = new DefaultFullHttpRequest(HTTP_1_1, GET, "/"); channel.writeInbound(requestIn); channel.runPendingTasks(); // blocks Uninterruptibles.awaitUninterruptibly(outputReceived); Request requestOut = requests.remove(0); assertTrue(requestOut != null); assertTrue(requestOut instanceof FullRequest); assertEquals("HTTP/1.1", requestOut.version()); assertEquals(HttpMethod.GET, requestOut.method()); assertEquals("/", requestOut.path()); assertFalse(requestOut.hasBody()); assertFalse(requestOut.body() == null); assertEquals(0, requestOut.body().readableBytes()); }
@Test public void testFullRequestWithBody() throws Exception { outputReceived = new CountDownLatch(1); String payload = "body"; ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, payload); FullHttpRequest requestIn = new DefaultFullHttpRequest(HTTP_1_1, GET, "/", body); channel.writeInbound(requestIn); channel.runPendingTasks(); // blocks Uninterruptibles.awaitUninterruptibly(outputReceived); Request requestOut = requests.remove(0); assertTrue(requestOut != null); assertTrue(requestOut instanceof FullRequest); assertEquals("HTTP/1.1", requestOut.version()); assertEquals(HttpMethod.GET, requestOut.method()); assertEquals("/", requestOut.path()); assertTrue(requestOut.hasBody()); assertFalse(requestOut.body() == null); assertEquals(body, requestOut.body()); }
@Test public void testFullResponse() throws Exception { outputReceived = new CountDownLatch(2); ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "response"); FullHttpRequest requestIn = new DefaultFullHttpRequest(HTTP_1_1, GET, "/"); FullResponse responseIn = ResponseBuilders.newOk().body(body).build(); channel.writeInbound(requestIn); channel.runPendingTasks(); // blocks channel.writeOutbound(responseIn); channel.runPendingTasks(); // blocks Uninterruptibles.awaitUninterruptibly(outputReceived); HttpResponse responseOut = (HttpResponse) responses.remove(0); assertTrue(responseOut != null); assertTrue(responseOut instanceof FullHttpResponse); assertEquals(HTTP_1_1, responseOut.protocolVersion()); assertEquals(OK, responseOut.status()); assertFalse(((FullHttpResponse) responseOut).content() == null); assertEquals(body, ((FullHttpResponse) responseOut).content()); }
@Override protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception { Class<?> messageType = msg.getClass(); LowCopyProtobufOutput outputSerializer = new LowCopyProtobufOutput(); msg.cachedSchema().writeTo(outputSerializer, msg); List<ByteBuffer> serializedBuffers = outputSerializer.buffer.finish(); ByteBuf requestContent = Unpooled.wrappedBuffer(serializedBuffers.toArray(new ByteBuffer[]{})); DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest( HttpVersion.HTTP_1_0, HttpMethod.POST, "foo", requestContent); httpRequest.headers().set(HttpProtostuffConstants.PROTOSTUFF_HEADER_NAME, messageType.getName()); httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream"); httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestContent.readableBytes()); out.add(httpRequest); }
private HttpRequest encodeRestApiRequest(ChannelHandlerContext ctx, RestApiRequest msg) { HttpMethod httpMethod = msg.method(); ByteBuf content = Unpooled.copiedBuffer(msg.body(), CharsetUtil.UTF_8); String path = msg.pathWithParameters(); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, path, content); //these headers COULD be overridden request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent()); request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx)); for (Map.Entry<String, Object> header : msg.headers().entrySet()) { request.headers().set(header.getKey(), header.getValue()); } //these headers should always be computed from the msg request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes()); addHttpBasicAuth(ctx, request, msg.username(), msg.password()); return request; }
@Test public void shouldUrlEncodeShortKeys() { String urlEncodedKeys = "%5B%221%22%2C%222%22%2C%223%22%5D"; String keys = "[\"1\",\"2\",\"3\"]"; String query = "stale=false&endKey=test"; ViewQueryRequest request = new ViewQueryRequest("design", "view", true, query, keys, "bucket", "password"); channel.writeOutbound(request); DefaultFullHttpRequest outbound = (DefaultFullHttpRequest) channel.readOutbound(); String failMsg = outbound.getUri(); assertEquals(HttpMethod.GET, outbound.getMethod()); assertTrue(failMsg, outbound.getUri().contains("keys=")); assertTrue(failMsg, outbound.getUri().endsWith("?stale=false&endKey=test&keys=" + urlEncodedKeys)); String content = outbound.content().toString(CharsetUtil.UTF_8); assertTrue(content.isEmpty()); ReferenceCountUtil.releaseLater(outbound); //NO-OP since content is empty but still... }
@Override protected FullHttpRequest buildRequest() { final StringBuilder uriBuilder = new StringBuilder(); uriBuilder.append("/v2/keys").append(key); final StringBuilder queryBuilder = new StringBuilder(); if (previousValue != null) { appendQueryStringSeparator(queryBuilder); queryBuilder.append("prevValue=").append(urlEncode(previousValue)); } if (previousIndex != null) { appendQueryStringSeparator(queryBuilder); queryBuilder.append("prevIndex=").append(previousIndex); } if (directory) { appendQueryStringSeparator(queryBuilder); queryBuilder.append("dir=true"); } if (recursive) { appendQueryStringSeparator(queryBuilder); queryBuilder.append("recursive=true"); } uriBuilder.append(queryBuilder); return new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, uriBuilder.toString()); }
@Override public void push(final String method, final String path, final Map<String, Object> headers) { ctx.channel().eventLoop().execute(() -> { AsciiString streamIdHeader = HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(); Http2Connection connection = encoder.connection(); int nextStreamId = connection.local().incrementAndGetNextStreamId(); Http2Headers h2headers = new DefaultHttp2Headers() .path(path) .method(method) .authority(authority) .scheme(scheme); headers.forEach((n, v) -> h2headers.add(n, v.toString())); encoder.writePushPromise(ctx, streamId, nextStreamId, h2headers, 0, ctx.newPromise()); // TODO: Is there another way of handling a push promise? DefaultFullHttpRequest pushRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method.toUpperCase()), path, Unpooled.EMPTY_BUFFER, new DefaultHttpHeaders(false).set(streamIdHeader, nextStreamId), EmptyHttpHeaders.INSTANCE); ctx.pipeline().fireChannelRead(pushRequest); ctx.pipeline().fireChannelReadComplete(); }); }
@Test public void testLanguageOrder() throws Exception { HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); req.headers().set(HeaderNames.ACCEPT_LANGUAGE, "da, en-gb;q=0.8, en;q=0.7"); RequestFromVertx request = new RequestFromVertx(create(req)); assertThat(request.languages()).containsExactly( new Locale("da"), new Locale("en", "gb"), new Locale("en") ); req.headers().set(HeaderNames.ACCEPT_LANGUAGE, "da, en-gb;q=0.7, en;q=0.9"); request = new RequestFromVertx(create(req)); assertThat(request.languages()).containsExactly( new Locale("da"), new Locale("en"), new Locale("en", "gb") ); }
@Test public void testHeader() throws Exception { HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); req.headers().add(HeaderNames.ACCEPT_ENCODING, "gzip, deflate"); req.headers().add(HeaderNames.ACCEPT_LANGUAGE, "en-US"); req.headers().add(HeaderNames.ACCEPT_CHARSET, "utf-8"); req.headers().add("test", "a").add("test", "b"); ContextFromVertx context = new ContextFromVertx(vertx, vertx.getOrCreateContext(), accessor, RequestFromVertXTest.create(req)); assertThat(context.headers().containsKey(HeaderNames.ACCEPT_LANGUAGE)).isTrue(); assertThat(context.header(HeaderNames.ACCEPT_LANGUAGE)).isEqualTo("en-US"); assertThat(context.headers().get("test")).containsExactly("a", "b"); assertThat(context.headers("test")).containsExactly("a", "b"); assertThat(context.headers().get("missing")).isNull(); assertThat(context.header("missing")).isNull(); }
@Test public void testQueryParamsDecode() { final DefaultFullHttpRequest defaultRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/v1.0/ac98760XYZ/experimental/metric_views/metXYZ?from=12345&to=56789&points=100" + "&foo=x,y,z&foo=p"); final HttpRequestWithDecodedQueryParams requestWithParams = HttpRequestWithDecodedQueryParams.create(defaultRequest); Map<String, List<String>> queryParams = requestWithParams.getQueryParams(); Assert.assertEquals(4, queryParams.size()); final String fromParam = queryParams.get("from").get(0); final String toParam = queryParams.get("to").get(0); final String pointsParam = queryParams.get("points").get(0); List<String> fooParams = queryParams.get("foo"); Assert.assertEquals(12345, Integer.parseInt(fromParam)); Assert.assertEquals(56789, Integer.parseInt(toParam)); Assert.assertEquals(100, Integer.parseInt(pointsParam)); Assert.assertEquals(2, fooParams.size()); for (String fooParam : fooParams) { Assert.assertTrue(fooParam.equals("x,y,z") || fooParam.equals("p")); } }