Search in sources :

Example 31 with HttpMethod

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

the class Netty4HttpServerTransport method buildCorsConfig.

// package private for testing
static Netty4CorsConfig buildCorsConfig(Settings settings) {
    if (SETTING_CORS_ENABLED.get(settings) == false) {
        return Netty4CorsConfigBuilder.forOrigins().disable().build();
    }
    String origin = SETTING_CORS_ALLOW_ORIGIN.get(settings);
    final Netty4CorsConfigBuilder builder;
    if (Strings.isNullOrEmpty(origin)) {
        builder = Netty4CorsConfigBuilder.forOrigins();
    } else if (origin.equals(ANY_ORIGIN)) {
        builder = Netty4CorsConfigBuilder.forAnyOrigin();
    } else {
        try {
            Pattern p = RestUtils.checkCorsSettingForRegex(origin);
            if (p == null) {
                builder = Netty4CorsConfigBuilder.forOrigins(RestUtils.corsSettingAsArray(origin));
            } else {
                builder = Netty4CorsConfigBuilder.forPattern(p);
            }
        } catch (PatternSyntaxException e) {
            throw new SettingsException("Bad regex in [" + SETTING_CORS_ALLOW_ORIGIN.getKey() + "]: [" + origin + "]", e);
        }
    }
    if (SETTING_CORS_ALLOW_CREDENTIALS.get(settings)) {
        builder.allowCredentials();
    }
    String[] strMethods = Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_METHODS.get(settings), ",");
    HttpMethod[] methods = Arrays.stream(strMethods).map(HttpMethod::valueOf).toArray(HttpMethod[]::new);
    return builder.allowedRequestMethods(methods).maxAge(SETTING_CORS_MAX_AGE.get(settings)).allowedRequestHeaders(Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_HEADERS.get(settings), ",")).shortCircuit().build();
}
Also used : Pattern(java.util.regex.Pattern) Netty4CorsConfigBuilder(org.elasticsearch.http.netty4.cors.Netty4CorsConfigBuilder) SettingsException(org.elasticsearch.common.settings.SettingsException) HttpMethod(io.netty.handler.codec.http.HttpMethod) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 32 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod 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)

Example 33 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project ambry by linkedin.

the class MockChannelHandlerContext method verifySatisfactionOfRequests.

// requestPerformanceEvaluationTest() helpers.
/**
 * Verify satisfaction of all types of requests in both success and non-success cases.
 * @param content the http content used by POST request
 * @param shouldBeSatisfied whether the requests should be satisfied or not
 * @throws IOException
 */
private void verifySatisfactionOfRequests(String content, boolean shouldBeSatisfied) throws IOException {
    byte[] fullRequestBytesArr = TestUtils.getRandomBytes(18);
    RestServiceErrorCode REST_ERROR_CODE = RestServiceErrorCode.AccessDenied;
    HttpRequest httpRequest;
    // headers with error code
    HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, REST_ERROR_CODE);
    httpHeaders.set(MockNettyMessageProcessor.INCLUDE_EXCEPTION_MESSAGE_IN_RESPONSE_HEADER_NAME, "true");
    for (HttpMethod httpMethod : Arrays.asList(HttpMethod.POST, HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.HEAD)) {
        if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.GET) {
            // success POST/GET requests
            httpRequest = RestTestUtils.createRequest(httpMethod, "/", null);
            sendRequestAndEvaluateResponsePerformance(httpRequest, content, HttpResponseStatus.OK, shouldBeSatisfied);
        } else {
            // success PUT/DELETE/HEAD requests
            httpRequest = RestTestUtils.createFullRequest(httpMethod, TestingUri.ImmediateResponseComplete.toString(), null, fullRequestBytesArr);
            sendRequestAndEvaluateResponsePerformance(httpRequest, null, HttpResponseStatus.OK, shouldBeSatisfied);
        }
        // non-success PUT/DELETE/HEAD/POST/GET requests (3xx or 4xx status code)
        httpRequest = RestTestUtils.createFullRequest(httpMethod, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders, fullRequestBytesArr);
        sendRequestAndEvaluateResponsePerformance(httpRequest, null, getExpectedHttpResponseStatus(REST_ERROR_CODE), shouldBeSatisfied);
        if (!shouldBeSatisfied) {
            // test 5xx status code
            httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, RestServiceErrorCode.InternalServerError);
            httpRequest = RestTestUtils.createFullRequest(httpMethod, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders, fullRequestBytesArr);
            sendRequestAndEvaluateResponsePerformance(httpRequest, null, getExpectedHttpResponseStatus(RestServiceErrorCode.InternalServerError), false);
            httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, REST_ERROR_CODE);
        }
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 34 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project ambry by linkedin.

the class CopyForcingByteBuf method backPressureTest.

/**
 * Tests {@link NettyRequest#addContent(HttpContent)} and
 * {@link NettyRequest#readInto(AsyncWritableChannel, Callback)} with different digest algorithms (including a test
 * with no digest algorithm) and checks that back pressure is applied correctly.
 * @throws Exception
 */
@Test
public void backPressureTest() throws Exception {
    String[] digestAlgorithms = { "", "MD5", "SHA-1", "SHA-256" };
    HttpMethod[] methods = { HttpMethod.POST, HttpMethod.PUT };
    for (HttpMethod method : methods) {
        for (String digestAlgorithm : digestAlgorithms) {
            backPressureTest(digestAlgorithm, true, method);
            backPressureTest(digestAlgorithm, false, method);
        }
    }
}
Also used : HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test)

Example 35 with HttpMethod

use of io.netty.handler.codec.http.HttpMethod in project riposte by Nike-Inc.

the class RiposteHandlerInternalUtil method determineFallbackOverallRequestSpanName.

@NotNull
String determineFallbackOverallRequestSpanName(@NotNull HttpRequest nettyRequest) {
    try {
        HttpMethod method = nettyRequest.method();
        String methodName = (method == null) ? null : method.name();
        return HttpRequestTracingUtils.getFallbackSpanNameForHttpRequest(null, methodName);
    } catch (Throwable t) {
        logger.error("An unexpected error occurred while trying to extract fallback span name from Netty HttpRequest. " + "A hardcoded fallback name will be used as a last resort, however this error should be investigated " + "as it shouldn't be possible.", t);
        return "UNKNOWN_HTTP_METHOD";
    }
}
Also used : HttpMethod(io.netty.handler.codec.http.HttpMethod) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

HttpMethod (io.netty.handler.codec.http.HttpMethod)95 Test (org.junit.Test)51 HttpRequest (io.netty.handler.codec.http.HttpRequest)28 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)25 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)21 URI (java.net.URI)15 IOException (java.io.IOException)13 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)11 HttpVersion (io.netty.handler.codec.http.HttpVersion)11 DefaultHttpClient (org.jocean.http.client.impl.DefaultHttpClient)11 TestChannelCreator (org.jocean.http.client.impl.TestChannelCreator)11 TestChannelPool (org.jocean.http.client.impl.TestChannelPool)11 DefaultSignalClient (org.jocean.http.rosa.impl.DefaultSignalClient)11 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)11 Subscription (rx.Subscription)11 Action2 (rx.functions.Action2)11 ByteBuf (io.netty.buffer.ByteBuf)10 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)10 Map (java.util.Map)9