66 lines
2.0 KiB
Java
66 lines
2.0 KiB
Java
package org.warp.jcwdb;
|
|
|
|
import java.io.IOException;
|
|
import java.nio.file.Path;
|
|
import java.util.Map;
|
|
import java.util.WeakHashMap;
|
|
|
|
public class JCWDatabase implements AutoCloseable {
|
|
protected final TypesManager typesManager;
|
|
protected final MixedIndexDatabase indices;
|
|
private final WeakHashMap<Long, EntryReference<?>> references;
|
|
private final WeakHashMap<Object, EntryReference<?>> referencesByObject;
|
|
|
|
public JCWDatabase(Path dataFile, Path metadataFile) throws IOException {
|
|
this.typesManager = new TypesManager(this);
|
|
this.indices = new MixedIndexDatabase(typesManager, dataFile, metadataFile);
|
|
this.references = new WeakHashMap<>();
|
|
this.referencesByObject = new WeakHashMap<>();
|
|
}
|
|
|
|
public <T> EntryReference<T> getRoot() throws IOException {
|
|
try {
|
|
return get(0);
|
|
} catch (IOException e) {
|
|
throw new IOException("Can't load root!", e);
|
|
}
|
|
}
|
|
|
|
public <T> EntryReference<T> get(long index) throws IOException {
|
|
EntryReference<T> ref = (EntryReference<T>) this.references.getOrDefault(index, null);
|
|
if (ref == null) {
|
|
int type = this.indices.getType(index);
|
|
DBTypeParser<T> typeParser = this.typesManager.get(type);
|
|
ref = new EntryReference<>(this, index, typeParser);
|
|
this.references.put(index, ref);
|
|
this.referencesByObject.put(ref.value, ref);
|
|
}
|
|
return ref;
|
|
}
|
|
|
|
public <T> EntryReference<T> add(T o) throws IOException {
|
|
EntryReference<T> ref = (EntryReference<T>) referencesByObject.getOrDefault(o, null);
|
|
if (ref != null) {
|
|
return ref;
|
|
}
|
|
DBTypeParser<T> typeParser = this.typesManager.get((Class<T>) o.getClass());
|
|
long index = indices.add(typeParser.getWriter(o));
|
|
ref = new EntryReference<>(this, index, typeParser);
|
|
this.references.put(index, ref);
|
|
this.referencesByObject.put(o, ref);
|
|
return ref;
|
|
}
|
|
|
|
protected void removeEntryReference(long index) {
|
|
this.references.remove(index);
|
|
}
|
|
|
|
@Override
|
|
public void close() throws Exception {
|
|
for (Map.Entry<Long, EntryReference<?>> reference : references.entrySet()) {
|
|
reference.getValue().close();
|
|
}
|
|
this.indices.close();
|
|
}
|
|
}
|