]> git.ktnx.net Git - mobile-ledger.git/commitdiff
reformat/rewrap
authorDamyan Ivanov <dam+mobileledger@ktnx.net>
Sun, 16 Dec 2018 17:09:57 +0000 (17:09 +0000)
committerDamyan Ivanov <dam+mobileledger@ktnx.net>
Sun, 16 Dec 2018 17:09:57 +0000 (17:09 +0000)
app/src/main/java/net/ktnx/mobileledger/AccountSummary.java
app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
app/src/main/java/net/ktnx/mobileledger/TransactionListAdapter.java
app/src/main/java/net/ktnx/mobileledger/async/RetrieveAccountsTask.java
app/src/main/java/net/ktnx/mobileledger/async/RetrieveTransactionsTask.java

index 2c9589e37cffeb6b25dad537fecd02b9ba2c7f27..3a59003dda2d149801fe139a4b1b9abfa77484f7 100644 (file)
@@ -52,10 +52,9 @@ import java.util.List;
 import static net.ktnx.mobileledger.SettingsActivity.PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS;
 
 public class AccountSummary extends AppCompatActivity {
-    DrawerLayout drawer;
-
     private static long account_list_last_updated;
     private static boolean account_list_needs_update = true;
+    DrawerLayout drawer;
     MenuItem mShowHiddenAccounts;
     SharedPreferences.OnSharedPreferenceChangeListener sBindPreferenceSummaryToValueListener;
     private AccountSummaryViewModel model;
@@ -74,17 +73,20 @@ public class AccountSummary extends AppCompatActivity {
         setSupportActionBar(toolbar);
 
         drawer = findViewById(R.id.drawer_layout);
-        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
-                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
+        ActionBarDrawerToggle toggle =
+                new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
+                        R.string.navigation_drawer_close);
         drawer.addDrawerListener(toggle);
         toggle.syncState();
 
         android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
 
         try {
-            PackageInfo pi = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
+            PackageInfo pi =
+                    getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
             ver.setText(pi.versionName);
-        } catch (Exception e) {
+        }
+        catch (Exception e) {
             e.printStackTrace();
         }
 
@@ -99,30 +101,33 @@ public class AccountSummary extends AppCompatActivity {
         llm.setOrientation(LinearLayoutManager.VERTICAL);
         root.setLayoutManager(llm);
 
-        root.addOnItemTouchListener(new RecyclerItemListener(this, root, new RecyclerItemListener.RecyclerTouchListener() {
-            @Override
-            public void onClickItem(View v, int position) {
-                Log.d("list", String.format("item %d clicked", position));
-                if (modelAdapter.isSelectionActive()) {
-                    modelAdapter.selectItem(position);
-                }
-            }
-
-            @Override
-            public void onLongClickItem(View v, int position) {
-                Log.d("list", String.format("item %d long-clicked", position));
-                modelAdapter.startSelection();
-                if (optMenu != null) {
-                    optMenu.findItem(R.id.menu_acc_summary_cancel_selection).setVisible(true);
-                    optMenu.findItem(R.id.menu_acc_summary_confirm_selection).setVisible(true);
-                    optMenu.findItem(R.id.menu_acc_summary_only_starred).setVisible(false);
-                }
-                {
-                    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.btn_add_transaction);
-                    if (fab != null) fab.hide();
-                }
-            }
-        }));
+        root.addOnItemTouchListener(new RecyclerItemListener(this, root,
+                new RecyclerItemListener.RecyclerTouchListener() {
+                    @Override
+                    public void onClickItem(View v, int position) {
+                        Log.d("list", String.format("item %d clicked", position));
+                        if (modelAdapter.isSelectionActive()) {
+                            modelAdapter.selectItem(position);
+                        }
+                    }
+
+                    @Override
+                    public void onLongClickItem(View v, int position) {
+                        Log.d("list", String.format("item %d long-clicked", position));
+                        modelAdapter.startSelection();
+                        if (optMenu != null) {
+                            optMenu.findItem(R.id.menu_acc_summary_cancel_selection)
+                                    .setVisible(true);
+                            optMenu.findItem(R.id.menu_acc_summary_confirm_selection)
+                                    .setVisible(true);
+                            optMenu.findItem(R.id.menu_acc_summary_only_starred).setVisible(false);
+                        }
+                        {
+                            FloatingActionButton fab = findViewById(R.id.btn_add_transaction);
+                            if (fab != null) fab.hide();
+                        }
+                    }
+                }));
 
         root.addOnScrollListener(new RecyclerView.OnScrollListener() {
             @Override
@@ -190,7 +195,8 @@ public class AccountSummary extends AppCompatActivity {
         DrawerLayout drawer = findViewById(R.id.drawer_layout);
         if (drawer.isDrawerOpen(GravityCompat.START)) {
             drawer.closeDrawer(GravityCompat.START);
-        } else {
+        }
+        else {
             super.onBackPressed();
         }
     }
@@ -233,8 +239,7 @@ public class AccountSummary extends AppCompatActivity {
         update_accounts(true);
     }
 
-    public
-    void onShowOnlyStarredClicked(MenuItem mi) {
+    public void onShowOnlyStarredClicked(MenuItem mi) {
         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
         boolean flag = pref.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false);
 
@@ -252,8 +257,10 @@ public class AccountSummary extends AppCompatActivity {
 
     private void update_accounts(boolean force) {
         long now = new Date().getTime();
-        if ((now > (account_list_last_updated + (24 * 3600*1000))) || force) {
-            Log.d("db", "accounts last updated at " + account_list_last_updated+" and now is " + now+". re-fetching");
+        if ((now > (account_list_last_updated + (24 * 3600 * 1000))) || force) {
+            Log.d("db",
+                    "accounts last updated at " + account_list_last_updated + " and now is " + now +
+                    ". re-fetching");
             update_accounts();
         }
     }
@@ -271,7 +278,7 @@ public class AccountSummary extends AppCompatActivity {
         if (error != 0) {
             String err_text = getResources().getString(error);
             Log.d("visual", String.format("showing snackbar: %s", err_text));
-            Snackbar.make(drawer, err_text, Snackbar.LENGTH_LONG ).show();
+            Snackbar.make(drawer, err_text, Snackbar.LENGTH_LONG).show();
         }
         else {
             MLDB.set_option_value(this, "last_refresh", new Date().getTime());
index 38289020715be1d118a1def9e034a83005ffb259..22b518a04efaef45ded25667966e8e9267fe4177 100644 (file)
@@ -74,11 +74,11 @@ import java.util.Objects;
  *  */
 
 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
+    private static SaveTransactionTask saver;
     private TableLayout table;
     private ProgressBar progress;
     private TextView text_date;
     private AutoCompleteTextView text_descr;
-    private static SaveTransactionTask saver;
     private MenuItem mSave;
 
     @Override
@@ -91,8 +91,7 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
         text_date = findViewById(R.id.new_transaction_date);
         text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
             @Override
-            public
-            void onFocusChange(View v, boolean hasFocus) {
+            public void onFocusChange(View v, boolean hasFocus) {
                 if (hasFocus) pickTransactionDate(v);
             }
         });
@@ -117,8 +116,7 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
     }
 
     @Override
-    protected
-    void onStart() {
+    protected void onStart() {
         super.onStart();
         if (text_descr.getText().toString().isEmpty()) text_descr.requestFocus();
     }
@@ -152,14 +150,13 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
         LedgerTransaction tr = new LedgerTransaction(date, text_descr.getText().toString());
 
         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
-        for ( int i = 0; i < table.getChildCount(); i++ ) {
+        for (int i = 0; i < table.getChildCount(); i++) {
             TableRow row = (TableRow) table.getChildAt(i);
             String acc = ((TextView) row.getChildAt(0)).getText().toString();
             String amt = ((TextView) row.getChildAt(1)).getText().toString();
             LedgerTransactionItem item =
-                    amt.length() > 0
-                    ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
-                    : new LedgerTransactionItem( acc );
+                    amt.length() > 0 ? new LedgerTransactionItem(acc, Float.parseFloat(amt))
+                                     : new LedgerTransactionItem(acc);
 
             tr.add_item(item);
         }
@@ -211,11 +208,11 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
                 }
                 else {
-                    Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
-                            .setAction("Action", null).show();
+                    Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
+                            Snackbar.LENGTH_LONG).setAction("Action", null).show();
                 }
             }
-//            @Override
+            //            @Override
 //            public boolean performClick(View view, MotionEvent m) {
 //                return true;
 //            }
@@ -247,7 +244,8 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
     }
 
     @TargetApi(Build.VERSION_CODES.N)
-    private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
+    private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table,
+                                             final String field) {
         String[] from = {field};
         int[] to = {android.R.id.text1};
         SimpleCursorAdapter adapter =
@@ -257,8 +255,7 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
 
         FilterQueryProvider provider = new FilterQueryProvider() {
             @Override
-            public
-            Cursor runQuery(CharSequence constraint) {
+            public Cursor runQuery(CharSequence constraint) {
                 if (constraint == null) return null;
 
                 String str = constraint.toString().toUpperCase();
@@ -269,11 +266,11 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
                 try (SQLiteDatabase db = MLDB.getReadableDatabase(getApplicationContext())) {
 
                     try (Cursor matches = db.rawQuery(String.format(
-                            "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 "
-                                    + "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 "
-                                    + "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end "
-                                    + "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' "
-                                    + "ORDER BY 2, 1;", field, field, field, field, table, field),
+                            "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
+                            "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
+                            "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
+                            "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 2, 1;",
+                            field, field, field, field, table, field),
                             new String[]{str, str, str, str}))
                     {
                         int i = 0;
@@ -313,16 +310,18 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
     }
 
     public int dp2px(float dp) {
-        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
+        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
+                getResources().getDisplayMetrics()));
     }
 
     private void do_add_account_row(boolean focus) {
         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
-        acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
+        acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
+                TableRow.LayoutParams.WRAP_CONTENT, 9f));
         acc.setHint(R.string.new_transaction_account_hint);
         acc.setWidth(0);
-        acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION
-                | EditorInfo.IME_FLAG_NAVIGATE_NEXT);
+        acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
+                          EditorInfo.IME_FLAG_NAVIGATE_NEXT);
         acc.setSingleLine(true);
 
         final EditText amt = new EditText(this);
@@ -330,7 +329,8 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
                 TableRow.LayoutParams.MATCH_PARENT, 1f));
         amt.setHint(R.string.new_transaction_amount_hint);
         amt.setWidth(0);
