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 * LocalStore.java
024 *
025 * Created on May 17, 2006, 6:50 AM
026 */
027
028 package org.jbudget.io;
029
030 import java.io.BufferedInputStream;
031 import java.io.BufferedOutputStream;
032 import java.io.BufferedReader;
033 import java.io.File;
034 import java.io.FileInputStream;
035 import java.io.FileOutputStream;
036 import java.io.FileReader;
037 import java.io.FileWriter;
038 import java.io.IOException;
039 import java.io.InputStream;
040 import java.io.OutputStream;
041 import java.io.PrintWriter;
042 import java.util.HashMap;
043 import java.util.Map;
044 import java.util.Set;
045 import org.jdom.Document;
046 import org.jdom.Element;
047 import org.jdom.JDOMException;
048 import org.jdom.input.SAXBuilder;
049 import org.jdom.output.Format;
050 import org.jdom.output.XMLOutputter;
051 import org.jbudget.Core.Account;
052 import org.jbudget.Core.Budget;
053 import org.jbudget.Core.Month;
054 import org.jbudget.Core.SharedPreferences;
055 import org.jbudget.Core.Transaction;
056 import org.jbudget.Core.User;
057 import org.jbudget.gui.user.UserPreferences;
058 import org.jbudget.util.DateFormater;
059
060 /**
061 *
062 * @author petrov
063 */
064 public class LocalStore implements StorageInterface
065 {
066 //================================ DATA ===================================//
067 /** Root directory for storing all the data */
068 private final File rootDirectory;
069
070 /** Index of available data */
071 private DataIndex dataIndex;
072
073 /** A flag that is set to true when a new DataIndex is created. This
074 * means that an empty data directory is initialized. */
075 private boolean newDataIndexFlag = false;
076
077 /** A map of JDOM Elements for Month objects that were loaded from
078 * the storage. Used for caching to prevent excessive reading and
079 * saving of XML data.
080 */
081 private final Map<Integer, Element> monthElementsMap =
082 new HashMap<Integer, Element>();
083
084 /** A map of JDOM Elements for Budget objects that were loaded from
085 * the storage. Used for caching to prevent excessive reading and
086 * saving/reading of XML data.
087 */
088 private final Map<Integer, Element> budgetElementsMap =
089 new HashMap<Integer, Element>();
090
091 /** A map of JDOM Elements for Account objects that were loaded from
092 * the storage. Used for caching to prevent excessive reading and
093 * saving/reading of XML data.
094 */
095 private final Map<Integer, Element> accountElementsMap =
096 new HashMap<Integer, Element>();
097
098 /** A map of JDOM Elements for User objects that were loaded from
099 * the storage. Used for caching to prevent excessive reading and
100 * saving/reading of XML data.
101 */
102 private final Map<Integer, Element> userElementsMap =
103 new HashMap<Integer, Element>();
104
105 /** A map of JDOM Elements for UserPreferences objects that were loaded from
106 * the storage. Used for caching to prevent excessive reading and
107 * saving/reading of XML data.
108 */
109 private final Map<Integer, Element> userPreferencesElementsMap =
110 new HashMap<Integer, Element>();
111
112 /** Global SharedPreference object used by the program. */
113 private SharedPreferences sharedPreferences = null;
114
115
116 //====================== Constructors ==============================//
117
118 /** Creates a new instance of LocalStore */
119 public LocalStore(File rootDirectory)
120 throws IOException,JDOMException {
121 this.rootDirectory = rootDirectory;
122 initialize();
123 }
124
125 /** Creates a new instance of LocalStore */
126 public LocalStore(String rootDirectoryStr)
127 throws IOException,JDOMException {
128 this.rootDirectory = new File(rootDirectoryStr);
129 initialize();
130 }
131
132 //===================================================================//
133
134
135 /** Makes sure that the root directory for storing all the files
136 * exists.
137 */
138 private void initialize() throws IOException, JDOMException
139 {
140 if (!rootDirectory.isDirectory())
141 throw new IOException(
142 "Path has to point to a directory: " + rootDirectory);
143 if (!rootDirectory.exists())
144 rootDirectory.mkdirs();
145
146 if ( (!rootDirectory.canRead()) || (!rootDirectory.canWrite()) )
147 throw new IOException(
148 "Can not read or write to directory: " + rootDirectory);
149 initializeIndex();
150 }
151
152
153 //====================== Working with DataIndex ======================//
154
155 /** Initializes an index of available data. Reads it from a file or creates
156 * a new one.
157 */
158 private synchronized void initializeIndex() throws JDOMException, IOException
159 {
160 File dataIndexFile = new File(rootDirectory, "data_index.xml");
161 if (!dataIndexFile.canRead()) {
162 dataIndex = new DataIndex(false);
163 newDataIndexFlag = true;
164 return;
165 }
166
167 InputStream iStream =
168 new BufferedInputStream (new FileInputStream(dataIndexFile));
169 SAXBuilder builder = new SAXBuilder();
170 Document indexDoc = builder.build(iStream);
171 Element indexElement = indexDoc.getRootElement();
172 indexDoc.setRootElement(new Element("Empty"));
173
174 dataIndex = DataIndex.getInstance(indexElement);
175 }
176
177
178 /** Saves the index of available data to a file */
179 private synchronized void storeIndex() throws IOException
180 {
181 File dataIndexFile = new File(rootDirectory, "data_index.xml");
182 OutputStream oStream =
183 new BufferedOutputStream (new FileOutputStream (dataIndexFile));
184 Element indexElement = dataIndex.getXmlElement();
185 Document indexDocument = new Document();
186 indexDocument.setRootElement(indexElement);
187
188 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
189 outputter.output(indexDocument, oStream);
190 oStream.close();
191 indexDocument.setRootElement(new Element("Empty"));
192 }
193
194
195 /** Interface implementation */
196 public synchronized DataIndex getDataIndex(){
197 return dataIndex;
198 }
199
200
201 public boolean isNewDataInidex() { return newDataIndexFlag;}
202
203
204 //======================== Working with Budgets =========================//
205
206 /** Reads a JDOM Element for a given Month from a corresponding file.
207 * Adds the element to the monthsElementsMap.
208 * @throws IOException if there is a problem reading the file.
209 * @throws JDOMExceptoin if there is a problem parsing the contents of
210 * the file.
211 */
212 private Element readMonthElement(int cMonth, int cYear) throws IOException,
213 JDOMException
214 {
215 File monthFile = getMonthFile(cMonth, cYear);
216 // Reading and parsing
217 InputStream iStream =
218 new BufferedInputStream (new FileInputStream(monthFile));
219 SAXBuilder builder = new SAXBuilder();
220 Document monthDoc = builder.build(iStream);
221 Element monthElement = monthDoc.getRootElement();
222 //Enabling the budgetDoc to be cleaned up by the garbage collector.
223 monthDoc.setRootElement(new Element("Empty"));
224
225 // Saving the new monthElement in the monthElementsMap for caching.
226 Integer monthIndex = new Integer(cYear*100 + cMonth);
227 monthElementsMap.put(monthIndex, monthElement);
228
229 return monthElement;
230 }
231
232
233 /** Stores a JDOM Element corresponding to a Month object to a file.
234 * @throws IOException if there are IO errors.
235 */
236 private void saveMonthElement(
237 Element element, int cMonth, int cYear) throws IOException, JDOMException
238 {
239 File monthFile = getMonthFile(cMonth, cYear);
240 File dir = monthFile.getParentFile();
241 dir.mkdirs();
242
243 backupFile(monthFile);
244
245 OutputStream oStream =
246 new BufferedOutputStream (new FileOutputStream (monthFile));
247 Document monthDocument = new Document();
248 monthDocument.setRootElement(element);
249
250 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
251 outputter.output(monthDocument, oStream);
252 oStream.close();
253 monthDocument.setRootElement(new Element("Empty"));
254 }
255
256 /** Returns a JDOM element that corresponds to the given month.
257 * Returns a cached version if it is available. Otherwise reads the
258 * object from permanent storage.
259 * @throws IllegalArgumentException if month is not available.
260 */
261 private Element getMonthElement(int month, int year) throws IOException,
262 JDOMException
263 {
264 if (!dataIndex.isValidMonth(month, year))
265 throw new IllegalArgumentException("Trying to get a Month element for a " +
266 "month that does not exist.\n year: " + year + ", month: " +
267 (new DateFormater()).formatMonth(month));
268
269 Integer monthIndex = new Integer(year*100 + month);
270 Element element = monthElementsMap.get(monthIndex);
271 if (element == null)
272 element = readMonthElement(month, year);
273
274 return element;
275 }
276
277
278 /** Implementing the interface. Gets a JDOM Element for a month converts
279 * it to a Month object and returns it.
280 * @throws IOException if there are IO errors.
281 * @throws JDOMException if there are parsing errors.
282 */
283 public synchronized Month getMonth(int cMonth, int cYear) throws IOException
284 {
285 try{
286 Element monthElement = getMonthElement(cMonth, cYear);
287 Month month = Month.getInstance(monthElement);
288 return month;
289 } catch (JDOMException ex) {
290 throw new IOException(ex.getMessage());
291 }
292 }
293
294 /** Implementing the interface. Converts a give month object to a JDOM Element
295 * and stores it in the cache. Also adds a record in the data index. Does
296 * not actually save the Element to disk, this is done when the cache is
297 * synchronized to disk.
298 */
299 public synchronized boolean storeMonth (Month month)
300 {
301 int cMonth = month.getMonth();
302 int cYear = month.getYear();
303 Element monthElement = month.getXmlElement();
304 Integer monthIndex = new Integer(cYear*100 + cMonth);
305 monthElementsMap.put(monthIndex, monthElement);
306 dataIndex.registerMonth(cMonth, cYear);
307 return true;
308 }
309
310 /** Implementing the interfaces. Removes a month.
311 * @throws IllegalArgumentException if there is no such month
312 */
313 public synchronized boolean removeMonth(int cMonth, int cYear)
314 {
315 if (!dataIndex.isValidMonth(cMonth, cYear))
316 throw new IllegalArgumentException("Trying to remove a Montn " +
317 "that does not exist.\n year: " + cYear + ", month: " +
318 (new DateFormater()).formatMonth(cMonth));
319
320 // removing month information from the data index
321 dataIndex.unregisterMonth(cMonth, cYear);
322
323 // removing a cached Element.
324 Integer monthIndex = new Integer(cYear*100 + cMonth);
325 monthElementsMap.remove(monthIndex);
326
327 // removing the file
328 File monthFile = getMonthFile(cMonth, cYear);
329 if (monthFile.exists())
330 monthFile.delete();
331
332 return true;
333 }
334
335 /** Implementing the interfaces. Removes a month.
336 * @throws IllegalArgumentException if there is no such month
337 */
338 public synchronized boolean removeMonth(Month month){
339 return removeMonth(month.getMonth(), month.getYear());
340 }
341
342 //======================= Working with budgets ========================//
343
344 /** Reads a JDOM Element containing the budget with given budget id.
345 * @throws IOException
346 * @throws IllegalArgumentException if there is no such budget.
347 */
348 private Element readBudgetElement(int id) throws IOException,
349 JDOMException
350 {
351 if (!dataIndex.isValidBudget(id))
352 throw new IllegalArgumentException("No budget with id: " + id);
353
354 File budgetFile = getBudgetFile(id);
355 // Reading and parsing
356 InputStream iStream =
357 new BufferedInputStream (new FileInputStream(budgetFile));
358
359 SAXBuilder builder = new SAXBuilder();
360 Document budgetDoc = builder.build(iStream);
361 Element budgetElement = budgetDoc.getRootElement();
362 //Enabling the budgetDoc to be cleaned up by the garbage collector.
363 budgetDoc.setRootElement(new Element("Empty"));
364
365 // Saving the new monthElement in the monthElementsMap for caching.
366 Integer budgetIndex = new Integer(id);
367 budgetElementsMap.put(budgetIndex, budgetElement);
368
369 return budgetElement;
370 }
371
372
373 /** Saves a JDOM Element containing the budget with given budget id. */
374 private void saveBudgetElement(
375 Element element, int id) throws IOException, JDOMException
376 {
377 File budgetFile = getBudgetFile(id);
378 File dir = budgetFile.getParentFile();
379 dir.mkdirs();
380
381 backupFile(budgetFile);
382
383 OutputStream oStream =
384 new BufferedOutputStream (new FileOutputStream (budgetFile));
385 Document budgetDocument = new Document();
386 budgetDocument.setRootElement(element);
387
388 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
389 outputter.output(budgetDocument, oStream);
390 oStream.close();
391
392 budgetDocument.setRootElement(new Element("Empty"));
393 }
394
395
396 /** Returns a JDOM Element containing the budget with given id.
397 * Uses a cached version if it is avalilable. Otherwise the Element
398 * is read from storage.
399 * @throws IllegalArgumentException if there is no budget with the given id
400 */
401 private Element getBudgetElement(int id) throws IOException, JDOMException
402 {
403 if (!dataIndex.isValidBudget(id))
404 throw new IllegalArgumentException("No budget with id: " + id);
405
406 Integer budgetIndex = new Integer(id);
407 Element budgetElement = budgetElementsMap.get(budgetIndex);
408 if (budgetElement == null)
409 budgetElement = readBudgetElement(id);
410
411 return budgetElement;
412 }
413
414 /** Implementing the interface. Returns a Budget object with a given
415 * id.
416 * @throws IllegalArgumentException if there is no budget with the given id
417 * @throws IOException if there are IO errors.
418 */
419 public synchronized Budget getBudget(int id) throws IOException
420 {
421 try{
422 Element budgetElement = getBudgetElement(id);
423 Budget budget = Budget.getInstance(budgetElement);
424 return budget;
425 } catch (JDOMException ex){
426 throw new IOException(ex.getMessage());
427 }
428 }
429
430 /** Stores a given budget.
431 * @return true when the operation has completed successfully.
432 */
433 public synchronized boolean storeBudget(Budget budget)
434 {
435 int id = budget.getID();
436 String name = budget.getName();
437 Element budgetElement = budget.getXmlElement();
438
439 Integer budgetIndex = new Integer(id);
440 budgetElementsMap.put(budgetIndex, budgetElement);
441
442 dataIndex.registerBudget(id, name);
443 return true;
444 }
445
446 /** removes a budget.
447 * @return true when the operation has completed successfully.
448 * @throws IllegalArgumentException if no such budget exists.
449 */
450 public synchronized boolean removeBudget(int id)
451 {
452 if (!dataIndex.isValidBudget(id))
453 throw new IllegalArgumentException("No budget with id: " + id);
454
455 // removing record of the budget
456 dataIndex.unregisterBudget(id);
457
458 // Clearing cache
459 Integer budgetIndex = new Integer(id);
460 budgetElementsMap.remove(budgetIndex);
461
462 // Removing file
463 File budgetFile = getBudgetFile(id);
464 if (budgetFile.exists())
465 budgetFile.delete();
466 return true;
467 }
468
469 /** removes a budget.
470 * @return true when the operation has completed successfully.
471 * @throws IllegalArgumentException if no such budget exists.
472 */
473 public synchronized boolean removeBudget(Budget budget){
474 return removeBudget(budget.getID());
475 }
476
477 //======================== Working with accounts ==========================//
478
479 /** Reads a JDOM Element containing the account with given account id.
480 * @throws IOException
481 * @throws IllegalArgumentException if there is no such account.
482 */
483 private Element readAccountElement(int id) throws IOException,
484 JDOMException
485 {
486 if (!dataIndex.isValidAccount(id))
487 throw new IllegalArgumentException("No account with id: " + id);
488
489 File accountFile = getAccountFile(id);
490 // Reading and parsing
491 InputStream iStream =
492 new BufferedInputStream (new FileInputStream(accountFile));
493
494 SAXBuilder builder = new SAXBuilder();
495 Document accountDoc = builder.build(iStream);
496 Element accountElement = accountDoc.getRootElement();
497 //Enabling the accountDoc to be cleaned up by the garbage collector.
498 accountDoc.setRootElement(new Element("Empty"));
499
500 // Saving the new monthElement in the monthElementsMap for caching.
501 Integer accountIndex = new Integer(id);
502 accountElementsMap.put(accountIndex, accountElement);
503
504 return accountElement;
505 }
506
507
508 /** Saves a JDOM Element containing the account with given account id. */
509 private void saveAccountElement(
510 Element element, int id) throws IOException, JDOMException
511 {
512 File accountFile = getAccountFile(id);
513 File dir = accountFile.getParentFile();
514 dir.mkdirs();
515
516 backupFile(accountFile);
517
518 OutputStream oStream =
519 new BufferedOutputStream (new FileOutputStream (accountFile));
520 Document accountDocument = new Document();
521 accountDocument.setRootElement(element);
522
523 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
524 outputter.output(accountDocument, oStream);
525 oStream.close();
526
527 accountDocument.setRootElement(new Element("Empty"));
528 }
529
530
531 /** Returns a JDOM Element containing the account with given id.
532 * Uses a cached version if it is avalilable. Otherwise the Element
533 * is read from storage.
534 * @throws IllegalArgumentException if there is no account with the given id
535 */
536 private Element getAccountElement(int id) throws IOException, JDOMException
537 {
538 if (!dataIndex.isValidAccount(id))
539 throw new IllegalArgumentException("No account with id: " + id);
540
541 Integer accountIndex = new Integer(id);
542 Element accountElement = accountElementsMap.get(accountIndex);
543 if (accountElement == null)
544 accountElement = readAccountElement(id);
545
546 return accountElement;
547 }
548
549 /** Implementing the interface. Returns a Account object with a given
550 * id.
551 * @throws IllegalArgumentException if there is no account with the given id
552 * @throws IOException if there are IO errors.
553 */
554 public synchronized Account getAccount(int id) throws IOException
555 {
556 try{
557 Element accountElement = getAccountElement(id);
558 Account account = Account.getInstance(accountElement);
559 return account;
560 } catch (JDOMException ex){
561 throw new IOException(ex.getMessage());
562 }
563 }
564
565 /** Stores a given account.
566 * @return true when the operation has completed successfully.
567 */
568 public synchronized boolean storeAccount(Account account)
569 {
570 int id = account.getID();
571 String name = account.getName();
572 Element accountElement = account.getXmlElement();
573
574 Integer accountIndex = new Integer(id);
575 accountElementsMap.put(accountIndex, accountElement);
576
577 dataIndex.registerAccount(id, name);
578 return true;
579 }
580
581 /** removes a account.
582 * @return true when the operation has completed successfully.
583 * @throws IllegalArgumentException if no such account exists.
584 */
585 public synchronized boolean removeAccount(int id)
586 {
587 if (!dataIndex.isValidAccount(id))
588 throw new IllegalArgumentException("No account with id: " + id);
589
590 // removing record of the account
591 dataIndex.unregisterAccount(id);
592
593 // Clearing cache
594 Integer accountIndex = new Integer(id);
595 accountElementsMap.remove(accountIndex);
596
597 // Removing file
598 File accountFile = getAccountFile(id);
599 if (accountFile.exists())
600 accountFile.delete();
601 return true;
602 }
603
604 /** removes a account.
605 * @return true when the operation has completed successfully.
606 * @throws IllegalArgumentException if no such account exists.
607 */
608 public synchronized boolean removeAccount(Account account){
609 return removeAccount(account.getID());
610 }
611
612
613 //========================= Working with users ==========================//
614
615 /** Reads a JDOM Element containing the user with a given uid.
616 * @throws IOException
617 * @throws IllegalArgumentException if there is no such user.
618 */
619 private Element readUserElement(int uid) throws IOException,
620 JDOMException
621 {
622 if (!dataIndex.isValidUser(uid))
623 throw new IllegalArgumentException("No user with uid: " + uid);
624
625 File userFile = getUserFile(uid);
626 // Reading and parsing
627 InputStream iStream =
628 new BufferedInputStream (new FileInputStream(userFile));
629
630 SAXBuilder builder = new SAXBuilder();
631 Document userDoc = builder.build(iStream);
632 Element userElement = userDoc.getRootElement();
633 //Enabling the userDoc to be cleaned up by the garbage collector.
634 userDoc.setRootElement(new Element("Empty"));
635
636 // Saving the new monthElement in the monthElementsMap for caching.
637 Integer userIndex = new Integer(uid);
638 userElementsMap.put(userIndex, userElement);
639
640 return userElement;
641 }
642
643
644 /** Saves a JDOM Element containing the user with given uid. */
645 private void saveUserElement(
646 Element element, int uid) throws IOException, JDOMException
647 {
648 File userFile = getUserFile(uid);
649 File dir = userFile.getParentFile();
650 dir.mkdirs();
651
652 backupFile(userFile);
653
654 OutputStream oStream =
655 new BufferedOutputStream (new FileOutputStream (userFile));
656 Document userDocument = new Document();
657 userDocument.setRootElement(element);
658
659 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
660 outputter.output(userDocument, oStream);
661 oStream.close();
662
663 userDocument.setRootElement(new Element("Empty"));
664 }
665
666
667 /** Returns a JDOM Element containing the user with a given uid.
668 * Uses a cached version if it is avalilable. Otherwise the Element
669 * is read from storage.
670 * @throws IllegalArgumentException if there is no user with the given id
671 */
672 private Element getUserElement(int uid) throws IOException, JDOMException
673 {
674 if (!dataIndex.isValidUser(uid))
675 throw new IllegalArgumentException("No user with uid: " + uid);
676
677 Integer userIndex = new Integer(uid);
678 Element userElement = userElementsMap.get(userIndex);
679 if (userElement == null)
680 userElement = readUserElement(uid);
681
682 return userElement;
683 }
684
685 /** Implementing the interface. Returns a User object with a given
686 * uid.
687 * @throws IllegalArgumentException if there is no user with the given uid
688 * @throws IOException if there are IO errors.
689 */
690 public synchronized User getUser(int uid) throws IOException
691 {
692 try{
693 Element userElement = getUserElement(uid);
694 User user = User.getInstance(userElement);
695 return user;
696 } catch (JDOMException ex){
697 throw new IOException(ex.getMessage());
698 }
699 }
700
701 /** Stores a given user.
702 * @return true when the operation has completed successfully.
703 */
704 public synchronized boolean storeUser(User user)
705 {
706 int uid = user.getUID();
707 String name = user.getName();
708 Element userElement = user.getXmlElement();
709
710 Integer userIndex = new Integer(uid);
711 userElementsMap.put(userIndex, userElement);
712
713 dataIndex.registerUser(uid, name);
714 return true;
715 }
716
717 /** removes a user.
718 * @return true when the operation has completed successfully.
719 * @throws IllegalArgumentException if no such user exists.
720 */
721 public synchronized boolean removeUser(int uid)
722 {
723 if (!dataIndex.isValidUser(uid))
724 throw new IllegalArgumentException("No user with uid: " + uid);
725
726 // removing record of the user
727 dataIndex.unregisterUser(uid);
728
729 // Clearing cache
730 Integer userIndex = new Integer(uid);
731 userElementsMap.remove(userIndex);
732
733 // Removing file
734 File userFile = getUserFile(uid);
735 if (userFile.exists())
736 userFile.delete();
737 return true;
738 }
739
740 /** removes a user.
741 * @return true when the operation has completed successfully.
742 * @throws IllegalArgumentException if no such user exists.
743 */
744 public synchronized boolean removeUser(User user){
745 return removeUser(user.getUID());
746 }
747
748 //==================== Working with userPreferences =========================//
749
750 /** Reads a JDOM Element containing the user preferences for a user with a
751 * given uid.
752 * @throws IOException
753 * @throws IllegalArgumentException if there is no such user.
754 */
755 private Element readUserPreferencesElement(int uid) throws IOException,
756 JDOMException
757 {
758 if (!dataIndex.isValidUser(uid) && uid != User.SYSTEM.getUID())
759 throw new IllegalArgumentException("No user with uid: " + uid);
760
761 File userPreferencesFile = getUserPreferencesFile(uid);
762 // Reading and parsing
763 InputStream iStream =
764 new BufferedInputStream (new FileInputStream(userPreferencesFile));
765
766 SAXBuilder builder = new SAXBuilder();
767 Document userDoc = builder.build(iStream);
768 Element userPreferencesElement = userDoc.getRootElement();
769 //Enabling the userDoc to be cleaned up by the garbage collector.
770 userDoc.setRootElement(new Element("Empty"));
771
772 // Saving the new monthElement in the monthElementsMap for caching.
773 Integer userIndex = new Integer(uid);
774 userPreferencesElementsMap.put(userIndex, userPreferencesElement);
775
776 return userPreferencesElement;
777 }
778
779
780 /** Saves a JDOM Element containing the user preferences for a user with
781 * a given uid. */
782 private void saveUserPreferencesElement( Element element, int uid)
783 throws IOException, JDOMException
784 {
785 File userFile = getUserPreferencesFile(uid);
786 File dir = userFile.getParentFile();
787 dir.mkdirs();
788
789 backupFile(userFile);
790
791 OutputStream oStream =
792 new BufferedOutputStream (new FileOutputStream (userFile));
793 Document userDocument = new Document();
794 userDocument.setRootElement(element);
795
796 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
797 outputter.output(userDocument, oStream);
798 oStream.close();
799
800 userDocument.setRootElement(new Element("Empty"));
801 }
802
803
804 /** Returns a JDOM Element containing the user preferences for the user
805 * with a given uid. Uses a cached version if it is avalilable. Otherwise the
806 * Element is read from storage.
807 * @throws IllegalArgumentException if there is no user with the given id
808 */
809 private Element getUserPreferencesElement(int uid)
810 throws IOException, JDOMException
811 {
812 if (!dataIndex.isValidUser(uid) && uid != User.SYSTEM.getUID())
813 throw new IllegalArgumentException("No user with uid: " + uid);
814
815 Integer userIndex = new Integer(uid);
816 Element userPreferencesElement = userPreferencesElementsMap.get(userIndex);
817 if (userPreferencesElement == null)
818 userPreferencesElement = readUserPreferencesElement(uid);
819
820 return userPreferencesElement;
821 }
822
823 /** Implementing the interface. Returns a UserPreferences object for the user
824 * with a given uid.
825 * @throws IllegalArgumentException if there is no user with the given uid
826 * @throws IOException if there are IO errors.
827 */
828 public synchronized UserPreferences getUserPreferences(int uid)
829 throws IOException
830 {
831 try{
832 Element userPreferencesElement = getUserPreferencesElement(uid);
833 UserPreferences userPreferences =
834 UserPreferences.getInstance(userPreferencesElement);
835 return userPreferences;
836 } catch (JDOMException ex){
837 throw new IOException(ex.getMessage());
838 }
839 }
840
841 /** Stores the preferences for the user with a given uid.
842 * @return true when the operation has completed successfully.
843 */
844 public synchronized boolean storeUserPreferences(
845 int uid, UserPreferences preferences)
846 {
847
848 Element userPreferencesElement = preferences.getXmlElement();
849 userPreferencesElementsMap.put(new Integer(uid), userPreferencesElement);
850 return true;
851 }
852
853 //==================== Working with shared preferences =======================//
854
855
856 /** Reads a JDOM Element containing the user preferences for a user with a
857 * given uid.
858 * @throws IOException
859 * @throws IllegalArgumentException if there is no such user.
860 */
861 private Element readSharedPreferencesElement() throws IOException,
862 JDOMException
863 {
864 File sharedPreferencesFile = getSharedPreferencesFile();
865
866 if (!sharedPreferencesFile.exists())
867 return null;
868
869 // Reading and parsing
870 InputStream iStream =
871 new BufferedInputStream (new FileInputStream(sharedPreferencesFile));
872
873 SAXBuilder builder = new SAXBuilder();
874 Document doc = builder.build(iStream);
875 Element element = doc.getRootElement();
876 //Enabling the userDoc to be cleaned up by the garbage collector.
877 doc.setRootElement(new Element("Empty"));
878
879 return element;
880 }
881
882
883 /** Saves a JDOM Element containing the user preferences for a user with
884 * a given uid. */
885 private void saveSharedPreferencesElement( Element element)
886 throws IOException, JDOMException
887 {
888 File file = getSharedPreferencesFile();
889 File dir = file.getParentFile();
890 dir.mkdirs();
891
892 backupFile(file);
893
894 OutputStream oStream =
895 new BufferedOutputStream (new FileOutputStream (file));
896 Document userDocument = new Document();
897 userDocument.setRootElement(element);
898
899 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
900 outputter.output(userDocument, oStream);
901 oStream.close();
902
903 userDocument.setRootElement(new Element("Empty"));
904 }
905
906 /** Returns the SharedPrefences object used by the program. */
907 public synchronized SharedPreferences getSharedPreferences()
908 {
909 if (sharedPreferences != null)
910 return sharedPreferences;
911
912 try
913 {
914 Element element = readSharedPreferencesElement();
915 if (element == null)
916 sharedPreferences = new SharedPreferences();
917 else
918 sharedPreferences = SharedPreferences.getInstance(element);
919
920 }
921 catch (JDOMException ex)
922 {
923 sharedPreferences = new SharedPreferences();
924 }
925 catch (IOException ex)
926 {
927 sharedPreferences = new SharedPreferences();
928 }
929
930 return sharedPreferences;
931 }
932
933 private void saveSharedPreferences() throws IOException, JDOMException
934 {
935 if (sharedPreferences == null)
936 return;
937
938 Element element = sharedPreferences.getXmlElement();
939 saveSharedPreferencesElement(element);
940 }
941
942
943 //======================== Working with Transactions =====================//
944
945 public synchronized boolean addTransaction (
946 Transaction transaction, int cMonth, int cYear) throws IOException,
947 JDOMException
948 {
949 Element monthElement = getMonthElement(cMonth, cYear);
950 Month.addTransaction(monthElement, transaction);
951 return true;
952 }
953
954 public synchronized boolean removeTransaction (
955 long transactionID, int cMonth, int cYear) throws IOException,
956 JDOMException
957 {
958 Element monthElement = getMonthElement(cMonth, cYear);
959 Month.removeTransaction(monthElement, transactionID);
960 return true;
961 }
962
963 //======================== Working with Allocations =====================//
964
965 public synchronized boolean addAllocation (
966 Transaction allocation, int cMonth, int cYear) throws IOException,
967 JDOMException
968 {
969 Element monthElement = getMonthElement(cMonth, cYear);
970 Month.addAllocation(monthElement, allocation);
971 return true;
972 }
973
974 public synchronized boolean removeAllocation (
975 long allocationID, int cMonth, int cYear) throws IOException,
976 JDOMException
977 {
978 Element monthElement = getMonthElement(cMonth, cYear);
979 Month.removeAllocation(monthElement, allocationID);
980 return true;
981 }
982
983 //======================= General Methods ===========================//
984
985 /** Writes all JDOME elements stored in the cache and the data index
986 * to the permanent storage.
987 */
988 public synchronized void commit() throws IOException, JDOMException
989 {
990 //Long time = System.currentTimeMillis();
991
992 //saving the data index.
993 storeIndex();
994
995 //saving month elements.
996 Set<Integer> dateSet = monthElementsMap.keySet();
997 for (Integer date: dateSet)
998 {
999 int cYear = date.intValue()/100;
1000 int cMonth = date.intValue() - cYear*100;
1001 Element monthElement = monthElementsMap.get(date);
1002 saveMonthElement(monthElement, cMonth, cYear);
1003 }
1004
1005 //saving budget elements
1006 Set<Integer> idSet = budgetElementsMap.keySet();
1007 for (Integer id: idSet)
1008 {
1009 int iId = id.intValue();
1010 Element budgetElement = budgetElementsMap.get(iId);
1011 saveBudgetElement(budgetElement, iId);
1012 }
1013
1014 //Saving Account elements
1015 Set<Integer> accountIdSet = accountElementsMap.keySet();
1016 for (Integer id: accountIdSet)
1017 {
1018 int iId = id.intValue();
1019 Element accountElement = accountElementsMap.get(iId);
1020 saveAccountElement(accountElement, iId);
1021 }
1022
1023 //Saving User elements
1024 Set<Integer> uidSet = userElementsMap.keySet();
1025 for (Integer uid: uidSet)
1026 {
1027 int iuid = uid.intValue();
1028 Element userElement = userElementsMap.get(iuid);
1029 saveUserElement(userElement, iuid);
1030 }
1031
1032 //Saving preferences
1033 uidSet = userPreferencesElementsMap.keySet();
1034 for (Integer uid: uidSet)
1035 {
1036 int iuid = uid.intValue();
1037 Element userElement = userPreferencesElementsMap.get(iuid);
1038 saveUserPreferencesElement(userElement, iuid);
1039 }
1040
1041 saveSharedPreferences();
1042
1043 //time = System.currentTimeMillis() - time;
1044 //System.out.println("Commit completed in " + time + " milliseconds.");
1045 }
1046
1047
1048 /** Returns string ID of this instance of the storage interface. */
1049 public String getIdString()
1050 {
1051 return "Local storage at " + rootDirectory.getAbsolutePath();
1052 }
1053
1054 //====================== Utils =================================//
1055
1056 /** Returns a File object that is initialized to point to the xml
1057 * file corresponding to the given month
1058 */
1059 private File getMonthFile (int cMonth, int cYear)
1060 {
1061 // Buliding a path tho the file for the given month
1062 String separator = File.separator;
1063 String yearStr = Integer.toString(cYear);
1064 String monthStr = (new DateFormater()).formatMonth(cMonth);
1065
1066 StringBuffer buffer = new StringBuffer();
1067 buffer.append("months");
1068 buffer.append(separator);
1069 buffer.append(yearStr);
1070 buffer.append(separator);
1071 buffer.append(monthStr);
1072 buffer.append(".xml");
1073 String path = buffer.toString();
1074
1075 return new File(rootDirectory, path);
1076 }
1077
1078 /** Returns a File object that is initialized to point to the xml
1079 * file corresponing to the Budget with a given id.
1080 */
1081 private File getBudgetFile(int id)
1082 {
1083 // Buliding a path to the file for the given budget
1084 String separator = File.separator;
1085 String idStr = Integer.toString(id);
1086
1087 StringBuffer buffer = new StringBuffer();
1088 buffer.append("budgets");
1089 buffer.append(separator);
1090 buffer.append(idStr);
1091 buffer.append(".xml");
1092 String path = buffer.toString();
1093
1094 return new File(rootDirectory, path);
1095 }
1096
1097 /** Returns a File object that is initialized to point to the xml
1098 * file corresponing to the Account with a given id.
1099 */
1100 private File getAccountFile(int id)
1101 {
1102 // Buliding a path to the file for the given account
1103 String separator = File.separator;
1104 String idStr = Integer.toString(id);
1105
1106 StringBuffer buffer = new StringBuffer();
1107 buffer.append("accounts");
1108 buffer.append(separator);
1109 buffer.append(idStr);
1110 buffer.append(".xml");
1111 String path = buffer.toString();
1112
1113 return new File(rootDirectory, path);
1114 }
1115
1116 /** Returns a File object that is initialized to point to the xml
1117 * file corresponing to the User with a given uid.
1118 */
1119 private File getUserFile(int uid)
1120 {
1121 // Buliding a path to the file for the given account
1122 String separator = File.separator;
1123 String idStr = Integer.toString(uid);
1124
1125 StringBuffer buffer = new StringBuffer();
1126 buffer.append("users");
1127 buffer.append(separator);
1128 buffer.append(idStr);
1129 buffer.append(".xml");
1130 String path = buffer.toString();
1131
1132 return new File(rootDirectory, path);
1133 }
1134
1135 /** Returns a File object that is initialized to point to the xml
1136 * file corresponing to the UserPreferences for the user with a given uid.
1137 */
1138 private File getUserPreferencesFile(int uid)
1139 {
1140 // Buliding a path to the file for the given account
1141 String separator = File.separator;
1142 String idStr = Integer.toString(uid);
1143
1144 StringBuffer buffer = new StringBuffer();
1145 buffer.append("users");
1146 buffer.append(separator);
1147 buffer.append("preferences");
1148 buffer.append(separator);
1149 buffer.append(idStr);
1150 buffer.append(".xml");
1151 String path = buffer.toString();
1152
1153 return new File(rootDirectory, path);
1154 }
1155
1156 private File getSharedPreferencesFile()
1157 {
1158 return new File(rootDirectory, "shared_preferences.xml");
1159 }
1160
1161
1162 //========================== Generating IDs =============================//
1163
1164 /** Creates a new numeric budget id and increases the counter. */
1165 public int generateBudgetID(){
1166 return dataIndex.generateBudgetID();
1167 }
1168
1169 /** Creates a new numeric account id and increases the counter. */
1170 public int generateAccountID(){
1171 return dataIndex.generateAccountID();
1172 }
1173
1174 /** Creates a new numeric id for an expense category
1175 * and increases the counter. */
1176 public int generateExpenseCategoryID(){
1177 return dataIndex.generateExpenseCategoryID();
1178 }
1179
1180 /** Creates a new numeric id for an income source
1181 * and increases the counter. */
1182 public int generateIncomeSourceID(){
1183 return dataIndex.generateIncomeSourceID();
1184 }
1185
1186 /** Creates a new uid for a new user
1187 * and increases the counter. */
1188 public int generateUID(){
1189 return dataIndex.generateUID();
1190 }
1191
1192 /** Creates a new numeric transaction id for
1193 * and increases the counter. */
1194 public long generateTransactionID(){
1195 return dataIndex.generateTransactionID();
1196 }
1197
1198 //========================== Creating Backups =============================//
1199
1200 /** Creates a backup of a given file. */
1201 private void backupFile(File file) throws IOException
1202 {
1203 if (!file.exists())
1204 return;
1205
1206 if (!file.canRead())
1207 throw new IOException("Cannot read file " + file.getAbsolutePath());
1208
1209 String backup_file_path = file.getAbsolutePath() + ".bkp";
1210 File backup_file = new File(backup_file_path);
1211
1212 if (backup_file.exists())
1213 backup_file.delete();
1214
1215 backup_file.createNewFile();
1216
1217 BufferedReader inputStream = null;
1218 PrintWriter outputStream = null;
1219
1220 try
1221 {
1222 inputStream =
1223 new BufferedReader(new FileReader(file));
1224 outputStream =
1225 new PrintWriter(new FileWriter(backup_file));
1226
1227 String l;
1228 while ((l = inputStream.readLine()) != null)
1229 outputStream.println(l);
1230 }
1231 finally
1232 {
1233 if (inputStream != null)
1234 inputStream.close();
1235 if (outputStream != null)
1236 outputStream.close();
1237 }
1238
1239 }
1240
1241 }