Search in sources :

Example 11 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class Connection method doInBackgroundLogin.

private Payload doInBackgroundLogin(Payload data) {
    String username = (String) data.data[0];
    String password = (String) data.data[1];
    HostNum hostNum = (HostNum) data.data[2];
    HttpSyncer server = new RemoteServer(this, null, hostNum);
    Response ret;
    try {
        ret = server.hostKey(username, password);
    } catch (UnknownHttpResponseException e) {
        data.success = false;
        data.result = new Object[] { "error", e.getResponseCode(), e.getMessage() };
        return data;
    } catch (Exception e2) {
        // Ask user to report all bugs which aren't timeout errors
        if (!timeoutOccurred(e2)) {
            AnkiDroidApp.sendExceptionReport(e2, "doInBackgroundLogin");
        }
        data.success = false;
        data.result = new Object[] { "connectionError", e2 };
        return data;
    }
    String hostkey = null;
    boolean valid = false;
    if (ret != null) {
        data.returnType = ret.code();
        Timber.d("doInBackgroundLogin - response from server: %d, (%s)", data.returnType, ret.message());
        if (data.returnType == 200) {
            try {
                JSONObject response = new JSONObject(ret.body().string());
                hostkey = response.getString("key");
                valid = (hostkey != null) && (hostkey.length() > 0);
            } catch (JSONException e) {
                valid = false;
            } catch (IllegalStateException | IOException | NullPointerException e) {
                throw new RuntimeException(e);
            }
        }
    } else {
        Timber.e("doInBackgroundLogin - empty response from server");
    }
    if (valid) {
        data.success = true;
        data.data = new String[] { username, hostkey };
    } else {
        data.success = false;
    }
    return data;
}
Also used : JSONException(com.ichi2.utils.JSONException) HostNum(com.ichi2.libanki.sync.HostNum) IOException(java.io.IOException) UnknownHttpResponseException(com.ichi2.anki.exception.UnknownHttpResponseException) JSONException(com.ichi2.utils.JSONException) NoEnoughServerSpaceException(com.ichi2.anki.exception.NoEnoughServerSpaceException) MediaSyncException(com.ichi2.anki.exception.MediaSyncException) IOException(java.io.IOException) UnknownHttpResponseException(com.ichi2.anki.exception.UnknownHttpResponseException) Response(okhttp3.Response) JSONObject(com.ichi2.utils.JSONObject) JSONObject(com.ichi2.utils.JSONObject) HttpSyncer(com.ichi2.libanki.sync.HttpSyncer) RemoteServer(com.ichi2.libanki.sync.RemoteServer)

Example 12 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class Collection method deleteNotesWithWrongFieldCounts.

private ArrayList<String> deleteNotesWithWrongFieldCounts(Runnable notifyProgress, JSONObject m) throws JSONException {
    Timber.d("deleteNotesWithWrongFieldCounts");
    ArrayList<String> problems = new ArrayList<>();
    // notes with invalid field counts
    ArrayList<Long> ids;
    ids = new ArrayList<>();
    Cursor cur = null;
    try {
        notifyProgress.run();
        cur = mDb.getDatabase().query("select id, flds from notes where mid = " + m.getLong("id"), null);
        Timber.i("cursor size: %d", cur.getCount());
        int currentRow = 0;
        // Since we loop through all rows, we only want one exception
        @Nullable Exception firstException = null;
        while (cur.moveToNext()) {
            try {
                String flds = cur.getString(1);
                long id = cur.getLong(0);
                int fldsCount = 0;
                for (int i = 0; i < flds.length(); i++) {
                    if (flds.charAt(i) == 0x1f) {
                        fldsCount++;
                    }
                }
                if (fldsCount + 1 != m.getJSONArray("flds").length()) {
                    ids.add(id);
                }
            } catch (IllegalStateException ex) {
                // DEFECT: Theory that is this an OOM is discussed in #5852
                // We store one exception to stop excessive logging
                Timber.i(ex, "deleteNotesWithWrongFieldCounts - Exception on row %d. Columns: %d", currentRow, cur.getColumnCount());
                if (firstException == null) {
                    String details = String.format(Locale.ROOT, "deleteNotesWithWrongFieldCounts row: %d col: %d", currentRow, cur.getColumnCount());
                    AnkiDroidApp.sendExceptionReport(ex, details);
                    firstException = ex;
                }
            }
            currentRow++;
        }
        Timber.i("deleteNotesWithWrongFieldCounts - completed successfully");
        notifyProgress.run();
        if (ids.size() > 0) {
            problems.add("Deleted " + ids.size() + " note(s) with wrong field count.");
            _remNotes(ids);
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    return problems;
}
Also used : ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) SuppressLint(android.annotation.SuppressLint) Nullable(androidx.annotation.Nullable) JSONException(com.ichi2.utils.JSONException) SQLiteDatabaseLockedException(android.database.sqlite.SQLiteDatabaseLockedException) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) IOException(java.io.IOException) NoSuchDeckException(com.ichi2.libanki.exception.NoSuchDeckException)

Example 13 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class Collection method nextID.

/**
 * Utils ******************************************************************** ***************************
 */
public int nextID(String type) {
    type = "next" + Character.toUpperCase(type.charAt(0)) + type.substring(1);
    int id;
    try {
        id = mConf.getInt(type);
    } catch (JSONException e) {
        id = 1;
    }
    mConf.put(type, id + 1);
    return id;
}
Also used : JSONException(com.ichi2.utils.JSONException) SuppressLint(android.annotation.SuppressLint)

Example 14 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class Collection method genCards.

