]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
aa47d73d403cc456bf6fca05a7046e8dbd421241
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / RetrieveTransactionsTask.java
1 /*
2  * Copyright © 2021 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.async;
19
20 import android.annotation.SuppressLint;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.os.AsyncTask;
23 import android.os.OperationCanceledException;
24
25 import androidx.annotation.NonNull;
26
27 import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
28
29 import net.ktnx.mobileledger.App;
30 import net.ktnx.mobileledger.err.HTTPException;
31 import net.ktnx.mobileledger.json.API;
32 import net.ktnx.mobileledger.json.AccountListParser;
33 import net.ktnx.mobileledger.json.ApiNotSupportedException;
34 import net.ktnx.mobileledger.json.TransactionListParser;
35 import net.ktnx.mobileledger.model.Data;
36 import net.ktnx.mobileledger.model.LedgerAccount;
37 import net.ktnx.mobileledger.model.LedgerTransaction;
38 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
39 import net.ktnx.mobileledger.model.MobileLedgerProfile;
40 import net.ktnx.mobileledger.ui.MainModel;
41 import net.ktnx.mobileledger.utils.Logger;
42 import net.ktnx.mobileledger.utils.NetworkUtil;
43
44 import java.io.BufferedReader;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.io.InputStreamReader;
48 import java.net.HttpURLConnection;
49 import java.net.MalformedURLException;
50 import java.net.URLDecoder;
51 import java.nio.charset.StandardCharsets;
52 import java.text.ParseException;
53 import java.util.ArrayList;
54 import java.util.Collections;
55 import java.util.HashMap;
56 import java.util.List;
57 import java.util.Locale;
58 import java.util.Objects;
59 import java.util.regex.Matcher;
60 import java.util.regex.Pattern;
61
62
63 public class RetrieveTransactionsTask extends
64         AsyncTask<Void, RetrieveTransactionsTask.Progress, RetrieveTransactionsTask.Result> {
65     private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
66     private static final Pattern reComment = Pattern.compile("^\\s*;");
67     private static final Pattern reTransactionStart = Pattern.compile(
68             "<tr class=\"title\" " + "id=\"transaction-(\\d+)" + "\"><td class=\"date" +
69             "\"[^\"]*>([\\d.-]+)</td>");
70     private static final Pattern reTransactionDescription =
71             Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
72     private static final Pattern reTransactionDetails = Pattern.compile(
73             "^\\s+" + "([!*]\\s+)?" + "(\\S[\\S\\s]+\\S)\\s\\s+" + "(?:([^\\d\\s+\\-]+)\\s*)?" +
74             "([-+]?\\d[\\d,.]*)" + "(?:\\s*([^\\d\\s+\\-]+)\\s*$)?");
75     private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
76     private static final Pattern reDecimalPoint = Pattern.compile("\\.\\d\\d?$");
77     private static final Pattern reDecimalComma = Pattern.compile(",\\d\\d?$");
78     // %3A is '='
79     private final Pattern reAccountName =
80             Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
81     private final Pattern reAccountValue = Pattern.compile(
82             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
83     private final MainModel mainModel;
84     private final MobileLedgerProfile profile;
85     private final List<LedgerAccount> prevAccounts;
86     private int expectedPostingsCount = -1;
87     public RetrieveTransactionsTask(@NonNull MainModel mainModel,
88                                     @NonNull MobileLedgerProfile profile,
89                                     List<LedgerAccount> accounts) {
90         this.mainModel = mainModel;
91         this.profile = profile;
92         this.prevAccounts = accounts;
93     }
94     private static void L(String msg) {
95         //debug("transaction-parser", msg);
96     }
97     static LedgerTransactionAccount parseTransactionAccountLine(String line) {
98         Matcher m = reTransactionDetails.matcher(line);
99         if (m.find()) {
100             String postingStatus = m.group(1);
101             String acc_name = m.group(2);
102             String currencyPre = m.group(3);
103             String amount = Objects.requireNonNull(m.group(4));
104             String currencyPost = m.group(5);
105
106             String currency = null;
107             if ((currencyPre != null) && (currencyPre.length() > 0)) {
108                 if ((currencyPost != null) && (currencyPost.length() > 0))
109                     return null;
110                 currency = currencyPre;
111             }
112             else if ((currencyPost != null) && (currencyPost.length() > 0)) {
113                 currency = currencyPost;
114             }
115
116             amount = amount.replace(',', '.');
117
118             return new LedgerTransactionAccount(acc_name, Float.parseFloat(amount), currency, null);
119         }
120         else {
121             return null;
122         }
123     }
124     @Override
125     protected void onProgressUpdate(Progress... values) {
126         super.onProgressUpdate(values);
127         Data.backgroundTaskProgress.postValue(values[0]);
128     }
129     @Override
130     protected void onPostExecute(Result result) {
131         super.onPostExecute(result);
132         Progress progress = new Progress();
133         progress.setState(ProgressState.FINISHED);
134         progress.setError(result.error);
135         onProgressUpdate(progress);
136     }
137     @Override
138     protected void onCancelled() {
139         super.onCancelled();
140         Progress progress = new Progress();
141         progress.setState(ProgressState.FINISHED);
142         onProgressUpdate(progress);
143     }
144     private void retrieveTransactionListLegacy(List<LedgerAccount> accounts,
145                                                List<LedgerTransaction> transactions)
146             throws IOException, HTTPException {
147         Progress progress = Progress.indeterminate();
148         progress.setState(ProgressState.RUNNING);
149         progress.setTotal(expectedPostingsCount);
150         int maxTransactionId = -1;
151         HashMap<String, LedgerAccount> map = new HashMap<>();
152         LedgerAccount lastAccount = null;
153         ArrayList<LedgerAccount> syntheticAccounts = new ArrayList<>();
154
155         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
156         http.setAllowUserInteraction(false);
157         publishProgress(progress);
158         if (http.getResponseCode() != 200)
159             throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
160
161         try (InputStream resp = http.getInputStream()) {
162             if (http.getResponseCode() != 200)
163                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
164
165             int matchedTransactionsCount = 0;
166
167             ParserState state = ParserState.EXPECTING_ACCOUNT;
168             String line;
169             BufferedReader buf =
170                     new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
171
172             int processedTransactionCount = 0;
173             int transactionId = 0;
174             LedgerTransaction transaction = null;
175             LINES:
176             while ((line = buf.readLine()) != null) {
177                 throwIfCancelled();
178                 Matcher m;
179                 m = reComment.matcher(line);
180                 if (m.find()) {
181                     // TODO: comments are ignored for now
182 //                            Log.v("transaction-parser", "Ignoring comment");
183                     continue;
184                 }
185                 //L(String.format("State is %d", updating));
186                 switch (state) {
187                     case EXPECTING_ACCOUNT:
188                         if (line.equals("<h2>General Journal</h2>")) {
189                             state = ParserState.EXPECTING_TRANSACTION;
190                             L("→ expecting transaction");
191                             continue;
192                         }
193                         m = reAccountName.matcher(line);
194                         if (m.find()) {
195                             String acct_encoded = m.group(1);
196                             String accName = URLDecoder.decode(acct_encoded, "UTF-8");
197                             accName = accName.replace("\"", "");
198                             L(String.format("found account: %s", accName));
199
200                             lastAccount = map.get(accName);
201                             if (lastAccount != null) {
202                                 L(String.format("ignoring duplicate account '%s'", accName));
203                                 continue;
204                             }
205                             String parentAccountName = LedgerAccount.extractParentName(accName);
206                             LedgerAccount parentAccount;
207                             if (parentAccountName != null) {
208                                 parentAccount = ensureAccountExists(parentAccountName, map,
209                                         syntheticAccounts);
210                             }
211                             else {
212                                 parentAccount = null;
213                             }
214                             lastAccount = new LedgerAccount(accName, parentAccount);
215
216                             accounts.add(lastAccount);
217                             map.put(accName, lastAccount);
218
219                             state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
220                             L("→ expecting account amount");
221                         }
222                         break;
223
224                     case EXPECTING_ACCOUNT_AMOUNT:
225                         m = reAccountValue.matcher(line);
226                         boolean match_found = false;
227                         while (m.find()) {
228                             throwIfCancelled();
229
230                             match_found = true;
231                             String value = Objects.requireNonNull(m.group(1));
232                             String currency = m.group(2);
233                             if (currency == null)
234                                 currency = "";
235
236                             {
237                                 Matcher tmpM = reDecimalComma.matcher(value);
238                                 if (tmpM.find()) {
239                                     value = value.replace(".", "");
240                                     value = value.replace(',', '.');
241                                 }
242
243                                 tmpM = reDecimalPoint.matcher(value);
244                                 if (tmpM.find()) {
245                                     value = value.replace(",", "");
246                                     value = value.replace(" ", "");
247                                 }
248                             }
249                             L("curr=" + currency + ", value=" + value);
250                             final float val = Float.parseFloat(value);
251                             lastAccount.addAmount(val, currency);
252                             for (LedgerAccount syn : syntheticAccounts) {
253                                 L(String.format(Locale.ENGLISH, "propagating %s %1.2f to %s",
254                                         currency, val, syn.getName()));
255                                 syn.addAmount(val, currency);
256                             }
257                         }
258
259                         if (match_found) {
260                             syntheticAccounts.clear();
261                             state = ParserState.EXPECTING_ACCOUNT;
262                             L("→ expecting account");
263                         }
264
265                         break;
266
267                     case EXPECTING_TRANSACTION:
268                         if (!line.isEmpty() && (line.charAt(0) == ' '))
269                             continue;
270                         m = reTransactionStart.matcher(line);
271                         if (m.find()) {
272                             transactionId = Integer.parseInt(Objects.requireNonNull(m.group(1)));
273                             state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
274                             L(String.format(Locale.ENGLISH,
275                                     "found transaction %d → expecting description", transactionId));
276                             progress.setProgress(++processedTransactionCount);
277                             if (maxTransactionId < transactionId)
278                                 maxTransactionId = transactionId;
279                             if ((progress.isIndeterminate()) ||
280                                 (progress.getTotal() < transactionId))
281                                 progress.setTotal(transactionId);
282                             publishProgress(progress);
283                         }
284                         m = reEnd.matcher(line);
285                         if (m.find()) {
286                             L("--- transaction value complete ---");
287                             break LINES;
288                         }
289                         break;
290
291                     case EXPECTING_TRANSACTION_DESCRIPTION:
292                         if (!line.isEmpty() && (line.charAt(0) == ' '))
293                             continue;
294                         m = reTransactionDescription.matcher(line);
295                         if (m.find()) {
296                             if (transactionId == 0)
297                                 throw new TransactionParserException(
298                                         "Transaction Id is 0 while expecting description");
299
300                             String date = Objects.requireNonNull(m.group(1));
301                             try {
302                                 int equalsIndex = date.indexOf('=');
303                                 if (equalsIndex >= 0)
304                                     date = date.substring(equalsIndex + 1);
305                                 transaction =
306                                         new LedgerTransaction(transactionId, date, m.group(2));
307                             }
308                             catch (ParseException e) {
309                                 throw new TransactionParserException(
310                                         String.format("Error parsing date '%s'", date));
311                             }
312                             state = ParserState.EXPECTING_TRANSACTION_DETAILS;
313                             L(String.format(Locale.ENGLISH,
314                                     "transaction %d created for %s (%s) →" + " expecting details",
315                                     transactionId, date, m.group(2)));
316                         }
317                         break;
318
319                     case EXPECTING_TRANSACTION_DETAILS:
320                         if (line.isEmpty()) {
321                             // transaction data collected
322
323                             transaction.finishLoading();
324                             transactions.add(transaction);
325
326                             state = ParserState.EXPECTING_TRANSACTION;
327                             L(String.format("transaction %s parsed → expecting transaction",
328                                     transaction.getId()));
329
330 // sounds like a good idea, but transaction-1 may not be the first one chronologically
331 // for example, when you add the initial seeding transaction after entering some others
332 //                                            if (transactionId == 1) {
333 //                                                L("This was the initial transaction.
334 //                                                Terminating " +
335 //                                                  "parser");
336 //                                                break LINES;
337 //                                            }
338                         }
339                         else {
340                             LedgerTransactionAccount lta = parseTransactionAccountLine(line);
341                             if (lta != null) {
342                                 transaction.addAccount(lta);
343                                 L(String.format(Locale.ENGLISH, "%d: %s = %s", transaction.getId(),
344                                         lta.getAccountName(), lta.getAmount()));
345                             }
346                             else
347                                 throw new IllegalStateException(
348                                         String.format("Can't parse transaction %d details: %s",
349                                                 transactionId, line));
350                         }
351                         break;
352                     default:
353                         throw new RuntimeException(
354                                 String.format("Unknown parser updating %s", state.name()));
355                 }
356             }
357
358             throwIfCancelled();
359         }
360     }
361     @NonNull
362     public LedgerAccount ensureAccountExists(String accountName, HashMap<String, LedgerAccount> map,
363                                              ArrayList<LedgerAccount> createdAccounts) {
364         LedgerAccount acc = map.get(accountName);
365
366         if (acc != null)
367             return acc;
368
369         String parentName = LedgerAccount.extractParentName(accountName);
370         LedgerAccount parentAccount;
371         if (parentName != null) {
372             parentAccount = ensureAccountExists(parentName, map, createdAccounts);
373         }
374         else {
375             parentAccount = null;
376         }
377
378         acc = new LedgerAccount(accountName, parentAccount);
379         createdAccounts.add(acc);
380         return acc;
381     }
382     public void addNumberOfPostings(int number) {
383         expectedPostingsCount += number;
384     }
385     private List<LedgerAccount> retrieveAccountList()
386             throws IOException, HTTPException, ApiNotSupportedException {
387         final API apiVersion = profile.getApiVersion();
388         if (apiVersion.equals(API.auto)) {
389             return retrieveAccountListAnyVersion();
390         }
391         else if (apiVersion.equals(API.html)) {
392             Logger.debug("json",
393                     "Declining using JSON API for /accounts with configured legacy API version");
394             return null;
395         }
396         else {
397             return retrieveAccountListForVersion(apiVersion);
398         }
399     }
400     private List<LedgerAccount> retrieveAccountListAnyVersion()
401             throws HTTPException, ApiNotSupportedException {
402         for (API ver : API.allVersions) {
403             try {
404                 return retrieveAccountListForVersion(ver);
405             }
406             catch (Exception e) {
407                 Logger.debug("json",
408                         String.format(Locale.US, "Error during account list retrieval using API %s",
409                                 ver.getDescription()));
410             }
411
412             throw new ApiNotSupportedException();
413         }
414
415         throw new RuntimeException("This should never be reached");
416     }
417     private List<LedgerAccount> retrieveAccountListForVersion(API version)
418             throws IOException, HTTPException {
419         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
420         http.setAllowUserInteraction(false);
421         switch (http.getResponseCode()) {
422             case 200:
423                 break;
424             case 404:
425                 return null;
426             default:
427                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
428         }
429         publishProgress(Progress.indeterminate());
430         SQLiteDatabase db = App.getDatabase();
431         ArrayList<LedgerAccount> list = new ArrayList<>();
432         HashMap<String, LedgerAccount> map = new HashMap<>();
433         HashMap<String, LedgerAccount> currentMap = new HashMap<>();
434         for (LedgerAccount acc : prevAccounts)
435             currentMap.put(acc.getName(), acc);
436         throwIfCancelled();
437         try (InputStream resp = http.getInputStream()) {
438             throwIfCancelled();
439             if (http.getResponseCode() != 200)
440                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
441
442             AccountListParser parser = AccountListParser.forApiVersion(version, resp);
443             expectedPostingsCount = 0;
444
445             while (true) {
446                 throwIfCancelled();
447                 LedgerAccount acc = parser.nextAccount(this, map);
448                 if (acc == null)
449                     break;
450                 list.add(acc);
451             }
452             throwIfCancelled();
453         }
454
455         // the current account tree may have changed, update the new-to be tree to match
456         for (LedgerAccount acc : list) {
457             LedgerAccount prevData = currentMap.get(acc.getName());
458             if (prevData != null) {
459                 acc.setExpanded(prevData.isExpanded());
460                 acc.setAmountsExpanded(prevData.amountsExpanded());
461             }
462         }
463
464         return list;
465     }
466     private List<LedgerTransaction> retrieveTransactionList()
467             throws ParseException, HTTPException, IOException, ApiNotSupportedException {
468         final API apiVersion = profile.getApiVersion();
469         if (apiVersion.equals(API.auto)) {
470             return retrieveTransactionListAnyVersion();
471         }
472         else if (apiVersion.equals(API.html)) {
473             Logger.debug("json",
474                     "Declining using JSON API for /accounts with configured legacy API version");
475             return null;
476         }
477         else {
478             return retrieveTransactionListForVersion(apiVersion);
479         }
480
481     }
482     private List<LedgerTransaction> retrieveTransactionListAnyVersion()
483             throws ApiNotSupportedException {
484         for (API ver : API.allVersions) {
485             try {
486                 return retrieveTransactionListForVersion(ver);
487             }
488             catch (Exception | HTTPException e) {
489                 Logger.debug("json",
490                         String.format(Locale.US, "Error during account list retrieval using API %s",
491                                 ver.getDescription()));
492             }
493
494             throw new ApiNotSupportedException();
495         }
496
497         throw new RuntimeException("This should never be reached");
498     }
499     private List<LedgerTransaction> retrieveTransactionListForVersion(API apiVersion)
500             throws IOException, ParseException, HTTPException {
501         Progress progress = new Progress();
502         progress.setTotal(expectedPostingsCount);
503
504         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
505         http.setAllowUserInteraction(false);
506         publishProgress(progress);
507         switch (http.getResponseCode()) {
508             case 200:
509                 break;
510             case 404:
511                 return null;
512             default:
513                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
514         }
515         ArrayList<LedgerTransaction> trList = new ArrayList<>();
516         try (InputStream resp = http.getInputStream()) {
517             throwIfCancelled();
518
519             TransactionListParser parser = TransactionListParser.forApiVersion(apiVersion, resp);
520
521             int processedPostings = 0;
522
523             while (true) {
524                 throwIfCancelled();
525                 LedgerTransaction transaction = parser.nextTransaction();
526                 throwIfCancelled();
527                 if (transaction == null)
528                     break;
529
530                 trList.add(transaction);
531
532                 progress.setProgress(processedPostings += transaction.getAccounts()
533                                                                      .size());
534 //                Logger.debug("trParser",
535 //                        String.format(Locale.US, "Parsed transaction %d - %s", transaction
536 //                        .getId(),
537 //                                transaction.getDescription()));
538 //                for (LedgerTransactionAccount acc : transaction.getAccounts()) {
539 //                    Logger.debug("trParser",
540 //                            String.format(Locale.US, "  %s", acc.getAccountName()));
541 //                }
542                 publishProgress(progress);
543             }
544
545             throwIfCancelled();
546         }
547
548         // json interface returns transactions if file order and the rest of the machinery
549         // expects them in reverse chronological order
550         Collections.sort(trList, (o1, o2) -> {
551             int res = o2.getDate()
552                         .compareTo(o1.getDate());
553             if (res != 0)
554                 return res;
555             return Long.compare(o2.getId(), o1.getId());
556         });
557         return trList;
558     }
559
560     @SuppressLint("DefaultLocale")
561     @Override
562     protected Result doInBackground(Void... params) {
563         Data.backgroundTaskStarted();
564         List<LedgerAccount> accounts;
565         List<LedgerTransaction> transactions;
566         try {
567             accounts = retrieveAccountList();
568             // accounts is null in API-version auto-detection and means
569             // requesting 'html' API version via the JSON classes
570             // this can't work, and the null results in the legacy code below
571             // being called
572             if (accounts == null)
573                 transactions = null;
574             else
575                 transactions = retrieveTransactionList();
576
577             if (accounts == null || transactions == null) {
578                 accounts = new ArrayList<>();
579                 transactions = new ArrayList<>();
580                 retrieveTransactionListLegacy(accounts, transactions);
581             }
582             mainModel.setAndStoreAccountAndTransactionListFromWeb(accounts, transactions);
583
584             return new Result(accounts, transactions);
585         }
586         catch (MalformedURLException e) {
587             e.printStackTrace();
588             return new Result("Invalid server URL");
589         }
590         catch (HTTPException e) {
591             e.printStackTrace();
592             return new Result(String.format("HTTP error %d: %s", e.getResponseCode(),
593                     e.getResponseMessage()));
594         }
595         catch (IOException e) {
596             e.printStackTrace();
597             return new Result(e.getLocalizedMessage());
598         }
599         catch (RuntimeJsonMappingException e) {
600             e.printStackTrace();
601             return new Result(Result.ERR_JSON_PARSER_ERROR);
602         }
603         catch (ParseException e) {
604             e.printStackTrace();
605             return new Result("Network error");
606         }
607         catch (OperationCanceledException e) {
608             e.printStackTrace();
609             return new Result("Operation cancelled");
610         }
611         catch (ApiNotSupportedException e) {
612             e.printStackTrace();
613             return new Result("Server version not supported");
614         }
615         finally {
616             Data.backgroundTaskFinished();
617         }
618     }
619     public void throwIfCancelled() {
620         if (isCancelled())
621             throw new OperationCanceledException(null);
622     }
623     private enum ParserState {
624         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_TRANSACTION,
625         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
626     }
627
628     public enum ProgressState {STARTING, RUNNING, FINISHED}
629
630     public static class Progress {
631         private int progress;
632         private int total;
633         private ProgressState state = ProgressState.RUNNING;
634         private String error = null;
635         private boolean indeterminate;
636         Progress() {
637             indeterminate = true;
638         }
639         Progress(int progress, int total) {
640             this.indeterminate = false;
641             this.progress = progress;
642             this.total = total;
643         }
644         public static Progress indeterminate() {
645             return new Progress();
646         }
647         public static Progress finished(String error) {
648             Progress p = new Progress();
649             p.setState(ProgressState.FINISHED);
650             p.setError(error);
651             return p;
652         }
653         public int getProgress() {
654             ensureState(ProgressState.RUNNING);
655             return progress;
656         }
657         protected void setProgress(int progress) {
658             this.progress = progress;
659             this.state = ProgressState.RUNNING;
660         }
661         public int getTotal() {
662             ensureState(ProgressState.RUNNING);
663             return total;
664         }
665         protected void setTotal(int total) {
666             this.total = total;
667             state = ProgressState.RUNNING;
668             indeterminate = total == -1;
669         }
670         private void ensureState(ProgressState wanted) {
671             if (state != wanted)
672                 throw new IllegalStateException(
673                         String.format("Bad state: %s, expected %s", state, wanted));
674         }
675         public ProgressState getState() {
676             return state;
677         }
678         public void setState(ProgressState state) {
679             this.state = state;
680         }
681         public String getError() {
682             ensureState(ProgressState.FINISHED);
683             return error;
684         }
685         public void setError(String error) {
686             this.error = error;
687             state = ProgressState.FINISHED;
688         }
689         public boolean isIndeterminate() {
690             return indeterminate;
691         }
692         public void setIndeterminate(boolean indeterminate) {
693             this.indeterminate = indeterminate;
694         }
695     }
696
697     private static class TransactionParserException extends IllegalStateException {
698         TransactionParserException(String message) {
699             super(message);
700         }
701     }
702
703     public static class Result {
704         public static String ERR_JSON_PARSER_ERROR = "err_json_parser";
705         public String error;
706         public List<LedgerAccount> accounts;
707         public List<LedgerTransaction> transactions;
708         Result(String error) {
709             this.error = error;
710         }
711         Result(List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
712             this.accounts = accounts;
713             this.transactions = transactions;
714         }
715     }
716 }