package ua.vydai.chat.server.model;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import ua.vydai.chat.server.model.interfaces.Closeable;
public class UserList {
UserList() {
userList = Collections.synchronizedMap(new HashMap<ClientObject, ChatCommunication>());
}
synchronized public int size() {
return userList.size();
}
synchronized public void add(ClientObject client, ChatCommunication chat) {
userList.put(client, chat);
}
synchronized public void remove(ClientObject client) {
getChatBy(client).close();
userList.remove(client);
}
synchronized public Closeable getChatBy(ClientObject client) {
return (Closeable)userList.get(client);
}
public ClientObject getClientBy(String userName) {
ClientObject result = null;
for (ClientObject client : getClients()) {
if (client.getUserName().equals(userName)) {
result = client;
break;
}
}
return result;
}
public ClientObject getClientBy(Socket userSocket) {
ClientObject result = null;
for (ClientObject client : getClients()) {
if (client.getSocket().equals(userSocket)) {
result = client;
break;
}
}
return result;
}
synchronized public Set<ClientObject> getClients() {
return userList.keySet();
}
synchronized public void clear() {
Closeable chat;
for (ClientObject userObj : getClients()) {
chat = getChatBy(userObj);
if (chat != null) { // if previously wasn't closed from client side, for example
chat.close();
}
}
userList.clear();
}
/**
* Method to check whether the userName is already exists
*/
public boolean isUserExists(String userName) {
return getClientBy(userName) != null;
}
/**
* Method to check whether the socket is already registered
*/
public boolean isSocketExists(Socket socket) {
return getClientBy(socket) != null;
}
private Map<ClientObject, ChatCommunication> userList;
}