Search in sources :

Example 16 with AmplifyException

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

the class Category method initialize.

/**
 * Initialize the category. This asynchronous call is made only after
 * the category has been successfully configured. Whereas configuration is a short-lived
 * synchronous phase of setup, initialization may require disk/network resources, etc.
 * @param context An Android Context
 * @return A category initialization result
 */
@NonNull
@WorkerThread
public final synchronized CategoryInitializationResult initialize(@NonNull Context context) {
    final Map<String, InitializationResult> pluginInitializationResults = new HashMap<>();
    if (!State.CONFIGURED.equals(state.get())) {
        for (P plugin : getPlugins()) {
            InitializationResult result = InitializationResult.failure(new AmplifyException("Tried to init before category was not configured.", "Call configure() on category, first."));
            pluginInitializationResults.put(plugin.getPluginKey(), result);
        }
    } else {
        state.set(State.CONFIGURING);
        for (P plugin : getPlugins()) {
            InitializationResult result;
            try {
                plugin.initialize(context);
                result = InitializationResult.success();
            } catch (AmplifyException pluginInitializationFailure) {
                result = InitializationResult.failure(pluginInitializationFailure);
            }
            pluginInitializationResults.put(plugin.getPluginKey(), result);
        }
    }
    final CategoryInitializationResult result = CategoryInitializationResult.with(pluginInitializationResults);
    categoryInitializationResult.set(result);
    if (result.isFailure()) {
        state.set(State.INITIALIZATION_FAILED);
    } else {
        state.set(State.INITIALIZED);
    }
    HubChannel hubChannel = HubChannel.forCategoryType(getCategoryType());
    InitializationStatus status = result.isFailure() ? InitializationStatus.FAILED : InitializationStatus.SUCCEEDED;
    Amplify.Hub.publish(hubChannel, HubEvent.create(status, result));
    return result;
}
Also used : InitializationResult(com.amplifyframework.core.InitializationResult) AmplifyException(com.amplifyframework.AmplifyException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) HubChannel(com.amplifyframework.hub.HubChannel) InitializationStatus(com.amplifyframework.core.InitializationStatus) WorkerThread(androidx.annotation.WorkerThread) NonNull(androidx.annotation.NonNull)

Example 17 with AmplifyException

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

the class ModelConverter method extractFieldValue.

private static Object extractFieldValue(String fieldName, Model instance, ModelSchema schema) throws AmplifyException {
    if (instance instanceof SerializedModel) {
        SerializedModel serializedModel = (SerializedModel) instance;
        Map<String, Object> serializedData = serializedModel.getSerializedData();
        return serializedData.get(fieldName);
    }
    try {
        Field privateField = instance.getClass().getDeclaredField(fieldName);
        privateField.setAccessible(true);
        return privateField.get(instance);
    } catch (Exception exception) {
        throw new AmplifyException("An invalid field was provided. " + fieldName + " is not present in " + schema.getName(), exception, "Check if this model schema is a correct representation of the fields in the provided Object");
    }
}
Also used : Field(java.lang.reflect.Field) AmplifyException(com.amplifyframework.AmplifyException) AmplifyException(com.amplifyframework.AmplifyException)

Example 18 with AmplifyException

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

the class AuthComponentConfigureTest method testConfigureExceptionHandling.

/**
 * If {@link AWSMobileClient} emits an error during initialization, the
 * {@link com.amplifyframework.auth.AuthPlugin#configure(JSONObject, Context)} method should wrap that exception
 * in an {@link AuthException} and throw it on its calling thread.
 * @throws AmplifyException the exception expected to be thrown when configuration fails.
 * @throws JSONException has to be declared as part of creating a test JSON object
 */
@Test(expected = AuthException.class)
public void testConfigureExceptionHandling() throws AmplifyException, JSONException {
    JSONObject pluginConfig = new JSONObject().put("TestKey", "TestVal");
    JSONObject json = new JSONObject().put("plugins", new JSONObject().put(PLUGIN_KEY, pluginConfig));
    AuthCategoryConfiguration authConfig = new AuthCategoryConfiguration();
    authConfig.populateFromJSON(json);
    doAnswer(invocation -> {
        Callback<UserStateDetails> callback = invocation.getArgument(2);
        callback.onError(new Exception());
        return null;
    }).when(mobileClient).initialize(any(), any(), any());
    authCategory.configure(authConfig, getApplicationContext());
}
Also used : JSONObject(org.json.JSONObject) AuthCategoryConfiguration(com.amplifyframework.auth.AuthCategoryConfiguration) UserStateDetails(com.amazonaws.mobile.client.UserStateDetails) AmplifyException(com.amplifyframework.AmplifyException) AuthException(com.amplifyframework.auth.AuthException) JSONException(org.json.JSONException) Test(org.junit.Test)

Example 19 with AmplifyException

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

the class TestStorageAdapter method create.

/**
 * Creates an instance of the {@link SynchronousStorageAdapter}, which has been initialized
 * so that it can be used with the given models. The {@link SynchronousStorageAdapter}
 * is backed by an {@link SQLiteStorageAdapter}. The caller of this method
 * should do due diligence to ensure that any resources created by
 * {@link SQLiteStorageAdapter#initialize(Context, Consumer, Consumer)} have been cleaned up.
 * @return An initialized instance of the {@link SynchronousStorageAdapter}
 */
static SynchronousStorageAdapter create(ModelProvider modelProvider) {
    SchemaRegistry schemaRegistry = SchemaRegistry.instance();
    schemaRegistry.clear();
    try {
        schemaRegistry.register(modelProvider.models());
    } catch (AmplifyException modelSchemaLoadingFailure) {
        throw new RuntimeException(modelSchemaLoadingFailure);
    }
    SQLiteStorageAdapter sqLiteStorageAdapter = SQLiteStorageAdapter.forModels(schemaRegistry, modelProvider);
    SynchronousStorageAdapter synchronousStorageAdapter = SynchronousStorageAdapter.delegatingTo(sqLiteStorageAdapter);
    Context context = ApplicationProvider.getApplicationContext();
    try {
        synchronousStorageAdapter.initialize(context);
    } catch (DataStoreException initializationFailure) {
        throw new RuntimeException(initializationFailure);
    }
    return synchronousStorageAdapter;
}
Also used : Context(android.content.Context) DataStoreException(com.amplifyframework.datastore.DataStoreException) AmplifyException(com.amplifyframework.AmplifyException) SynchronousStorageAdapter(com.amplifyframework.datastore.storage.SynchronousStorageAdapter) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry)

Example 20 with AmplifyException

use of com.amplifyframework.AmplifyException 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)

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