Added an optional default value to Track.get(..) to remove necessity for null pointer...
[stereo.git] / MemphisDJ / src / music / LibraryTrack.java
blob907af0be89e8735fff7946be81baba2782b1ca8e
1 package music;
3 import interfaces.Album;
4 import interfaces.Constants;
5 import interfaces.Track;
7 import java.io.IOException;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.HashSet;
11 import java.util.Map;
12 import java.util.Set;
14 public class LibraryTrack implements Track {
16 private final int id;
17 private final long persistentId;
18 private final Set<Track> backingTracks = new HashSet<Track>(2);
20 private LibraryTrack(int id, long persistantId, Album album) {
21 this.id = id;
22 this.persistentId = persistantId;
23 this.setAlbum(album);
26 public int id() {
27 Track current = current();
28 if (current == null) return id;
29 return current.id();
32 public Album getAlbum() {
33 Track current = current();
34 if (current == null) return null;
35 return current.getAlbum();
38 public long persistentId() {
39 Track current = current();
40 if (current == null) return persistentId;
41 return current.persistentId();
44 public void put(Constants tag, Object value) {
45 for (Track t: backingTracks) {
46 t.put(tag, value);
50 public void setAlbum(Album album) {
51 for (Track t: backingTracks) {
52 t.setAlbum(album);
56 public Object get(Constants tag) {
57 Track current = current();
58 if (current == null) return null;
59 return current.get(tag);
62 public Object get(Constants tag, Object defaultValue) {
63 Object ret = get(tag);
64 if (ret == null) {
65 return defaultValue;
67 else {
68 return ret;
72 public Iterable<Constants> getAllTags() {
73 Track current = current();
74 if (current == null) return new ArrayList<Constants>(0);
75 return current.getAllTags();
78 public void getStream(StreamReader reader) throws IOException {
79 Track current = current();
80 if (current == null) return;
81 current.getStream(reader);
84 public String toString() {
85 Track c = current();
86 if (c == null) return "";
87 return c.toString();
90 synchronized void addBackingTrack(Track t) {
91 backingTracks.add(t);
94 synchronized void removeBackingTrack(Track t) {
95 backingTracks.remove(t);
98 synchronized int numBackingTracks() {
99 return backingTracks.size();
102 private synchronized Track current() {
103 if (backingTracks.isEmpty()) return null;
104 return backingTracks.iterator().next();
107 private static Factory factory = new Factory();
108 public static Factory factory() {
109 return factory;
112 public static class Factory {
113 private Map<Long, LibraryTrack> tracks = new HashMap<Long, LibraryTrack>();
114 private volatile int id = 0;
115 public synchronized LibraryTrack create(Track t) {
116 LibraryTrack track = tracks.get(t.persistentId());
117 if (track == null) {
118 track = new LibraryTrack(++id, t.persistentId(), t.getAlbum());
119 tracks.put(t.persistentId(), track);
121 return track;