Java tutorial
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.libraryweasel.configmanager; import com.fasterxml.jackson.databind.ObjectMapper; import org.libraryweasel.configmanager.api.ConfigManager; import org.libraryweasel.plugin.file.InstancePathsService; import org.libraryweasel.servo.Component; import org.libraryweasel.servo.Service; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @Component(ConfigManager.class) public class JsonConfigManager implements ConfigManager { @Service private volatile InstancePathsService pathsService; private ObjectMapper objectMapper = new ObjectMapper(); @Override public <T> T read(String name, Class<T> configurationClass) { Path path = pathsService.getInstancePath("config/" + name + ".json"); try { return objectMapper.readValue(path.toFile(), configurationClass); } catch (Exception ex) { throw new RuntimeException(ex); } } @Override public <T> void write(String name, T instance) { Path path = pathsService.getInstancePath("config/" + name + ".json"); try { objectMapper.writeValue(path.toFile(), instance); } catch (Exception ex) { throw new RuntimeException(ex); } } @Override public List<String> getConfigurations() { List<String> result = new ArrayList<>(); Path dir = pathsService.getInstancePath("config/"); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{json}")) { for (Path entry : stream) { result.add(entry.getFileName().toString()); } } catch (IOException ex) { throw new RuntimeException(ex); } return result; } }