package main.settings;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Vector;
import common.info.Server;
import common.util.NonNullObjectInputStream;
public class ServerList implements Serializable
{
private static final long serialVersionUID = 7620508875698520858L;
private static volatile HashSet<Server> set;
private static volatile Vector<Server> list;
private static volatile ServerListListener listener;
static
{
set = new HashSet<Server>();
list = new Vector<Server>();
}
private ServerList()
{
listener = null;
}
@SuppressWarnings("unchecked")
public static synchronized boolean readFromDataFile()
{
FileInputStream is;
try
{
is = new FileInputStream(new File(Settings.application.files.servers));
}
catch (FileNotFoundException e)
{
return false;
}
Object read;
try
{
read = new NonNullObjectInputStream(is).readObject();
}
catch (IOException e)
{
return false;
}
catch (ClassNotFoundException e)
{
return false;
}
try
{
set = (HashSet<Server>) read;
}
catch (ClassCastException e)
{
return false;
}
for (Server server : set)
{
list.add(server);
}
fireChange();
return true;
}
public static synchronized boolean writeToDataFile()
{
FileOutputStream fos;
try
{
fos = new FileOutputStream(new File(Settings.application.files.servers));
}
catch (FileNotFoundException e)
{
return false;
}
try
{
new ObjectOutputStream(fos).writeObject(set);
}
catch (IOException e)
{
return false;
}
return true;
}
public static void setListener(ServerListListener listener)
{
ServerList.listener = listener;
}
private static void fireChange()
{
if (listener != null)
{
listener.onChange();
}
}
public static synchronized void addServer(Server server)
{
if (set.contains(server))
{
set.remove(server);
list.remove(server);
}
set.add(server);
list.add(server);
fireChange();
}
public static int getCount()
{
return list.size();
}
public static Server getAt(int index)
{
return list.get(index);
}
}