commit | author | age
|
ac1194
|
1 |
package de.uhilger.avdirektor.handler; |
U |
2 |
|
|
3 |
import com.sun.net.httpserver.HttpExchange; |
|
4 |
import com.sun.net.httpserver.HttpHandler; |
|
5 |
import java.io.File; |
|
6 |
import java.io.FileInputStream; |
|
7 |
import java.io.IOException; |
|
8 |
import java.io.InputStream; |
|
9 |
import java.io.OutputStream; |
|
10 |
import java.nio.charset.StandardCharsets; |
|
11 |
import java.util.logging.Logger; |
|
12 |
|
|
13 |
/** |
|
14 |
* |
|
15 |
* @author ulrich |
|
16 |
*/ |
|
17 |
public class FileHandler implements HttpHandler { |
|
18 |
|
|
19 |
private static final Logger logger = Logger.getLogger(FileHandler.class.getName()); |
|
20 |
|
16b442
|
21 |
private final String basePath; |
ac1194
|
22 |
|
U |
23 |
public FileHandler(String basePath) { |
|
24 |
this.basePath = basePath; |
|
25 |
} |
|
26 |
|
|
27 |
@Override |
|
28 |
public void handle(HttpExchange t) throws IOException { |
|
29 |
String ctxPath = t.getHttpContext().getPath(); |
|
30 |
String uriPath = t.getRequestURI().getPath(); |
|
31 |
String fName = uriPath.substring(ctxPath.length()); |
|
32 |
if(fName.endsWith("/")) { |
|
33 |
fName += "index.html"; |
|
34 |
} |
|
35 |
OutputStream os = t.getResponseBody(); |
16b442
|
36 |
File file = new File(basePath, fName); |
U |
37 |
if(file.exists()) { |
|
38 |
t.sendResponseHeaders(200, file.length()); |
|
39 |
InputStream in = new FileInputStream(file); |
ac1194
|
40 |
int b = in.read(); |
U |
41 |
while(b > -1) { |
|
42 |
os.write(b); |
|
43 |
b = in.read(); |
|
44 |
} |
|
45 |
in.close(); |
|
46 |
} else { |
|
47 |
String response = fName + " not found."; |
|
48 |
byte[] bytes = response.getBytes(StandardCharsets.UTF_8); |
|
49 |
t.sendResponseHeaders(404, bytes.length); |
|
50 |
os.write(bytes); |
|
51 |
} |
|
52 |
os.flush(); |
|
53 |
os.close(); |
|
54 |
} |
|
55 |
|
|
56 |
} |