git-svn-id: https://stereo.googlecode.com/svn/trunk@440 c67ee986-0855-0410-825f-15918...
[stereo.git] / DACPlib / src / daap / DAAPLackey.java
blob3b1de7861aa9e1ae3c6dddf70615a7e07f6eaf75
1 package daap;
3 import interfaces.Library;
4 import interfaces.Track;
6 import java.io.IOException;
7 import java.util.ArrayList;
8 import java.util.HashSet;
9 import java.util.List;
10 import java.util.Set;
12 /**
13 * DAAPLackey polls DAAP libraries for changes and updates the DJ's library.
15 public class DAAPLackey {
17 private final Set<DAAPClient> clients;
19 private final Library<? extends Track> library;
21 private static DAAPLackey lackey;
22 public static DAAPLackey lackey() {
23 return lackey;
26 public DAAPLackey(Library<? extends Track> library) {
28 lackey = this;
30 this.library = library;
31 this.clients = new HashSet<DAAPClient>();
33 new PollThread().start();
36 public void request(final String host, final int port) {
38 new Thread("DAAP Connection Thread") {
39 public void run() {
41 try {
42 List<DAAPClient> pls = DAAPClient.create(host, port, library.nextCollectionId());
44 for (DAAPClient c: pls) {
45 add(c);
48 catch (IOException ex) {
49 System.err.println("Error connecting to daap server: " + ex.getMessage());
53 }.start();
56 private synchronized void add(DAAPClient client) {
57 clients.add(client);
58 library.addSource(client);
59 library.addCollection(client.collection());
62 private synchronized void remove(DAAPClient client) {
63 library.removeCollection(client.collection());
64 library.removeSource(client);
65 clients.remove(client);
68 private synchronized List<DAAPClient> clients() {
69 return new ArrayList<DAAPClient>(clients);
72 private class PollThread extends Thread {
73 public void run() {
74 while (true) {
76 List<DAAPClient> clients = clients();
78 for (DAAPClient client: clients) {
79 try {
80 client.update();
82 catch (IOException ex) {
83 System.err.println("Unable to update client, closing (" + client.collection().name() + ")");
84 ex.printStackTrace();
86 client.close();
87 remove(client);
91 try {
92 Thread.sleep(10000);
93 } catch (InterruptedException e) {
94 //swallow