save&load are now in the main class

This commit is contained in:
Jannik 2018-05-17 18:58:54 +02:00
parent 1fca1c551d
commit 031046643c
3 changed files with 170 additions and 161 deletions

View File

@ -21,15 +21,25 @@
*/ */
package kellerkinder.HomeFlix.application; package kellerkinder.HomeFlix.application;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Locale; import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.kellerkinder.Alerts.JFX2BtnCancelAlert; import org.kellerkinder.Alerts.JFX2BtnCancelAlert;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonObject;
import javafx.application.Application; import javafx.application.Application;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
import javafx.event.EventHandler; import javafx.event.EventHandler;
@ -56,11 +66,12 @@ public class Main extends Application {
private static String javaVend = System.getProperty("java.vendor"); private static String javaVend = System.getProperty("java.vendor");
private static String local = System.getProperty("user.language") + "_" + System.getProperty("user.country"); private static String local = System.getProperty("user.language") + "_" + System.getProperty("user.country");
private static String dirHomeFlix; private static String dirHomeFlix;
private File directory; private static File directory;
private File configFile; private static File configFile;
private File posterCache; private static File posterCache;
private ResourceBundle bundle; private ResourceBundle bundle;
private static Logger LOGGER; private static Logger LOGGER;
private Properties props = new Properties();
@Override @Override
public void start(Stage primaryStage) throws IOException { public void start(Stage primaryStage) throws IOException {
@ -69,6 +80,8 @@ public class Main extends Application {
LOGGER.info("User: " + userName + " " + userHome); LOGGER.info("User: " + userName + " " + userHome);
this.primaryStage = primaryStage; this.primaryStage = primaryStage;
mainWindowController = new MainWindowController(this);
mainWindow(); mainWindow();
} }
@ -80,6 +93,7 @@ public class Main extends Application {
try { try {
FXMLLoader loader = new FXMLLoader(); FXMLLoader loader = new FXMLLoader();
loader.setLocation(ClassLoader.getSystemResource("fxml/MainWindow.fxml")); loader.setLocation(ClassLoader.getSystemResource("fxml/MainWindow.fxml"));
loader.setController(mainWindowController);
pane = (AnchorPane) loader.load(); pane = (AnchorPane) loader.load();
primaryStage.setMinHeight(600.00); primaryStage.setMinHeight(600.00);
primaryStage.setMinWidth(1000.00); primaryStage.setMinWidth(1000.00);
@ -87,21 +101,14 @@ public class Main extends Application {
primaryStage.setTitle("Project HomeFlix"); primaryStage.setTitle("Project HomeFlix");
primaryStage.getIcons().add(new Image(Main.class.getResourceAsStream("/icons/Homeflix_Icon_64x64.png"))); //adds application icon primaryStage.getIcons().add(new Image(Main.class.getResourceAsStream("/icons/Homeflix_Icon_64x64.png"))); //adds application icon
primaryStage.setOnCloseRequest(event -> System.exit(1)); primaryStage.setOnCloseRequest(event -> System.exit(1));
mainWindowController = loader.getController(); //Link of FXMLController and controller class
mainWindowController.setMain(this); //call setMain
directory = new File(dirHomeFlix);
configFile = new File(dirHomeFlix + "/config.xml");
posterCache = new File(dirHomeFlix + "/posterCache");
// generate window // generate window
scene = new Scene(pane); // create new scene, append pane to scene scene = new Scene(pane); // create new scene, append pane to scene
scene.getStylesheets().add(getClass().getResource("/css/MainWindow.css").toExternalForm()); scene.getStylesheets().add(getClass().getResource("/css/MainWindow.css").toExternalForm());
primaryStage.setScene(scene); // append scene to stage primaryStage.setScene(scene); // append scene to stage
primaryStage.show(); // show stage primaryStage.show(); // show stage
// startup checks // startup checks TODO move to mwc
if (!configFile.exists()) { if (!configFile.exists()) {
directory.mkdir(); directory.mkdir();
@ -110,21 +117,41 @@ public class Main extends Application {
mainWindowController.setFontSize(17.0); mainWindowController.setFontSize(17.0);
mainWindowController.setAutoUpdate(false); mainWindowController.setAutoUpdate(false);
mainWindowController.setLocal(local); mainWindowController.setLocal(local);
mainWindowController.saveSettings(); saveSettings();
} }
if (!posterCache.exists()) { if (!posterCache.exists()) {
posterCache.mkdir(); posterCache.mkdir();
} }
// initialize here as it loads the games to the mwc and the GUI, therefore the window must exist
mainWindowController.init();
mainWindowController.getDbController().init();
} catch (IOException e) { } catch (IOException e) {
LOGGER.error(e); LOGGER.error(e);
} }
} }
/**
* set the log file location and initialize the logger launch the GUI
* @param args arguments given at the start
*/
public static void main(String[] args) {
if (osName.contains("Windows")) {
dirHomeFlix = userHome + "/Documents/HomeFlix";
} else {
dirHomeFlix = userHome + "/HomeFlix";
}
// set the concrete files
directory = new File(dirHomeFlix);
configFile = new File(dirHomeFlix + "/config.xml");
posterCache = new File(dirHomeFlix + "/posterCache");
System.setProperty("logFilename", dirHomeFlix + "/app.log");
File logFile = new File(dirHomeFlix + "/app.log");
logFile.delete();
LOGGER = LogManager.getLogger(Main.class.getName());
launch(args);
}
/** /**
* we need to get the path for the first source from the user and add it to * we need to get the path for the first source from the user and add it to
* sources.json, if the user ends the file-/directory-chooser the program will exit * sources.json, if the user ends the file-/directory-chooser the program will exit
@ -187,23 +214,101 @@ public class Main extends Application {
} }
/** /**
* set the log file location and initialize the logger launch the GUI * save the configuration to the config.xml file
* @param args arguments given at the start
*/ */
public static void main(String[] args) { public void saveSettings() {
LOGGER.info("saving settings ...");
try {
props.setProperty("color", mainWindowController.getColor());
props.setProperty("autoUpdate", String.valueOf(mainWindowController.isAutoUpdate()));
props.setProperty("useBeta", String.valueOf(mainWindowController.isUseBeta()));
props.setProperty("autoplay", String.valueOf(mainWindowController.isAutoplay()));
props.setProperty("size", mainWindowController.getFontSize().toString());
props.setProperty("local", mainWindowController.getLocal());
if (osName.contains("Windows")) { OutputStream outputStream = new FileOutputStream(getConfigFile()); // new output-stream
dirHomeFlix = userHome + "/Documents/HomeFlix"; props.storeToXML(outputStream, "Project HomeFlix settings"); // write new .xml
} else { outputStream.close();
dirHomeFlix = userHome + "/HomeFlix"; } catch (IOException e) {
LOGGER.error("An error occurred while saving the settings!", e);
} }
System.setProperty("logFilename", dirHomeFlix + "/app.log");
File logFile = new File(dirHomeFlix + "/app.log");
logFile.delete();
LOGGER = LogManager.getLogger(Main.class.getName());
launch(args);
} }
/**
* load the configuration from the config.xml file
* and try to load the API keys from apiKeys.json
*/
public void loadSettings() {
LOGGER.info("loading settings ...");
try {
InputStream inputStream = new FileInputStream(getConfigFile());
props.loadFromXML(inputStream); // new input-stream from .xml
try {
mainWindowController.setColor(props.getProperty("color"));
} catch (Exception e) {
LOGGER.error("cloud not load color", e);
mainWindowController.setColor("00a8cc");
}
try {
mainWindowController.setFontSize(Double.parseDouble(props.getProperty("size")));
} catch (Exception e) {
LOGGER.error("cloud not load fontsize", e);
mainWindowController.setFontSize(17.0);
}
try {
mainWindowController.setAutoUpdate(Boolean.parseBoolean(props.getProperty("autoUpdate")));
} catch (Exception e) {
LOGGER.error("cloud not load autoUpdate", e);
mainWindowController.setAutoUpdate(false);
}
try {
mainWindowController.setUseBeta(Boolean.parseBoolean(props.getProperty("useBeta")));
} catch (Exception e) {
LOGGER.error("cloud not load autoUpdate", e);
mainWindowController.setUseBeta(false);
}
try {
mainWindowController.setAutoplay(Boolean.parseBoolean(props.getProperty("autoplay")));
} catch (Exception e) {
LOGGER.error("cloud not load autoplay", e);
mainWindowController.setAutoplay(false);
}
try {
mainWindowController.setLocal(props.getProperty("local"));
} catch (Exception e) {
LOGGER.error("cloud not load local", e);
mainWindowController.setLocal(System.getProperty("user.language") + "_" + System.getProperty("user.country"));
}
inputStream.close();
} catch (IOException e) {
LOGGER.error("An error occurred while loading the settings!", e);
}
// try loading the omdbAPI key
try {
InputStream in = getClass().getClassLoader().getResourceAsStream("apiKeys.json");
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
JsonObject apiKeys = Json.parse(reader).asObject();
mainWindowController.setOmdbAPIKey(apiKeys.getString("omdbAPIKey", ""));
reader.close();
in.close();
} else {
LOGGER.warn("Cloud not load apiKeys.json. No such file");
}
} catch (Exception e) {
LOGGER.error("Cloud not load the omdbAPI key. Please contact the developer!", e);
}
}
public Stage getPrimaryStage() { public Stage getPrimaryStage() {
return primaryStage; return primaryStage;

View File

@ -24,19 +24,14 @@ package kellerkinder.HomeFlix.application;
import java.awt.Desktop; import java.awt.Desktop;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader; import java.io.FileReader;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer; import java.io.Writer;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.Locale; import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -239,27 +234,29 @@ public class MainWindowController {
private MenuItem like = new MenuItem("like"); private MenuItem like = new MenuItem("like");
private MenuItem dislike = new MenuItem("dislike"); // TODO one option (like or dislike) private MenuItem dislike = new MenuItem("dislike"); // TODO one option (like or dislike)
private ContextMenu menu = new ContextMenu(like, dislike); private ContextMenu menu = new ContextMenu(like, dislike);
private Properties props = new Properties();
/** /**
* "Main" Method called in Main.java main() when starting
* Initialize other objects: Updater, dbController and ApiQuery * Initialize other objects: Updater, dbController and ApiQuery
* @param main the main object
*/ */
void setMain(Main main) { public MainWindowController(Main main) {
this.main = main; this.main = main;
mainWindowController = this; mainWindowController = this;
dbController = new DBController(this.main, this); dbController = new DBController(this.main, this);
omdbAPIController = new OMDbAPIController(this, dbController, this.main); omdbAPIController = new OMDbAPIController(this, dbController, this.main);
} }
// call all initialize methods @FXML
void init() { public void initialize() {
LOGGER.info("Initializing Project-HomeFlix build " + buildNumber); LOGGER.info("Initializing Project-HomeFlix build " + buildNumber);
loadSettings(); main.loadSettings(); // load settings
checkAutoUpdate(); checkAutoUpdate();
// initialize the GUI and the DBController
initTabel(); initTabel();
initUI(); initUI();
initActions(); initActions();
dbController.init();
} }
// Initialize UI elements // Initialize UI elements
@ -328,20 +325,21 @@ public class MainWindowController {
HamburgerBackArrowBasicTransition burgerTask = new HamburgerBackArrowBasicTransition(menuHam); HamburgerBackArrowBasicTransition burgerTask = new HamburgerBackArrowBasicTransition(menuHam);
menuHam.addEventHandler(MouseEvent.MOUSE_PRESSED, (e) -> { menuHam.addEventHandler(MouseEvent.MOUSE_PRESSED, (e) -> {
if (menuTrue == false) { if (menuTrue) {
sideMenuSlideIn();
burgerTask.setRate(1.0);
burgerTask.play();
menuTrue = true;
} else {
sideMenuSlideOut(); sideMenuSlideOut();
burgerTask.setRate(-1.0); burgerTask.setRate(-1.0);
burgerTask.play(); burgerTask.play();
menuTrue = false; menuTrue = false;
} else {
sideMenuSlideIn();
burgerTask.setRate(1.0);
burgerTask.play();
menuTrue = true;
} }
if (settingsTrue == true) { if (settingsTrue) {
settingsScrollPane.setVisible(false); settingsScrollPane.setVisible(false);
saveSettings(); main.saveSettings();
settingsTrue = false; settingsTrue = false;
} }
}); });
@ -351,11 +349,10 @@ public class MainWindowController {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
ObservableList<FilmTabelDataType> helpData; ObservableList<FilmTabelDataType> helpData;
filterData.clear(); filterData.clear();
filmRoot.getChildren().removeAll(filmRoot.getChildren()); filmRoot.getChildren().clear();
helpData = filmsList; helpData = filmsList;
for (int i = 0; i < helpData.size(); i++) { for (int i = 0; i < helpData.size(); i++) {
if (helpData.get(i).getTitle().toLowerCase().contains(searchTextField.getText().toLowerCase())) { if (helpData.get(i).getTitle().toLowerCase().contains(searchTextField.getText().toLowerCase())) {
filterData.add(helpData.get(i)); // add data from newDaten to filteredData where title contains search input filterData.add(helpData.get(i)); // add data from newDaten to filteredData where title contains search input
@ -379,7 +376,7 @@ public class MainWindowController {
local = local.substring(local.length() - 6, local.length() - 1); // reading only en_US from English (en_US) local = local.substring(local.length() - 6, local.length() - 1); // reading only en_US from English (en_US)
setLocal(local); setLocal(local);
setLocalUI(); setLocalUI();
saveSettings(); main.saveSettings();
} }
}); });
@ -391,7 +388,7 @@ public class MainWindowController {
} else { } else {
setUseBeta(false); setUseBeta(false);
} }
saveSettings(); main.saveSettings();
} }
}); });
@ -402,7 +399,7 @@ public class MainWindowController {
if (!getCurrentTitle().isEmpty()) { if (!getCurrentTitle().isEmpty()) {
dbController.readCache(getCurrentStreamUrl()); dbController.readCache(getCurrentStreamUrl());
} }
saveSettings(); main.saveSettings();
} }
}); });
@ -568,14 +565,14 @@ public class MainWindowController {
} }
@FXML @FXML
private void settingsBtnclicked(){ private void settingsBtnclicked() {
if(settingsTrue == false){ if (settingsTrue) {
settingsScrollPane.setVisible(true);
settingsTrue = true;
}else{
settingsScrollPane.setVisible(false); settingsScrollPane.setVisible(false);
saveSettings(); main.saveSettings();
settingsTrue = false; settingsTrue = false;
} else {
settingsScrollPane.setVisible(true);
settingsTrue = true;
} }
} }
@ -607,7 +604,7 @@ public class MainWindowController {
@FXML @FXML
private void colorPickerAction() { private void colorPickerAction() {
setColor(colorPicker.getValue().toString().substring(2, 10)); setColor(colorPicker.getValue().toString().substring(2, 10));
saveSettings(); main.saveSettings();
applyColor(); applyColor();
} }
@ -622,13 +619,13 @@ public class MainWindowController {
@FXML @FXML
private void autoUpdateToggleBtnAction(){ private void autoUpdateToggleBtnAction(){
autoUpdate = isAutoUpdate() ? false : true; autoUpdate = isAutoUpdate() ? false : true;
saveSettings(); main.saveSettings();
} }
@FXML @FXML
private void autoplayToggleBtnAction(){ private void autoplayToggleBtnAction(){
autoplay = isAutoplay() ? false : true; autoplay = isAutoplay() ? false : true;
saveSettings(); main.saveSettings();
} }
// refresh the selected child of the root node // refresh the selected child of the root node
@ -806,103 +803,6 @@ public class MainWindowController {
columnFavorite.setText(getBundle().getString("columnFavorite")); columnFavorite.setText(getBundle().getString("columnFavorite"));
} }
/**
* save the configuration to the config.xml file
*/
public void saveSettings() {
LOGGER.info("saving settings ...");
try {
props.setProperty("color", getColor());
props.setProperty("autoUpdate", String.valueOf(isAutoUpdate()));
props.setProperty("useBeta", String.valueOf(isUseBeta()));
props.setProperty("autoplay", String.valueOf(isAutoplay()));
props.setProperty("size", getFontSize().toString());
props.setProperty("local", getLocal());
props.setProperty("ratingSortType", columnFavorite.getSortType().toString());
OutputStream outputStream = new FileOutputStream(main.getConfigFile()); // new output-stream
props.storeToXML(outputStream, "Project HomeFlix settings"); // write new .xml
outputStream.close();
} catch (IOException e) {
LOGGER.error("An error occurred while saving the settings!", e);
}
}
/**
* load the configuration from the config.xml file
* and try to load the API keys from apiKeys.json
*/
public void loadSettings() {
LOGGER.info("loading settings ...");
try {
InputStream inputStream = new FileInputStream(main.getConfigFile());
props.loadFromXML(inputStream); // new input-stream from .xml
try {
setColor(props.getProperty("color"));
} catch (Exception e) {
LOGGER.error("cloud not load color", e);
setColor("00a8cc");
}
try {
setFontSize(Double.parseDouble(props.getProperty("size")));
} catch (Exception e) {
LOGGER.error("cloud not load fontsize", e);
setFontSize(17.0);
}
try {
setAutoUpdate(Boolean.parseBoolean(props.getProperty("autoUpdate")));
} catch (Exception e) {
LOGGER.error("cloud not load autoUpdate", e);
setAutoUpdate(false);
}
try {
setUseBeta(Boolean.parseBoolean(props.getProperty("useBeta")));
} catch (Exception e) {
LOGGER.error("cloud not load autoUpdate", e);
setUseBeta(false);
}
try {
setAutoplay(Boolean.parseBoolean(props.getProperty("autoplay")));
} catch (Exception e) {
LOGGER.error("cloud not load autoplay", e);
setAutoplay(false);
}
try {
setLocal(props.getProperty("local"));
} catch (Exception e) {
LOGGER.error("cloud not load local", e);
setLocal(System.getProperty("user.language") + "_" + System.getProperty("user.country"));
}
inputStream.close();
} catch (IOException e) {
LOGGER.error("An error occurred while loading the settings!", e);
}
// try loading the omdbAPI key
try {
InputStream in = getClass().getClassLoader().getResourceAsStream("apiKeys.json");
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
JsonObject apiKeys = Json.parse(reader).asObject();
omdbAPIKey = apiKeys.getString("omdbAPIKey", "");
reader.close();
in.close();
} else {
LOGGER.warn("Cloud not load apiKeys.json. No such file");
}
} catch (Exception e) {
LOGGER.error("Cloud not load the omdbAPI key. Please contact the developer!", e);
}
}
// if AutoUpdate, then check for updates // if AutoUpdate, then check for updates
private void checkAutoUpdate() { private void checkAutoUpdate() {
@ -1008,6 +908,10 @@ public class MainWindowController {
public String getOmdbAPIKey() { public String getOmdbAPIKey() {
return omdbAPIKey; return omdbAPIKey;
} }
public void setOmdbAPIKey(String omdbAPIKey) {
this.omdbAPIKey = omdbAPIKey;
}
public ObservableList<FilmTabelDataType> getFilmsList() { public ObservableList<FilmTabelDataType> getFilmsList() {
return filmsList; return filmsList;

View File

@ -22,7 +22,7 @@
<?import javafx.scene.text.Font?> <?import javafx.scene.text.Font?>
<?import javafx.scene.text.TextFlow?> <?import javafx.scene.text.TextFlow?>
<AnchorPane fx:id="mainAnchorPane" prefHeight="600.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="kellerkinder.HomeFlix.application.MainWindowController"> <AnchorPane fx:id="mainAnchorPane" prefHeight="600.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/9" xmlns:fx="http://javafx.com/fxml/1">
<children> <children>
<AnchorPane fx:id="tableModeAnchorPane" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="32.0"> <AnchorPane fx:id="tableModeAnchorPane" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="32.0">
<children> <children>