-        amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
+        amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
+                         InputType.TYPE_NUMBER_FLAG_DECIMAL);
         amt.setMinWidth(dp2px(40));
         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
@@ -345,7 +345,8 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
         acc.setNextFocusRightId(amt.getId());
 
         final TableRow row = new TableRow(this);
-        row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
+        row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
+                TableRow.LayoutParams.MATCH_PARENT));
         row.setGravity(Gravity.BOTTOM);
         row.addView(acc);
         row.addView(amt);
@@ -363,8 +364,7 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
         do_add_account_row(true);
     }
 
-    public
-    void resetTransactionFromMenu(MenuItem item) {
+    public void resetTransactionFromMenu(MenuItem item) {
         reset_form();
     }
 
@@ -372,8 +372,7 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
         save_transaction();
     }
 
-    private
-    boolean is_zero(float f) {
+    private boolean is_zero(float f) {
         return (f < 0.005) && (f > -0.005);
     }
 
@@ -435,22 +434,21 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
                 }
             }
 
-            if ((empty_rows == 0) && ((table.getChildCount() == accounts) || (table.getChildCount()
-                    == amounts)))
+            if ((empty_rows == 0) &&
+                ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
             {
                 do_add_account_row(false);
             }
 
-            Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, "
-                            + "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, "
-                            + "single_empty_with_acc=%s", accounts, accounts_with_values,
-                    amounts_with_accounts, amounts, running_total,
+            Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
+                                               "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
+                                               "single_empty_with_acc=%s", accounts,
+                    accounts_with_values, amounts_with_accounts, amounts, running_total,
                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
 
-            if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) && (
-                    amounts_with_accounts == amounts) && (
-                    single_empty_amount && single_empty_amount_has_account || is_zero(
-                            running_total)))
+            if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
+                (amounts_with_accounts == amounts) &&
+                (single_empty_amount && single_empty_amount_has_account || is_zero(running_total)))
             {
                 if (mSave != null) mSave.setVisible(true);
             }
@@ -472,8 +470,7 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
     }
 
     @Override
-    public
-    void done(String error) {
+    public void done(String error) {
         progress.setVisibility(View.INVISIBLE);
         Log.d("visuals", "hiding progress");
 
@@ -491,15 +488,15 @@ public class NewTransactionActivity extends AppCompatActivity implements TaskCal
 
         text_descr.requestFocus();
 
-        while(table.getChildCount() > 2) {
+        while (table.getChildCount() > 2) {
             table.removeViewAt(2);
         }
-        for( int i = 0; i < 2; i++ ) {
+        for (int i = 0; i < 2; i++) {
             TableRow tr = (TableRow) table.getChildAt(i);
-            if ( tr == null) break;
+            if (tr == null) break;
 
-            ((TextView)tr.getChildAt(0)).setText("");
-            ((TextView)tr.getChildAt(1)).setText("");
+            ((TextView) tr.getChildAt(0)).setText("");
+            ((TextView) tr.getChildAt(1)).setText("");
         }
     }
 }
index d0b2e9433e7c8a5c5893c4f2674cd4caa02251a0..263aa96e23b896e090e7b79c36be43f9f83ced55 100644 (file)
@@ -53,37 +53,34 @@ class TransactionListAdapter
         try (SQLiteDatabase db = MLDB.getReadableDatabase(ctx.getApplicationContext())) {
             tr.loadData(db);
 
-                holder.tvDescription
-                        .setText(String.format("%s\n%s", tr.getDescription(), tr.getDate()));
-                TableLayout tbl = holder.row.findViewById(R.id.transaction_row_acc_amounts);
-                tbl.removeAllViews();
-                for (Iterator<LedgerTransactionItem> it = tr.getItemsIterator(); it.hasNext(); ) {
-                    LedgerTransactionItem acc = it.next();
-                    TableRow row = new TableRow(holder.row.getContext());
-                    TextView child = new TextView(ctx);
-                    child.setText(acc.getShortAccountName());
-                    row.addView(child);
-                    child = new TextView(ctx);
-                    child.setText(acc.toString());
-                    row.addView(child);
-                    tbl.addView(row);
-                }
-
-                if (position % 2 == 0) {
-                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) holder.row
-                            .setBackgroundColor(
-                                    rm.getColor(R.color.table_row_even_bg, ctx.getTheme()));
-                    else holder.row.setBackgroundColor(rm.getColor(R.color.table_row_even_bg));
-                }
-                else {
-                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) holder.row
-                            .setBackgroundColor(
-                                    rm.getColor(R.color.drawer_background, ctx.getTheme()));
-                    else holder.row.setBackgroundColor(rm.getColor(R.color.drawer_background));
-                }
+            holder.tvDescription
+                    .setText(String.format("%s\n%s", tr.getDescription(), tr.getDate()));
+            TableLayout tbl = holder.row.findViewById(R.id.transaction_row_acc_amounts);
+            tbl.removeAllViews();
+            for (Iterator<LedgerTransactionItem> it = tr.getItemsIterator(); it.hasNext(); ) {
+                LedgerTransactionItem acc = it.next();
+                TableRow row = new TableRow(holder.row.getContext());
+                TextView child = new TextView(ctx);
+                child.setText(acc.getShortAccountName());
+                row.addView(child);
+                child = new TextView(ctx);
+                child.setText(acc.toString());
+                row.addView(child);
+                tbl.addView(row);
+            }
 
-                holder.row.setTag(R.id.POS, position);
+            if (position % 2 == 0) {
+                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) holder.row
+                        .setBackgroundColor(rm.getColor(R.color.table_row_even_bg, ctx.getTheme()));
+                else holder.row.setBackgroundColor(rm.getColor(R.color.table_row_even_bg));
             }
