forked from LupusNobilis/java-org.hwo
119 lines
2.5 KiB
Java
119 lines
2.5 KiB
Java
package org.hwo.serialize;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
public class Database {
|
|
|
|
//HEADER
|
|
//[4]String DatabaseID
|
|
//[4] Short ObjectCount
|
|
//[2] Short InfoSize
|
|
//[InfoSize] Info
|
|
//[4] String "DATA"
|
|
|
|
private static final String DATABASE_ID = "HF3B";
|
|
|
|
private List<DatabaseObject> objects;
|
|
private long sizeInBytes;
|
|
|
|
public Database() {
|
|
this.objects = new ArrayList<DatabaseObject>();
|
|
|
|
}
|
|
|
|
public void addObject(DatabaseObject obj) {
|
|
if(this.objects.contains(obj))
|
|
return;
|
|
this.objects.add(obj);
|
|
}
|
|
|
|
public void addObject(String name) {
|
|
DatabaseObject temp = new DatabaseObject(name);
|
|
if(temp != null)
|
|
this.objects.add(temp);
|
|
}
|
|
|
|
public DatabaseObject getObject(String name) {
|
|
for(DatabaseObject o : objects)
|
|
if(o.getName().equals(name))
|
|
return o;
|
|
return null;
|
|
}
|
|
|
|
public void removeObject(DatabaseObject obj) {
|
|
if(this.objects.contains(obj))
|
|
return;
|
|
int index = this.objects.indexOf(obj);
|
|
this.objects.remove(index);
|
|
}
|
|
|
|
public void removeObject(String obj) {
|
|
DatabaseObject temp = getObject(obj);
|
|
removeObject(temp);
|
|
}
|
|
|
|
public String toString() {
|
|
String result = new String();
|
|
|
|
result += "==========Database==========" + "\n";
|
|
for(DatabaseObject o : this.objects)
|
|
result += o.toString(5);
|
|
result += "\n";
|
|
return result;
|
|
}
|
|
|
|
public void print() {
|
|
System.out.print(this.toString());
|
|
}
|
|
|
|
public byte[] serialize() {
|
|
List<Byte> bytes = new ArrayList<Byte>();
|
|
|
|
BinaryParser.writeBytes(bytes, DATABASE_ID);
|
|
BinaryParser.writeBytes(bytes, (short)this.objects.size());
|
|
BinaryParser.writeBytes(bytes, "DATA");
|
|
|
|
for(DatabaseObject obj : this.objects) {
|
|
byte[] temp = obj.serialize();
|
|
for(byte b : temp)
|
|
bytes.add(b);
|
|
}
|
|
|
|
byte[] result = new byte[bytes.size()];
|
|
for(int i = 0; i < bytes.size(); i++)
|
|
result[i] = bytes.get(i);
|
|
|
|
this.sizeInBytes = result.length;
|
|
|
|
bytes = null;
|
|
return result;
|
|
}
|
|
|
|
public static Database deserialize(byte[] src) {
|
|
//HEADER
|
|
//[4]String DatabaseID
|
|
//[4] Short ObjectCount
|
|
//[4] String "DATA"
|
|
int ptr = 0;
|
|
String tDbId = BinaryParser.readString(src, 4, ptr);
|
|
ptr += 4;
|
|
if(!tDbId.equals(DATABASE_ID))
|
|
return null;
|
|
short tObjCount = BinaryParser.readShort(src, ptr);
|
|
ptr += 2;
|
|
String tDataId = BinaryParser.readString(src, 4, ptr);
|
|
ptr += 4;
|
|
|
|
Database result = new Database();
|
|
for(int i = 0; i < tObjCount; i++) {
|
|
DatabaseObject obj = DatabaseObject.deserialize(src, ptr);
|
|
ptr += obj.getSizeInBytes();
|
|
result.addObject(obj);
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
}
|