01: /**
02: *
03: */package fitnesse.responders;
04:
05: import java.io.*;
06:
07: import fitnesse.FitNesseContext;
08: import fitnesse.Responder;
09: import fitnesse.http.InputStreamResponse;
10: import fitnesse.http.Request;
11: import fitnesse.http.Response;
12:
13: /**
14: * @author pairadmin
15: *
16: */
17: public class ClasspathFileResponder implements Responder {
18:
19: /**
20: * Serves up the files directly from the classpath.
21: *
22: * @see fitnesse.Responder#makeResponse(fitnesse.FitNesseContext,
23: * fitnesse.http.Request)
24: */
25: public Response makeResponse(FitNesseContext context,
26: Request request) throws Exception {
27: InputStreamResponse response = new InputStreamResponse();
28: response.setContentType(getContentType(request));
29: String resourceName = "/" + request.getResource();
30: InputStream bodyStream = getClass().getResourceAsStream(
31: resourceName);
32: if (bodyStream == null) {
33: throw new FileNotFoundException(resourceName);
34: }
35: int bodyLen = getBodyStreamLength(bodyStream);
36: bodyStream = getClass().getResourceAsStream(resourceName);
37: response.setBody(bodyStream, bodyLen);
38: return response;
39: }
40:
41: private int getBodyStreamLength(InputStream bodyStream)
42: throws IOException {
43: byte[] data = new byte[1024];
44: int readCount = 0;
45: int count = 0;
46:
47: while ((readCount = bodyStream.read(data, 0, data.length)) != -1) {
48: count += readCount;
49: }
50:
51: // need to reset the stream so it may be used later.
52: // bodyStream.reset();
53:
54: return count;
55: }
56:
57: private String getContentType(Request request) {
58: String resource = request.getResource();
59: if (resource.endsWith(".hta")) {
60: return "application/hta";
61: } else if (resource.endsWith(".css")) {
62: return "text/css";
63: } else if (resource.endsWith(".xpi")) {
64: return "application/x-xpinstall";
65: } else if (resource.endsWith(".js")) {
66: return "text/javascript";
67: }
68: return "text/html";
69: }
70:
71: }
|