Skip to content

Commit bc41a13

Browse files
committed
Add AddCluster route and handler for cluster registration; implement validation and database storage; enhance AddBone handler to include boneType in database save
1 parent bc64589 commit bc41a13

11 files changed

Lines changed: 260 additions & 112 deletions

File tree

.idea/dataSources.xml

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/sqldialects.xml

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/main/java/io/nodelink/server/NodeLinkHelper.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,18 @@ public void fullClearAndRefresh(Terminal terminal) {
152152
terminal.flush();
153153
}
154154

155+
private String getFinalURL() {
156+
Object value = NodeLink.getInstance().getStoreData().get(NodeLink.getInstance().getStoreData().WHICH_TYPE);
157+
158+
if (value == null) {
159+
return "Not set...";
160+
} else if ((boolean) value) {
161+
return "Not available...";
162+
} else {
163+
return NodeLink.getInstance().getStoreData().get(NodeLink.getInstance().getStoreData().URL_BONE).toString();
164+
}
165+
}
166+
155167
private void updateLocationDisplay() {
156168
Object value = NodeLink.getInstance().getStoreData().get(NodeLink.getInstance().getStoreData().WHICH_TYPE);
157169

@@ -168,7 +180,7 @@ private void updateLocationDisplay() {
168180
if (clusterLocationValue != null) {
169181
CLUSTER_LOCATION clusterLocation = CLUSTER_LOCATION.valueOf(clusterLocationValue.toString());
170182

171-
terminal.writer().println(GREEN + " ● Cluster Region: " + RESET + clusterLocation.name() + " |" + " (" + "https://." + clusterLocation.getLocationCluster() + ".nodelinkapp.xyz" + ")");
183+
terminal.writer().println(GREEN + " ● Cluster Region: " + RESET + clusterLocation.name() + " |" + " (" + getFinalURL() + ")");
172184
} else {
173185
terminal.writer().println(GREEN + " ● Cluster Region: " + RESET + "Not set...");
174186
}
@@ -177,7 +189,7 @@ private void updateLocationDisplay() {
177189
if (boneLocationValue != null) {
178190
BONE_LOCATION boneLocation = BONE_LOCATION.valueOf(boneLocationValue.toString());
179191

180-
terminal.writer().println(GREEN + " ● Bone Location: " + RESET + boneLocation.name() + " |" + " (" + "https://." + boneLocation.getLocation() + ".nodelinkapp.xyz" + ")");
192+
terminal.writer().println(GREEN + " ● Bone Location: " + RESET + boneLocation.name() + " |" + " (" + getFinalURL() + ")");
181193
} else {
182194
terminal.writer().println(GREEN + " ● Bone Location: " + RESET + "Not set...");
183195
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package io.nodelink.server.app.cluster.api.routes.v1.definition;
2+
3+
import io.javalin.http.Context;
4+
import io.javalin.http.HandlerType;
5+
import io.nodelink.server.app.cluster.api.routes.v1.handler.AddClusterH;
6+
import io.nodelink.server.app.infra.RouteDefinition;
7+
8+
public class AddCluster implements RouteDefinition {
9+
10+
@Override
11+
public HandlerType method() {
12+
return HandlerType.POST;
13+
}
14+
15+
@Override
16+
public String path() {
17+
return "/addCluster";
18+
}
19+
20+
@Override
21+
public boolean enabled() {
22+
return true;
23+
}
24+
25+
@Override
26+
public void handle(Context ctx) throws Exception {
27+
new AddClusterH().handle(ctx);
28+
}
29+
}
30+
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package io.nodelink.server.app.cluster.api.routes.v1.handler;
2+
3+
import com.fasterxml.jackson.core.JsonProcessingException;
4+
import com.fasterxml.jackson.databind.JsonNode;
5+
import com.fasterxml.jackson.databind.ObjectMapper;
6+
import com.fasterxml.jackson.databind.node.ObjectNode;
7+
import io.javalin.http.Context;
8+
import io.nodelink.server.app.data.CLUSTER_LOCATION;
9+
import io.nodelink.server.app.infra.ApiHandler;
10+
import io.nodelink.server.app.infra.DatabaseService;
11+
12+
import java.sql.SQLException;
13+
14+
public class AddClusterH implements ApiHandler {
15+
private final ObjectMapper objectMapper = new ObjectMapper();
16+
17+
@Override
18+
public void handle(Context ctx) throws JsonProcessingException, SQLException {
19+
JsonNode requestBody = objectMapper.readTree(ctx.body());
20+
21+
// Check if in the request body we have "clusterType" and "boneType"
22+
if (requestBody == null || !requestBody.has("clusterType") || !requestBody.has("boneType")) {
23+
ctx.status(400).result("Invalid request body. 'boneType' and 'clusterType' are required.");
24+
}
25+
26+
// Then i generate an ID
27+
int range = (1 - 9999) + 1;
28+
int id = (int) (Math.random() * range) + 9999;
29+
String clusterId = "C" + id;
30+
31+
// I will put data in variables
32+
// Assert not null for requestBody
33+
assert requestBody != null;
34+
35+
String clusterType = requestBody.get("clusterType").asText();
36+
String boneType = requestBody.get("boneType").asText();
37+
38+
// Check SQLite
39+
if (DatabaseService.getTimestamp("ClusterTable", clusterId) != null) {
40+
ctx.status(409).result("Erreur : Le cluster " + clusterId + " existe déjà.");
41+
}
42+
43+
// Check if location is valid
44+
CLUSTER_LOCATION clusterType_Enum;
45+
try {
46+
clusterType_Enum = CLUSTER_LOCATION.valueOf(clusterType.toUpperCase());
47+
} catch (IllegalArgumentException e) {
48+
ctx.status(400).result("Erreur : Location '" + clusterType + "' inconnue.");
49+
System.out.println("Location : " + clusterType + " inconnue");
50+
return;
51+
}
52+
53+
Object getId = DatabaseService.getInfo("BoneTable", "boneType", boneType, "id").toString();
54+
55+
56+
57+
String clusterLocation = clusterType_Enum.getLocationCluster();
58+
String finalUrl = String.format("https://%s.%s.nodelinkapp.xyz", clusterId, clusterLocation);
59+
// Response JSON
60+
ObjectNode clusterData = objectMapper.createObjectNode();
61+
clusterData.put("id", id);
62+
clusterData.put("clusterId", clusterId);
63+
clusterData.put("clusterType", clusterType);
64+
clusterData.put("url", finalUrl);
65+
66+
clusterData.putArray("coords")
67+
.add(clusterType_Enum.getLatitude())
68+
.add(clusterType_Enum.getLongitude());
69+
70+
// Save to Database
71+
try {
72+
DatabaseService.saveCluster(clusterId, clusterData.toString(), clusterType);
73+
74+
System.out.println("[DB] Cluster " + clusterId + " saved to database.");
75+
ctx.status(201).json(clusterData);
76+
77+
} catch (Exception e) {
78+
ctx.status(500).result("Error : " + e.getMessage());
79+
}
80+
}
81+
}

src/main/java/io/nodelink/server/app/infra/DatabaseService.java

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,38 +13,60 @@ public class DatabaseService {
1313
Statement stmt = conn.createStatement();
1414

1515
// Tables existantes
16-
stmt.execute("CREATE TABLE IF NOT EXISTS ClusterTable (id TEXT PRIMARY KEY, content TEXT, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);");
17-
stmt.execute("CREATE TABLE IF NOT EXISTS BoneTable (id TEXT PRIMARY KEY, content TEXT, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);");
16+
stmt.execute("CREATE TABLE IF NOT EXISTS ClusterTable (id TEXT PRIMARY KEY, content TEXT, clusterType TEXT, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);");
17+
stmt.execute("CREATE TABLE IF NOT EXISTS BoneTable (id TEXT PRIMARY KEY, content TEXT, boneType TEXT, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);");
18+
19+
System.out.println("Database initialized successfully.");
1820
} catch (SQLException e) {
1921
e.printStackTrace();
2022
}
2123
}
2224

23-
public static void save(String table, String id, String content, String timestamp, boolean fromSync) throws SQLException {
25+
private static void save(String table, String id, String content, String timestamp, String Type) throws SQLException {
2426
try (Connection conn = DriverManager.getConnection(URL)) {
25-
String sql = "INSERT OR REPLACE INTO " + table + " (id, content, updated_at) VALUES (?, ?, ?)";
27+
String sql = "INSERT OR REPLACE INTO " + table + " (id, content, boneType, updated_at) VALUES (?, ?, ?, ?)";
2628
PreparedStatement pstmt = conn.prepareStatement(sql);
2729
pstmt.setString(1, id);
2830
pstmt.setString(2, content);
29-
pstmt.setString(3, timestamp);
31+
pstmt.setString(3, Type);
32+
pstmt.setString(4, timestamp);
3033
pstmt.executeUpdate();
3134
}
3235
}
3336

3437
// Raccourci pour sauvegarder un Bone
35-
public static void saveBone(String id, String jsonContent) throws SQLException {
38+
public static void saveBone(String id, String jsonContent, String boneType) throws SQLException {
3639
String timestamp = java.time.Instant.now().toString();
3740
// On injecte le timestamp dans le JSON avant de sauvegarder
3841
String enrichedJson = injectTimestamp(jsonContent, timestamp);
39-
save("BoneTable", id, enrichedJson, timestamp, false);
42+
save("BoneTable", id, enrichedJson, timestamp, boneType);
4043
}
4144

45+
public static Object getInfo(String table, String query, String value, String valueToReturn) throws SQLException {
46+
if (!table.equals("BoneTable") && !table.equals("ClusterTable")) {
47+
return false;
48+
}
49+
50+
try (Connection conn = DriverManager.getConnection(URL)) {
51+
String sql = "SELECT * FROM " + table + " WHERE " + query + " = ?";
52+
PreparedStatement preparedStatement = conn.prepareStatement(sql);
53+
preparedStatement.setString(1, value);
54+
ResultSet resultSet = preparedStatement.executeQuery();
55+
56+
if (resultSet.next()) {
57+
return resultSet.getString(valueToReturn);
58+
}
59+
}
60+
return false;
61+
}
62+
63+
4264
// Raccourci pour sauvegarder un Cluster
43-
public static void saveCluster(String id, String jsonContent) throws SQLException {
65+
public static void saveCluster(String id, String jsonContent, String clusterType) throws SQLException {
4466
String timestamp = java.time.Instant.now().toString();
4567
// On injecte le timestamp dans le JSON avant de sauvegarder
4668
String enrichedJson = injectTimestamp(jsonContent, timestamp);
47-
save("ClusterTable", id, enrichedJson, timestamp, false);
69+
save("ClusterTable", id, enrichedJson, timestamp, clusterType);
4870
}
4971

5072
// Utilitaire pour ajouter le champ updated_at dans le JSON lui-même

src/main/java/io/nodelink/server/app/node/api/routes/v1/handler/AddBoneH.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public void handle(Context ctx) throws JsonProcessingException {
6363

6464
// Save to Database
6565
try {
66-
DatabaseService.saveBone(boneId, boneData.toString());
66+
DatabaseService.saveBone(boneId, boneData.toString(), boneType);
6767

6868
System.out.println("[DB] Bone " + boneId + " saved to database.");
6969
ctx.status(201).json(boneData);

0 commit comments

Comments
 (0)