Example usage for io.netty.handler.codec.http HttpHeaderNames CONTENT_ENCODING

List of usage examples for io.netty.handler.codec.http HttpHeaderNames CONTENT_ENCODING

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpHeaderNames CONTENT_ENCODING.

Prototype

AsciiString CONTENT_ENCODING

To view the source code for io.netty.handler.codec.http HttpHeaderNames CONTENT_ENCODING.

Click Source Link

Document

"content-encoding"

Usage

From source file:com.heliosapm.streams.forwarder.HttpJsonOutboundHandler.java

License:Apache License

/**
 * {@inheritDoc}// w  ww  . ja va 2  s .c o  m
 * @see io.netty.handler.codec.MessageToMessageEncoder#encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)
 */
@Override
protected void encode(final ChannelHandlerContext ctx, final ConsumerRecords<String, StreamedMetricValue> msg,
        final List<Object> out) throws Exception {
    final StreamedMetricValue[] smvs = StreamSupport.stream(msg.spliterator(), true)
            .map(new Function<ConsumerRecord<String, StreamedMetricValue>, StreamedMetricValue>() {
                @Override
                public StreamedMetricValue apply(ConsumerRecord<String, StreamedMetricValue> t) {
                    return t.value();
                }

            }).toArray(s -> new StreamedMetricValue[s]);
    final int size = smvs.length;
    final ByteBuf buff = buffManager.buffer(size * 200);

    JSONOps.serializeAndGzip(smvs, buff);
    final int sz = buff.readableBytes();
    final HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, postUri,
            buff);
    request.headers().set(HttpHeaderNames.HOST, host);
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    request.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    request.headers().set(HttpHeaderNames.CONTENT_ENCODING, HttpHeaderValues.GZIP);
    request.headers().set(HttpHeaderNames.CONTENT_LENGTH, buff.readableBytes());
    out.add(request);

    ctx.executor().execute(new Runnable() {
        public void run() {
            final NonBlockingHashSet<String> hosts = new NonBlockingHashSet<String>();
            StreamSupport.stream(msg.spliterator(), true)
                    .map(new Function<ConsumerRecord<String, StreamedMetricValue>, String>() {
                        @Override
                        public String apply(ConsumerRecord<String, StreamedMetricValue> t) {
                            return t.value().getTags().get("host");
                        }
                    }).forEach(h -> hosts.add(h));
            log.info("Hosts:{}, Size: {}", hosts, sz);
        }
    });
}

From source file:io.vertx.core.http.Http2ClientTest.java

License:Open Source License

private void testResponseCompression(boolean enabled) throws Exception {
    byte[] expected = TestUtils.randomAlphaString(1000).getBytes();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream in = new GZIPOutputStream(baos);
    in.write(expected);//www.  ja va  2  s  .c o m
    in.close();
    byte[] compressed = baos.toByteArray();
    server.requestHandler(req -> {
        assertEquals(enabled ? "deflate, gzip" : null, req.getHeader(HttpHeaderNames.ACCEPT_ENCODING));
        req.response().putHeader(HttpHeaderNames.CONTENT_ENCODING.toLowerCase(), "gzip")
                .end(Buffer.buffer(compressed));
    });
    startServer();
    client.close();
    client = vertx.createHttpClient(clientOptions.setTryUseCompression(enabled));
    client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", onSuccess(resp -> {
        String encoding = resp.getHeader(HttpHeaderNames.CONTENT_ENCODING);
        assertEquals(enabled ? null : "gzip", encoding);
        resp.bodyHandler(buff -> {
            assertEquals(Buffer.buffer(enabled ? expected : compressed), buff);
            testComplete();
        });
    })).end();
    await();
}

From source file:io.vertx.core.http.Http2ServerTest.java

License:Open Source License

@Test
public void testResponseCompressionDisabled() throws Exception {
    waitFor(2);//from w ww .jav a  2s  .  c o m
    String expected = TestUtils.randomAlphaString(1000);
    server.requestHandler(req -> {
        req.response().end(expected);
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        request.decoder.frameListener(new Http2EventAdapter() {
            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals(null, headers.get(HttpHeaderNames.CONTENT_ENCODING));
                    complete();
                });
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                String s = data.toString(StandardCharsets.UTF_8);
                vertx.runOnContext(v -> {
                    assertEquals(expected, s);
                    complete();
                });
                return super.onDataRead(ctx, streamId, data, padding, endOfStream);
            }
        });
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, GET("/").add("accept-encoding", "gzip"), 0, true,
                request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

From source file:io.vertx.core.http.Http2ServerTest.java

License:Open Source License

@Test
public void testResponseCompressionEnabled() throws Exception {
    waitFor(2);/* ww  w.ja va  2 s .  c  om*/
    String expected = TestUtils.randomAlphaString(1000);
    server.close();
    server = vertx.createHttpServer(serverOptions.setCompressionSupported(true));
    server.requestHandler(req -> {
        req.response().end(expected);
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        request.decoder.frameListener(new Http2EventAdapter() {
            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals("gzip", headers.get(HttpHeaderNames.CONTENT_ENCODING).toString());
                    complete();
                });
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                byte[] bytes = new byte[data.readableBytes()];
                data.readBytes(bytes);
                vertx.runOnContext(v -> {
                    String decoded;
                    try {
                        GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(bytes));
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while (true) {
                            int i = in.read();
                            if (i == -1) {
                                break;
                            }
                            baos.write(i);
                            ;
                        }
                        decoded = baos.toString();
                    } catch (IOException e) {
                        fail(e);
                        return;
                    }
                    assertEquals(expected, decoded);
                    complete();
                });
                return super.onDataRead(ctx, streamId, data, padding, endOfStream);
            }
        });
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, GET("/").add("accept-encoding", "gzip"), 0, true,
                request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

