1
0

Fixed CORS error

This commit is contained in:
Jose
2025-03-06 16:52:27 +01:00
parent 278c49427a
commit a6019111b5
24 changed files with 239 additions and 110 deletions

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

13
.idea/compiler.xml generated Normal file
View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="contaminus" />
</profile>
</annotationProcessing>
</component>
</project>

20
.idea/jarRepositories.xml generated Normal file
View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>

14
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/backend/vertx/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_23" project-jdk-name="23" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/classes" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/ContaminUS.iml" filepath="$PROJECT_DIR$/ContaminUS.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

10
ContaminUS.iml Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager">
<output url="file://$MODULE_DIR$/bin" />
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="23" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -57,9 +57,17 @@ public class ConfigManager {
} }
} }
public String getProperty(String key) { public String getStringProperty(String key) {
return config.getProperty(key); return config.getProperty(key);
} }
public int getIntProperty(String key) {
return Integer.parseInt(config.getProperty(key));
}
public boolean getBooleanProperty(String key) {
return Boolean.parseBoolean(config.getProperty(key));
}
public void setProperty(String key, String value) { public void setProperty(String key, String value) {
config.setProperty(key, value); config.setProperty(key, value);

View File

@@ -13,13 +13,13 @@ public class DatabaseManager {
ConfigManager config = ConfigManager.getInstance(); ConfigManager config = ConfigManager.getInstance();
JsonObject dbConfig = new JsonObject() JsonObject dbConfig = new JsonObject()
.put("url", config.getProperty("db.protocol") + "//" + .put("url", config.getStringProperty("db.protocol") + "//" +
config.getProperty("db.host") + ":" + config.getStringProperty("db.host") + ":" +
config.getProperty("db.port") + "/" + config.getStringProperty("db.port") + "/" +
config.getProperty("db.name")) config.getStringProperty("db.name"))
.put("user", config.getProperty("db.user")) .put("user", config.getStringProperty("db.user"))
.put("password", config.getProperty("db.pwd")) .put("password", config.getStringProperty("db.pwd"))
.put("max_pool_size", config.getProperty("db.poolSize")); .put("max_pool_size", config.getStringProperty("db.poolSize"));
pool = JDBCPool.pool(vertx, dbConfig); pool = JDBCPool.pool(vertx, dbConfig);
} }

View File

@@ -29,8 +29,9 @@ public class QueryBuilder {
return this; return this;
} }
public QueryBuilder where(String condition) { public QueryBuilder where(String conditionsString, Object... values) {
conditions.add(condition); conditionsString = conditionsString.replaceAll("\\?", "%s");
conditions.add(String.format(conditionsString, values));
return this; return this;
} }

View File

@@ -1,83 +1,118 @@
package net.miarma.contaminus.server; package net.miarma.contaminus.server;
import java.util.Optional;
import io.vertx.core.AbstractVerticle; import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise; import io.vertx.core.Promise;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.eventbus.Message; import io.vertx.core.eventbus.Message;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router; import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.CorsHandler;
import net.miarma.contaminus.common.ConfigManager;
import net.miarma.contaminus.common.Constants; import net.miarma.contaminus.common.Constants;
import net.miarma.contaminus.database.QueryBuilder; import net.miarma.contaminus.database.QueryBuilder;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
public class ApiVerticle extends AbstractVerticle { public class ApiVerticle extends AbstractVerticle {
@Override private ConfigManager configManager = ConfigManager.getInstance();
public void start(Promise<Void> startPromise) {
Constants.LOGGER.info("🟢 Iniciando ApiVerticle..."); @Override
Router router = Router.router(vertx); public void start(Promise<Void> startPromise) {
router.get(Constants.API_PREFIX + "/sensors").blockingHandler(this::getAllSensors); 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);
router.route().handler(CorsHandler.create()
.addOrigin("http://"+configManager.getStringProperty("inet.host")+":"+configManager.getIntProperty("webserver.port"))
.allowCredentials(true)
.allowedHeaders(allowedHeaders)
.allowedMethods(allowedMethods));
router.get(Constants.API_PREFIX + "/sensors").blockingHandler(this::getAllSensors);
router.get(Constants.API_PREFIX + "/sensors/:id").blockingHandler(this::getSensorById); router.get(Constants.API_PREFIX + "/sensors/:id").blockingHandler(this::getSensorById);
router.get(Constants.API_PREFIX + "/status").handler(ctx -> router.get(Constants.API_PREFIX + "/status").handler(ctx -> ctx.json(new JsonObject().put("status", "OK")));
ctx.json(new JsonObject().put("status", "OK"))
); vertx.createHttpServer()
vertx.createHttpServer().requestHandler(router).listen(8081); .requestHandler(router)
startPromise.complete(); .listen(
} configManager.getIntProperty("api.port"),
configManager.getStringProperty("inet.host"),
private void getAllSensors(RoutingContext context) { result -> {
Optional<String> sort = Optional.ofNullable(context.request().getParam("_sort")); if (result.succeeded()) {
Optional<String> order = Optional.ofNullable(context.request().getParam("_order")); Constants.LOGGER.info(String.format(
// forma tela de rara que me ha dado chatgpt para parsear esto XD "📡 ApiVerticle desplegado. (http://%s:%d)",
Optional<Integer> limit = Optional.ofNullable(context.request().getParam("_limit")) configManager.getStringProperty("inet.host"),
.map(s -> { configManager.getIntProperty("api.port")
try { ));
return Integer.parseInt(s); startPromise.complete();
} catch (NumberFormatException e) { } else {
return null; Constants.LOGGER.error("❌ Error al desplegar ApiVerticle", result.cause());
} startPromise.fail(result.cause());
}); }
});
}
String query = QueryBuilder
.select("*") private void getAllSensors(RoutingContext context) {
.from("sensor_mq_data") Optional<String> sort = Optional.ofNullable(context.request().getParam("_sort"));
.orderBy(sort, order) Optional<String> order = Optional.ofNullable(context.request().getParam("_order"));
.limit(limit) Optional<Integer> limit = Optional.ofNullable(context.request().getParam("_limit"))
.build(); .map(s -> {
try {
vertx.eventBus().request("db.query", query, new DeliveryOptions(), ar -> { return Integer.parseInt(s);
if (ar.succeeded()) { } catch (NumberFormatException e) {
Message<Object> result = ar.result(); return null;
}
});
String query = QueryBuilder
.select("*")
.from("sensor_mq_data")
.orderBy(sort, order)
.limit(limit)
.build();
vertx.eventBus().request("db.query", query, req -> {
if (req.succeeded()) {
Message<Object> result = req.result();
JsonArray jsonArray = (JsonArray) result.body(); JsonArray jsonArray = (JsonArray) result.body();
context.json(jsonArray); context.json(jsonArray);
} else { } else {
context.fail(500, ar.cause()); context.fail(500, req.cause());
} }
}); });
} }
private void getSensorById(RoutingContext context) {
String id = context.request().getParam("id");
String query = QueryBuilder
.select("*")
.from("sensor_mq_data")
.where("id = " + id)
.build();
vertx.eventBus().request("db.query", query, new DeliveryOptions(), ar -> {
if (ar.succeeded()) {
Message<Object> result = ar.result();
JsonArray jsonArray = (JsonArray) result.body();
context.json(jsonArray);
} else {
context.fail(500, ar.cause());
}
});
}
} private void getSensorById(RoutingContext context) {
String id = context.request().getParam("id");
String query = QueryBuilder
.select("*")
.from("sensor_mq_data")
.where("id = ?", id)
.build();
vertx.eventBus().request("db.query", query, req -> {
if (req.succeeded()) {
Message<Object> result = req.result();
JsonArray jsonArray = (JsonArray) result.body();
context.json(jsonArray);
} else {
context.fail(500, req.cause());
}
});
}
}

View File

