Search in sources :

Example 51 with HttpHeaders

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders in project ballerina by ballerina-lang.

the class HttpCachingClientTest method testIsFreshResponse.

@Test(description = "Test for the isFreshResponse() function which determines whether a cached response is still " + "fresh.", enabled = false)
public void testIsFreshResponse() {
    final String dateHeader = "Thu, 01 Mar 2018 15:36:34 GMT";
    // 600 second difference
    final String expiresHeader = "Thu, 01 Mar 2018 15:46:34 GMT";
    BStruct cachedResponse = BCompileUtil.createAndGetStruct(compileResult.getProgFile(), PROTOCOL_PACKAGE_HTTP, RESPONSE);
    ResponseCacheControlStruct responseCacheControl = new ResponseCacheControlStruct(compileResult.getProgFile().getPackageInfo(PROTOCOL_PACKAGE_HTTP).getStructInfo(RESPONSE_CACHE_CONTROL));
    responseCacheControl.setMaxAge(300).setSMaxAge(300);
    HTTPCarbonMessage cachedResponseMsg = HttpUtil.createHttpCarbonMessage(false);
    cachedResponseMsg.setProperty(HTTP_STATUS_CODE, 200);
    cachedResponseMsg.setHeader(AGE, String.valueOf(200));
    cachedResponseMsg.setHeader(DATE, dateHeader);
    cachedResponseMsg.setHeader(EXPIRES, expiresHeader);
    initInboundResponse(cachedResponse, responseCacheControl, cachedResponseMsg);
    HttpHeaders responseHeaders = cachedResponseMsg.getHeaders();
    BValue[] inputArgs = { cachedResponse, new BBoolean(true) };
    BValue[] returns;
    // When all 3 parameters for freshness life time is set
    returns = BRunUtil.invoke(compileResult, "isFreshResponse", inputArgs);
    Assert.assertTrue(((BBoolean) returns[0]).booleanValue());
    responseHeaders.set(AGE, "350");
    returns = BRunUtil.invoke(compileResult, "isFreshResponse", inputArgs);
    Assert.assertFalse(((BBoolean) returns[0]).booleanValue());
    // When only max-age and Expires header are there
    responseCacheControl.setSMaxAge(-1);
    inputArgs[1] = new BBoolean(false);
    returns = BRunUtil.invoke(compileResult, "isFreshResponse", inputArgs);
    Assert.assertFalse(((BBoolean) returns[0]).booleanValue());
    responseHeaders.set(AGE, "200");
    returns = BRunUtil.invoke(compileResult, "isFreshResponse", inputArgs);
    Assert.assertTrue(((BBoolean) returns[0]).booleanValue());
    // When only Expires header is there
    responseCacheControl.setMaxAge(-1);
    returns = BRunUtil.invoke(compileResult, "isFreshResponse", inputArgs);
    Assert.assertTrue(((BBoolean) returns[0]).booleanValue());
    responseHeaders.set(AGE, "650");
    returns = BRunUtil.invoke(compileResult, "isFreshResponse", inputArgs);
    Assert.assertFalse(((BBoolean) returns[0]).booleanValue());
    // When there are none of the above 3
    responseHeaders.remove(EXPIRES);
    returns = BRunUtil.invoke(compileResult, "isFreshResponse", inputArgs);
    Assert.assertFalse(((BBoolean) returns[0]).booleanValue());
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) BStruct(org.ballerinalang.model.values.BStruct) HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) BValue(org.ballerinalang.model.values.BValue) BBoolean(org.ballerinalang.model.values.BBoolean) BString(org.ballerinalang.model.values.BString) ResponseCacheControlStruct(org.ballerinalang.net.http.caching.ResponseCacheControlStruct) Test(org.testng.annotations.Test)

Example 52 with HttpHeaders

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders in project ballerina by ballerina-lang.

the class HttpCachingClientTest method testReplaceHeaders.

