de.otto.jlineup.service.RunPersistenceService Maven / Gradle / Ivy
package de.otto.jlineup.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.otto.jlineup.web.JLineupRunStatus;
import de.otto.jlineup.web.configuration.JLineupWebProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import static com.google.common.collect.Maps.toMap;
import static de.otto.jlineup.web.State.DEAD;
import static java.lang.invoke.MethodHandles.lookup;
@Service
public class RunPersistenceService {
private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());
private static final String RUNS_FILENAME = "runs.json";
private final JLineupWebProperties jLineupWebProperties;
private final ObjectMapper objectMapper;
@Autowired
public RunPersistenceService(JLineupWebProperties jLineupWebProperties, ObjectMapper objectMapper) {
this.jLineupWebProperties = jLineupWebProperties;
this.objectMapper = objectMapper;
}
void persistRuns(Map runs) {
Comparator comparator = Comparator.comparing(JLineupRunStatus::getStartTime);
try {
Map mapWithLatestEntries = runs.entrySet().stream()
.sorted(Map.Entry.comparingByValue(comparator).reversed())
.limit(jLineupWebProperties.getMaxPersistedRuns())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
String serializedRuns = objectMapper.writeValueAsString(mapWithLatestEntries);
Path path = getRunsFilePath();
Files.write(path, serializedRuns.getBytes());
} catch (IOException e) {
LOG.error("Serialization of runs failed. Please file a bug report at https://github.com/otto-de/jlineup/issues", e);
}
}
Map readRuns() {
if (Files.exists(getRunsFilePath())) {
try {
TypeReference