File: UserManager.java

package info (click to toggle)
cronometer 0.9.9%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 8,732 kB
  • sloc: java: 17,382; xml: 909; makefile: 19; sh: 18
file content (527 lines) | stat: -rw-r--r-- 16,815 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/*
 *******************************************************************************
 * Copyright (c) 2005 Chris Rose and AIMedia
 * All rights reserved. CRONUser and the accompanying materials
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     Chris Rose
 *     Simon Werner
 *******************************************************************************/
package ca.spaz.cron.user;

import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JFrame;

import ca.spaz.cron.CRONOMETER;
import ca.spaz.gui.ErrorReporter;
import ca.spaz.gui.WrapperDialog;
import ca.spaz.util.*;

/**
 * A CRONOMETER-specific, property-based <code>User</code> implementation. This 
 * class stores all the global settings for all users and manages the list of 
 * individual <code>User</code>'s in CRONOMETER.
 * 
 * @author Simon Werner
 */
public class UserManager {
   

   private static final String LAST_BUILD = "last.build";
   private static final String CHECK_FOR_UDAPTES = "check.for.updates";
   private static final String HIDE_WHEN_MINIMIZED = "hide.when.minimized";
   private static final String SETTINGS_FILE = "Settings.xml";
   private static final String OLD_SETTINGS_FILE = "user.settings";
   private static final String MAIN_WINDOW = "main.window";
   private static final String LAST_USER = "last.user";
   private static final String FIRST_CRON_RUN = "first.cron.run";
   private static final String DIET_DIVIDER = "diet.divider";

   private static String subdirectory = "cronometer";
   private static UserManager instance = null;
   private static Settings settings;
   private static User currentUser;
   private static List<User> userList;
   private static List<UserChangeListener> listeners;
   private static User lastSelectedUser = null;

   // TODO: Should not hardcode these
   public static final String userFileList[] = { 
      "biomarkers.xml", "metrics.xml", "notes.xml", "servings.xml" };
      
   public static final UserManager getUserManager() {
      if (null == instance) {
         instance = new UserManager();
      }
      return instance;
   }
   
   public UserManager() {
      if (settings == null) {
         settings = new Settings(Settings.TAG_GENERAL);
         userList = settings.loadSettings(getSettingsFile());
         settings.save();
         setCurrentUser(getLastUser());
      }
   }

   /**
    * Get the last user that used CRON-o-meter.
    */
   public User getLastUser() {
      User user = getUser(getLastUsername());
      if (user == null) {
         user = getUserList().get(0);
      }
      return user;
   }
   
   /**
    * Get the last username that used CRON-o-meter, the last time it was run.
    * @return
    */
   public String getLastUsername() {
      return settings.get(LAST_USER, "Default User");
   }
   
   /**
    * Open the dialog to manage the users.
    */
   public static void startUserManagerDialog() {
      WrapperDialog.showDialog(CRONOMETER.getInstance(), new UserManagerDialog(), true);      
   }

   public void saveUserProperties() throws IOException {
      settings.save();
   }
   
   /**
    * Add a new user to Cronometer via the UI.
    * @param parentWindow allow a popup to set the user settings
    * @return the user that was just added.
    */
   public void addUser(JComponent parentWindow) {
      User user = new User(new Settings(Settings.TAG_USER));
      setCurrentUser(user);
      addUser(user);
      user.doFirstRun(parentWindow);
      settings.save();
   }
   
   /**
    * Add a new user to Cronometer
    * @param user the user to add.
    */
   public void addUser(User user) {
      userList.add(user);
      settings.save();
   }
   
   /**
    * Find the User with the given username
    * @param username the name of the user
    * @return User the Object that relates to the given name.  Null if the User is not found.
    */
   public User getUser(String username) {
      return getUser(getUserList(), username);
   }
   
   /**
    * Find the User with the given username
    * @param username the name of the user
    * @return User the Object that relates to the given name.  Null if the User is not found.
    */
   public static User getUser(List<User> uList, String username) {
      Iterator<User> it = uList.iterator();
      User user = null;
      
      while (it.hasNext()) {
         user = it.next();
         if (username.equals(user.getUsername())) {
            return user;
         }
      }
      return null;
   }

   /**
    * Delete a user from Cronometer.
    * @param user the user Object to delete.
    */
   public void deleteUser(User user) {
      userList.remove(user);
      deleteFiles(user);
      if (currentUser == user) {
         // Make sure we select a new currentUser, find the first active user
         setCurrentUser(getUserList().get(0));
      }
      settings.save();
   }
   
   /**
    * Delete all the settings file related to this user.
    * @param user
    */
   public void deleteFiles(User user) {
      File userDir = getUserDirectory(user);
      if (userDir.exists()) {
         int i;
         for (i=0; i<userFileList.length; i++) {
            File userFile = new File(userDir.getAbsolutePath(), userFileList[i]);
            if (userFile.exists()) {
               if (!userFile.delete()) {
                  Logger.error("Unable to delete the file: " + userFile.getAbsolutePath());
               }
            }
         }
         if (!userDir.delete()) {
            Logger.error("Unable to delete the folder: " + userDir.getAbsolutePath());
         }
      }
   }
   
   
   /**
    * Delete the user with the given <code>username</code>
    * @param username the name of the user
    * @return true if the delete was succesful
    */
   public boolean deleteUser(String username) {
      User user = getUser(username);
      if (userExists(username)) {
         deleteUser(user);
         return true;
      }
      return false;
   }
   
