Search in sources :

Example 1 with DataStoreConfiguration

use of com.amplifyframework.datastore.DataStoreConfiguration in project amplify-android by aws-amplify.

the class QueryPredicateTest method setup.

/**
 * Setup the queryPredicateProvider.
 * @throws DataStoreException on failure to build {@link DataStoreConfiguration}
 */
@Before
public void setup() throws DataStoreException {
    expectedPredicate = BlogOwner.NAME.beginsWith(RandomString.string());
    blogSyncExpression = () -> expectedPredicate;
    DataStoreConfiguration dataStoreConfiguration = DataStoreConfiguration.builder().syncExpression(BlogOwner.class, blogSyncExpression).build();
    queryPredicateProvider = new QueryPredicateProvider(() -> dataStoreConfiguration);
}
Also used : DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Before(org.junit.Before)

Example 2 with DataStoreConfiguration

use of com.amplifyframework.datastore.DataStoreConfiguration in project amplify-android by aws-amplify.

the class SubscriptionProcessorTest method setup.

/**
 * Sets up an {@link SubscriptionProcessor} and associated test dependencies.
 * @throws DataStoreException on error building the {@link DataStoreConfiguration}
 */
@Before
public void setup() throws DataStoreException {
    ModelProvider modelProvider = AmplifyModelProvider.getInstance();
    schemaRegistry = SchemaRegistry.instance();
    schemaRegistry.register(modelProvider.modelSchemas());
    this.modelSchemas = sortedModels(modelProvider);
    this.appSync = mock(AppSync.class);
    this.merger = mock(Merger.class);
    DataStoreConfiguration dataStoreConfiguration = DataStoreConfiguration.builder().syncExpression(BlogOwner.class, () -> BlogOwner.NAME.beginsWith("John")).build();
    QueryPredicateProvider queryPredicateProvider = new QueryPredicateProvider(() -> dataStoreConfiguration);
    queryPredicateProvider.resolvePredicates();
    this.subscriptionProcessor = SubscriptionProcessor.builder().appSync(appSync).modelProvider(modelProvider).schemaRegistry(schemaRegistry).merger(merger).queryPredicateProvider(queryPredicateProvider).onFailure(throwable -> {
    }).build();
}
Also used : DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) ModelProvider(com.amplifyframework.core.model.ModelProvider) AmplifyModelProvider(com.amplifyframework.testmodels.commentsblog.AmplifyModelProvider) AppSync(com.amplifyframework.datastore.appsync.AppSync) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Before(org.junit.Before)

Example 3 with DataStoreConfiguration

use of com.amplifyframework.datastore.DataStoreConfiguration in project amplify-android by aws-amplify.

the class SyncStatusTest method syncStatusGetReturnSyncedStatus.

/**
 * Get returns sync status.
 */
@Test
public void syncStatusGetReturnSyncedStatus() {
    final LastSyncMetadata lastSyncMetadata = LastSyncMetadata.baseSyncedAt(BlogOwner.class.getName(), Time.now());
    List<LastSyncMetadata> resultList = new ArrayList<>();
    resultList.add(lastSyncMetadata);
    Consumer<DataStoreException> onObservationError = value -> {
    };
    SqlQueryProcessor mockSqlQueryProcessor = mock(SqlQueryProcessor.class);
    when(mockSqlQueryProcessor.queryOfflineData(eq(LastSyncMetadata.class), any(), any())).thenReturn(resultList);
    DataStoreConfiguration mockDataStoreConfig = mock(DataStoreConfiguration.class);
    when(mockDataStoreConfig.getSyncIntervalInMinutes()).thenReturn(5L);
    SyncStatus subject = new SyncStatus(mockSqlQueryProcessor, mockDataStoreConfig);
    boolean result = subject.get(LastSyncMetadata.class.getName(), onObservationError);
    Assert.assertTrue(result);
}
Also used : LastSyncMetadata(com.amplifyframework.datastore.syncengine.LastSyncMetadata) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) LastSyncMetadata(com.amplifyframework.datastore.syncengine.LastSyncMetadata) ArrayList(java.util.ArrayList) Time(com.amplifyframework.util.Time) DataStoreException(com.amplifyframework.datastore.DataStoreException) Consumer(com.amplifyframework.core.Consumer) List(java.util.List) Assert(org.junit.Assert) Mockito.mock(org.mockito.Mockito.mock) DataStoreException(com.amplifyframework.datastore.DataStoreException) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) ArrayList(java.util.ArrayList) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 4 with DataStoreConfiguration

use of com.amplifyframework.datastore.DataStoreConfiguration in project amplify-android by aws-amplify.

the class SyncStatusTest method syncStatusGetReturnNotSyncedStatus.

/**
 * Get returns false for sync status.
 */
