001     
002    /*****************************************************************************
003    
004        jBudget.
005        Copyright (C) 2006  Dmitri Petrov
006    
007        This program is free software: you can redistribute it and/or modify
008        it under the terms of the GNU General Public License as published by
009        the Free Software Foundation, either version 3 of the License, or
010        (at your option) any later version.
011    
012        This program is distributed in the hope that it will be useful,
013        but WITHOUT ANY WARRANTY; without even the implied warranty of
014        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015        GNU General Public License for more details.
016    
017        You should have received a copy of the GNU General Public License
018        along with this program.  If not, see <http://www.gnu.org/licenses/>.
019     
020    *****************************************************************************/
021    
022    /*
023     * DataManager.java
024     *
025     * Created on April 18, 2006, 6:33 PM
026     */
027    
028    package org.jbudget.io;
029    
030    import org.jbudget.Core.TransactionFilter;
031    import java.io.File;
032    import java.io.IOException;
033    import java.util.ArrayList;
034    import java.util.Calendar;
035    import java.util.Collections;
036    import java.util.Comparator;
037    import java.util.Date;
038    import java.util.GregorianCalendar;
039    import java.util.List;
040    import java.util.TimerTask;
041    import java.util.prefs.BackingStoreException;
042    import java.util.prefs.Preferences;
043    import javax.swing.JFrame;
044    import javax.swing.JOptionPane;
045    import org.jdom.JDOMException;
046    import org.jbudget.Main;
047    import org.jbudget.Core.Account;
048    import org.jbudget.Core.Budget;
049    import org.jbudget.Core.Month;
050    import org.jbudget.Core.SharedPreferences;
051    import org.jbudget.Core.Transaction;
052    import org.jbudget.Core.User;
053    import org.jbudget.gui.DirectoryLocationDialog;
054    import org.jbudget.gui.user.InitializationWisardDialog;
055    import org.jbudget.gui.user.UserPreferences;
056    import org.jbudget.util.DateFormater;
057    import org.jbudget.util.Pair;
058    
059    /**
060     * A singleton class that is used to manage all the data in the program.
061     * It is responsible for saving and reading data from the disk. It is also 
062     * responsible for making sure that the data on the disk is synchronized with
063     * the data in memory.
064     *
065     * @author petrov
066     */
067    public class DataManager extends EventDispatcher
068    {
069    
070        private static final boolean TESTING = false;
071        
072        private static final Preferences defaultPreferences =
073                    Preferences.userNodeForPackage(DataManager.class);
074        
075        private final Preferences myPreferences;
076        /** Index of the data available on the primary storage.
077         *  Usually this is a hard drive, but we want the interface to be 
078         *  extensible so that, other types of storage can be accommodated. */
079        private DataIndex primaryDataIndex;
080        /** Primary storage component. Used for reading/saving data */
081        private StorageInterface primaryStorage;
082        /** Index of the data that has already been loaded in memory */
083        private final DataIndex availableDataIndex = new DataIndex(true);
084        /** Calendar instance that is used inside the object */
085        private final Calendar calendar = new GregorianCalendar();
086        /** the only instance of DatatManager */
087        private static DataManager theManager = new DataManager(defaultPreferences);
088        /** Was a check for an new/empty data directory performed? */
089        private boolean newDirectoryCheck = false;
090        /** Did we just create a new data directory ? */
091        private boolean newDataDir = false;
092        /** Current User */
093        private User currentUser = User.UNKNOWN;
094        /** Main window. (Used for displaying exception dialogs) */
095        private JFrame mainWindow = null;
096        /** Timer that is used to periodically save the data to permanent storage. */
097        java.util.Timer timer = new java.util.Timer();
098    
099        //=========================== Constructor ================================//
100        
101        /** Creates a new instance of DataManager */
102        private DataManager(Preferences ioPreferences)
103        {
104            myPreferences = ioPreferences;
105            String dataDir;
106            if (TESTING) {
107                dataDir = "./TestData";
108            } else {
109                dataDir = ioPreferences.get(PrefKeys.MAIN_DIR, PrefDef.MAIN_DIR);
110                if (Main.debug) {
111                    System.out.println("Working directory from preferences:");
112                    System.out.println(dataDir);
113                }
114                boolean flag = true;
115                if (dataDir == null || dataDir.length() == 0) {
116                    flag = false;
117                }
118                if (flag) {
119                    File dir = new File(dataDir);
120                    if (dir.isFile()) {
121                        if (Main.debug) {
122                            System.out.println(
123                                    "Data directory read from preferences is a file. " + dir);
124                        }
125                        flag = false;
126                    } else if ((!dir.exists()) && (!dir.mkdirs())) {
127                        if (Main.debug) {
128                            System.out.println(
129                                    "Can not create data directory. No write permission? " + dir);
130                        }
131                        flag = false;
132                    }
133                }
134    
135                if (!flag) {
136                    File dir = DirectoryLocationDialog.showDialog(mainWindow);
137    
138                    if (dir == null) {
139                        if (Main.debug) {
140                            System.out.println("No data directory. Exiting");
141                        }
142                        System.exit(1);
143                    }
144                    dataDir = dir.getAbsolutePath();
145                    ioPreferences.put(PrefKeys.MAIN_DIR, dataDir);
146                }
147    
148            }
149    
150            primaryStorage = null;
151            try {
152                primaryStorage = new LocalStore(dataDir);
153            } catch (Exception ex) {
154                handleException(ex);
155            }
156            if (primaryStorage != null) {
157                primaryDataIndex = primaryStorage.getDataIndex();
158            } else {
159                primaryDataIndex = new DataIndex(false);
160            }
161            
162            // Start the timer task that will periodically save the data.
163            timer.schedule(new CommitTimerTask(), 300000, 300000);
164        }
165    
166        //============================= INSTANCES ================================//
167        
168        /** Returns the default instance of the DataManager. Uses default preferences 
169         */
170        public static DataManager getInstance()
171        {
172            if (!theManager.newDirectoryCheck) 
173            {
174                theManager.newDirectoryCheck = true;
175                if (theManager.primaryStorage.isNewDataInidex()) 
176                {
177                    new InitializationWisardDialog(theManager.mainWindow);
178                    theManager.newDataDir = true;
179                }
180            }
181            return theManager;
182        }
183    
184        /** Creates a new instance of the DataManager from the defauld preference
185         * object for the program. This has to be done if the preferences has changes
186         * in such a way that the DataManager instance becomes invalid. For example, 
187         * if the storage directory was changes by the user.
188         */
189        public static DataManager getNewInstance()
190        {
191            if (theManager != null) 
192                theManager.close();
193            
194            DataManager oldManager = theManager;
195    
196            theManager = new DataManager(defaultPreferences);
197            theManager.newDirectoryCheck = true;
198            if (theManager.primaryStorage.isNewDataInidex()) 
199            {
200                new InitializationWisardDialog(theManager.mainWindow);
201                theManager.newDataDir = true;
202            }
203            
204            oldManager.fireDataDirChanged();
205    
206            return theManager;
207        }
208    
209        /** Returns a customized version of the DataManager that uses Preferences 
210         *  different from the default. This method exists for testing only.
211         */
212        public static DataManager getCustomizedInstance(Preferences ioPreferences)
213        {
214            return new DataManager(ioPreferences);
215        }
216    
217        /** Commits all cached data to permanent storage, disposes of any resources
218         *  that were allocated in the constructor (i.e., closes network connections).
219         */
220        public void close()
221        {
222            // Stop the commit timer.
223            timer.cancel();
224            
225            // Now save everything.
226            saveAllMonths();
227            try
228            {
229                primaryStorage.commit();
230            } 
231            catch (Exception ex)
232            {
233                handleException(ex);
234            }
235            if (TESTING)
236            {
237                try
238                {
239                    myPreferences.put(PrefKeys.MAIN_DIR, "");
240                    myPreferences.flush();
241                    myPreferences.sync();
242                } 
243                catch (BackingStoreException ex)
244                {
245                    System.out.println("Could not clear preferences. " +
246                                       "BackingStroeException.");
247                }
248            }
249        }
250        
251        //============================= ACCESSORS ================================//
252        
253        /** Returns true if a new data directory was created when the program 
254         * was started.
255         */
256        public boolean isNewDataDir() 
257        {
258            return newDataDir;
259        }
260        
261        /** Returns a string describing the current storage interfaces used 
262         * by the DataManager. */
263        public String getIdString() 
264        {
265            if (primaryStorage == null)
266                return "No data source.";
267            return primaryStorage.getIdString();
268        }
269    
270        //===============================  MONTHS  ==============================//
271        
272        /** Returns a List of valid years. For each year in the list there is at least
273         * one record for a month belonging to this year. */
274        public synchronized List<Integer> getValidYears()
275        {
276            return primaryDataIndex.getValidYears();
277        }
278    
279        /** Returns a list of valid months for a given year. */
280        public synchronized List<Integer> getValidMonths(int cYear)
281        {
282            return primaryDataIndex.getValidMonths(cYear);
283        }
284    
285        /** Returns a list of valid months for a given year. */
286        public synchronized List<Integer> getValidMonths(Integer iYear)
287        {
288            return primaryDataIndex.getValidMonths(iYear.intValue());
289        }
290    
291        /** Returns true if the given Date corresponds to a valid month. */
292        public synchronized boolean isValidMonth(Date d)
293        {
294            calendar.setTime(d);
295    
296            int cYear = calendar.get(Calendar.YEAR);
297            int cMonth = calendar.get(Calendar.MONTH);
298            
299            return isValidMonth(cMonth, cYear);
300        }
301    
302        /** Returns true if the given month/year combination corresponds to a valid
303         *  month.
304         */
305        public synchronized boolean isValidMonth(int cMonth, int cYear)
306        {
307            return primaryDataIndex.isValidMonth(cMonth, cYear);
308        }
309    
310        /** Returns a month object for the given month/year combination.
311         * @throws IllegalArgumentException if there is no record for this month, or
312         *         if the values given don't make sense.
313         */
314        public synchronized Month getMonth(int cMonth, int cYear)
315        {
316            if (availableDataIndex.isValidMonth(cMonth, cYear)) {
317                return availableDataIndex.getMonth(cMonth, cYear);
318            }
319            try {
320                Month month = primaryStorage.getMonth(cMonth, cYear);
321                availableDataIndex.addMonth(month);
322                return month;
323            } catch (Exception ex) {
324                handleException(ex);
325            }
326            return null;
327        }
328    
329        /** Returns the Month object that corresponds (contains) a given date. */
330        public synchronized Month getMonth(Date d)
331        {
332            calendar.setTime(d);
333    
334            int cYear = calendar.get(Calendar.YEAR);
335            int cMonth = calendar.get(Calendar.MONTH);
336    
337            return getMonth(cMonth, cYear);
338        }
339    
340        /** Returns the first valid Month object preceeding the month given by 
341         *  the month and year combination. Returns null if there are no valid months
342         *  before the given month.
343         */
344        public synchronized Month getPreviousMonth(int cMonth, int cYear)
345        {
346            for (int m = cMonth - 1; m >= Calendar.JANUARY; m--) {
347                if (isValidMonth(m, cYear)) {
348                    return getMonth(m, cYear);
349                }
350            }
351    
352            List<Integer> validYears = new ArrayList<Integer>();
353            validYears.addAll(getValidYears());
354    
355            Collections.sort(validYears);
356            int index = Collections.binarySearch(validYears, new Integer(cYear));
357    
358            if (index == 0 || index == -1) {
359                return null;
360            }
361            if (index > 0) {
362                index--;
363            } else {
364                index = -index - 2;
365            }
366    
367            cYear = validYears.get(index).intValue();
368            List<Integer> validMonths = new ArrayList<Integer>();
369            validMonths.addAll(getValidMonths(cYear));
370            Collections.sort(validMonths);
371            cMonth = validMonths.get(validMonths.size() - 1).intValue();
372            return getMonth(cMonth, cYear);
373        }
374    
375        /** Creates a new month for the given month/year combination and saves
376         *  in in the permanent storage. Uses the budget from the closes preceeding
377         *  month. If there are no preceeding months, uses a budget with the highest
378         *  id.
379         *  @throws IllegalArguementException if this month has been created 
380         *          previously.
381         *  @throws IllegalStateException if there is no Budget that can be 
382         *          used to create a new Month.
383         *  @throws IOException if there are any problems with IO operations.
384         */
385        public synchronized Month newMonth(int cMonth, int cYear)
386        {
387            if (isValidMonth(cMonth, cYear)) {
388                throw new IllegalArgumentException("Trying to create a month that " +
389                        "already exits. Year: " + cYear + " Month: " + cMonth);
390            }
391    
392            Integer iMonth = new Integer(cMonth);
393            Integer iYear = new Integer(cYear);
394    
395            // Looking for a suitable budget.
396            // a previous month ?
397            Month prevMonth = getPreviousMonth(cMonth, cYear);
398            Budget budget = null;
399            if (prevMonth != null) {
400                budget = prevMonth.getBudget();
401            } else {
402                List<Pair<Integer, String>> budgetList = getValidBudgets();
403                if (budgetList.size() > 0) {
404                    Collections.sort(budgetList, new Comparator<Pair<Integer, String>>()
405                    {
406    
407                        public int compare(Pair<Integer, String> a, Pair<Integer, String> b)
408                        {
409                            return a.first().compareTo(b.first());
410                        }
411                    });
412                    budget = getBudget(budgetList.get(0).first().intValue());
413                }
414            }
415    
416            if (budget == null) {
417                throw new IllegalStateException("No budgets are defined. Can not create" +
418                        " a new Month object.");
419            }
420    
421            Month month = new Month(budget, cMonth, cYear);
422            addMonth(month);
423            return month;
424        }
425    
426        /** Adds and saves a given month. 
427         * @throws IllegalArgumentException if this month (a month object with 
428         *         identical month/year)  already exists.
429         */
430        public synchronized void addMonth(Month month)
431        {
432            if (isValidMonth(month.getMonth(), month.getYear())) {
433                throw new IllegalArgumentException("Trying to add a Month object " +
434                        "for a month/year that already exists: " +
435                        (new DateFormater()).formatMonth(month.getMonth()) + " " +
436                        month.getYear());
437            }
438    
439            saveMonth(month);
440            updateInitialBalances(month);
441            fireMonthAdded(month);
442        }
443    
444        /** Saves the given Month object. This has to be called every time there
445         *  is an update to a Month other than adding/removing transactions.
446         */
447        public void saveMonth(Month month)
448        {
449            primaryStorage.storeMonth(month);
450            availableDataIndex.addMonth(month);
451            fireMonthUpdated(month);
452        }
453    
454        /** Removes a month object. Deletes it from the permanent storage.
455         * @throws IllegalArgumentException if no such month exists.
456         */
457        public synchronized void removeMonth(int cMonth, int cYear)
458        {
459            Month month = getMonth(cMonth, cYear);
460            primaryStorage.removeMonth(month);
461            if (availableDataIndex.isValidMonth(cMonth, cYear)) {
462                availableDataIndex.removeMonth(month);
463                fireMonthRemoved(month.getMonth(), month.getYear());
464            }
465        }
466        
467        /** Returns a list of months that are passed by a given filter. */
468        public synchronized List<Month> getMonths(TransactionFilter filter)
469        {
470            Date currentDate = filter.startingDate;
471            calendar.setTime(currentDate);
472            calendar.set(Calendar.DAY_OF_MONTH, 1);
473            currentDate = calendar.getTime();
474    
475            List<Month> months = new ArrayList<Month>();
476            while ( currentDate.before(filter.endingDate) ||
477                    currentDate.equals(filter.endingDate) ) 
478            {
479                if (isValidMonth(currentDate))
480                    months.add(getMonth(currentDate));
481                calendar.setTime(currentDate);
482                calendar.add(Calendar.MONTH, 1);
483                currentDate = calendar.getTime();
484            }
485            
486            return months;
487        }
488    
489        //===============================   BUDGETS  ============================//
490        
491        /** Returns a list of Pairs (ID, name) of existing budgets */
492        public synchronized List<Pair<Integer, String>> getValidBudgets()
493        {
494            return primaryDataIndex.getValidBudgets();
495        }
496    
497        /** Returns a Budget object with given numeric budget ID 
498         * @throws IllegalArgumentException if there is no record of a budget with
499         *         such id.
500         * @throws IOException if there is a problem with IO.
501         */
502        public synchronized Budget getBudget(int budgetID)
503        {
504            if (availableDataIndex.isValidBudget(budgetID)) {
505                return availableDataIndex.getBudget(budgetID);
506            }
507    
508            try {
509                Budget budget = primaryStorage.getBudget(budgetID);
510                availableDataIndex.addBudget(budget);
511                return budget;
512            } catch (Exception ex) {
513                handleException(ex);
514            }
515            return null;
516        }
517    
518        /** Adds and saves a budget object.
519         *  @throws IllegalArgumentException if a budget with an ID of a new object 
520         *          already exists.
521         */
522        public synchronized void addBudget(Budget budget)
523        {
524            primaryStorage.storeBudget(budget);
525            availableDataIndex.addBudget(budget);
526            fireBudgetAdded(budget);
527        }
528    
529        /** Removes a budget with the given budget id. Checks that the budget is not
530         *  used by any months. 
531         *  @throws IllegalArgumentException if the budget is used by at least one
532         *          month, so it can not be removed.
533         */
534        public synchronized void removeBudget(int budgetID)
535        {
536            if (!isUnusedBudget(budgetID)) {
537                throw new IllegalArgumentException("Can not remove budget. It is " +
538                        "used by at least one month");
539            }
540            availableDataIndex.removeBudget(budgetID);
541            primaryStorage.removeBudget(budgetID);
542            fireBudgetRemoved(budgetID);
543        }
544    
545        /** Removes all unused budgets */
546        public synchronized void removeUnusedBudgets()
547        {
548            List<Pair<Integer, String>> unusedBudgets = getUnusedBudgets();
549            for (Pair<Integer, String> budgetInfo : unusedBudgets) {
550                int budgetID = budgetInfo.first().intValue();
551                availableDataIndex.removeBudget(budgetID);
552                primaryStorage.removeBudget(budgetID);
553                fireBudgetRemoved(budgetID);
554            }
555        }
556    
557        /** Returns true if the given budget is not used by any month. */
558        public synchronized boolean isUnusedBudget(Budget budget)
559        {
560            List<Integer> iYears = getValidYears();
561            for (Integer iYear : iYears) {
562                List<Integer> iMonths = getValidMonths(iYear.intValue());
563                for (Integer iMonth : iMonths) {
564                    Month month = getMonth(iMonth.intValue(), iYear.intValue());
565                    if (budget.equals(month.getBudget())) {
566                        return false;
567                    }
568                }
569            }
570            return true;
571        }
572    
573        /** Returns true if a budget with the given ID is not used by any month */
574        public synchronized boolean isUnusedBudget(int budgetID)
575        {
576            return isUnusedBudget(getBudget(budgetID));
577        }
578    
579        /** Returns a list of pairs of ID, name of unsuded budgets */
580        public synchronized List<Pair<Integer, String>> getUnusedBudgets()
581        {
582            List<Pair<Integer, String>> allBudgets = getValidBudgets();
583            List<Pair<Integer, String>> unusedBudgets =
584                    new ArrayList<Pair<Integer, String>>();
585            for (Pair<Integer, String> budgetInfo : allBudgets) {
586                if (isUnusedBudget(budgetInfo.first().intValue())) {
587                    unusedBudgets.add(budgetInfo);
588                }
589            }
590            return Collections.unmodifiableList(unusedBudgets);
591        }
592    
593        //=========================   Accounts   ================================//
594        
595        /** Returns a list of Pairs (ID, name) of existing accounts */
596        public synchronized List<Pair<Integer, String>> getValidAccounts()
597        {
598            List<Pair<Integer, String>> accountsInfo =
599                    new ArrayList<Pair<Integer, String>>();
600            accountsInfo.addAll(primaryDataIndex.getAccountInfo());
601            return accountsInfo;
602        }
603    
604        /** Returns an Account object with a given numeric ID 
605         * @throws IllegalArgumentException if there is no record of an Account with
606         *         such an id.
607         * @throws IOException if there is a problem with IO.
608         */
609        public synchronized Account getAccount(int accountID)
610        {
611            if (availableDataIndex.isValidAccount(accountID)) {
612                return availableDataIndex.getAccount(accountID);
613            }
614            try {
615                Account account = primaryStorage.getAccount(accountID);
616                availableDataIndex.addAccount(account);
617                return account;
618            } catch (Exception ex) {
619                handleException(ex);
620            }
621            return null;
622        }
623    
624        /** Adds and saves an account object.
625         *  @throws IllegalArgumentException if an account with an ID of a new object 
626         *          already exists.
627         */
628        public synchronized void addAccount(Account account)
629        {
630            primaryStorage.storeAccount(account);
631            availableDataIndex.addAccount(account);
632            fireAccountAdded(account);
633        }
634    
635        /** Updates an existing account object. If there is no account with such
636         *  id, calls addAccount.
637         */
638        public synchronized void updateAccount(Account account)
639        {
640            Pair<Integer, String> accountInfo = new Pair<Integer, String>(
641                    new Integer(account.getID()), account.getName());
642    
643            if (!getValidAccounts().contains(accountInfo)) {
644                addAccount(account);
645                return;
646            }
647    
648            primaryStorage.storeAccount(account);
649            fireAccountUpdated(account);
650        }
651    
652        /** Removes an account with a given id. Checks that the account is not used
653         *  in any budgets.
654         *  @throws IllegalArgumentException if the account is used by at least one
655         *          budget, so it can not be removed.
656         */
657        public synchronized void removeAccount(int accountID)
658        {
659            if (!isUnusedAccount(accountID)) {
660                throw new IllegalArgumentException("Can not remove account. It is " +
661                        "used by at least one budget");
662            }
663            availableDataIndex.removeAccount(accountID);
664            primaryStorage.removeAccount(accountID);
665            fireAccountRemoved(accountID);
666        }
667    
668        /** Returns true if a given account is not used by any budget. */
669        public synchronized boolean isUnusedAccount(Account account)
670        {
671            List<Pair<Integer, String>> list = getValidBudgets();
672    
673            for (Pair<Integer, String> pair : list) {
674                Budget budget = getBudget(pair.first().intValue());
675                List<Account> accounts = budget.getRegisteredAccounts();
676                if (accounts.contains(account)) {
677                    return false;
678                }
679            }
680    
681            return true;
682        }
683    
684        /** Returns true if an account with the given ID is not used by any budget */
685        public synchronized boolean isUnusedAccount(int accountID)
686        {
687            return isUnusedAccount(getAccount(accountID));
688        }
689    
690        /** Returns a list of pairs of ID, name of unsuded accounts */
691        public synchronized List<Pair<Integer, String>> getUnusedAccounts()
692        {
693            List<Pair<Integer, String>> allAccounts = getValidAccounts();
694            List<Pair<Integer, String>> unusedAccounts =
695                    new ArrayList<Pair<Integer, String>>();
696            for (Pair<Integer, String> accountInfo : allAccounts) {
697                if (isUnusedAccount(accountInfo.first().intValue())) {
698                    unusedAccounts.add(accountInfo);
699                }
700            }
701            return Collections.unmodifiableList(unusedAccounts);
702        }
703    
704        /** Returns a list of cash accounts for all users of the system */
705        public synchronized List<Account> getCashAccounts()
706        {
707            List<Pair<Integer, String>> info = getValidUsers();
708            List<Account> cashAccounts = new ArrayList<Account>(info.size());
709            for (Pair<Integer, String> userInfo : info) {
710                User u = getUser(userInfo.first().intValue());
711                int cashID = u.getCashAccountID();
712                if (cashID >= 0) {
713                    cashAccounts.add(getAccount(cashID));
714                }
715            }
716            return cashAccounts;
717        }
718    
719        //=========================     Users    ================================//
720        
721        /** Returns a list of Pairs (ID, name) of all users. */
722        public synchronized List<Pair<Integer, String>> getValidUsers()
723        {
724            return getValidUsers(true, true);
725        }
726    
727        /** Returns a list of Pairs (ID, name) of existing users.
728         *@param showSystemUsers if true the system users (<b>unknown</b> and 
729         * <b>system</b>) are shown.
730         */
731        public synchronized List<Pair<Integer, String>> 
732                getValidUsers(boolean showSystem, boolean showUnknown)
733        {
734            List<Pair<Integer, String>> userData = new ArrayList<Pair<Integer, String>>();
735            if (showSystem) 
736            {
737                userData.add(new Pair<Integer, String>(
738                                      new Integer(User.SYSTEM.getUID()),
739                                      User.SYSTEM.getName()));
740            }
741            if (showUnknown) 
742            {
743                userData.add(new Pair<Integer, String>(
744                                       new Integer(User.SYSTEM.getUID()),
745                                       User.SYSTEM.getName()));
746            }
747            userData.addAll(primaryDataIndex.getUserInfo());
748            return userData;
749        }
750    
751        /** Returns a User object with a given uid
752         * @throws IllegalArgumentException if there is no record of a User with
753         *         such a uid.
754         * @throws IOException if there is a problem with IO.
755         */
756        public synchronized User getUser(int uid)
757        {
758            if (uid == User.UNKNOWN.getUID()) {
759                return User.UNKNOWN;
760            }
761    
762            User user = null;
763    
764            if (uid == User.SYSTEM.getUID()) {
765                user = User.SYSTEM;
766            } else {
767                if (availableDataIndex.isValidUser(uid)) {
768                    return availableDataIndex.getUser(uid);
769                }
770    
771                try {
772                    user = primaryStorage.getUser(uid);
773                    availableDataIndex.addUser(user);
774                } catch (Exception ex) {
775                    handleException(ex);
776                    return null;
777                }
778            }
779    
780            try {
781                UserPreferences preferences = primaryStorage.getUserPreferences(uid);
782                user.setUserPreferences(preferences);
783            } catch (Exception ex) {
784                System.out.println("Exception while loading user preferences: " + ex);
785            }
786    
787            return user;
788        }
789        
790        /** Returns a list of all users. */
791        public synchronized List<User> getAllUsers(boolean includeSystem, 
792                                                   boolean includeUnknown)
793        {
794           List<User> users = new ArrayList<User>();
795           
796           for (Pair<Integer, String> 
797                   userInfo : getValidUsers(includeSystem, includeUnknown))
798           {
799               users.add(getUser(userInfo.first().intValue()));
800           }
801           
802           return users;
803        }
804    
805        /** Adds and saves a User object.
806         *  @throws IllegalArgumentException if an user with a uid of a new object 
807         *          already exists.
808         */
809        public synchronized void addUser(User user)
810        {
811            if (user.equals(User.SYSTEM)) {
812                return;
813            }
814            if (user.equals(User.UNKNOWN)) {
815                return;
816            }
817    
818            primaryStorage.storeUser(user);
819            availableDataIndex.addUser(user);
820            fireUserAdded(user);
821        }
822    
823        /** Removes an user with a given uid. All transactions that belong to this 
824         *  user are changed to UNKNOWN.
825         *  @throws IllegalArgumentException if the user is used by at least one
826         *          budget, so it can not be removed.
827         */
828        public synchronized void removeUser(int uid)
829        {
830    
831            if (uid == User.SYSTEM.getUID()) {
832                return;
833            }
834            if (uid == User.UNKNOWN.getUID()) {
835                return;
836            }
837    
838            replaceUser(getUser(uid), User.UNKNOWN);
839            availableDataIndex.removeUser(uid);
840            primaryStorage.removeUser(uid);
841            fireUserRemoved(uid);
842        }
843    
844        /**
845         * Changes all transactions in all months that are owned by a user 'user'
846         * to point to a new user 'newUser'. 
847         */
848        public synchronized void replaceUser(User user, User newUser)
849        {
850            assert user != null;
851            assert newUser != null;
852    
853            List<Month> allMonths = this.getAllMonths();
854    
855            for (Month month : allMonths) {
856                if (month.replaceUser(user, newUser)) {
857                    fireMonthUpdated(month);
858                }
859            }
860        }
861    
862        /** Saves the preferences associated with the given user */
863        public synchronized void saveUserPreferences(User user)
864        {
865            if (user.getUserPreferences() == null) {
866                return;
867            }
868    
869            int uid = user.getUID();
870            primaryStorage.storeUserPreferences(uid, user.getUserPreferences());
871        }
872    
873        //========================= Current User ================================//
874        
875        /** Returns current user object */
876        public User getCurrentUser()
877        {
878            return currentUser;
879        }
880    
881        /** Changes the current user */
882        public boolean setCurrentUser(String userName, String password)
883        {
884            List<Pair<Integer, String>> usersInfo = getValidUsers();
885            for (Pair<Integer, String> userInfo : usersInfo) {
886                if (userInfo.second().equals(userName)) {
887                    int uid = userInfo.first().intValue();
888                    return setCurrentUser(getUser(uid), password);
889                }
890            }
891            return false;
892        }
893    
894        /** Changes the current user */
895        public boolean setCurrentUser(User user, String password)
896        {
897            if (!user.checkPassword(password))
898                return false;
899            currentUser = user;
900            fireUserChanged(user);
901            return true;
902        }
903    
904        //========================= Transactions ================================//
905        
906        /** Adds a transaction to a month and to a record for the month. This is
907         * done for the sake of efficiency, so that the whole Month object doesn't 
908         * have to be saved every time a transaction is added. First this
909         * methods checkes if the transaction has occured in a valid month. If not,
910         * a new month is created. Then it checks that the transaction has not been 
911         * previously added to the Month (if it has an IllegalArgumentException is 
912         * thrown). After that, it adds the transaction to the Month object by calling
913         * the addTransaction method. Finally, it saves the transaction in the record 
914         * corresponding to the month object.
915         * @param tr the Transaction object that will be added to the corresponding 
916         *        month.
917         */
918        public synchronized void addTransaction(Transaction tr)
919        {
920            Date transactionDate = tr.getDate();
921            calendar.setTime(transactionDate);
922            int cYear = calendar.get(Calendar.YEAR);
923            int cMonth = calendar.get(Calendar.MONTH);
924            int cDay = calendar.get(Calendar.DAY_OF_MONTH);
925            if (!isValidMonth(cMonth, cYear)) {
926                newMonth(cMonth, cYear);
927            }
928    
929            assert isValidMonth(cMonth, cYear);
930            Month month = getMonth(cMonth, cYear);
931            month.addTransaction(tr);
932            try {
933                primaryStorage.addTransaction(tr, cMonth, cYear);
934                updateInitialBalances(month);
935                fireTransactionAdded(tr);
936            } catch (Exception ex) {
937                handleException(ex);
938            }
939        }
940    
941        /** Removes a transaction record from a Month corresponding to the date of the
942         * transaction and from a record for the Month.
943         * This method is provided for the sake of efficiency, so that whole Month 
944         * object doesn't have to be saved every time a transaction is removed. First
945         * it checkes that there is a valid Month object that corresponds to the date
946         * of the transaction. If not, an IllegalArgumentException is thrown. After 
947         * checking it removes the transaction from the Month using removeTransaction 
948         * method of the month and removes a record of this transaction from the 
949         * record of the month
950         *@param tr the transaction object that will be removed.
951         */
952        public synchronized void removeTransaction(Transaction tr)
953        {
954            Date transactionDate = tr.getDate();
955            calendar.setTime(transactionDate);
956            int cYear = calendar.get(Calendar.YEAR);
957            int cMonth = calendar.get(Calendar.MONTH);
958            int cDay = calendar.get(Calendar.DAY_OF_MONTH);
959            if (!isValidMonth(cMonth, cYear)) 
960            {
961                throw new IllegalArgumentException(
962                        "Trying to remove a trasaction from a" +
963                        " Month that does not exist");
964            }
965    
966            Month month = getMonth(cMonth, cYear);
967    
968            try 
969            {
970                primaryStorage.removeTransaction(tr.getID(), cMonth, cYear);
971                month.removeTransaction(tr);
972                updateInitialBalances(month);
973                fireTransactionRemoved(tr.getTransfers(), cDay, cMonth, cYear);
974            } catch (Exception ex) {
975                handleException(ex);
976            }
977        }
978    
979        /** Returns all transactions that pass a given filter. */
980        public List<Transaction> getTransactions(TransactionFilter filter)
981        {
982            // Don't show anyting unless we have a valid user.
983            if (currentUser == User.UNKNOWN)
984                return Collections.emptyList();
985            
986            Date currentDate = filter.startingDate;
987            calendar.setTime(currentDate);
988            calendar.set(Calendar.DAY_OF_MONTH, 1);
989            currentDate = calendar.getTime();
990    
991            List<Transaction> transactions = new ArrayList<Transaction>();
992            while ( currentDate.before(filter.endingDate) ||
993                    currentDate.equals(filter.endingDate) ) 
994            {
995                if (isValidMonth(currentDate))
996                {
997                    Month month = getMonth(currentDate);
998                    transactions.addAll(filter.apply(month.getTransactions()));
999                }
1000                calendar.setTime(currentDate);
1001                calendar.add(Calendar.MONTH, 1);
1002                currentDate = calendar.getTime();
1003            }
1004            
1005            return transactions;
1006        }
1007    
1008        //========================== Allocations =================================//
1009        
1010        /** Adds an allocation to a month and to a record for the month. This is
1011         * done for the sake of efficiency, so that the whole Month object doesn't 
1012         * have to be saved every time an allocation is added. First this
1013         * methods checkes if the allocation has occured in a valid month. If not,
1014         * a new month is created. Then it checks that the allocation has not been 
1015         * previously added to the Month (if it has an IllegalArgumentException is 
1016         * thrown). After that, it adds the allocation to the Month object by calling
1017         * the addAllocation method. Finally, it saves the allocation in the record 
1018         * corresponding to the month object.
1019         * @param allocation the Transaction object that will be added to the 
1020         *        corresponding month.
1021         */
1022        public synchronized void addAllocation(Transaction allocation)
1023        {
1024            Date allocationDate = allocation.getDate();
1025            calendar.setTime(allocationDate);
1026            int cYear = calendar.get(Calendar.YEAR);
1027            int cMonth = calendar.get(Calendar.MONTH);
1028            int cDay = calendar.get(Calendar.DAY_OF_MONTH);
1029            if (!isValidMonth(cMonth, cYear)) {
1030                newMonth(cMonth, cYear);
1031            }
1032    
1033            assert isValidMonth(cMonth, cYear);
1034            Month month = getMonth(cMonth, cYear);
1035            month.addAllocation(allocation);
1036            try {
1037                primaryStorage.addAllocation(allocation, cMonth, cYear);
1038                updateInitialBalances(month);
1039                fireAllocationAdded(allocation);
1040            } catch (Exception ex) {
1041                handleException(ex);
1042            }
1043        }
1044    
1045        /** Removes an allocation record from a Month corresponding to the date of the
1046         * allocation and from a record for the Month.
1047         * This method is provided for the sake of efficiency, so that whole Month 
1048         * object doesn't have to be saved every time an allocation is removed. First
1049         * it checkes that there is a valid Month object that corresponds to the date
1050         * of the allocation. If not, an IllegalArgumentException is thrown. After 
1051         * checking it removes the allocation from the Month using removeTransaction 
1052         * method of the month and removes a record of this allocation from the 
1053         * record of the month
1054         *@param allocation the transaction object that will be removed.
1055         */
1056        public synchronized void removeAllocation(Transaction allocation)
1057        {
1058            Date allocationDate = allocation.getDate();
1059            calendar.setTime(allocationDate);
1060            int cYear = calendar.get(Calendar.YEAR);
1061            int cMonth = calendar.get(Calendar.MONTH);
1062            int cDay = calendar.get(Calendar.DAY_OF_MONTH);
1063            if (!isValidMonth(cMonth, cYear)) {
1064                throw new IllegalArgumentException("Trying to remove an allocation from a" +
1065                        " Month that does not exist");
1066            }
1067    
1068            Month month = getMonth(cMonth, cYear);
1069    
1070            try 
1071            {
1072                primaryStorage.removeAllocation(allocation.getID(), cMonth, cYear);
1073                month.removeAllocation(allocation);
1074                updateInitialBalances(month);
1075                fireAllocationRemoved(allocation.getTransfers(), 
1076                                      cDay, cMonth, cYear);
1077            } catch (Exception ex) {
1078                handleException(ex);
1079            }
1080        }
1081    
1082        /** Returns all transactions that pass a given filter. */
1083        public List<Transaction> getAllocations(TransactionFilter filter)
1084        {
1085            // Don't show anyting unless we have a valid user.
1086            if (currentUser == User.UNKNOWN)
1087                return Collections.emptyList();
1088            
1089            Date currentDate = filter.startingDate;
1090            calendar.setTime(currentDate);
1091            calendar.set(Calendar.DAY_OF_MONTH, 1);
1092            currentDate = calendar.getTime();
1093    
1094            List<Transaction> allocations = new ArrayList<Transaction>();
1095            while ( currentDate.before(filter.endingDate) ||
1096                    currentDate.equals(filter.endingDate) ) 
1097            {
1098                if (isValidMonth(currentDate))
1099                {
1100                    Month month = getMonth(currentDate);
1101                    allocations.addAll(filter.apply(month.getAllocations()));
1102                }
1103                calendar.setTime(currentDate);
1104                calendar.add(Calendar.MONTH, 1);
1105                currentDate = calendar.getTime();
1106            }
1107            
1108            return allocations;
1109        }
1110        
1111        //========================== Preferences =================================//
1112        
1113        /** Returns a reference to the SharedPreferences object used by the program.
1114         * This is the only instance of this object that should be used anywhere. */
1115        
1116        public SharedPreferences getSharedPreferences() 
1117        {
1118            return primaryStorage.getSharedPreferences();
1119        }
1120    
1121        //======================= Exception Handling =============================//
1122        
1123        /** Sets the mainWindow variable. This is used to handle exceptions.
1124         *  If an exception occurs and mainWindow is not null a graphical dialog will 
1125         *  be displayed. If mainWindow is null a message will be printed to stderr
1126         */
1127        public void setMainWindow(JFrame mainWindow)
1128        {
1129            this.mainWindow = mainWindow;
1130        }
1131        
1132        /** Returns a reference to the main frame of the application. */
1133        public JFrame getMainWindow() 
1134        {
1135            return mainWindow;
1136        }
1137    
1138        /** Handles exceptions. If an IOException or JDOMException occurs the program
1139         *  notifies user that the data is corrupted and exits without attempting to 
1140         *  synchronize the storage, so unsaved info is lost.
1141         */
1142        public void handleException(Exception ex)
1143        {
1144            if (mainWindow != null) {
1145                if (ex instanceof IOException) {
1146                    JOptionPane.showMessageDialog(mainWindow, "Input/Output error: " +
1147                            ex.getMessage() + "\n The program will exit.",
1148                            "Filesystem Error", JOptionPane.ERROR_MESSAGE);
1149                } else if (ex instanceof JDOMException) {
1150                    JOptionPane.showMessageDialog(mainWindow, "Data corruption error: " +
1151                            ex.getMessage() + "\n The program will exit.", "Data Corruption",
1152                            JOptionPane.ERROR_MESSAGE);
1153                } else {
1154                    JOptionPane.showMessageDialog(mainWindow, "error: " +
1155                            ex.getMessage() + "\n The program will exit.", "Error",
1156                            JOptionPane.ERROR_MESSAGE);
1157                }
1158            } else {
1159                if (ex instanceof IOException) {
1160                    System.err.println("Input/Output error: " +
1161                            ex.getMessage() + "\n The program will exit.");
1162                } else if (ex instanceof JDOMException) {
1163                    System.err.println("Data corruption error: " +
1164                            ex.getMessage() + "\n The program will exit.");
1165                } else {
1166                    System.err.println("error: " +
1167                            ex.getMessage() + "\n The program will exit.");
1168                }
1169            }
1170    
1171            if (TESTING) {
1172                Thread.dumpStack();
1173            }
1174    
1175            System.exit(1);
1176        }
1177    
1178        //========================== Private helper methods ======================//
1179        
1180        /** Updates the starting balances and expense allocations.
1181         *  If the month given to this function 
1182         *  inherits the starting balances from a previous month, this function 
1183         *  will get the final balance from the previous month and initialize the 
1184         *  stargng balance for the given month. It works only for two months that 
1185         *  immediately follow each other. For example if a Month object for May 2006
1186         *  is given as argument, the function will check if there is a record for 
1187         *  April of 2006. If there is no such record nothing will be done. Also if 
1188         *  the carryBalance property is 'false' in the Month object for May 2006, 
1189         *  this function doesn't do anything. In the other case the final balances 
1190         *  for the previous month (April 2006) are computed and used as the starting
1191         *  balances for the given month (May 2006). After that the function checkes
1192         *  if the month immediately after the given month (June 2006) is valid. If it
1193         *  is, the function updates it's starting balances using the final balances 
1194         *  of the current month (May 2006). And so it goes....
1195         */
1196        private void updateInitialBalances(Month month)
1197        {
1198            assert month != null;
1199    
1200            if (!month.getCarryBalance()) {
1201                return;
1202            }
1203    
1204            int cMonth = month.getMonth();
1205            int cYear = month.getYear();
1206    
1207            int prevCMonth = cMonth - 1;
1208            int prevCYear = cYear;
1209            if (prevCMonth < Calendar.JANUARY) {
1210                prevCMonth = Calendar.DECEMBER;
1211                prevCYear--;
1212            }
1213    
1214            if (!isValidMonth(prevCMonth, prevCYear)) {
1215                return;
1216            }
1217    
1218            Month pMonth = getMonth(prevCMonth, prevCYear);
1219    
1220            month.setStartingAllocations(pMonth.getFinalAllocations());
1221            month.setStartingBalances(pMonth.getFinalBalances());
1222    
1223            saveMonth(month);
1224    
1225            // Now we need to deal with months that come after the current month.
1226    
1227            int nextCMonth = cMonth + 1;
1228            int nextCYear = cYear;
1229            if (nextCMonth > Calendar.DECEMBER) {
1230                nextCMonth = Calendar.JANUARY;
1231                nextCYear++;
1232            }
1233    
1234            while (isValidMonth(nextCMonth, nextCYear)) {
1235                Month nMonth = getMonth(nextCMonth, nextCYear);
1236    
1237                if (!nMonth.getCarryBalance()) {
1238                    return;
1239                }
1240    
1241                nMonth.setStartingAllocations(month.getFinalAllocations());
1242                nMonth.setStartingBalances(month.getFinalBalances());
1243    
1244                saveMonth(nMonth);
1245                nextCMonth++;
1246    
1247                if (prevCMonth > Calendar.DECEMBER) {
1248                    nextCMonth = Calendar.JANUARY;
1249                    nextCYear++;
1250                }
1251                month = nMonth;
1252            }
1253    
1254        }
1255    
1256        /** Saves all months to the primary storage. The budgets don't have to be
1257         * saved once they are added by <code>addBudget</code> since they are 
1258         * immutable.
1259         */
1260        public void saveAllMonths()
1261        {
1262            List<Integer> years = availableDataIndex.getValidYears();
1263            for (Integer iYear : years) {
1264                List<Integer> months =
1265                        availableDataIndex.getValidMonths(iYear.intValue());
1266                for (Integer iMonth : months) {
1267                    saveMonth(availableDataIndex.getMonth(
1268                            iMonth.intValue(), iYear.intValue()));
1269                }
1270            }
1271        }
1272    
1273        //========================== Generating IDs  =============================//
1274        
1275        /** Creates a new numeric budget id and increases the counter. */
1276        public int generateBudgetID()
1277        {
1278            return primaryStorage.generateBudgetID();
1279        }
1280    
1281        /** Creates a new numeric account id and increases the counter. */
1282        public int generateAccountID()
1283        {
1284            return primaryStorage.generateAccountID();
1285        }
1286    
1287        /** Creates a new numeric id for an expense category 
1288         * and increases the counter. */
1289        public int generateExpenseCategoryID()
1290        {
1291            return primaryStorage.generateExpenseCategoryID();
1292        }
1293    
1294        /** Creates a new numeric id for an income source 
1295         * and increases the counter. */
1296        public int generateIncomeSourceID()
1297        {
1298            return primaryStorage.generateIncomeSourceID();
1299        }
1300    
1301        /** Creates a new uid for a new user 
1302         * and increases the counter. */
1303        public int generateUID()
1304        {
1305            return primaryStorage.generateUID();
1306        }
1307    
1308        /** Creates a new numeric transaction id for 
1309         * and increases the counter. */
1310        public long generateTransactionID()
1311        {
1312            return primaryStorage.generateTransactionID();
1313        }
1314    
1315        //=============================== Debugging ==============================//
1316        
1317        /** Clears all data. */
1318        public void clear()
1319        {
1320            if (!TESTING) {
1321                throw new UnsupportedOperationException();
1322            }
1323    
1324            for (Month month : getAllMonths()) {
1325                this.removeMonth(month.getMonth(), month.getYear());
1326            }
1327    
1328            List<Pair<Integer, String>> budgets = new ArrayList<Pair<Integer, String>>();
1329            budgets.addAll(getValidBudgets());
1330            for (Pair<Integer, String> budgetInfo : budgets) {
1331                removeBudget(budgetInfo.first().intValue());
1332            }
1333    
1334            List<Pair<Integer, String>> accounts = new ArrayList<Pair<Integer, String>>();
1335            accounts.addAll(getValidAccounts());
1336            for (Pair<Integer, String> accountInfo : accounts) {
1337                removeAccount(accountInfo.first().intValue());
1338            }
1339    
1340            List<Pair<Integer, String>> users = new ArrayList<Pair<Integer, String>>();
1341            users.addAll(getValidUsers());
1342            for (Pair<Integer, String> userInfo : users) {
1343                removeUser(userInfo.first().intValue());
1344            }
1345        }
1346    
1347        /** Returns a list of all valid month objects */
1348        public List<Month> getAllMonths()
1349        {
1350            List<Month> months = new ArrayList<Month>();
1351    
1352            List<Integer> validYears = getValidYears();
1353            for (Integer iYear : validYears) {
1354                List<Integer> validMonths = getValidMonths(iYear.intValue());
1355                for (Integer iMonth : validMonths) {
1356                    months.add(getMonth(iMonth.intValue(), iYear.intValue()));
1357                }
1358            }
1359    
1360            return months;
1361        }
1362    
1363        //=========================== Inner Classes ==============================//
1364        
1365        public static class PrefKeys
1366        {
1367    
1368            public static final String MAIN_DIR = "main_dir";
1369        }
1370    
1371        public static class PrefDef
1372        {
1373    
1374            public static final String MAIN_DIR = "";
1375        }
1376        
1377        /** A class that implements the timer task that is used to save changes
1378         * periodically, so that they are not lost in case the program crashes.
1379         */
1380        private class CommitTimerTask extends TimerTask
1381        {
1382            public void run()
1383            {
1384                saveAllMonths();
1385                try
1386                {
1387                    primaryStorage.commit();
1388                } 
1389                catch (Exception ex)
1390                {
1391                    handleException(ex);
1392                }
1393            }
1394        };
1395    
1396    }