   public static User getCurrentUser() {
      return currentUser; 
   }
   
   public void setCurrentUser(User user) {
      if (user == null || currentUser == user) {
         return;
      }
      if (currentUser != null) {
         currentUser.saveUserData();
      }
      currentUser = user;
      settings.set(LAST_USER, currentUser.getUsername());
      this.notifyUserChangeListeners();
   }
   
   /**
    * Search for a user and set that user as the current user.  
    * @param username the name of the user
    * @return true if the operation was successful
    */
   public boolean setCurrentUser(String username) {
      User user = getUser(username);
      if (user != null) {
         setCurrentUser(user);
         return true;
      } else {
         return false;
      }
   }
   
   public static List<User> getUserList() {
      return userList;
   }
   
   /**
    * Sets the subdirectory to use for user data. 
    * @param aSubdirectory
    */
   public static void setSubdirectory(String aSubdirectory) {
      subdirectory = aSubdirectory;
   }
 
   /**
    * Gets the subdirectory being used for user data.
    */
   public static String getSubdirectory() {
      return subdirectory;
   } 
   
   public static File getCronometerDirectory() {
      File appDir = ToolBox.getUserAppDirectory(UserManager.getSubdirectory());
      if (!appDir.exists()) {
         appDir.mkdirs();
         if (!appDir.exists()) {
            Logger.error("Unable to create user app prefs directory " + appDir);
         }
      }
      return appDir;
   }

   public static File getUserDirectory(User user) {
      File userDir = new File(getCronometerDirectory(), user.getUsername());
      if (!userDir.exists()) {
         userDir.mkdirs();
         if (!userDir.exists()) {
            Logger.error("Unable to create user app prefs directory " + userDir);
         }
      }
      return userDir;
   }
   
   /**
    * Upgrade the settings file to the multiuser style.
    * @param inFile the old "user.settings" file
    * @param outFile the new filename, "Settings.xml".
    */
   private void upgradeToMultiuser(File inFile, File outFile) {
      // Move the User files to the new location
      String cronPath = UserManager.getCronometerDirectory().getAbsolutePath();
      moveUserFiles(cronPath, cronPath, User.DEFAULT_USERNAME);
      
      // Update the settings file
      if (inFile.exists() && outFile.exists()) {
         // This condition should never occur
          //System.err.println("Error: Upgrade of old settings file failed.  Please contact the CRON-o-meter developers.");
      //    System.exit(-1);
      }
      
      if (!inFile.exists()) return;
      
      if (!outFile.exists()) {
         try {
              InputStream in = new BufferedInputStream(new FileInputStream(inFile));
              PrintStream out = new PrintStream(
                      new BufferedOutputStream(new FileOutputStream(outFile)));
              Settings.convertSettingsFile(in, out);
              out.close();
              in.close();
              //inFile.renameTo(new File(inFile.getParent(), "backup"));             
         } catch (Exception e) {
              e.printStackTrace();
         }
      }
   }
   
