package it.cavallium.strangedb.java.database; import it.cavallium.strangedb.database.DatabaseCore; import it.cavallium.strangedb.java.objects.EnhancedObject; import it.cavallium.strangedb.functionalinterfaces.FunctionWithIO; import java.io.IOException; import java.nio.file.Path; public class DatabaseJava extends DatabaseCore implements IDatabaseTools { private final IDatabaseTools databaseTools; private final DatabaseObjectsIO objectsIO; private EnhancedObject loadedRootObject; public DatabaseJava(Path dataFile, Path blocksMetaFile, Path referencesMetaFile) throws IOException { super(dataFile, blocksMetaFile, referencesMetaFile); this.databaseTools = this; this.objectsIO = new DatabaseObjectsIO(databaseTools, referencesIO); } @Override public synchronized void close() throws IOException { if (this.closed) { throw new IOException("The database has been already closed!"); } this.objectsIO.setEnhancedObject(0, loadedRootObject); super.close(); } public T loadRoot(FunctionWithIO ifAbsent) throws IOException { if (loadedRootObject != null) { throw new RuntimeException("Root already set!"); } T root; if (referencesMetadata.getFirstFreeReference() > 0) { root = objectsIO.loadEnhancedObject(0); } else { if (objectsIO.newNullObject() != 0) { throw new IOException("Can't allocate root!"); } else { root = ifAbsent.apply(DatabaseJava.this); objectsIO.setEnhancedObject(0, root); } } loadedRootObject = root; return root; } protected void registerClass(Class type, int id) { this.objectsIO.registerClass(type, id); } @Override public void initializeEnhancedObject(EnhancedObject enhancedObject) throws IOException { this.objectsIO.getDataInitializer().initializeDbObject(enhancedObject); } @Override public IObjectsIO getObjectsIO() { return objectsIO; } }