Skip to content

Instantly share code, notes, and snippets.

@engintekin
Created October 26, 2011 20:02
Show Gist options
  • Save engintekin/1317626 to your computer and use it in GitHub Desktop.
Save engintekin/1317626 to your computer and use it in GitHub Desktop.
Gzip your response in Play framework
@With(Compress.class)
public class Application extends Controller {
public static void index() {
render();//response will be gzipped
}
}
package controllers;
import play.*;
import play.mvc.*;
import java.io.*;
import java.util.*;
import java.util.zip.GZIPOutputStream;
public class Compress extends Controller {
@Finally
public static void compress() throws IOException {
String text = response.out.toString();
// if ("text/xml".equals(response.contentType)) {
// text = new com.googlecode.htmlcompressor.compressor.XmlCompressor().compress(text);
// } else if ("text/html; charset=utf-8".equals(response.contentType)) {
// text = new com.googlecode.htmlcompressor.compressor.HtmlCompressor().compress(text);
// }
final ByteArrayOutputStream gzip = gzip(text);
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Length", gzip.size() + "");
response.out = gzip;
}
public static ByteArrayOutputStream gzip(final String input)
throws IOException {
final InputStream inputStream = new ByteArrayInputStream(input.getBytes());
final ByteArrayOutputStream stringOutputStream = new ByteArrayOutputStream((int) (input.length() * 0.75));
final OutputStream gzipOutputStream = new GZIPOutputStream(stringOutputStream);
final byte[] buf = new byte[5000];
int len;
while ((len = inputStream.read(buf)) > 0) {
gzipOutputStream.write(buf, 0, len);
}
inputStream.close();
gzipOutputStream.close();
return stringOutputStream;
}
}
@knaak
Copy link

knaak commented Mar 28, 2013

very useful, thank you.

You should check that the request accepts gzip though

@rajeshl
Copy link

rajeshl commented Apr 14, 2013

Good stuff!
It is definitely a much needed addition to Play, which surprisingly does not come with built in support for compression output.
Agree with @knaak that accept request must be checked. But that easily done. Also, we use a way to trigger gzip on or off on server side. This would help during development, if you want to see output on console.

@mwhawkins
Copy link

Why doesn't this work with Play 2.1.1? Is this for a different version?

@opyate
Copy link

opyate commented Dec 3, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment