001    /*
002    
003      $Id: UserManager.java,v 1.10 2003/03/28 15:02:45 culdesac Exp $
004    
005    */
006    
007    package sharpster.daemon.usermanagement;
008    
009    import sharpster.common.*;
010    
011    import net.jxta.document.*;
012    import net.jxta.id.*;
013    import java.io.FileInputStream;
014    import java.io.FileOutputStream;
015    import java.io.StringWriter;
016    import java.util.Enumeration;
017    import java.util.Hashtable;
018    
019    /**
020     * Class responsible of the management of users. Stores
021     * information about the external users which the daemon has
022     * knowledge of. It also keeps track of all the .le shares which the
023     * external users have made to the user of the local client.
024     */
025    public class UserManager {
026               
027        /**
028         * A class used to have cross references between users and their id's.
029         */
030        public KeyManager userKeyManager;
031        
032        /**
033         * A string containing the path to the configuration file (used in 
034         * loadFromFile and saveToFile).
035         */
036        private String configFile;
037    
038        /**
039         * A hash table containing a file collection for each user.
040         */
041        private Hashtable availableShares; 
042    
043        /**
044         * Constructor
045         */
046        public UserManager() {
047            userKeyManager = new KeyManager();
048            configFile = new String();
049            availableShares = new Hashtable();
050        }
051    
052        /**
053         * Perform evantual initialization.
054         */
055        public void initialize() {
056        }
057    
058        /**
059         * Returns a unqiue key value for a given user.
060         */
061        public synchronized ID getKey(String user) {
062            return userKeyManager.getKey(user);
063        }
064    
065        /**
066         * Returns a user, for a given key.
067         */
068        public synchronized String getUser(ID key) {
069            return userKeyManager.getValue(key);
070        }
071    
072        /**
073         * Add an external user.
074         */
075        public synchronized void addUser(String user) {
076            userKeyManager.add(user,null);
077            saveToFile(null);
078        }
079    
080        /**
081         * Returns all users that are stored in memory.
082         */
083        public synchronized String[] getAllUsers() {
084            return userKeyManager.getAllValues();
085        }
086        
087        /**
088         * Verifies that the users specified in the <code>FileCollection</code> object exists.
089         */
090        public synchronized ResponseCollection checkUsersExistance(FileCollection files) {
091            ResponseCollection responses = new ResponseCollection();
092            MissingUsersResponse missingResponse = new MissingUsersResponse();
093    
094            for(int i=0;i<files.getFileCount();i++) {
095                SharedFile file = files.getFile(i);
096                String[] users = file.getSharedToUsers();
097                if(users != null) {
098                    for(int j=0;j<users.length;j++) {
099                        ID id = userKeyManager.getKey(users[j]);
100                        if(id == null) {
101                            missingResponse.addMissingUsers(users[j]);
102                        }
103                    }
104                }
105            }       
106    
107            if(missingResponse.hasMissingUsers()) {
108                missingResponse.setError(true);
109                missingResponse.setOrigin("UserManager");
110                missingResponse.setUser("localhost");
111                responses.addResponse(missingResponse);
112            }
113    
114            return responses;
115        }
116    
117        /**
118         * Verifies that the given user exists.
119         */
120        public synchronized boolean checkUserExistance(String user) {
121            ID id = userKeyManager.getKey(user);
122            return (id!=null);
123        }
124        
125        /**
126         * Returns information about the external users which the daemon
127         * has knowledge of.
128         */
129        public synchronized ResponseCollection viewUsers() {
130            //return new ResponseCollection();
131            System.out.println("View users");
132    
133            String[] users = userKeyManager.getAllValues();
134            ExistingUserResponse existingUsers = new ExistingUserResponse();
135            ResponseCollection responses = new ResponseCollection();
136    
137            existingUsers.setExistingUsers(users);
138            existingUsers.setOrigin("UserManager");
139            existingUsers.setError(false);
140            existingUsers.setUser(sharpster.daemon.SharpsterDaemon.getPeerName());
141            
142            responses.addResponse(existingUsers);
143            return responses;
144        }
145    
146        /**
147         * Returns information about which files the external users, which the
148         * daemon has knowledge of, have shared to the user of the local client.
149         */
150        public synchronized ResponseCollection viewFileAccess() {
151            ResponseCollection responses = new ResponseCollection();
152            String[] users = userKeyManager.getAllValues();
153            
154            if(users == null) return responses;
155    
156            for(int i=0;i<users.length;i++) {
157                FileCollection files = (FileCollection)availableShares.get(users[i]);
158                if(files != null) {
159                    AccessableFilesResponse filesResponse = new AccessableFilesResponse();
160                    filesResponse.setFiles(files);
161                    filesResponse.setOrigin("UserManager");
162                    filesResponse.setUser(users[i]);
163                    filesResponse.setError(false);
164                    responses.addResponse(filesResponse);
165                }
166            }       
167    
168            return responses;
169        }
170    
171        /**
172         * Adds information about files, which are shared to the user of the local client.
173         */
174        public synchronized void addFileAccess(FileCollection files, String fromUser) {
175            availableShares.put(fromUser, files);
176        }
177    
178        /**
179         * Saves the user information to a configuration file.
180         */
181        public synchronized boolean saveToFile(String file) {
182            if(file == null) {
183                file = configFile;
184            }
185            else {
186                configFile = new String(file);
187            }
188    
189            try {
190              String[] users = userKeyManager.getAllValues();
191              //  for(int i=0;i<users.length;i++) {
192              // System.out.println(users[i]);
193              // }
194              
195                StructuredDocument document = (StructuredTextDocument) 
196                    StructuredDocumentFactory.newStructuredDocument(new MimeMediaType("text/xml"), "users");
197                Element element, userElement;
198                
199                for(int i=0;i<users.length;i++) {
200                    userElement = document.createElement("user");
201                    document.appendChild(userElement);
202                    
203                    element = document.createElement("name", users[i]);
204                    userElement.appendChild(element);
205                    
206                    ID id = userKeyManager.getKey(users[i]);
207                    element = document.createElement("id", id.toString());
208                    userElement.appendChild(element);
209                }
210                
211                FileOutputStream output = new FileOutputStream(file);
212                StructuredTextDocument doc = (StructuredTextDocument)document;
213                doc.sendToStream(output);
214                output.close();
215            }
216            catch(Exception e) {
217                //e.printStackTrace();
218                return false;
219            }
220                
221            return true;
222        }
223    
224        /**
225         * Loads user information from a configuration file.
226         */
227        public synchronized boolean loadFromFile(String file) {
228            if(file == null) {
229                file = configFile;
230            }
231            else {
232                configFile = new String(file);
233            }
234    
235            try {
236                FileInputStream input = new FileInputStream(file);
237                StructuredDocument document = (StructuredTextDocument) 
238                    StructuredDocumentFactory.newStructuredDocument(new MimeMediaType("text/xml"), input);
239                
240                Enumeration users = document.getChildren();
241                ID id=null;
242                String username=null;
243    
244                while(users.hasMoreElements()) {
245                    Element user = (Element)users.nextElement();
246                    Enumeration parameters = user.getChildren();
247                    while(parameters.hasMoreElements()) {
248                        Element parameter = (Element)parameters.nextElement();
249    
250                        String key = (String)parameter.getKey();
251                        if(key.equals("name")) {
252                            username = new String((String)parameter.getValue());
253                            //System.out.println("Found username: "+username);
254                        }
255                        else if(key.equals("id")) {
256                            id = IDFactory.fromURL(IDFactory.jxtaURL((String)parameter.getValue()));
257                            //System.out.println("Found id: "+id.toString());
258                        }
259                    }
260                    if(username!=null && id!=null) userKeyManager.add(username,id);
261                }
262                input.close();
263            }
264            catch(Exception e) {
265                //e.printStackTrace();
266                return false;
267            }
268            return true;
269        } 
270    }