@Test
public void syncStatusGetReturnNotSyncedStatus() {
    final LastSyncMetadata lastSyncMetadata = LastSyncMetadata.baseSyncedAt(BlogOwner.class.getName(), Time.now());
    List<LastSyncMetadata> resultList = new ArrayList<>();
    resultList.add(lastSyncMetadata);
    Consumer<DataStoreException> onObservationError = value -> {
    };
    SqlQueryProcessor mockSqlQueryProcessor = mock(SqlQueryProcessor.class);
    when(mockSqlQueryProcessor.queryOfflineData(eq(LastSyncMetadata.class), any(), any())).thenReturn(resultList);
    DataStoreConfiguration mockDataStoreConfig = mock(DataStoreConfiguration.class);
    when(mockDataStoreConfig.getSyncIntervalInMinutes()).thenReturn(0L);
    SyncStatus subject = new SyncStatus(mockSqlQueryProcessor, mockDataStoreConfig);
    boolean result = subject.get(LastSyncMetadata.class.getName(), onObservationError);
    Assert.assertFalse(result);
}
Also used : LastSyncMetadata(com.amplifyframework.datastore.syncengine.LastSyncMetadata) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) LastSyncMetadata(com.amplifyframework.datastore.syncengine.LastSyncMetadata) ArrayList(java.util.ArrayList) Time(com.amplifyframework.util.Time) DataStoreException(com.amplifyframework.datastore.DataStoreException) Consumer(com.amplifyframework.core.Consumer) List(java.util.List) Assert(org.junit.Assert) Mockito.mock(org.mockito.Mockito.mock) DataStoreException(com.amplifyframework.datastore.DataStoreException) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) ArrayList(java.util.ArrayList) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 5 with DataStoreConfiguration

use of com.amplifyframework.datastore.DataStoreConfiguration in project amplify-android by aws-amplify.

the class SQLiteStorageAdapter method initialize.

/**
 * {@inheritDoc}
 */
