View Javadoc
1   package com.github.searls.jasmine.coffee;
2   
3   import com.github.searls.jasmine.config.JasmineConfiguration;
4   import com.github.searls.jasmine.format.BuildsJavaScriptToWriteFailureHtml;
5   import org.apache.commons.io.IOUtils;
6   import org.eclipse.jetty.http.HttpHeaders;
7   import org.eclipse.jetty.server.Request;
8   import org.eclipse.jetty.util.resource.Resource;
9   
10  import javax.servlet.http.HttpServletResponse;
11  import java.io.IOException;
12  import java.io.UnsupportedEncodingException;
13  
14  public class HandlesRequestsForCoffee {
15  
16    private CoffeeScript coffeeScript = new CoffeeScript();
17    private BuildsJavaScriptToWriteFailureHtml buildsJavaScriptToWriteFailureHtml = new BuildsJavaScriptToWriteFailureHtml();
18    private JasmineConfiguration configuration;
19  
20    public HandlesRequestsForCoffee(JasmineConfiguration configuration) {
21      this.configuration = configuration;
22    }
23  
24    public void handle(Request baseRequest, HttpServletResponse response, Resource resource) throws IOException {
25      baseRequest.setHandled(true);
26      String javascript = null;
27      if (!configuration.isCoffeeScriptCompilationEnabled()) {
28        // CoffeeScript RequireJS plugin should be used for translation
29        javascript = IOUtils.toString(resource.getInputStream(), "UTF-8");
30      } else {
31        javascript = compileCoffee(resource);
32      }
33      setHeaders(response, resource, javascript);
34      writeResponse(response, javascript);
35    }
36  
37    private void writeResponse(HttpServletResponse response, String javascript) throws IOException {
38      response.getWriter().write(javascript);
39    }
40  
41    private void setHeaders(HttpServletResponse response, Resource resource, String javascript) {
42      response.setCharacterEncoding("UTF-8");
43      response.setContentType("text/javascript");
44      response.setDateHeader(HttpHeaders.LAST_MODIFIED, resource.lastModified());
45      try {
46        int contentLength = javascript.getBytes("UTF-8").length;
47        response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(contentLength));
48      } catch (UnsupportedEncodingException e) {
49        throw new RuntimeException(
50          "The JVM does not support the compiler's default encoding.", e);
51      }
52  
53    }
54  
55    private String compileCoffee(Resource resource) {
56      try {
57        return coffeeScript.compile(IOUtils.toString(resource.getInputStream(), "UTF-8"));
58      } catch (Exception e) {
59        return buildsJavaScriptToWriteFailureHtml.build("CoffeeScript Error: failed to compile <code>" + resource.getName() + "</code>. <br/>Error message:<br/><br/><code>" + e.getMessage() + "</code>");
60      }
61    }
62  
63  }