Skip to content

Instantly share code, notes, and snippets.

@h4ck4life
Forked from engintekin/Application.java
Created November 14, 2013 18:44
Show Gist options
  • Save h4ck4life/7472164 to your computer and use it in GitHub Desktop.
Save h4ck4life/7472164 to your computer and use it in GitHub Desktop.
@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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment