]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
whitespace
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / RetrieveTransactionsTask.java
1 /*
2  * Copyright © 2019 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 net.ktnx.mobileledger.App;
26 import net.ktnx.mobileledger.err.HTTPException;
27 import net.ktnx.mobileledger.json.AccountListParser;
28 import net.ktnx.mobileledger.json.ParsedBalance;
29 import net.ktnx.mobileledger.json.ParsedLedgerAccount;
30 import net.ktnx.mobileledger.json.ParsedLedgerTransaction;
31 import net.ktnx.mobileledger.json.TransactionListParser;
32 import net.ktnx.mobileledger.model.Data;
33 import net.ktnx.mobileledger.model.LedgerAccount;
34 import net.ktnx.mobileledger.model.LedgerTransaction;
35 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
36 import net.ktnx.mobileledger.model.MobileLedgerProfile;
37 import net.ktnx.mobileledger.ui.activity.MainActivity;
38 import net.ktnx.mobileledger.utils.NetworkUtil;
39
40 import java.io.BufferedReader;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.InputStreamReader;
44 import java.lang.ref.WeakReference;
45 import java.net.HttpURLConnection;
46 import java.net.MalformedURLException;
47 import java.net.URLDecoder;
48 import java.nio.charset.StandardCharsets;
49 import java.text.ParseException;
50 import java.util.ArrayList;
51 import java.util.HashMap;
52 import java.util.Locale;
53 import java.util.Stack;
54 import java.util.regex.Matcher;
55 import java.util.regex.Pattern;
56
57 import androidx.annotation.NonNull;
58
59 import static net.ktnx.mobileledger.utils.Logger.debug;
60
61
62 public class RetrieveTransactionsTask
63         extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
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("<tr class=\"title\" " +
67                                                                       "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
68     private static final Pattern reTransactionDescription =
69             Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
70     private static final Pattern reTransactionDetails =
71             Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
72     private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
73     private WeakReference<MainActivity> contextRef;
74     // %3A is '='
75     private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
76     private Pattern reAccountValue = Pattern.compile(
77             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
78     private MobileLedgerProfile profile;
79     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
80                                     @NonNull MobileLedgerProfile profile) {
81         this.contextRef = contextRef;
82         this.profile = profile;
83     }
84     private static void L(String msg) {
85         //debug("transaction-parser", msg);
86     }
87     @Override
88     protected void onProgressUpdate(Progress... values) {
89         super.onProgressUpdate(values);
90         MainActivity context = getContext();
91         if (context == null) return;
92         context.onRetrieveProgress(values[0]);
93     }
94     @Override
95     protected void onPreExecute() {
96         super.onPreExecute();
97         MainActivity context = getContext();
98         if (context == null) return;
99         context.onRetrieveStart();
100     }
101     @Override
102     protected void onPostExecute(String error) {
103         super.onPostExecute(error);
104         MainActivity context = getContext();
105         if (context == null) return;
106         context.onRetrieveDone(error);
107     }
108     @Override
109     protected void onCancelled() {
110         super.onCancelled();
111         MainActivity context = getContext();
112         if (context == null) return;
113         context.onRetrieveDone(null);
114     }
115     private String retrieveTransactionListLegacy()
116             throws IOException, ParseException, HTTPException {
117         Progress progress = new Progress();
118         int maxTransactionId = Progress.INDETERMINATE;
119         ArrayList<LedgerAccount> accountList = new ArrayList<>();
120         HashMap<String, Void> accountNames = new HashMap<>();
121         HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
122         LedgerAccount lastAccount = null, prevAccount = null;
123         boolean onlyStarred = Data.optShowOnlyStarred.get();
124
125         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
126         http.setAllowUserInteraction(false);
127         publishProgress(progress);
128         switch (http.getResponseCode()) {
129             case 200:
130                 break;
131             default:
132                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
133         }
134
135         SQLiteDatabase db = App.getDatabase();
136         try (InputStream resp = http.getInputStream()) {
137             if (http.getResponseCode() != 200)
138                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
139             db.beginTransaction();
140             try {
141                 prepareDbForRetrieval(db, profile);
142
143                 int matchedTransactionsCount = 0;
144
145
146                 ParserState state = ParserState.EXPECTING_ACCOUNT;
147                 String line;
148                 BufferedReader buf =
149                         new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
150
151                 int processedTransactionCount = 0;
152                 int transactionId = 0;
153                 LedgerTransaction transaction = null;
154                 LINES:
155                 while ((line = buf.readLine()) != null) {
156                     throwIfCancelled();
157                     Matcher m;
158                     m = reComment.matcher(line);
159                     if (m.find()) {
160                         // TODO: comments are ignored for now
161 //                            Log.v("transaction-parser", "Ignoring comment");
162                         continue;
163                     }
164                     //L(String.format("State is %d", updating));
165                     switch (state) {
166                         case EXPECTING_ACCOUNT:
167                             if (line.equals("<h2>General Journal</h2>")) {
168                                 state = ParserState.EXPECTING_TRANSACTION;
169                                 L("→ expecting transaction");
170                                 // commit the current transaction and start a new one
171                                 // the account list in the UI should reflect the (committed)
172                                 // state of the database
173                                 db.setTransactionSuccessful();
174                                 db.endTransaction();
175                                 Data.accounts.setList(accountList);
176                                 db.beginTransaction();
177                                 continue;
178                             }
179                             m = reAccountName.matcher(line);
180                             if (m.find()) {
181                                 String acct_encoded = m.group(1);
182                                 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
183                                 acct_name = acct_name.replace("\"", "");
184                                 L(String.format("found account: %s", acct_name));
185
186                                 prevAccount = lastAccount;
187                                 lastAccount = profile.tryLoadAccount(db, acct_name);
188                                 if (lastAccount == null) lastAccount = new LedgerAccount(acct_name);
189                                 else lastAccount.removeAmounts();
190                                 profile.storeAccount(db, lastAccount);
191
192                                 if (prevAccount != null) prevAccount
193                                         .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
194                                 // make sure the parent account(s) are present,
195                                 // synthesising them if necessary
196                                 // this happens when the (missing-in-HTML) parent account has
197                                 // only one child so we create a synthetic parent account record,
198                                 // copying the amounts when child's amounts are parsed
199                                 String parentName = lastAccount.getParentName();
200                                 if (parentName != null) {
201                                     Stack<String> toAppend = new Stack<>();
202                                     while (parentName != null) {
203                                         if (accountNames.containsKey(parentName)) break;
204                                         toAppend.push(parentName);
205                                         parentName = new LedgerAccount(parentName).getParentName();
206                                     }
207                                     syntheticAccounts.clear();
208                                     while (!toAppend.isEmpty()) {
209                                         String aName = toAppend.pop();
210                                         LedgerAccount acc = profile.tryLoadAccount(db, aName);
211                                         if (acc == null) {
212                                             acc = new LedgerAccount(aName);
213                                             acc.setHiddenByStar(lastAccount.isHiddenByStar());
214                                             acc.setExpanded(!lastAccount.hasSubAccounts() ||
215                                                             lastAccount.isExpanded());
216                                         }
217                                         acc.setHasSubAccounts(true);
218                                         acc.removeAmounts();    // filled below when amounts are parsed
219                                         if ((!onlyStarred || !acc.isHiddenByStar()) &&
220                                             acc.isVisible(accountList)) accountList.add(acc);
221                                         L(String.format("gap-filling with %s", aName));
222                                         accountNames.put(aName, null);
223                                         profile.storeAccount(db, acc);
224                                         syntheticAccounts.put(aName, acc);
225                                     }
226                                 }
227
228                                 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
229                                     lastAccount.isVisible(accountList))
230                                     accountList.add(lastAccount);
231                                 accountNames.put(acct_name, null);
232
233                                 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
234                                 L("→ expecting account amount");
235                             }
236                             break;
237
238                         case EXPECTING_ACCOUNT_AMOUNT:
239                             m = reAccountValue.matcher(line);
240                             boolean match_found = false;
241                             while (m.find()) {
242                                 throwIfCancelled();
243
244                                 match_found = true;
245                                 String value = m.group(1);
246                                 String currency = m.group(2);
247                                 if (currency == null) currency = "";
248                                 value = value.replace(',', '.');
249                                 L("curr=" + currency + ", value=" + value);
250                                 final float val = Float.parseFloat(value);
251                                 profile.storeAccountValue(db, lastAccount.getName(), currency, val);
252                                 lastAccount.addAmount(val, currency);
253                                 for (LedgerAccount syn : syntheticAccounts.values()) {
254                                     syn.addAmount(val, currency);
255                                     profile.storeAccountValue(db, syn.getName(), currency, val);
256                                 }
257                             }
258
259                             if (match_found) {
260                                 state = ParserState.EXPECTING_ACCOUNT;
261                                 L("→ expecting account");
262                             }
263
264                             break;
265
266                         case EXPECTING_TRANSACTION:
267                             if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
268                             m = reTransactionStart.matcher(line);
269                             if (m.find()) {
270                                 transactionId = Integer.valueOf(m.group(1));
271                                 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
272                                 L(String.format(Locale.ENGLISH,
273                                         "found transaction %d → expecting description",
274                                         transactionId));
275                                 progress.setProgress(++processedTransactionCount);
276                                 if (maxTransactionId < transactionId)
277                                     maxTransactionId = transactionId;
278                                 if ((progress.getTotal() == Progress.INDETERMINATE) ||
279                                     (progress.getTotal() < transactionId))
280                                     progress.setTotal(transactionId);
281                                 publishProgress(progress);
282                             }
283                             m = reEnd.matcher(line);
284                             if (m.find()) {
285                                 L("--- transaction value complete ---");
286                                 break LINES;
287                             }
288                             break;
289
290                         case EXPECTING_TRANSACTION_DESCRIPTION:
291                             if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
292                             m = reTransactionDescription.matcher(line);
293                             if (m.find()) {
294                                 if (transactionId == 0) throw new TransactionParserException(
295                                         "Transaction Id is 0 while expecting " + "description");
296
297                                 String date = m.group(1);
298                                 try {
299                                     int equalsIndex = date.indexOf('=');
300                                     if (equalsIndex >= 0) date = date.substring(equalsIndex + 1);
301                                     transaction =
302                                             new LedgerTransaction(transactionId, date, m.group(2));
303                                 }
304                                 catch (ParseException e) {
305                                     e.printStackTrace();
306                                     return String.format("Error parsing date '%s'", date);
307                                 }
308                                 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
309                                 L(String.format(Locale.ENGLISH,
310                                         "transaction %d created for %s (%s) →" +
311                                         " expecting details", transactionId, date, m.group(2)));
312                             }
313                             break;
314
315                         case EXPECTING_TRANSACTION_DETAILS:
316                             if (line.isEmpty()) {
317                                 // transaction data collected
318                                 if (transaction.existsInDb(db)) {
319                                     profile.markTransactionAsPresent(db, transaction);
320                                     matchedTransactionsCount++;
321
322                                     if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
323                                         profile.markTransactionsBeforeTransactionAsPresent(db,
324                                                 transaction);
325                                         progress.setTotal(progress.getProgress());
326                                         publishProgress(progress);
327                                         break LINES;
328                                     }
329                                 }
330                                 else {
331                                     profile.storeTransaction(db, transaction);
332                                     matchedTransactionsCount = 0;
333                                     progress.setTotal(maxTransactionId);
334                                 }
335
336                                 state = ParserState.EXPECTING_TRANSACTION;
337                                 L(String.format("transaction %s saved → expecting transaction",
338                                         transaction.getId()));
339                                 transaction.finishLoading();
340
341 // sounds like a good idea, but transaction-1 may not be the first one chronologically
342 // for example, when you add the initial seeding transaction after entering some others
343 //                                            if (transactionId == 1) {
344 //                                                L("This was the initial transaction. Terminating " +
345 //                                                  "parser");
346 //                                                break LINES;
347 //                                            }
348                             }
349                             else {
350                                 m = reTransactionDetails.matcher(line);
351                                 if (m.find()) {
352                                     String acc_name = m.group(1);
353                                     String amount = m.group(2);
354                                     String currency = m.group(3);
355                                     if (currency == null) currency = "";
356                                     amount = amount.replace(',', '.');
357                                     transaction.addAccount(new LedgerTransactionAccount(acc_name,
358                                             Float.valueOf(amount), currency));
359                                     L(String.format(Locale.ENGLISH, "%d: %s = %s",
360                                             transaction.getId(), acc_name, amount));
361                                 }
362                                 else throw new IllegalStateException(
363                                         String.format("Can't parse transaction %d " + "details: %s",
364                                                 transactionId, line));
365                             }
366                             break;
367                         default:
368                             throw new RuntimeException(
369                                     String.format("Unknown parser updating %s", state.name()));
370                     }
371                 }
372
373                 throwIfCancelled();
374
375                 profile.deleteNotPresentTransactions(db);
376                 db.setTransactionSuccessful();
377
378                 profile.setLastUpdateStamp();
379
380                 return null;
381             }
382             finally {
383                 db.endTransaction();
384             }
385         }
386     }
387     private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
388         db.execSQL("UPDATE transactions set keep=0 where profile=?",
389                 new String[]{profile.getUuid()});
390         db.execSQL("update account_values set keep=0 where profile=?;",
391                 new String[]{profile.getUuid()});
392         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
393     }
394     private boolean retrieveAccountList() throws IOException, HTTPException {
395         Progress progress = new Progress();
396
397         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
398         http.setAllowUserInteraction(false);
399         switch (http.getResponseCode()) {
400             case 200:
401                 break;
402             case 404:
403                 return false;
404             default:
405                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
406         }
407         publishProgress(progress);
408         SQLiteDatabase db = App.getDatabase();
409         ArrayList<LedgerAccount> accountList = new ArrayList<>();
410         boolean listFilledOK = false;
411         try (InputStream resp = http.getInputStream()) {
412             if (http.getResponseCode() != 200)
413                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
414
415             db.beginTransaction();
416             try {
417                 profile.markAccountsAsNotPresent(db);
418
419                 AccountListParser parser = new AccountListParser(resp);
420
421                 LedgerAccount prevAccount = null;
422
423                 while (true) {
424                     throwIfCancelled();
425                     ParsedLedgerAccount parsedAccount = parser.nextAccount();
426                     if (parsedAccount == null) break;
427
428                     LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
429                     if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
430                     else acc.removeAmounts();
431
432                     profile.storeAccount(db, acc);
433                     String lastCurrency = null;
434                     float lastCurrencyAmount = 0;
435                     for (ParsedBalance b : parsedAccount.getAibalance()) {
436                         final String currency = b.getAcommodity();
437                         final float amount = b.getAquantity().asFloat();
438                         if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
439                         else {
440                             if (lastCurrency != null) {
441                                 profile.storeAccountValue(db, acc.getName(), lastCurrency,
442                                         lastCurrencyAmount);
443                                 acc.addAmount(lastCurrencyAmount, lastCurrency);
444                             }
445                             lastCurrency = currency;
446                             lastCurrencyAmount = amount;
447                         }
448                     }
449                     if (lastCurrency != null) {
450                         profile.storeAccountValue(db, acc.getName(), lastCurrency,
451                                 lastCurrencyAmount);
452                         acc.addAmount(lastCurrencyAmount, lastCurrency);
453                     }
454
455                     if (acc.isVisible(accountList)) accountList.add(acc);
456
457                     if (prevAccount != null) {
458                         prevAccount.setHasSubAccounts(
459                                 acc.getName().startsWith(prevAccount.getName() + ":"));
460                     }
461
462                     prevAccount = acc;
463                 }
464                 throwIfCancelled();
465
466                 profile.deleteNotPresentAccounts(db);
467                 throwIfCancelled();
468                 db.setTransactionSuccessful();
469                 listFilledOK = true;
470             }
471             finally {
472                 db.endTransaction();
473             }
474         }
475         // should not be set in the DB transaction, because of a possible deadlock
476         // with the main and DbOpQueueRunner threads
477         if (listFilledOK) Data.accounts.setList(accountList);
478
479         return true;
480     }
481     private boolean retrieveTransactionList() throws IOException, ParseException, HTTPException {
482         Progress progress = new Progress();
483         int maxTransactionId = Progress.INDETERMINATE;
484
485         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "transactions");
486         http.setAllowUserInteraction(false);
487         publishProgress(progress);
488         switch (http.getResponseCode()) {
489             case 200:
490                 break;
491             case 404:
492                 return false;
493             default:
494                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
495         }
496         SQLiteDatabase db = App.getDatabase();
497         try (InputStream resp = http.getInputStream()) {
498             if (http.getResponseCode() != 200)
499                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
500             throwIfCancelled();
501             db.beginTransaction();
502             try {
503                 profile.markTransactionsAsNotPresent(db);
504
505                 int matchedTransactionsCount = 0;
506                 TransactionListParser parser = new TransactionListParser(resp);
507
508                 int processedTransactionCount = 0;
509
510                 DetectedTransactionOrder transactionOrder = DetectedTransactionOrder.UNKNOWN;
511                 int orderAccumulator = 0;
512                 int lastTransactionId = 0;
513
514                 while (true) {
515                     throwIfCancelled();
516                     ParsedLedgerTransaction parsedTransaction = parser.nextTransaction();
517                     throwIfCancelled();
518                     if (parsedTransaction == null) break;
519
520                     LedgerTransaction transaction = parsedTransaction.asLedgerTransaction();
521                     if (transaction.getId() > lastTransactionId) orderAccumulator++;
522                     else orderAccumulator--;
523                     lastTransactionId = transaction.getId();
524                     if (transactionOrder == DetectedTransactionOrder.UNKNOWN) {
525                         if (orderAccumulator > 30) {
526                             transactionOrder = DetectedTransactionOrder.FILE;
527                             debug("rtt", String.format(Locale.ENGLISH,
528                                     "Detected native file order after %d transactions (factor %d)",
529                                     processedTransactionCount, orderAccumulator));
530                             progress.setTotal(Data.transactions.size());
531                         }
532                         else if (orderAccumulator < -30) {
533                             transactionOrder = DetectedTransactionOrder.REVERSE_CHRONOLOGICAL;
534                             debug("rtt", String.format(Locale.ENGLISH,
535                                     "Detected reverse chronological order after %d transactions (factor %d)",
536                                     processedTransactionCount, orderAccumulator));
537                         }
538                     }
539
540                     if (transaction.existsInDb(db)) {
541                         profile.markTransactionAsPresent(db, transaction);
542                         matchedTransactionsCount++;
543
544                         if ((transactionOrder == DetectedTransactionOrder.REVERSE_CHRONOLOGICAL) &&
545                             (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT))
546                         {
547                             profile.markTransactionsBeforeTransactionAsPresent(db, transaction);
548                             progress.setTotal(progress.getProgress());
549                             publishProgress(progress);
550                             db.setTransactionSuccessful();
551                             profile.setLastUpdateStamp();
552                             return true;
553                         }
554                     }
555                     else {
556                         profile.storeTransaction(db, transaction);
557                         matchedTransactionsCount = 0;
558                         progress.setTotal(maxTransactionId);
559                     }
560
561
562                     if ((transactionOrder != DetectedTransactionOrder.UNKNOWN) &&
563                         ((progress.getTotal() == Progress.INDETERMINATE) ||
564                          (progress.getTotal() < transaction.getId())))
565                         progress.setTotal(transaction.getId());
566
567                     progress.setProgress(++processedTransactionCount);
568                     publishProgress(progress);
569                 }
570
571                 throwIfCancelled();
572                 profile.deleteNotPresentTransactions(db);
573                 throwIfCancelled();
574                 db.setTransactionSuccessful();
575                 profile.setLastUpdateStamp();
576             }
577             finally {
578                 db.endTransaction();
579             }
580         }
581
582         return true;
583     }
584
585     @SuppressLint("DefaultLocale")
586     @Override
587     protected String doInBackground(Void... params) {
588         Data.backgroundTaskStarted();
589         try {
590             if (!retrieveAccountList() || !retrieveTransactionList())
591                 return retrieveTransactionListLegacy();
592             return null;
593         }
594         catch (MalformedURLException e) {
595             e.printStackTrace();
596             return "Invalid server URL";
597         }
598         catch (HTTPException e) {
599             e.printStackTrace();
600             return String.format("HTTP error %d: %s", e.getResponseCode(), e.getResponseMessage());
601         }
602         catch (IOException e) {
603             e.printStackTrace();
604             return e.getLocalizedMessage();
605         }
606         catch (ParseException e) {
607             e.printStackTrace();
608             return "Network error";
609         }
610         catch (OperationCanceledException e) {
611             e.printStackTrace();
612             return "Operation cancelled";
613         }
614         finally {
615             Data.backgroundTaskFinished();
616         }
617     }
618     private MainActivity getContext() {
619         return contextRef.get();
620     }
621     private void throwIfCancelled() {
622         if (isCancelled()) throw new OperationCanceledException(null);
623     }
624     enum DetectedTransactionOrder {UNKNOWN, REVERSE_CHRONOLOGICAL, FILE}
625
626     private enum ParserState {
627         EXPECTING_ACCOUNT, EXPECTING_ACCOUNT_AMOUNT, EXPECTING_JOURNAL, EXPECTING_TRANSACTION,
628         EXPECTING_TRANSACTION_DESCRIPTION, EXPECTING_TRANSACTION_DETAILS
629     }
630
631     public class Progress {
632         public static final int INDETERMINATE = -1;
633         private int progress;
634         private int total;
635         Progress() {
636             this(INDETERMINATE, INDETERMINATE);
637         }
638         Progress(int progress, int total) {
639             this.progress = progress;
640             this.total = total;
641         }
642         public int getProgress() {
643             return progress;
644         }
645         protected void setProgress(int progress) {
646             this.progress = progress;
647         }
648         public int getTotal() {
649             return total;
650         }
651         protected void setTotal(int total) {
652             this.total = total;
653         }
654     }
655
656     private class TransactionParserException extends IllegalStateException {
657         TransactionParserException(String message) {
658             super(message);
659         }
660     }
661 }