package omq.common.registry;

import java.util.Hashtable;
import java.util.Vector;

import omq.Remote;
import omq.common.util.ParameterQueue;
import omq.exception.NotBoundException;
import omq.exception.RemoteException;
import omq.server.remote.request.RemoteObject;


/**
 * 
 * @author Sergi Toda <sergi.toda@estudiants.urv.cat> 
 *
 */
public class RegistryImpl extends RemoteObject implements Registry {

	private static final long serialVersionUID = -1164110488581245862L;
	private Hashtable<String, Remote> bindings = new Hashtable<String, Remote>();

	public RegistryImpl() throws Exception {
		super(ParameterQueue.REGISTRY_NAME);
	}

	public RegistryImpl(String UID) throws Exception {
		super(UID);
	}

	@Override
	public Remote lookup(String name) throws RemoteException {
		synchronized (bindings) {
			if (!bindings.containsKey(name)) {
				throw new NotBoundException("Object Not Bound");
			}
			return bindings.get(name);
		}
	}

	@Override
	public void bind(String name, Remote obj) throws RemoteException {
		synchronized (bindings) {
			if (bindings.containsKey(name)) {
				throw new RemoteException(name + " already exists");
			}
			bindings.put(name, obj);
		}
	}

	@Override
	public void unbind(String name) throws RemoteException {
		synchronized (bindings) {
			if (!bindings.containsKey(name))
				throw new NotBoundException("Object Not Bound");
			bindings.remove(name);
		}
	}

	@Override
	public void rebind(String name, Remote obj) throws RemoteException {
		synchronized (bindings) {
			bindings.put(name, obj);
		}
	}

	@Override
	public Vector<String> list() throws RemoteException {
		return new Vector<String>(bindings.keySet());
	}

}