@@ -29,10 +29,12 @@ public class DatabaseVerticle extends AbstractVerticle {
.execute() .execute()
.onSuccess(_res -> { .onSuccess(_res -> {
Constants.LOGGER.info("✅ Database connection ok"); Constants.LOGGER.info("✅ Database connection ok");
Constants.LOGGER.info("📡 DatabaseVerticle desplegado");
startPromise.complete(); startPromise.complete();
}) })
.onFailure(err -> { .onFailure(err -> {
Constants.LOGGER.error("❌ Database connection failed"); Constants.LOGGER.error("❌ Database connection failed");
Constants.LOGGER.error("❌ Error al desplegar DatabaseVerticle", err);
startPromise.fail(err); startPromise.fail(err);
}); });

View File

@@ -3,15 +3,28 @@ package net.miarma.contaminus.server;
import io.vertx.core.AbstractVerticle; import io.vertx.core.AbstractVerticle;
import io.vertx.ext.web.Router; import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.StaticHandler; import io.vertx.ext.web.handler.StaticHandler;
import net.miarma.contaminus.common.ConfigManager;
import net.miarma.contaminus.common.Constants; import net.miarma.contaminus.common.Constants;
public class HttpServerVerticle extends AbstractVerticle { public class HttpServerVerticle extends AbstractVerticle {
private ConfigManager configManager = ConfigManager.getInstance();
@Override @Override
public void start() { public void start() {
Constants.LOGGER.info("🟢 Iniciando HttpServerVerticle..."); Constants.LOGGER.info("🟢 Iniciando HttpServerVerticle...");
Router router = Router.router(vertx); Router router = Router.router(vertx);
router.route("/*").handler(StaticHandler.create("webroot").setDefaultContentEncoding("UTF-8")); router.route("/*").handler(StaticHandler.create("webroot").setDefaultContentEncoding("UTF-8"));
vertx.createHttpServer().requestHandler(router).listen(8080);
vertx.createHttpServer().requestHandler(router).listen(
configManager.getIntProperty("webserver.port"), configManager.getStringProperty("inet.host"), result -> {
if (result.succeeded()) {
Constants.LOGGER.info(String.format("📡 HttpServerVerticle desplegado. (http://%s:%d)",
configManager.getStringProperty("inet.host"), configManager.getIntProperty("api.port"))
);
} else {
Constants.LOGGER.error("❌ Error al desplegar HttpServerVerticle", result.cause());
}
});
} }

View File

@@ -13,27 +13,9 @@ public class MainVerticle extends AbstractVerticle {
final DeploymentOptions options = new DeploymentOptions(); final DeploymentOptions options = new DeploymentOptions();
options.setThreadingModel(ThreadingModel.WORKER); options.setThreadingModel(ThreadingModel.WORKER);
getVertx().deployVerticle(new DatabaseVerticle(), options, result -> { getVertx().deployVerticle(new DatabaseVerticle(), options);
if(result.succeeded()) { getVertx().deployVerticle(new ApiVerticle(), options);
Constants.LOGGER.info("📡 HttpServerVerticle desplegado.(http://localhost:8080)"); getVertx().deployVerticle(new HttpServerVerticle());
} else {
Constants.LOGGER.error("❌ Error al desplegar HttpServerVerticle", result.cause());
}
});
getVertx().deployVerticle(new ApiVerticle(), options, result -> {
if(result.succeeded()) {
Constants.LOGGER.info("📡 ApiVerticle desplegado. (http://localhost:8081/api/v1)");
} else {
Constants.LOGGER.error("❌ Error al desplegar ApiVerticle", result.cause());
}
});
getVertx().deployVerticle(new HttpServerVerticle(), result -> {
if(result.succeeded()) {
Constants.LOGGER.info("📡 DatabaseVerticle desplegado.");
} else {
Constants.LOGGER.error("❌ Error al desplegar HttpServerVerticle", result.cause());
}
});
} }
@Override @Override

View File

@@ -1,7 +1,13 @@
# DB Configuration
db.protocol=jdbc:mariadb: db.protocol=jdbc:mariadb:
db.host=localhost db.host=localhost
db.port=3306 db.port=3306
db.name=dad db.name=dad
db.user=root db.user=root
db.pwd=root db.pwd=root
dp.poolSize=5 dp.poolSize=5
# Server Configuration
inet.host=localhost
webserver.port=8080
api.port=8081

View File

@@ -15,7 +15,7 @@
<meta name="twitter:image" content="https://contaminus.miarma.net/logo.png" /> <meta name="twitter:image" content="https://contaminus.miarma.net/logo.png" />
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon"> <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
<title>ContaminUS</title> <title>ContaminUS</title>
<script type="module" crossorigin src="/assets/index-Ch0_cdBw.js"></script> <script type="module" crossorigin src="/assets/index-B9-ngIAm.js"></script>
<link rel="modulepreload" crossorigin href="/assets/react-vendors-DbHEDQBy.js"> <link rel="modulepreload" crossorigin href="/assets/react-vendors-DbHEDQBy.js">
<link rel="modulepreload" crossorigin href="/assets/leaflet-DYDK0jU3.js"> <link rel="modulepreload" crossorigin href="/assets/leaflet-DYDK0jU3.js">
<link rel="modulepreload" crossorigin href="/assets/chartjs-C6LAl0aW.js"> <link rel="modulepreload" crossorigin href="/assets/chartjs-C6LAl0aW.js">

View File

@@ -1,2 +1,2 @@
/net/
/META-INF/ /META-INF/
/net/

View File

@@ -1,7 +1,13 @@
# DB Configuration
db.protocol=jdbc:mariadb: db.protocol=jdbc:mariadb:
db.host=localhost db.host=localhost
db.port=3306 db.port=3306
db.name=dad db.name=dad
db.user=root db.user=root
db.pwd=root db.pwd=root
dp.poolSize=5 dp.poolSize=5
# Server Configuration
inet.host=localhost
webserver.port=8080
api.port=8081

View File

@@ -15,7 +15,7 @@
<meta name="twitter:image" content="https://contaminus.miarma.net/logo.png" /> <meta name="twitter:image" content="https://contaminus.miarma.net/logo.png" />
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon"> <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
<title>ContaminUS</title> <title>ContaminUS</title>
<script type="module" crossorigin src="/assets/index-Ch0_cdBw.js"></script> <script type="module" crossorigin src="/assets/index-B9-ngIAm.js"></script>
<link rel="modulepreload" crossorigin href="/assets/react-vendors-DbHEDQBy.js"> <link rel="modulepreload" crossorigin href="/assets/react-vendors-DbHEDQBy.js">
<link rel="modulepreload" crossorigin href="/assets/leaflet-DYDK0jU3.js"> <link rel="modulepreload" crossorigin href="/assets/leaflet-DYDK0jU3.js">
<link rel="modulepreload" crossorigin href="/assets/chartjs-C6LAl0aW.js"> <link rel="modulepreload" crossorigin href="/assets/chartjs-C6LAl0aW.js">

View File

@@ -7,7 +7,7 @@
}, },
"appConfig": { "appConfig": {
"endpoints": { "endpoints": {
"baseUrl": "http://localhost:8080/api/v1", "baseUrl": "http://localhost:80/api/v1",
"sensors": "sensors", "sensors": "sensors",
"sensor": "sensors/sensor" "sensor": "sensors/sensor"
}, },

View File

@@ -69,14 +69,10 @@ const HistoryChartsContent = () => {
const options = theme === "dark" ? optionsDark : optionsLight; const options = theme === "dark" ? optionsDark : optionsLight;
const currentHour = new Date().getHours(); const currentHour = new Date().getHours();
console.log("currentHour", currentHour);
const timeLabels = [ const timeLabels = [
`${currentHour - 3}:00`, `${currentHour - 2}:00`, `${currentHour - 1}:00`, `${currentHour}:00`, `${currentHour + 1}:00`, `${currentHour + 2}:00`, `${currentHour + 3}:00` `${currentHour - 3}:00`, `${currentHour - 2}:00`, `${currentHour - 1}:00`, `${currentHour}:00`, `${currentHour + 1}:00`, `${currentHour + 2}:00`, `${currentHour + 3}:00`
] ]
//const timeLabels = config?.appConfig?.historyChartConfig?.timeLabels ?? [];
if (loading) return <p>Cargando datos...</p>; if (loading) return <p>Cargando datos...</p>;
const temperatureData = []; const temperatureData = [];

View File

@@ -45,7 +45,8 @@ const SummaryCards = () => {
baseUrl: `${BASE}/${ENDPOINT}`, baseUrl: `${BASE}/${ENDPOINT}`,
params: { params: {
_sort: 'timestamp', _sort: 'timestamp',
_order: 'desc' _order: 'desc',
_limit: 1
} }
} }