uk.co.everywheremusic.viewcontroller.SetupScene.java Source code

Java tutorial

Introduction

Here is the source code for uk.co.everywheremusic.viewcontroller.SetupScene.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.co.everywheremusic.viewcontroller;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import uk.co.everywheremusic.model.DBManager;
import uk.co.everywheremusic.model.LibraryManager;
import uk.co.everywheremusic.model.SongBean;
import uk.co.everywheremusic.model.SongDAO;
import uk.co.everywheremusic.model.Globals;
import uk.co.everywheremusic.model.PasswordDAO;

/**
 *
 * @author kyle
 */
public class SetupScene extends Application {

    private GridPane grid;
    private ColumnConstraints column1;
    private ColumnConstraints column2;
    private ColumnConstraints column3;
    private ColumnConstraints column4;
    private Image imgLogo;
    private Label sceneTitle;
    private Label lblFolder;
    private TextField txtFolder;
    private Button btnFolder;
    private Label lblPassword;
    private PasswordField txtPassword;
    private Label lblConfirmPassword;
    private PasswordField txtConfirmPassword;
    private TextArea textArea;
    private Label lblProgress;
    private ProgressBar progressBar;
    private Button btnInstall;
    private Button btnDone;
    private Scene scene;

    Task setupWorker;

    private String installFolder;
    private String musicFolder;
    private String password;

    DBManager dbMan;
    SongDAO sdao;
    PasswordDAO pdao;

    @Override
    public void start(Stage primaryStage) {

        String[] config = LibraryManager.readConfigFile("." + Globals.INSTALL_EXT + Globals.SETTINGS_FILENAME);
        if (config != null) {
            new ServerScene(config[0], config[1]).showWindow(primaryStage);
        } else {
            startSetupWindow(primaryStage);
        }

    }

