01: package com.icesoft.faces.webapp.http.core;
02:
03: import com.icesoft.faces.webapp.http.common.FileLocator;
04: import com.icesoft.faces.webapp.http.common.MimeTypeMatcher;
05: import com.icesoft.faces.webapp.http.common.Request;
06: import com.icesoft.faces.webapp.http.common.Response;
07: import com.icesoft.faces.webapp.http.common.ResponseHandler;
08: import com.icesoft.faces.webapp.http.common.Server;
09:
10: import java.io.File;
11: import java.io.FileInputStream;
12: import java.io.PrintWriter;
13: import java.util.Date;
14:
15: public class FileServer implements Server {
16: private FileLocator locator;
17: private MimeTypeMatcher mimeTypeMatcher;
18:
19: public FileServer(FileLocator locator,
20: MimeTypeMatcher mimeTypeMatcher) {
21: this .locator = locator;
22: this .mimeTypeMatcher = mimeTypeMatcher;
23: }
24:
25: public void service(Request request) throws Exception {
26: final String path = request.getURI().getPath();
27: final File file = locator.locate(path);
28: if (file.exists()) {
29: request.respondWith(new ResponseHandler() {
30: public void respond(Response response) throws Exception {
31: String mimeType = mimeTypeMatcher.mimeTypeFor(path);
32: Date lastModified = new Date(file.lastModified());
33:
34: response.setHeader("Content-Type", mimeType);
35: response.setHeader("Last-Modified", lastModified);
36: response.writeBodyFrom(new FileInputStream(file));
37: }
38: });
39: } else {
40: request.respondWith(new ResponseHandler() {
41: public void respond(Response response) throws Exception {
42: response.setStatus(404);
43: response.setHeader("Content-Type", "text/plain");
44: PrintWriter writer = new PrintWriter(response
45: .writeBody(), true);
46: writer.print("Cannot find file ");
47: writer.println(file);
48: }
49: });
50: }
51: }
52:
53: public void shutdown() {
54: }
55: }
|