
automately.core.services.api.ApiServer Maven / Gradle / Ivy
package automately.core.services.api;
import automately.core.services.api.routers.DefaultHandler;
import automately.core.services.api.routers.FilesHandler;
import automately.core.services.api.routers.JobsHandler;
import automately.core.services.api.routers.MessageBusHandler;
import automately.core.services.core.AutomatelyService;
import io.jcluster.core.Cluster;
import io.jcluster.core.Config;
import io.jcluster.core.Logger;
import io.jsync.Async;
import io.jsync.http.HttpServer;
import io.jsync.http.RouteMatcher;
import io.jsync.json.JsonObject;
import org.apache.http.client.utils.DateUtils;
import java.util.Date;
/**
* The ApiServer class handles the Automately RESTful API.
* It will start an HTTP server by default on port 8080.
*/
public class ApiServer extends AutomatelyService {
// TODO Update the API server
private Logger logger;
private HttpServer httpServer;
private String httpHost = "0.0.0.0";
private int httpPort = 8080;
@Override
public String name() {
return getClass().getCanonicalName();
}
@Override
public void start(Cluster owner) {
Async async = owner.async();
Config config = owner.config();
JsonObject apiConfig = coreConfig().getObject("api", new JsonObject());
if (apiConfig.containsField("host")) {
httpHost = apiConfig.getString("host", "0.0.0.0");
}
if (apiConfig.containsField("port")) {
httpPort = apiConfig.getInteger("port", 8080);
}
apiConfig.putString("host", httpHost);
apiConfig.putValue("port", httpPort);
coreConfig().putObject("api", apiConfig);
config.save();
logger = owner.logger();
httpServer = async.createHttpServer();
httpServer.requestHandler(req -> {
req.response().putHeader("Server", "automately-core-REST");
req.response().putHeader("Date", DateUtils.formatDate(new Date(System.currentTimeMillis())));
RouteMatcher matcher = new RouteMatcher();
matcher.noMatch(new DefaultHandler());
matcher.allWithRegEx("/jobs(/|.*)?", new JobsHandler());
matcher.allWithRegEx("/files(/|.*)?", new FilesHandler());
matcher.allWithRegEx("/messageBus(/|.*)", new MessageBusHandler());
matcher.handle(req);
});
httpServer.listen(httpPort, httpHost, asyncResult -> {
if (!asyncResult.succeeded()) {
logger.fatal("Could not start API Server on " + httpHost + ":" + httpPort);
return;
}
logger.info("API Server Started on " + httpHost + ":" + httpPort);
});
}
@Override
public void stop() {
httpServer.close(asyncResult -> {
if (asyncResult.succeeded()) {
logger.info("API Server Stopped");
}
});
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy