Search in sources :

Example 76 with JSONException

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

the class ClozeTest method testCloze.

@Test
public void testCloze() {
    final Context context = ApplicationProvider.getApplicationContext();
    Collection d = getCol();
    Note f = d.newNote(d.getModels().byName("Cloze"));
    try {
        String name = f.model().getString("name");
        assertEquals("Cloze", name);
    } catch (JSONException e) {
        fail();
    }
    // a cloze model with no clozes is not empty
    f.setItem("Text", "nothing");
    assertThat(d.addNote(f), is(greaterThan(0)));
    // try with one cloze
    f = d.newNote(d.getModels().byName("Cloze"));
    f.setItem("Text", "hello {{c1::world}}");
    assertEquals(1, d.addNote(f));
    assertThat(f.firstCard().q(), containsString("hello <span class=cloze>[...]</span>"));
    assertThat(f.firstCard().a(), containsString("hello <span class=cloze>world</span>"));
    // and with a comment
    f = d.newNote(d.getModels().byName("Cloze"));
    f.setItem("Text", "hello {{c1::world::typical}}");
    assertEquals(1, d.addNote(f));
    assertThat(f.firstCard().q(), containsString("<span class=cloze>[typical]</span>"));
    assertThat(f.firstCard().a(), containsString("<span class=cloze>world</span>"));
    // and with two clozes
    f = d.newNote(d.getModels().byName("Cloze"));
    f.setItem("Text", "hello {{c1::world}} {{c2::bar}}");
    assertEquals(2, d.addNote(f));
    Card c1 = f.firstCard();
    Card c2 = f.cards().get(1);
    assertThat(c1.q(), containsString("<span class=cloze>[...]</span> bar"));
    assertThat(c1.a(), containsString("<span class=cloze>world</span> bar"));
    assertThat(c2.q(), containsString("world <span class=cloze>[...]</span>"));
    assertThat(c2.a(), containsString("world <span class=cloze>bar</span>"));
    // if there are multiple answers for a single cloze, they are given in a
    // list
    f = d.newNote(d.getModels().byName("Cloze"));
    f.setItem("Text", "a {{c1::b}} {{c1::c}}");
    assertEquals(1, d.addNote(f));
    assertThat(f.firstCard().a(), containsString("<span class=cloze>b</span> <span class=cloze>c</span>"));
    // if we add another cloze, a card should be generated
    int cnt = d.cardCount();
    f.setItem("Text", "{{c2::hello}} {{c1::foo}}");
    f.flush();
    assertEquals(cnt + 1, d.cardCount());
    // 0 or negative indices are not supported
    f.setItem("Text", "{{c0::zero}} {{c-1:foo}}");
    f.flush();
    assertEquals(2, f.cards().size());
    // Try a multiline cloze
    f.setItem("Text", "Cloze with {{c1::multi-line\n" + "string}}");
    f.flush();
    assertEquals(1, d.addNote(f));
    String a = f.firstCard().q();
    String b = f.firstCard().a();
    assertThat(f.firstCard().q(), containsString("Cloze with <span class=cloze>[...]</span>"));
    assertThat(f.firstCard().a(), containsString("Cloze with <span class=cloze>multi-line\nstring</span>"));
    // try a multiline cloze in p tag
    f.setItem("Text", "<p>Cloze in html tag with {{c1::multi-line\n" + "string}}</p>");
    f.flush();
    assertEquals(1, d.addNote(f));
    assertThat(f.firstCard().q(), containsString("<p>Cloze in html tag with <span class=cloze>[...]</span>"));
    assertThat(f.firstCard().a(), containsString("<p>Cloze in html tag with <span class=cloze>multi-line\nstring</span>"));
    // make sure multiline cloze things aren't too greedy
    f.setItem("Text", "<p>Cloze in html tag with {{c1::multi-line\n" + "string}} and then {{c2:another\n" + "one}}</p>");
    f.flush();
    assertEquals(1, d.addNote(f));
    assertThat(f.firstCard().q(), containsString("<p>Cloze in html tag with <span class=cloze>[...]</span> and then {{c2:another\n" + "one}}</p>"));
    assertThat(f.firstCard().a(), containsString("<p>Cloze in html tag with <span class=cloze>multi-line\n" + "string</span> and then {{c2:another\n" + "one}}</p>"));
}
Also used : Context(android.content.Context) JSONException(com.ichi2.utils.JSONException) Matchers.containsString(org.hamcrest.Matchers.containsString) RobolectricTest(com.ichi2.anki.RobolectricTest) Test(org.junit.Test)

Example 77 with JSONException

use of com.ichi2.utils.JSONException in project Anki-Android by ankidroid.

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)

Example 78 with JSONException

use of com.ichi2.utils.JSONException in project Anki-Android by ankidroid.

the class Collection method fixIntegrity.

