Search in sources :

Example 1 with AmplifyException

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

the class OrchestratorTest method itemsPlacedInStorageArePublishedToNetwork.

/**
 * When an item is placed into storage, a cascade of
 * things happen which should ultimately result in a mutation call
 * to the API category, with an {@link MutationType} corresponding to the type of
 * modification that was made to the storage.
 * @throws AmplifyException On failure to load model schema into registry
 */
// Casting ? in HubEvent<?> to PendingMutation<? extends Model>
@SuppressWarnings("unchecked")
@Test
public void itemsPlacedInStorageArePublishedToNetwork() throws AmplifyException {
    // Arrange: orchestrator is running
    orchestrator.start().test();
    orchestratorInitObserver.await(10, TimeUnit.SECONDS);
    HubAccumulator accumulator = HubAccumulator.create(HubChannel.DATASTORE, isProcessed(susan), 1).start();
    // Act: Put BlogOwner into storage, and wait for it to complete.
    SynchronousStorageAdapter.delegatingTo(localStorageAdapter).save(susan);
    // Assert that the event is published out to the API
    assertEquals(Collections.singletonList(susan), Observable.fromIterable(accumulator.await(10, TimeUnit.SECONDS)).map(HubEvent::getData).map(data -> (OutboxMutationEvent<BlogOwner>) data).map(OutboxMutationEvent::getElement).map(OutboxMutationEvent.OutboxMutationEventElement::getModel).toList().blockingGet());
    assertTrue(orchestrator.stop().blockingAwait(5, TimeUnit.SECONDS));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AmplifyException(com.amplifyframework.AmplifyException) MutationType(com.amplifyframework.api.graphql.MutationType) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) ModelProvider(com.amplifyframework.core.model.ModelProvider) DataStoreChannelEventName(com.amplifyframework.datastore.DataStoreChannelEventName) RunWith(org.junit.runner.RunWith) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) SynchronousStorageAdapter(com.amplifyframework.datastore.storage.SynchronousStorageAdapter) Observable(io.reactivex.rxjava3.core.Observable) TestHubEventFilters.isProcessed(com.amplifyframework.datastore.syncengine.TestHubEventFilters.isProcessed) ModelMetadata(com.amplifyframework.datastore.appsync.ModelMetadata) HubEvent(com.amplifyframework.hub.HubEvent) Before(org.junit.Before) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) Amplify(com.amplifyframework.core.Amplify) HubChannel(com.amplifyframework.hub.HubChannel) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) AppSyncClient(com.amplifyframework.datastore.appsync.AppSyncClient) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Completable(io.reactivex.rxjava3.core.Completable) Mockito.times(org.mockito.Mockito.times) Logger(com.amplifyframework.logging.Logger) Mockito.verify(org.mockito.Mockito.verify) RobolectricTestRunner(org.robolectric.RobolectricTestRunner) TimeUnit(java.util.concurrent.TimeUnit) GraphQLBehavior(com.amplifyframework.api.graphql.GraphQLBehavior) InMemoryStorageAdapter(com.amplifyframework.datastore.storage.InMemoryStorageAdapter) Temporal(com.amplifyframework.core.model.temporal.Temporal) ShadowLog(org.robolectric.shadows.ShadowLog) ApiMocking(com.amplifyframework.testutils.mocks.ApiMocking) Collections(java.util.Collections) SimpleModelProvider(com.amplifyframework.datastore.model.SimpleModelProvider) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) HubEvent(com.amplifyframework.hub.HubEvent) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) Test(org.junit.Test)

Example 2 with AmplifyException

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

the class InMemoryStorageAdapter method delete.

// item.getClass() -> Class<?>, but type is T. So cast as Class<T> is OK.
@SuppressWarnings("unchecked")
@Override
public <T extends Model> void delete(@NonNull final T item, @NonNull final StorageItemChange.Initiator initiator, @NonNull final QueryPredicate predicate, @NonNull final Consumer<StorageItemChange<T>> onSuccess, @NonNull final Consumer<DataStoreException> onError) {
    final int index = indexOf(item);
    if (index < 0) {
        onError.accept(new DataStoreException("This item was not found in the datastore: " + item.toString(), "Use save() function to create models to store."));
        return;
    }
    Model savedItem = items.remove(index);
    final ModelSchema schema;
    final SerializedModel patchItem;
    try {
        schema = ModelSchema.fromModelClass(item.getClass());
        patchItem = SerializedModel.create(savedItem, schema);
    } catch (AmplifyException schemaBuildFailure) {
        onError.accept(new DataStoreException("Failed to build model schema.", schemaBuildFailure, "Verify your model."));
        return;
    }
    if (!predicate.evaluate(savedItem)) {
        onError.accept(new DataStoreException("Conditional check failed.", "Verify that there is a saved model that matches the provided predicate."));
        return;
    }
    StorageItemChange<T> deletion = StorageItemChange.<T>builder().item((T) savedItem).patchItem(patchItem).modelSchema(schema).type(StorageItemChange.Type.DELETE).predicate(predicate).initiator(initiator).build();
    itemChangeStream.onNext(deletion);
    onSuccess.accept(deletion);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) DataStoreException(com.amplifyframework.datastore.DataStoreException) AmplifyException(com.amplifyframework.AmplifyException) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) SerializedModel(com.amplifyframework.core.model.SerializedModel)

