package dcj.examples.Collaborative;
import dcj.util.Collaborative.*;
import java.util.Hashtable;
import java.util.Vector;
public class SearchCollector extends RMIMediatorImpl
{
protected Vector unassignedSites = new Vector();
protected Hashtable siteTable = new Hashtable();
protected SiteIndex index = new SiteIndex();
public SearchCollector(Vector sites) {
Enumeration e = sites.elements();
while (e.hasMoreElements()) {
String s = (String)e.nextElement();
addSite(s);
}
}
public SiteIndex getIndex() { return index; }
public boolean register(Identity i, RMICollaborator c)
throws RemoteException {
boolean success = super.register(i, c);
if (success) {
try {
SiteSearcher searcher = (SiteSearcher)c;
Vector sites = searcher.getSites();
if (sites == null) {
// This searcher doesn't have any sites yet, so give
// it some of our unassigned sites.
assignSites(searcher);
}
else {
// The searcher has some sites that it searches already,
// so add them to our site table.
Enumeration enum = sites.elements();
while (enum.hasMoreElements()) {
String siteName = (String)enum.nextElement();
addSite(siteName, searcher);
}
}
}
catch (Exception e) {
success = false;
System.out.println("Failed assigning sites.");
e.printStackTrace();
}
}
return success;
}
public boolean addSite(String siteName) {
boolean success = false;
if (!siteTable.get(siteName)) {
unassignedSites.addElement(siteName);
success = true;
}
return success;
}
public boolean addSite(String siteName, SiteSearcher searcher) {
siteTable.put(siteName, searcher);
unassignedSites.removeElement(siteName);
return success;
}
public boolean removeSite(String siteName) {
boolean success = false;
if (siteTable.remove(siteName) || unassignedSites.remove(siteName)) {
success = true;
}
return success;
}
protected boolean assignSites(SiteSearcher searcher) {
boolean success = false;
String sHost = searcher.getHostName();
try {
byte[] hostIP = InetAddress.getByName(sHost).getAddress();
Enumeration enum = unassignedSites.elements();
while (enum.hasMoreElements()) {
String siteName = (String)enum.nextElement();
try {
byte[] siteIP = InetAddress.getByName(siteName).getAddress();
if (hostIP[0] == siteIP[0] && hostIP[1] == siteIP[1]) {
searcher.addSite(siteName);
addSite(siteName, searcher);
success = true;
}
}
catch (Exception e1) {}
}
}
catch (Exception e2) {}
if (!success) {
// Couldn't assign a site by address, so pick one at random
// and give it to this searcher.
if (unassignedSites.length() > 0) {
String siteName = (String)unassignedSites.elementAt(0);
searcher.addSite(siteName);
addSite(siteName, searcher);
success = true;
}
}
return success;
}
public boolean update() {
Vector searchers = getMembers();
Enumeration enum = searchers.elements();
while (enum.hasMoreElements()) {
SiteSearcher s = (SiteSearcher)enum.nextElement();
Hashtable results = s.doSearch();
mergeResults(results);
}
}
}
|