View Javadoc
1   package com.github.searls.jasmine.server;
2   
3   import com.github.searls.jasmine.coffee.DetectsCoffee;
4   import com.github.searls.jasmine.coffee.HandlesRequestsForCoffee;
5   import com.github.searls.jasmine.config.JasmineConfiguration;
6   import com.github.searls.jasmine.runner.CreatesRunner;
7   import org.eclipse.jetty.server.Request;
8   import org.eclipse.jetty.server.handler.ResourceHandler;
9   import org.eclipse.jetty.util.resource.Resource;
10  
11  import javax.servlet.ServletException;
12  import javax.servlet.http.HttpServletRequest;
13  import javax.servlet.http.HttpServletResponse;
14  import java.io.IOException;
15  
16  public class JasmineResourceHandler extends ResourceHandler {
17  
18    private final DetectsCoffee detectsCoffee;
19    private final HandlesRequestsForCoffee handlesRequestsForCoffee;
20    private final CreatesRunner createsRunner;
21  
22    public JasmineResourceHandler(CreatesRunner createsRunner, JasmineConfiguration configuration) {
23      this(createsRunner, new HandlesRequestsForCoffee(configuration), new DetectsCoffee());
24    }
25  
26    public JasmineResourceHandler(CreatesRunner createsRunner,
27                                  HandlesRequestsForCoffee handlesRequestsForCoffee,
28                                  DetectsCoffee detectsCoffee) {
29      this.detectsCoffee = detectsCoffee;
30      this.createsRunner = createsRunner;
31      this.handlesRequestsForCoffee = handlesRequestsForCoffee;
32      setAliases(true);
33    }
34  
35    @Override
36    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
37      this.createSpecRunnerIfNecessary(target);
38      Resource resource = this.getResource(baseRequest);
39      response.addDateHeader("EXPIRES", 0L);
40      if (this.detectsCoffee.detect(target) && this.weCanHandleIt(baseRequest, resource)) {
41        this.handlesRequestsForCoffee.handle(baseRequest, response, resource);
42      } else {
43        //Not testable. Who knew test-driving an LSP violation would be this hard. Sigh.  :-(
44        super.handle(target, baseRequest, baseRequest, response);
45      }
46    }
47  
48    private void createSpecRunnerIfNecessary(String target) throws IOException {
49      if ("/".equals(target)) {
50        this.createsRunner.create();
51      }
52    }
53  
54    private boolean weCanHandleIt(Request baseRequest, Resource resource) {
55      return !baseRequest.isHandled() && resource != null && resource.exists();
56    }
57  
58  }