Search in sources :

Example 91 with HttpMethod

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

the class MockChannelHandlerContext method keepAliveTest.

/**
 * Tests keep-alive for different HTTP methods and error statuses.
 */
@Test
public void keepAliveTest() {
    HttpMethod[] HTTP_METHODS = { HttpMethod.POST, HttpMethod.PUT, HttpMethod.GET, HttpMethod.HEAD, HttpMethod.DELETE };
    EmbeddedChannel channel = createEmbeddedChannel();
    for (HttpMethod httpMethod : HTTP_METHODS) {
        for (RestServiceErrorCode errorCode : RestServiceErrorCode.values()) {
            channel = doKeepAliveTest(channel, httpMethod, errorCode, getExpectedHttpResponseStatus(errorCode), 0, null);
        }
        channel = doKeepAliveTest(channel, httpMethod, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 0, null);
        channel = doKeepAliveTest(channel, httpMethod, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 0, true);
        channel = doKeepAliveTest(channel, httpMethod, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 0, false);
    }
    // special test for put because the keep alive depends on content size (0 already tested above)
    channel = doKeepAliveTest(channel, HttpMethod.PUT, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 1, null);
    channel = doKeepAliveTest(channel, HttpMethod.PUT, null, HttpResponseStatus.INTERNAL_SERVER_ERROR, 100, null);
    channel.close();
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test)

Example 92 with HttpMethod

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

the class SpdyHttpDecoder method createHttpRequest.

private static FullHttpRequest createHttpRequest(SpdyHeadersFrame requestFrame, ByteBufAllocator alloc) throws Exception {
    // Create the first line of the request from the name/value pairs
    SpdyHeaders headers = requestFrame.headers();
    HttpMethod method = HttpMethod.valueOf(headers.getAsString(METHOD));
    String url = headers.getAsString(PATH);
    HttpVersion httpVersion = HttpVersion.valueOf(headers.getAsString(VERSION));
    headers.remove(METHOD);
    headers.remove(PATH);
    headers.remove(VERSION);
    boolean release = true;
    ByteBuf buffer = alloc.buffer();
    try {
        FullHttpRequest req = new DefaultFullHttpRequest(httpVersion, method, url, buffer);
        // Remove the scheme header
        headers.remove(SCHEME);
        // Replace the SPDY host header with the HTTP host header
        CharSequence host = headers.get(HOST);
        headers.remove(HOST);
        req.headers().set(HttpHeaderNames.HOST, host);
        for (Map.Entry<CharSequence, CharSequence> e : requestFrame.headers()) {
            req.headers().add(e.getKey(), e.getValue());
        }
        // The Connection and Keep-Alive headers are no longer valid
        HttpUtil.setKeepAlive(req, true);
        // Transfer-Encoding header is not valid
        req.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
        release = false;
        return req;
    } finally {
        if (release) {
            buffer.release();
        }
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBuf(io.netty.buffer.ByteBuf) HttpVersion(io.netty.handler.codec.http.HttpVersion) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 93 with HttpMethod

use of 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.
 */
public 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());
    setHttpHeadersAndCookies(request, url, nettyRequest);
    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) HttpMethod(io.netty.handler.codec.http.HttpMethod) URL(java.net.URL)

Example 94 with HttpMethod

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

the class PushMessageSender method channelRead0.

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception {
    if (!request.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, request, BAD_REQUEST, null);
        return;
    }
    final String path = request.uri();
    if (path == null) {
        sendHttpResponse(ctx, request, BAD_REQUEST, null);
        return;
    }
    if (path.endsWith("/push")) {
        logPushAttempt();
        final HttpMethod method = request.method();
        if ((method != HttpMethod.POST) && (method != HttpMethod.GET)) {
            sendHttpResponse(ctx, request, METHOD_NOT_ALLOWED, null);
            return;
        }
        final PushUserAuth userAuth = getPushUserAuth(request);
        if (!userAuth.isSuccess()) {
            sendHttpResponse(ctx, request, UNAUTHORIZED, userAuth);
            logNoIdentity();
            return;
        }
        final PushConnection pushConn = pushConnectionRegistry.get(userAuth.getClientIdentity());
        if (pushConn == null) {
            sendHttpResponse(ctx, request, NOT_FOUND, userAuth);
            logClientNotConnected();
            return;
        }
        if (!verifySecureToken(request, pushConn)) {
            sendHttpResponse(ctx, request, FORBIDDEN, userAuth);
            logSecurityTokenVerificationFail();
            return;
        }
        if (method == HttpMethod.GET) {
            // client only checking if particular CID + ESN is connected to this instance
            sendHttpResponse(ctx, request, OK, userAuth);
            return;
        }
        final ByteBuf body = request.content().retain();
        if (body.readableBytes() <= 0) {
            sendHttpResponse(ctx, request, NO_CONTENT, userAuth);
            return;
        }
        if (pushConn.isRateLimited()) {
            sendHttpResponse(ctx, request, HttpResponseStatus.SERVICE_UNAVAILABLE, userAuth);
            logRateLimited();
            return;
        }
        final ChannelFuture clientFuture = pushConn.sendPushMessage(body);
        clientFuture.addListener(cf -> {
            HttpResponseStatus status;
            if (cf.isSuccess()) {
                logPushSuccess();
                status = OK;
            } else {
                logPushError(cf.cause());
                status = INTERNAL_SERVER_ERROR;
            }
            sendHttpResponse(ctx, request, status, userAuth);
        });
    } else {
        // Last handler in the chain
        sendHttpResponse(ctx, request, BAD_REQUEST, null);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) ByteBuf(io.netty.buffer.ByteBuf) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 95 with HttpMethod

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

the class Router method toString.

/**
 * Returns visualized routing rules.
 */
@Override
public String toString() {
    // Step 1/2: Dump routers and anyMethodRouter in order
    int numRoutes = size();
    List<String> methods = new ArrayList<String>(numRoutes);
    List<String> patterns = new ArrayList<String>(numRoutes);
    List<String> targets = new ArrayList<String>(numRoutes);
    // For router
    for (Entry<HttpMethod, MethodlessRouter<T>> e : routers.entrySet()) {
        HttpMethod method = e.getKey();
        MethodlessRouter<T> router = e.getValue();
        aggregateRoutes(method.toString(), router.routes(), methods, patterns, targets);
    }
    // For anyMethodRouter
    aggregateRoutes("*", anyMethodRouter.routes(), methods, patterns, targets);
    // For notFound
    if (notFound != null) {
        methods.add("*");
        patterns.add("*");
        targets.add(targetToString(notFound));
    }
    // Step 2/2: Format the List into aligned columns: <method> <patterns> <target>
    int maxLengthMethod = maxLength(methods);
    int maxLengthPattern = maxLength(patterns);
    String format = "%-" + maxLengthMethod + "s  %-" + maxLengthPattern + "s  %s\n";
    int initialCapacity = (maxLengthMethod + 1 + maxLengthPattern + 1 + 20) * methods.size();
    StringBuilder b = new StringBuilder(initialCapacity);
    for (int i = 0; i < methods.size(); i++) {
        String method = methods.get(i);
        String pattern = patterns.get(i);
        String target = targets.get(i);
        b.append(String.format(format, method, pattern, target));
    }
    return b.toString();
}
Also used : ArrayList(java.util.ArrayList) HttpMethod(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod)

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