Search in sources :

Example 46 with DefaultHttpRequest

use of io.netty.handler.codec.http.DefaultHttpRequest in project Glowstone by GlowstoneMC.

the class HttpClient method connect.

/**
 * Opens a URL.
 *
 * @param url       the URL to download
 * @param eventLoop an {@link EventLoop} that will receive the response body
 * @param callback  a callback to handle the response or any error
 */
public void connect(String url, EventLoop eventLoop, HttpCallback callback) {
    URI uri = URI.create(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    SslContext sslCtx = null;
    if ("https".equalsIgnoreCase(scheme)) {
        if (port == -1) {
            port = 443;
        }
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (SSLException e) {
            callback.error(e);
            return;
        }
    } else if ("http".equalsIgnoreCase(scheme)) {
        if (port == -1) {
            port = 80;
        }
    } else {
        throw new IllegalArgumentException("Only http(s) is supported!");
    }
    new Bootstrap().group(eventLoop).resolver(resolverGroup).channel(Networking.bestSocketChannel()).handler(new HttpChannelInitializer(sslCtx, callback)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).connect(InetSocketAddress.createUnresolved(host, port)).addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
            HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
            request.headers().set(HttpHeaderNames.HOST, host);
            future.channel().writeAndFlush(request);
        } else {
            callback.error(future.cause());
        }
    });
}
Also used : HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) DnsServerAddressStreamProvider(io.netty.resolver.dns.DnsServerAddressStreamProvider) SequentialDnsServerAddressStreamProvider(io.netty.resolver.dns.SequentialDnsServerAddressStreamProvider) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SocketUtils(io.netty.util.internal.SocketUtils) URI(java.net.URI) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpMethod(io.netty.handler.codec.http.HttpMethod) EventLoop(io.netty.channel.EventLoop) DnsServerAddressStreamProviders(io.netty.resolver.dns.DnsServerAddressStreamProviders) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) Networking(net.glowstone.net.Networking) SSLException(javax.net.ssl.SSLException) List(java.util.List) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) DnsEndpoint(net.glowstone.net.config.DnsEndpoint) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) DnsAddressResolverGroup(io.netty.resolver.dns.DnsAddressResolverGroup) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) DnsEndpoint(net.glowstone.net.config.DnsEndpoint) SslContext(io.netty.handler.ssl.SslContext)

Example 47 with DefaultHttpRequest

use of io.netty.handler.codec.http.DefaultHttpRequest in project crate by crate.

the class HttpAuthUpstreamHandlerTest method testNotNoHbaConfig.

@Test
public void testNotNoHbaConfig() throws Exception {
    HttpAuthUpstreamHandler handler = new HttpAuthUpstreamHandler(Settings.EMPTY, authService);
    EmbeddedChannel ch = new EmbeddedChannel(handler);
    DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/_sql");
    request.headers().add(HttpHeaderNames.AUTHORIZATION.toString(), "Basic QWxhZGRpbjpPcGVuU2VzYW1l");
    request.headers().add("X-Real-Ip", "10.1.0.100");
    ch.writeInbound(request);
    ch.releaseInbound();
    assertFalse(handler.authorized());
    assertUnauthorized(ch.readOutbound(), "No valid auth.host_based.config entry found for host \"10.1.0.100\", user \"Aladdin\", protocol \"http\". Did you enable TLS in your client?\n");
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Test(org.junit.Test)

Example 48 with DefaultHttpRequest

use of io.netty.handler.codec.http.DefaultHttpRequest in project crate by crate.

the class HttpAuthUpstreamHandlerTest method testAuthorized.

@Test
public void testAuthorized() throws Exception {
    HttpAuthUpstreamHandler handler = new HttpAuthUpstreamHandler(Settings.EMPTY, new AlwaysOKAuthentication(userName -> User.CRATE_USER));
    EmbeddedChannel ch = new EmbeddedChannel(handler);
    DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/_sql");
    ch.writeInbound(request);
    ch.releaseInbound();
    assertThat(handler.authorized(), is(true));
}
Also used : HttpVersion(io.netty.handler.codec.http.HttpVersion) BeforeClass(org.junit.BeforeClass) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) Unpooled(io.netty.buffer.Unpooled) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Settings(org.elasticsearch.common.settings.Settings) SSLSession(javax.net.ssl.SSLSession) SystemDefaultDnsResolver(org.apache.http.impl.conn.SystemDefaultDnsResolver) WWW_AUTHENTICATE_REALM_MESSAGE(io.crate.auth.HttpAuthUpstreamHandler.WWW_AUTHENTICATE_REALM_MESSAGE) Locale(java.util.Locale) Is.is(org.hamcrest.core.Is.is) ESTestCase(org.elasticsearch.test.ESTestCase) EnumSet(java.util.EnumSet) HttpRequest(io.netty.handler.codec.http.HttpRequest) User(io.crate.user.User) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) StandardCharsets(java.nio.charset.StandardCharsets) Certificate(java.security.cert.Certificate) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Mockito.mock(org.mockito.Mockito.mock) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Test(org.junit.Test)

