001    
002    /** GroupController
003     * A class that handles group management.
004     * @author Daniel Fredriksson
005     * @version 0.1
006     *
007     */
008    
009    package sharpster.daemon.groupmanagement;
010    
011    import sharpster.common.*;
012    import java.util.Hashtable;
013    import java.util.LinkedList;
014    import java.util.Iterator;
015    import java.util.Enumeration;
016    import java.util.ListIterator;
017    import java.io.FileOutputStream;
018    import java.io.FileInputStream;
019    import net.jxta.document.*;
020    import net.jxta.id.*;
021    import sharpster.daemon.usermanagement.*;
022    
023    public class GroupController {
024    
025      private UserManager userManager;
026    
027    
028      /**
029       *
030       */
031      public void initialize(UserManager um) {
032       
033        userManager = um;
034       }
035    
036      /** A table containing all the groups. */
037        private Hashtable groupTable;
038        
039    
040        /** Initialize the groupTable and read the groups from the disk. */
041        public GroupController() {
042            groupTable = new Hashtable();
043            if(!readFromDisk())
044              System.out.println("Couldn't read \"groups.cfg\".");
045        }
046    
047    
048        /** Checks if a given group exists. 
049         * @param groupName A name of a group.
050         * @return True if a group with the name groupName exists, otherwise false.
051         */
052        private boolean existGroup(String groupName) {
053            return groupTable.containsKey(groupName);
054        }
055        
056        /** Add a given group to the groups.
057         * @param group A groupname.
058         * @return A groupResponse contaning the result of the method.
059         */
060        private GroupResponse addGroup(String group) {
061            GroupClass groupClass;
062            GroupResponse groupResponse = new GroupResponse();
063            
064            if(existGroup(group))
065                groupResponse.setSubError(sharpster.common.SubError.GROUP_EXIST);
066            else {
067                groupResponse.setSubError(sharpster.common.SubError.NO_ERROR);
068                groupClass = new GroupClass();
069                groupClass.setName(group);
070                groupTable.put(group, groupClass);
071                if( !(saveToDisk() && saveToFile(group,true)))
072                  System.out.println("Couldn't write \"groups.cfg\".");
073            }
074            return groupResponse;
075        }
076        
077        /** Remove a given group from the groups.
078         * @param group A groupname.
079         * @return A groupResponse containing the result of the method.
080         */
081        private GroupResponse removeGroup(String group) {
082            GroupClass groupClass;
083            GroupResponse groupResponse = new GroupResponse();
084            
085            if(!existGroup(group))
086                groupResponse.setSubError(sharpster.common.SubError.NO_SUCH_GROUP);
087            else {
088                groupResponse.setSubError(sharpster.common.SubError.NO_ERROR);
089                groupTable.remove(group);
090                  if( !(saveToDisk() && saveToFile(group,false)))
091                  System.out.println("Couldn't write \"groups.cfg\".");
092            }
093            return groupResponse;
094        }
095        
096        /** Add a given user to a given group.
097         * @param group A groupname.
098         * @param user A username.
099         * @return A groupResponse containing the result of the method.
100         */
101        private GroupResponse addUser(String group, String user) {
102            GroupResponse groupResponse = new GroupResponse();
103            
104            if(!existGroup(group))
105                groupResponse.setSubError(sharpster.common.SubError.NO_SUCH_GROUP);
106            else if(findGroupFromString(group).isUserInGroup(user))
107                groupResponse.setSubError(sharpster.common.SubError.
108                                          USER_ALREADY_IN_GROUP);
109            else {
110                findGroupFromString(group).addUser(user);
111                groupResponse.setSubError(sharpster.common.SubError.NO_ERROR);
112                if(!saveToDisk())
113                  System.out.println("Couldn't write \"groups.cfg\".");
114            }
115            return groupResponse;
116        }
117    
118        /** Remove a given user from a given group. 
119         * @param group A groupname.
120         * @param user A username.
121         * @return A groupResponse containing the result of the method.
122         */
123        private GroupResponse removeUser(String group, String user) {
124            GroupResponse groupResponse = new GroupResponse();
125            
126            if(!existGroup(group))
127                groupResponse.setSubError(sharpster.common.SubError.NO_SUCH_GROUP);
128            else if(!findGroupFromString(group).isUserInGroup(user))
129                groupResponse.setSubError(sharpster.common.SubError.
130                                          USER_NOT_IN_GROUP);
131            else {
132                findGroupFromString(group).removeUser(user);
133                groupResponse.setSubError(sharpster.common.SubError.NO_ERROR);
134                if(!saveToDisk())
135                  System.out.println("Couldn't write \"groups.cfg\".");
136            }
137            return groupResponse;
138        }
139    
140    
141        /** Save the group data to disk. 
142         * @return True if the groupinformation was successfully written,
143         * otherwise false.
144         * @throws Exception if the groupinformation couldn't be written.
145         */
146        private boolean saveToDisk() {
147    
148            StructuredDocument document;
149            Element groupElement, userElement;
150            Iterator groupsIterator, usersIterator;
151            String groupName;
152            
153            try {
154                document = (StructuredTextDocument)
155                    StructuredDocumentFactory.newStructuredDocument(new 
156                      MimeMediaType("text/xml"), "groups");
157                
158                groupsIterator = groupTable.keySet().iterator();
159                
160                while(groupsIterator.hasNext()) { 
161                    groupName = (String)groupsIterator.next();
162                    groupElement = document.createElement("group");
163                    document.appendChild(groupElement);
164                    
165                    groupElement.appendChild(document.createElement("name", 
166                                                                    groupName));
167                    
168                    usersIterator = findGroupFromString(groupName).getUsers().
169                      iterator();
170                    while(usersIterator.hasNext()) {
171                        userElement = document.createElement("user", 
172                                                             usersIterator.next());
173                        groupElement.appendChild(userElement);
174                    } // UserIterator
175                } // GroupIterator
176                
177                // annan fil...
178                FileOutputStream output = new FileOutputStream("config/groups.cfg");
179                document.sendToStream(output);
180                output.close();
181            } // try
182            catch(Exception e) {
183              //e.printStackTrace();
184                return false;
185            }
186            return true;
187        }
188        
189            
190        /** Read the groups file from disk.
191         * @return True if the groupinformation was successfully read,
192         * otherwise false
193         * @throws Exception is thrown if the groupinformation couldn't be read.
194         */
195        private boolean readFromDisk() {
196            FileInputStream input;
197            StructuredDocument document;
198            Enumeration groupsEnum, groupEnum;
199            Element element;
200            String currentGroup="";
201    
202            try {
203                input = new FileInputStream("config/groups.cfg");
204                
205                document = (StructuredTextDocument)
206                    StructuredDocumentFactory.newStructuredDocument(new 
207                      MimeMediaType("text/xml"), input);
208                groupsEnum = document.getChildren(); // "groups" level
209                
210                while(groupsEnum.hasMoreElements()) { // "group" level
211                    groupEnum = ((Element)groupsEnum.nextElement()).getChildren();
212             
213                    while(groupEnum.hasMoreElements()) { // "name", "user" level
214                        element = (Element)groupEnum.nextElement();
215    
216                        // getting the name of a group, add the group
217                        if(element.getKey().equals("name")) {
218                            currentGroup = (String)element.getValue();
219                            addGroup((String)element.getValue());
220                        }
221    
222                        // getting a user in a group
223                        // add the user to the last read group
224                        // or return false
225                        else if(element.getKey().equals("user")) {
226                            if(currentGroup.length()==0) {
227                                System.out.println("user before name in user.cfg");
228                                return false; 
229                            }
230                        
231                            else
232                                addUser(currentGroup, (String)element.getValue());
233                        }
234    
235                        // getting something that doesn't belong in the file
236                        // return false
237                        else {
238                            System.out.println("Error in user.cfg");
239                            return false;
240                        }
241                    }
242                    currentGroup="";
243                }
244            }
245            catch(Exception e) {
246              //e.printStackTrace();
247                return false;
248            }
249            // file was read ok, return true
250            return true;
251        }
252            
253                
254        /** List all the groups.
255         * @return A groupResponse containing a list with all the groups. 
256         */
257        private GroupResponse listGroups() {
258            GroupResponse groupResponse = new GroupResponse();
259            LinkedList groups = new LinkedList();
260            groups.addAll(groupTable.keySet());
261            groupResponse.setGroups(groups);
262            groupResponse.setSubError(sharpster.common.SubError.NO_ERROR);
263            return groupResponse;
264        }
265    
266            
267        /** Returns a list containing all the users in a given group. 
268         * @param group A groupname.
269         * @return A groupResponse contaning a list with all the users in the 
270         * group
271         */
272        private GroupResponse listUsersInGroup(String group) {
273            GroupResponse groupResponse = new GroupResponse();
274            LinkedList users = new LinkedList();
275            if(!existGroup(group))
276                groupResponse.setSubError(sharpster.common.SubError.NO_SUCH_GROUP);
277            else {
278                users.addAll(findGroupFromString(group).getUsers());
279                groupResponse.setUsers(users);
280                groupResponse.setSubError(sharpster.common.SubError.NO_ERROR);
281            }
282            return groupResponse;
283        }
284                
285    
286        /** Returns all groups and all users. 
287         * @return A groupResponse contaning a list with all the groups
288         * and a list with all the users.
289         */
290        private GroupResponse listAll() {
291            GroupResponse groupResponse = new GroupResponse();
292            LinkedList groups = new LinkedList();
293            LinkedList users = new LinkedList();
294            ListIterator groupsIterator;
295            String Dummy = "!!SHARPSTER--DUMMY!!";
296            GroupClass group;
297            
298            groups.addAll(groupTable.keySet());
299            groupResponse.setGroups(groups);
300            
301            groupsIterator = groups.listIterator();
302            System.out.println(groups);
303            while(groupsIterator.hasNext()) {
304                group = (GroupClass)findGroupFromString((String)groupsIterator.
305                                                        next());
306                users.addAll(group.getUsers());
307                users.add(Dummy);
308            }
309    
310            // remove the last !!SHARPSTER--DUMMY!!
311            if(!users.isEmpty())
312              users.removeLast();
313    
314            groupResponse.setUsers(users);
315            return groupResponse;
316        }
317        
318    
319        /** Return the GroupClass for a given string representation of a group.
320         * @param group A groupname.
321         * @return A group with the given name.
322         */
323        private GroupClass findGroupFromString(String group) {
324            return (GroupClass)groupTable.get(group);
325        }
326    
327    
328        /** Returns a list containing a given user as the first element followed
329         * by every group the user is a memeber of. 
330         * @param user A username.
331         * @return A list containing all the groups the user is a member of.
332         */
333        public LinkedList getGroups(String user) {
334            LinkedList userGroups = new LinkedList();
335            Iterator groupsIterator;
336            GroupClass group;
337    
338            groupsIterator = groupTable.keySet().iterator();
339            userGroups.add(user);
340    
341            while(groupsIterator.hasNext()) {
342                group = (GroupClass)findGroupFromString((String)groupsIterator.
343                                                        next());
344                if( group.isUserInGroup(user))
345                    userGroups.add(group.getName());
346            }
347     
348            return userGroups;
349        }
350    
351        /** Recieves a groupcommand, executes the given command and returns
352         * the result.
353         * @param command A groupcommand.
354         * @return A responseCollection contaning the result of the command. 
355         */
356        public ResponseCollection groupCommand(GroupCommand command) {
357            GroupResponse groupResponse = new GroupResponse();
358            ResponseCollection response = new ResponseCollection();
359    
360            switch(command.command) {
361                case sharpster.common.SubCommand.ADD_USER :
362                    groupResponse = addUser(command.group, command.user);
363                    break;
364                case sharpster.common.SubCommand.REMOVE_USER :
365                    groupResponse = removeUser(command.group, command.user);
366                    break;
367                case sharpster.common.SubCommand.LIST_GROUPS :
368                    groupResponse = listGroups();
369                    break;
370                case sharpster.common.SubCommand.LIST_ALL :
371                    groupResponse = listAll();
372                    break;
373                case sharpster.common.SubCommand.LIST_USERS_IN_GROUP :
374                    groupResponse = listUsersInGroup(command.group);
375                    break;
376                case sharpster.common.SubCommand.ADD_GROUP :
377                    groupResponse = addGroup(command.group);
378                    break;
379                case sharpster.common.SubCommand.REMOVE_GROUP :
380                    groupResponse = removeGroup(command.group);
381                    break;  
382                default :
383                  System.out.println("GM: Unknown Group Command.");
384            }
385    
386            if(groupResponse.getSubError()==sharpster.common.SubError.NO_ERROR)
387              groupResponse.setError(false);
388            else
389              groupResponse.setError(true);
390            groupResponse.setOrigin("GroupManagement");
391            groupResponse.setCommand(command.command);
392            response.addResponse(groupResponse);
393            return response;
394        } 
395     
396      /**
397       * Saves the user information to a configuration file.
398       
399       */
400      public boolean saveToFile(String name, boolean add) {
401        
402        
403        
404        try {
405          if (add) {
406            userManager.userKeyManager.add(name, null);
407          }
408          else {
409            userManager.userKeyManager.remove(name);
410          }
411    
412          String[] users = userManager.userKeyManager.getAllValues();
413          
414          StructuredDocument document = (StructuredTextDocument) 
415            StructuredDocumentFactory.newStructuredDocument(new MimeMediaType("text/xml"), "users");
416          Element element, userElement;
417                
418          for(int i=0;i<users.length;i++) {
419            userElement = document.createElement("user");
420            document.appendChild(userElement);
421                    
422            element = document.createElement("name", users[i]);
423            userElement.appendChild(element);
424                    
425            ID id = userManager.userKeyManager.getKey(users[i]);
426            element = document.createElement("id", id.toString());
427            userElement.appendChild(element);
428          }
429                
430          FileOutputStream output = new FileOutputStream("config/users.cfg");
431          StructuredTextDocument doc = (StructuredTextDocument)document;
432          doc.sendToStream(output);
433          output.close();
434        }
435        catch(Exception e) {
436          //e.printStackTrace();
437          return false;
438        }
439                
440        return true;
441      }
442    
443      
444    }
445    
446    
447    
448