commit | author | age
|
60719c
|
1 |
/* |
U |
2 |
AV-Direktor - Control OMXPlayer on Raspberry Pi via HTTP |
|
3 |
Copyright (C) 2021 Ulrich Hilger |
|
4 |
|
|
5 |
This program is free software: you can redistribute it and/or modify |
|
6 |
it under the terms of the GNU Affero General Public License as |
|
7 |
published by the Free Software Foundation, either version 3 of the |
|
8 |
License, or (at your option) any later version. |
|
9 |
|
|
10 |
This program is distributed in the hope that it will be useful, |
|
11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
13 |
GNU Affero General Public License for more details. |
|
14 |
|
|
15 |
You should have received a copy of the GNU Affero General Public License |
|
16 |
along with this program. If not, see <https://www.gnu.org/licenses/>. |
|
17 |
*/ |
|
18 |
|
229976
|
19 |
package de.uhilger.calypso.handler; |
ac1194
|
20 |
|
U |
21 |
import com.sun.net.httpserver.HttpExchange; |
|
22 |
import com.sun.net.httpserver.HttpHandler; |
|
23 |
import java.io.File; |
|
24 |
import java.io.FileInputStream; |
|
25 |
import java.io.IOException; |
|
26 |
import java.io.InputStream; |
|
27 |
import java.io.OutputStream; |
|
28 |
import java.nio.charset.StandardCharsets; |
|
29 |
import java.util.logging.Logger; |
|
30 |
|
|
31 |
/** |
|
32 |
* |
|
33 |
* @author ulrich |
|
34 |
*/ |
|
35 |
public class FileHandler implements HttpHandler { |
|
36 |
|
|
37 |
private static final Logger logger = Logger.getLogger(FileHandler.class.getName()); |
|
38 |
|
16b442
|
39 |
private final String basePath; |
ac1194
|
40 |
|
U |
41 |
public FileHandler(String basePath) { |
|
42 |
this.basePath = basePath; |
|
43 |
} |
|
44 |
|
|
45 |
@Override |
|
46 |
public void handle(HttpExchange t) throws IOException { |
|
47 |
String ctxPath = t.getHttpContext().getPath(); |
|
48 |
String uriPath = t.getRequestURI().getPath(); |
|
49 |
String fName = uriPath.substring(ctxPath.length()); |
|
50 |
if(fName.endsWith("/")) { |
|
51 |
fName += "index.html"; |
|
52 |
} |
|
53 |
OutputStream os = t.getResponseBody(); |
16b442
|
54 |
File file = new File(basePath, fName); |
U |
55 |
if(file.exists()) { |
|
56 |
t.sendResponseHeaders(200, file.length()); |
|
57 |
InputStream in = new FileInputStream(file); |
ac1194
|
58 |
int b = in.read(); |
U |
59 |
while(b > -1) { |
|
60 |
os.write(b); |
|
61 |
b = in.read(); |
|
62 |
} |
|
63 |
in.close(); |
|
64 |
} else { |
|
65 |
String response = fName + " not found."; |
|
66 |
byte[] bytes = response.getBytes(StandardCharsets.UTF_8); |
|
67 |
t.sendResponseHeaders(404, bytes.length); |
|
68 |
os.write(bytes); |
|
69 |
} |
|
70 |
os.flush(); |
|
71 |
os.close(); |
|
72 |
} |
|
73 |
|
|
74 |
} |