projectresurrection.Music.java Source code

Java tutorial

Introduction

Here is the source code for projectresurrection.Music.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 projectresurrection;

import com.mpatric.mp3agic.*;
import com.thoughtworks.xstream.XStream;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import org.apache.commons.io.*;

/**
 *
 * @author Onryo
 */
public class Music implements Runnable {

    private Thread t;
    private final String THREAD_NAME = "musicThread";
    private static Queue<String> commands = new PriorityQueue<>();
    private JPanel tab;
    private MusicPlayer player;
    private JPanel pnlMenu;
    private JPanel pnlSub;
    private JPanel pnlPlayer;
    private JPanel pnlAdd;
    private JPanel pnlLoad;
    private List<File> files;
    private Map<String, Map> fileData = new HashMap();
    private Map artists = new HashMap();
    private Map albums = new HashMap();
    private Map songs = new HashMap();
    private static final File FOLDER = new File("C:\\Eve\\music");
    private static final String MUSIC_FILE = "C:\\Eve\\music\\music.xml";
    public static final int ARTISTS = 0;
    public static final int ALBUMS = 1;
    public static final int SONGS = 2;
    public static final int SHUFFLE = 0;

    public Music() {
        t = new Thread(this, THREAD_NAME);
    }

    public void addCommand(String command) {
        switch (command) {

        }
    }

