|
| 1 | +package io.kestra.core.repositories; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import io.kestra.core.models.Setting; |
| 6 | +import io.kestra.jdbc.JdbcMapper; |
| 7 | +import jakarta.validation.ConstraintViolationException; |
| 8 | + |
| 9 | +import java.util.*; |
| 10 | + |
| 11 | +public class InMemorySettingRepository implements SettingRepositoryInterface { |
| 12 | + private final Map<String, String> settings = new HashMap<>(); |
| 13 | + private static final ObjectMapper MAPPER = JdbcMapper.of(); |
| 14 | + |
| 15 | + @Override |
| 16 | + public Optional<Setting> findByKey(String key) { |
| 17 | + return deserialize(settings.get(key)); |
| 18 | + } |
| 19 | + |
| 20 | + @Override |
| 21 | + public List<Setting> findAll() { |
| 22 | + return new ArrayList<>(settings.values().stream().map(this::deserialize) |
| 23 | + .filter(Optional::isPresent).map(Optional::get).toList()); |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public Setting save(Setting setting) throws ConstraintViolationException { |
| 28 | + return internalSave(setting); |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public Setting internalSave(Setting setting) throws ConstraintViolationException { |
| 33 | + settings.put(setting.getKey(), serialize(setting)); |
| 34 | + return setting; |
| 35 | + } |
| 36 | + |
| 37 | + @Override |
| 38 | + public Setting delete(Setting setting) { |
| 39 | + if (!settings.containsKey(setting.getKey())) { |
| 40 | + throw new IllegalStateException("Setting " + setting.getKey() + " doesn't exists"); |
| 41 | + } |
| 42 | + |
| 43 | + settings.remove(setting.getKey()); |
| 44 | + return setting; |
| 45 | + } |
| 46 | + |
| 47 | + public void clear() { |
| 48 | + settings.clear(); |
| 49 | + } |
| 50 | + |
| 51 | + private String serialize(Setting setting) { |
| 52 | + try { |
| 53 | + return MAPPER.writeValueAsString(setting); |
| 54 | + } catch (JsonProcessingException e) { |
| 55 | + throw new RuntimeException(e); |
| 56 | + } |
| 57 | + } |
| 58 | + private Optional<Setting> deserialize(String jsonString) { |
| 59 | + if (jsonString == null) { |
| 60 | + return Optional.empty(); |
| 61 | + } |
| 62 | + try { |
| 63 | + return Optional.ofNullable(MAPPER.readValue(jsonString, Setting.class)); |
| 64 | + } catch (JsonProcessingException e) { |
| 65 | + throw new RuntimeException(e); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments