Search in sources :

Example 1 with ModelProvider

use of com.amplifyframework.core.model.ModelProvider 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 2 with ModelProvider

use of com.amplifyframework.core.model.ModelProvider in project amplify-android by aws-amplify.

the class SyncProcessor method hydrate.

/**
 * The task of hydrating the DataStore either succeeds (with no return value),
 * or it fails, with an explanation.
 * @return An Rx {@link Completable} which can be used to perform the operation.
 */
Completable hydrate() {
    final List<Completable> hydrationTasks = new ArrayList<>();
    List<ModelSchema> modelSchemas = new ArrayList<>(modelProvider.modelSchemas().values());
    // And sort them all, according to their model's topological order,
    // So that when we save them, the references will exist.
    TopologicalOrdering ordering = TopologicalOrdering.forRegisteredModels(schemaRegistry, modelProvider);
    Collections.sort(modelSchemas, ordering::compare);
    for (ModelSchema schema : modelSchemas) {
        hydrationTasks.add(createHydrationTask(schema));
    }
    return Completable.concat(hydrationTasks).doOnSubscribe(ignore -> {
        // This is where we trigger the syncQueriesStarted event since
        // doOnSubscribe means that all upstream hydration tasks
        // have started.
        Amplify.Hub.publish(HubChannel.DATASTORE, HubEvent.create(DataStoreChannelEventName.SYNC_QUERIES_STARTED, new SyncQueriesStartedEvent(modelNames)));
    }).doOnComplete(() -> {
        // When the Completable completes, then emit syncQueriesReady.
        Amplify.Hub.publish(HubChannel.DATASTORE, HubEvent.create(DataStoreChannelEventName.SYNC_QUERIES_READY));
    });
}
Also used : DataStoreConfigurationProvider(com.amplifyframework.datastore.DataStoreConfigurationProvider) Single(io.reactivex.rxjava3.core.Single) DataStoreErrorHandler(com.amplifyframework.datastore.DataStoreErrorHandler) BehaviorProcessor(io.reactivex.rxjava3.processors.BehaviorProcessor) NonNull(androidx.annotation.NonNull) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) ModelProvider(com.amplifyframework.core.model.ModelProvider) DataStoreChannelEventName(com.amplifyframework.datastore.DataStoreChannelEventName) AppSync(com.amplifyframework.datastore.appsync.AppSync) SyncQueriesStartedEvent(com.amplifyframework.datastore.events.SyncQueriesStartedEvent) AtomicReference(java.util.concurrent.atomic.AtomicReference) ApiException(com.amplifyframework.api.ApiException) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Time(com.amplifyframework.util.Time) Schedulers(io.reactivex.rxjava3.schedulers.Schedulers) Consumer(com.amplifyframework.core.Consumer) ModelSchema(com.amplifyframework.core.model.ModelSchema) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) HubEvent(com.amplifyframework.hub.HubEvent) Amplify(com.amplifyframework.core.Amplify) Flowable(io.reactivex.rxjava3.core.Flowable) HubChannel(com.amplifyframework.hub.HubChannel) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) Completable(io.reactivex.rxjava3.core.Completable) Logger(com.amplifyframework.logging.Logger) Objects(java.util.Objects) DataStoreException(com.amplifyframework.datastore.DataStoreException) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) AmplifyDisposables(com.amplifyframework.datastore.AmplifyDisposables) ForEach(com.amplifyframework.util.ForEach) Collections(java.util.Collections) ModelSchema(com.amplifyframework.core.model.ModelSchema) Completable(io.reactivex.rxjava3.core.Completable) ArrayList(java.util.ArrayList) SyncQueriesStartedEvent(com.amplifyframework.datastore.events.SyncQueriesStartedEvent)

Example 3 with ModelProvider

use of com.amplifyframework.core.model.ModelProvider in project amplify-android by aws-amplify.

the class SyncProcessorTest method syncAndExpect.

