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,10 +57,18 @@ public class ConfigManager {
}
}
public String getProperty(String key) {
public String getStringProperty(String 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) {
config.setProperty(key, value);
saveConfig();

View File

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

View File

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

View File

@@ -1,36 +1,75 @@
package net.miarma.contaminus.server;
import java.util.Optional;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.eventbus.Message;
import io.vertx.core.http.HttpMethod;
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.CorsHandler;
import net.miarma.contaminus.common.ConfigManager;
import net.miarma.contaminus.common.Constants;
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);
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 + "/status").handler(ctx ->
ctx.json(new JsonObject().put("status", "OK"))
);
vertx.createHttpServer().requestHandler(router).listen(8081);
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"),
result -> {
if (result.succeeded()) {
Constants.LOGGER.info(String.format(
"📡 ApiVerticle desplegado. (http://%s:%d)",
configManager.getStringProperty("inet.host"),
configManager.getIntProperty("api.port")
));
startPromise.complete();
} else {
Constants.LOGGER.error("❌ Error al desplegar ApiVerticle", result.cause());
startPromise.fail(result.cause());
}
});
}
private void getAllSensors(RoutingContext context) {
Optional<String> sort = Optional.ofNullable(context.request().getParam("_sort"));
Optional<String> order = Optional.ofNullable(context.request().getParam("_order"));
// forma tela de rara que me ha dado chatgpt para parsear esto XD
Optional<Integer> limit = Optional.ofNullable(context.request().getParam("_limit"))
.map(s -> {
try {
@@ -40,7 +79,6 @@ public class ApiVerticle extends AbstractVerticle {
}
});
String query = QueryBuilder
.select("*")
.from("sensor_mq_data")
@@ -48,36 +86,33 @@ public class ApiVerticle extends AbstractVerticle {
.limit(limit)
.build();
vertx.eventBus().request("db.query", query, new DeliveryOptions(), ar -> {
if (ar.succeeded()) {
Message<Object> result = ar.result();
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, 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)
.where("id = ?", id)
.build();
vertx.eventBus().request("db.query", query, new DeliveryOptions(), ar -> {
if (ar.succeeded()) {
Message<Object> result = ar.result();
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, ar.cause());
context.fail(500, req.cause());
}
});
}
}

View File

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

View File

@@ -3,15 +3,28 @@ 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;
public class HttpServerVerticle extends AbstractVerticle {
private ConfigManager configManager = ConfigManager.getInstance();
@Override
public void start() {
Constants.LOGGER.info("🟢 Iniciando HttpServerVerticle...");
Router router = Router.router(vertx);
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();
options.setThreadingModel(ThreadingModel.WORKER);
getVertx().deployVerticle(new DatabaseVerticle(), options, result -> {
if(result.succeeded()) {
Constants.LOGGER.info("📡 HttpServerVerticle desplegado.(http://localhost:8080)");
} 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());
}
});
getVertx().deployVerticle(new DatabaseVerticle(), options);
getVertx().deployVerticle(new ApiVerticle(), options);
getVertx().deployVerticle(new HttpServerVerticle());
}
@Override

View File

@@ -1,3 +1,4 @@
# DB Configuration
db.protocol=jdbc:mariadb:
db.host=localhost
db.port=3306
@@ -5,3 +6,8 @@ db.name=dad
db.user=root
db.pwd=root
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" />
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
<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/leaflet-DYDK0jU3.js">
<link rel="modulepreload" crossorigin href="/assets/chartjs-C6LAl0aW.js">

View File

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

View File

@@ -1,3 +1,4 @@
# DB Configuration
db.protocol=jdbc:mariadb:
db.host=localhost
db.port=3306
@@ -5,3 +6,8 @@ db.name=dad
db.user=root
db.pwd=root
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" />
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
<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/leaflet-DYDK0jU3.js">
<link rel="modulepreload" crossorigin href="/assets/chartjs-C6LAl0aW.js">

View File

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

View File

@@ -69,14 +69,10 @@ const HistoryChartsContent = () => {
const options = theme === "dark" ? optionsDark : optionsLight;
const currentHour = new Date().getHours();
console.log("currentHour", currentHour);
const timeLabels = [
`${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>;
const temperatureData = [];

View File

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