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     * DataIndex.java
024     *
025     * Created on April 18, 2006, 4:31 PM
026     */
027    
028    package org.jbudget.io;
029    
030    import java.text.ParseException;
031    import java.util.ArrayList;
032    import java.util.Calendar;
033    import java.util.Collections;
034    import java.util.HashMap;
035    import java.util.LinkedList;
036    import java.util.List;
037    import java.util.Map;
038    import org.jdom.Attribute;
039    import org.jdom.Element;
040    import org.jdom.JDOMException;
041    import org.jbudget.Core.Account;
042    import org.jbudget.Core.Budget;
043    import org.jbudget.Core.Month;
044    import org.jbudget.Core.User;
045    import org.jbudget.util.DateFormater;
046    import org.jbudget.util.Pair;
047    
048    /** An object that stores an index of all available 
049     *  Month objects.
050     *
051     * @author petrov
052     */
053    public class DataIndex
054    {
055      /** A list of valid years */
056      private List<Integer> validYears = new ArrayList<Integer>();
057      
058      /** A map that connects a year to a list of valid months for that year */
059      private Map<Integer, List<Integer>> validMonths = 
060          new HashMap<Integer, List<Integer>>();
061      
062      /** A map of year*100+month to the Month objects */
063      private Map<Integer, Month> months = new HashMap<Integer, Month>();
064      
065      /** A list of {@link org.petrov.dmitri.jbudget.util.Pair Pairs} of  budgetIDs 
066       *  and names of the budgets that are active.<br>
067       *  This has different meaning for the index of data in the memory and
068       *  on the disk or on a server. In the case when this object is used 
069       *  as an index of data in the memory (current work set) the map describes
070       *  the budget objects that have been loaded from the permanent storage and
071       *  currently reside in memory. Any budget from this list can be accessed by
072       *  calling {@link #getBudget(int) getBudget(budgetID)}.
073       *  In the case when this object is used to index
074       *  the data available in permanent storage, the map just contains all numeric
075       *  ids and names of all budgets available in storage.
076       */
077      private List<Pair<Integer, String>> validBudgets = 
078          new ArrayList<Pair<Integer, String>>();
079      
080      /** A map of numeric budget ID's and budgets. */
081      private Map<Integer, Budget> budgets = new HashMap<Integer, Budget>();
082      
083      /** A list of valid accounts. Works pretty much the same way as the list of
084       *  valid budgets
085       */
086      private List<Pair<Integer, String>> validAccounts =
087          new ArrayList<Pair<Integer, String>>();
088      
089      /** A map of numberic account ID's and Accounts. */
090      private Map<Integer, Account> accounts = new HashMap<Integer, Account>();
091      
092      /** A list of uids/names of users */
093      private List<Pair<Integer, String>> validUsers =
094          new ArrayList<Pair<Integer, String>>();
095      
096      /** A map of uids and User objects */
097      private Map<Integer, User> users = new HashMap<Integer, User>();
098      
099      /** If this flag is true the object does not store any Month instances.
100       *  An attempt to add a Month or to get a month will cause an exception.
101       */
102      final private boolean haveData;
103      
104      //=========================== Counters ==================================//
105      
106      /** A counter that is used for assinging IDs to Budgets */
107      private int budgetCounter = 0;
108      
109      /** A counter that is used for assigning IDs to Accounts */
110      private int accountCounter = 0;
111      
112      /** A counter that is used for assigning IDs to ExpenseCategories 
113       * and income sources.
114       */
115      private int categoryCounter = 0;
116      
117      /** A counter that is used for assigning IDs to Transactions */
118      private long transactionCounter = 0L;
119      
120      /** A user counter */
121      private int userCounter = 1;
122      
123      //========================= End Counters ================================//
124      
125      /** Creates a new instance of DataIndex */
126      public DataIndex(boolean storeData)
127      {
128        this.haveData = storeData;
129      }
130      
131      /** Returns a list of years that have at least one valid month (a month
132       * for which we have a Month object)
133       */
134      synchronized public List<Integer> getValidYears(){
135        return Collections.unmodifiableList(validYears);
136      }
137      
138      /** Returns a list of valid months for a given year */
139      synchronized public List<Integer> getValidMonths(int year){
140        List<Integer> months_list = validMonths.get(new Integer(year));
141        if (months_list == null)
142          return Collections.emptyList();
143        return Collections.unmodifiableList(months_list);
144      }
145      
146      //=========================== MONTHS ===================================//
147      
148      /** Returns true if we have a Month object for the given year/month
149       * combination
150       */
151      synchronized public boolean isValidMonth(int month, int year)
152      {
153        assert month >= Calendar.JANUARY  &&  month <= Calendar.DECEMBER : 
154                                                         "Invalid month: " + month;
155        List<Integer> months = validMonths.get(new Integer(year));
156        if (months == null)
157          return false;
158        return months.contains(new Integer(month));
159      }
160      
161      /** Returns the Month object that represents the given year/month
162       *  combination.
163       * @throws UnsupportedOperationException if this object is used in indexing
164       *         only mode (a 'false' is passed to the constructor).
165       */
166      synchronized public Month getMonth(int month, int year)
167      {
168        if (!haveData)
169          throw new UnsupportedOperationException();
170        assert month >= Calendar.JANUARY && month <= Calendar.DECEMBER : 
171                                                          "Invalid Month: " + month;
172        return months.get(new Integer(year*100 + month));
173      }
174      
175      /** Adds or replaces a Month object that is associated with the given
176       * year/month combination
177       * @throws UnsupportedOperationException if this object is used in indexing
178       *         only mode ('false' is passed to the constructor).
179       */
180      synchronized public void addMonth(Month monthObject)
181      {
182        if (!haveData)
183          throw new UnsupportedOperationException();
184        int month = monthObject.getMonth();
185        int year = monthObject.getYear();
186        registerMonthPrivate(month, year);
187        Integer iMYear = new Integer(year * 100 + month);
188        months.put(iMYear, monthObject);
189      }
190      
191      /** Removes a Month object from this data index.
192       * @throws UnsupportedOperationException if this object is used in indexing
193       *         only mode ('false' is passed to the constructor).
194       * @throws IllegalArgumentException if the Month is not present in the data
195       *         index.
196       */
197       synchronized public void removeMonth(Month monthObject){
198        if (!haveData)
199          throw new UnsupportedOperationException();
200        int month = monthObject.getMonth();
201        int year = monthObject.getYear();
202        unregisterMonthPrivate(month, year);
203        Integer iMYear = new Integer(year * 100 + month);
204        assert months.get(iMYear) != null;
205        months.remove(iMYear);
206      }
207      
208      /**
209       * Registers a month object by marking that there is a month object
210       *  that corresponds to the given year/month combination. This function
211       *  sould be used only when the DataIndex is used in indexing only mode and
212       *  does not store any month objects. In the opposite case use 
213       *  {@link #addMonth(Month) addMonth}.
214       * 
215       * @throws UnsupportedOperationException if this object is not used in indexing
216       *        only mode ('true' is passed to the constructor).
217       */
218       synchronized public void registerMonth(int month, int year){
219        if (haveData)
220          throw new UnsupportedOperationException();
221        
222        registerMonthPrivate(month, year);
223      }
224      
225      /** Unregisteres a month object by removing all information related to it
226       *  from this data index. This function sould be used only when the DataIndex
227       *  is used in indexing only mode. In the opposite case use 
228       *  {@link #removeMonth(Month) removeMonth}.
229       *
230       *@throws UnsupportedOperationException if this object is not used in indexing
231       *        only mode ('true' is passed to the constructor).
232       *@throws IllegalArgumentException if the month that is bein passed to this
233       *        function is not present in this index.
234       */
235       synchronized public void unregisterMonth(int month, int year){
236        if (haveData)
237          throw new UnsupportedOperationException();
238        
239        unregisterMonthPrivate(month, year);
240      }
241      
242      /**
243       * Actually does the work necessary to make a record that a month is valid.
244       * 
245       * @see #registerMonth(int, int)
246       * @see #addMonth(Month)
247       */
248      private void registerMonthPrivate(int month, int year)
249      {
250        Integer iYear = new Integer(year);
251        Integer iMonth = new Integer(month);
252        List<Integer> vMonths = validMonths.get(iYear);
253        if (vMonths == null){
254          vMonths = new LinkedList<Integer>();
255          validMonths.put(iYear,vMonths);
256          vMonths.add(iMonth);
257          int index =  Collections.binarySearch(validYears, iYear);
258          assert index < 0;
259          validYears.add(-1-index,iYear);
260        } else {
261          int index = Collections.binarySearch(vMonths,iMonth);
262          if (index < 0)
263            vMonths.add(-1-index, iMonth);
264        }
265      }
266      
267      /** Actually does the work to remove information about a month object.
268       * @see #unregisterMonth(int, int)
269       * @see #removeMonth(Month)
270       * @throws IllegalArgumentException if no record for the current month exists.
271       */
272      private void unregisterMonthPrivate(int month, int year)
273      {
274        Integer iYear = new Integer(year);
275        Integer iMonth = new Integer(month);
276        if (!validYears.contains(iYear))
277          throw new IllegalArgumentException("Trying to remove month that is " +
278              "not present in the date index. Month " + month + ", year = " +
279              year);
280        List<Integer> vMonths = validMonths.get(iYear);
281        if ( vMonths == null || (!vMonths.contains(iMonth)))
282          throw new IllegalArgumentException("Trying to remove month that is " +
283              "not present in the date index. Month " + month + ", year = " +
284              year);
285        vMonths.remove(iMonth);
286        if (vMonths.isEmpty()){
287          validMonths.remove(iYear);
288          validYears.remove(iYear);
289        }
290      }
291      
292      /** Returns a list containing {@link org.petrov.dmitri.jbudget.util.Pair 
293       * Pairs}  of ids and  names of all valid Budgets */
294      public List<Pair<Integer,String>> getValidBudgets(){
295        return Collections.unmodifiableList(validBudgets);
296      }
297      
298      //=========================== BUDGETS ===================================//
299      
300      /** adds information about a Budget instance to the list of valid budgets.
301       * @throws IllegalStateException if a budget with given id is already
302       *         present.
303       *@throws UnsupportedOperationException if this object is not used in indexing
304       *        only mode ('true' is passed to the constructor).
305       */
306      synchronized public void registerBudget(int id, String name) 
307      {
308        if (haveData)
309          throw new UnsupportedOperationException();
310        registerBudgetPrivate(id, name) ;
311        assert isValidBudget(id);
312      }
313          
314      /** adds information about a Budget instance to the list of valid budgets.
315       * @throws IllegalStateException if a budget with given id is already
316       *         present.
317       */
318      private void registerBudgetPrivate(int id, String name) 
319      {
320        addToList(validBudgets, new Integer(id), name, "budget");
321      }
322      
323      
324      /** removes information about a Budget instance from the list of valid
325       *  budgets.
326       * @throws IllegalArgumentException if no budget with the given id exists.
327       * @throws UnsupportedOperationException if this object is not used in indexing
328       *        only mode ('true' is passed to the constructor).
329       */
330      synchronized public void unregisterBudget(int id) 
331      {
332        if (haveData)
333          throw new UnsupportedOperationException();
334        unregisterBudgetPrivate(id);
335        assert !isValidBudget(id);
336      }
337      
338      /** removes information about a Budget instance from the list of valid
339       *  budgets.
340       * @throws IllegalArgumentException if no budget with the given id exists.
341       */
342      private void unregisterBudgetPrivate(int id)
343      {
344        removeFromList(validBudgets, new Integer(id), "budget");
345      }
346      
347      /** Returns a Budget object with the given numeric ID.
348       * @throws UnsupportedOperationException if this object is used in indexing
349       *         only mode ('false' is passed to the constructor).
350       * @throws IllegalArguementException if there is no budget with such id.
351       */
352      synchronized public Budget getBudget(int id)
353      {
354        if (!haveData)
355          throw new UnsupportedOperationException();
356        Budget budget = budgets.get(new Integer(id));
357        if (budget == null)
358          throw new IllegalArgumentException(
359              "Can not find a budget with a given ID");
360        return budget;
361      }
362      
363      /** Stores the budget.
364       * @throws UnsupportedOperationException if this object is used in indexing
365       *         only mode ('false' is passed to the constructor).
366       */
367      synchronized public void addBudget(Budget budget)
368      {
369        if (!haveData)
370          throw new UnsupportedOperationException();
371        registerBudgetPrivate(budget.getID(), budget.getName());
372        budgets.put(new Integer(budget.getID()), budget);
373        assert isValidBudget(budget.getID());
374      }
375      
376      /** Removes a budget with a given numeric ID.  
377       * @throws UnsupportedOperationException if this object is used in indexing
378       *         only mode ('false' is passed to the constructor).
379       * @throws IllegalArgumentException if no budget with the given id exists.
380       */
381      synchronized public void removeBudget(int id)
382      {
383        if (!haveData)
384          throw new UnsupportedOperationException();
385        unregisterBudgetPrivate(id);
386        budgets.remove(new Integer(id));
387        assert !isValidBudget(id);
388      }
389      
390      
391      /** Returns true if there is a Budget with such id */
392      synchronized public boolean isValidBudget(int id){
393        return getFromList(validBudgets, new Integer(id)) != null;
394      }
395      
396      //============================ ACCOUNTS =================================//
397      
398      /** Returns true if there is an account with a given ID */
399      synchronized public boolean isValidAccount(int id){
400        return getAccountName(id) != null;
401      }
402      
403      /** Returns an unmodifiable list that contains numerical IDs and names of
404       * all valid accounts
405       */
406      synchronized public List<Pair<Integer, String>> getAccountInfo(){
407        return Collections.unmodifiableList(validAccounts);
408      }
409      
410      /** Returns the name of the account that has a given ID */
411      synchronized public String getAccountName(int id) {
412        return getFromList(validAccounts, new Integer(id));
413      }
414      
415      /** Returns an account with a given ID. 
416       *@throws an UnsupportedOperationException if haveData is false.
417       */
418      synchronized public Account getAccount(int id){
419        if (!haveData)
420          throw new UnsupportedOperationException();
421        return accounts.get(new Integer(id));
422      }
423      
424      /** Stores an account in this index 
425       *@throws an UnsupportedOperationException if haveData is false.
426       */
427      synchronized public void addAccount(Account account){
428        if (!haveData)
429          throw new UnsupportedOperationException();
430        accounts.put(new Integer(account.getID()), account);
431        registerAccountPrivate(account.getID(), account.getName());
432      }
433      
434      /** Removes all information about an account with a given id.
435       *@throws an UnsupportedOperationException if haveData is false.
436       */
437      synchronized public void removeAccount(int accountID){
438        if (!haveData)
439          throw new UnsupportedOperationException();
440        accounts.remove(new Integer(accountID));
441        unregisterAccountPrivate(accountID);
442      }
443      
444      /** Records information about account. Should only be used when the DataIndex
445       * object is in indexing only mode (haveData is false).
446       *@throws an UnsupportedOperationException if haveData is true.
447       */
448      synchronized public void registerAccount(int accountID, String accountName){
449        if (haveData)
450          throw new UnsupportedOperationException();
451        registerAccountPrivate(accountID, accountName);
452      }
453      
454      /** Actually does the work of registering the account */
455      synchronized private void registerAccountPrivate(
456          int accountID, String accountName)
457      {
458        addToList(validAccounts, new Integer(accountID), accountName, "account");
459      }
460      
461      /** Removes a record of information about account.Should only be used when 
462       * the DataIndex object is in indexing only mode (haveData is false).
463       *  @throws an UnsupportedOperationException if haveData is true.
464       *  @throws na IllegalArgumentException if there is no account with such ID.
465       */
466      synchronized public void unregisterAccount(int accountID){
467        if (haveData)
468          throw new UnsupportedOperationException();
469        unregisterAccountPrivate(accountID);
470      }
471        
472      /** Acutally does the work on unregestering the account */
473      synchronized private void unregisterAccountPrivate(int accountID){
474        removeFromList(validAccounts, new Integer(accountID), "account");
475      }
476      
477      //============================ USERS ===================================//
478      
479      /** Returns true if there is a user with a given ID */
480      synchronized public boolean isValidUser(int uid){
481        return getUserName(uid) != null;
482      }
483      
484      /** Returns an unmodifiable list that contains UIDs and names of
485       * all valid users
486       */
487      synchronized public List<Pair<Integer, String>> getUserInfo(){
488        return Collections.unmodifiableList(validUsers);
489      }
490      
491      /** Returns the name of the user that has a given UID */
492      synchronized public String getUserName(int uid) {
493        return getFromList(validUsers, new Integer(uid));
494      }
495      
496      /** Returns an user with a given UID. 
497       *@throws an UnsupportedOperationException if haveData is false.
498       */
499      synchronized public User getUser(int uid){
500        if (!haveData)
501          throw new UnsupportedOperationException();
502        return users.get(new Integer(uid));
503      }
504      
505      /** Stores an user in this index 
506       *@throws an UnsupportedOperationException if haveData is false.
507       */
508      synchronized public void addUser(User user){
509        if (!haveData)
510          throw new UnsupportedOperationException();
511        users.put(new Integer(user.getUID()), user);
512        registerUserPrivate(user.getUID(), user.getName());
513      }
514      
515      /** Removes all information about an user with a given uid.
516       *@throws an UnsupportedOperationException if haveData is false.
517       */
518      synchronized public void removeUser(int uid){
519        if (!haveData)
520          throw new UnsupportedOperationException();
521        users.remove(new Integer(uid));
522        unregisterUserPrivate(uid);
523      }
524      
525      /** Records information about a user. Should only be used when the DataIndex
526       * object is in indexing only mode (haveData is false).
527       *@throws an UnsupportedOperationException if haveData is true.
528       */
529      synchronized public void registerUser(int uid, String userName){
530        if (haveData)
531          throw new UnsupportedOperationException();
532        registerUserPrivate(uid, userName);
533      }
534      
535      /** Actually does the work of registering the user */
536      synchronized private void registerUserPrivate(
537          int uid, String userName)
538      {
539        addToList(validUsers, new Integer(uid), userName, "user");
540      }
541      
542      /** Removes a record of information about a user. Should only be used when 
543       * the DataIndex object is in indexing only mode (haveData is false).
544       *  @throws an UnsupportedOperationException if haveData is true.
545       *  @throws na IllegalArgumentException if there is no user with such ID.
546       */
547      synchronized public void unregisterUser(int uid){
548        if (haveData)
549          throw new UnsupportedOperationException();
550        unregisterUserPrivate(uid);
551      }
552        
553      /** Acutally does the work on unregestering the user */
554      synchronized private void unregisterUserPrivate(int uid){
555        removeFromList(validUsers, new Integer(uid), "user");
556      }
557      
558      //========================== Generating IDs=============================//
559      
560      /** Creates a new numeric budget id and increases the counter. */
561      synchronized public int generateBudgetID(){
562        return ++budgetCounter;
563      }
564      
565      /** Creates a new numeric account id and increases the counter. */
566      synchronized public int generateAccountID(){
567        return ++accountCounter;
568      }
569      
570      /** Creates a new numeric id for an expense category 
571       * and increases the counter. */
572      synchronized public int generateExpenseCategoryID(){
573        return ++categoryCounter;
574      }
575      
576      /** Creates a new numeric id for an income source 
577       * and increases the counter. */
578      synchronized public int generateIncomeSourceID(){
579        return ++categoryCounter;
580      }
581      
582      /** Creates a new uid for a new user 
583       * and increases the counter. */
584      synchronized public int generateUID(){
585        return ++userCounter;
586      }
587      
588      /** Creates a new numeric transaction id for 
589       * and increases the counter. */
590      synchronized public long generateTransactionID(){
591        return ++transactionCounter;
592      }
593      
594      //============================ Convenience Methods ======================//
595      
596      /** Used to add a pair Integer, String and such to sorted lists and 
597       *  maintain sorting. Used in various registerXXXXPrivate methods.
598       */
599      private static <T extends Comparable, E> void addToList(List<Pair<T, E>> list,
600          T index, E data, String name)
601      {
602        Pair<T, E> newPair = new Pair(index, data);
603        for (int i = 0, s = list.size(); i < s; i++){
604          T curr_index = list.get(i).first();
605          if (curr_index.equals(index))
606          {
607            list.remove(i);
608            list.add(i, newPair);
609            return;
610          }
611          else if (index.compareTo(curr_index) > 0)
612          {
613            list.add(i, newPair);
614            return;
615          }
616        }
617        list.add(newPair);
618      }
619      
620      /** Removes a generic pair index/data (i.e. Integer, String) from a sorted
621       *  list and maintans sorting. Used in most unregisterXXXXPrivate methods.
622       */
623      private static <T extends Comparable, E> void removeFromList(
624          List<Pair<T, E>> list, T index, String name)
625      {
626        Pair<T, E> target = null;
627        int i = 0;
628        for (Pair<T,E> pair : list){
629          if (pair.first().compareTo(index) < 0)
630            break;
631          else if (pair.first().equals(index)){
632            target = pair;
633            break;
634          }
635          i++;
636        }
637            
638        if (target != null)
639          list.remove(i);
640        else
641          throw new IllegalArgumentException(
642              "Asked to unregister nonexistent " + name);
643      }
644      
645      /** Searches the list of pairs index/data for a pair with a give index
646       *  and returns the data
647       */
648      private static <T extends Comparable, E> E getFromList( 
649          List<Pair<T, E>> list, T index)
650      {
651        for (Pair<T,E> pair : list)
652          if (pair.first().compareTo(index) < 0)
653            return null;
654          else if (pair.first().equals(index))
655            return pair.second();
656          
657        return null;
658      }
659      
660      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
661      
662      /** Returns true if the index is used in indexing only mode. That is, if
663       *  the DataIndex object does not store any Month objects
664       */
665      public boolean indexingMode(){
666        return !haveData;
667      }
668      
669      @Override
670      public String toString()
671      {
672        DateFormater dateFormater = new DateFormater();
673        
674        StringBuffer buffer = new StringBuffer();
675        buffer.append("Valid Months:\n");
676        List<Integer> yearList = getValidYears();
677        for (Integer iYear : yearList){
678          buffer.append(iYear + ":");
679          List<Integer> monthList = getValidMonths(iYear.intValue());
680          for (Integer iMonth : monthList){
681            buffer.append(dateFormater.formatMonth(iMonth.intValue()));
682            buffer.append(" ");
683          }
684          buffer.append("\n");
685        }
686        
687        buffer.append("Valid Budgets:");
688        List<Pair<Integer,String>> budgetList = getValidBudgets();
689        for (Pair<Integer,String> budgetPair : budgetList){
690          buffer.append("ID: ");
691          buffer.append(budgetPair.first());
692          buffer.append(", name: ");
693          buffer.append(budgetPair.second());
694          buffer.append("\n");
695        }
696        
697        buffer.append("Valid Accounts:");
698        List<Pair<Integer,String>> accountList = getAccountInfo();
699        for (Pair<Integer,String> pair : accountList){
700          buffer.append("ID: ");
701          buffer.append(pair.first());
702          buffer.append(", name: ");
703          buffer.append(pair.second());
704          buffer.append("\n");
705        }
706        
707        buffer.append("Users:");
708        List<Pair<Integer,String>> userList = getAccountInfo();
709        for (Pair<Integer,String> pair : userList){
710          buffer.append("UID: ");
711          buffer.append(pair.first());
712          buffer.append(", name: ");
713          buffer.append(pair.second());
714          buffer.append("\n");
715        }
716        
717        return buffer.toString();
718      }
719      
720      
721      //================ Converting to and from JDOM Elements ==========//
722      
723      /** Returns a JDOM XML Element representation of the current budget */
724      synchronized public Element getXmlElement()
725      {
726        DateFormater formater = new DateFormater();
727        
728        if (!indexingMode())
729          throw new UnsupportedOperationException("Can not convert DataIndex " +
730              "object to JDOM Element \n The DataIndex object must be in indexing-" +
731              "only mode");
732        
733        Element dataIndexElement = new Element("data_index");
734        
735        for (Integer iYear : getValidYears())
736        {
737          Element yearElement = new Element("year");
738          yearElement.setAttribute("year", iYear.toString());
739          dataIndexElement.addContent(yearElement);
740          for (Integer iMonth : getValidMonths(iYear.intValue()))
741          {
742            Element monthElement = new Element("month");
743            monthElement.setAttribute("month", 
744                formater.formatMonth(iMonth.intValue()));
745            yearElement.addContent(monthElement);
746          }
747        }
748        
749        for (Pair<Integer, String> p : getValidBudgets())
750        {
751          Element budgetElement = new Element("budget");
752          budgetElement.setAttribute("id", p.first().toString());
753          budgetElement.setAttribute("name", p.second());
754          dataIndexElement.addContent(budgetElement);
755        }
756        
757        for (Pair<Integer, String> p : getAccountInfo())
758        {
759          Element accountElement = new Element("account");
760          accountElement.setAttribute("id", p.first().toString());
761          accountElement.setAttribute("name", p.second());
762          dataIndexElement.addContent(accountElement);
763        }
764        
765        for (Pair<Integer, String> p : getUserInfo())
766        {
767          Element userElement = new Element("user");
768          userElement.setAttribute("uid", p.first().toString());
769          userElement.setAttribute("name", p.second());
770          dataIndexElement.addContent(userElement);
771        }
772        
773        // Saving counters
774        Element countersElement = new Element("counters");
775        dataIndexElement.addContent(countersElement);
776        countersElement.setAttribute(
777            "budget_counter", Integer.toString(budgetCounter));
778        countersElement.setAttribute(
779            "account_counter", Integer.toString(accountCounter));
780        countersElement.setAttribute(
781            "category_counter", Integer.toString(categoryCounter));
782        countersElement.setAttribute(
783            "user_counter", Integer.toString(userCounter));
784        countersElement.setAttribute(
785            "transaction_counter", Long.toString(transactionCounter));
786        
787        return dataIndexElement;
788      }
789      
790      
791      /** Parses JDOM Element into a {@link DataIndex DataIndex} object. The 
792       *  {@link DataIndex DataIndex} object created by this function works in 
793       *  indexing only mode. 
794       *  @throws JDOMException in case of parsing errors.
795       */
796      public static DataIndex getInstance(Element element) throws JDOMException
797      {
798        DataIndex dataIndex = new DataIndex(false);
799        DateFormater formater = new DateFormater();
800        
801        if (!element.getName().equals("data_index"))
802          throw new JDOMException("Bad JDOM Element. Expected: data_index, got: " +
803              element.getName());
804        
805        // Reading valid months
806        List<Element> yearElements = element.getChildren("year");
807        try{
808          for (Element yearElement : yearElements)
809          {
810            int cYear = yearElement.getAttribute("year").getIntValue();
811            List<Element> monthElements = yearElement.getChildren("month");
812            for (Element monthElement : monthElements){
813              int cMonth = formater.parseMonth(
814                  monthElement.getAttribute("month").getValue());
815              dataIndex.registerMonth(cMonth, cYear);
816            }
817          }
818        } catch (ParseException ex) {
819          throw new JDOMException(ex.getMessage());
820        }
821        
822        
823        //Reading budgets
824        List<Element> budgetElements = element.getChildren("budget");
825        for (Element budgetElement : budgetElements)
826        {
827          Attribute idAttr = budgetElement.getAttribute("id");
828          if (idAttr == null)
829            throw new JDOMException("Bad budget element. No id attribute");
830          int id = idAttr.getIntValue();
831          
832          Attribute nameAttr = budgetElement.getAttribute("name");
833          if (nameAttr == null)
834            throw new JDOMException("Bad budget element. No name attribute");
835          String name = nameAttr.getValue();
836          
837          dataIndex.registerBudget(id, name);
838        }
839        
840        
841        //Reading accounts
842        List<Element> accountElements = element.getChildren("account");
843        for (Element accountElement : accountElements)
844        {
845          Attribute idAttr = accountElement.getAttribute("id");
846          if (idAttr == null)
847            throw new JDOMException("Bad account element. No id attribute");
848          int id = idAttr.getIntValue();
849          
850          Attribute nameAttr = accountElement.getAttribute("name");
851          if (nameAttr == null)
852            throw new JDOMException("Bad account element. No name attribute");
853          String name = nameAttr.getValue();
854          
855          dataIndex.registerAccount(id, name);
856        }
857        
858        
859        //Reading users
860        List<Element> userElements = element.getChildren("user");
861        for (Element userElement : userElements)
862        {
863          Attribute idAttr = userElement.getAttribute("uid");
864          if (idAttr == null)
865            throw new JDOMException("Bad user element. No uid attribute");
866          int id = idAttr.getIntValue();
867          
868          Attribute nameAttr = userElement.getAttribute("name");
869          if (nameAttr == null)
870            throw new JDOMException("Bad user element. No name attribute");
871          String name = nameAttr.getValue();
872          
873          dataIndex.registerUser(id, name);
874        }
875        
876        
877        //Restoring counters
878        Element countersElement = element.getChild("counters");
879        if (countersElement == null)
880          throw new JDOMException("Bad Element. No counters information.");
881        
882        //System.out.println(countersElement.getAttributes());
883        
884        dataIndex.budgetCounter = 
885            countersElement.getAttribute("budget_counter").getIntValue();
886        dataIndex.accountCounter = 
887            countersElement.getAttribute("account_counter").getIntValue();
888        dataIndex.categoryCounter = 
889            countersElement.getAttribute("category_counter").getIntValue();
890        dataIndex.userCounter = 
891            countersElement.getAttribute("user_counter").getIntValue();
892        dataIndex.transactionCounter = 
893            countersElement.getAttribute("transaction_counter").getIntValue();
894        
895        return dataIndex;
896      }
897      
898      
899    }