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