List of usage examples for io.netty.handler.codec.http HttpMethod GET
HttpMethod GET
To view the source code for io.netty.handler.codec.http HttpMethod GET.
Click Source Link
From source file:org.elasticsearch.http.nio.Netty4HttpClient.java
License:Apache License
public Collection<FullHttpResponse> get(SocketAddress remoteAddress, String... uris) throws InterruptedException { Collection<HttpRequest> requests = new ArrayList<>(uris.length); for (int i = 0; i < uris.length; i++) { final HttpRequest httpRequest = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, uris[i]); httpRequest.headers().add(HOST, "localhost"); httpRequest.headers().add(Task.X_OPAQUE_ID, String.valueOf(i)); requests.add(httpRequest);//from ww w.j a va2 s .c o m } return sendRequests(remoteAddress, requests); }
From source file:org.elasticsearch.http.nio.NioHttpChannelTests.java
License:Apache License
public void testHeadersSet() { Settings settings = Settings.builder().build(); final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); httpRequest.headers().add(HttpHeaderNames.ORIGIN, "remote"); final NioHttpRequest request = new NioHttpRequest(xContentRegistry(), httpRequest); HttpHandlingSettings handlingSettings = HttpHandlingSettings.fromSettings(settings); NioCorsConfig corsConfig = NioHttpServerTransport.buildCorsConfig(settings); // send a response NioHttpChannel channel = new NioHttpChannel(nioChannel, bigArrays, request, 1, handlingSettings, corsConfig, threadPool.getThreadContext()); TestResponse resp = new TestResponse(); final String customHeader = "custom-header"; final String customHeaderValue = "xyz"; resp.addHeader(customHeader, customHeaderValue); channel.sendResponse(resp);/*from www . ja v a 2 s .c o m*/ // inspect what was written ArgumentCaptor<Object> responseCaptor = ArgumentCaptor.forClass(Object.class); verify(channelContext).sendMessage(responseCaptor.capture(), any()); Object nioResponse = responseCaptor.getValue(); HttpResponse response = ((NioHttpResponse) nioResponse).getResponse(); assertThat(response.headers().get("non-existent-header"), nullValue()); assertThat(response.headers().get(customHeader), equalTo(customHeaderValue)); assertThat(response.headers().get(HttpHeaderNames.CONTENT_LENGTH), equalTo(Integer.toString(resp.content().length()))); assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE), equalTo(resp.contentType())); }
From source file:org.elasticsearch.http.nio.NioHttpChannelTests.java
License:Apache License
@SuppressWarnings("unchecked") public void testReleaseInListener() throws IOException { final Settings settings = Settings.builder().build(); final NamedXContentRegistry registry = xContentRegistry(); final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); final NioHttpRequest request = new NioHttpRequest(registry, httpRequest); HttpHandlingSettings handlingSettings = HttpHandlingSettings.fromSettings(settings); NioCorsConfig corsConfig = NioHttpServerTransport.buildCorsConfig(settings); NioHttpChannel channel = new NioHttpChannel(nioChannel, bigArrays, request, 1, handlingSettings, corsConfig, threadPool.getThreadContext()); final BytesRestResponse response = new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, JsonXContent.contentBuilder().startObject().endObject()); assertThat(response.content(), not(instanceOf(Releasable.class))); // ensure we have reserved bytes if (randomBoolean()) { BytesStreamOutput out = channel.bytesOutput(); assertThat(out, instanceOf(ReleasableBytesStreamOutput.class)); } else {/*from w w w. ja v a 2 s. c o m*/ try (XContentBuilder builder = channel.newBuilder()) { // do something builder builder.startObject().endObject(); } } channel.sendResponse(response); Class<BiConsumer<Void, Exception>> listenerClass = (Class<BiConsumer<Void, Exception>>) (Class) BiConsumer.class; ArgumentCaptor<BiConsumer<Void, Exception>> listenerCaptor = ArgumentCaptor.forClass(listenerClass); verify(channelContext).sendMessage(any(), listenerCaptor.capture()); BiConsumer<Void, Exception> listener = listenerCaptor.getValue(); if (randomBoolean()) { listener.accept(null, null); } else { listener.accept(null, new ClosedChannelException()); } // ESTestCase#after will invoke ensureAllArraysAreReleased which will fail if the response content was not released }
From source file:org.elasticsearch.http.nio.NioHttpChannelTests.java
License:Apache License
@SuppressWarnings("unchecked") public void testConnectionClose() throws Exception { final Settings settings = Settings.builder().build(); final FullHttpRequest httpRequest; final boolean close = randomBoolean(); if (randomBoolean()) { httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); if (close) { httpRequest.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); }//from www . j a va 2s.c o m } else { httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/"); if (!close) { httpRequest.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } } final NioHttpRequest request = new NioHttpRequest(xContentRegistry(), httpRequest); HttpHandlingSettings handlingSettings = HttpHandlingSettings.fromSettings(settings); NioCorsConfig corsConfig = NioHttpServerTransport.buildCorsConfig(settings); NioHttpChannel channel = new NioHttpChannel(nioChannel, bigArrays, request, 1, handlingSettings, corsConfig, threadPool.getThreadContext()); final TestResponse resp = new TestResponse(); channel.sendResponse(resp); Class<BiConsumer<Void, Exception>> listenerClass = (Class<BiConsumer<Void, Exception>>) (Class) BiConsumer.class; ArgumentCaptor<BiConsumer<Void, Exception>> listenerCaptor = ArgumentCaptor.forClass(listenerClass); verify(channelContext).sendMessage(any(), listenerCaptor.capture()); BiConsumer<Void, Exception> listener = listenerCaptor.getValue(); listener.accept(null, null); if (close) { verify(nioChannel, times(1)).close(); } else { verify(nioChannel, times(0)).close(); } }
From source file:org.elasticsearch.http.nio.NioHttpChannelTests.java
License:Apache License
private FullHttpResponse executeRequest(final Settings settings, final String originValue, final String host) { // construct request and send it over the transport layer final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); if (originValue != null) { httpRequest.headers().add(HttpHeaderNames.ORIGIN, originValue); }// ww w .j ava 2 s . co m httpRequest.headers().add(HttpHeaderNames.HOST, host); final NioHttpRequest request = new NioHttpRequest(xContentRegistry(), httpRequest); HttpHandlingSettings httpHandlingSettings = HttpHandlingSettings.fromSettings(settings); NioCorsConfig corsConfig = NioHttpServerTransport.buildCorsConfig(settings); NioHttpChannel channel = new NioHttpChannel(nioChannel, bigArrays, request, 1, httpHandlingSettings, corsConfig, threadPool.getThreadContext()); channel.sendResponse(new TestResponse()); // get the response ArgumentCaptor<Object> responseCaptor = ArgumentCaptor.forClass(Object.class); verify(channelContext, atLeastOnce()).sendMessage(responseCaptor.capture(), any()); return ((NioHttpResponse) responseCaptor.getValue()).getResponse(); }
From source file:org.elasticsearch.http.nio.NioHttpClient.java
License:Apache License
public Collection<FullHttpResponse> get(InetSocketAddress remoteAddress, String... uris) throws InterruptedException { Collection<HttpRequest> requests = new ArrayList<>(uris.length); for (int i = 0; i < uris.length; i++) { final HttpRequest httpRequest = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, uris[i]); httpRequest.headers().add(HOST, "localhost"); httpRequest.headers().add(Task.X_OPAQUE_ID, String.valueOf(i)); requests.add(httpRequest);// ww w . j a v a2 s .co m } return sendRequests(remoteAddress, requests); }
From source file:org.elasticsearch.http.nio.NioHttpRequest.java
License:Apache License
@Override public RestRequest.Method method() { HttpMethod httpMethod = request.method(); if (httpMethod == HttpMethod.GET) return RestRequest.Method.GET; if (httpMethod == HttpMethod.POST) return RestRequest.Method.POST; if (httpMethod == HttpMethod.PUT) return RestRequest.Method.PUT; if (httpMethod == HttpMethod.DELETE) return RestRequest.Method.DELETE; if (httpMethod == HttpMethod.HEAD) { return RestRequest.Method.HEAD; }/*ww w. j a v a2s .c o m*/ if (httpMethod == HttpMethod.OPTIONS) { return RestRequest.Method.OPTIONS; } if (httpMethod == HttpMethod.PATCH) { return RestRequest.Method.PATCH; } if (httpMethod == HttpMethod.TRACE) { return RestRequest.Method.TRACE; } if (httpMethod == HttpMethod.CONNECT) { return RestRequest.Method.CONNECT; } throw new IllegalArgumentException("Unexpected http method: " + httpMethod); }
From source file:org.elasticsearch.http.nio.NioHttpServerTransportTests.java
License:Apache License
public void testBadRequest() throws InterruptedException { final AtomicReference<Throwable> causeReference = new AtomicReference<>(); final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() { @Override// www . ja va 2s.c om public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) { throw new AssertionError(); } @Override public void dispatchBadRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext, final Throwable cause) { causeReference.set(cause); try { final ElasticsearchException e = new ElasticsearchException( "you sent a bad request and you should feel bad"); channel.sendResponse(new BytesRestResponse(channel, BAD_REQUEST, e)); } catch (final IOException e) { throw new AssertionError(e); } } }; final Settings settings; final int maxInitialLineLength; final Setting<ByteSizeValue> httpMaxInitialLineLengthSetting = HttpTransportSettings.SETTING_HTTP_MAX_INITIAL_LINE_LENGTH; if (randomBoolean()) { maxInitialLineLength = httpMaxInitialLineLengthSetting.getDefault(Settings.EMPTY).bytesAsInt(); settings = Settings.EMPTY; } else { maxInitialLineLength = randomIntBetween(1, 8192); settings = Settings.builder().put(httpMaxInitialLineLengthSetting.getKey(), maxInitialLineLength + "b") .build(); } try (NioHttpServerTransport transport = new NioHttpServerTransport(settings, networkService, bigArrays, pageRecycler, threadPool, xContentRegistry(), dispatcher)) { transport.start(); final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses()); try (NioHttpClient client = new NioHttpClient()) { final String url = "/" + new String(new byte[maxInitialLineLength], Charset.forName("UTF-8")); final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url); final FullHttpResponse response = client.post(remoteAddress.address(), request); try { assertThat(response.status(), equalTo(HttpResponseStatus.BAD_REQUEST)); assertThat(new String(response.content().array(), Charset.forName("UTF-8")), containsString("you sent a bad request and you should feel bad")); } finally { response.release(); } } } assertNotNull(causeReference.get()); assertThat(causeReference.get(), instanceOf(TooLongFrameException.class)); }
From source file:org.glowroot.central.SyntheticMonitorService.java
License:Apache License
private static ListenableFuture<HttpResponseStatus> runPing(String url) throws Exception { URI uri = new URI(url); String scheme = uri.getScheme(); if (scheme == null) { throw new IllegalStateException("URI missing scheme"); }//from w ww.j av a2 s.c o m final boolean ssl = uri.getScheme().equalsIgnoreCase("https"); final String host = uri.getHost(); if (host == null) { throw new IllegalStateException("URI missing host"); } final int port; if (uri.getPort() == -1) { port = ssl ? 443 : 80; } else { port = uri.getPort(); } final EventLoopGroup group = new NioEventLoopGroup(); final HttpClientHandler httpClientHandler = new HttpClientHandler(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (ssl) { SslContext sslContext = SslContextBuilder.forClient().build(); p.addLast(sslContext.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec()); p.addLast(new HttpObjectAggregator(1048576)); p.addLast(httpClientHandler); } }); final HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaderNames.HOST, host); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); request.headers().set("Glowroot-Transaction-Type", "Synthetic"); ChannelFuture future = bootstrap.connect(host, port); final SettableFuture<HttpResponseStatus> settableFuture = SettableFuture.create(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { Channel ch = future.channel(); if (future.isSuccess()) { ch.writeAndFlush(request); } ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { HttpResponseStatus responseStatus = httpClientHandler.responseStatus; if (HttpResponseStatus.OK.equals(responseStatus)) { settableFuture.set(responseStatus); } else { settableFuture.setException( new Exception("Unexpected http response status: " + responseStatus)); } } else { settableFuture.setException(future.cause()); } group.shutdownGracefully(); } }); } }); return settableFuture; }
From source file:org.glowroot.common2.repo.util.HttpClient.java
License:Apache License
private String postOrGet(String url, byte /*@Nullable*/ [] content, @Nullable String contentType, final HttpProxyConfig httpProxyConfig, final @Nullable String passwordOverride) throws Exception { URI uri = new URI(url); String scheme = checkNotNull(uri.getScheme()); final boolean ssl = scheme.equalsIgnoreCase("https"); final String host = checkNotNull(uri.getHost()); final int port; if (uri.getPort() == -1) { port = ssl ? 443 : 80;/*from www . j a va 2 s . co m*/ } else { port = uri.getPort(); } EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); // TODO follow netty proxy support at https://github.com/netty/netty/issues/1133 final HttpProxyHandler httpProxyHandler = newHttpProxyHandlerIfNeeded(httpProxyConfig, passwordOverride); final HttpClientHandler handler = new HttpClientHandler(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (httpProxyHandler != null) { p.addLast(httpProxyHandler); } if (ssl) { SslContext sslContext = SslContextBuilder.forClient().build(); p.addLast(sslContext.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec()); p.addLast(new HttpObjectAggregator(1048576)); p.addLast(handler); } }); if (!httpProxyConfig.host().isEmpty()) { // name resolution should be performed by the proxy server in case some proxy rules // depend on the remote hostname bootstrap.resolver(NoopAddressResolverGroup.INSTANCE); } HttpRequest request; if (content == null) { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); } else { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(), Unpooled.wrappedBuffer(content)); request.headers().set(HttpHeaderNames.CONTENT_TYPE, checkNotNull(contentType)); request.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.length); } request.headers().set(HttpHeaderNames.HOST, host); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); Channel ch = bootstrap.connect(host, port).sync().channel(); if (httpProxyHandler != null) { // this line is needed to capture and throw connection exception properly httpProxyHandler.connectFuture().get(); } ch.writeAndFlush(request).get(); ch.closeFuture().sync().get(); Throwable exception = handler.exception; if (exception != null) { Throwables.propagateIfPossible(exception, Exception.class); throw new Exception(exception); } HttpResponseStatus responseStatus = checkNotNull(handler.responseStatus); int statusCode = responseStatus.code(); if (statusCode == 429) { throw new TooManyRequestsHttpResponseException(); } else if (statusCode < 200 || statusCode >= 300) { throw new IOException("Unexpected response status code: " + statusCode); } return checkNotNull(handler.responseContent); } finally { group.shutdownGracefully(0, 10, SECONDS).get(); } }