From b18cd774a08afb15f9c3b953508b4823211c547b Mon Sep 17 00:00:00 2001 From: Damyan Ivanov Date: Thu, 4 Apr 2019 07:13:14 +0300 Subject: [PATCH] JSON API for adding transactions --- ...tionTask.java => SendTransactionTask.java} | 76 +++++++++++++++---- .../ui/activity/NewTransactionActivity.java | 25 ++++-- 2 files changed, 80 insertions(+), 21 deletions(-) rename app/src/main/java/net/ktnx/mobileledger/async/{SaveTransactionTask.java => SendTransactionTask.java} (70%) diff --git a/app/src/main/java/net/ktnx/mobileledger/async/SaveTransactionTask.java b/app/src/main/java/net/ktnx/mobileledger/async/SendTransactionTask.java similarity index 70% rename from app/src/main/java/net/ktnx/mobileledger/async/SaveTransactionTask.java rename to app/src/main/java/net/ktnx/mobileledger/async/SendTransactionTask.java index bad55eed..fa69f86c 100644 --- a/app/src/main/java/net/ktnx/mobileledger/async/SaveTransactionTask.java +++ b/app/src/main/java/net/ktnx/mobileledger/async/SendTransactionTask.java @@ -20,6 +20,10 @@ package net.ktnx.mobileledger.async; import android.os.AsyncTask; import android.util.Log; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + +import net.ktnx.mobileledger.json.ParsedLedgerTransaction; import net.ktnx.mobileledger.model.Data; import net.ktnx.mobileledger.model.LedgerTransaction; import net.ktnx.mobileledger.model.LedgerTransactionAccount; @@ -40,20 +44,66 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static java.lang.Thread.sleep; +import static android.os.SystemClock.sleep; -public class SaveTransactionTask extends AsyncTask { +public class SendTransactionTask extends AsyncTask { private final TaskCallback taskCallback; protected String error; private String token; private String session; - private String backendUrl; private LedgerTransaction ltr; - public SaveTransactionTask(TaskCallback callback) { + public SendTransactionTask(TaskCallback callback) { taskCallback = callback; } private boolean sendOK() throws IOException { + HttpURLConnection http = NetworkUtil.prepareConnection(Data.profile.get(), "add"); + http.setRequestMethod("PUT"); + http.setRequestProperty("Content-Type", "application/json"); + http.setRequestProperty("Accept", "*/*"); + + ParsedLedgerTransaction jsonTransaction; + jsonTransaction = ltr.toParsedLedgerTransaction(); + ObjectMapper mapper = new ObjectMapper(); + ObjectWriter writer = mapper.writerFor(ParsedLedgerTransaction.class); + String body = writer.writeValueAsString(jsonTransaction); + + byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8); + http.setDoOutput(true); + http.setDoInput(true); + http.addRequestProperty("Content-Length", String.valueOf(bodyBytes.length)); + + Log.d("network", "request header: " + http.getRequestProperties().toString()); + + try (OutputStream req = http.getOutputStream()) { + Log.d("network", "Request body: " + body); + req.write(bodyBytes); + + final int responseCode = http.getResponseCode(); + Log.d("network", + String.format("Response: %d %s", responseCode, http.getResponseMessage())); + + try (InputStream resp = http.getErrorStream()) { + + switch (responseCode) { + case 200: + case 201: + break; + case 405: + return false; // will cause a retry with the legacy method + default: + BufferedReader reader = new BufferedReader(new InputStreamReader(resp)); + String line = reader.readLine(); + Log.d("network", "Response content: " + line); + throw new IOException( + String.format("Error response code %d", responseCode)); + } + } + } + + return true; + } + private boolean legacySendOK() throws IOException { HttpURLConnection http = NetworkUtil.prepareConnection(Data.profile.get(), "add"); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); @@ -144,19 +194,15 @@ public class SaveTransactionTask extends AsyncTask= 2) - throw new IOException(String.format("aborting after %d tries", tried)); - sleep(100); - } - catch (InterruptedException e) { - e.printStackTrace(); + if (!sendOK()) { + int tried = 0; + while (!legacySendOK()) { + tried++; + if (tried >= 2) + throw new IOException(String.format("aborting after %d tries", tried)); + sleep(100); } } } diff --git a/app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java b/app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java index 6f0ea1a8..845afea5 100644 --- a/app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java +++ b/app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java @@ -47,7 +47,7 @@ import com.google.android.material.snackbar.Snackbar; import net.ktnx.mobileledger.BuildConfig; import net.ktnx.mobileledger.R; import net.ktnx.mobileledger.async.DescriptionSelectedCallback; -import net.ktnx.mobileledger.async.SaveTransactionTask; +import net.ktnx.mobileledger.async.SendTransactionTask; import net.ktnx.mobileledger.async.TaskCallback; import net.ktnx.mobileledger.model.Data; import net.ktnx.mobileledger.model.LedgerTransaction; @@ -77,7 +77,7 @@ import androidx.fragment.app.DialogFragment; public class NewTransactionActivity extends ProfileThemedActivity implements TaskCallback, DescriptionSelectedCallback { - private static SaveTransactionTask saver; + private static SendTransactionTask saver; private TableLayout table; private ProgressBar progress; private FloatingActionButton fab; @@ -149,7 +149,7 @@ public class NewTransactionActivity extends ProfileThemedActivity progress.setVisibility(View.VISIBLE); try { - saver = new SaveTransactionTask(this); + saver = new SendTransactionTask(this); String dateString = tvDate.getText().toString(); Date date; @@ -158,16 +158,29 @@ public class NewTransactionActivity extends ProfileThemedActivity LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString()); TableLayout table = findViewById(R.id.new_transaction_accounts_table); + LedgerTransactionAccount emptyAmountAccount = null; + float emptyAmountAccountBalance = 0; for (int i = 0; i < table.getChildCount(); i++) { TableRow row = (TableRow) table.getChildAt(i); String acc = ((TextView) row.getChildAt(0)).getText().toString(); + if (acc.isEmpty()) continue; + String amt = ((TextView) row.getChildAt(1)).getText().toString(); - LedgerTransactionAccount item = - amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt)) - : new LedgerTransactionAccount(acc); + LedgerTransactionAccount item; + if (amt.length() > 0) { + final float amount = Float.parseFloat(amt); + item = new LedgerTransactionAccount(acc, amount); + emptyAmountAccountBalance += amount; + } + else { + item = new LedgerTransactionAccount(acc); + emptyAmountAccount = item; + } tr.addAccount(item); } + + if (emptyAmountAccount != null) emptyAmountAccount.setAmount(-emptyAmountAccountBalance); saver.execute(tr); } catch (ParseException e) { -- 2.39.5