Skip to content

Instantly share code, notes, and snippets.

@dgageot
Created February 15, 2013 14:27
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgageot/4960701 to your computer and use it in GitHub Desktop.
Save dgageot/4960701 to your computer and use it in GitHub Desktop.
Jersey Filter *Prototype* that uses PhantomJS to retrieve pages asked by Googlebot. This way the javascript is interpreted by phantomjs and it provides a static webpage to Google.
package main;
import com.google.common.base.Strings;
import com.google.common.io.ByteStreams;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
public class SEOFilter implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
String method = request.getMethod();
if (!method.equals("GET")) {
return response;
}
String userAgent = Strings.nullToEmpty(request.getRequestHeaders().getFirst("User-agent"));
//if (!userAgent.contains("Chrome")) {
if (!userAgent.contains("Googlebot")) {
return response;
}
String uri = request.getAbsolutePath().toString();
if (uri.endsWith(".jpg") || uri.endsWith(".gif") || uri.endsWith(".png")) {
return response;
}
if (uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".map")) {
return response;
}
System.out.println("Google is in the house! " + uri);
try {
Process process = new ProcessBuilder("phantomjs", "download.js", uri)
.directory(new File("."))
.redirectErrorStream(true)
.start();
process.waitFor();
byte[] body = ByteStreams.toByteArray(process.getInputStream());
String page = "<!DOCTYPE html>" + new String(body);
response.setResponse(Response
.fromResponse(response.getResponse())
.type(MediaType.TEXT_HTML_TYPE)
.entity(page)
.build());
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment