org.jbudget.io
Class DataManager

java.lang.Object
  extended by org.jbudget.io.EventDispatcher
      extended by org.jbudget.io.DataManager

public class DataManager
extends EventDispatcher

A singleton class that is used to manage all the data in the program. It is responsible for saving and reading data from the disk. It is also responsible for making sure that the data on the disk is synchronized with the data in memory.

Author:
petrov

Nested Class Summary
private  class DataManager.CommitTimerTask
          A class that implements the timer task that is used to save changes periodically, so that they are not lost in case the program crashes.
static class DataManager.PrefDef
           
static class DataManager.PrefKeys
           
 
Nested classes/interfaces inherited from class org.jbudget.io.EventDispatcher
EventDispatcher.AccountListener, EventDispatcher.AllocationListener, EventDispatcher.BudgetListener, EventDispatcher.DataSourceListener, EventDispatcher.MonthListener, EventDispatcher.TransactionListener, EventDispatcher.UserListener
 
Field Summary
private  DataIndex availableDataIndex
          Index of the data that has already been loaded in memory
private  java.util.Calendar calendar
          Calendar instance that is used inside the object
private  org.jbudget.Core.User currentUser
          Current User
private static java.util.prefs.Preferences defaultPreferences
           
private  javax.swing.JFrame mainWindow
          Main window.
private  java.util.prefs.Preferences myPreferences
           
private  boolean newDataDir
          Did we just create a new data directory ?
private  boolean newDirectoryCheck
          Was a check for an new/empty data directory performed?
private  DataIndex primaryDataIndex
          Index of the data available on the primary storage.
private  StorageInterface primaryStorage
          Primary storage component.
private static boolean TESTING
           
private static DataManager theManager
          the only instance of DatatManager
(package private)  java.util.Timer timer
          Timer that is used to periodically save the data to permanent storage.
 
Constructor Summary
private DataManager(java.util.prefs.Preferences ioPreferences)
          Creates a new instance of DataManager
 
Method Summary
 void addAccount(org.jbudget.Core.Account account)
          Adds and saves an account object.
 void addAllocation(org.jbudget.Core.Transaction allocation)
          Adds an allocation to a month and to a record for the month.
 void addBudget(org.jbudget.Core.Budget budget)
          Adds and saves a budget object.
 void addMonth(org.jbudget.Core.Month month)
          Adds and saves a given month.
 void addTransaction(org.jbudget.Core.Transaction tr)
          Adds a transaction to a month and to a record for the month.
 void addUser(org.jbudget.Core.User user)
          Adds and saves a User object.
 void clear()
          Clears all data.
 void close()
          Commits all cached data to permanent storage, disposes of any resources that were allocated in the constructor (i.e., closes network connections).
 int generateAccountID()
          Creates a new numeric account id and increases the counter.
 int generateBudgetID()
          Creates a new numeric budget id and increases the counter.
 int generateExpenseCategoryID()
          Creates a new numeric id for an expense category and increases the counter.
 int generateIncomeSourceID()
          Creates a new numeric id for an income source and increases the counter.
 long generateTransactionID()
          Creates a new numeric transaction id for and increases the counter.
 int generateUID()
          Creates a new uid for a new user and increases the counter.
 org.jbudget.Core.Account getAccount(int accountID)
          Returns an Account object with a given numeric ID
 java.util.List<org.jbudget.Core.Month> getAllMonths()
          Returns a list of all valid month objects
 java.util.List<org.jbudget.Core.Transaction> getAllocations(org.jbudget.Core.TransactionFilter filter)
          Returns all transactions that pass a given filter.
 java.util.List<org.jbudget.Core.User> getAllUsers(boolean includeSystem, boolean includeUnknown)
          Returns a list of all users.
 org.jbudget.Core.Budget getBudget(int budgetID)
          Returns a Budget object with given numeric budget ID
 java.util.List<org.jbudget.Core.Account> getCashAccounts()
          Returns a list of cash accounts for all users of the system
 org.jbudget.Core.User getCurrentUser()
          Returns current user object
