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();
}
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));
});
}
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();
}
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);
}
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();
}
Aggregations