Post added
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package net.miarma.contaminus.common;
|
||||
|
||||
public class Host {
|
||||
static ConfigManager configManager = ConfigManager.getInstance();
|
||||
static String host = configManager.getStringProperty("inet.host");
|
||||
static int apiPort = configManager.getIntProperty("api.port");
|
||||
static int webserverPort = configManager.getIntProperty("webserver.port");
|
||||
|
||||
public static String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public static int getApiPort() {
|
||||
return apiPort;
|
||||
}
|
||||
|
||||
public static int getWebserverPort() {
|
||||
return webserverPort;
|
||||
}
|
||||
|
||||
public static String getOrigin() {
|
||||
return "http://" + host + ":" + webserverPort;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -24,6 +24,37 @@ public class QueryBuilder {
|
||||
return qb;
|
||||
}
|
||||
|
||||
public static QueryBuilder insert(String table, String... columns) {
|
||||
QueryBuilder qb = new QueryBuilder();
|
||||
StringJoiner joiner = new StringJoiner(", ");
|
||||
if (columns.length > 0) {
|
||||
for (String column : columns) {
|
||||
joiner.add(column);
|
||||
}
|
||||
qb.query.append("INSERT INTO ").append(table).append(" (").append(joiner).append(") ");
|
||||
} else {
|
||||
qb.query.append("INSERT INTO ").append(table).append(" ");
|
||||
}
|
||||
|
||||
return qb;
|
||||
}
|
||||
|
||||
public QueryBuilder values(Object... values) {
|
||||
StringJoiner joiner = new StringJoiner(", ", "VALUES (", ")");
|
||||
for (Object value : values) {
|
||||
if(value instanceof String) {
|
||||
joiner.add("'" + value + "'");
|
||||
} else if(value == null) {
|
||||
joiner.add("NULL");
|
||||
}
|
||||
else {
|
||||
joiner.add(value.toString());
|
||||
}
|
||||
}
|
||||
this.query.append(joiner).append(" ");
|
||||
return this;
|
||||
}
|
||||
|
||||
public QueryBuilder from(String table) {
|
||||
query.append("FROM ").append(table).append(" ");
|
||||
return this;
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
package net.miarma.contaminus.server;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import io.vertx.core.AbstractVerticle;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.eventbus.Message;
|
||||
@@ -8,56 +13,42 @@ import io.vertx.core.json.JsonArray;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.Router;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import io.vertx.ext.web.handler.BodyHandler;
|
||||
import io.vertx.ext.web.handler.CorsHandler;
|
||||
import net.miarma.contaminus.common.ConfigManager;
|
||||
import net.miarma.contaminus.common.Constants;
|
||||
import net.miarma.contaminus.common.Host;
|
||||
import net.miarma.contaminus.database.QueryBuilder;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
public class ApiVerticle extends AbstractVerticle {
|
||||
private ConfigManager configManager = ConfigManager.getInstance();
|
||||
|
||||
@Override
|
||||
public void start(Promise<Void> startPromise) {
|
||||
Constants.LOGGER.info("🟢 Iniciando ApiVerticle...");
|
||||
Router router = Router.router(vertx);
|
||||
|
||||
Set<String> allowedHeaders = new HashSet<>();
|
||||
allowedHeaders.add("x-requested-with");
|
||||
allowedHeaders.add("Access-Control-Allow-Origin");
|
||||
allowedHeaders.add("origin");
|
||||
allowedHeaders.add("Content-Type");
|
||||
allowedHeaders.add("accept");
|
||||
|
||||
Set<HttpMethod> allowedMethods = new HashSet<>();
|
||||
allowedMethods.add(io.vertx.core.http.HttpMethod.GET);
|
||||
allowedMethods.add(io.vertx.core.http.HttpMethod.POST);
|
||||
allowedMethods.add(io.vertx.core.http.HttpMethod.OPTIONS);
|
||||
|
||||
Set<HttpMethod> allowedMethods = new HashSet<>(Arrays.asList(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT)); // Por ejemplo
|
||||
Set<String> allowedHeaders = new HashSet<>(Arrays.asList("Content-Type", "Authorization"));
|
||||
|
||||
router.route().handler(CorsHandler.create()
|
||||
.addOrigin("http://"+configManager.getStringProperty("inet.host")+":"+configManager.getIntProperty("webserver.port"))
|
||||
.addOrigin(Host.getOrigin())
|
||||
.allowCredentials(true)
|
||||
.allowedHeaders(allowedHeaders)
|
||||
.allowedMethods(allowedMethods));
|
||||
|
||||
router.route().handler(BodyHandler.create());
|
||||
router.get(Constants.API_PREFIX + "/sensors").blockingHandler(this::getAllSensors);
|
||||
router.get(Constants.API_PREFIX + "/sensors/:id").blockingHandler(this::getSensorById);
|
||||
router.post(Constants.API_PREFIX + "/sensors").blockingHandler(this::insertSensor);
|
||||
router.get(Constants.API_PREFIX + "/status").handler(ctx -> ctx.json(new JsonObject().put("status", "OK")));
|
||||
|
||||
vertx.createHttpServer()
|
||||
.requestHandler(router)
|
||||
.listen(
|
||||
configManager.getIntProperty("api.port"),
|
||||
configManager.getStringProperty("inet.host"),
|
||||
Host.getApiPort(),
|
||||
Host.getHost(),
|
||||
result -> {
|
||||
if (result.succeeded()) {
|
||||
Constants.LOGGER.info(String.format(
|
||||
"📡 ApiVerticle desplegado. (http://%s:%d)",
|
||||
configManager.getStringProperty("inet.host"),
|
||||
configManager.getIntProperty("api.port")
|
||||
"📡 ApiVerticle desplegado. (http://%s:%d)", Host.getHost(), Host.getApiPort()
|
||||
));
|
||||
startPromise.complete();
|
||||
} else {
|
||||
@@ -115,4 +106,38 @@ public class ApiVerticle extends AbstractVerticle {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void insertSensor(RoutingContext context) {
|
||||
JsonObject body = context.body().asJsonObject();
|
||||
|
||||
if (body == null) {
|
||||
context.fail(400, new IllegalArgumentException("Body is missing or invalid"));
|
||||
return;
|
||||
}
|
||||
|
||||
String sensorType = body.getString("sensor_type");
|
||||
Float lat = body.getFloat("lat");
|
||||
Float lon = body.getFloat("lon");
|
||||
Float value = body.getFloat("value");
|
||||
|
||||
if (sensorType == null || lat == null || lon == null || value == null) {
|
||||
context.fail(400, new IllegalArgumentException("Missing required fields"));
|
||||
return;
|
||||
}
|
||||
|
||||
String query = QueryBuilder
|
||||
.insert("sensor_mq_data", "sensor_type", "value", "lat", "lon")
|
||||
.values(sensorType, value, lat, lon)
|
||||
.build();
|
||||
|
||||
vertx.eventBus().request("db.query", query, req -> {
|
||||
if (req.succeeded()) {
|
||||
context.json(new JsonObject().put("result", "OK"));
|
||||
} else {
|
||||
context.fail(500, req.cause());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -41,25 +41,41 @@ public class DatabaseVerticle extends AbstractVerticle {
|
||||
eventBus.consumer("db.query", this::handleDatabaseQuery);
|
||||
}
|
||||
|
||||
private void handleDatabaseQuery(Message<String> msg) {
|
||||
@SuppressWarnings("unused")
|
||||
private void handleDatabaseQuery(Message<String> msg) {
|
||||
String query = msg.body();
|
||||
Constants.LOGGER.info("📥 Query: " + query);
|
||||
|
||||
if(query == null || query.isEmpty()) {
|
||||
msg.fail(400, "Empty query");
|
||||
return;
|
||||
}
|
||||
|
||||
if(query.startsWith("SELECT")) {
|
||||
pool.query(query).execute()
|
||||
.onSuccess(res -> {
|
||||
RowSet<Row> rows = res;
|
||||
JsonArray jsonArray = new JsonArray();
|
||||
for (Row row : rows) {
|
||||
jsonArray.add(new JsonObject()
|
||||
.put("id", row.getInteger("id"))
|
||||
.put("sensor_type", row.getString("sensor_type"))
|
||||
.put("value", row.getFloat("value"))
|
||||
.put("lat", row.getFloat("lat"))
|
||||
.put("lon", row.getFloat("lon"))
|
||||
.put("timestamp", row.getLocalDateTime("timestamp").toString())
|
||||
);
|
||||
}
|
||||
msg.reply(jsonArray);
|
||||
})
|
||||
.onFailure(err -> msg.fail(500, err.getMessage()));
|
||||
} else if(query.startsWith("INSERT")) {
|
||||
pool.query(msg.body()).execute()
|
||||
.onSuccess(_res -> msg.reply(new JsonObject().put("status", "success")))
|
||||
.onFailure(err -> msg.fail(500, err.getMessage()));
|
||||
} else {
|
||||
msg.fail(400, "Invalid operation");
|
||||
}
|
||||
|
||||
pool.query(query).execute()
|
||||
.onSuccess(res -> {
|
||||
RowSet<Row> rows = res;
|
||||
JsonArray jsonArray = new JsonArray();
|
||||
for (Row row : rows) {
|
||||
jsonArray.add(new JsonObject()
|
||||
.put("id", row.getInteger("id"))
|
||||
.put("sensorType", row.getString("sensor_type"))
|
||||
.put("value", row.getFloat("value"))
|
||||
.put("lat", row.getFloat("lat"))
|
||||
.put("lon", row.getFloat("lon"))
|
||||
.put("timestamp", row.getLocalDateTime("timestamp").toString())
|
||||
);
|
||||
}
|
||||
msg.reply(jsonArray);
|
||||
})
|
||||
.onFailure(err -> msg.fail(500, err.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,11 @@ package net.miarma.contaminus.server;
|
||||
import io.vertx.core.AbstractVerticle;
|
||||
import io.vertx.ext.web.Router;
|
||||
import io.vertx.ext.web.handler.StaticHandler;
|
||||
import net.miarma.contaminus.common.ConfigManager;
|
||||
import net.miarma.contaminus.common.Constants;
|
||||
import net.miarma.contaminus.common.Host;
|
||||
|
||||
public class HttpServerVerticle extends AbstractVerticle {
|
||||
private ConfigManager configManager = ConfigManager.getInstance();
|
||||
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
Constants.LOGGER.info("🟢 Iniciando HttpServerVerticle...");
|
||||
@@ -16,10 +15,10 @@ public class HttpServerVerticle extends AbstractVerticle {
|
||||
router.route("/*").handler(StaticHandler.create("webroot").setDefaultContentEncoding("UTF-8"));
|
||||
|
||||
vertx.createHttpServer().requestHandler(router).listen(
|
||||
configManager.getIntProperty("webserver.port"), configManager.getStringProperty("inet.host"), result -> {
|
||||
Host.getWebserverPort(), Host.getHost(), result -> {
|
||||
if (result.succeeded()) {
|
||||
Constants.LOGGER.info(String.format("📡 HttpServerVerticle desplegado. (http://%s:%d)",
|
||||
configManager.getStringProperty("inet.host"), configManager.getIntProperty("api.port"))
|
||||
Host.getHost(), Host.getWebserverPort())
|
||||
);
|
||||
} else {
|
||||
Constants.LOGGER.error("❌ Error al desplegar HttpServerVerticle", result.cause());
|
||||
|
||||
@@ -4,7 +4,6 @@ import io.vertx.core.AbstractVerticle;
|
||||
import io.vertx.core.DeploymentOptions;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.ThreadingModel;
|
||||
import net.miarma.contaminus.common.Constants;
|
||||
|
||||
public class MainVerticle extends AbstractVerticle {
|
||||
|
||||
|
||||
Reference in New Issue
Block a user