   public void moveUserFiles(String oldUserDirStr, String newBaseDir, String newUsername) {
      try {
         File oldUserDir = new File(oldUserDirStr);
         File newUserDir = new File(newBaseDir, newUsername);
   
         Logger.log(oldUserDir.getAbsolutePath());
         if (!oldUserDir.exists()) {
            Logger.error("Unable to find the old user directory.");
            return;
         }
         
         if (!newUserDir.exists()) {
            newUserDir.mkdir();
         }
         
         int i;
         for (i=0; i<userFileList.length; i++) {
            File oldUserFile = new File(oldUserDir.getAbsolutePath(), userFileList[i]);
            File newUserFile = new File(newUserDir.getAbsolutePath(), userFileList[i]);
            if (oldUserFile.renameTo(newUserFile)) {
               Logger.log(oldUserFile.getAbsolutePath() + " moved to " + newUserFile.getAbsolutePath());
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   
   public File getSettingsFile() {
      File settingFile = new File(getCronometerDirectory(), SETTINGS_FILE);
      File oldSettingFile = new File(getCronometerDirectory(), OLD_SETTINGS_FILE);

      Logger.debug("Initializing settings file " + settingFile.getAbsolutePath());
      if (oldSettingFile.exists()) {
         Logger.debug("Upgrading settings file " + settingFile.getAbsolutePath());
         upgradeToMultiuser(oldSettingFile, settingFile);
      } else if(!settingFile.exists()) {
         Logger.debug("Creating settings file " + settingFile.getAbsolutePath());
         try {
            if (settingFile.createNewFile()) {
               // Nothing.  All is well.
            } else {
               Logger.error("Unable to create settings file");
            }
         } catch (IOException e) {
            Logger.error("getSettingsFile()", e);
            ErrorReporter.showError(e, CRONOMETER.getInstance()); 
         }
      } else {
         // Nothing.  All is well.
      }
      return settingFile;
   }
   
   public void setLastBuild(int build) {
      settings.set(LAST_BUILD, build);         
   }

   public int getLastBuild() {
      return settings.getInt(LAST_BUILD, 0);
   }

   public void setCheckForUpdates(boolean val) {
       /* We don't want our users ever enabling this feature and screwing up
        * their system. Always leave as false. */
      settings.set(CHECK_FOR_UDAPTES, false);
      notifyUserChangeListeners();
   }

   public boolean getCheckForUpdates() {
       /* Never return true, we don't want users to manually upgrade cronometer
        * unless they know what they're doing. */
      //return settings.getBoolean(CHECK_FOR_UDAPTES, true);
      return false;
   }
   
   public void setHideWhenMinimized(boolean state) { 
      settings.set(HIDE_WHEN_MINIMIZED, state);
   }
   
   public boolean getHideWhenMinimized() {
      return settings.getBoolean(HIDE_WHEN_MINIMIZED, false);
   }

   public void saveWindow(JFrame frame) {
      try {
         frame.setVisible(true);
         settings.set(MAIN_WINDOW +".width", frame.getWidth());
         settings.set(MAIN_WINDOW +".height", frame.getHeight());
         settings.set(MAIN_WINDOW +".x", frame.getLocationOnScreen().x);
         settings.set(MAIN_WINDOW +".y", frame.getLocationOnScreen().y);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
   
   public void restoreWindow(JFrame frame, Point p) {      
      Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
      Dimension screen = defaultToolkit.getScreenSize();
      int x = settings.getInt(MAIN_WINDOW +".x", p.x);
      int y = settings.getInt(MAIN_WINDOW +".y", p.y);
      int w = settings.getInt(MAIN_WINDOW +".width", frame.getWidth());
      int h = settings.getInt(MAIN_WINDOW +".height", frame.getHeight());
      if (x < 0 || x+w*0.10 > screen.width) {
         x = p.x;
         //w = frame.getWidth();
      }
      if (y < 0 || y+h*0.10 > screen.height) {
         y = p.y;
         //h = frame.getHeight();
      }
      frame.setLocation(x, y);
      frame.setSize(w, h);       
   }

   public boolean firstCronRun() {
      return settings.getBoolean(FIRST_CRON_RUN, true);
   }

   public void setFirstCronRun(boolean val) {
      settings.set(FIRST_CRON_RUN, val);
      notifyUserChangeListeners();
   }
   
   public void setDietDivider(int val) { 
      settings.set(DIET_DIVIDER, val); 
   }
   
   public int getDietDivider(int val) { 
      return settings.getInt(DIET_DIVIDER, val); 
   }

   /**
    * Search if the given username exists
    * @param username
    * @return
    */
   public boolean userExists(String username) {
      return getUser(username) != null;
   }

   public static boolean renameUserDirectory(User oldUser, String newName) {
      File userDir = getUserDirectory(oldUser); 
      if (!userDir.renameTo(new File(getCronometerDirectory(), newName))) {
         System.err.println("Unable to rename the user folder");
         return false;
      }
      return true;
         
   }

   private List<UserChangeListener> getListeners() {
      if (null == listeners) {
         listeners = new ArrayList<UserChangeListener>();
      }
      return listeners;
   }
   
   public final void addUserChangeListener(UserChangeListener l) {
      if ( ! getListeners().contains(l)) {
         getListeners().add(l);
      }
   }

   protected final void notifyUserChangeListeners() {
      List l = getListeners();
      for (Iterator iter = l.iterator(); iter.hasNext();) {
         UserChangeListener listener = (UserChangeListener) iter.next();
         listener.userChanged(this);
      }
      CRONOMETER.getInstance().setTitle(CRONOMETER.getFullTitleWithUser());
   }
   
   public final void removeUserChangeListener(UserChangeListener l) {
      getListeners().remove(l);
   }

   /**
    * Get the number of users that the UserManager class is managing.
    * @return the number of users
    */
   public int numberOfUsers() {
      return userList.size();
   }

   /**
    * Return any user, except the current user.  If the lastSelectedUser has been set, then 
    * return the lastSelectedUser.
    * @return any user
    */
   public static User selectOtherUser() {
      List<User> uList = getOtherUsers();
      if (uList.size() == 0) {
         return null;
      }
      if (lastSelectedUser == null || lastSelectedUser == currentUser) {
         lastSelectedUser = uList.get(0);
      }
      return lastSelectedUser;
   }

   /**
    * Return the list of users, but does not include the current user.
    * @return the list of Users
    */
   public static List<User> getOtherUsers() {
      ArrayList<User> uList = new ArrayList<User>(userList);
      uList.remove(getCurrentUser());
      return uList;
   }

   public static void setLastSelectedUser(User user) {
      lastSelectedUser = user;
   }
}