Skip to content

Commit 52e08c9

Browse files
committed
Refactor database interactions to use a unified InfoTable; update AddBone and AddCluster handlers for consistency; remove deprecated methods and improve error handling
1 parent bc41a13 commit 52e08c9

6 files changed

Lines changed: 36 additions & 55 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ private void initTerminal() {
110110
terminal.writer().println("Commande inconnue : " + command);
111111
}
112112
} catch (Exception e) {
113-
terminal.writer().println("Erreur : La commande '" + command + "' n'est pas reconnue.");
113+
//terminal.writer().println("Erreur : La commande '" + command + "' n'est pas reconnue.");
114114
}
115115

116116
terminal.writer().flush();

src/main/java/io/nodelink/server/app/cluster/api/routes/v1/handler/AddClusterH.java

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,9 @@ public void handle(Context ctx) throws JsonProcessingException, SQLException {
3333
assert requestBody != null;
3434

3535
String clusterType = requestBody.get("clusterType").asText();
36-
String boneType = requestBody.get("boneType").asText();
3736

3837
// Check SQLite
39-
if (DatabaseService.getTimestamp("ClusterTable", clusterId) != null) {
38+
if ((boolean) DatabaseService.getInfo("InfoTable", "id", clusterId, "id")) {
4039
ctx.status(409).result("Erreur : Le cluster " + clusterId + " existe déjà.");
4140
}
4241

@@ -50,31 +49,35 @@ public void handle(Context ctx) throws JsonProcessingException, SQLException {
5049
return;
5150
}
5251

53-
Object getId = DatabaseService.getInfo("BoneTable", "boneType", boneType, "id").toString();
54-
55-
56-
52+
Object getId = DatabaseService.getInfo("InfoTable", "ServerType", requestBody.get("boneType").asText(), "id");
5753
String clusterLocation = clusterType_Enum.getLocationCluster();
5854
String finalUrl = String.format("https://%s.%s.nodelinkapp.xyz", clusterId, clusterLocation);
55+
56+
String boneId = "";
57+
if (!getId.equals(false)) {
58+
boneId = getId.toString();
59+
} else {
60+
//TODO Add Sync method
61+
}
62+
5963
// Response JSON
6064
ObjectNode clusterData = objectMapper.createObjectNode();
6165
clusterData.put("id", id);
6266
clusterData.put("clusterId", clusterId);
6367
clusterData.put("clusterType", clusterType);
6468
clusterData.put("url", finalUrl);
69+
clusterData.put("link", boneId);
6570

6671
clusterData.putArray("coords")
6772
.add(clusterType_Enum.getLatitude())
6873
.add(clusterType_Enum.getLongitude());
6974

70-
// Save to Database
7175
try {
72-
DatabaseService.saveCluster(clusterId, clusterData.toString(), clusterType);
76+
DatabaseService.save("InfoTable", clusterId, clusterData.toString(), clusterType);
7377

7478
System.out.println("[DB] Cluster " + clusterId + " saved to database.");
75-
ctx.status(201).json(clusterData);
76-
77-
} catch (Exception e) {
79+
} catch (SQLException e) {
80+
e.printStackTrace();
7881
ctx.status(500).result("Error : " + e.getMessage());
7982
}
8083
}

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

Lines changed: 7 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,19 @@ 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, 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);");
16+
stmt.execute("CREATE TABLE IF NOT EXISTS InfoTable (id TEXT PRIMARY KEY, content TEXT, ServerType TEXT, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP);");
1817

1918
System.out.println("Database initialized successfully.");
2019
} catch (SQLException e) {
2120
e.printStackTrace();
2221
}
2322
}
2423

