Search in sources :

Example 46 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project turbo-rpc by hank-whu.

the class NettyRestHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, final FullHttpRequest httpRequest) throws Exception {
    boolean keepAlive = HttpUtil.isKeepAlive(httpRequest);
    String uri = httpRequest.uri();
    HttpMethod httpMethod = httpRequest.method();
    int index = uri.indexOf('&', invokerFactory.restPrefix.length());
    if (index < 0) {
        index = uri.length();
    }
    if (invokerFactory.restPrefix.length() >= index) {
        if (logger.isInfoEnabled()) {
            logger.info("not support this method " + toString(httpRequest));
        }
        doRequestFilter(httpRequest, null);
        ctx.write(new RestHttpResponse(null, httpRequest, NOT_FOUND, NOT_SUPPORT_THIS_METHOD, keepAlive), ctx.voidPromise());
        return;
    }
    String restPath = uri.substring(invokerFactory.restPrefix.length(), index);
    final Invoker<CompletableFuture<?>> invoker = invokerFactory.get(restPath);
    CompletableFuture<?> future = null;
    try {
        if (invoker == null) {
            if (logger.isInfoEnabled()) {
                logger.info("not support this method " + toString(httpRequest));
            }
            doRequestFilter(httpRequest, null);
            ctx.write(new RestHttpResponse(null, httpRequest, NOT_FOUND, NOT_SUPPORT_THIS_METHOD, keepAlive), ctx.voidPromise());
            return;
        }
        boolean allowHandle = doRequestFilter(httpRequest, invoker);
        if (!allowHandle) {
            ctx.write(new RestHttpResponse(invoker, httpRequest, SERVICE_UNAVAILABLE, RestServerFilter.SERVER_FILTER_DENY, keepAlive), ctx.voidPromise());
            return;
        }
        Object params = null;
        if (httpMethod == HttpMethod.GET) {
            params = HttpParamExtractor.extractFromQueryPath(invoker, uri, index);
        } else if (httpMethod == HttpMethod.POST) {
            params = HttpParamExtractor.extractFromBody(invoker, jsonMapper, httpRequest.content());
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("only support get and post " + toString(httpRequest));
            }
            ctx.write(new RestHttpResponse(invoker, httpRequest, INTERNAL_SERVER_ERROR, ONLY_SUPPORT_GET_POST, keepAlive), ctx.voidPromise());
            return;
        }
        if (params == null) {
            future = invoker.invoke();
        } else if (params instanceof MethodParam) {
            future = invoker.invoke((MethodParam) params);
        } else if (params instanceof Object[]) {
            future = invoker.invoke((Object[]) params);
        } else {
            future = invoker.invoke((Object) params);
        }
    } catch (Throwable e) {
        if (logger.isWarnEnabled()) {
            logger.warn(uri + " error ", e);
        }
        ctx.write(new RestHttpResponse(invoker, httpRequest, INTERNAL_SERVER_ERROR, e, keepAlive), ctx.voidPromise());
        return;
    }
    if (future == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("unknown error " + toString(httpRequest));
        }
        ctx.write(new RestHttpResponse(invoker, httpRequest, INTERNAL_SERVER_ERROR, UNKNOWN, keepAlive), ctx.voidPromise());
        return;
    }
    future.whenComplete((result, throwable) -> {
        if (result != null) {
            ctx.write(new RestHttpResponse(invoker, httpRequest, OK, result, keepAlive), ctx.voidPromise());
        } else if (throwable != null) {
            ctx.write(new RestHttpResponse(invoker, httpRequest, INTERNAL_SERVER_ERROR, throwable, keepAlive), ctx.voidPromise());
        } else {
            ctx.write(new RestHttpResponse(invoker, httpRequest, INTERNAL_SERVER_ERROR, UNKNOWN, keepAlive), ctx.voidPromise());
        }
    });
}
Also used : MethodParam(rpc.turbo.param.MethodParam) CompletableFuture(java.util.concurrent.CompletableFuture) RestHttpResponse(rpc.turbo.transport.server.rest.protocol.RestHttpResponse) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 47 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project turbo-rpc by hank-whu.

the class NettyRestHandler method toString.

private String toString(FullHttpRequest httpRequest) {
    String uri = httpRequest.uri();
    HttpMethod httpMethod = httpRequest.method();
    return httpMethod.name() + " " + uri;
}
Also used : HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 48 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project elasticsearch by elastic.

the class Netty4HttpServerTransportTests method testCorsConfigWithDefaults.

