added json persister, added config reading and writing to file

This commit is contained in:
aj 2019-05-13 07:46:52 +01:00
parent bb829f875d
commit 0371080b00
17 changed files with 403 additions and 190 deletions

1
.gitignore vendored
View File

@ -1,5 +1,6 @@
fmframework/src/sarsoo/fmframework/net/Key.java
.fm
# Directories #
/build/

View File

@ -1,65 +0,0 @@
{
"pie":
{
"tags":[
"jazz",
"blues",
"rnb",
"soulfunk",
],
"hierarchies":[
"rap",
"rock",
"metal"
]
}
,
"genrehierarchy":{
"genres":[
{
"tags":[
"rap",
"classic rap",
"grime",
"trap",
"uk hip-hop"
],
"name":"rap"
},
{
"tags":[
"rock",
"classic rock",
"indie",
"pop punk",
"punk",
"emo"
],
"name":"rock"
},
{
"tags":[
"metal",
"industrial",
"thrash",
"metalcore",
],
"name":"metal"
},
{
"tags":[
"electronic",
"house",
"dnb",
"future bass",
"edm",
"garage"
],
"name":"electronic"
}
]
}
}

View File

@ -12,17 +12,17 @@ public class Config {
}
public Config(ArrayList<ConfigVariable> variables) {
for(ConfigVariable i: variables) {
for (ConfigVariable i : variables) {
addVariable(i);
}
}
public Config addVariable(ConfigVariable variable) {
for(ConfigVariable i: variables) {
if(variable.getKey().equalsIgnoreCase(i.getKey())) {
for (ConfigVariable i : variables) {
if (variable.getKey().equalsIgnoreCase(i.getKey())) {
i.setValue(variable.getValue());
for(VariableListener j: variable.getListeners()) {
for (VariableListener j : variable.getListeners()) {
i.addListener(j);
}
@ -38,8 +38,8 @@ public class Config {
public ConfigVariable getVariable(String key) {
for(ConfigVariable i: variables) {
if (i.getKey() == key) {
for (ConfigVariable i : variables) {
if (i.getKey().equalsIgnoreCase(key)) {
return i;
}
}
@ -47,14 +47,28 @@ public class Config {
return null;
}
public List<ConfigVariable> getVariables() {
return variables;
}
public String getValue(String key) {
ConfigVariable variable = getVariable(key);
if(variable != null) {
if (variable != null) {
return variable.getValue();
}
return null;
}
public String toString() {
String string = "config:";
for(ConfigVariable i: variables) {
string += " " + i.getKey() + " " + i.getValue();
}
return string;
}
}

View File

@ -0,0 +1,73 @@
package sarsoo.fmframework.config;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import sarsoo.fmframework.file.JSONPersister;
import sarsoo.fmframework.log.Logger;
import sarsoo.fmframework.log.entry.ErrorEntry;
import sarsoo.fmframework.log.entry.InfoEntry;
import sarsoo.fmframework.log.entry.LogEntry;
public class ConfigPersister {
protected String variableTag = "vars";
public Config readConfig(String path) {
Logger.getLog().log(new LogEntry("read config").addArg(path));
JSONPersister persist = new JSONPersister();
JSONObject obj = persist.readJSONFromFile(path + "config.json");
Config config = new Config();
if (obj != null) {
JSONArray array = obj.getJSONArray(variableTag);
for (int i = 0; i < array.length(); i++) {
JSONObject var = (JSONObject) array.get(i);
String key = var.keys().next();
config.addVariable(new ConfigVariable(key, var.getString(key)));
// Logger.getLog().logInfo(
// new InfoEntry("read config").addArg(path).addArg("inserted " + key + " " + var.getString(key)));
}
} else {
Logger.getLog().logError(new ErrorEntry("read config").addArg(path).addArg("null json read"));
}
return config;
}
public void saveConfig(String path, Config config) {
JSONObject object = new JSONObject();
JSONArray array = new JSONArray();
List<ConfigVariable> variables = config.getVariables();
for (ConfigVariable i : variables) {
if (!i.isTemporary()) {
JSONObject obj = new JSONObject();
obj.put(i.getKey(), i.getValue());
array.put(obj);
}
}
object.put(variableTag, array);
JSONPersister persist = new JSONPersister();
persist.saveJSONtoFile(object, path + "config.json");
}
}

View File

@ -8,11 +8,22 @@ public class ConfigVariable {
protected String key;
protected String value;
protected boolean temporary;
protected List<VariableListener> listeners;
public ConfigVariable(String key, String value) {
this.key = key;
this.value = value;
this.temporary = false;
this.listeners = new ArrayList<VariableListener>();
}
public ConfigVariable(String key, String value, boolean temporary) {
this.key = key;
this.value = value;
this.temporary = temporary;
this.listeners = new ArrayList<VariableListener>();
}
@ -25,6 +36,14 @@ public class ConfigVariable {
return value;
}
public boolean isTemporary() {
return temporary;
}
public void setTemporary(boolean temporary) {
this.temporary = temporary;
}
public void setValue(String value) {
this.value = value;

View File

@ -0,0 +1,68 @@
package sarsoo.fmframework.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.json.JSONObject;
import sarsoo.fmframework.log.Logger;
import sarsoo.fmframework.log.entry.ErrorEntry;
import sarsoo.fmframework.log.entry.LogEntry;
public class JSONPersister {
public void saveJSONtoFile(JSONObject obj, String path) {
try (FileWriter file = new FileWriter(path)) {
file.write(obj.toString());
Logger.getLog().log(new LogEntry("save json").addArg("json saved"));
} catch (IOException e) {
Logger.getLog().logError(new ErrorEntry("save json").addArg("io exception"));
}
}
public JSONObject readJSONFromFile(String path) {
if (new File(path).isFile()) {
File file = new File(path);
return readJSONFromFile(file);
}else {
Logger.getLog().logError(new ErrorEntry("json load " + path).addArg("invalid path"));
}
return null;
}
public JSONObject readJSONFromFile(File file) {
try {
if (file.isFile()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String jsonLine = br.readLine();
while (jsonLine != null) {
sb.append(jsonLine);
jsonLine = br.readLine();
}
br.close();
String jsonString = sb.toString();
JSONObject rootParsedJsonObj = new JSONObject(jsonString);
return rootParsedJsonObj;
}
} catch (IOException e) {
Logger.getLog().logError(new ErrorEntry("failed to load json " + file));
}
return null;
}
}

View File

@ -1,14 +1,18 @@
package sarsoo.fmframework.fx;
import java.io.File;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import sarsoo.fmframework.config.Config;
import sarsoo.fmframework.config.ConfigVariable;
import sarsoo.fmframework.config.ConfigPersister;
import sarsoo.fmframework.fx.controller.RootController;
import sarsoo.fmframework.net.Key;
import sarsoo.fmframework.fx.service.SaveConfigService;
import sarsoo.fmframework.log.Logger;
import sarsoo.fmframework.log.entry.LogEntry;
public class FmFramework extends Application {
@ -23,23 +27,19 @@ public class FmFramework extends Application {
public void start(Stage stage) throws Exception {
FmFramework.stage = stage;
config = new Config();
config.addVariable(new ConfigVariable("username", "sarsoo"));
config.addVariable(new ConfigVariable("api_key", Key.getKey()));
initConfig();
FXMLLoader loader = new FXMLLoader(getClass().getResource("ui/RootPane.fxml"));
// Parent root = FXMLLoader.load(getClass().getResource("ui/main.fxml"));
Parent root = (Parent)loader.load();
Parent root = (Parent) loader.load();
Scene scene = new Scene(root, 1000, 800);
rootScene = scene;
// scene.getStylesheets().add("styles/style.css");
control = (RootController)loader.getController();
control = (RootController) loader.getController();
// (new Thread(new TagCaller())).start();
stage.setMinHeight(800);
stage.setMinWidth(960);
@ -49,19 +49,34 @@ public class FmFramework extends Application {
}
private void initConfig() {
ConfigPersister persist = new ConfigPersister();
config = persist.readConfig(".fm/");
if (config != null) {
if (!(new File(".fm/").isFile())) {
new File(".fm/").mkdir();
}
SaveConfigService saveConfig = new SaveConfigService(".fm/", config);
saveConfig.start();
}else {
Logger.getLog().log(new LogEntry("load config").addArg("null config returned"));
}
}
public static Config getSessionConfig() {
return config;
}
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(
new Thread(() -> (new ConfigPersister()).saveConfig(".fm/", config)));
launch(args);
}
// public void changeScene() throws IOException {
// Parent root = FXMLLoader.load(getClass().getResource("ui/changed.fxml"));
//
// }
public static RootController getController() {
return control;
}

View File

@ -20,7 +20,6 @@ import sarsoo.fmframework.fx.FmFramework;
import sarsoo.fmframework.fx.tab.ArtistTab;
import sarsoo.fmframework.music.Artist;
import sarsoo.fmframework.music.FMObj;
import sarsoo.fmframework.net.Key;
import sarsoo.fmframework.util.FMObjList;
import sarsoo.fmframework.util.Maths;
import javafx.scene.layout.*;

View File

@ -26,7 +26,6 @@ import sarsoo.fmframework.music.Album;
import sarsoo.fmframework.music.Artist;
import sarsoo.fmframework.music.FMObj;
import sarsoo.fmframework.music.Track;
import sarsoo.fmframework.net.Key;
import sarsoo.fmframework.util.FMObjList;
import sarsoo.fmframework.util.Maths;
import javafx.scene.layout.*;

View File

@ -1,9 +1,6 @@
package sarsoo.fmframework.fx.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONArray;
@ -21,6 +18,8 @@ import javafx.scene.control.TitledPane;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.FileChooser;
import sarsoo.fmframework.config.Config;
import sarsoo.fmframework.file.JSONPersister;
import sarsoo.fmframework.fx.FmFramework;
import sarsoo.fmframework.fx.chart.GenrePieChartTitledPane;
import sarsoo.fmframework.fx.chart.PieChartTitledPane;
@ -30,6 +29,8 @@ import sarsoo.fmframework.log.entry.LogEntry;
public class GenrePieChartPaneController {
protected String defaultPath = "./piechart.json";
@FXML
BorderPane borderPane;
@ -52,56 +53,42 @@ public class GenrePieChartPaneController {
@FXML
public void initialize() {
try {
if (new File("./piechart.json").isFile()) {
File file = new File("./piechart.json");
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String jsonLine = br.readLine();
while (jsonLine != null) {
sb.append(jsonLine);
jsonLine = br.readLine();
}
Config config = FmFramework.getSessionConfig();
br.close();
JSONPersister persist = new JSONPersister();
String jsonString = sb.toString();
JSONObject rootParsedJsonObj = persist.readJSONFromFile(".fm/piechart.json");
JSONObject rootParsedJsonObj = new JSONObject(jsonString);
if (rootParsedJsonObj != null) {
JSONArray hierarchiesJsonArray = rootParsedJsonObj.getJSONObject("genrehierarchy").getJSONArray("genres");
JSONArray hierarchiesJsonArray = rootParsedJsonObj.getJSONObject("genrehierarchy")
.getJSONArray("genres");
if (hierarchiesJsonArray.length() > 0) {
if (hierarchiesJsonArray.length() > 0) {
// menuPieChart.setVisible(true);
}
}
int counter;
for (counter = 0; counter < hierarchiesJsonArray.length(); counter++) {
int counter;
for (counter = 0; counter < hierarchiesJsonArray.length(); counter++) {
JSONObject hierarchyJsonObj = (JSONObject) hierarchiesJsonArray.get(counter);
JSONObject hierarchyJsonObj = (JSONObject) hierarchiesJsonArray.get(counter);
// JSONArray hierarchyTagsJsonArray = hierarchyJsonObj.getJSONArray("tags");
// ArrayList<String> hierarchyTagNameList = new ArrayList<String>();
String hierarchyName = hierarchyJsonObj.getString("name");
JSONArray hierarchyTagsJsonArray = hierarchyJsonObj.getJSONArray("tags");
ArrayList<String> hierarchyTagNameList = new ArrayList<String>();
String hierarchyName = hierarchyJsonObj.getString("name");
JSONArray hierarchyTagsJsonArray = hierarchyJsonObj.getJSONArray("tags");
ArrayList<String> hierarchyTagNameList = new ArrayList<String>();
int i;
for (i = 0; i < hierarchyTagsJsonArray.length(); i++) {
hierarchyTagNameList.add(hierarchyTagsJsonArray.getString(i));
int i;
for (i = 0; i < hierarchyTagsJsonArray.length(); i++) {
hierarchyTagNameList.add(hierarchyTagsJsonArray.getString(i));
// allTags.add(hierarchyTagsJsonArray.getString(i));
}
choiceBox.getItems().add(new GenreHierarchy(hierarchyName, hierarchyTagNameList));
// paneList.add(new GenrePieChartTitledPane(hierarchyName, hierarchyTagNameList));
}
choiceBox.getItems().add(new GenreHierarchy(hierarchyName, hierarchyTagNameList));
// paneList.add(new GenrePieChartTitledPane(hierarchyName, hierarchyTagNameList));
}
} catch (IOException e) {
}
}
@FXML
@ -137,10 +124,12 @@ public class GenrePieChartPaneController {
@FXML
protected void handleLoadAll(ActionEvent event) {
Config config = FmFramework.getSessionConfig();
File file = null;
String path = null;
if (new File("./piechart.json").isFile()) {
file = new File("./piechart.json");
if (new File(".fm/piechart.json").isFile()) {
file = new File(".fm/piechart.json");
} else {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("open pie chart json");
@ -148,11 +137,16 @@ public class GenrePieChartPaneController {
file = fileChooser.showOpenDialog(FmFramework.getStage());
}
refreshPieCharts(file);
if (file != null) {
JSONPersister persist = new JSONPersister();
JSONObject rootParsedJsonObj = persist.readJSONFromFile(file);
refreshPieCharts(rootParsedJsonObj);
}
}
public void refreshPieCharts(File file) {
public void refreshPieCharts(JSONObject object) {
Logger.getLog().log(new LogEntry("refreshPieCharts"));
@ -163,24 +157,7 @@ public class GenrePieChartPaneController {
@Override
protected Void call() throws Exception {
String jsonString = null;
if (file != null) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String jsonLine = br.readLine();
while (jsonLine != null) {
sb.append(jsonLine);
jsonLine = br.readLine();
}
br.close();
jsonString = sb.toString();
Logger.getLog().logInfo(new InfoEntry("refreshPieCharts").addArg("json read"));
}
JSONObject rootParsedJsonObj = new JSONObject(jsonString);
JSONObject rootParsedJsonObj = object;
JSONArray hierarchiesJsonArray = rootParsedJsonObj.getJSONObject("genrehierarchy")
.getJSONArray("genres");

View File

@ -13,6 +13,7 @@ import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.stage.FileChooser;
import sarsoo.fmframework.config.Config;
import sarsoo.fmframework.config.VariableEvent;
import sarsoo.fmframework.config.VariableListener;
import sarsoo.fmframework.file.ListPersister;
@ -49,6 +50,21 @@ public class RootController {
@FXML
public void initialize() {
Logger.setLog(new Log(TextAreaConsole.getInstance(), false));
Config config = FmFramework.getSessionConfig();
if(config.getVariable("api_key") == null) {
while(config.getVariable("api_key") == null) {
setApiKey();
}
}
if(config.getVariable("username") == null) {
while(config.getVariable("username") == null) {
changeUsername();
}
}
FmFramework.getSessionConfig().getVariable("username").addListener(new VariableListener() {
@Override
@ -177,6 +193,10 @@ public class RootController {
@FXML
protected void handleChangeUsername(ActionEvent event) throws IOException {
changeUsername();
}
public void changeUsername() {
Service<Void> service = new Service<Void>() {
@Override
protected Task<Void> createTask() {
@ -197,6 +217,27 @@ public class RootController {
service.start();
}
public void setApiKey() {
Service<Void> service = new Service<Void>() {
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
String apiKey = JOptionPane.showInputDialog("enter api key:");
if (apiKey != null) {
FmFramework.getSessionConfig().getVariable("api_key").setValue(apiKey);
}
return null;
}
};
}
};
service.start();
}
@FXML
protected void handleLookupAlbum(ActionEvent event) throws IOException {
Service<Void> service = new Service<Void>() {

View File

@ -12,7 +12,6 @@ import sarsoo.fmframework.config.Config;
import sarsoo.fmframework.fm.FmUserNetwork;
import sarsoo.fmframework.fx.FmFramework;
import sarsoo.fmframework.music.Album;
import sarsoo.fmframework.net.Key;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.*;

View File

@ -20,7 +20,6 @@ public class GetLastTrackService extends Service<Track> {
Config config = FmFramework.getSessionConfig();
System.out.println(config.getValue("api_key") + config.getValue("username"));
FmUserNetwork net = new FmUserNetwork(config.getValue("api_key"), config.getValue("username"));
return net.getLastTrack();

View File

@ -0,0 +1,52 @@
package sarsoo.fmframework.fx.service;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import sarsoo.fmframework.config.Config;
import sarsoo.fmframework.config.ConfigPersister;
import sarsoo.fmframework.fm.FmUserNetwork;
import sarsoo.fmframework.fx.FmFramework;
import sarsoo.fmframework.log.Logger;
import sarsoo.fmframework.log.entry.ErrorEntry;
import sarsoo.fmframework.log.entry.LogEntry;
public class SaveConfigService extends Service<Integer> {
protected Config config;
protected String path;
public SaveConfigService(String path, Config config) {
this.path = path;
this.config = config;
}
@Override
protected Task<Integer> createTask() {
return new Task<Integer>() {
@Override
protected Integer call() throws Exception {
ConfigPersister persister = new ConfigPersister();
while(!this.isCancelled()) {
persister.saveConfig(path, config);
Logger.getLog().log(new LogEntry("save config").addArg("config saved"));
Thread.sleep(60000);
}
return 0;
}
@Override
protected void failed() {
super.failed();
Logger.getLog().logError(new ErrorEntry("failed to save config"));
}
};
}
}

View File

@ -15,15 +15,4 @@
-fx-font-size: 200%;
}
.wikiTextArea{
}
.stats{
}

View File

@ -86,7 +86,7 @@
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<TextArea fx:id="textAreaWiki" editable="false" layoutX="37.0" layoutY="34.0" prefHeight="285.0" prefWidth="296.0" styleClass="wikiTextArea" wrapText="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
<TextArea fx:id="textAreaWiki" editable="false" layoutX="37.0" layoutY="34.0" prefHeight="285.0" prefWidth="296.0" wrapText="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
</items>

View File

@ -0,0 +1,33 @@
package sarsoo.fmframework.config;
import static org.junit.Assert.*;
import org.junit.Test;
public class ConfigPersisterTest {
@Test
public void testWrite() {
Config config = new Config();
config.addVariable(new ConfigVariable("test", "test1"));
ConfigPersister persister = new ConfigPersister();
persister.saveConfig(".fm/config.json", config);
assertTrue(true);
}
@Test
public void testRead() {
ConfigPersister persister = new ConfigPersister();
Config config = persister.readConfig(".fm/config.json");
System.out.println(config);
assertTrue(true);
}
}