static DataManager getCustomizedInstance(java.util.prefs.Preferences ioPreferences)
          Returns a customized version of the DataManager that uses Preferences different from the default.
 java.lang.String getIdString()
          Returns a string describing the current storage interfaces used by the DataManager.
static DataManager getInstance()
          Returns the default instance of the DataManager.
 javax.swing.JFrame getMainWindow()
          Returns a reference to the main frame of the application.
 org.jbudget.Core.Month getMonth(java.util.Date d)
          Returns the Month object that corresponds (contains) a given date.
 org.jbudget.Core.Month getMonth(int cMonth, int cYear)
          Returns a month object for the given month/year combination.
 java.util.List<org.jbudget.Core.Month> getMonths(org.jbudget.Core.TransactionFilter filter)
          Returns a list of months that are passed by a given filter.
static DataManager getNewInstance()
          Creates a new instance of the DataManager from the defauld preference object for the program.
 org.jbudget.Core.Month getPreviousMonth(int cMonth, int cYear)
          Returns the first valid Month object preceeding the month given by the month and year combination.
 org.jbudget.Core.SharedPreferences getSharedPreferences()
          Returns a reference to the SharedPreferences object used by the program.
 java.util.List<org.jbudget.Core.Transaction> getTransactions(org.jbudget.Core.TransactionFilter filter)
          Returns all transactions that pass a given filter.
 java.util.List<Pair<java.lang.Integer,java.lang.String>> getUnusedAccounts()
          Returns a list of pairs of ID, name of unsuded accounts
 java.util.List<Pair<java.lang.Integer,java.lang.String>> getUnusedBudgets()
          Returns a list of pairs of ID, name of unsuded budgets
 org.jbudget.Core.User getUser(int uid)
          Returns a User object with a given uid
 java.util.List<Pair<java.lang.Integer,java.lang.String>> getValidAccounts()
          Returns a list of Pairs (ID, name) of existing accounts
 java.util.List<Pair<java.lang.Integer,java.lang.String>> getValidBudgets()
          Returns a list of Pairs (ID, name) of existing budgets
 java.util.List<java.lang.Integer> getValidMonths(int cYear)
          Returns a list of valid months for a given year.
 java.util.List<java.lang.Integer> getValidMonths(java.lang.Integer iYear)
          Returns a list of valid months for a given year.
 java.util.List<Pair<java.lang.Integer,java.lang.String>> getValidUsers()
          Returns a list of Pairs (ID, name) of all users.
 java.util.List<Pair<java.lang.Integer,java.lang.String>> getValidUsers(boolean showSystem, boolean showUnknown)
          Returns a list of Pairs (ID, name) of existing users.
 java.util.List<java.lang.Integer> getValidYears()
          Returns a List of valid years.
 void handleException(java.lang.Exception ex)
          Handles exceptions.
 boolean isNewDataDir()
          Returns true if a new data directory was created when the program was started.
 boolean isUnusedAccount(org.jbudget.Core.Account account)
          Returns true if a given account is not used by any budget.
 boolean isUnusedAccount(int accountID)
          Returns true if an account with the given ID is not used by any budget
 boolean isUnusedBudget(org.jbudget.Core.Budget budget)
          Returns true if the given budget is not used by any month.
 boolean isUnusedBudget(int budgetID)
          Returns true if a budget with the given ID is not used by any month
 boolean isValidMonth(java.util.Date d)
          Returns true if the given Date corresponds to a valid month.
 boolean isValidMonth(int cMonth, int cYear)
          Returns true if the given month/year combination corresponds to a valid month.
 org.jbudget.Core.Month newMonth(int cMonth, int cYear)
          Creates a new month for the given month/year combination and saves in in the permanent storage.
 void removeAccount(int accountID)
          Removes an account with a given id.
 void removeAllocation(org.jbudget.Core.Transaction allocation)
          Removes an allocation record from a Month corresponding to the date of the allocation and from a record for the Month.
 void removeBudget(int budgetID)
          Removes a budget with the given budget id.
 void removeMonth(int cMonth, int cYear)
          Removes a month object.
 void removeTransaction(org.jbudget.Core.Transaction tr)
          Removes a transaction record from a Month corresponding to the date of the transaction and from a record for the Month.
 void removeUnusedBudgets()
          Removes all unused budgets
 void removeUser(int uid)
          Removes an user with a given uid.
 void replaceUser(org.jbudget.Core.User user, org.jbudget.Core.User newUser)
          Changes all transactions in all months that are owned by a user 'user' to point to a new user 'newUser'.
 void saveAllMonths()
          Saves all months to the primary storage.
 void saveMonth(org.jbudget.Core.Month month)
          Saves the given Month object.
 void saveUserPreferences(org.jbudget.Core.User user)
          Saves the preferences associated with the given user
 boolean setCurrentUser(java.lang.String userName, java.lang.String password)
          Changes the current user
 boolean setCurrentUser(org.jbudget.Core.User user, java.lang.String password)
          Changes the current user
 void setMainWindow(javax.swing.JFrame mainWindow)
          Sets the mainWindow variable.
 void updateAccount(org.jbudget.Core.Account account)
          Updates an existing account object.