From source file:io.vertx.core.http.impl.Http2ServerResponseImpl.java

License:Open Source License

public Http2ServerResponseImpl(Http2ServerConnection conn, VertxHttp2Stream stream, Object metric, boolean push,
        String contentEncoding, String host) {

    this.metric = metric;
    this.stream = stream;
    this.ctx = conn.handlerContext;
    this.conn = conn;
    this.push = push;
    this.host = host;

    if (contentEncoding != null) {
        putHeader(HttpHeaderNames.CONTENT_ENCODING, contentEncoding);
    }/*  w w w  .j  a va 2 s  .com*/
}

From source file:io.vertx.core.http.impl.Http2ServerResponseImpl.java

License:Open Source License

public Http2ServerResponseImpl(Http2ServerConnection conn, VertxHttp2Stream stream, HttpMethod method,
        String path, boolean push, String contentEncoding) {
    this.stream = stream;
    this.ctx = conn.handlerContext;
    this.conn = conn;
    this.push = push;
    this.host = null;

    if (contentEncoding != null) {
        putHeader(HttpHeaderNames.CONTENT_ENCODING, contentEncoding);
    }//from w  ww  .ja va2s.  co  m

    this.metric = conn.metrics().responsePushed(conn.metric(), method, path, this);
}

From source file:io.vertx.test.core.Http2ClientTest.java

License:Open Source License

private void testResponseCompression(boolean enabled) throws Exception {
    byte[] expected = TestUtils.randomAlphaString(1000).getBytes();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream in = new GZIPOutputStream(baos);
    in.write(expected);//from w w w.j  a va 2  s  .co  m
    in.close();
    byte[] compressed = baos.toByteArray();
    server.close();
    server = vertx.createHttpServer(serverOptions);
    server.requestHandler(req -> {
        assertEquals(enabled ? "deflate, gzip" : null, req.getHeader(HttpHeaderNames.ACCEPT_ENCODING));
        req.response().putHeader(HttpHeaderNames.CONTENT_ENCODING.toLowerCase(), "gzip")
                .end(Buffer.buffer(compressed));
    });
    startServer();
    client.close();
    client = vertx.createHttpClient(clientOptions.setTryUseCompression(enabled));
    client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
        String encoding = resp.getHeader(HttpHeaderNames.CONTENT_ENCODING);
        assertEquals(enabled ? null : "gzip", encoding);
        resp.bodyHandler(buff -> {
            assertEquals(Buffer.buffer(enabled ? expected : compressed), buff);
            testComplete();
        });
    }).end();
    await();
}

From source file:org.ballerinalang.net.grpc.InboundMessage.java

License:Open Source License

public Decompressor getMessageDecompressor() {
    String contentEncodingHeader = httpCarbonMessage.getHeader(MESSAGE_ENCODING);
    if (contentEncodingHeader != null) {
        httpCarbonMessage.removeHeader(HttpHeaderNames.CONTENT_ENCODING.toString());
        Decompressor decompressor = DecompressorRegistry.getDefaultInstance()
                .lookupDecompressor(contentEncodingHeader);
        if (decompressor != null) {
            return decompressor;
        }//from   w  w w.ja  v a 2s . c om
    }
    return null;
}

From source file:org.ballerinalang.stdlib.services.configuration.compression.CompressionConfigSuccessTest.java

License:Open Source License

@Test(description = "Test Compression.AUTO, with no Accept-Encoding header. The response here means the one "
        + "that should be sent to transport, not to end user.")
public void testAutoCompress() {
    HTTPTestRequest inRequestMsg = MessageUtils.generateHTTPMessage("/autoCompress",
            HttpConstants.HTTP_METHOD_GET);
    HttpCarbonMessage response = Services.invokeNew(serviceResult, MOCK_ENDPOINT_NAME, inRequestMsg);
    Assert.assertNotNull(response, "Response message not found");
    Assert.assertNull(response.getHeaders().get(HttpHeaderNames.CONTENT_ENCODING.toString()),
            "The content-encoding header should be null and the identity which means no compression "
                    + "should be done to the response");
}

From source file:org.ballerinalang.stdlib.services.configuration.compression.CompressionConfigSuccessTest.java

License:Open Source License

@Test(description = "Test Compression.AUTO, with Accept-Encoding header. The response here means the one "
        + "that should be sent to transport, not to end user.")
public void testAutoCompressWithAcceptEncoding() {
    List<Header> headers = new ArrayList<>();
    headers.add(new Header(HttpHeaderNames.ACCEPT_ENCODING.toString(), ENCODING_GZIP));
    HTTPTestRequest inRequestMsg = MessageUtils.generateHTTPMessage("/autoCompress",
            HttpConstants.HTTP_METHOD_GET, headers, "hello");
    HttpCarbonMessage response = Services.invokeNew(serviceResult, MOCK_ENDPOINT_NAME, inRequestMsg);
    Assert.assertNotNull(response, "Response message not found");
    Assert.assertNull(response.getHeader(HttpHeaderNames.CONTENT_ENCODING.toString()),
            "The content-encoding header should be null and the original value of Accept-Encoding should "
                    + "be used for compression from the backend");
}