pl.setblack.airomem.core.Persistent Maven / Gradle / Ivy
Show all versions of airomem-core Show documentation
/*
* Copyright (c) Jarek Ratajski, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
package pl.setblack.airomem.core;
import pl.setblack.airomem.core.builders.PrevaylerBuilder;
import pl.setblack.airomem.data.DataRoot;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Supplier;
/**
* Simplified version of persistence controller.
*
* This version does not force to follow IMMUTABLE , MUTABLE Pattern. IT is
* easier to implement - but of course not that safe for team development.
*/
public class Persistent implements AutoCloseable {
private final PersistenceController> controller;
private Persistent(PersistenceController> controller) {
this.controller = controller;
}
public static boolean exists(Path path) {
return Files.exists(path);
}
public static Persistent load(Path path) {
return new Persistent(PrevaylerBuilder.>newBuilder()
.withFolder(path)
.build());
}
public static Persistent loadOptional(Path path, Supplier constructor, boolean useRoyalFoodTester) {
return new Persistent(PrevaylerBuilder.>newBuilder()
.useSupplier(() -> new DataRoot<>(constructor.get()))
.withRoyalFoodTester(useRoyalFoodTester)
.withFolder(path)
.build());
}
public static Persistent loadOptional(Path path, Supplier constructor) {
return loadOptional(path, constructor, true);
}
public static Persistent create(Path path, T initial) {
return new Persistent(PrevaylerBuilder.>newBuilder()
.useSupplier(() -> new DataRoot<>(initial))
.forceOverwrite(true)
.withFolder(path)
.build());
}
public RESULT query(Query query) {
return controller.query((dataRoot) -> query.evaluate(dataRoot.getDataObject()));
}
public T readOnly() {
return query(t -> t);
}
@Override
public void close() {
this.controller.close();
}
public void shut() {
this.controller.shut();
}
public boolean isOpen() {
return controller.isOpen();
}
public R executeAndQuery(ContextCommand cmd) {
return controller.executeAndQuery((ContextCommand, R>) ((x, ctx) -> cmd.execute(x.getDataObject(), ctx)));
}
public R executeAndQuery(Command cmd) {
return controller.executeAndQuery((Command, R>) (x -> cmd.execute(x.getDataObject())));
}
public void execute(VoidContextCommand cmd) {
controller.execute((VoidContextCommand>) ((x, ctx) -> cmd.execute(x.getDataObject(), ctx)));
}
public void execute(VoidCommand cmd) {
controller.execute((VoidCommand>) (x -> cmd.execute(x.getDataObject())));
}
}