Example 3 with AmplifyException

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

the class InMemoryStorageAdapter method save.

@Override
public <T extends Model> void save(@NonNull final T item, @NonNull final StorageItemChange.Initiator initiator, @NonNull final QueryPredicate predicate, @NonNull final Consumer<StorageItemChange<T>> onSuccess, @NonNull final Consumer<DataStoreException> onError) {
    StorageItemChange.Type type = StorageItemChange.Type.CREATE;
    final int index = indexOf(item);
    Model savedItem = null;
    if (index > -1) {
        // There is an existing record with that ID; this is an update.
        type = StorageItemChange.Type.UPDATE;
        savedItem = items.get(index);
        if (!predicate.evaluate(savedItem)) {
            onError.accept(new DataStoreException("Conditional check failed.", "Verify that there is a saved model that matches the provided predicate."));
            return;
        } else {
            items.remove(index);
        }
    }
    final ModelSchema schema;
    final SerializedModel patchItem;
    try {
        schema = ModelSchema.fromModelClass(item.getClass());
        patchItem = SerializedModel.difference(item, savedItem, schema);
    } catch (AmplifyException schemaBuildFailure) {
        onError.accept(new DataStoreException("Failed to build model schema.", schemaBuildFailure, "Verify your model."));
        return;
    }
    items.add(item);
    StorageItemChange<T> change = StorageItemChange.<T>builder().item(item).patchItem(patchItem).modelSchema(schema).type(type).predicate(predicate).initiator(initiator).build();
    itemChangeStream.onNext(change);
    onSuccess.accept(change);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) DataStoreException(com.amplifyframework.datastore.DataStoreException) AmplifyException(com.amplifyframework.AmplifyException) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) SerializedModel(com.amplifyframework.core.model.SerializedModel)

Example 4 with AmplifyException

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

the class ObserveQueryExecutorTest method observeQueryReturnsRecordsBasedOnMaxTime.

/**
 * observe Query Returns batched Records Based On MaxTime.
 * @throws InterruptedException InterruptedException
 * @throws DataStoreException DataStoreException
 */
