/*
|
mini-server - Ein minimalistischer HTTP-Server
|
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.minsrv;
|
|
import com.sun.net.httpserver.HttpServer;
|
import de.uhilger.minsrv.handler.StopServerHandler;
|
import de.uhilger.minsrv.handler.FileHandler;
|
import java.io.IOException;
|
import java.util.logging.Logger;
|
import java.net.InetSocketAddress;
|
import java.util.concurrent.Executors;
|
|
/**
|
* Die Klasse Server stellt Methoden zur Ausführung eines
|
* HTTP-Servers bereit
|
*
|
* @author Ulrich Hilger
|
* @version 0.1, 25.03.2021
|
*/
|
public class Server {
|
|
private static final Logger logger = Logger.getLogger(Server.class.getName());
|
|
public static final String STR_SLASH = "/";
|
|
|
private int port;
|
|
private String ctx;
|
|
/**
|
* Ein neues Objekt der Kalsse Server erzeugen
|
* @param port der Port, über den dieser Server erreichbar sein soll
|
*/
|
public Server(int port) {
|
this.port = port;
|
}
|
|
/**
|
* Den Port angeben, unter dem der Server erreichbar sein soll
|
*
|
* @param port der Port, unter dem der Server erreichbar sein soll
|
*/
|
public void setPort(int port) {
|
this.port = port;
|
}
|
|
/**
|
* Den Namen des Kontexts angeben, über den dieser Server
|
* erreichbar sein soll
|
* @param ctxName
|
*/
|
public void setContextName(String ctxName) {
|
if(!ctxName.startsWith(STR_SLASH)) {
|
this.ctx = STR_SLASH + ctxName;
|
} else {
|
this.ctx = ctxName;
|
}
|
}
|
|
/**
|
* Die Endpunkte ('Context'e) einrichten, unter denen die Dienste
|
* dieses Servers erreichbar sein sollen und den Server starten
|
*
|
* @throws IOException wenn etwas schief geht, finden sich Angaben
|
* in diesem Objekt
|
*/
|
public void start() throws IOException {
|
logger.info("Server starting on port " + port);
|
|
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
|
server.createContext(ctx + "/av", new FileHandler(App.getInitParameter(App.IP_WWW_DATA)));
|
server.createContext(ctx + "/server/stop", new StopServerHandler());
|
server.setExecutor(Executors.newFixedThreadPool(20));
|
server.start();
|
}
|
|
}
|