Search in sources :

Example 11 with StorIOException

use of com.pushtorefresh.storio.StorIOException in project storio by pushtorefresh.

the class PreparedGetListOfObjects method executeAsBlocking.

/**
     * Executes Get Operation immediately in current thread.
     * <p>
     * Notice: This is blocking I/O operation that should not be executed on the Main Thread,
     * it can cause ANR (Activity Not Responding dialog), block the UI and drop animations frames.
     * So please, call this method on some background thread. See {@link WorkerThread}.
     *
     * @return non-null, immutable {@link List} with mapped results, list can be empty.
     */
@WorkerThread
@SuppressWarnings({ "TryFinallyCanBeTryWithResources", "unchecked" })
// Min SDK :( unchecked for empty list
@NonNull
@Override
public List<T> executeAsBlocking() {
    try {
        final GetResolver<T> getResolver;
        if (explicitGetResolver != null) {
            getResolver = explicitGetResolver;
        } else {
            final SQLiteTypeMapping<T> typeMapping = storIOSQLite.lowLevel().typeMapping(type);
            if (typeMapping == null) {
                throw new IllegalStateException("This type does not have type mapping: " + "type = " + type + "," + "db was not touched by this operation, please add type mapping for this type");
            }
            getResolver = typeMapping.getResolver();
        }
        final Cursor cursor;
        if (query != null) {
            cursor = getResolver.performGet(storIOSQLite, query);
        } else if (rawQuery != null) {
            cursor = getResolver.performGet(storIOSQLite, rawQuery);
        } else {
            throw new IllegalStateException("Please specify query");
        }
        try {
            final int count = cursor.getCount();
            if (count == 0) {
                // it's immutable
                return EMPTY_LIST;
            }
            final List<T> list = new ArrayList<T>(count);
            while (cursor.moveToNext()) {
                list.add(getResolver.mapFromCursor(cursor));
            }
            return unmodifiableList(list);
        } finally {
            cursor.close();
        }
    } catch (Exception exception) {
        throw new StorIOException("Error has occurred during Get operation. query = " + (query != null ? query : rawQuery), exception);
    }
}
Also used : EMPTY_LIST(java.util.Collections.EMPTY_LIST) StorIOException(com.pushtorefresh.storio.StorIOException) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) StorIOException(com.pushtorefresh.storio.StorIOException) WorkerThread(android.support.annotation.WorkerThread) NonNull(android.support.annotation.NonNull)

Example 12 with StorIOException

use of com.pushtorefresh.storio.StorIOException in project storio by pushtorefresh.

the class PreparedGetObject method executeAsBlocking.

/**
     * Executes Get Operation immediately in current thread.
     * <p>
     * Notice: This is blocking I/O operation that should not be executed on the Main Thread,
     * it can cause ANR (Activity Not Responding dialog), block the UI and drop animations frames.
     * So please, call this method on some background thread. See {@link WorkerThread}.
     *
     * @return single instance of mapped result. Can be {@code null}, if no items are found.
     */
@Nullable
@SuppressWarnings({ "ConstantConditions", "NullableProblems" })
@WorkerThread
public T executeAsBlocking() {
    try {
        final GetResolver<T> getResolver;
        if (explicitGetResolver != null) {
            getResolver = explicitGetResolver;
        } else {
            final SQLiteTypeMapping<T> typeMapping = storIOSQLite.lowLevel().typeMapping(type);
            if (typeMapping == null) {
                throw new IllegalStateException("This type does not have type mapping: " + "type = " + type + "," + "db was not touched by this operation, please add type mapping for this type");
            }
            getResolver = typeMapping.getResolver();
        }
        final Cursor cursor;
        if (query != null) {
            cursor = getResolver.performGet(storIOSQLite, query);
        } else if (rawQuery != null) {
            cursor = getResolver.performGet(storIOSQLite, rawQuery);
        } else {
            throw new IllegalStateException("Please specify query");
        }
        try {
            final int count = cursor.getCount();
            if (count == 0) {
                return null;
            }
            cursor.moveToNext();
            return getResolver.mapFromCursor(cursor);
        } finally {
            cursor.close();
        }
    } catch (Exception exception) {
        throw new StorIOException("Error has occurred during Get operation. query = " + (query != null ? query : rawQuery), exception);
    }
}
Also used : StorIOException(com.pushtorefresh.storio.StorIOException) Cursor(android.database.Cursor) StorIOException(com.pushtorefresh.storio.StorIOException) WorkerThread(android.support.annotation.WorkerThread) Nullable(android.support.annotation.Nullable)

Example 13 with StorIOException

use of com.pushtorefresh.storio.StorIOException in project storio by pushtorefresh.

the class PreparedPutCollectionOfObjects method executeAsBlocking.

/**
     * Executes Put Operation immediately in current thread.
     * <p>
     * Notice: This is blocking I/O operation that should not be executed on the Main Thread,
     * it can cause ANR (Activity Not Responding dialog), block the UI and drop animations frames.
     * So please, call this method on some background thread. See {@link WorkerThread}.
     *
     * @return non-null results of Put Operation.
     */
