Search in sources :

Example 21 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project ambry by linkedin.

the class FrontendIntegrationTest method getNotModifiedBlobAndVerify.

/**
 * Gets the blob with blob ID {@code blobId} and verifies that the blob is not returned as blob is not modified
 * @param blobId the blob ID of the blob to GET.
 * @param getOption the options to use while getting the blob.
 * @param isPrivate {@code true} if the blob is private, {@code false} if not.
 * @throws Exception
 */
private void getNotModifiedBlobAndVerify(String blobId, GetOption getOption, boolean isPrivate) throws Exception {
    HttpHeaders headers = new DefaultHttpHeaders();
    if (getOption != null) {
        headers.add(RestUtils.Headers.GET_OPTION, getOption.toString());
    }
    headers.add(RestUtils.Headers.IF_MODIFIED_SINCE, new Date());
    FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, blobId, headers, null);
    ResponseParts responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
    HttpResponse response = getHttpResponse(responseParts);
    assertEquals("Unexpected response status", HttpResponseStatus.NOT_MODIFIED, response.status());
    assertNotNull("Date header should be set", response.headers().get(RestUtils.Headers.DATE));
    assertNotNull("Last-Modified header should be set", response.headers().get("Last-Modified"));
    assertNull("Content-Length should not be set", response.headers().get(RestUtils.Headers.CONTENT_LENGTH));
    assertNull("Accept-Ranges should not be set", response.headers().get(RestUtils.Headers.ACCEPT_RANGES));
    assertNull("Content-Range header should not be set", response.headers().get(RestUtils.Headers.CONTENT_RANGE));
    assertNull(RestUtils.Headers.BLOB_SIZE + " should have been null ", response.headers().get(RestUtils.Headers.BLOB_SIZE));
    assertNull("Content-Type should have been null", response.headers().get(RestUtils.Headers.CONTENT_TYPE));
    verifyCacheHeaders(isPrivate, response);
    assertNoContent(responseParts.queue);
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpResponse(io.netty.handler.codec.http.HttpResponse) ResponseParts(com.github.ambry.rest.NettyClient.ResponseParts) Date(java.util.Date)

Example 22 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project reactor-netty by reactor.

the class HttpServerHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // read message and track if it was keepAlive
    if (msg instanceof HttpRequest) {
        final HttpRequest request = (HttpRequest) msg;
        DecoderResult decoderResult = request.decoderResult();
        if (decoderResult.isFailure()) {
            Throwable cause = decoderResult.cause();
            HttpServerOperations.log.debug("Decoding failed: " + msg + " : ", cause);
            HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, cause instanceof TooLongFrameException ? HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE : HttpResponseStatus.BAD_REQUEST);
            response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0).set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            return;
        }
        if (persistentConnection) {
            pendingResponses += 1;
            if (HttpServerOperations.log.isDebugEnabled()) {
                HttpServerOperations.log.debug("Increasing pending responses, now " + "{}", pendingResponses);
            }
            persistentConnection = isKeepAlive(request);
        } else {
            if (HttpServerOperations.log.isDebugEnabled()) {
                HttpServerOperations.log.debug("dropping pipelined HTTP request, " + "previous response requested connection close");
            }
            ReferenceCountUtil.release(msg);
            return;
        }
        if (pendingResponses > 1) {
            if (HttpServerOperations.log.isDebugEnabled()) {
                HttpServerOperations.log.debug("buffering pipelined HTTP request, " + "pending response count: {}, queue: {}", pendingResponses, pipelined != null ? pipelined.size() : 0);
            }
            overflow = true;
            doPipeline(ctx, msg);
            return;
        } else {
            overflow = false;
            parentContext.createOperations(ctx.channel(), msg);
            if (!(msg instanceof FullHttpRequest)) {
                return;
            }
        }
    } else if (persistentConnection && pendingResponses == 0) {
        if (HttpServerOperations.log.isDebugEnabled()) {
            HttpServerOperations.log.debug("Dropped HTTP content, " + "Since response has been sent already:{}", msg);
        }
        if (msg instanceof LastHttpContent) {
            ctx.fireChannelRead(msg);
        } else {
            ReferenceCountUtil.release(msg);
        }
        ctx.read();
        return;
    } else if (overflow) {
        if (HttpServerOperations.log.isDebugEnabled()) {
            HttpServerOperations.log.debug("buffering pipelined HTTP content, " + "pending response count: {}, pending pipeline:{}", pendingResponses, pipelined != null ? pipelined.size() : 0);
        }
        doPipeline(ctx, msg);
        return;
    }
    ctx.fireChannelRead(msg);
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DecoderResult(io.netty.handler.codec.DecoderResult) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent)

Example 23 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project java by wavefrontHQ.

the class OpenTSDBPortUnificationHandler method handleHttpMessage.

/**
 * Handles an incoming HTTP message.  The currently supported paths are:
 * {@link <ahref="http://opentsdb.net/docs/build/html/api_http/put.html">/api/put</a>}
 * {@link <ahref="http://opentsdb.net/docs/build/html/api_http/version.html">/api/version</a>},
 *
 * @throws IOException        when reading contents of HTTP body fails
 * @throws URISyntaxException when the request URI cannot be parsed
 */