public void testCorsConfigWithDefaults() {
    final Set<String> methods = Strings.commaDelimitedListToSet(SETTING_CORS_ALLOW_METHODS.getDefault(Settings.EMPTY));
    final Set<String> headers = Strings.commaDelimitedListToSet(SETTING_CORS_ALLOW_HEADERS.getDefault(Settings.EMPTY));
    final long maxAge = SETTING_CORS_MAX_AGE.getDefault(Settings.EMPTY);
    final Settings settings = Settings.builder().put(SETTING_CORS_ENABLED.getKey(), true).build();
    final Netty4CorsConfig corsConfig = Netty4HttpServerTransport.buildCorsConfig(settings);
    assertFalse(corsConfig.isAnyOriginSupported());
    assertEquals(Collections.emptySet(), corsConfig.origins().get());
    assertEquals(headers, corsConfig.allowedRequestHeaders());
    assertEquals(methods, corsConfig.allowedRequestMethods().stream().map(HttpMethod::name).collect(Collectors.toSet()));
    assertEquals(maxAge, corsConfig.maxAge());
    assertFalse(corsConfig.isCredentialsAllowed());
}
Also used : Netty4CorsConfig(org.elasticsearch.http.netty4.cors.Netty4CorsConfig) Matchers.containsString(org.hamcrest.Matchers.containsString) Strings.collectionToDelimitedString(org.elasticsearch.common.Strings.collectionToDelimitedString) Settings(org.elasticsearch.common.settings.Settings) HttpTransportSettings(org.elasticsearch.http.HttpTransportSettings) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 49 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project elasticsearch by elastic.

the class Netty4HttpServerTransportTests method testCorsConfig.

public void testCorsConfig() {
    final Set<String> methods = new HashSet<>(Arrays.asList("get", "options", "post"));
    final Set<String> headers = new HashSet<>(Arrays.asList("Content-Type", "Content-Length"));
    // sometimes have a leading whitespace between comma delimited elements
    final String prefix = randomBoolean() ? " " : "";
    final Settings settings = Settings.builder().put(SETTING_CORS_ENABLED.getKey(), true).put(SETTING_CORS_ALLOW_ORIGIN.getKey(), "*").put(SETTING_CORS_ALLOW_METHODS.getKey(), collectionToDelimitedString(methods, ",", prefix, "")).put(SETTING_CORS_ALLOW_HEADERS.getKey(), collectionToDelimitedString(headers, ",", prefix, "")).put(SETTING_CORS_ALLOW_CREDENTIALS.getKey(), true).build();
    final Netty4CorsConfig corsConfig = Netty4HttpServerTransport.buildCorsConfig(settings);
    assertTrue(corsConfig.isAnyOriginSupported());
    assertEquals(headers, corsConfig.allowedRequestHeaders());
    assertEquals(methods, corsConfig.allowedRequestMethods().stream().map(HttpMethod::name).collect(Collectors.toSet()));
}
Also used : Netty4CorsConfig(org.elasticsearch.http.netty4.cors.Netty4CorsConfig) Matchers.containsString(org.hamcrest.Matchers.containsString) Strings.collectionToDelimitedString(org.elasticsearch.common.Strings.collectionToDelimitedString) Settings(org.elasticsearch.common.settings.Settings) HttpTransportSettings(org.elasticsearch.http.HttpTransportSettings) HttpMethod(io.netty.handler.codec.http.HttpMethod) HashSet(java.util.HashSet)

Example 50 with HttpMethod

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod in project rest.li by linkedin.

the class NettyRequestAdapter method toNettyRequest.

/**
   * Adapts a RestRequest to Netty's HttpRequest
   * @param request  R2 rest request
   * @return Adapted HttpRequest.
   */
static HttpRequest toNettyRequest(RestRequest 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 = "/";
    }
    ByteBuf content = Unpooled.wrappedBuffer(request.getEntity().asByteBuffer());
    HttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, nettyMethod, path, content);
    nettyRequest.headers().set(HttpConstants.CONTENT_LENGTH, request.getEntity().length());
    for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
        nettyRequest.headers().set(entry.getKey(), entry.getValue());
    }
    nettyRequest.headers().set(HttpHeaderNames.HOST, url.getAuthority());
    nettyRequest.headers().set(HttpConstants.REQUEST_COOKIE_HEADER_NAME, request.getCookies());
    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) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) AsciiString(io.netty.util.AsciiString) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) HttpMethod(io.netty.handler.codec.http.HttpMethod) URL(java.net.URL)

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)14 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