001    /*
002    
003      $Id: KeyManager.java,v 1.4 2003/03/31 13:17:41 culdesac Exp $
004    
005    */
006    
007    package sharpster.common;
008    
009    import java.util.Hashtable;
010    import java.util.LinkedList;
011    import java.util.Enumeration;
012    import java.util.ListIterator;
013    import net.jxta.id.*;
014    
015    /**
016     * Class responsible for supplying unique keys for all users.
017     */
018    
019    public class KeyManager {
020        
021        /**
022         * Maps a key to a string.
023         */
024        private Hashtable keyToValueMap;
025        
026        /**
027         * Maps a string to a key value.
028         */
029        private Hashtable valueToKeyMap;
030    
031        /**
032         * Constructs an instance of the class and initializes the member
033         * attributes.
034         */
035        public KeyManager() {
036            keyToValueMap = new Hashtable();
037            valueToKeyMap = new Hashtable();
038        }
039        
040        /**
041         * Adds a key value for the specified user.
042         */
043        public ID add(String str, ID key) {
044            if(valueToKeyMap.containsKey(str)) {
045                return (ID)valueToKeyMap.get(str);
046            }
047    
048            if(key == null) {
049                key = IDFactory.newPeerGroupID();
050            }
051    
052            valueToKeyMap.put(new String(str), key);
053            keyToValueMap.put(key, new String(str));
054    
055            return key;
056        }
057    
058        /**
059         * Removes the key value for the specified user.
060         */
061        public void remove(String str) {
062            if(valueToKeyMap.containsKey(str)) {
063                ID key = (ID)valueToKeyMap.remove(str);
064                keyToValueMap.remove(key);
065            }
066        }
067    
068        /**
069         * Returns the key value for the specified user.
070         */
071        public ID getKey(String str) {
072            return (ID)valueToKeyMap.get(str);
073        }
074    
075        /**
076         * Returns the user for the given key value.
077         */
078        public String getValue(ID key) {
079            return (String)keyToValueMap.get(key);
080        }
081    
082        public String[] getAllValues() {
083            try {
084                Enumeration enum = keyToValueMap.elements();
085                String[] list = new String[keyToValueMap.size()];
086                int i=0;
087    
088                while(enum.hasMoreElements()) {
089                    list[i++] = new String((String)enum.nextElement());
090                }
091    
092                return list;
093            }
094            catch(Exception e) {
095                return null;
096            }
097        }
098    }
099    
100    
101    
102