private void syncAndExpect(int numPages, int maxSyncRecords) throws AmplifyException, InterruptedException {
    initSyncProcessor(maxSyncRecords);
    // Arrange a subscription to the storage adapter. We're going to watch for changes.
    // We expect to see content here as a result of the SyncProcessor applying updates.
    final TestObserver<StorageItemChange<? extends Model>> adapterObserver = storageAdapter.observe().test();
    // Arrange: return some responses for the sync() call on the RemoteModelState
    AppSyncMocking.SyncConfigurator configurator = AppSyncMocking.sync(appSync);
    List<ModelWithMetadata<BlogOwner>> expectedResponseItems = new ArrayList<>();
    String token = null;
    for (int pageIndex = 0; pageIndex < numPages; pageIndex++) {
        String nextToken = pageIndex < numPages - 1 ? RandomString.string() : null;
        ModelWithMetadata<BlogOwner> randomBlogOwner = randomBlogOwnerWithMetadata();
        configurator.mockSuccessResponse(BlogOwner.class, token, nextToken, randomBlogOwner);
        if (expectedResponseItems.size() < maxSyncRecords) {
            expectedResponseItems.add(randomBlogOwner);
        }
        token = nextToken;
    }
    // Act: Call hydrate, and await its completion - assert it completed without error
    TestObserver<ModelWithMetadata<? extends Model>> hydrationObserver = TestObserver.create();
    syncProcessor.hydrate().subscribe(hydrationObserver);
    // Wait 2 seconds, or 1 second per 100 pages, whichever is greater
    long timeoutMs = Math.max(OP_TIMEOUT_MS, TimeUnit.SECONDS.toMillis(numPages / 100));
    assertTrue(hydrationObserver.await(timeoutMs, TimeUnit.MILLISECONDS));
    hydrationObserver.assertNoErrors();
    hydrationObserver.assertComplete();
    // Since hydrate() completed, the storage adapter observer should see some values.
    // There should be a total of four changes on storage adapter
    // A model and a metadata save for each of the two BlogOwner-type items
    // Additionally, there should be 4 last sync time records, one for each of the
    // models managed by the system.
    adapterObserver.awaitCount(expectedResponseItems.size() * 2 + 4);
    // Validate the changes emitted from the storage adapter's observe().
    assertEquals(// Expect items as described above.
    Observable.fromIterable(expectedResponseItems).flatMap(modelWithMutation -> Observable.fromArray(modelWithMutation.getModel(), modelWithMutation.getSyncMetadata())).toSortedList(SortByModelId::compare).blockingGet(), // Actually...
    Observable.fromIterable(adapterObserver.values()).map(StorageItemChange::item).filter(item -> !LastSyncMetadata.class.isAssignableFrom(item.getClass())).toSortedList(SortByModelId::compare).blockingGet());
    // Lastly: validate the current contents of the storage adapter.
    // There should be 2 BlogOwners, and 2 MetaData records.
    List<? extends Model> itemsInStorage = storageAdapter.query(modelProvider);
    assertEquals(itemsInStorage.toString(), expectedResponseItems.size() * 2 + modelProvider.models().size(), itemsInStorage.size());
    assertEquals(// Expect the 4 items for the bloggers (2 models and their metadata)
    Observable.fromIterable(expectedResponseItems).flatMap(blogger -> Observable.fromArray(blogger.getModel(), blogger.getSyncMetadata())).toList().map(HashSet::new).blockingGet(), Observable.fromIterable(storageAdapter.query(modelProvider)).filter(item -> !LastSyncMetadata.class.isAssignableFrom(item.getClass())).toList().map(HashSet::new).blockingGet());
    adapterObserver.dispose();
    hydrationObserver.dispose();
}
Also used : Arrays(java.util.Arrays) AmplifyException(com.amplifyframework.AmplifyException) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) ModelProvider(com.amplifyframework.core.model.ModelProvider) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) Range(android.util.Range) Random(java.util.Random) Timer(java.util.Timer) SyncQueriesStartedEvent(com.amplifyframework.datastore.events.SyncQueriesStartedEvent) SynchronousStorageAdapter(com.amplifyframework.datastore.storage.SynchronousStorageAdapter) Time(com.amplifyframework.util.Time) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) DRUM_POST(com.amplifyframework.datastore.appsync.TestModelWithMetadataInstances.DRUM_POST) TimerTask(java.util.TimerTask) BLOGGER_JAMESON(com.amplifyframework.datastore.appsync.TestModelWithMetadataInstances.BLOGGER_JAMESON) HubEvent(com.amplifyframework.hub.HubEvent) HubChannel(com.amplifyframework.hub.HubChannel) UUID(java.util.UUID) RobolectricTestRunner(org.robolectric.RobolectricTestRunner) DataStoreException(com.amplifyframework.datastore.DataStoreException) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) RandomString(com.amplifyframework.testutils.random.RandomString) ForEach(com.amplifyframework.util.ForEach) HubEventFilter(com.amplifyframework.hub.HubEventFilter) Mockito.any(org.mockito.Mockito.any) Mockito.mock(org.mockito.Mockito.mock) DataStoreConfigurationProvider(com.amplifyframework.datastore.DataStoreConfigurationProvider) Single(io.reactivex.rxjava3.core.Single) AppSyncMocking(com.amplifyframework.datastore.appsync.AppSyncMocking) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) DataStoreChannelEventName(com.amplifyframework.datastore.DataStoreChannelEventName) RunWith(org.junit.runner.RunWith) AppSync(com.amplifyframework.datastore.appsync.AppSync) SystemModelsProviderFactory(com.amplifyframework.datastore.model.SystemModelsProviderFactory) BLOGGER_ISLA(com.amplifyframework.datastore.appsync.TestModelWithMetadataInstances.BLOGGER_ISLA) Mockito.spy(org.mockito.Mockito.spy) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) HashSet(java.util.HashSet) ArgumentCaptor(org.mockito.ArgumentCaptor) TestObserver(io.reactivex.rxjava3.observers.TestObserver) Observable(io.reactivex.rxjava3.core.Observable) ModelSchema(com.amplifyframework.core.model.ModelSchema) ModelMetadata(com.amplifyframework.datastore.appsync.ModelMetadata) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) LinkedHashSet(java.util.LinkedHashSet) Before(org.junit.Before) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Model(com.amplifyframework.core.model.Model) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Completable(io.reactivex.rxjava3.core.Completable) Mockito.times(org.mockito.Mockito.times) DELETED_DRUM_POST(com.amplifyframework.datastore.appsync.TestModelWithMetadataInstances.DELETED_DRUM_POST) Mockito.when(org.mockito.Mockito.when) ModelSyncedEvent(com.amplifyframework.datastore.events.ModelSyncedEvent) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) InMemoryStorageAdapter(com.amplifyframework.datastore.storage.InMemoryStorageAdapter) Assert.assertNull(org.junit.Assert.assertNull) Temporal(com.amplifyframework.core.model.temporal.Temporal) AmplifyModelProvider(com.amplifyframework.testmodels.commentsblog.AmplifyModelProvider) Post(com.amplifyframework.testmodels.commentsblog.Post) SimpleModelProvider(com.amplifyframework.datastore.model.SimpleModelProvider) Assert.assertEquals(org.junit.Assert.assertEquals) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) ArrayList(java.util.ArrayList) RandomString(com.amplifyframework.testutils.random.RandomString) Model(com.amplifyframework.core.model.Model) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) AppSyncMocking(com.amplifyframework.datastore.appsync.AppSyncMocking) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 4 with ModelProvider