private  void updateInitialBalances(org.jbudget.Core.Month month)
          Updates the starting balances and expense allocations.
 
Methods inherited from class org.jbudget.io.EventDispatcher
addAccountListener, addAllocationListener, addBudgetListener, addDataSourceListener, addMonthListener, addTransactionListener, addUserListener, fireAccountAdded, fireAccountRemoved, fireAccountUpdated, fireAllocationAdded, fireAllocationRemoved, fireBudgetAdded, fireBudgetRemoved, fireDataDirChanged, fireMonthAdded, fireMonthRemoved, fireMonthUpdated, fireTransactionAdded, fireTransactionRemoved, fireUserAdded, fireUserChanged, fireUserRemoved, removeAccountListener, removeAllocationListener, removeBudgetListener, removeDataSourceListener, removeMonthListener, removeTransactionListener, removeUserListener
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

TESTING

private static final boolean TESTING
See Also:
Constant Field Values

defaultPreferences

private static final java.util.prefs.Preferences defaultPreferences

myPreferences

private final java.util.prefs.Preferences myPreferences

primaryDataIndex

private DataIndex primaryDataIndex
Index of the data available on the primary storage. Usually this is a hard drive, but we want the interface to be extensible so that, other types of storage can be accommodated.


primaryStorage

private StorageInterface primaryStorage
Primary storage component. Used for reading/saving data


availableDataIndex

private final DataIndex availableDataIndex
Index of the data that has already been loaded in memory


calendar

private final java.util.Calendar calendar
Calendar instance that is used inside the object


theManager

private static DataManager theManager
the only instance of DatatManager


newDirectoryCheck

private boolean newDirectoryCheck
Was a check for an new/empty data directory performed?


newDataDir

private boolean newDataDir
Did we just create a new data directory ?


currentUser

private org.jbudget.Core.User currentUser
Current User


mainWindow

private javax.swing.JFrame mainWindow
Main window. (Used for displaying exception dialogs)


timer

java.util.Timer timer
Timer that is used to periodically save the data to permanent storage.

Constructor Detail

DataManager

private DataManager(java.util.prefs.Preferences ioPreferences)
Creates a new instance of DataManager

Method Detail

getInstance

public static DataManager getInstance()
Returns the default instance of the DataManager. Uses default preferences


getNewInstance

public static DataManager getNewInstance()
Creates a new instance of the DataManager from the defauld preference object for the program. This has to be done if the preferences has changes in such a way that the DataManager instance becomes invalid. For example, if the storage directory was changes by the user.


getCustomizedInstance

public static DataManager getCustomizedInstance(java.util.prefs.Preferences ioPreferences)
Returns a customized version of the DataManager that uses Preferences different from the default. This method exists for testing only.


close

public void close()
Commits all cached data to permanent storage, disposes of any resources that were allocated in the constructor (i.e., closes network connections).


isNewDataDir

public boolean isNewDataDir()
Returns true if a new data directory was created when the program was started.


getIdString

public java.lang.String getIdString()
Returns a string describing the current storage interfaces used by the DataManager.


getValidYears