+            else {
+                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) holder.row
+                        .setBackgroundColor(rm.getColor(R.color.drawer_background, ctx.getTheme()));
+                else holder.row.setBackgroundColor(rm.getColor(R.color.drawer_background));
+            }
+
+            holder.row.setTag(R.id.POS, position);
         }
     }
 
index 3d96d3270f188bb09346769a63ac3325b0e147f9..a342ca4dcc9b61b845d8adc25a0d7e591b8cc8bb 100644 (file)
@@ -41,9 +41,8 @@ import java.util.regex.Pattern;
 
 public class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Void> {
     int error;
-
-    private SharedPreferences pref;
     WeakReference<AccountSummary> mContext;
+    private SharedPreferences pref;
 
     public RetrieveAccountsTask(WeakReference<AccountSummary> context) {
         mContext = context;
@@ -56,110 +55,116 @@ public class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Vo
 
     protected Void doInBackground(Void... params) {
         try {
-            HttpURLConnection http = NetworkUtil.prepare_connection( pref, "add");
+            HttpURLConnection http = NetworkUtil.prepare_connection(pref, "add");
             publishProgress(0);
-            try (SQLiteDatabase db = MLDB.getDatabase(mContext.get(), MLDB.DatabaseMode.WRITE)) {
-                    try (InputStream resp = http.getInputStream()) {
-                        Log.d("update_accounts", String.valueOf(http.getResponseCode()));
-                        if (http.getResponseCode() != 200) {
-                            throw new IOException(
-                                    String.format("HTTP error: %d %s", http.getResponseCode(), http.getResponseMessage()));
-                        }
-                        else {
-                            if (db.inTransaction()) throw new AssertionError();
-
-                            db.beginTransaction();
-
-                            try {
-                                db.execSQL("update account_values set keep=0;");
-                                db.execSQL("update accounts set keep=0;");
-
-                                String line;
-                                String last_account_name = null;
-                                BufferedReader buf =
-                                        new BufferedReader(new InputStreamReader(resp, "UTF-8"));
-                                // %3A is '='
-                                Pattern account_name_re = Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
-                                Pattern value_re = Pattern.compile(
-                                        "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
-                                Pattern tr_re = Pattern.compile("</tr>");
-                                Pattern descriptions_line_re = Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
-                                Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
-                                int count = 0;
-                                while ((line = buf.readLine()) != null) {
-                                    Matcher m = account_name_re.matcher(line);
-                                    if (m.find()) {
-                                        String acct_encoded = m.group(1);
-                                        String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
-                                        acct_name = acct_name.replace("\"", "");
-                                        Log.d("account-parser", acct_name);
-
-                                        addAccount(db, acct_name);
-                                        publishProgress(++count);
-
-                                        last_account_name = acct_name;
-
-                                        continue;
-                                    }
+            try (SQLiteDatabase db = MLDB.getWritableDatabase(mContext.get())) {
+                try (InputStream resp = http.getInputStream()) {
+                    Log.d("update_accounts", String.valueOf(http.getResponseCode()));
+                    if (http.getResponseCode() != 200) {
+                        throw new IOException(
+                                String.format("HTTP error: %d %s", http.getResponseCode(),
+                                        http.getResponseMessage()));
+                    }
+                    else {
+                        if (db.inTransaction()) throw new AssertionError();
+
+                        db.beginTransaction();
+
+                        try {
+                            db.execSQL("update account_values set keep=0;");
+                            db.execSQL("update accounts set keep=0;");
+
+                            String line;
+                            String last_account_name = null;
+                            BufferedReader buf =
+                                    new BufferedReader(new InputStreamReader(resp, "UTF-8"));
+                            // %3A is '='
+                            Pattern account_name_re =
+                                    Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
+                            Pattern value_re = Pattern.compile(
+                                    "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
+                            Pattern tr_re = Pattern.compile("</tr>");
+                            Pattern descriptions_line_re =
+                                    Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
+                            Pattern description_items_re =
+                                    Pattern.compile("\"value\":\"([^\"]+)\"");
+                            int count = 0;
+                            while ((line = buf.readLine()) != null) {
+                                Matcher m = account_name_re.matcher(line);
+                                if (m.find()) {
+                                    String acct_encoded = m.group(1);
+                                    String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
+                                    acct_name = acct_name.replace("\"", "");
+                                    Log.d("account-parser", acct_name);
+
+                                    addAccount(db, acct_name);
+                                    publishProgress(++count);
+
+                                    last_account_name = acct_name;
+
+                                    continue;
+                                }
 
-                                    Matcher tr_m = tr_re.matcher(line);
-                                    if (tr_m.find()) {
-                                        Log.d("account-parser", "<tr> - another account expected");
-                                        last_account_name = null;
-                                        continue;
-                                    }
+                                Matcher tr_m = tr_re.matcher(line);
+                                if (tr_m.find()) {
+                                    Log.d("account-parser", "<tr> - another account expected");
+                                    last_account_name = null;
+                                    continue;
+                                }
 
-                                    if (last_account_name != null) {
-                                        m = value_re.matcher(line);
-                                        boolean match_found = false;
-                                        while (m.find()) {
-                                            match_found = true;
-                                            String value = m.group(1);
-                                            String currency = m.group(2);
-                                            if (currency == null) currency = "";
-                                            value = value.replace(',', '.');
-                                            Log.d("db", "curr=" + currency + ", value=" + value);
-                                            db.execSQL(
-                                                    "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
-                                                    new Object[]{last_account_name, currency, Float.valueOf(value)
-                                                    });
-                                        }
-
-                                        if (match_found) continue;
+                                if (last_account_name != null) {
+                                    m = value_re.matcher(line);
+                                    boolean match_found = false;
+                                    while (m.find()) {
+                                        match_found = true;
+                                        String value = m.group(1);
+                                        String currency = m.group(2);
+                                        if (currency == null) currency = "";
+                                        value = value.replace(',', '.');
+                                        Log.d("db", "curr=" + currency + ", value=" + value);
+                                        db.execSQL(
+                                                "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
+                                                new Object[]{last_account_name, currency,
+                                                             Float.valueOf(value)
+                                                });
                                     }
 
-                                    m = descriptions_line_re.matcher(line);
-                                    if (m.find()) {
-                                        db.execSQL("update description_history set keep=0;");
-                                        m = description_items_re.matcher(line);
-                                        while (m.find()) {
-                                            String description = m.group(1);
-                                            if (description.isEmpty()) continue;
-
-                                            Log.d("db", String.format("Stored description: %s",
-                                                    description));
-                                            db.execSQL("insert or replace into description_history"
-                                                            + "(description, description_upper, keep) " + "values(?, ?, 1);",
-                                                    new Object[]{description, description.toUpperCase()
-                                                    });
-                                        }
-                                    }
+                                    if (match_found) continue;
                                 }
 
-                                db.execSQL("delete from account_values where keep=0;");
-                                db.execSQL("delete from accounts where keep=0;");
-//                        db.execSQL("delete from description_history where keep=0;");
-                                db.setTransactionSuccessful();
-                            }
-                            finally {
-                                db.endTransaction();
+                                m = descriptions_line_re.matcher(line);
+                                if (m.find()) {
+                                    db.execSQL("update description_history set keep=0;");
+                                    m = description_items_re.matcher(line);
+                                    while (m.find()) {
+                                        String description = m.group(1);
+                                        if (description.isEmpty()) continue;
+
+                                        Log.d("db", String.format("Stored description: %s",
+                                                description));
+                                        db.execSQL("insert or replace into description_history" +
+                                                   "(description, description_upper, keep) " +
+                                                   "values(?, ?, 1);",
+                                                new Object[]{description, description.toUpperCase()
+                                                });
+                                    }
+                                }
                             }
 
+                            db.execSQL("delete from account_values where keep=0;");
+                            db.execSQL("delete from accounts where keep=0;");
+//                        db.execSQL("delete from description_history where keep=0;");
+                            db.setTransactionSuccessful();
+                        }
+                        finally {
+                            db.endTransaction();
                         }
+
                     }
                 }
             }
-        } catch (MalformedURLException e) {
+        }
+        catch (MalformedURLException e) {
             error = R.string.err_bad_backend_url;
             e.printStackTrace();
         }
@@ -182,11 +187,10 @@ public class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Vo
     private void addAccount(SQLiteDatabase db, String name) {
         do {
             LedgerAccount acc = new LedgerAccount(name);
-            db.execSQL(
-                    "update accounts set level = ?, keep = 1 where name = ?",
+            db.execSQL("update accounts set level = ?, keep = 1 where name = ?",
                     new Object[]{acc.getLevel(), name});
-            db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?,"
-                            + "?,? " + "where (select changes() = 0)",
+            db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?," +
+                       "?,? " + "where (select changes() = 0)",
                     new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
             name = acc.getParentName();
         } while (name != null);
index 8a9a8f62e8e98c4917aab9e383828c48f496771d..63b30b5c0a9467d71163d062ee866bb7ff6c6c05 100644 (file)
@@ -95,79 +95,83 @@ public class RetrieveTransactionsTask extends
             Context ctx = contextRef.get();
             if (ctx == null) return null;
             try (SQLiteDatabase db = MLDB.getWritableDatabase(ctx)) {
-                    try (InputStream resp = http.getInputStream()) {
-                        if (http.getResponseCode() != 200) throw new IOException(
-                                String.format("HTTP error %d", http.getResponseCode()));
-                        db.beginTransaction();
-                        try {
-                            db.execSQL("DELETE FROM transactions;");
-                            db.execSQL("DELETE FROM transaction_accounts");
+                try (InputStream resp = http.getInputStream()) {
+                    if (http.getResponseCode() != 200) throw new IOException(
+                            String.format("HTTP error %d", http.getResponseCode()));
+                    db.beginTransaction();
+                    try {
+                        db.execSQL("DELETE FROM transactions;");
+                        db.execSQL("DELETE FROM transaction_accounts");
 
-                            int state = ParserState.EXPECTING_JOURNAL;
-                            String line;
-                            BufferedReader buf =
-                                    new BufferedReader(new InputStreamReader(resp, "UTF-8"));
+                        int state = ParserState.EXPECTING_JOURNAL;
+                        String line;
+                        BufferedReader buf =
+                                new BufferedReader(new InputStreamReader(resp, "UTF-8"));
 
-                            int transactionCount = 0;
-                            int transactionId = 0;
-                            LedgerTransaction transaction = null;
-                            LINES:
-                            while ((line = buf.readLine()) != null) {
-                                if (isCancelled()) break;
-                                if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
-                                Matcher m;
-                                //L(String.format("State is %d", state));
-                                switch (state) {
-                                    case ParserState.EXPECTING_JOURNAL:
-                                        if (line.equals("<h2>General Journal</h2>")) {
-                                            state = ParserState.EXPECTING_TRANSACTION;
-                                            L("→ expecting transaction");
-                                        }
-                                        break;
-                                    case ParserState.EXPECTING_TRANSACTION:
-                                        m = transactionStartPattern.matcher(line);
-                                        if (m.find()) {
-                                            transactionId = Integer.valueOf(m.group(1));
-                                            state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
-                                            L(String.format("found transaction %d → expecting " +
-                                                            "description", transactionId));
-                                            progress.setProgress(++transactionCount);
-                                            if (progress.getTotal() == Progress.INDETERMINATE)
-                                                progress.setTotal(transactionId);
-                                            publishProgress(progress);
-                                        }
-                                        m = endPattern.matcher(line);
-                                        if (m.find()) {
-                                            L("--- transaction list complete ---");
-                                            success = true;
-                                            break LINES;
-                                        }
-                                        break;
-                                    case ParserState.EXPECTING_TRANSACTION_DESCRIPTION:
-                                        m = transactionDescriptionPattern.matcher(line);
-                                        if (m.find()) {
-                                            if (transactionId == 0)
-                                                throw new TransactionParserException(
-                                                        "Transaction Id is 0 while expecting " +
-                                                        "description");
+                        int transactionCount = 0;
+                        int transactionId = 0;
+                        LedgerTransaction transaction = null;
+                        LINES:
+                        while ((line = buf.readLine()) != null) {
+                            if (isCancelled()) break;
+                            Matcher m;
+                            //L(String.format("State is %d", state));
+                            switch (state) {
+                                case ParserState.EXPECTING_JOURNAL:
+                                    if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
+                                    if (line.equals("<h2>General Journal</h2>")) {
+                                        state = ParserState.EXPECTING_TRANSACTION;
+                                        L("→ expecting transaction");
+                                    }
+                                    break;
+                                case ParserState.EXPECTING_TRANSACTION:
+                                    if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
+                                    m = transactionStartPattern.matcher(line);
+                                    if (m.find()) {
+                                        transactionId = Integer.valueOf(m.group(1));
+                                        state = ParserState.EXPECTING_TRANSACTION_DESCRIPTION;
+                                        L(String.format(
+                                                "found transaction %d → expecting " + "description",
+                                                transactionId));
+                                        progress.setProgress(++transactionCount);
+                                        if (progress.getTotal() == Progress.INDETERMINATE)
+                                            progress.setTotal(transactionId);
+                                        publishProgress(progress);
+                                    }
+                                    m = endPattern.matcher(line);
+                                    if (m.find()) {
+                                        L("--- transaction list complete ---");
+                                        success = true;
+                                        break LINES;
+                                    }
+                                    break;
+                                case ParserState.EXPECTING_TRANSACTION_DESCRIPTION:
+                                    if (!line.isEmpty() && (line.charAt(0) == ' ')) continue;
+                                    m = transactionDescriptionPattern.matcher(line);
+                                    if (m.find()) {
+                                        if (transactionId == 0)
+                                            throw new TransactionParserException(
+                                                    "Transaction Id is 0 while expecting " +
+                                                    "description");
 
-                                            transaction =
-                                                    new LedgerTransaction(transactionId, m.group(1),
-                                                            m.group(2));
-                                            state = ParserState.EXPECTING_TRANSACTION_DETAILS;
-                                            L(String.format("transaction %d created for %s (%s) →" +
-                                                            " expecting details", transactionId,
-                                                    m.group(1), m.group(2)));
-                                        }
-                                        break;
-                                    case ParserState.EXPECTING_TRANSACTION_DETAILS:
-                                        if (line.isEmpty()) {
-                                            // transaction data collected
-                                            transaction.insertInto(db);
+                                        transaction =
+                                                new LedgerTransaction(transactionId, m.group(1),
+                                                        m.group(2));
+                                        state = ParserState.EXPECTING_TRANSACTION_DETAILS;
+                                        L(String.format("transaction %d created for %s (%s) →" +
+                                                        " expecting details", transactionId,
+                                                m.group(1), m.group(2)));
+                                    }
+                                    break;
+                                case ParserState.EXPECTING_TRANSACTION_DETAILS:
+                                    if (line.isEmpty()) {
+                                        // transaction data collected
+                                        transaction.insertInto(db);
 
-                                            state = ParserState.EXPECTING_TRANSACTION;
-                                            L(String.format("transaction %s saved → expecting " +
-                                                            "transaction", transaction.getId()));
+                                        state = ParserState.EXPECTING_TRANSACTION;
+                                        L(String.format(
+                                                "transaction %s saved → expecting " + "transaction",
+                                                transaction.getId()));
 
 // sounds like a good idea, but transaction-1 may not be the first one chronologically
 // for example, when you add the initial seeding transaction after entering some others
@@ -176,33 +180,30 @@ public class RetrieveTransactionsTask extends
 //                                                  "parser");
 //                                                break LINES;
 //                                            }
+                                    }
+                                    else {
+                                        m = transactionDetailsPattern.matcher(line);
+                                        if (m.find()) {
+                                            String acc_name = m.group(1);
+                                            String amount = m.group(2);
+                                            amount = amount.replace(',', '.');
+                                            transaction.add_item(new LedgerTransactionItem(acc_name,
+                                                    Float.valueOf(amount)));
+                                            L(String.format("%s = %s", acc_name, amount));
                                         }
-                                        else {
-                                            m = transactionDetailsPattern.matcher(line);
-                                            if (m.find()) {
-                                                String acc_name = m.group(1);
-                                                String amount = m.group(2);
-                                                amount = amount.replace(',', '.');
-                                                transaction.add_item(
-                                                        new LedgerTransactionItem(acc_name,
-                                                                Float.valueOf(amount)));
-                                                L(String.format("%s = %s", acc_name, amount));
-                                            }
-                                            else throw new IllegalStateException(String.format(
-                                                    "Can't parse transaction details"));
-                                        }
-                                        break;
-                                    default:
-                                        throw new RuntimeException(
-                                                String.format("Unknown " + "parser state %d",
-                                                        state));
-                                }
+                                        else throw new IllegalStateException(
+                                                String.format("Can't parse transaction details"));
+                                    }
+                                    break;
+                                default:
+                                    throw new RuntimeException(
+                                            String.format("Unknown " + "parser state %d", state));
                             }
-                            if (!isCancelled()) db.setTransactionSuccessful();
-                        }
-                        finally {
-                            db.endTransaction();
                         }
+                        if (!isCancelled()) db.setTransactionSuccessful();
+                    }
+                    finally {
+                        db.endTransaction();
                     }
                 }
             }