private void handleHttpMessage(final ChannelHandlerContext ctx, final Object message) {
    final FullHttpRequest request = (FullHttpRequest) message;
    URI uri;
    try {
        uri = new URI(request.uri());
    } catch (URISyntaxException e) {
        String errMsg = createErrMsg(e);
        writeHttpResponse(request, ctx, HttpResponseStatus.BAD_REQUEST, errMsg);
        blockMessage("WF-300", "Request URI, '" + request.uri() + "' cannot be parsed", e, ctx);
        return;
    }
    if (uri.getPath().equals("/api/put")) {
        final ObjectMapper jsonTree = new ObjectMapper();
        HttpResponseStatus status;
        String content = "";
        // were stored successfully. If one or more data points had an error, the API will return a 400.
        try {
            if (reportMetrics(jsonTree.readTree(request.content().toString(CharsetUtil.UTF_8)))) {
                status = HttpResponseStatus.NO_CONTENT;
            } else {
                // TODO: improve error message
                // http://opentsdb.net/docs/build/html/api_http/put.html#response
                // User should understand that successful points are processed and the reason for BAD_REQUEST
                // is due to at least one failure point.
                status = HttpResponseStatus.BAD_REQUEST;
                content = "At least one data point had error.";
            }
        } catch (Exception e) {
            status = HttpResponseStatus.BAD_REQUEST;
            if (e != null) {
                content = createErrMsg(e);
            }
            blockMessage("WF-300", "Failed to handle /api/put request", e, ctx);
        }
        writeHttpResponse(request, ctx, status, content);
    } else if (uri.getPath().equals("/api/version")) {
        writeHttpResponse(request, ctx, HttpResponseStatus.OK, // TODO: should be a JSON response object (see docs)
        "Wavefront OpenTSDB Endpoint");
    // http://opentsdb.net/docs/build/html/api_http/version.html
    } else {
        writeHttpResponse(request, ctx, HttpResponseStatus.BAD_REQUEST, "Unsupported path");
        blockMessage("WF-300", "Unexpected path '" + request.uri() + "'", null, ctx);
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 24 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project pancm_project by xuwujing.

the class NettyServerHandler method channelRead.

/*
	 * 收到消息时,返回信息
	 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof FullHttpRequest)) {
        result = "未知请求!";
        send(ctx, result, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    FullHttpRequest httpRequest = (FullHttpRequest) msg;
    try {
        // 获取路径
        String path = httpRequest.uri();
        // 获取参数
        String body = getBody(httpRequest);
        // 获取请求方法
        HttpMethod method = httpRequest.method();
        // 如果不是这个路径,就直接返回错误
        if (!"/test".equalsIgnoreCase(path)) {
            result = "非法请求!";
            send(ctx, result, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        System.out.println("接收到:" + method + " 请求");
        // 如果是GET请求
        if (HttpMethod.GET.equals(method)) {
            // 接受到的消息,做业务逻辑处理...
            System.out.println("body:" + body);
            result = "GET请求";
            send(ctx, result, HttpResponseStatus.OK);
            return;
        }
        // 如果是POST请求
        if (HttpMethod.POST.equals(method)) {
            // 接受到的消息,做业务逻辑处理...
            System.out.println("body:" + body);
            result = "POST请求";
            send(ctx, result, HttpResponseStatus.OK);
            return;
        }
        // 如果是PUT请求
        if (HttpMethod.PUT.equals(method)) {
            // 接受到的消息,做业务逻辑处理...
            System.out.println("body:" + body);
            result = "PUT请求";
            send(ctx, result, HttpResponseStatus.OK);
            return;
        }
        // 如果是DELETE请求
        if (HttpMethod.DELETE.equals(method)) {
            // 接受到的消息,做业务逻辑处理...
            System.out.println("body:" + body);
            result = "DELETE请求";
            send(ctx, result, HttpResponseStatus.OK);
            return;
        }
    } catch (Exception e) {
        System.out.println("处理请求失败!");
        e.printStackTrace();
    } finally {
        // 释放请求
        httpRequest.release();
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 25 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project xipki by xipki.

the class OcspBenchRequestor method ask.

public void ask(BigInteger[] serialNumbers) throws OcspRequestorException {
    byte[] ocspReq = buildRequest(serialNumbers);
    int size = ocspReq.length;
    FullHttpRequest request;
    if (size <= MAX_LEN_GET && requestOptions.isUseHttpGetForRequest()) {
        String b64Request = Base64.encodeToString(ocspReq);
        String urlEncodedReq;
        try {
            urlEncodedReq = URLEncoder.encode(b64Request, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new OcspRequestorException(ex.getMessage());
        }
        String newRawpath = StringUtil.concat(responderRawPathGet, urlEncodedReq);
        request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, newRawpath);
    } else {
        ByteBuf content = Unpooled.wrappedBuffer(ocspReq);
        request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, responderRawPathPost, content);
        request.headers().addInt("Content-Length", content.readableBytes());
    }
    request.headers().add("Content-Type", "application/ocsp-request");
    httpClient.send(request);
}
Also used : OcspRequestorException(org.xipki.ocsp.client.api.OcspRequestorException) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)287 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)180 Test (org.junit.jupiter.api.Test)74 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)69 Test (org.junit.Test)64 ByteBuf (io.netty.buffer.ByteBuf)54 HttpResponse (io.netty.handler.codec.http.HttpResponse)49 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)43 URI (java.net.URI)35 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)31 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)30 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)30 AsciiString (io.netty.util.AsciiString)25 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)23 Map (java.util.Map)22 ChannelPromise (io.netty.channel.ChannelPromise)21 HttpMethod (io.netty.handler.codec.http.HttpMethod)20 IOException (java.io.IOException)19 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)18 ResponseParts (com.github.ambry.rest.NettyClient.ResponseParts)16