public java.util.List<java.lang.Integer> getValidYears()
Returns a List of valid years. For each year in the list there is at least one record for a month belonging to this year.


getValidMonths

public java.util.List<java.lang.Integer> getValidMonths(int cYear)
Returns a list of valid months for a given year.


getValidMonths

public java.util.List<java.lang.Integer> getValidMonths(java.lang.Integer iYear)
Returns a list of valid months for a given year.


isValidMonth

public boolean isValidMonth(java.util.Date d)
Returns true if the given Date corresponds to a valid month.


isValidMonth

public boolean isValidMonth(int cMonth,
                            int cYear)
Returns true if the given month/year combination corresponds to a valid month.


getMonth

public org.jbudget.Core.Month getMonth(int cMonth,
                                       int cYear)
Returns a month object for the given month/year combination.

Throws:
java.lang.IllegalArgumentException - if there is no record for this month, or if the values given don't make sense.

getMonth

public org.jbudget.Core.Month getMonth(java.util.Date d)
Returns the Month object that corresponds (contains) a given date.


getPreviousMonth

public org.jbudget.Core.Month getPreviousMonth(int cMonth,
                                               int cYear)
Returns the first valid Month object preceeding the month given by the month and year combination. Returns null if there are no valid months before the given month.


newMonth

public org.jbudget.Core.Month newMonth(int cMonth,
                                       int cYear)
Creates a new month for the given month/year combination and saves in in the permanent storage. Uses the budget from the closes preceeding month. If there are no preceeding months, uses a budget with the highest id.

Throws:
IllegalArguementException - if this month has been created previously.
java.lang.IllegalStateException - if there is no Budget that can be used to create a new Month.
java.io.IOException - if there are any problems with IO operations.

addMonth

public void addMonth(org.jbudget.Core.Month month)
Adds and saves a given month.

Throws:
java.lang.IllegalArgumentException - if this month (a month object with identical month/year) already exists.

saveMonth

public void saveMonth(org.jbudget.Core.Month month)
Saves the given Month object. This has to be called every time there is an update to a Month other than adding/removing transactions.


removeMonth

public void removeMonth(int cMonth,
                        int cYear)
Removes a month object. Deletes it from the permanent storage.

Throws:
java.lang.IllegalArgumentException - if no such month exists.

getMonths

public java.util.List<org.jbudget.Core.Month> getMonths(org.jbudget.Core.TransactionFilter filter)
Returns a list of months that are passed by a given filter.


getValidBudgets

public java.util.List<Pair<java.lang.Integer,java.lang.String>> getValidBudgets()
Returns a list of Pairs (ID, name) of existing budgets


getBudget

public org.jbudget.Core.Budget getBudget(int budgetID)
Returns a Budget object with given numeric budget ID

Throws:
java.lang.IllegalArgumentException - if there is no record of a budget with such id.
java.io.IOException - if there is a problem with IO.

addBudget

public void addBudget(org.jbudget.Core.Budget budget)
Adds and saves a budget object.

Throws:
java.lang.IllegalArgumentException - if a budget with an ID of a new object already exists.

removeBudget

public void removeBudget(int budgetID)
Removes a budget with the given budget id. Checks that the budget is not used by any months.

Throws:
java.lang.IllegalArgumentException - if the budget is used by at least one month, so it can not be removed.

removeUnusedBudgets

public void removeUnusedBudgets()
Removes all unused budgets


isUnusedBudget

public boolean isUnusedBudget(org.jbudget.Core.Budget budget)
Returns true if the given budget is not used by any month.


isUnusedBudget

public boolean isUnusedBudget(int budgetID)
Returns true if a budget with the given ID is not used by any month


getUnusedBudgets

public java.util.List<Pair<java.lang.Integer,java.lang.String>> getUnusedBudgets()
Returns a list of pairs of ID, name of unsuded budgets


getValidAccounts

public java.util.List<Pair<java.lang.Integer,java.lang.String>> getValidAccounts()
Returns a list of Pairs (ID, name) of existing accounts


getAccount

public org.jbudget.Core.Account getAccount(int accountID)
Returns an Account object with a given numeric ID

