org.bidib.wizard.mvc.ping.model.DefaultPingTablePreferences Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of bidibwizard-client Show documentation
Show all versions of bidibwizard-client Show documentation
jBiDiB BiDiB Wizard Client Application POM
package org.bidib.wizard.mvc.ping.model;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.bidib.jbidibc.messages.utils.ByteUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
public class DefaultPingTablePreferences implements PingTablePreferences {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPingTablePreferences.class);
private final transient ObjectMapper mapper;
private final transient File pingTablePreferencesFile;
private Map preferencesMap = new HashMap<>();
public DefaultPingTablePreferences(final File pingTablePreferencesFile) {
this.pingTablePreferencesFile = pingTablePreferencesFile;
this.mapper = new ObjectMapper();
this.mapper.registerModule(new JavaTimeModule());
}
@Override
public void load() {
this.preferencesMap.clear();
try {
PingTableNodePreferenceEntry[] entries =
this.mapper.readValue(this.pingTablePreferencesFile, PingTableNodePreferenceEntry[].class);
for (PingTableNodePreferenceEntry entry : entries) {
this.preferencesMap.put(ByteUtils.parseHexUniqueId(entry.getUid()), entry);
}
}
catch (FileNotFoundException ex) {
LOGGER.warn("Load the preferences store failed because the file was not found: {}", ex.getMessage());
}
catch (IOException ex) {
LOGGER.warn("Load the preferences store failed.", ex);
}
LOGGER.info("Current preferencesMap: {}", preferencesMap);
}
@Override
public void store() {
LOGGER.info("Store the ping preferences to file.");
try {
// make sure the path to the preferences store exists
FileUtils.forceMkdirParent(this.pingTablePreferencesFile);
// write the preferences store
this.mapper
.writerWithDefaultPrettyPrinter().writeValue(this.pingTablePreferencesFile,
preferencesMap.values().toArray(new PingTableNodePreferenceEntry[0]));
}
catch (IOException ex) {
LOGGER.warn("Store ping preferences failed.", ex);
}
}
@Override
public void clear() {
LOGGER.info("Clear the pairing store.");
preferencesMap.clear();
}
@Override
public PingTableNodePreferenceEntry getPrefences(long uniqueId) {
Long lookupValue = Long.valueOf(uniqueId);
return preferencesMap.get(lookupValue);
}
@Override
public PingTableNodePreferenceEntry getPrefencesOrDefault(long uniqueId) {
Long lookupValue = Long.valueOf(uniqueId);
return preferencesMap
.computeIfAbsent(lookupValue, uid -> new PingTableNodePreferenceEntry(ByteUtils.formatHexUniqueId(uid)));
}
}