/**
 * Fix possible problems and rebuild caches.
 */
public CheckDatabaseResult fixIntegrity(TaskManager.ProgressCallback<String> progressCallback) {
    File file = new File(mPath);
    CheckDatabaseResult result = new CheckDatabaseResult(file.length());
    final int[] currentTask = { 1 };
    // a few fixes are in all-models loops, the rest are one-offs
    int totalTasks = (getModels().all().size() * 4) + 27;
    Runnable notifyProgress = () -> fixIntegrityProgress(progressCallback, currentTask[0]++, totalTasks);
    Consumer<FunctionalInterfaces.FunctionThrowable<Runnable, List<String>, JSONException>> executeIntegrityTask = function -> {
        // DEFECT: notifyProgress will lag if an exception is thrown.
        try {
            mDb.getDatabase().beginTransaction();
            result.addAll(function.apply(notifyProgress));
            mDb.getDatabase().setTransactionSuccessful();
        } catch (Exception e) {
            Timber.e(e, "Failed to execute integrity check");
            AnkiDroidApp.sendExceptionReport(e, "fixIntegrity");
        } finally {
            try {
                mDb.getDatabase().endTransaction();
            } catch (Exception e) {
                Timber.e(e, "Failed to end integrity check transaction");
                AnkiDroidApp.sendExceptionReport(e, "fixIntegrity - endTransaction");
            }
        }
    };
    try {
        mDb.getDatabase().beginTransaction();
        save();
        notifyProgress.run();
        if (!mDb.getDatabase().isDatabaseIntegrityOk()) {
            return result.markAsFailed();
        }
        mDb.getDatabase().setTransactionSuccessful();
    } catch (SQLiteDatabaseLockedException ex) {
        Timber.w(ex, "doInBackgroundCheckDatabase - Database locked");
        return result.markAsLocked();
    } catch (RuntimeException e) {
        Timber.e(e, "doInBackgroundCheckDatabase - RuntimeException on marking card");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundCheckDatabase");
        return result.markAsFailed();
    } finally {
        // if the database was locked, we never got the transaction.
        if (mDb.getDatabase().inTransaction()) {
            mDb.getDatabase().endTransaction();
        }
    }
    executeIntegrityTask.accept(this::deleteNotesWithMissingModel);
    // for each model
    for (Model m : getModels().all()) {
        executeIntegrityTask.accept((callback) -> deleteCardsWithInvalidModelOrdinals(callback, m));
        executeIntegrityTask.accept((callback) -> deleteNotesWithWrongFieldCounts(callback, m));
    }
    executeIntegrityTask.accept(this::deleteNotesWithMissingCards);
    executeIntegrityTask.accept(this::deleteCardsWithMissingNotes);
    executeIntegrityTask.accept(this::removeOriginalDuePropertyWhereInvalid);
    executeIntegrityTask.accept(this::removeDynamicPropertyFromNonDynamicDecks);
    executeIntegrityTask.accept(this::removeDeckOptionsFromDynamicDecks);
    executeIntegrityTask.accept(this::resetInvalidDeckOptions);
    executeIntegrityTask.accept(this::rebuildTags);
    executeIntegrityTask.accept(this::updateFieldCache);
    executeIntegrityTask.accept(this::fixNewCardDuePositionOverflow);
    executeIntegrityTask.accept(this::resetNewCardInsertionPosition);
    executeIntegrityTask.accept(this::fixExcessiveReviewDueDates);
    // v2 sched had a bug that could create decimal intervals
    executeIntegrityTask.accept(this::fixDecimalCardsData);
    executeIntegrityTask.accept(this::fixDecimalRevLogData);
    executeIntegrityTask.accept(this::restoreMissingDatabaseIndices);
    executeIntegrityTask.accept(this::ensureModelsAreNotEmpty);
    executeIntegrityTask.accept((progressNotifier) -> this.ensureCardsHaveHomeDeck(progressNotifier, result));
    // and finally, optimize (unable to be done inside transaction).
    try {
        optimize(notifyProgress);
    } catch (Exception e) {
        Timber.e(e, "optimize");
        AnkiDroidApp.sendExceptionReport(e, "fixIntegrity - optimize");
    }
    file = new File(mPath);
    long newSize = file.length();
    result.setNewSize(newSize);
    // if any problems were found, force a full sync
    if (result.hasProblems()) {
        modSchemaNoCheck();
    }
    logProblems(result.getProblems());
    return result;
}
Also used : TemplateRenderOutput(com.ichi2.libanki.TemplateManager.TemplateRenderContext.TemplateRenderOutput) Arrays(java.util.Arrays) TaskManager(com.ichi2.async.TaskManager) NonNull(androidx.annotation.NonNull) UsageAnalytics(com.ichi2.anki.analytics.UsageAnalytics) AbstractSched(com.ichi2.libanki.sched.AbstractSched) Random(java.util.Random) DroidBackend(com.ichi2.libanki.backend.DroidBackend) Time(com.ichi2.libanki.utils.Time) FunctionalInterfaces(com.ichi2.utils.FunctionalInterfaces) ParsedNode(com.ichi2.libanki.template.ParsedNode) KotlinCleanup(com.ichi2.utils.KotlinCleanup) SupportSQLiteDatabase(androidx.sqlite.db.SupportSQLiteDatabase) Locale(java.util.Locale) UIUtils(com.ichi2.anki.UIUtils) Map(java.util.Map) CancelListener.isCancelled(com.ichi2.async.CancelListener.isCancelled) JSONException(com.ichi2.utils.JSONException) SQLiteDatabaseLockedException(android.database.sqlite.SQLiteDatabaseLockedException) PrintWriter(java.io.PrintWriter) Upgrade(com.ichi2.upgrade.Upgrade) HashUtil(com.ichi2.utils.HashUtil) GregorianCalendar(java.util.GregorianCalendar) Set(java.util.Set) JSONObject(com.ichi2.utils.JSONObject) Timber(timber.log.Timber) CancelListener(com.ichi2.async.CancelListener) Contract(org.jetbrains.annotations.Contract) List(java.util.List) BackendNotSupportedException(com.ichi2.libanki.backend.exception.BackendNotSupportedException) Nullable(androidx.annotation.Nullable) AnkiDroidApp(com.ichi2.anki.AnkiDroidApp) ContentValues(android.content.ContentValues) UnknownDatabaseVersionException(com.ichi2.libanki.exception.UnknownDatabaseVersionException) Pattern(java.util.regex.Pattern) VersionUtils(com.ichi2.utils.VersionUtils) RustCleanup(net.ankiweb.rsdroid.RustCleanup) Context(android.content.Context) Pair(android.util.Pair) R(com.ichi2.anki.R) HashMap(java.util.HashMap) Sched(com.ichi2.libanki.sched.Sched) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) SuppressLint(android.annotation.SuppressLint) JSONArray(com.ichi2.utils.JSONArray) Calendar(java.util.Calendar) ProgressSender(com.ichi2.async.ProgressSender) ChessFilter(com.ichi2.libanki.hooks.ChessFilter) SupportSQLiteStatement(androidx.sqlite.db.SupportSQLiteStatement) Cursor(android.database.Cursor) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) CheckResult(androidx.annotation.CheckResult) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) SchedV2(com.ichi2.libanki.sched.SchedV2) TextUtils(android.text.TextUtils) CollectionTask(com.ichi2.async.CollectionTask) TemplateError(com.ichi2.libanki.template.TemplateError) IOException(java.io.IOException) File(java.io.File) Consumer(java.util.function.Consumer) NoSuchDeckException(com.ichi2.libanki.exception.NoSuchDeckException) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Collections(java.util.Collections) VisibleForTesting(androidx.annotation.VisibleForTesting) Resources(android.content.res.Resources) SQLiteDatabaseLockedException(android.database.sqlite.SQLiteDatabaseLockedException) SuppressLint(android.annotation.SuppressLint) JSONException(com.ichi2.utils.JSONException) SQLiteDatabaseLockedException(android.database.sqlite.SQLiteDatabaseLockedException) BackendNotSupportedException(com.ichi2.libanki.backend.exception.BackendNotSupportedException) UnknownDatabaseVersionException(com.ichi2.libanki.exception.UnknownDatabaseVersionException) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) IOException(java.io.IOException) NoSuchDeckException(com.ichi2.libanki.exception.NoSuchDeckException) File(java.io.File)

Example 79 with JSONException

use of com.ichi2.utils.JSONException in project Anki-Android by ankidroid.

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 = get_config_int(type);
    } catch (JSONException e) {
        Timber.w(e);
        id = 1;
    }
    set_config(type, id + 1);
    return id;
}
Also used : JSONException(com.ichi2.utils.JSONException) SuppressLint(android.annotation.SuppressLint)

Example 80 with JSONException

use of com.ichi2.utils.JSONException in project Anki-Android by ankidroid.

the class Utils method ids2str.

/**
 * Given a list of integers, return a string '(int1,int2,...)'.
 */
public static String ids2str(JSONArray ids) {
    StringBuilder str = new StringBuilder(512);
    str.append("(");
    if (ids != null) {
        int len = ids.length();
        for (int i = 0; i < len; i++) {
            try {
                if (i == (len - 1)) {
                    str.append(ids.getLong(i));
                } else {
                    str.append(ids.getLong(i)).append(",");
                }
            } catch (JSONException e) {
                Timber.e(e, "ids2str :: JSONException");
            }
        }
    }
    str.append(")");
    return str.toString();
}
Also used : JSONException(com.ichi2.utils.JSONException) SuppressLint(android.annotation.SuppressLint)

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