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