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