@Test(description = "Tests whether the headers of a cached response are correctly updated by a validation response", enabled = false)
public void testReplaceHeaders() {
    final String cachedDateHeader = "Thu, 01 Mar 2018 15:36:34 GMT";
    final String cachedExpiresHeader = "Thu, 01 Mar 2018 15:46:34 GMT";
    final String validationDateHeader = "Thu, 01 Mar 2018 15:38:20 GMT";
    final String validationExpiresHeader = "Thu, 01 Mar 2018 15:48:20 GMT";
    final String validationTestHeader = "ballerina-replace-headers";
    final String cacheControlHeader = "no-cache=\"Set-Cookie\",max-age=120";
    final String etagHeader = "1sps79e:q0efehi8";
    BStruct cachedResponse = BCompileUtil.createAndGetStruct(compileResult.getProgFile(), PROTOCOL_PACKAGE_HTTP, RESPONSE);
    HTTPCarbonMessage cachedResponseMsg = HttpUtil.createHttpCarbonMessage(false);
    cachedResponseMsg.setProperty(HTTP_STATUS_CODE, 200);
    cachedResponseMsg.setHeader(DATE, cachedDateHeader);
    cachedResponseMsg.setHeader(CACHE_CONTROL, cacheControlHeader);
    cachedResponseMsg.setHeader(EXPIRES, cachedExpiresHeader);
    cachedResponseMsg.setHeader(ETAG, etagHeader);
    initInboundResponse(cachedResponse, cachedResponseMsg);
    BStruct validationResponse = BCompileUtil.createAndGetStruct(compileResult.getProgFile(), PROTOCOL_PACKAGE_HTTP, RESPONSE);
    HTTPCarbonMessage validationResponseMsg = HttpUtil.createHttpCarbonMessage(false);
    validationResponseMsg.setProperty(HTTP_STATUS_CODE, 304);
    validationResponseMsg.setHeader(DATE, validationDateHeader);
    validationResponseMsg.setHeader(CACHE_CONTROL, cacheControlHeader);
    validationResponseMsg.setHeader(EXPIRES, validationExpiresHeader);
    validationResponseMsg.setHeader(ETAG, etagHeader);
    validationResponseMsg.setHeader("test-name", validationTestHeader);
    initInboundResponse(validationResponse, validationResponseMsg);
    BValue[] inputArg = { cachedResponse, validationResponse };
    BRunUtil.invoke(compileResult, "replaceHeaders", inputArg);
    HttpHeaders updatedCachedRespHeaders = cachedResponseMsg.getHeaders();
    Assert.assertEquals(updatedCachedRespHeaders.size(), 5);
    Assert.assertEquals(updatedCachedRespHeaders.get(DATE), validationDateHeader);
    Assert.assertEquals(updatedCachedRespHeaders.get(CACHE_CONTROL), cacheControlHeader);
    Assert.assertEquals(updatedCachedRespHeaders.get(EXPIRES), validationExpiresHeader);
    Assert.assertEquals(updatedCachedRespHeaders.get(ETAG), etagHeader);
    Assert.assertEquals(updatedCachedRespHeaders.get("test-name"), validationTestHeader);
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) BStruct(org.ballerinalang.model.values.BStruct) HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) BValue(org.ballerinalang.model.values.BValue) BString(org.ballerinalang.model.values.BString) Test(org.testng.annotations.Test)

Example 53 with HttpHeaders

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

the class HttpCompressionClientServerTests method serverCompressionEnabledSmallResponse.

@Test
public void serverCompressionEnabledSmallResponse() throws Exception {
    HttpServer server = HttpServer.create(o -> o.port(0).compression(25));
    NettyContext nettyContext = server.newHandler((in, out) -> out.header("content-length", "5").sendString(Mono.just("reply"))).block(Duration.ofMillis(10_000));
    // don't activate compression on the client options to avoid auto-handling (which removes the header)
    HttpClient client = HttpClient.create(o -> o.connectAddress(() -> address(nettyContext)));
    HttpClientResponse resp = // edit the header manually to attempt to trigger compression on server side
    client.get("/test", req -> req.header("Accept-Encoding", "gzip")).block();
    // check the server didn't send the gzip header, only transfer-encoding
    HttpHeaders headers = resp.responseHeaders();
    assertThat(headers.get("conTENT-encoding")).isNull();
    // check the server sent plain text
    String reply = resp.receive().asString().blockFirst();
    Assert.assertEquals("reply", reply);
    resp.dispose();
    nettyContext.dispose();
    nettyContext.onClose().block();
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) InetSocketAddress(java.net.InetSocketAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) Flux(reactor.core.publisher.Flux) ByteArrayInputStream(java.io.ByteArrayInputStream) Ignore(org.junit.Ignore) Duration(java.time.Duration) NettyContext(reactor.ipc.netty.NettyContext) HttpClient(reactor.ipc.netty.http.client.HttpClient) Assert(org.junit.Assert) HttpServer(reactor.ipc.netty.http.server.HttpServer) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpClient(reactor.ipc.netty.http.client.HttpClient) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) HttpServer(reactor.ipc.netty.http.server.HttpServer) NettyContext(reactor.ipc.netty.NettyContext) Test(org.junit.Test)

Example 54 with HttpHeaders

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders in project cdap by caskdata.