    private void startSetupWindow(Stage primaryStage) {
        try {
            installFolder = new File(".").getCanonicalPath() + Globals.INSTALL_EXT;
        } catch (IOException ex) {
            Logger.getLogger(SetupScene.class.getName()).log(Level.SEVERE, null, ex);
            installFolder = System.getProperty("user.dir") + Globals.INSTALL_EXT;
        }

        primaryStage.setTitle(Globals.APP_NAME);

        grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));

        column1 = new ColumnConstraints(100, 100, Double.MAX_VALUE);
        column1.setHgrow(Priority.ALWAYS);
        column2 = new ColumnConstraints(100, 100, Double.MAX_VALUE);
        column2.setHgrow(Priority.ALWAYS);
        column3 = new ColumnConstraints(100, 100, Double.MAX_VALUE);
        column3.setHgrow(Priority.ALWAYS);
        column4 = new ColumnConstraints(100, 100, Double.MAX_VALUE);
        column4.setHgrow(Priority.ALWAYS);
        grid.getColumnConstraints().addAll(column1, column2, column3, column4);

        sceneTitle = new Label(Globals.SETUP_FRAME_TITLE);
        sceneTitle.setId(Globals.CSS_TITLE_ID);
        sceneTitle.setPrefWidth(Double.MAX_VALUE);
        sceneTitle.setAlignment(Pos.CENTER);

        ImageView imageView = null;
        try {

            imageView = new ImageView();
            String img = new File(Globals.IC_LOGO).toURI().toURL().toString();
            imgLogo = new Image(img);

            imageView.setImage(imgLogo);

        } catch (MalformedURLException ex) {
            Logger.getLogger(ServerScene.class.getName()).log(Level.SEVERE, null, ex);
        }

        GridPane titlePane = new GridPane();
        ColumnConstraints c1 = new ColumnConstraints(50);
        ColumnConstraints c2 = new ColumnConstraints(400);
        titlePane.getColumnConstraints().addAll(c1, c2);
        titlePane.add(imageView, 0, 0);
        titlePane.add(sceneTitle, 1, 0);
        titlePane.setAlignment(Pos.CENTER);
        grid.add(titlePane, 0, 0, 4, 1);

        lblFolder = new Label(Globals.SETUP_LBL_MUSIC_FOLDER);
        grid.add(lblFolder, 0, 2, 3, 1);

        txtFolder = new TextField();
        txtFolder.setText("/home/kyle/Music/Test music");
        grid.add(txtFolder, 0, 3, 3, 1);

        btnFolder = new Button(Globals.SETUP_BTN_MUSIC_FOLDER);
        btnFolder.setPrefWidth(Double.MAX_VALUE);
        grid.add(btnFolder, 3, 3);

        final DirectoryChooser dirChooser = new DirectoryChooser();

        btnFolder.setOnAction((ActionEvent event) -> {
            File dir = dirChooser.showDialog(primaryStage);
            if (dir != null) {
                txtFolder.setText(dir.getAbsolutePath());
            }
        });

        lblPassword = new Label("Choose a password:");
        grid.add(lblPassword, 0, 4, 2, 1);

        lblConfirmPassword = new Label("Confirm your password:");
        grid.add(lblConfirmPassword, 2, 4, 2, 1);

        txtPassword = new PasswordField();
        grid.add(txtPassword, 0, 5, 2, 1);

        txtConfirmPassword = new PasswordField();
        grid.add(txtConfirmPassword, 2, 5, 1, 1);

        textArea = new TextArea();
        textArea.setPrefHeight(Double.MAX_VALUE);
        textArea.setDisable(true);
        textArea.setWrapText(true);
        grid.add(textArea, 0, 7, 4, 2);

        StackPane progressPane = new StackPane();
        lblProgress = new Label(Globals.SETUP_LBL_PERCENT);
        lblProgress.setId(Globals.CSS_PROGBAR_LBL_ID);
        lblProgress.setVisible(false);
        progressBar = new ProgressBar(0);
        progressBar.setPrefWidth(Double.MAX_VALUE);
        progressBar.setVisible(false);
        progressPane.getChildren().addAll(progressBar, lblProgress);
        progressPane.setAlignment(Pos.CENTER_RIGHT);
        grid.add(progressPane, 0, 11, 3, 1);

        StackPane buttonPane = new StackPane();
        btnInstall = new Button(Globals.SETUP_BTN_INSTALL);
        btnInstall.setPrefWidth(Double.MAX_VALUE);
        btnDone = new Button(Globals.SETUP_BTN_DONE);
        btnDone.setPrefWidth(Double.MAX_VALUE);
        btnDone.setVisible(false);
        buttonPane.getChildren().addAll(btnInstall, btnDone);
        grid.add(buttonPane, 3, 11);

        btnInstall.setOnAction((ActionEvent event) -> {

            boolean valid = validateForm();
            if (valid) {

                lblFolder.setDisable(true);
                txtFolder.setDisable(true);
                btnFolder.setDisable(true);
                lblPassword.setDisable(true);
                txtPassword.setDisable(true);
                lblConfirmPassword.setDisable(true);
                txtConfirmPassword.setDisable(true);

                textArea.setDisable(false);
                lblProgress.setVisible(true);
                progressBar.setVisible(true);
                btnInstall.setDisable(true);

                musicFolder = txtFolder.getText();
                password = txtPassword.getText();

                setupWorker = createSetupWorker();
                progressBar.progressProperty().unbind();
                progressBar.progressProperty().bind(setupWorker.progressProperty());

                setupWorker.messageProperty().addListener(
                        (ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
                            String[] values = newValue.split("\\|");
                            lblProgress.setText(values[0] + "%");
                            textArea.appendText(values[1] + "\n");

                            if (values[1].equals(Globals.SETUP_MSG_DONE)) {
                                btnInstall.setVisible(false);
                                btnDone.setVisible(true);
                            }

                        });

                new Thread(setupWorker).start();

            }
        });

        btnDone.setOnAction((ActionEvent event) -> {
            primaryStage.hide();
            new ServerScene(installFolder, musicFolder).showWindow(new Stage());
        });

        try {
            String imgUrl = new File(Globals.IC_LOGO).toURI().toURL().toString();
            javafx.scene.image.Image i = new javafx.scene.image.Image(imgUrl);
            primaryStage.getIcons().add(i);
        } catch (MalformedURLException ex) {
            Logger.getLogger(ServerScene.class.getName()).log(Level.SEVERE, null, ex);
        }

        scene = new Scene(grid, 600, 400);
        primaryStage.setScene(scene);

        scene.getStylesheets().add(SetupScene.class.getResource(Globals.CSS_FILE).toExternalForm());
        //  grid.setGridLinesVisible(true);
        primaryStage.show();
    }

    private boolean validateForm() {

        boolean valid = true;
        String errorMessage = "";

        File musicDir = new File(txtFolder.getText());
        if (!musicDir.isDirectory()) {
            valid = false;
            errorMessage += Globals.SETUP_ERR_INVALID_FOLDER + "\n\n";
        }

        String password = txtPassword.getText();
        String confirmPassword = txtConfirmPassword.getText();
        if (!password.equals(confirmPassword)) {
            valid = false;
            errorMessage += "Passwords do not match\n\n";
        }

        if (password.equals("")) {
            valid = false;
            errorMessage += "Enter a password\n\n";
        }

        if (!valid) {
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle(Globals.SETUP_ALERT_TITLE);
            alert.setHeaderText(Globals.SETUP_ALERT_HEADER_TEXT);

            TextArea text = new TextArea(errorMessage);
            text.setEditable(false);
            text.setWrapText(true);
            GridPane.setVgrow(text, Priority.NEVER);
            GridPane.setHgrow(text, Priority.NEVER);

            GridPane content = new GridPane();
            content.setMaxWidth(Double.MAX_VALUE);
            content.add(text, 0, 0);

            alert.getDialogPane().setContent(content);
            alert.showAndWait();
        }

        return valid;

    }

    private Task createSetupWorker() {
        return new Task() {
            @Override
            protected Object call() throws Exception {

                updateMessage("0|" + Globals.SETUP_MSG_DB_CREATE);
                LibraryManager.appendLogFile(Globals.SETUP_MSG_DB_CREATE);

                LibraryManager libMan = new LibraryManager(installFolder, musicFolder);

                saveSettings();

                File path = new File(musicFolder);
                Collection<File> files = FileUtils.listFiles(path, Globals.FILE_EXTENSIONS, true);
                Object[] fileArray = files.toArray();

                dbMan = new DBManager(installFolder);
                sdao = dbMan.getSongDAO();
                pdao = dbMan.getPasswordDAO();
                dbMan.wipeDatabase();

                pdao.insertPassword(password);

                files = FileUtils.listFiles(path, Globals.FILE_EXTENSIONS, true);
                fileArray = files.toArray();

                // process files
                for (Integer i = 0; i < fileArray.length; i++) {

                    File tempFile = (File) fileArray[i];

                    if (!tempFile.isDirectory()) {

                        String[] metaData = libMan.readID3(tempFile);

                        if (metaData != null) {

                            if ((metaData[1] != null && !metaData[1].equals(""))
                                    && (metaData[3] != null && !metaData[3].equals(""))) {

                                Float percent = new Float(0);
                                float total = fileArray.length;
                                float number = i + 1;
                                float div = (number / total);
                                percent = div * 100;

                                updateMessage(Math.round(percent) + "|" + Globals.SETUP_MSG_PROCESSING_SONG
                                        + metaData[1] + " - " + metaData[3]);
                                LibraryManager.appendLogFile(
                                        Globals.SETUP_MSG_PROCESSING_SONG + metaData[1] + " - " + metaData[3]);
                                updateProgress(i + 1, fileArray.length);

                            }

                            metaData[0] = libMan.absolutePathtoRelativePath(metaData[0]);

                            SongBean song = new SongBean(0, metaData[1], metaData[2], metaData[3], metaData[4],
                                    metaData[5], metaData[6], metaData[7], metaData[8], metaData[9], metaData[10],
                                    tempFile.getAbsolutePath(), System.currentTimeMillis());

                            sdao.insertSong(song);

                        }
                    }

                }

                updateMessage("100|" + Globals.SETUP_MSG_DONE);
                LibraryManager.appendLogFile(Globals.SETUP_MSG_DONE);

                return true;

            }
        };
    }

    private void saveSettings() {
        try {

            LibraryManager.appendLogFile(Globals.LOG_SAVING_SETTINGS);

            String data = Globals.SETTINGS_INSTALL_FOLDER + "|" + installFolder + "\n"
                    + Globals.SETTINGS_MUSIC_FOLDER + "|" + musicFolder + "\n";

            try (FileWriter fileWrite = new FileWriter(installFolder + Globals.SETTINGS_FILENAME, false)) {
                fileWrite.write(data);
                fileWrite.flush();
            }

        } catch (IOException e) {
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        System.out.println(System.currentTimeMillis());

        launch(args);

    }

}