use of com.amplifyframework.core.model.ModelProvider in project amplify-android by aws-amplify.

the class OrchestratorTest method setup.

/**
 * Setup mocks and other common elements.
 * @throws AmplifyException Not expected.
 */
@SuppressWarnings("unchecked")
@Before
public void setup() throws AmplifyException {
    ShadowLog.stream = System.out;
    // Arrange: create a BlogOwner
    susan = BlogOwner.builder().name("Susan Quimby").build();
    // SYNC_QUERIES_READY indicates that the sync queries have completed.
    orchestratorInitObserver = HubAccumulator.create(HubChannel.DATASTORE, DataStoreChannelEventName.SYNC_QUERIES_READY, 1).start();
    ModelMetadata metadata = new ModelMetadata(susan.getId(), false, 1, Temporal.Timestamp.now());
    ModelWithMetadata<BlogOwner> modelWithMetadata = new ModelWithMetadata<>(susan, metadata);
    // Mock behaviors from for the API category
    mockApi = mock(GraphQLBehavior.class);
    ApiMocking.mockSubscriptionStart(mockApi);
    ApiMocking.mockSuccessfulMutation(mockApi, susan.getId(), modelWithMetadata);
    ApiMocking.mockSuccessfulQuery(mockApi, modelWithMetadata);
    AppSyncClient appSync = AppSyncClient.via(mockApi);
    localStorageAdapter = InMemoryStorageAdapter.create();
    ModelProvider modelProvider = SimpleModelProvider.withRandomVersion(BlogOwner.class);
    SchemaRegistry schemaRegistry = SchemaRegistry.instance();
    schemaRegistry.clear();
    schemaRegistry.register(modelProvider.models());
    orchestrator = new Orchestrator(modelProvider, schemaRegistry, localStorageAdapter, appSync, DataStoreConfiguration::defaults, () -> Orchestrator.State.SYNC_VIA_API, true);
}
Also used : GraphQLBehavior(com.amplifyframework.api.graphql.GraphQLBehavior) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) AppSyncClient(com.amplifyframework.datastore.appsync.AppSyncClient) ModelProvider(com.amplifyframework.core.model.ModelProvider) SimpleModelProvider(com.amplifyframework.datastore.model.SimpleModelProvider) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) ModelMetadata(com.amplifyframework.datastore.appsync.ModelMetadata) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Before(org.junit.Before)

