Aegis/app/src/main/java/me/impy/aegis/db/Database.java

95 lines
2.8 KiB
Java
Raw Normal View History

package me.impy.aegis.db;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Database {
2017-08-26 21:15:53 +02:00
private static final int VERSION = 1;
2017-12-27 21:01:53 +01:00
2017-08-26 21:15:53 +02:00
private List<DatabaseEntry> _entries = new ArrayList<>();
2017-12-27 21:01:53 +01:00
private long _counter = 0;
2017-08-26 21:15:53 +02:00
public byte[] serialize() throws Exception {
return serialize(false);
}
public byte[] serialize(boolean pretty) throws Exception {
JSONArray array = new JSONArray();
2017-08-26 21:15:53 +02:00
for (DatabaseEntry e : _entries) {
array.put(e.serialize());
}
JSONObject obj = new JSONObject();
2017-08-26 21:15:53 +02:00
obj.put("version", VERSION);
obj.put("entries", array);
String string = pretty ? obj.toString(4) : obj.toString();
return string.getBytes("UTF-8");
}
public void deserialize(byte[] data) throws Exception {
deserialize(data, true);
}
public void deserialize(byte[] data, boolean incCount) throws Exception {
JSONObject obj = new JSONObject(new String(data, "UTF-8"));
2017-08-26 21:15:53 +02:00
// TODO: support different VERSION deserialization providers
int ver = obj.getInt("version");
2017-08-26 21:15:53 +02:00
if (ver != VERSION) {
throw new Exception("Unsupported version");
}
JSONArray array = obj.getJSONArray("entries");
for (int i = 0; i < array.length(); i++) {
DatabaseEntry entry = new DatabaseEntry(null);
entry.deserialize(array.getJSONObject(i));
// if incCount is false, don't increment the counter and don't set an ID
// this is used by the database importer to prevent an exception down the line
// TODO: find a better solution for this ugly hack
if (incCount) {
addKey(entry);
} else {
_entries.add(entry);
}
}
}
2017-12-27 21:01:53 +01:00
public void addKey(DatabaseEntry entry) throws Exception {
entry.setID(++_counter);
2017-08-26 21:15:53 +02:00
_entries.add(entry);
}
2017-11-27 21:06:23 +01:00
public void removeKey(DatabaseEntry entry) {
entry = getKeyByID(entry.getID());
2017-08-26 21:15:53 +02:00
_entries.remove(entry);
}
public void replaceKey(DatabaseEntry newEntry) {
DatabaseEntry oldEntry = getKeyByID(newEntry.getID());
_entries.set(_entries.indexOf(oldEntry), newEntry);
}
public void swapKeys(DatabaseEntry entry1, DatabaseEntry entry2) {
Collections.swap(_entries, _entries.indexOf(entry1), _entries.indexOf(entry2));
}
2017-11-27 21:06:23 +01:00
public List<DatabaseEntry> getKeys() {
return Collections.unmodifiableList(_entries);
}
private DatabaseEntry getKeyByID(long id) {
for (DatabaseEntry entry : _entries) {
if (entry.getID() == id) {
return entry;
}
}
throw new AssertionError("no entry found with the same id");
}
}