25-
private static void save(String table, String id, String content, String timestamp, String Type) throws SQLException {
24+
public static void save(String table, String id, String content, String Type) throws SQLException {
2625
try (Connection conn = DriverManager.getConnection(URL)) {
27-
String sql = "INSERT OR REPLACE INTO " + table + " (id, content, boneType, updated_at) VALUES (?, ?, ?, ?)";
26+
String sql = "INSERT OR REPLACE INTO " + table + " (id, content, ServerType, updated_at) VALUES (?, ?, ?, ?)";
27+
String timestamp = java.time.Instant.now().toString();
28+
2829
PreparedStatement pstmt = conn.prepareStatement(sql);
2930
pstmt.setString(1, id);
3031
pstmt.setString(2, content);
@@ -34,16 +35,8 @@ private static void save(String table, String id, String content, String timesta
3435
}
3536
}
3637

37-
// Raccourci pour sauvegarder un Bone
38-
public static void saveBone(String id, String jsonContent, String boneType) throws SQLException {
39-
String timestamp = java.time.Instant.now().toString();
40-
// On injecte le timestamp dans le JSON avant de sauvegarder
41-
String enrichedJson = injectTimestamp(jsonContent, timestamp);
42-
save("BoneTable", id, enrichedJson, timestamp, boneType);
43-
}
44-
4538
public static Object getInfo(String table, String query, String value, String valueToReturn) throws SQLException {
46-
if (!table.equals("BoneTable") && !table.equals("ClusterTable")) {
39+
if (!table.equals("InfoTable")) {
4740
return false;
4841
}
4942

@@ -60,30 +53,8 @@ public static Object getInfo(String table, String query, String value, String va
6053
return false;
6154
}
6255

63-
64-
// Raccourci pour sauvegarder un Cluster
65-
public static void saveCluster(String id, String jsonContent, String clusterType) throws SQLException {
66-
String timestamp = java.time.Instant.now().toString();
67-
// On injecte le timestamp dans le JSON avant de sauvegarder
68-
String enrichedJson = injectTimestamp(jsonContent, timestamp);
69-
save("ClusterTable", id, enrichedJson, timestamp, clusterType);
70-
}
71-
72-
// Utilitaire pour ajouter le champ updated_at dans le JSON lui-même
73-
private static String injectTimestamp(String json, String ts) {
74-
try {
75-
ObjectMapper mapper = new ObjectMapper();
76-
JsonNode node = mapper.readTree(json);
77-
((com.fasterxml.jackson.databind.node.ObjectNode) node).put("updated_at", ts);
78-
return node.toString();
79-
} catch (Exception e) {
80-
return json;
81-
}
82-
}
83-
8456
public static String getTimestamp(String table, String id) {
85-
// On valide le nom de la table pour éviter des injections SQL
86-
if (!table.equals("BoneTable") && !table.equals("ClusterTable")) {
57+
if (!table.equals("InfoTable")) {
8758
return null;
8859
}
8960

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package io.nodelink.server.app.infra;
2+
3+
import io.javalin.http.Context;
4+
5+
public class Sync implements ApiHandler {
6+
@Override
7+
public void handle(Context ctx) throws Exception {
8+
9+
}
10+
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public void handle(Context ctx) throws JsonProcessingException {
3333
String boneType = requestBody.get("boneType").asText();
3434

3535
// Check SQLite
36-
if (DatabaseService.getTimestamp("BoneTable", boneId) != null) {
36+
if (DatabaseService.getTimestamp("InfoTable", boneId) != null) {
3737
ctx.status(409).result("Erreur : Le Bone " + boneId + " existe déjà.");
3838
}
3939

@@ -63,7 +63,7 @@ public void handle(Context ctx) throws JsonProcessingException {
6363

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

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

src/main/java/io/nodelink/server/command/CommandLogics.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,7 @@ public CommandLogics(CommandDispatcher dispatcher, LineReader reader, Terminal t
140140

141141
String oneArgument = cleanedTokens[4].toUpperCase();
142142
String twoArgument = cleanedTokens[5].toUpperCase();
143-
System.out.println(oneArgument);
144-
System.out.println(twoArgument);
143+
145144
try {
146145
CLUSTER_LOCATION clusterLocation = CLUSTER_LOCATION.valueOf(oneArgument);
147146
terminal.writer().println("Emplacement du bone défini sur : " + clusterLocation.name());
@@ -155,8 +154,6 @@ public CommandLogics(CommandDispatcher dispatcher, LineReader reader, Terminal t
155154
boneLocation.name()
156155
);
157156

158-
System.out.println(registrationJson);
159-
160157
HttpRequest registerReq = HttpRequest.newBuilder()
161158
.uri(URI.create("http://localhost:" + CONSTANT.PORT_CLUSTER + "/cluster/api/v1/addCluster"))
162159
.header("Content-Type", "application/json")
@@ -183,7 +180,7 @@ public CommandLogics(CommandDispatcher dispatcher, LineReader reader, Terminal t
183180

184181
NodeLink.getInstance().getStoreData().put(NodeLink.getInstance().getStoreData().BONE_LOCATION, clusterLocation.name());
185182

186-
// NodeLink.getHelper().fullClearAndRefresh(terminal);
183+
NodeLink.getHelper().fullClearAndRefresh(terminal);
187184
} catch (IllegalArgumentException e) {
188185
terminal.writer().println("Emplacement invalide. Veuillez choisir parmi les emplacements disponibles.");
189186
}

0 commit comments

Comments
 (0)