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 fmframework/src/sarsoo/fmframework/net/Key.java
.fm
# Directories # # Directories #
/build/ /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

@ -39,7 +39,7 @@ public class Config {
public ConfigVariable getVariable(String key) { public ConfigVariable getVariable(String key) {
for (ConfigVariable i : variables) { for (ConfigVariable i : variables) {
if (i.getKey() == key) { if (i.getKey().equalsIgnoreCase(key)) {
return i; return i;
} }
} }
@ -47,6 +47,10 @@ public class Config {
return null; return null;
} }
public List<ConfigVariable> getVariables() {
return variables;
}
public String getValue(String key) { public String getValue(String key) {
ConfigVariable variable = getVariable(key); ConfigVariable variable = getVariable(key);
@ -57,4 +61,14 @@ public class Config {
return null; 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 key;
protected String value; protected String value;
protected boolean temporary;
protected List<VariableListener> listeners; protected List<VariableListener> listeners;
public ConfigVariable(String key, String value) { public ConfigVariable(String key, String value) {
this.key = key; this.key = key;
this.value = value; 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>(); this.listeners = new ArrayList<VariableListener>();
} }
@ -25,6 +36,14 @@ public class ConfigVariable {
return value; return value;
} }
public boolean isTemporary() {
return temporary;
}
public void setTemporary(boolean temporary) {
this.temporary = temporary;
}
public void setValue(String value) { public void setValue(String value) {
this.value = 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; package sarsoo.fmframework.fx;
import java.io.File;
import javafx.application.Application; import javafx.application.Application;
import javafx.fxml.FXMLLoader; import javafx.fxml.FXMLLoader;
import javafx.scene.Parent; import javafx.scene.Parent;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.stage.Stage; import javafx.stage.Stage;
import sarsoo.fmframework.config.Config; import sarsoo.fmframework.config.Config;
import sarsoo.fmframework.config.ConfigVariable; import sarsoo.fmframework.config.ConfigPersister;
import sarsoo.fmframework.fx.controller.RootController; 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 { public class FmFramework extends Application {
@ -23,10 +27,7 @@ public class FmFramework extends Application {
public void start(Stage stage) throws Exception { public void start(Stage stage) throws Exception {
FmFramework.stage = stage; FmFramework.stage = stage;
config = new Config(); initConfig();
config.addVariable(new ConfigVariable("username", "sarsoo"));
config.addVariable(new ConfigVariable("api_key", Key.getKey()));
FXMLLoader loader = new FXMLLoader(getClass().getResource("ui/RootPane.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("ui/RootPane.fxml"));
@ -38,7 +39,6 @@ public class FmFramework extends Application {
rootScene = scene; rootScene = scene;
// scene.getStylesheets().add("styles/style.css"); // scene.getStylesheets().add("styles/style.css");
control = (RootController) loader.getController(); control = (RootController) loader.getController();
// (new Thread(new TagCaller())).start(); // (new Thread(new TagCaller())).start();
stage.setMinHeight(800); stage.setMinHeight(800);
@ -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() { public static Config getSessionConfig() {
return config; return config;
} }
public static void main(String[] args) { public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(
new Thread(() -> (new ConfigPersister()).saveConfig(".fm/", config)));
launch(args); launch(args);
} }
// public void changeScene() throws IOException {
// Parent root = FXMLLoader.load(getClass().getResource("ui/changed.fxml"));
//
// }
public static RootController getController() { public static RootController getController() {
return control; return control;
} }

View File

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

View File

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

View File

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

View File

@ -13,6 +13,7 @@ import javafx.event.ActionEvent;
import javafx.event.EventHandler; import javafx.event.EventHandler;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.stage.FileChooser; import javafx.stage.FileChooser;
import sarsoo.fmframework.config.Config;
import sarsoo.fmframework.config.VariableEvent; import sarsoo.fmframework.config.VariableEvent;
import sarsoo.fmframework.config.VariableListener; import sarsoo.fmframework.config.VariableListener;
import sarsoo.fmframework.file.ListPersister; import sarsoo.fmframework.file.ListPersister;
@ -49,6 +50,21 @@ public class RootController {
@FXML @FXML
public void initialize() { public void initialize() {
Logger.setLog(new Log(TextAreaConsole.getInstance(), false)); 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() { FmFramework.getSessionConfig().getVariable("username").addListener(new VariableListener() {
@Override @Override
@ -177,6 +193,10 @@ public class RootController {
@FXML @FXML
protected void handleChangeUsername(ActionEvent event) throws IOException { protected void handleChangeUsername(ActionEvent event) throws IOException {
changeUsername();
}
public void changeUsername() {
Service<Void> service = new Service<Void>() { Service<Void> service = new Service<Void>() {
@Override @Override
protected Task<Void> createTask() { protected Task<Void> createTask() {
@ -197,6 +217,27 @@ public class RootController {
service.start(); 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 @FXML
protected void handleLookupAlbum(ActionEvent event) throws IOException { protected void handleLookupAlbum(ActionEvent event) throws IOException {
Service<Void> service = new Service<Void>() { 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.fm.FmUserNetwork;
import sarsoo.fmframework.fx.FmFramework; import sarsoo.fmframework.fx.FmFramework;
import sarsoo.fmframework.music.Album; import sarsoo.fmframework.music.Album;
import sarsoo.fmframework.net.Key;
import javafx.scene.chart.BarChart; import javafx.scene.chart.BarChart;
import javafx.scene.chart.XYChart; import javafx.scene.chart.XYChart;
import javafx.scene.control.*; import javafx.scene.control.*;

View File

@ -20,7 +20,6 @@ public class GetLastTrackService extends Service<Track> {
Config config = FmFramework.getSessionConfig(); 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")); FmUserNetwork net = new FmUserNetwork(config.getValue("api_key"), config.getValue("username"));
return net.getLastTrack(); 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%; -fx-font-size: 200%;
}
.wikiTextArea{
}
.stats{
} }

View File

@ -86,7 +86,7 @@
</AnchorPane> </AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0"> <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children> <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> </children>
</AnchorPane> </AnchorPane>
</items> </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);
}
}