]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java
let the loading screen use the default background color
[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 static net.ktnx.mobileledger.utils.Logger.debug;
58
59
60 public class RetrieveTransactionsTask
61         extends AsyncTask<Void, RetrieveTransactionsTask.Progress, String> {
62     private static final int MATCHING_TRANSACTIONS_LIMIT = 150;
63     private static final Pattern reComment = Pattern.compile("^\\s*;");
64     private static final Pattern reTransactionStart = Pattern.compile("<tr class=\"title\" " +
65                                                                       "id=\"transaction-(\\d+)\"><td class=\"date\"[^\"]*>([\\d.-]+)</td>");
66     private static final Pattern reTransactionDescription =
67             Pattern.compile("<tr class=\"posting\" title=\"(\\S+)\\s(.+)");
68     private static final Pattern reTransactionDetails =
69             Pattern.compile("^\\s+(\\S[\\S\\s]+\\S)\\s\\s+([-+]?\\d[\\d,.]*)(?:\\s+(\\S+)$)?");
70     private static final Pattern reEnd = Pattern.compile("\\bid=\"addmodal\"");
71     private WeakReference<MainActivity> contextRef;
72     // %3A is '='
73     private Pattern reAccountName = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
74     private Pattern reAccountValue = Pattern.compile(
75             "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
76     private MobileLedgerProfile profile;
77     public RetrieveTransactionsTask(WeakReference<MainActivity> contextRef,
78                                     MobileLedgerProfile profile) {
79         this.contextRef = contextRef;
80         this.profile = profile;
81     }
82     private static void L(String msg) {
83         //debug("transaction-parser", msg);
84     }
85     @Override
86     protected void onProgressUpdate(Progress... values) {
87         super.onProgressUpdate(values);
88         MainActivity context = getContext();
89         if (context == null) return;
90         context.onRetrieveProgress(values[0]);
91     }
92     @Override
93     protected void onPreExecute() {
94         super.onPreExecute();
95         MainActivity context = getContext();
96         if (context == null) return;
97         context.onRetrieveStart();
98     }
99     @Override
100     protected void onPostExecute(String error) {
101         super.onPostExecute(error);
102         MainActivity context = getContext();
103         if (context == null) return;
104         context.onRetrieveDone(error);
105     }
106     @Override
107     protected void onCancelled() {
108         super.onCancelled();
109         MainActivity context = getContext();
110         if (context == null) return;
111         context.onRetrieveDone(null);
112     }
113     private String retrieveTransactionListLegacy()
114             throws IOException, ParseException, HTTPException {
115         Progress progress = new Progress();
116         int maxTransactionId = Progress.INDETERMINATE;
117         ArrayList<LedgerAccount> accountList = new ArrayList<>();
118         HashMap<String, Void> accountNames = new HashMap<>();
119         HashMap<String, LedgerAccount> syntheticAccounts = new HashMap<>();
120         LedgerAccount lastAccount = null, prevAccount = null;
121         boolean onlyStarred = Data.optShowOnlyStarred.get();
122
123         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "journal");
124         http.setAllowUserInteraction(false);
125         publishProgress(progress);
126         switch (http.getResponseCode()) {
127             case 200:
128                 break;
129             default:
130                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
131         }
132
133         SQLiteDatabase db = App.getDatabase();
134         try (InputStream resp = http.getInputStream()) {
135             if (http.getResponseCode() != 200)
136                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
137             db.beginTransaction();
138             try {
139                 prepareDbForRetrieval(db, profile);
140
141                 int matchedTransactionsCount = 0;
142
143
144                 ParserState state = ParserState.EXPECTING_ACCOUNT;
145                 String line;
146                 BufferedReader buf =
147                         new BufferedReader(new InputStreamReader(resp, StandardCharsets.UTF_8));
148
149                 int processedTransactionCount = 0;
150                 int transactionId = 0;
151                 LedgerTransaction transaction = null;
152                 LINES:
153                 while ((line = buf.readLine()) != null) {
154                     throwIfCancelled();
155                     Matcher m;
156                     m = reComment.matcher(line);
157                     if (m.find()) {
158                         // TODO: comments are ignored for now
159 //                            Log.v("transaction-parser", "Ignoring comment");
160                         continue;
161                     }
162                     //L(String.format("State is %d", updating));
163                     switch (state) {
164                         case EXPECTING_ACCOUNT:
165                             if (line.equals("<h2>General Journal</h2>")) {
166                                 state = ParserState.EXPECTING_TRANSACTION;
167                                 L("→ expecting transaction");
168                                 // commit the current transaction and start a new one
169                                 // the account list in the UI should reflect the (committed)
170                                 // state of the database
171                                 db.setTransactionSuccessful();
172                                 db.endTransaction();
173                                 Data.accounts.setList(accountList);
174                                 db.beginTransaction();
175                                 continue;
176                             }
177                             m = reAccountName.matcher(line);
178                             if (m.find()) {
179                                 String acct_encoded = m.group(1);
180                                 String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
181                                 acct_name = acct_name.replace("\"", "");
182                                 L(String.format("found account: %s", acct_name));
183
184                                 prevAccount = lastAccount;
185                                 lastAccount = profile.tryLoadAccount(db, acct_name);
186                                 if (lastAccount == null) lastAccount = new LedgerAccount(acct_name);
187                                 else lastAccount.removeAmounts();
188                                 profile.storeAccount(db, lastAccount);
189
190                                 if (prevAccount != null) prevAccount
191                                         .setHasSubAccounts(prevAccount.isParentOf(lastAccount));
192                                 // make sure the parent account(s) are present,
193                                 // synthesising them if necessary
194                                 // this happens when the (missing-in-HTML) parent account has
195                                 // only one child so we create a synthetic parent account record,
196                                 // copying the amounts when child's amounts are parsed
197                                 String parentName = lastAccount.getParentName();
198                                 if (parentName != null) {
199                                     Stack<String> toAppend = new Stack<>();
200                                     while (parentName != null) {
201                                         if (accountNames.containsKey(parentName)) break;
202                                         toAppend.push(parentName);
203                                         parentName = new LedgerAccount(parentName).getParentName();
204                                     }
205                                     syntheticAccounts.clear();
206                                     while (!toAppend.isEmpty()) {
207                                         String aName = toAppend.pop();
208                                         LedgerAccount acc = profile.tryLoadAccount(db, aName);
209                                         if (acc == null) {
210                                             acc = new LedgerAccount(aName);
211                                             acc.setHiddenByStar(lastAccount.isHiddenByStar());
212                                             acc.setExpanded(!lastAccount.hasSubAccounts() ||
213                                                             lastAccount.isExpanded());
214                                         }
215                                         acc.setHasSubAccounts(true);
216                                         acc.removeAmounts();    // filled below when amounts are parsed
217                                         if ((!onlyStarred || !acc.isHiddenByStar()) &&
218                                             acc.isVisible(accountList)) accountList.add(acc);
219                                         L(String.format("gap-filling with %s", aName));
220                                         accountNames.put(aName, null);
221                                         profile.storeAccount(db, acc);
222                                         syntheticAccounts.put(aName, acc);
223                                     }
224                                 }
225
226                                 if ((!onlyStarred || !lastAccount.isHiddenByStar()) &&
227                                     lastAccount.isVisible(accountList))
228                                     accountList.add(lastAccount);
229                                 accountNames.put(acct_name, null);
230
231                                 state = ParserState.EXPECTING_ACCOUNT_AMOUNT;
232                                 L("→ expecting account amount");
233                             }
234                             break;
235
236                         case EXPECTING_ACCOUNT_AMOUNT:
237                             m = reAccountValue.matcher(line);
238                             boolean match_found = false;
239                             while (m.find()) {
240                                 throwIfCancelled();
241
242                                 match_found = true;
243                                 String value = m.group(1);
244                                 String currency = m.group(2);
245                                 if (currency == null) currency = "";
246                                 value = value.replace(',', '.');
247                                 L("curr=" + currency + ", value=" + value);
248                                 final float val = Float.parseFloat(value);
249                                 profile.storeAccountValue(db, lastAccount.getName(), currency, val);
250                                 lastAccount.addAmount(val, currency);
251                                 for (LedgerAccount syn : syntheticAccounts.values()) {
252                                     syn.addAmount(val, currency);
253                                     profile.storeAccountValue(db, syn.getName(), currency, val);
254                                 }
255                             }
256
257                             if (match_found) {
258                                 state = ParserState.EXPECTING_ACCOUNT;
259                                 L("→ expecting account");
260                             }
261
262                             break;
263
264                         case EXPECTING_TRANSACTION:
265                             if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
266                             m = reTransactionStart.matcher(line);
267                             if (m.find()) {
268                                 transactionId = Integer.valueOf(m.group(1));
269                                 state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
270                                 L(String.format(Locale.ENGLISH,
271                                         "found transaction %d → expecting description",
272                                         transactionId));
273                                 progress.setProgress(++processedTransactionCount);
274                                 if (maxTransactionId < transactionId)
275                                     maxTransactionId = transactionId;
276                                 if ((progress.getTotal() == Progress.INDETERMINATE) ||
277                                     (progress.getTotal() < transactionId))
278                                     progress.setTotal(transactionId);
279                                 publishProgress(progress);
280                             }
281                             m = reEnd.matcher(line);
282                             if (m.find()) {
283                                 L("--- transaction value complete ---");
284                                 break LINES;
285                             }
286                             break;
287
288                         case EXPECTING_TRANSACTION_DESCRIPTION:
289                             if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
290                             m = reTransactionDescription.matcher(line);
291                             if (m.find()) {
292                                 if (transactionId == 0) throw new TransactionParserException(
293                                         "Transaction Id is 0 while expecting " + "description");
294
295                                 String date = m.group(1);
296                                 try {
297                                     int equalsIndex = date.indexOf('=');
298                                     if (equalsIndex >= 0) date = date.substring(equalsIndex + 1);
299                                     transaction =
300                                             new LedgerTransaction(transactionId, date, m.group(2));
301                                 }
302                                 catch (ParseException e) {
303                                     e.printStackTrace();
304                                     return String.format("Error parsing date '%s'", date);
305                                 }
306                                 state = ParserState.EXPECTING_TRANSACTION_DETAILS;
307                                 L(String.format(Locale.ENGLISH,
308                                         "transaction %d created for %s (%s) →" +
309                                         " expecting details", transactionId, date, m.group(2)));
310                             }
311                             break;
312
313                         case EXPECTING_TRANSACTION_DETAILS:
314                             if (line.isEmpty()) {
315                                 // transaction data collected
316                                 if (transaction.existsInDb(db)) {
317                                     profile.markTransactionAsPresent(db, transaction);
318                                     matchedTransactionsCount++;
319
320                                     if (matchedTransactionsCount == MATCHING_TRANSACTIONS_LIMIT) {
321                                         profile.markTransactionsBeforeTransactionAsPresent(db,
322                                                 transaction);
323                                         progress.setTotal(progress.getProgress());
324                                         publishProgress(progress);
325                                         break LINES;
326                                     }
327                                 }
328                                 else {
329                                     profile.storeTransaction(db, transaction);
330                                     matchedTransactionsCount = 0;
331                                     progress.setTotal(maxTransactionId);
332                                 }
333
334                                 state = ParserState.EXPECTING_TRANSACTION;
335                                 L(String.format("transaction %s saved → expecting transaction",
336                                         transaction.getId()));
337                                 transaction.finishLoading();
338
339 // sounds like a good idea, but transaction-1 may not be the first one chronologically
340 // for example, when you add the initial seeding transaction after entering some others
341 //                                            if (transactionId == 1) {
342 //                                                L("This was the initial transaction. Terminating " +
343 //                                                  "parser");
344 //                                                break LINES;
345 //                                            }
346                             }
347                             else {
348                                 m = reTransactionDetails.matcher(line);
349                                 if (m.find()) {
350                                     String acc_name = m.group(1);
351                                     String amount = m.group(2);
352                                     String currency = m.group(3);
353                                     if (currency == null) currency = "";
354                                     amount = amount.replace(',', '.');
355                                     transaction.addAccount(new LedgerTransactionAccount(acc_name,
356                                             Float.valueOf(amount), currency));
357                                     L(String.format(Locale.ENGLISH, "%d: %s = %s",
358                                             transaction.getId(), acc_name, amount));
359                                 }
360                                 else throw new IllegalStateException(
361                                         String.format("Can't parse transaction %d " + "details: %s",
362                                                 transactionId, line));
363                             }
364                             break;
365                         default:
366                             throw new RuntimeException(
367                                     String.format("Unknown parser updating %s", state.name()));
368                     }
369                 }
370
371                 throwIfCancelled();
372
373                 profile.deleteNotPresentTransactions(db);
374                 db.setTransactionSuccessful();
375
376                 profile.setLastUpdateStamp();
377
378                 return null;
379             }
380             finally {
381                 db.endTransaction();
382             }
383         }
384     }
385     private void prepareDbForRetrieval(SQLiteDatabase db, MobileLedgerProfile profile) {
386         db.execSQL("UPDATE transactions set keep=0 where profile=?",
387                 new String[]{profile.getUuid()});
388         db.execSQL("update account_values set keep=0 where profile=?;",
389                 new String[]{profile.getUuid()});
390         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{profile.getUuid()});
391     }
392     private boolean retrieveAccountList()
393             throws IOException, HTTPException {
394         Progress progress = new Progress();
395
396         HttpURLConnection http = NetworkUtil.prepareConnection(profile, "accounts");
397         http.setAllowUserInteraction(false);
398         switch (http.getResponseCode()) {
399             case 200:
400                 break;
401             case 404:
402                 return false;
403             default:
404                 throw new HTTPException(http.getResponseCode(), http.getResponseMessage());
405         }
406         publishProgress(progress);
407         SQLiteDatabase db = App.getDatabase();
408         ArrayList<LedgerAccount> accountList = new ArrayList<>();
409         boolean listFilledOK = false;
410         try (InputStream resp = http.getInputStream()) {
411             if (http.getResponseCode() != 200)
412                 throw new IOException(String.format("HTTP error %d", http.getResponseCode()));
413
414             db.beginTransaction();
415             try {
416                 profile.markAccountsAsNotPresent(db);
417
418                 AccountListParser parser = new AccountListParser(resp);
419
420                 LedgerAccount prevAccount = null;
421
422                 while (true) {
423                     throwIfCancelled();
424                     ParsedLedgerAccount parsedAccount = parser.nextAccount();
425                     if (parsedAccount == null) break;
426
427                     LedgerAccount acc = profile.tryLoadAccount(db, parsedAccount.getAname());
428                     if (acc == null) acc = new LedgerAccount(parsedAccount.getAname());
429                     else acc.removeAmounts();
430
431                     profile.storeAccount(db, acc);
432                     String lastCurrency = null;
433                     float lastCurrencyAmount = 0;
434                     for (ParsedBalance b : parsedAccount.getAibalance()) {
435                         final String currency = b.getAcommodity();
436                         final float amount = b.getAquantity().asFloat();
437                         if (currency.equals(lastCurrency)) lastCurrencyAmount += amount;
438                         else {
439                             if (lastCurrency != null) {
440                                 profile.storeAccountValue(db, acc.getName(), lastCurrency,
441                                         lastCurrencyAmount);
442                                 acc.addAmount(lastCurrencyAmount, lastCurrency);
443                             }
444                             lastCurrency = currency;
445                             lastCurrencyAmount = amount;
446                         }
447                     }
448                     if (lastCurrency != null) {
449                         profile.storeAccountValue(db, acc.getName(), lastCurrency,
450                                 lastCurrencyAmount);
451                         acc.addAmount(lastCurrencyAmount, lastCurrency);
452                     }
453
454                     if (acc.isVisible(accountList)) accountList.add(acc);
455
456                     if (prevAccount != null) {
457                         prevAccount.setHasSubAccounts(
458                                 acc.getName().startsWith(prevAccount.getName() + ":"));
459                     }
460
461                     prevAccount = acc;
462                 }
463                 throwIfCancelled();
464
465                 profile.deleteNotPresentAccounts(db);
466                 throwIfCancelled();
467                 db.setTransactionSuccessful();
468                 listFilledOK = true;
469             }
470             finally {
471                 db.endTransaction();
472             }
473         }
474         // should not be set in the DB transaction, because of a possible deadlock
475         // with the main and DbOpQueueRunner threads
476         if (listFilledOK) Data.accounts.setList(accountList);
477
478         return true;
479     }
480     private boolean retrieveTransactionList()
481             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 }