Search code examples
javahttp-compressionundertow

Compressing Undertow server responses


i have a programmatic Undertow server setup. Static content is served by Undertow as well, without a reverse proxy. Java code for Undertow startup looks like this:

ResourceManager resourceManager = 
    new FileResourceManager(new File("deploymentDir"), 100);

DeploymentInfo servletBuilder = Servlets.deployment()
      .setResourceManager(resourceManager)
      .setDeploymentName("testDeployment")
      .setContextPath("/");

DeploymentManager manager = Servlets.defaultContainer()
      .addDeployment(servletBuilder);
manager.deploy();

Undertow.Builder builder = Undertow.builder();
builder.addHttpListener(8080, domainName);

PathHandler path = Handlers.path(Handlers.redirect("/"))
      .addPrefixPath("/", manager.start());

Undertow server = builder.setHandler(path).build();
server.start();

I'm wondering how does one gzip server responses in Undertow?

Thanks, Vitaliy.


Solution

  • I had to look at GzipContentEncodingTestCase in Undertow's source to get it to work. One has to create an EncodingHandler with appropriate parameters, and then invoke setNext() so that to chain it to the PathHandler:

    PathHandler path = Handlers.path(Handlers.redirect("/"))
        .addPrefixPath("/", manager.start());
    
    final EncodingHandler handler = 
        new EncodingHandler(new ContentEncodingRepository()
          .addEncodingHandler("gzip", 
              new GzipEncodingProvider(), 50,
              Predicates.parse("max-content-size[5]")))
          .setNext(path);
    
    // ...
    Undertow server = builder.setHandler(handler).build();