Example 49 with DefaultHttpRequest

use of io.netty.handler.codec.http.DefaultHttpRequest in project graylog2-server by Graylog2.

the class HttpHandlerTest method successfullyProcessOPTIONSRequest.

@Test
public void successfullyProcessOPTIONSRequest() {
    final HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/gelf");
    httpRequest.headers().add(HttpHeaderNames.HOST, "localhost");
    httpRequest.headers().add(HttpHeaderNames.ORIGIN, "http://example.com");
    httpRequest.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    channel.writeInbound(httpRequest);
    channel.finish();
    final HttpResponse httpResponse = channel.readOutbound();
    assertThat(httpResponse.status()).isEqualTo(HttpResponseStatus.OK);
    final HttpHeaders headers = httpResponse.headers();
    assertThat(headers.get(HttpHeaderNames.CONTENT_LENGTH)).isEqualTo("0");
    assertThat(headers.get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("http://example.com");
    assertThat(headers.get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS)).isEqualTo("true");
    assertThat(headers.get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS)).isEqualTo("Authorization, Content-Type");
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpResponse(io.netty.handler.codec.http.HttpResponse) Test(org.junit.Test)

Example 50 with DefaultHttpRequest

use of io.netty.handler.codec.http.DefaultHttpRequest in project rest.li by linkedin.

the class NettyRequestAdapter method toNettyRequest.

/**
 * Adapts a StreamRequest to Netty's HttpRequest
 * @param request  R2 stream request
 * @return Adapted HttpRequest.
 */
public static HttpRequest toNettyRequest(StreamRequest request) throws Exception {
    HttpMethod nettyMethod = HttpMethod.valueOf(request.getMethod());
    URL url = new URL(request.getURI().toString());
    String path = url.getFile();
    // it MUST be given as "/" (the server root).
    if (path.isEmpty()) {
        path = "/";
    }
    HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, nettyMethod, path);
    nettyRequest.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
        // that contains a Transfer-Encoding header field.
        if (entry.getKey().equalsIgnoreCase(HttpHeaderNames.CONTENT_LENGTH.toString())) {
            continue;
        }
        nettyRequest.headers().set(entry.getKey(), entry.getValue());
    }
    nettyRequest.headers().set(HttpHeaderNames.HOST, url.getAuthority());
    // RFC 6265
    // When the user agent generates an HTTP/1.1 request, the user agent MUST
    // NOT attach more than one Cookie header field.
    String encodedCookieHeaderValues = CookieUtil.clientEncode(request.getCookies());
    if (encodedCookieHeaderValues != null) {
        nettyRequest.headers().set(HttpConstants.REQUEST_COOKIE_HEADER_NAME, encodedCookieHeaderValues);
    }
    return nettyRequest;
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) AsciiString(io.netty.util.AsciiString) Map(java.util.Map) HttpMethod(io.netty.handler.codec.http.HttpMethod) URL(java.net.URL)

Aggregations

DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)115 HttpRequest (io.netty.handler.codec.http.HttpRequest)81 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)53 Test (org.junit.Test)51 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)44 HttpMethod (io.netty.handler.codec.http.HttpMethod)23 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)20 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)18 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)16 HttpContent (io.netty.handler.codec.http.HttpContent)13 HttpObject (io.netty.handler.codec.http.HttpObject)13 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)12 ByteBuf (io.netty.buffer.ByteBuf)11 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)11 Test (org.junit.jupiter.api.Test)10 Channel (io.netty.channel.Channel)9 ArrayList (java.util.ArrayList)9 Nettys4Test (org.jocean.http.util.Nettys4Test)9 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)8 DisposableWrapper (org.jocean.idiom.DisposableWrapper)6