Sauvegarde et lecture du fichier de synchronisation -> Json vers AppData terminé

This commit is contained in:
Maximilien LEDOUX 2022-03-08 09:05:03 +01:00
parent 57984456f1
commit d4cff6de09

View File

@ -1,9 +1,8 @@
package lightcontainer.storage;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.*;
import java.util.Iterator;
import java.util.*;
public class JsonAdapter implements Adapter {
@ -65,6 +64,62 @@ public class JsonAdapter implements Adapter {
@Override
public AppData fromString(String appDataString) {
try {
JsonElement jsonString = JsonParser.parseString(appDataString);
JsonObject jsonAppData = jsonString.getAsJsonObject();
AppConfig appConfig = AppConfig.getInstance();
appConfig.setUnicastPort(jsonAppData.get("unicast_port").getAsInt());
appConfig.setMulticastIp(jsonAppData.get("multicast_ip").getAsString());
appConfig.setMulticastPort(jsonAppData.get("multicast_port").getAsInt());
appConfig.setNetworkInterface(jsonAppData.get("network_interface").getAsString());
appConfig.setTls(jsonAppData.get("tls").getAsBoolean());
JsonArray jsonUsers = jsonAppData.getAsJsonArray("users");
List<User> users = new ArrayList<>();
getUsers(jsonUsers, users);
AppData appData = AppData.getInstance();
appData.setAppConfig(appConfig);
for (User user : users) {
appData.addUser(user);
}
return appData;
} catch (JsonParseException parseException) {
System.out.println("[FFE] : Error while loading configuration file"); //TODO - changer en log
}
return null;
}
private void getUsers(JsonArray jsonUsers, List<User> users) {
for (JsonElement element : jsonUsers) {
JsonObject jsonUser = element.getAsJsonObject();
String name = jsonUser.get("username").getAsString();
String password = jsonUser.get("password").getAsString();
String aeskey = jsonUser.get("aes_key").getAsString();
Map<String, File> userFiles = new HashMap<>();
JsonArray jsonFiles = jsonUser.getAsJsonArray("files");
getFiles(userFiles, jsonFiles);
User user = new User(name, password, aeskey, userFiles);
users.add(user);
}
}
private void getFiles(Map<String, File> userFiles, JsonArray jsonFiles) {
for (JsonElement fileElement : jsonFiles) {
JsonObject jsonFile = fileElement.getAsJsonObject();
String fileName = jsonFile.get("name").getAsString();
int size = jsonFile.get("size").getAsInt();
String iv = jsonFile.get("iv").getAsString();
Set<String> storage = new HashSet<>();
JsonArray jsonStorage = jsonFile.getAsJsonArray("storage");
getStorage(storage, jsonStorage);
File file = new File(fileName, size, iv, storage);
userFiles.put(file.getName(), file);
}
}
private void getStorage(Set<String> storage, JsonArray jsonStorage) {
for (JsonElement storageElement : jsonStorage) {
String storageName = storageElement.getAsString();
storage.add(storageName);
}
}
}