package javacodebook.net.rmi.objectcopy;

import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject;
import java.net.MalformedURLException;
import java.util.*;

/**
 * @author benjamin_rusch
 *
 * Dieser Server beinhaltet AddressDaten. Kennt der Client den Nachname, 
 * kann er auch weitere Informationen über diese Person erlangen. 
 * Zusätzlich hat er noch Zugriff auf die Anzahl gespeicherter Adressen
 * Achtung: Bevor der Server laufen kann müssen Stub und Skeleton generiert 
 * werden: 
 * 	   rmic javacodebook.net.rmi.objectcopy.AddressBookServer
 */
public class AddressBookServer implements AddressBook {

	// Adressen werden in eine HashTable abgelegt
	private Hashtable content = new Hashtable();
		
	public int getSize() throws RemoteException {
		return content.size();
	}
	
	public Address getAddressByName(String name) throws RemoteException {
		return (Address)content.get(name);
	}
	
	public AddressBookServer(int port)throws Exception
	{
		// AdressBuch wird mit Daten gefüllt
		fillHashTable();
		// Die Registry wird vom Program aus gestartet
		LocateRegistry.createRegistry(port);
		// Dieses Server-Objekt wird exportiert
		UnicastRemoteObject.exportObject(this,port);
		
		// Das exportierte Objekt wird an der registry mit defnierter
		// URL angemeldet
  		Naming.rebind("//localhost:"+port+"/"+AddressBook.NAMING, this);
	}
	
	/**
	 * Füllt Adressbuch mit Daten.
	 */
	private void fillHashTable() {
		content.put("Arbeit",
				new Address("Arbeit", "Andi", "Terlindenweg","Soest"));
		content.put("Einstellbar",
				new Address("Einstellbar","Manuel","Kaiserallee","Karlsruhe"));
		content.put("Sörwis",
				new Address("Sörwis","Sigrid","Winsstrasse","Berlin"));
		content.put("Mutig",
				new Address("Mutig","Miss","Kungshamra","Stockholm"));
	}
	
	// Server wird gestartet.
	public static void main(String[] args) throws Exception{
			new AddressBookServer(1099);
			
	}
}