@Test
public void observeQueryReturnsRecordsBasedOnMaxTime() throws InterruptedException, DataStoreException {
    CountDownLatch latch = new CountDownLatch(1);
    CountDownLatch changeLatch = new CountDownLatch(1);
    AtomicInteger count = new AtomicInteger();
    BlogOwner blogOwner = BlogOwner.builder().name("Alan Turing").build();
    List<BlogOwner> datastoreResultList = new ArrayList<>();
    int maxRecords = 50;
    datastoreResultList.add(blogOwner);
    Consumer<Cancelable> observationStarted = NoOpConsumer.create();
    SyncStatus mockSyncStatus = mock(SyncStatus.class);
    when(mockSyncStatus.get(any(), any())).thenReturn(false);
    Subject<StorageItemChange<? extends Model>> subject = PublishSubject.<StorageItemChange<? extends Model>>create().toSerialized();
    Consumer<DataStoreQuerySnapshot<BlogOwner>> onQuerySnapshot = value -> {
        if (count.get() == 0) {
            Assert.assertTrue(value.getItems().contains(blogOwner));
            latch.countDown();
        } else if (count.get() == 1) {
            Assert.assertEquals(6, value.getItems().size());
            changeLatch.countDown();
        }
        count.getAndIncrement();
    };
    Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
    Action onObservationComplete = () -> {
    };
    SqlQueryProcessor mockSqlQueryProcessor = mock(SqlQueryProcessor.class);
    when(mockSqlQueryProcessor.queryOfflineData(eq(BlogOwner.class), any(), any())).thenReturn(datastoreResultList);
    when(mockSqlQueryProcessor.modelExists(any(), any())).thenReturn(true);
    ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 5);
    ObserveQueryExecutor<BlogOwner> observeQueryExecutor = new ObserveQueryExecutor<>(subject, mockSqlQueryProcessor, threadPool, mockSyncStatus, new ModelSorter<>(), maxRecords, 1);
    observeQueryExecutor.observeQuery(BlogOwner.class, new ObserveQueryOptions(), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
    Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
    for (int i = 0; i < 5; i++) {
        BlogOwner itemChange = BlogOwner.builder().name("Alan Turing" + i).build();
        try {
            subject.onNext(StorageItemChange.<BlogOwner>builder().changeId(UUID.randomUUID().toString()).initiator(StorageItemChange.Initiator.SYNC_ENGINE).item(itemChange).patchItem(SerializedModel.create(itemChange, ModelSchema.fromModelClass(BlogOwner.class))).modelSchema(ModelSchema.fromModelClass(BlogOwner.class)).predicate(QueryPredicates.all()).type(StorageItemChange.Type.UPDATE).build());
        } catch (AmplifyException exception) {
            exception.printStackTrace();
        }
    }
    Assert.assertTrue(changeLatch.await(5, TimeUnit.SECONDS));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Arrays(java.util.Arrays) AmplifyException(com.amplifyframework.AmplifyException) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Consumer(com.amplifyframework.core.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PublishSubject(io.reactivex.rxjava3.subjects.PublishSubject) ModelSchema(com.amplifyframework.core.model.ModelSchema) Subject(io.reactivex.rxjava3.subjects.Subject) NoOpConsumer(com.amplifyframework.core.NoOpConsumer) PostStatus(com.amplifyframework.testmodels.commentsblog.PostStatus) ExecutorService(java.util.concurrent.ExecutorService) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) SerializedModel(com.amplifyframework.core.model.SerializedModel) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Model(com.amplifyframework.core.model.Model) Test(org.junit.Test) Action(com.amplifyframework.core.Action) UUID(java.util.UUID) Mockito.when(org.mockito.Mockito.when) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) DataStoreException(com.amplifyframework.datastore.DataStoreException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) Assert(org.junit.Assert) Comparator(java.util.Comparator) NoOpAction(com.amplifyframework.core.NoOpAction) Post(com.amplifyframework.testmodels.commentsblog.Post) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) Action(com.amplifyframework.core.Action) NoOpAction(com.amplifyframework.core.NoOpAction) AmplifyException(com.amplifyframework.AmplifyException) ArrayList(java.util.ArrayList) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Cancelable(com.amplifyframework.core.async.Cancelable) DataStoreException(com.amplifyframework.datastore.DataStoreException) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) CountDownLatch(java.util.concurrent.CountDownLatch) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) ExecutorService(java.util.concurrent.ExecutorService) Test(org.junit.Test)

Example 5 with AmplifyException

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

the class ObserveQueryExecutorTest method observeQueryReturnsSortedListOfTotalItems.

/**
 * observe Query Returns Sorted List Of Total Items.
 * @throws InterruptedException InterruptedException
 * @throws DataStoreException DataStoreException
 */
