com.xlrit.gears.base.repository.TestRepository Maven / Gradle / Ivy
package com.xlrit.gears.base.repository;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.xlrit.gears.base.execution.Execution;
import com.xlrit.gears.base.id.IdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestRepository extends AbstractRepository {
private static final Logger LOG = LoggerFactory.getLogger(TestRepository.class);
private final IdGenerator idGenerator;
private final Map knownElements;
public TestRepository(Class entityType, IdGenerator idGenerator) {
super(entityType);
this.idGenerator = idGenerator;
this.knownElements = new HashMap<>();
}
public TestRepository(Class entityType) {
this(entityType, null);
}
public void addKnownElement(String id, T element) {
knownElements.put(id, element);
}
@Override
public List findAll() {
return List.copyOf(knownElements.values());
}
@Override
public T findById(String id) {
return knownElements.get(id);
}
@Override
protected T doCreate(Execution execution) {
if (idGenerator == null) throw new UnsupportedOperationException("Creation is only possible when an IdGenerator is set");
try {
String id = idGenerator.getNextId();
Constructor constructor = entityType.getConstructor(String.class);
T element = constructor.newInstance(id);
addKnownElement(id, element);
return element;
}
catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
@Override
protected void doRemove(T instance, Execution execution) {
throw new UnsupportedOperationException();
}
}