Throws:
java.lang.IllegalArgumentException - if there is no record of an Account with such an id.
java.io.IOException - if there is a problem with IO.

addAccount

public void addAccount(org.jbudget.Core.Account account)
Adds and saves an account object.

Throws:
java.lang.IllegalArgumentException - if an account with an ID of a new object already exists.

updateAccount

public void updateAccount(org.jbudget.Core.Account account)
Updates an existing account object. If there is no account with such id, calls addAccount.


removeAccount

public void removeAccount(int accountID)
Removes an account with a given id. Checks that the account is not used in any budgets.

Throws:
java.lang.IllegalArgumentException - if the account is used by at least one budget, so it can not be removed.

isUnusedAccount

public boolean isUnusedAccount(org.jbudget.Core.Account account)
Returns true if a given account is not used by any budget.


isUnusedAccount

public boolean isUnusedAccount(int accountID)
Returns true if an account with the given ID is not used by any budget


getUnusedAccounts

public java.util.List<Pair<java.lang.Integer,java.lang.String>> getUnusedAccounts()
Returns a list of pairs of ID, name of unsuded accounts


getCashAccounts

public java.util.List<org.jbudget.Core.Account> getCashAccounts()
Returns a list of cash accounts for all users of the system


getValidUsers

public java.util.List<Pair<java.lang.Integer,java.lang.String>> getValidUsers()
Returns a list of Pairs (ID, name) of all users.


getValidUsers

public java.util.List<Pair<java.lang.Integer,java.lang.String>> getValidUsers(boolean showSystem,
                                                                              boolean showUnknown)
Returns a list of Pairs (ID, name) of existing users.

Parameters:
showSystemUsers - if true the system users (unknown and system) are shown.

getUser

public org.jbudget.Core.User getUser(int uid)
Returns a User object with a given uid

Throws:
java.lang.IllegalArgumentException - if there is no record of a User with such a uid.
java.io.IOException - if there is a problem with IO.

getAllUsers

public java.util.List<org.jbudget.Core.User> getAllUsers(boolean includeSystem,
                                                         boolean includeUnknown)
Returns a list of all users.


addUser

public void addUser(org.jbudget.Core.User user)
Adds and saves a User object.

Throws:
java.lang.IllegalArgumentException - if an user with a uid of a new object already exists.

removeUser

public void removeUser(int uid)
Removes an user with a given uid. All transactions that belong to this user are changed to UNKNOWN.

Throws:
java.lang.IllegalArgumentException - if the user is used by at least one budget, so it can not be removed.

replaceUser

public void replaceUser(org.jbudget.Core.User user,
                        org.jbudget.Core.User newUser)
Changes all transactions in all months that are owned by a user 'user' to point to a new user 'newUser'.


saveUserPreferences

public void saveUserPreferences(org.jbudget.Core.User user)
Saves the preferences associated with the given user


getCurrentUser

public org.jbudget.Core.User getCurrentUser()
Returns current user object


setCurrentUser

public boolean setCurrentUser(java.lang.String userName,
                              java.lang.String password)
Changes the current user


setCurrentUser

public boolean setCurrentUser(org.jbudget.Core.User user,
                              java.lang.String password)
Changes the current user


addTransaction

public void addTransaction(org.jbudget.Core.Transaction tr)
Adds a transaction to a month and to a record for the month. This is done for the sake of efficiency, so that the whole Month object doesn't have to be saved every time a transaction is added. First this methods checkes if the transaction has occured in a valid month. If not, a new month is created. Then it checks that the transaction has not been previously added to the Month (if it has an IllegalArgumentException is thrown). After that, it adds the transaction to the Month object by calling the addTransaction method. Finally, it saves the transaction in the record corresponding to the month object.

Parameters:
tr - the Transaction object that will be added to the corresponding month.

removeTransaction

public void removeTransaction(org.jbudget.Core.Transaction tr)
Removes a transaction record from a Month corresponding to the date of the transaction and from a record for the Month. This method is provided for the sake of efficiency, so that whole Month object doesn't have to be saved every time a transaction is removed. First it checkes that there is a valid Month object that corresponds to the date of the transaction. If not, an IllegalArgumentException is thrown. After checking it removes the transaction from the Month using removeTransaction method of the month and removes a record of this transaction from the record of the month