@Override
public synchronized void initialize(@NonNull Context context, @NonNull Consumer<List<ModelSchema>> onSuccess, @NonNull Consumer<DataStoreException> onError, @NonNull DataStoreConfiguration dataStoreConfiguration) {
    Objects.requireNonNull(context);
    Objects.requireNonNull(onSuccess);
    Objects.requireNonNull(onError);
    // Create a thread pool large enough to take advantage of parallelization, but small enough to avoid
    // OutOfMemoryError and CursorWindowAllocationException issues.
    this.threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * THREAD_POOL_SIZE_MULTIPLIER);
    this.context = context;
    this.dataStoreConfiguration = dataStoreConfiguration;
    threadPool.submit(() -> {
        try {
            /*
                 * Start with a fresh registry.
                 */
            schemaRegistry.clear();
            /*
                 * Create {@link ModelSchema} objects for the corresponding {@link Model}.
                 * Any exception raised during this when inspecting the Model classes
                 * through reflection will be notified via the `onError` callback.
                 */
            schemaRegistry.register(modelsProvider.modelSchemas(), modelsProvider.customTypeSchemas());
            /*
                 * Create the CREATE TABLE and CREATE INDEX commands for each of the
                 * Models. Instantiate {@link SQLiteStorageHelper} to execute those
                 * create commands.
                 */
            this.sqlCommandFactory = new SQLiteCommandFactory(schemaRegistry, gson);
            CreateSqlCommands createSqlCommands = getCreateCommands(modelsProvider.modelNames());
            sqliteStorageHelper = SQLiteStorageHelper.getInstance(context, databaseName, DATABASE_VERSION, createSqlCommands);
            /*
                 * Create and/or open a database. This also invokes
                 * {@link SQLiteStorageHelper#onCreate(SQLiteDatabase)} which executes the tasks
                 * to create tables and indexes. When the function returns without any exception
                 * being thrown, invoke the `onError` callback.
                 *
                 * Errors are thrown when there is no write permission to the database, no space
                 * left in the database for any write operation and other errors thrown while
                 * creating and opening a database. All errors are passed through the
                 * `onError` callback.
                 *
                 * databaseConnectionHandle represents a connection handle to the database.
                 * All database operations will happen through this handle.
                 */
            databaseConnectionHandle = sqliteStorageHelper.getWritableDatabase();
            /*
                 * Create helper instance that can traverse through model relations.
                 */
            this.sqliteModelTree = new SQLiteModelTree(schemaRegistry, databaseConnectionHandle);
            /*
                 * Create a command processor which runs the actual SQL transactions.
                 */
            this.sqlCommandProcessor = new SQLCommandProcessor(databaseConnectionHandle);
            sqlQueryProcessor = new SqlQueryProcessor(sqlCommandProcessor, sqlCommandFactory, schemaRegistry);
            syncStatus = new SyncStatus(sqlQueryProcessor, dataStoreConfiguration);
            /*
                 * Detect if the version of the models stored in SQLite is different
                 * from the version passed in through {@link ModelProvider#version()}.
                 * Delete the database if there is a version change.
                 */
            toBeDisposed.add(updateModels().subscribe(() -> onSuccess.accept(Immutable.of(new ArrayList<>(schemaRegistry.getModelSchemaMap().values()))), throwable -> onError.accept(new DataStoreException("Error in initializing the SQLiteStorageAdapter", throwable, AmplifyException.TODO_RECOVERY_SUGGESTION))));
        } catch (Exception exception) {
            onError.accept(new DataStoreException("Error in initializing the SQLiteStorageAdapter", exception, "See attached exception"));
        }
    });
}
Also used : ObjectsCompat(androidx.core.util.ObjectsCompat) AmplifyException(com.amplifyframework.AmplifyException) NonNull(androidx.annotation.NonNull) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) ModelProvider(com.amplifyframework.core.model.ModelProvider) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Gson(com.google.gson.Gson) Map(java.util.Map) PublishSubject(io.reactivex.rxjava3.subjects.PublishSubject) QueryOptions(com.amplifyframework.core.model.query.QueryOptions) CustomTypeSchema(com.amplifyframework.core.model.CustomTypeSchema) SerializedModel(com.amplifyframework.core.model.SerializedModel) Immutable(com.amplifyframework.util.Immutable) Set(java.util.Set) Executors(java.util.concurrent.Executors) Logger(com.amplifyframework.logging.Logger) Objects(java.util.Objects) DataStoreException(com.amplifyframework.datastore.DataStoreException) LocalStorageAdapter(com.amplifyframework.datastore.storage.LocalStorageAdapter) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable) Disposable(io.reactivex.rxjava3.disposables.Disposable) Context(android.content.Context) SerializedCustomType(com.amplifyframework.core.model.SerializedCustomType) QueryField(com.amplifyframework.core.model.query.predicate.QueryField) Single(io.reactivex.rxjava3.core.Single) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) SystemModelsProviderFactory(com.amplifyframework.datastore.model.SystemModelsProviderFactory) HashMap(java.util.HashMap) CustomTypeField(com.amplifyframework.core.model.CustomTypeField) ModelField(com.amplifyframework.core.model.ModelField) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) GsonFactory(com.amplifyframework.util.GsonFactory) HashSet(java.util.HashSet) Consumer(com.amplifyframework.core.Consumer) CompositeDisposable(io.reactivex.rxjava3.disposables.CompositeDisposable) ModelSchema(com.amplifyframework.core.model.ModelSchema) Subject(io.reactivex.rxjava3.subjects.Subject) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) ExecutorService(java.util.concurrent.ExecutorService) Cursor(android.database.Cursor) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) Amplify(com.amplifyframework.core.Amplify) CompoundModelProvider(com.amplifyframework.datastore.model.CompoundModelProvider) Iterator(java.util.Iterator) Model(com.amplifyframework.core.model.Model) Completable(io.reactivex.rxjava3.core.Completable) Action(com.amplifyframework.core.Action) Where(com.amplifyframework.core.model.query.Where) ModelAssociation(com.amplifyframework.core.model.ModelAssociation) TimeUnit(java.util.concurrent.TimeUnit) ModelMigrations(com.amplifyframework.datastore.storage.sqlite.migrations.ModelMigrations) VisibleForTesting(androidx.annotation.VisibleForTesting) Collections(java.util.Collections) DataStoreException(com.amplifyframework.datastore.DataStoreException) ArrayList(java.util.ArrayList) AmplifyException(com.amplifyframework.AmplifyException) DataStoreException(com.amplifyframework.datastore.DataStoreException)

Aggregations

DataStoreConfiguration (com.amplifyframework.datastore.DataStoreConfiguration)5 Consumer (com.amplifyframework.core.Consumer)3 DataStoreException (com.amplifyframework.datastore.DataStoreException)3 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 ModelProvider (com.amplifyframework.core.model.ModelProvider)2 LastSyncMetadata (com.amplifyframework.datastore.syncengine.LastSyncMetadata)2 Before (org.junit.Before)2 Context (android.content.Context)1 Cursor (android.database.Cursor)1 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)1 NonNull (androidx.annotation.NonNull)1 VisibleForTesting (androidx.annotation.VisibleForTesting)1 ObjectsCompat (androidx.core.util.ObjectsCompat)1 AmplifyException (com.amplifyframework.AmplifyException)1 Action (com.amplifyframework.core.Action)1 Amplify (com.amplifyframework.core.Amplify)1 Cancelable (com.amplifyframework.core.async.Cancelable)1 CustomTypeField (com.amplifyframework.core.model.CustomTypeField)1