@SuppressWarnings("unchecked")
@WorkerThread
@NonNull
@Override
public PutResults<T> executeAsBlocking() {
    try {
        final StorIOSQLite.LowLevel lowLevel = storIOSQLite.lowLevel();
        // Nullable
        final List<SimpleImmutableEntry<T, PutResolver<T>>> objectsAndPutResolvers;
        if (explicitPutResolver != null) {
            objectsAndPutResolvers = null;
        } else {
            objectsAndPutResolvers = new ArrayList<SimpleImmutableEntry<T, PutResolver<T>>>(objects.size());
            for (final T object : objects) {
                final SQLiteTypeMapping<T> typeMapping = (SQLiteTypeMapping<T>) lowLevel.typeMapping(object.getClass());
                if (typeMapping == null) {
                    throw new IllegalStateException("One of the objects from the collection does not have type mapping: " + "object = " + object + ", object.class = " + object.getClass() + "," + "db was not affected by this operation, please add type mapping for this type");
                }
                objectsAndPutResolvers.add(new SimpleImmutableEntry<T, PutResolver<T>>(object, typeMapping.putResolver()));
            }
        }
        if (useTransaction) {
            lowLevel.beginTransaction();
        }
        final Map<T, PutResult> results = new HashMap<T, PutResult>(objects.size());
        boolean transactionSuccessful = false;
        try {
            if (explicitPutResolver != null) {
                for (final T object : objects) {
                    final PutResult putResult = explicitPutResolver.performPut(storIOSQLite, object);
                    results.put(object, putResult);
                    if (!useTransaction && (putResult.wasInserted() || putResult.wasUpdated())) {
                        lowLevel.notifyAboutChanges(Changes.newInstance(putResult.affectedTables()));
                    }
                }
            } else {
                for (final SimpleImmutableEntry<T, PutResolver<T>> objectAndPutResolver : objectsAndPutResolvers) {
                    final T object = objectAndPutResolver.getKey();
                    final PutResolver<T> putResolver = objectAndPutResolver.getValue();
                    final PutResult putResult = putResolver.performPut(storIOSQLite, object);
                    results.put(object, putResult);
                    if (!useTransaction && (putResult.wasInserted() || putResult.wasUpdated())) {
                        lowLevel.notifyAboutChanges(Changes.newInstance(putResult.affectedTables()));
                    }
                }
            }
            if (useTransaction) {
                lowLevel.setTransactionSuccessful();
                transactionSuccessful = true;
            }
        } finally {
            if (useTransaction) {
                lowLevel.endTransaction();
                // if put was in transaction and it was successful -> notify about changes
                if (transactionSuccessful) {
                    // in most cases it will be 1 table
                    final Set<String> affectedTables = new HashSet<String>(1);
                    for (final T object : results.keySet()) {
                        final PutResult putResult = results.get(object);
                        if (putResult.wasInserted() || putResult.wasUpdated()) {
                            affectedTables.addAll(putResult.affectedTables());
                        }
                    }
                    // It'll reduce number of possible deadlock situations
                    if (!affectedTables.isEmpty()) {
                        lowLevel.notifyAboutChanges(Changes.newInstance(affectedTables));
                    }
                }
            }
        }
        return PutResults.newInstance(results);
    } catch (Exception exception) {
        throw new StorIOException("Error has occurred during Put operation. objects = " + objects, exception);
    }
}
Also used : HashMap(java.util.HashMap) StorIOException(com.pushtorefresh.storio.StorIOException) StorIOException(com.pushtorefresh.storio.StorIOException) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) StorIOSQLite(com.pushtorefresh.storio.sqlite.StorIOSQLite) SQLiteTypeMapping(com.pushtorefresh.storio.sqlite.SQLiteTypeMapping) HashSet(java.util.HashSet) WorkerThread(android.support.annotation.WorkerThread) NonNull(android.support.annotation.NonNull)

Example 14 with StorIOException

use of com.pushtorefresh.storio.StorIOException in project storio by pushtorefresh.

the class PreparedPutContentValuesIterable method executeAsBlocking.

/**
     * Executes Put Operation immediately in current thread.
     * <p>
     * Notice: This is blocking I/O operation that should not be executed on the Main Thread,
     * it can cause ANR (Activity Not Responding dialog), block the UI and drop animations frames.
     * So please, call this method on some background thread. See {@link WorkerThread}.
     *
     * @return non-null results of Put Operation.
     */
