Decoupled config stuff from LibraryUtils, now configuring hibernate with database directory that can be changed during runtime.

This commit is contained in:
neviyn 2016-02-26 15:43:21 +00:00
parent ecc789a556
commit 4e668954a9
8 changed files with 85 additions and 84 deletions

View File

@ -0,0 +1,63 @@
package musicplayer;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
public final class ConfigManager {
static final String settingsFilename = "settings.cfg";
static final File propertiesFile = new File(settingsFilename);
static final Properties librarySettings = new Properties();
// Config Keys
static final String foldersKey = "libraryFolders";
static final String databaseKey = "databaseDir";
public static List<File> getLibraryDirectories(){
try(FileInputStream inputStream = new FileInputStream(propertiesFile)){
librarySettings.load(inputStream);
if(librarySettings.containsKey(foldersKey)){
return Arrays.asList(librarySettings.getProperty(foldersKey).split(","))
.stream().map(File::new).filter(File::exists).collect(Collectors.toList());
}
} catch (IOException ex) {
propertiesFile.getParentFile().mkdirs();
try {
propertiesFile.createNewFile();
} catch (IOException ignored) {}
}
return new ArrayList<>();
}
public static void saveLibraryDirectories(List<File> folderList){
librarySettings.setProperty(foldersKey, folderList.stream().map(File::toString).collect(Collectors.joining(",")));
try(FileWriter fileWriter = new FileWriter(settingsFilename)){
librarySettings.store(fileWriter, "");
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getDatabaseConnectionString() {
try (FileInputStream inputStream = new FileInputStream(propertiesFile)) {
librarySettings.load(inputStream);
if (librarySettings.containsKey(databaseKey)) {
return "jdbc:hsqldb:file:" + librarySettings.getProperty(databaseKey) + ";shutdown=true";
}
} catch (IOException ignored) {
}
return "jdbc:hsqldb:mem:."; // If not set use an in-memory database for now.
}
public static void setDatabaseFile(String fileName){
librarySettings.setProperty(databaseKey, fileName);
try(FileWriter fileWriter = new FileWriter(settingsFilename)){
librarySettings.store(fileWriter, "");
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -42,12 +42,12 @@ public class LibraryConfigGUI {
} }
private void updateLibraryListContents(){ private void updateLibraryListContents(){
listModel.setFolderList(LibraryUtils.getLibraryDirectories()); listModel.setFolderList(ConfigManager.getLibraryDirectories());
} }
private void saveLibraryList(){ private void saveLibraryList(){
List<File> folders = listModel.currentFolderList(); List<File> folders = listModel.currentFolderList();
LibraryUtils.saveLibrarySettings(folders); ConfigManager.saveLibraryDirectories(folders);
} }
private void addNew(){ private void addNew(){

View File

@ -22,40 +22,6 @@ import java.util.stream.Collectors;
public final class LibraryUtils { public final class LibraryUtils {
static final String musicFileExtensionRegex = "(?iu).*\\.(mp3|mp4|flac|ogg)"; static final String musicFileExtensionRegex = "(?iu).*\\.(mp3|mp4|flac|ogg)";
static final Properties librarySettings = new Properties();
static final String settingsFilename = "settings.cfg";
static final File propertiesFile = new File(settingsFilename);
private static List<File> libraryDirectories;
static final String foldersKey = "libraryFolders";
public static List<File> getLibraryDirectories(){
loadLibrarySettings(); // Make sure libraryDirectories matches the stored version.
return libraryDirectories;
}
public static void loadLibrarySettings(){
try(FileInputStream inputStream = new FileInputStream(propertiesFile)){
librarySettings.load(inputStream);
if(librarySettings.containsKey(foldersKey)){
libraryDirectories = Arrays.asList(librarySettings.getProperty(foldersKey).split(","))
.stream().map(File::new).filter(File::exists).collect(Collectors.toList());
}
} catch (IOException ex) {
propertiesFile.getParentFile().mkdirs();
try {
propertiesFile.createNewFile();
} catch (IOException ignored) {}
}
}
public static void saveLibrarySettings(List<File> folderList){
librarySettings.setProperty(foldersKey, folderList.stream().map(File::toString).collect(Collectors.joining(",")));
try(FileWriter fileWriter = new FileWriter(settingsFilename)){
librarySettings.store(fileWriter, "");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void processSongsWithCallback(List<Path> rootDirectory, LibraryCallbackInterface callbackInterface){ public static void processSongsWithCallback(List<Path> rootDirectory, LibraryCallbackInterface callbackInterface){
Thread thread = new Thread(() -> { Thread thread = new Thread(() -> {

View File

@ -37,7 +37,7 @@ public class Player {
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
playSong(callbackInterface.getNextSong(currentSong)); callbackInterface.playNextSong();
}); });
callbackThing.start(); callbackThing.start();
}); });
@ -57,8 +57,8 @@ public class Player {
callbackInterface.setSongHighlighting(currentSong); callbackInterface.setSongHighlighting(currentSong);
File songFile = currentSong.getSongFile(); File songFile = currentSong.getSongFile();
if (!songFile.exists()) { if (!songFile.exists()) {
callbackInterface.playNextSong();
callbackInterface.removeInvalidSong(currentSong); callbackInterface.removeInvalidSong(currentSong);
playSong(callbackInterface.getNextSong(currentSong));
return; return;
} }
playBin.setURI(songFile.toURI()); playBin.setURI(songFile.toURI());

View File

@ -24,7 +24,7 @@ import java.util.stream.Collectors;
public class PlayerGUI implements PlayerCallbackInterface, LibraryCallbackInterface { public class PlayerGUI implements PlayerCallbackInterface, LibraryCallbackInterface {
public JPanel mainPanel; public JPanel mainPanel;
private JTree libraryView; private JTree libraryView = new JTree();
private JTable playList = new JTable(); private JTable playList = new JTable();
private JSlider seekBar; private JSlider seekBar;
private JComboBox libraryDisplayType = new JComboBox(); private JComboBox libraryDisplayType = new JComboBox();
@ -33,12 +33,13 @@ public class PlayerGUI implements PlayerCallbackInterface, LibraryCallbackInterf
private static DefaultMutableTreeNode updatingNode = new DefaultMutableTreeNode(); private static DefaultMutableTreeNode updatingNode = new DefaultMutableTreeNode();
private boolean libraryUpdating = false; private boolean libraryUpdating = false;
private Map<String, Runnable> libraryDisplayVariants = createDisplayVariantMap(); private Map<String, Runnable> libraryDisplayVariants;
public PlayerGUI() { public PlayerGUI() {
createUI(); createUI();
DatabaseManager.init(); DatabaseManager.init();
resetTree(); resetTree();
libraryDisplayVariants = createDisplayVariantMap();
libraryDisplayVariants.keySet().forEach(libraryDisplayType::addItem); libraryDisplayVariants.keySet().forEach(libraryDisplayType::addItem);
Thread seekBarUpdater = new Thread(() -> { Thread seekBarUpdater = new Thread(() -> {
boolean running = true; boolean running = true;
@ -135,17 +136,6 @@ public class PlayerGUI implements PlayerCallbackInterface, LibraryCallbackInterf
playList.revalidate(); playList.revalidate();
} }
/**
* Get the next song in the playlist.
*
* @param currentSong The song that is currently selected.
* @return The next song to be selected.
*/
@Override
public Optional<Song> getNextSong(Song currentSong) {
return playlistTableModel.nextSong(currentSong);
}
/** /**
* Set the highlighted song in the playlist to this song. * Set the highlighted song in the playlist to this song.
* *
@ -163,7 +153,7 @@ public class PlayerGUI implements PlayerCallbackInterface, LibraryCallbackInterf
*/ */
public void playNextSong() { public void playNextSong() {
SwingUtilities.invokeLater(() -> seekBar.setValue(0)); SwingUtilities.invokeLater(() -> seekBar.setValue(0));
player.playSong(getNextSong(player.getCurrentSong())); player.playSong(playlistTableModel.nextSong(player.getCurrentSong()));
} }
/** /**
@ -213,7 +203,7 @@ public class PlayerGUI implements PlayerCallbackInterface, LibraryCallbackInterf
addNodeToTreeModel(model, parentNode, newNode); addNodeToTreeModel(model, parentNode, newNode);
addNodeToTreeModel(model, parentNode, updatingNode); addNodeToTreeModel(model, parentNode, updatingNode);
libraryView.setModel(model); libraryView.setModel(model);
List<Path> dirs = LibraryUtils.getLibraryDirectories().stream().map(File::toPath).collect(Collectors.toList()); List<Path> dirs = ConfigManager.getLibraryDirectories().stream().map(File::toPath).collect(Collectors.toList());
LibraryUtils.processSongsWithCallback(dirs, this); LibraryUtils.processSongsWithCallback(dirs, this);
} }
@ -281,7 +271,6 @@ public class PlayerGUI implements PlayerCallbackInterface, LibraryCallbackInterf
} }
private JTree createLibraryArea() { private JTree createLibraryArea() {
libraryView = new JTree();
libraryView.setRootVisible(false); libraryView.setRootVisible(false);
libraryView.setToggleClickCount(1); libraryView.setToggleClickCount(1);
libraryView.setCellRenderer(new LibraryTreeCellRenderer()); libraryView.setCellRenderer(new LibraryTreeCellRenderer());
@ -296,6 +285,8 @@ public class PlayerGUI implements PlayerCallbackInterface, LibraryCallbackInterf
playList.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); playList.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
playList.getColumnModel().getColumn(0).setPreferredWidth(10); playList.getColumnModel().getColumn(0).setPreferredWidth(10);
playList.getColumnModel().getColumn(0).setMaxWidth(10); playList.getColumnModel().getColumn(0).setMaxWidth(10);
playList.getColumnModel().getColumn(1).setPreferredWidth(30);
playList.getColumnModel().getColumn(1).setMaxWidth(30);
JPopupMenu popupMenu = new JPopupMenu(); JPopupMenu popupMenu = new JPopupMenu();
JMenuItem menuItem = new JMenuItem("Remove"); JMenuItem menuItem = new JMenuItem("Remove");
menuItem.addActionListener((e) -> playlistTableModel.removeSong(playList.getSelectedRows())); menuItem.addActionListener((e) -> playlistTableModel.removeSong(playList.getSelectedRows()));

View File

@ -6,8 +6,6 @@ import java.util.Optional;
public interface PlayerCallbackInterface { public interface PlayerCallbackInterface {
Optional<Song> getNextSong(Song currentSong);
void setSongHighlighting(Song playingSong); void setSongHighlighting(Song playingSong);
void setSeekBarDuration(int seconds); void setSeekBarDuration(int seconds);
@ -16,4 +14,6 @@ public interface PlayerCallbackInterface {
void playerStopped(); void playerStopped();
void playNextSong();
} }

View File

@ -1,5 +1,6 @@
package musicplayer.db; package musicplayer.db;
import musicplayer.ConfigManager;
import musicplayer.model.Album; import musicplayer.model.Album;
import musicplayer.model.Artist; import musicplayer.model.Artist;
import musicplayer.model.Song; import musicplayer.model.Song;
@ -31,7 +32,14 @@ public class DatabaseManager {
public static void init() { public static void init() {
if (getInstance().sessionFactory != null) if (getInstance().sessionFactory != null)
getInstance().sessionFactory.close(); getInstance().sessionFactory.close();
getInstance().sessionFactory = new Configuration().configure() Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
properties.put("hibernate.connection.driver_class", "org.hsqldb.jdbc.JDBCDriver");
properties.put("hibernate.connection.url", ConfigManager.getDatabaseConnectionString());
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.enable_lazy_load_no_trans", "true");
getInstance().sessionFactory = new Configuration()
.addProperties(properties)
.addAnnotatedClass(Album.class) .addAnnotatedClass(Album.class)
.addAnnotatedClass(Artist.class) .addAnnotatedClass(Artist.class)
.addAnnotatedClass(Song.class) .addAnnotatedClass(Song.class)

View File

@ -1,27 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.HSQLDialect
</property>
<property name="hibernate.connection.driver_class">
org.hsqldb.jdbc.JDBCDriver
</property>
<property name="hibernate.connection.url">
jdbc:hsqldb:file:E:/dev/testdb;shutdown=true
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root123
</property>
<property name="hibernate.hbm2ddl.auto">
update
</property>
<property name="hibernate.enable_lazy_load_no_trans">
true
</property>
</session-factory>
</hibernate-configuration>