Created
February 15, 2013 14:27
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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