/*
|
AV-Direktor - Control OMXPlayer on Raspberry Pi via HTTP
|
Copyright (C) 2021 Ulrich Hilger
|
|
This program is free software: you can redistribute it and/or modify
|
it under the terms of the GNU Affero General Public License as
|
published by the Free Software Foundation, either version 3 of the
|
License, or (at your option) any later version.
|
|
This program is distributed in the hope that it will be useful,
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
GNU Affero General Public License for more details.
|
|
You should have received a copy of the GNU Affero General Public License
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
*/
|
|
package de.uhilger.calypso.handler;
|
|
import com.sun.net.httpserver.HttpExchange;
|
import com.sun.net.httpserver.HttpHandler;
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.io.OutputStream;
|
import java.nio.charset.StandardCharsets;
|
import java.util.logging.Logger;
|
|
/**
|
*
|
* @author ulrich
|
*/
|
public class FileHandler implements HttpHandler {
|
|
private static final Logger logger = Logger.getLogger(FileHandler.class.getName());
|
|
private final String basePath;
|
|
public FileHandler(String basePath) {
|
this.basePath = basePath;
|
}
|
|
@Override
|
public void handle(HttpExchange t) throws IOException {
|
String ctxPath = t.getHttpContext().getPath();
|
String uriPath = t.getRequestURI().getPath();
|
String fName = uriPath.substring(ctxPath.length());
|
if(fName.endsWith("/")) {
|
fName += "index.html";
|
}
|
OutputStream os = t.getResponseBody();
|
File file = new File(basePath, fName);
|
if(file.exists()) {
|
t.sendResponseHeaders(200, file.length());
|
InputStream in = new FileInputStream(file);
|
int b = in.read();
|
while(b > -1) {
|
os.write(b);
|
b = in.read();
|
}
|
in.close();
|
} else {
|
String response = fName + " not found.";
|
byte[] bytes = response.getBytes(StandardCharsets.UTF_8);
|
t.sendResponseHeaders(404, bytes.length);
|
os.write(bytes);
|
}
|
os.flush();
|
os.close();
|
}
|
|
}
|