blog-software-java/src/main/java/eu/m724/blog/Server.java
Minecon724 5d98a8fd60
Some checks are pending
/ build (push) Waiting to run
Some refactoring
Signed-off-by: Minecon724 <git@m724.eu>
2025-03-08 10:54:17 +01:00

86 lines
2.9 KiB
Java

/*
* Copyright (c) 2025 blog-software-java developers
* blog-software-java is licensed under the GNU General Public License. See the LICENSE.md file
* in the project root for the full license text.
*/
package eu.m724.blog;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Path;
/**
* The {@code Server} class represents a basic HTTP server designed to serve files
* from a specified webroot directory.<br>
* {@link SimpleFileServer} is used.
*/
public class Server {
private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);
private final Path sitePath;
private final String contextPath;
private InetSocketAddress listenAddress;
/**
* Constructs a {@link Server} instance with the specified webroot directory
* and the specified listening address.
*
* @param sitePath the directory from which files will be served
* @param contextPath TODO explain
* @param listenAddress the address and port the server will listen on
*/
public Server(Path sitePath, String contextPath, InetSocketAddress listenAddress) {
this.sitePath = sitePath;
this.contextPath = contextPath;
this.listenAddress = listenAddress;
}
/**
* Constructs a {@link Server} instance with the specified webroot directory.
* The server will bind to the localhost address with a dynamically chosen port.
*
* @param sitePath the directory from which files will be served
* @param contextPath TODO explain
*/
public Server(Path sitePath, String contextPath) {
this(sitePath, contextPath, new InetSocketAddress("localhost", 0));
}
/**
* Starts an HTTP server on the specified listen address.
*
* @throws IOException if an I/O error occurs during server initialization
*/
public void start() throws IOException {
var server = HttpServer.create(listenAddress, 0);
server.createContext(contextPath, SimpleFileServer.createFileHandler(sitePath.toAbsolutePath()));
server.start();
LOGGER.info("Server started on http:/{}", server.getAddress());
this.listenAddress = server.getAddress();
}
/**
* Attempts to open the default web browser and navigate to the server's URL.
*/
public void openBrowser() {
try {
var process = Runtime.getRuntime().exec(new String[] { "xdg-open", "http://" + listenAddress.getHostString() + ":" + listenAddress.getPort() + contextPath });
var code = process.waitFor();
if (code != 0) {
throw new Exception("Exit code " + code);
}
LOGGER.info("Opened browser"); // TODO make this debug?
} catch (Exception e) {
LOGGER.error("Failed to open browser: {}", String.valueOf(e));
}
}
}