Example 5 with ModelProvider

use of com.amplifyframework.core.model.ModelProvider in project amplify-android by aws-amplify.

the class SQLCommandProcessorTest method setup.

/**
 * Sets up model registry and in-memory database.
 * @throws AmplifyException if model fails to register.
 */
@Before
public void setup() throws AmplifyException {
    ModelProvider modelProvider = AmplifyModelProvider.getInstance();
    schemaRegistry = SchemaRegistry.instance();
    schemaRegistry.register(modelProvider.models());
    sqlCommandFactory = new SQLiteCommandFactory(schemaRegistry, GsonFactory.instance());
    sqliteDatabase = createDatabase(modelProvider, schemaRegistry);
    sqlCommandProcessor = new SQLCommandProcessor(sqliteDatabase);
    gson = GsonFactory.instance();
}
Also used : ModelProvider(com.amplifyframework.core.model.ModelProvider) AmplifyModelProvider(com.amplifyframework.testmodels.commentsblog.AmplifyModelProvider) Before(org.junit.Before)

Aggregations

ModelProvider (com.amplifyframework.core.model.ModelProvider)11 ModelSchema (com.amplifyframework.core.model.ModelSchema)5 Before (org.junit.Before)5 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)4 DataStoreException (com.amplifyframework.datastore.DataStoreException)4 NonNull (androidx.annotation.NonNull)3 Model (com.amplifyframework.core.model.Model)3 DataStoreConfiguration (com.amplifyframework.datastore.DataStoreConfiguration)3 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)3 SimpleModelProvider (com.amplifyframework.datastore.model.SimpleModelProvider)3 AmplifyModelProvider (com.amplifyframework.testmodels.commentsblog.AmplifyModelProvider)3 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)3 Completable (io.reactivex.rxjava3.core.Completable)3 Single (io.reactivex.rxjava3.core.Single)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Test (org.junit.Test)3 AmplifyException (com.amplifyframework.AmplifyException)2 GraphQLRequest (com.amplifyframework.api.graphql.GraphQLRequest)2 PaginatedResult (com.amplifyframework.api.graphql.PaginatedResult)2