@WorkerThread
@NonNull
@Override
public PutResults<ContentValues> executeAsBlocking() {
    try {
        final StorIOSQLite.LowLevel lowLevel = storIOSQLite.lowLevel();
        final Map<ContentValues, PutResult> putResults = new HashMap<ContentValues, PutResult>();
        if (useTransaction) {
            lowLevel.beginTransaction();
        }
        boolean transactionSuccessful = false;
        try {
            for (ContentValues contentValues : contentValuesIterable) {
                final PutResult putResult = putResolver.performPut(storIOSQLite, contentValues);
                putResults.put(contentValues, putResult);
                if (!useTransaction && (putResult.wasInserted() || putResult.wasUpdated())) {
                    lowLevel.notifyAboutChanges(Changes.newInstance(putResult.affectedTables()));
                }
            }
            if (useTransaction) {
                lowLevel.setTransactionSuccessful();
                transactionSuccessful = true;
            }
        } finally {
            if (useTransaction) {
                lowLevel.endTransaction();
                if (transactionSuccessful) {
                    // in most cases it will be 1 table
                    final Set<String> affectedTables = new HashSet<String>(1);
                    for (final ContentValues contentValues : putResults.keySet()) {
                        final PutResult putResult = putResults.get(contentValues);
                        if (putResult.wasInserted() || putResult.wasUpdated()) {
                            affectedTables.addAll(putResult.affectedTables());
                        }
                    }
                    // It'll reduce number of possible deadlock situations
                    if (!affectedTables.isEmpty()) {
                        lowLevel.notifyAboutChanges(Changes.newInstance(affectedTables));
                    }
                }
            }
        }
        return PutResults.newInstance(putResults);
    } catch (Exception exception) {
        throw new StorIOException("Error has occurred during Put operation. contentValues = " + contentValuesIterable, exception);
    }
}
Also used : ContentValues(android.content.ContentValues) StorIOException(com.pushtorefresh.storio.StorIOException) HashMap(java.util.HashMap) StorIOSQLite(com.pushtorefresh.storio.sqlite.StorIOSQLite) StorIOException(com.pushtorefresh.storio.StorIOException) HashSet(java.util.HashSet) WorkerThread(android.support.annotation.WorkerThread) NonNull(android.support.annotation.NonNull)

Example 15 with StorIOException

use of com.pushtorefresh.storio.StorIOException in project storio by pushtorefresh.

the class PreparedPutContentValuesIterableTest method verifyBehaviorInCaseOfExceptionWithoutTransactionBlocking.

@Test
public void verifyBehaviorInCaseOfExceptionWithoutTransactionBlocking() {
    final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class);
    final StorIOSQLite.Internal internal = mock(StorIOSQLite.Internal.class);
    //noinspection unchecked
    final PutResolver<ContentValues> putResolver = mock(PutResolver.class);
    final List<ContentValues> contentValues = singletonList(mock(ContentValues.class));
    when(putResolver.performPut(same(storIOSQLite), any(ContentValues.class))).thenThrow(new IllegalStateException("test exception"));
    try {
        new PreparedPutContentValuesIterable.Builder(storIOSQLite, contentValues).withPutResolver(putResolver).useTransaction(false).prepare().executeAsBlocking();
        failBecauseExceptionWasNotThrown(StorIOException.class);
    } catch (StorIOException expected) {
        IllegalStateException cause = (IllegalStateException) expected.getCause();
        assertThat(cause).hasMessage("test exception");
        // Main check of this test
        verify(internal, never()).endTransaction();
        verify(storIOSQLite).lowLevel();
        verify(putResolver).performPut(same(storIOSQLite), any(ContentValues.class));
        verifyNoMoreInteractions(storIOSQLite, internal, putResolver);
    }
}
Also used : ContentValues(android.content.ContentValues) StorIOException(com.pushtorefresh.storio.StorIOException) StorIOSQLite(com.pushtorefresh.storio.sqlite.StorIOSQLite) Test(org.junit.Test)

Aggregations

StorIOException (com.pushtorefresh.storio.StorIOException)40 StorIOSQLite (com.pushtorefresh.storio.sqlite.StorIOSQLite)24 Test (org.junit.Test)23 TestSubscriber (rx.observers.TestSubscriber)17 NonNull (android.support.annotation.NonNull)15 WorkerThread (android.support.annotation.WorkerThread)15 ContentValues (android.content.ContentValues)10 Cursor (android.database.Cursor)8 Query (com.pushtorefresh.storio.sqlite.queries.Query)6 HashMap (java.util.HashMap)6 StorIOContentResolver (com.pushtorefresh.storio.contentresolver.StorIOContentResolver)5 DeleteQuery (com.pushtorefresh.storio.sqlite.queries.DeleteQuery)4 SimpleImmutableEntry (java.util.AbstractMap.SimpleImmutableEntry)4 Query (com.pushtorefresh.storio.contentresolver.queries.Query)3 HashSet (java.util.HashSet)3 Uri (android.net.Uri)2 CheckResult (android.support.annotation.CheckResult)2 Nullable (android.support.annotation.Nullable)2 ContentResolverTypeMapping (com.pushtorefresh.storio.contentresolver.ContentResolverTypeMapping)2 SQLiteTypeMapping (com.pushtorefresh.storio.sqlite.SQLiteTypeMapping)2