@Test
public void observeQueryReturnsSortedListOfTotalItems() throws InterruptedException, DataStoreException {
    CountDownLatch latch = new CountDownLatch(1);
    CountDownLatch changeLatch = new CountDownLatch(1);
    AtomicInteger count = new AtomicInteger();
    List<String> names = Arrays.asList("John", "Jacob", "Joe", "Bob", "Bobby", "Bobb", "Dan", "Dany", "Daniel");
    List<String> weas = Arrays.asList("pon", "lth", "ver", "kly", "ken", "sel", "ner", "rer", "ned");
    List<BlogOwner> owners = new ArrayList<>();
    for (int i = 0; i < names.size() / 2; i++) {
        BlogOwner owner = BlogOwner.builder().name(names.get(i)).wea(weas.get(i)).build();
        owners.add(owner);
    }
    int maxRecords = 50;
    Consumer<Cancelable> observationStarted = NoOpConsumer.create();
    SyncStatus mockSyncStatus = mock(SyncStatus.class);
    when(mockSyncStatus.get(any(), any())).thenReturn(false);
    Subject<StorageItemChange<? extends Model>> subject = PublishSubject.<StorageItemChange<? extends Model>>create().toSerialized();
    Consumer<DataStoreQuerySnapshot<BlogOwner>> onQuerySnapshot = value -> {
        if (count.get() == 0) {
            Assert.assertTrue(value.getItems().contains(owners.get(0)));
            latch.countDown();
        } else if (count.get() == 1) {
            List<BlogOwner> sorted = new ArrayList<>(owners);
            Collections.sort(sorted, Comparator.comparing(BlogOwner::getName).reversed().thenComparing(BlogOwner::getWea));
            assertEquals(sorted, value.getItems());
            Assert.assertEquals(8, value.getItems().size());
            changeLatch.countDown();
        }
        count.getAndIncrement();
    };
    Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
    Action onObservationComplete = () -> {
    };
    SqlQueryProcessor mockSqlQueryProcessor = mock(SqlQueryProcessor.class);
    when(mockSqlQueryProcessor.queryOfflineData(eq(BlogOwner.class), any(), any())).thenReturn(owners);
    when(mockSqlQueryProcessor.modelExists(any(), any())).thenReturn(true);
    ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 5);
    ObserveQueryExecutor<BlogOwner> observeQueryExecutor = new ObserveQueryExecutor<>(subject, mockSqlQueryProcessor, threadPool, mockSyncStatus, new ModelSorter<>(), maxRecords, 1);
    List<QuerySortBy> sortBy = new ArrayList<>();
    sortBy.add(BlogOwner.NAME.descending());
    sortBy.add(BlogOwner.WEA.ascending());
    observeQueryExecutor.observeQuery(BlogOwner.class, new ObserveQueryOptions(null, sortBy), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
    Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
    for (int i = (names.size() / 2) + 1; i < names.size(); i++) {
        BlogOwner itemChange = BlogOwner.builder().name(names.get(i)).wea(weas.get(i)).build();
        owners.add(itemChange);
        try {
            subject.onNext(StorageItemChange.<BlogOwner>builder().changeId(UUID.randomUUID().toString()).initiator(StorageItemChange.Initiator.SYNC_ENGINE).item(itemChange).patchItem(SerializedModel.create(itemChange, ModelSchema.fromModelClass(BlogOwner.class))).modelSchema(ModelSchema.fromModelClass(BlogOwner.class)).predicate(QueryPredicates.all()).type(StorageItemChange.Type.CREATE).build());
        } catch (AmplifyException exception) {
            exception.printStackTrace();
        }
    }
    Assert.assertTrue(changeLatch.await(7, TimeUnit.SECONDS));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Arrays(java.util.Arrays) AmplifyException(com.amplifyframework.AmplifyException) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Consumer(com.amplifyframework.core.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PublishSubject(io.reactivex.rxjava3.subjects.PublishSubject) ModelSchema(com.amplifyframework.core.model.ModelSchema) Subject(io.reactivex.rxjava3.subjects.Subject) NoOpConsumer(com.amplifyframework.core.NoOpConsumer) PostStatus(com.amplifyframework.testmodels.commentsblog.PostStatus) ExecutorService(java.util.concurrent.ExecutorService) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) SerializedModel(com.amplifyframework.core.model.SerializedModel) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Model(com.amplifyframework.core.model.Model) Test(org.junit.Test) Action(com.amplifyframework.core.Action) UUID(java.util.UUID) Mockito.when(org.mockito.Mockito.when) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) DataStoreException(com.amplifyframework.datastore.DataStoreException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) Assert(org.junit.Assert) Comparator(java.util.Comparator) NoOpAction(com.amplifyframework.core.NoOpAction) Post(com.amplifyframework.testmodels.commentsblog.Post) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) Action(com.amplifyframework.core.Action) NoOpAction(com.amplifyframework.core.NoOpAction) AmplifyException(com.amplifyframework.AmplifyException) ArrayList(java.util.ArrayList) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Cancelable(com.amplifyframework.core.async.Cancelable) DataStoreException(com.amplifyframework.datastore.DataStoreException) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) CountDownLatch(java.util.concurrent.CountDownLatch) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) ExecutorService(java.util.concurrent.ExecutorService) Test(org.junit.Test)

Aggregations

AmplifyException (com.amplifyframework.AmplifyException)34 DataStoreException (com.amplifyframework.datastore.DataStoreException)14 Model (com.amplifyframework.core.model.Model)10 ModelSchema (com.amplifyframework.core.model.ModelSchema)10 SerializedModel (com.amplifyframework.core.model.SerializedModel)10 HashMap (java.util.HashMap)9 Test (org.junit.Test)9 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)8 Collections (java.util.Collections)7 TimeUnit (java.util.concurrent.TimeUnit)7 Assert.assertEquals (org.junit.Assert.assertEquals)7 Mockito.mock (org.mockito.Mockito.mock)7 DataStoreConfiguration (com.amplifyframework.datastore.DataStoreConfiguration)6 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)6 JSONException (org.json.JSONException)6 StorageItemChange (com.amplifyframework.datastore.storage.StorageItemChange)5 Post (com.amplifyframework.testmodels.commentsblog.Post)5 ArrayList (java.util.ArrayList)5 JSONObject (org.json.JSONObject)5 Context (android.content.Context)4