package de.uhilger.avdirektor.handler;
|
|
import com.sun.net.httpserver.HttpExchange;
|
import com.sun.net.httpserver.HttpHandler;
|
import de.uhilger.avdirektor.App;
|
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 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 outFile = new File(basePath, fName);
|
if(outFile.exists()) {
|
t.sendResponseHeaders(200, outFile.length());
|
InputStream in = new FileInputStream(outFile);
|
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();
|
}
|
|
}
|