    private static Object xmlRead(String path) {
        Object output = null;
        try {
            String xml = "";
            String line = null;
            XStream xstream = new XStream();
            FileReader fr = new FileReader(path);
            BufferedReader br = new BufferedReader(fr);
            while ((line = br.readLine()) != null) {
                xml += line;
            }
            br.close();
            output = xstream.fromXML(xml);
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return (output);
    }

    private static void xmlWrite(String path, Object input) {
        try {
            XStream xstream = new XStream();
            String xml = xstream.toXML(input);
            FileWriter file = new FileWriter(path);
            file.write(xml);
            file.flush();
            file.close();
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }

    public void start(JPanel pan, MusicPlayer mp) {
        tab = pan;
        player = mp;
        pnlMenu = ((JPanel) ((JPanel) ((JViewport) ((JScrollPane) tab.getComponent(0)).getComponent(0))
                .getComponent(0)).getComponent(0));
        pnlSub = ((JPanel) ((JPanel) ((JViewport) ((JScrollPane) tab.getComponent(0)).getComponent(0))
                .getComponent(0)).getComponent(1));
        pnlAdd = ((JPanel) ((JPanel) ((JViewport) ((JScrollPane) tab.getComponent(0)).getComponent(0))
                .getComponent(0)).getComponent(2));
        pnlPlayer = ((JPanel) ((JPanel) ((JViewport) ((JScrollPane) tab.getComponent(0)).getComponent(0))
                .getComponent(0)).getComponent(3));
        pnlLoad = ((JPanel) ((JPanel) ((JViewport) ((JScrollPane) tab.getComponent(0)).getComponent(0))
                .getComponent(0)).getComponent(4));
        player.start(pnlPlayer);
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                if (new File(MUSIC_FILE).exists()) {
                    fileData = (Map) xmlRead(MUSIC_FILE);
                } else {
                    fileData = new HashMap();
                    fileData.put("artists", new HashMap());
                    xmlWrite(MUSIC_FILE, fileData);
                }
                update();
                t.start();
                pnlLoad.setVisible(false);
                pnlMenu.setVisible(true);
            }
        });
        t1.start();
    }

    public Map getInfo() {
        return artists;
    }

    public List getSongs() {
        List songList = new ArrayList(songs.keySet());
        List list = new ArrayList();
        for (int i = 0; i < songList.size(); i++) {
            list.add(((List) songs.get(songList.get(i))).get(0));
        }
        return list;
    }

    public void subMenu(int menu) {
        JPanel panel = (JPanel) ((JViewport) ((JScrollPane) pnlSub.getComponent(3)).getComponent(0))
                .getComponent(0);
        JLabel header = (JLabel) pnlSub.getComponent(1);
        JLabel label;
        panel.removeAll();
        int y = 10;
        switch (menu) {
        case 0:
            header.setText("Artists");
            panel.setPreferredSize(new Dimension(349, (55 + (artists.size() * 35))));
            label = new JLabel("All");
            label.setOpaque(true);
            label.setBackground(new Color(245, 245, 245));
            label.setFont(new Font("Tahoma", Font.PLAIN, 20));
            label.setBounds(10, y, 339, 35);
            label.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent arg0) {
                    subMenu(ALBUMS);
                    panel.revalidate();
                    panel.repaint();
                }
            });
            panel.add(label);
            y += 35;
            List artistList = new ArrayList(artists.keySet());
            Collections.sort(artistList);
            for (int i = 0; i < artistList.size(); i++) {
                String artist = artistList.get(i).toString();
                label = new JLabel(artist);
                label.setOpaque(true);
                if (i % 2 == 1) {
                    label.setBackground(new Color(245, 245, 245));
                }
                label.setFont(new Font("Tahoma", Font.PLAIN, 20));
                label.setBounds(10, y, 339, 35);
                label.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent arg0) {
                        subMenu(ARTISTS, artist);
                        panel.revalidate();
                        panel.repaint();
                    }
                });
                panel.add(label);
                y += 35;
            }
            break;
        case 1:
            header.setText("Albums");
            panel.setPreferredSize(new Dimension(349, (55 + (albums.size() * 35))));
            label = new JLabel("All");
            label.setOpaque(true);
            label.setBackground(new Color(245, 245, 245));
            label.setFont(new Font("Tahoma", Font.PLAIN, 20));
            label.setBounds(10, y, 339, 35);
            label.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent arg0) {
                    subMenu(SONGS);
                    panel.revalidate();
                    panel.repaint();
                }
            });
            panel.add(label);
            y += 35;
            List albumList = new ArrayList(albums.keySet());
            Collections.sort(albumList);
            for (int i = 0; i < albumList.size(); i++) {
                String album = albumList.get(i).toString();
                label = new JLabel(album);
                label.setOpaque(true);
                if (i % 2 == 1) {
                    label.setBackground(new Color(245, 245, 245));
                }
                label.setFont(new Font("Tahoma", Font.PLAIN, 20));
                label.setBounds(10, y, 339, 35);
                label.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent arg0) {
                        subMenu(ALBUMS, album);
                        panel.revalidate();
                        panel.repaint();
                    }
                });
                panel.add(label);
                y += 35;
            }
            break;
        case 2:
            header.setText("Songs");
            panel.setPreferredSize(new Dimension(349, (20 + (songs.size() * 35))));
            List songList = new ArrayList(songs.keySet());
            Collections.sort(songList);
            List fileList = new ArrayList();
            for (int i = 0; i < songList.size(); i++) {
                fileList.add(((List) songs.get(songList.get(i))).get(0));
            }
            for (int i = 0; i < songList.size(); i++) {
                int num = i;
                String song = songList.get(i).toString();
                label = new JLabel(song);
                label.setOpaque(true);
                if (i % 2 == 0) {
                    label.setBackground(new Color(245, 245, 245));
                }
                label.setFont(new Font("Tahoma", Font.PLAIN, 20));
                label.setBounds(10, y, 339, 35);
                label.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent arg0) {
                        player.setPlaylist(fileList, num);
                        pnlSub.setVisible(false);
                        pnlPlayer.setVisible(true);
                        try {
                            Thread.sleep(200);
                        } catch (Exception e) {
                        }
                        if (player.isPlaying() == false) {
                            player.toggle();
                        }
                    }
                });
                panel.add(label);
                y += 35;
            }
            break;
        }
        pnlMenu.setVisible(false);
        pnlSub.setVisible(true);
    }

    public void subMenu(int type, String menu) {
        JPanel panel = (JPanel) ((JViewport) ((JScrollPane) pnlSub.getComponent(3)).getComponent(0))
                .getComponent(0);
        JLabel header = (JLabel) pnlSub.getComponent(1);
        JLabel label;
        header.setText(menu);
        panel.removeAll();
        int y = 10;
        switch (type) {
        case 0:
            List albumList = new ArrayList(((Map) artists.get(menu)).keySet());
            Collections.sort(albumList);
            panel.setPreferredSize(new Dimension(349, (55 + (albumList.size() * 35))));
            label = new JLabel("All");
            label.setOpaque(true);
            label.setBackground(new Color(245, 245, 245));
            label.setFont(new Font("Tahoma", Font.PLAIN, 20));
            label.setBounds(10, y, 339, 35);
            label.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent arg0) {
                    subMenuAll(ARTISTS, menu);
                    panel.revalidate();
                    panel.repaint();
                }
            });
            panel.add(label);
            y += 35;
            for (int i = 0; i < albumList.size(); i++) {
                String album = albumList.get(i).toString();
                label = new JLabel(album);
                label.setOpaque(true);
                if (i % 2 == 1) {
                    label.setBackground(new Color(245, 245, 245));
                }
                label.setFont(new Font("Tahoma", Font.PLAIN, 20));
                label.setBounds(10, y, 339, 35);
                label.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent arg0) {
                        subMenu(ALBUMS, album);
                        panel.revalidate();
                        panel.repaint();
                    }
                });
                panel.add(label);
                y += 35;
            }
            break;
        case 1:
            List songList = new ArrayList();
            List albumSongs = new ArrayList(((Map) albums.get(menu)).keySet());
            Collections.sort(albumSongs);
            Map tracks = new HashMap();
            for (int i = 0; i < albumSongs.size(); i++) {
                String track = ((List) songs.get(albumSongs.get(i))).get(1).toString();
                if (tracks.containsKey(track)) {
                    track = track + "(1)";
                    int j = 2;
                    while (tracks.containsKey(track)) {
                        track = track + "(" + j + ")";
                    }
                }
                tracks.put(track, albumSongs.get(i));
            }
            List nums = new ArrayList(tracks.keySet());
            Collections.sort(nums);
            List hasTrack = new ArrayList();
            List noTrack = new ArrayList();
            for (int i = 0; i < nums.size(); i++) {
                if (nums.get(i).equals("-1")) {
                    noTrack.add(tracks.get(nums.get(i)));
                } else {
                    hasTrack.add(tracks.get(nums.get(i)));
                }
            }
            Collections.sort(noTrack);
            for (int i = 0; i < hasTrack.size(); i++) {
                songList.add(hasTrack.get(i));
            }
            for (int i = 0; i < noTrack.size(); i++) {
                songList.add(noTrack.get(i));
            }
            panel.setPreferredSize(new Dimension(349, (20 + (albumSongs.size() * 35))));
            List fileList = new ArrayList();
            for (int i = 0; i < songList.size(); i++) {
                fileList.add(((List) songs.get(songList.get(i))).get(0));
            }
            for (int i = 0; i < songList.size(); i++) {
                int num = i;
                String song = songList.get(i).toString();
                label = new JLabel(song);
                label.setOpaque(true);
                if (i % 2 == 0) {
                    label.setBackground(new Color(245, 245, 245));
                }
                label.setFont(new Font("Tahoma", Font.PLAIN, 20));
                label.setBounds(10, y, 339, 35);
                label.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent arg0) {
                        player.setPlaylist(fileList, num);
                        pnlSub.setVisible(false);
                        pnlPlayer.setVisible(true);
                        try {
                            Thread.sleep(200);
                        } catch (Exception e) {
                        }
                        if (player.isPlaying() == false) {
                            player.toggle();
                        }
                    }
                });
                panel.add(label);
                y += 35;
            }
            break;
        }
        panel.revalidate();
        panel.repaint();
    }

    public void subMenuAll(int type, String menu) {
        JPanel panel = (JPanel) ((JViewport) ((JScrollPane) pnlSub.getComponent(3)).getComponent(0))
                .getComponent(0);
        JLabel header = (JLabel) pnlSub.getComponent(1);
        header.setText(menu + " - All");
        panel.removeAll();
        int y = 10;
        switch (type) {
        case 0:
            List songList = new ArrayList();
            List albumList = new ArrayList(((Map) artists.get(menu)).keySet());
            Collections.sort(albumList);
            for (int i = 0; i < albumList.size(); i++) {
                List albumSongs = new ArrayList(((Map) albums.get(albumList.get(i))).keySet());
                Map tracks = new HashMap();
                for (int j = 0; j < albumSongs.size(); j++) {
                    String track = ((List) songs.get(albumSongs.get(j))).get(1).toString();
                    tracks.put(track, albumSongs.get(j));
                }
                List nums = new ArrayList(tracks.keySet());
                Collections.sort(nums);
                List hasTrack = new ArrayList();
                List noTrack = new ArrayList();
                for (int j = 0; j < nums.size(); j++) {
                    if (nums.get(j).equals("-1")) {
                        noTrack.add(tracks.get(nums.get(j)));
                    } else {
                        hasTrack.add(tracks.get(nums.get(j)));
                    }
                }
                for (int j = 0; j < hasTrack.size(); j++) {
                    songList.add(hasTrack.get(j));
                }
                for (int j = 0; j < noTrack.size(); j++) {
                    songList.add(noTrack.get(j));
                }
            }
            panel.setPreferredSize(new Dimension(349, (20 + (songList.size() * 35))));
            List fileList = new ArrayList();
            for (int i = 0; i < songList.size(); i++) {
                fileList.add(((List) songs.get(songList.get(i))).get(0));
            }
            for (int i = 0; i < songList.size(); i++) {
                int num = i;
                String song = songList.get(i).toString();
                JLabel label = new JLabel(song);
                label.setOpaque(true);
                if (i % 2 == 0) {
                    label.setBackground(new Color(245, 245, 245));
                }
                label.setFont(new Font("Tahoma", Font.PLAIN, 20));
                label.setBounds(10, y, 339, 35);
                label.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent arg0) {
                        player.setPlaylist(fileList, num);
                        pnlSub.setVisible(false);
                        pnlPlayer.setVisible(true);
                        try {
                            Thread.sleep(200);
                        } catch (Exception e) {
                        }
                        if (player.isPlaying() == false) {
                            player.toggle();
                        }
                    }
                });
                panel.add(label);
                y += 35;
            }
            break;
        }
        panel.revalidate();
        panel.repaint();
    }

    private void getFiles(File file) {
        if (file.isFile()) {
            files.add(file);
        } else if (file.isDirectory()) {
            File[] listOfFiles = file.listFiles();
            if (listOfFiles != null) {
                for (int i = 0; i < listOfFiles.length; i++) {
                    getFiles(listOfFiles[i]);
                }
            }
        }
    }

    public void addSongs(String dir) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                File directory = new File(dir);
                JProgressBar progress = (JProgressBar) pnlAdd.getComponent(3);
                progress.setValue(0);
                files = new ArrayList();
                List tempSongs = new ArrayList();
                Map<String, Map> artists = fileData.get("artists");
                getFiles(directory);
                List<File> mp3s = new ArrayList();
                for (int i = 0; i < files.size(); i++) {
                    if (FilenameUtils.getExtension(files.get(i).getAbsolutePath()).equals("mp3")) {
                        mp3s.add(files.get(i));
                    }
                }
                for (int i = 0; i < mp3s.size(); i++) {
                    try {
                        File file = mp3s.get(i);
                        File tempFile = new File(FOLDER.getAbsolutePath() + "\\" + file.getName());
                        String name;
                        if (tempFile.exists()) {
                            String prevName = file.getName();
                            name = ("(1)" + file.getName());
                            int j = 2;
                            while (new File(FOLDER.getAbsoluteFile() + "\\" + name).exists()) {
                                name = "(" + j + ")" + file.getName();
                                j++;
                            }
                            file.renameTo(new File(file.getParent() + "\\" + name));
                            file = new File(file.getParent() + "\\" + name);
                            FileUtils.copyFileToDirectory(new File(file.getAbsolutePath()), FOLDER);
                            file.renameTo(new File(file.getParent() + "\\" + prevName));
                            file = new File(FOLDER.getAbsolutePath() + "\\" + name);
                        } else {
                            FileUtils.copyFileToDirectory(file.getAbsoluteFile(), FOLDER);
                            file = new File(FOLDER.getAbsolutePath() + "\\" + file.getName());
                        }
                        Mp3File song = new Mp3File(file.getAbsolutePath());
                        ID3v2 tag = song.getId3v2Tag();
                        if (tag.getArtist() == null || tag.getArtist().equals("")) {
                            tag.setArtist("Unknown");
                        }
                        if (tag.getAlbum() == null || tag.getAlbum().equals("")) {
                            tag.setAlbum("Unknown");
                        }
                        if (tag.getTitle() == null || tag.getTitle().equals("")) {
                            tag.setTitle("Unknown");
                        }
                        if (songs.containsKey(tag.getTitle())) {
                            String title = tag.getTitle() + "(1)";
                            int j = 2;
                            while (tempSongs.contains(title)) {
                                title = tag.getTitle() + "(" + j + ")";
                                j++;
                            }
                            tag.setTitle(title);
                        }
                        if (tag.getTrack() == null || tag.getTrack().equals("")) {
                            tag.setTrack("-1");
                        }
                        if (!artists.containsKey(tag.getArtist())) {
                            artists.put(tag.getArtist(), new HashMap<String, Map>());
                        }
                        if (!artists.get(tag.getArtist()).containsKey(tag.getAlbum())) {
                            artists.get(tag.getArtist()).put(tag.getAlbum(), new HashMap<String, List>());
                        }
                        ((Map) artists.get(tag.getArtist()).get(tag.getAlbum())).put(tag.getTitle(),
                                Arrays.asList(file.getName(), tag.getTrack(), false));
                        songs.put(tag.getTitle(), Arrays.asList(file.getName(), tag.getTrack()));
                        progress.setValue(((i + 1) * 100) / mp3s.size());
                        progress.revalidate();
                    } catch (Exception e) {
                        e.printStackTrace(System.out);
                    }
                }
                fileData = new HashMap();
                fileData.put("artists", artists);
                xmlWrite(MUSIC_FILE, fileData);
                update();
            }
        });
        t1.start();
    }

    private void update() {
        artists = fileData.get("artists");
        List artistList = new ArrayList(artists.keySet());
        for (int i = 0; i < artistList.size(); i++) {
            List albumList = new ArrayList(((Map) artists.get(artistList.get(i))).keySet());
            for (int j = 0; j < albumList.size(); j++) {
                albums.put(albumList.get(j), ((Map) ((Map) artists.get(artistList.get(i))).get(albumList.get(j))));
                List songList = new ArrayList(
                        ((Map) ((Map) artists.get(artistList.get(i))).get(albumList.get(j))).keySet());
                for (int l = 0; l < songList.size(); l++) {
                    songs.put(songList.get(l),
                            ((List) ((Map) ((Map) artists.get(artistList.get(i))).get(albumList.get(j)))
                                    .get(songList.get(l))));
                }
            }
        }
    }

    public void run() {
        while (true) {
            try {
                update();
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
        }
    }
}