View Javadoc
1   package com.github.searls.jasmine.thirdpartylibs;
2   
3   import org.apache.commons.io.IOUtils;
4   import org.eclipse.jetty.http.HttpHeaders;
5   import org.eclipse.jetty.server.Request;
6   import org.eclipse.jetty.server.handler.ResourceHandler;
7   
8   import javax.servlet.ServletException;
9   import javax.servlet.http.HttpServletRequest;
10  import javax.servlet.http.HttpServletResponse;
11  import java.io.IOException;
12  import java.io.InputStream;
13  import java.io.UnsupportedEncodingException;
14  import java.util.Date;
15  
16  public abstract class AbstractThirdPartyLibsResourceHandler extends ResourceHandler {
17  
18    @Override
19    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
20      if (baseRequest.isHandled()) {
21        return;
22      }
23  
24      String resourcePath = getResourcePath(target);
25      InputStream resource = findResource(resourcePath);
26  
27      if (resource != null) {
28        String javascript = IOUtils.toString(resource, "UTF-8");
29        if ("/jasmine/boot.js".equals(target)) {
30          javascript = javascript.replaceAll("window.onload =", "jasmine.boot =");
31        }
32        setHeaders(response, resourcePath, javascript);
33        writeResponse(response, javascript);
34        baseRequest.setHandled(true);
35      }
36    }
37  
38    protected abstract InputStream findResource(String resourcePath);
39  
40    private String getResourcePath(String url) {
41      return url.replaceFirst("^/", "");
42    }
43  
44    private void setHeaders(HttpServletResponse response, String resourcePath, String content) {
45      response.setCharacterEncoding("UTF-8");
46  
47      if (resourcePath.endsWith(".css")) {
48        response.setContentType("text/css");
49      } else {
50        response.setContentType("text/javascript");
51      }
52      response.addDateHeader("EXPIRES", 0L);
53      response.setDateHeader(HttpHeaders.LAST_MODIFIED, new Date().getTime());
54      try {
55        int contentLength = content.getBytes("UTF-8").length;
56        response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(contentLength));
57      } catch (UnsupportedEncodingException e) {
58        throw new RuntimeException("The JVM does not support javascript default encoding.", e);
59      }
60    }
61  
62    private void writeResponse(HttpServletResponse response, String javascript) throws IOException {
63      response.getWriter().write(javascript);
64    }
65  }