78 lines
2.6 KiB
Java
78 lines
2.6 KiB
Java
package ru.kirillius.XCP.web;
|
|
|
|
import org.eclipse.jetty.ee10.servlet.DefaultServlet;
|
|
import org.eclipse.jetty.ee10.servlet.ServletContextHandler;
|
|
import org.eclipse.jetty.ee10.servlet.ServletHolder;
|
|
import org.eclipse.jetty.server.Server;
|
|
import org.eclipse.jetty.util.resource.ResourceFactory;
|
|
import ru.kirillius.XCP.Commons.Context;
|
|
import ru.kirillius.XCP.RPC.JSONRPC.JsonRpcServlet;
|
|
import ru.kirillius.XCP.RPC.Services.Auth;
|
|
import ru.kirillius.XCP.RPC.Services.Profile;
|
|
import ru.kirillius.XCP.RPC.Services.UserManagement;
|
|
import ru.kirillius.XCP.Services.ServiceLoadPriority;
|
|
import ru.kirillius.XCP.Services.WebService;
|
|
|
|
import java.io.IOException;
|
|
import java.net.InetSocketAddress;
|
|
import java.util.Objects;
|
|
|
|
@ServiceLoadPriority(100)
|
|
public class WebServiceImpl implements WebService {
|
|
private Server server;
|
|
|
|
@Override
|
|
public void initialize(Context context) {
|
|
if (server != null) {
|
|
throw new IllegalStateException("Server is started already");
|
|
}
|
|
var jsonRpc = new JsonRpcServlet(context);
|
|
jsonRpc.registerRpcService(
|
|
UserManagement.class,
|
|
Auth.class,
|
|
Profile.class
|
|
);
|
|
var config = context.getConfig();
|
|
server = new Server(new InetSocketAddress(config.getHost(), config.getHttpPort()));
|
|
var servletContext = new ServletContextHandler("/", ServletContextHandler.SESSIONS);
|
|
servletContext.addServlet(new ServletHolder(jsonRpc), "/api/*");
|
|
servletContext.addServlet(DefaultServlet.class, "/");
|
|
var resourceFactory = ResourceFactory.root();
|
|
|
|
try {
|
|
var resource = resourceFactory.newResource(Objects.requireNonNull(getClass().getClassLoader().getResource("htdocs/")).toURI());
|
|
servletContext.setBaseResource(resource);
|
|
} catch (Exception e) {
|
|
throw new RuntimeException("Unable to determine path to htdocs directory", e);
|
|
}
|
|
|
|
server.setHandler(servletContext);
|
|
try {
|
|
server.start();
|
|
} catch (Exception e) {
|
|
throw new RuntimeException("Failed to start jetty web server", e);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void close() throws IOException {
|
|
if (server != null) {
|
|
try {
|
|
server.stop();
|
|
} catch (Exception e) {
|
|
throw new IOException("Failed to stop web server", e);
|
|
} finally {
|
|
server = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
public void join() {
|
|
try {
|
|
server.join();
|
|
} catch (InterruptedException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
}
|