the class DelayedHttpServiceResponder method execute.

/**
 * Calls to other responder methods in this class only cache the response to be sent. The response is actually
 * sent only when this method is called.
 *
 * @param keepAlive {@code true} to keep the connection open; {@code false} otherwise
 */
public void execute(boolean keepAlive) {
    Preconditions.checkState(bufferedResponse != null, "Can not call execute before one of the other responder methods are called.");
    try {
        HttpContentProducer contentProducer = bufferedResponse.getContentProducer();
        HttpHeaders headers = new DefaultHttpHeaders().add(bufferedResponse.getHeaders());
        headers.set(HttpHeaderNames.CONNECTION, keepAlive ? HttpHeaderValues.KEEP_ALIVE : HttpHeaderValues.CLOSE);
        if (!headers.contains(HttpHeaderNames.CONTENT_TYPE)) {
            headers.set(HttpHeaderNames.CONTENT_TYPE, bufferedResponse.getContentType());
        }
        if (contentProducer != null) {
            responder.sendContent(HttpResponseStatus.valueOf(bufferedResponse.getStatus()), bodyProducerFactory.create(contentProducer, taskExecutor), headers);
        } else {
            responder.sendContent(HttpResponseStatus.valueOf(bufferedResponse.getStatus()), bufferedResponse.getContentBuffer(), headers);
        }
        emitMetrics(bufferedResponse.getStatus());
    } finally {
        close();
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) EmptyHttpHeaders(io.netty.handler.codec.http.EmptyHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpContentProducer(co.cask.cdap.api.service.http.HttpContentProducer)

Example 55 with HttpHeaders

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders in project pinpoint by naver.

the class Http1xClientConnectionCreateRequestInterceptor method after.

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args, result, throwable);
    }
    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }
    if (!trace.canSampled()) {
        if (result instanceof HttpRequest) {
            final HttpRequest request = (HttpRequest) result;
            requestTraceWriter.write(request);
        }
        return;
    }
    try {
        final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        recorder.recordApi(descriptor);
        recorder.recordException(throwable);
        recorder.recordServiceType(VertxConstants.VERTX_HTTP_CLIENT);
        if (!validate(args, result)) {
            return;
        }
        final HttpRequest request = (HttpRequest) result;
        final HttpHeaders headers = request.headers();
        if (headers == null) {
            return;
        }
        String host = ArrayArgumentUtils.getArgument(args, 4, String.class, "UNKNOWN");
        // generate next trace id.
        final TraceId nextId = trace.getTraceId().getNextTraceId();
        recorder.recordNextSpanId(nextId.getSpanId());
        requestTraceWriter.write(request, nextId, host);
        final ClientRequestWrapper clientRequest = new VertxHttpClientRequestWrapper(request, host);
        this.clientRequestRecorder.record(recorder, clientRequest, throwable);
        this.cookieRecorder.record(recorder, request, throwable);
    } catch (Throwable t) {
        if (logger.isWarnEnabled()) {
            logger.warn("AFTER. Caused:{}", t.getMessage(), t);
        }
    } finally {
        trace.traceBlockEnd();
    }
}
Also used : Trace(com.navercorp.pinpoint.bootstrap.context.Trace) HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) ClientRequestWrapper(com.navercorp.pinpoint.bootstrap.plugin.request.ClientRequestWrapper) VertxHttpClientRequestWrapper(com.navercorp.pinpoint.plugin.vertx.VertxHttpClientRequestWrapper) SpanEventRecorder(com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder) TraceId(com.navercorp.pinpoint.bootstrap.context.TraceId) VertxHttpClientRequestWrapper(com.navercorp.pinpoint.plugin.vertx.VertxHttpClientRequestWrapper)

Aggregations

HttpHeaders (io.netty.handler.codec.http.HttpHeaders)286 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)149 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)83 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)73 Test (org.junit.Test)68 Test (org.junit.jupiter.api.Test)57 Test (org.testng.annotations.Test)51 HttpRequest (io.netty.handler.codec.http.HttpRequest)43 HttpResponse (io.netty.handler.codec.http.HttpResponse)40 AsciiString (io.netty.util.AsciiString)29 ByteBuf (io.netty.buffer.ByteBuf)27 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)27 BStruct (org.ballerinalang.model.values.BStruct)26 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)22 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)22 HttpServletResponse (javax.servlet.http.HttpServletResponse)20 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)19 Cookie (io.netty.handler.codec.http.cookie.Cookie)19 BValue (org.ballerinalang.model.values.BValue)19 ChannelPromise (io.netty.channel.ChannelPromise)18