public ArrayList<Long> genCards(long[] nids) {
    // build map of (nid,ord) so we don't create dupes
    String snids = Utils.ids2str(nids);
    HashMap<Long, HashMap<Integer, Long>> have = new HashMap<>();
    HashMap<Long, Long> dids = new HashMap<>();
    HashMap<Long, Long> dues = new HashMap<>();
    Cursor cur = null;
    try {
        cur = mDb.getDatabase().query("select id, nid, ord, did, due, odue, odid, type from cards where nid in " + snids, null);
        while (cur.moveToNext()) {
            long id = cur.getLong(0);
            long nid = cur.getLong(1);
            int ord = cur.getInt(2);
            long did = cur.getLong(3);
            long due = cur.getLong(4);
            long odue = cur.getLong(5);
            long odid = cur.getLong(6);
            @Consts.CARD_TYPE int type = cur.getInt(7);
            // existing cards
            if (!have.containsKey(nid)) {
                have.put(nid, new HashMap<Integer, Long>());
            }
            have.get(nid).put(ord, id);
            // if in a filtered deck, add new cards to original deck
            if (odid != 0) {
                did = odid;
            }
            // and their dids
            if (dids.containsKey(nid)) {
                if (dids.get(nid) != 0 && dids.get(nid) != did) {
                    // cards are in two or more different decks; revert to model default
                    dids.put(nid, 0L);
                }
            } else {
                // first card or multiple cards in same deck
                dids.put(nid, did);
            }
            // save due
            if (odid != 0) {
                due = odue;
            }
            if (!dues.containsKey(nid) && type == Consts.CARD_TYPE_NEW) {
                dues.put(nid, due);
            }
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    // build cards for each note
    ArrayList<Object[]> data = new ArrayList<>();
    long ts = getTime().maxID(mDb);
    long now = getTime().intTime();
    ArrayList<Long> rem = new ArrayList<>();
    int usn = usn();
    cur = null;
    try {
        cur = mDb.getDatabase().query("SELECT id, mid, flds FROM notes WHERE id IN " + snids, null);
        while (cur.moveToNext()) {
            long nid = cur.getLong(0);
            long mid = cur.getLong(1);
            String flds = cur.getString(2);
            Model model = getModels().get(mid);
            ArrayList<Integer> avail = getModels().availOrds(model, Utils.splitFields(flds));
            Long did = dids.get(nid);
            // use sibling due if there is one, else use a new id
            long due;
            if (dues.containsKey(nid)) {
                due = dues.get(nid);
            } else {
                due = nextID("pos");
            }
            if (did == null || did == 0L) {
                did = model.getLong("did");
            }
            // add any missing cards
            for (JSONObject t : _tmplsFromOrds(model, avail)) {
                int tord = t.getInt("ord");
                boolean doHave = have.containsKey(nid) && have.get(nid).containsKey(tord);
                if (!doHave) {
                    // check deck is not a cram deck
                    long ndid;
                    try {
                        ndid = t.getLong("did");
                        if (ndid != 0) {
                            did = ndid;
                        }
                    } catch (JSONException e) {
                    // do nothing
                    }
                    if (getDecks().isDyn(did)) {
                        did = 1L;
                    }
                    // if the deck doesn't exist, use default instead
                    did = mDecks.get(did).getLong("id");
                    // give it a new id instead
                    data.add(new Object[] { ts, nid, did, tord, now, usn, due });
                    ts += 1;
                }
            }
            // note any cards that need removing
            if (have.containsKey(nid)) {
                for (Map.Entry<Integer, Long> n : have.get(nid).entrySet()) {
                    if (!avail.contains(n.getKey())) {
                        rem.add(n.getValue());
                    }
                }
            }
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    // bulk update
    mDb.executeMany("INSERT INTO cards VALUES (?,?,?,?,?,?,0,0,?,0,0,0,0,0,0,0,0,\"\")", data);
    return rem;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JSONException(com.ichi2.utils.JSONException) Cursor(android.database.Cursor) SuppressLint(android.annotation.SuppressLint) JSONObject(com.ichi2.utils.JSONObject) Map(java.util.Map) HashMap(java.util.HashMap)

Example 15 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class Sched method _updateRevIvl.

@Override
protected void _updateRevIvl(@NonNull Card card, @Consts.BUTTON_TYPE int ease) {
    try {
        int idealIvl = _nextRevIvl(card, ease);
        JSONObject conf = _revConf(card);
        card.setIvl(Math.min(Math.max(_adjRevIvl(card, idealIvl), card.getIvl() + 1), conf.getInt("maxIvl")));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}
Also used : JSONObject(com.ichi2.utils.JSONObject) JSONException(com.ichi2.utils.JSONException)

Aggregations

JSONException (com.ichi2.utils.JSONException)54 JSONObject (com.ichi2.utils.JSONObject)41 JSONException (org.json.JSONException)28 Collection (com.ichi2.libanki.Collection)25 ArrayList (java.util.ArrayList)25 JSONObject (org.json.JSONObject)22 JSONArray (com.ichi2.utils.JSONArray)21 SuppressLint (android.annotation.SuppressLint)18 IOException (java.io.IOException)17 File (java.io.File)16 Note (com.ichi2.libanki.Note)14 ConfirmModSchemaException (com.ichi2.anki.exception.ConfirmModSchemaException)12 HashMap (java.util.HashMap)12 Bundle (android.os.Bundle)11 Deck (com.ichi2.libanki.Deck)11 Resources (android.content.res.Resources)10 Model (com.ichi2.libanki.Model)10 Map (java.util.Map)10 List (java.util.List)9 Context (android.content.Context)8