Parameters:
tr - the transaction object that will be removed.

getTransactions

public java.util.List<org.jbudget.Core.Transaction> getTransactions(org.jbudget.Core.TransactionFilter filter)
Returns all transactions that pass a given filter.


addAllocation

public void addAllocation(org.jbudget.Core.Transaction allocation)
Adds an allocation to a month and to a record for the month. This is done for the sake of efficiency, so that the whole Month object doesn't have to be saved every time an allocation is added. First this methods checkes if the allocation has occured in a valid month. If not, a new month is created. Then it checks that the allocation has not been previously added to the Month (if it has an IllegalArgumentException is thrown). After that, it adds the allocation to the Month object by calling the addAllocation method. Finally, it saves the allocation in the record corresponding to the month object.

Parameters:
allocation - the Transaction object that will be added to the corresponding month.

removeAllocation

public void removeAllocation(org.jbudget.Core.Transaction allocation)
Removes an allocation record from a Month corresponding to the date of the allocation and from a record for the Month. This method is provided for the sake of efficiency, so that whole Month object doesn't have to be saved every time an allocation is removed. First it checkes that there is a valid Month object that corresponds to the date of the allocation. If not, an IllegalArgumentException is thrown. After checking it removes the allocation from the Month using removeTransaction method of the month and removes a record of this allocation from the record of the month

Parameters:
allocation - the transaction object that will be removed.

getAllocations

public java.util.List<org.jbudget.Core.Transaction> getAllocations(org.jbudget.Core.TransactionFilter filter)
Returns all transactions that pass a given filter.


getSharedPreferences

public org.jbudget.Core.SharedPreferences getSharedPreferences()
Returns a reference to the SharedPreferences object used by the program. This is the only instance of this object that should be used anywhere.


setMainWindow

public void setMainWindow(javax.swing.JFrame mainWindow)
Sets the mainWindow variable. This is used to handle exceptions. If an exception occurs and mainWindow is not null a graphical dialog will be displayed. If mainWindow is null a message will be printed to stderr


getMainWindow

public javax.swing.JFrame getMainWindow()
Returns a reference to the main frame of the application.


handleException

public void handleException(java.lang.Exception ex)
Handles exceptions. If an IOException or JDOMException occurs the program notifies user that the data is corrupted and exits without attempting to synchronize the storage, so unsaved info is lost.


updateInitialBalances

private void updateInitialBalances(org.jbudget.Core.Month month)
Updates the starting balances and expense allocations. If the month given to this function inherits the starting balances from a previous month, this function will get the final balance from the previous month and initialize the stargng balance for the given month. It works only for two months that immediately follow each other. For example if a Month object for May 2006 is given as argument, the function will check if there is a record for April of 2006. If there is no such record nothing will be done. Also if the carryBalance property is 'false' in the Month object for May 2006, this function doesn't do anything. In the other case the final balances for the previous month (April 2006) are computed and used as the starting balances for the given month (May 2006). After that the function checkes if the month immediately after the given month (June 2006) is valid. If it is, the function updates it's starting balances using the final balances of the current month (May 2006). And so it goes....


saveAllMonths

public void saveAllMonths()
Saves all months to the primary storage. The budgets don't have to be saved once they are added by addBudget since they are immutable.


generateBudgetID

public int generateBudgetID()
Creates a new numeric budget id and increases the counter.


generateAccountID

public int generateAccountID()
Creates a new numeric account id and increases the counter.


generateExpenseCategoryID

public int generateExpenseCategoryID()
Creates a new numeric id for an expense category and increases the counter.


generateIncomeSourceID

public int generateIncomeSourceID()
Creates a new numeric id for an income source and increases the counter.


generateUID

public int generateUID()
Creates a new uid for a new user and increases the counter.


generateTransactionID

public long generateTransactionID()
Creates a new numeric transaction id for and increases the counter.


clear

public void clear()
Clears all data.


getAllMonths

public java.util.List<org.jbudget.Core.Month> getAllMonths()
Returns a list of all valid month objects