package ch.marcsladek.jrtnp.server;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import ch.marcsladek.jrtnp.connection.Connection;
import ch.marcsladek.jrtnp.connection.ConnectionFactory;
public class ClientManager {
protected final Pool<String, Connection> clientPool;
private ConnectionFactory factory;
/**
* @param connectionFactoryClassName
* class name of the factory used to create objects of own Connection
* implementation
* @throws InstantiationException
* when unable to create instance of given class name
* @throws IllegalAccessException
* when unable to access given class name
* @throws ClassNotFoundException
* when unable to find given class name
*/
@SuppressWarnings("unchecked")
protected ClientManager(String connectionFactoryClassName)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
clientPool = new Pool<String, Connection>();
factory = ((Class<? extends ConnectionFactory>) Class
.forName(connectionFactoryClassName)).newInstance();
}
/**
* Returns a new Connection for the given Socket and adds it to the pool
*
* @param socket
* for establishing the connection to
* @return the new Conenction
* @throws IOException
* when unable to listen to socket
*/
public synchronized Connection newClient(Socket socket) throws IOException {
Connection client = factory.newInstance(socket);
return clientPool.add(client.getIdentifier(), client);
}
/**
* Removes the given Connection from the pool
*
* @param identifier
* specifies Connection
* @return whether was successful or not
*/
public synchronized boolean removeClient(String identifier) {
Connection client = clientPool.remove(identifier);
boolean success = false;
if (client != null) {
try {
client.shutdown();
success = true;
} catch (IOException e) {
}
}
return success;
}
/**
* Sends the Object to the Connection given connection
*
* @param identifier
* specifies Connection
* @param obj
* Object being sent
* @return whether was successful or not
* @throws IOException
* when unable to access socket
*/
public final synchronized boolean send(String identifier, Object obj)
throws IOException {
Connection client = clientPool.get(identifier);
if (client != null) {
return client.send(obj);
} else {
return false;
}
}
/**
* @return a list of connected Clients
*/
public final synchronized List<String> list() {
return new ArrayList<String>(clientPool.keys());
}
/**
* shuts down the connections to all clients
*/
public final synchronized void shutdown() {
for (Connection client : clientPool.list()) {
try {
client.shutdown();
} catch (IOException e) {
}
}
}
@Override
public String toString() {
return "ClientManager [factory=" + factory.getClass().getName() + ", clientPool="
+ clientPool + "]";
}
}