use of com.amplifyframework.AmplifyException in project amplify-android by aws-amplify.
the class MultiAuthSyncEngineInstrumentationTest method configure.
/**
* Method used to configure each scenario.
* @param modelType The model type.
* @param signInToCognito Does the test scenario require the user to be logged in with user pools.
* @param signInWithOidc Does the test scenario require the user to be logged in with an OIDC provider.
* @param expectedAuthType The auth type that should succeed for the test.
* @throws AmplifyException No expected.
* @throws IOException Not expected.
*/
private void configure(Class<? extends Model> modelType, boolean signInToCognito, boolean signInWithOidc, AuthorizationType expectedAuthType) throws AmplifyException, IOException {
Amplify.addPlugin(new AndroidLoggingPlugin(LogLevel.VERBOSE));
String tag = modelType.getSimpleName();
MultiAuthTestModelProvider modelProvider = MultiAuthTestModelProvider.getInstance(Collections.singletonList(modelType));
SchemaRegistry schemaRegistry = SchemaRegistry.instance();
ModelSchema modelSchema = ModelSchema.fromModelClass(modelType);
schemaRegistry.register(modelType.getSimpleName(), modelSchema);
StrictMode.enable();
Context context = getApplicationContext();
@RawRes int configResourceId = Resources.getRawResourceId(context, "amplifyconfiguration");
AmplifyConfiguration amplifyConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId);
readCredsFromConfig(context);
// Setup an auth plugin
CategoryConfiguration authCategoryConfiguration = amplifyConfiguration.forCategoryType(CategoryType.AUTH);
// Turn off persistence so the mobile client's state for one test does not interfere with the others.
try {
authCategoryConfiguration.getPluginConfig("awsCognitoAuthPlugin").getJSONObject("Auth").getJSONObject("Default").put("Persistence", false);
} catch (JSONException exception) {
exception.printStackTrace();
fail();
return;
}
AuthCategory authCategory = new AuthCategory();
AWSCognitoAuthPlugin authPlugin = new AWSCognitoAuthPlugin();
authCategory.addPlugin(authPlugin);
authCategory.configure(authCategoryConfiguration, context);
auth = SynchronousAuth.delegatingTo(authCategory);
if (signInToCognito) {
Log.v(tag, "Test requires signIn.");
AuthSignInResult authSignInResult = auth.signIn(cognitoUser, cognitoPassword);
if (!authSignInResult.isSignInComplete()) {
fail("Unable to complete initial sign-in");
}
}
if (signInWithOidc) {
oidcLogin();
if (token.get() == null) {
fail("Unable to autenticate with OIDC provider");
}
}
// Setup an API
DefaultCognitoUserPoolsAuthProvider cognitoProvider = new DefaultCognitoUserPoolsAuthProvider(authPlugin.getEscapeHatch());
CategoryConfiguration apiCategoryConfiguration = amplifyConfiguration.forCategoryType(CategoryType.API);
ApiAuthProviders apiAuthProviders = ApiAuthProviders.builder().cognitoUserPoolsAuthProvider(cognitoProvider).awsCredentialsProvider(authPlugin.getEscapeHatch()).oidcAuthProvider(token::get).build();
ApiCategory apiCategory = new ApiCategory();
requestInterceptor = new HttpRequestInterceptor(expectedAuthType);
apiCategory.addPlugin(AWSApiPlugin.builder().configureClient("DataStoreIntegTestsApi", okHttpClientBuilder -> okHttpClientBuilder.addInterceptor(requestInterceptor)).apiAuthProviders(apiAuthProviders).build());
apiCategory.configure(apiCategoryConfiguration, context);
api = SynchronousApi.delegatingTo(apiCategory);
// Setup DataStore
DataStoreConfiguration dsConfig = DataStoreConfiguration.builder().errorHandler(exception -> Log.e(tag, "DataStore error handler received an error.", exception)).syncExpression(modelSchema.getName(), () -> Where.id("FAKE_ID").getQueryPredicate()).build();
CategoryConfiguration dataStoreCategoryConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId).forCategoryType(CategoryType.DATASTORE);
String databaseName = "IntegTest" + modelType.getSimpleName() + ".db";
SQLiteStorageAdapter sqLiteStorageAdapter = TestStorageAdapter.create(schemaRegistry, modelProvider, databaseName);
AWSDataStorePlugin awsDataStorePlugin = AWSDataStorePlugin.builder().storageAdapter(sqLiteStorageAdapter).modelProvider(modelProvider).apiCategory(apiCategory).authModeStrategy(AuthModeStrategyType.MULTIAUTH).schemaRegistry(schemaRegistry).dataStoreConfiguration(dsConfig).build();
DataStoreCategory dataStoreCategory = new DataStoreCategory();
dataStoreCategory.addPlugin(awsDataStorePlugin);
dataStoreCategory.configure(dataStoreCategoryConfiguration, context);
dataStoreCategory.initialize(context);
dataStore = SynchronousDataStore.delegatingTo(dataStoreCategory);
}
use of com.amplifyframework.AmplifyException in project amplify-android by aws-amplify.
the class MultiAuthSyncEngineInstrumentationTest method createRecord.
/**
* Create a instance of the model using the private constructor via reflection.
* @return A instance of the model being tested.
*/
private Model createRecord(Class<? extends Model> modelType, String modelId) {
try {
String recordDetail = "IntegTest-" + modelType.getSimpleName() + " " + RandomString.string();
Map<String, Object> modelMap = new HashMap<>();
modelMap.put("id", modelId);
modelMap.put("name", recordDetail);
return SerializedModel.builder().serializedData(modelMap).modelSchema(ModelSchema.fromModelClass(modelType)).build();
} catch (AmplifyException exception) {
Log.e(modelType.getSimpleName(), "Unable to create an instance of model " + modelType.getSimpleName(), exception);
throw new RuntimeException("Unable to create an instance of model " + modelType.getSimpleName(), exception);
}
}
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 Class<T> itemClass, @NonNull StorageItemChange.Initiator initiator, @NonNull QueryPredicate predicate, @NonNull Action onSuccess, @NonNull Consumer<DataStoreException> onError) {
final ModelSchema schema;
try {
schema = ModelSchema.fromModelClass(itemClass);
} catch (AmplifyException schemaBuildFailure) {
onError.accept(new DataStoreException("Failed to build model schema.", schemaBuildFailure, "Verify your model."));
return;
}
for (Model savedItem : items) {
if (!itemClass.isInstance(savedItem) || !predicate.evaluate(savedItem)) {
continue;
}
items.remove(savedItem);
StorageItemChange<T> deletion = StorageItemChange.<T>builder().item((T) savedItem).modelSchema(schema).type(StorageItemChange.Type.DELETE).predicate(predicate).initiator(initiator).build();
itemChangeStream.onNext(deletion);
}
onSuccess.call();
}
use of com.amplifyframework.AmplifyException in project amplify-android by aws-amplify.
the class ObserveQueryExecutorTest method observeQueryReturnsSortedListOfTotalItemsWithInt.
/**
* ObserveQuery returns sorted list of total items with int.
* @throws InterruptedException interrupted exception.
* @throws AmplifyException data store exception.
*/
@Test
public void observeQueryReturnsSortedListOfTotalItemsWithInt() throws InterruptedException, AmplifyException {
CountDownLatch latch = new CountDownLatch(1);
CountDownLatch changeLatch = new CountDownLatch(1);
AtomicInteger count = new AtomicInteger();
List<Post> posts = new ArrayList<>();
for (int counter = 0; counter < 5; counter++) {
final Post post = Post.builder().title(counter + "-title").status(PostStatus.INACTIVE).rating(counter).build();
posts.add(post);
}
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<Post>> onQuerySnapshot = value -> {
if (count.get() == 0) {
Assert.assertTrue(value.getItems().contains(posts.get(0)));
latch.countDown();
} else if (count.get() == 1) {
List<Post> sorted = new ArrayList<>(posts);
Collections.sort(sorted, Comparator.comparing(Post::getRating));
assertEquals(sorted, value.getItems());
Assert.assertEquals(11, value.getItems().size());
changeLatch.countDown();
}
count.getAndIncrement();
};
Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
Action onObservationComplete = NoOpAction.create();
SqlQueryProcessor mockSqlQueryProcessor = mock(SqlQueryProcessor.class);
when(mockSqlQueryProcessor.queryOfflineData(eq(Post.class), any(), any())).thenReturn(posts);
when(mockSqlQueryProcessor.modelExists(any(), any())).thenReturn(true);
ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 5);
ObserveQueryExecutor<Post> observeQueryExecutor = new ObserveQueryExecutor<>(subject, mockSqlQueryProcessor, threadPool, mockSyncStatus, new ModelSorter<>(), maxRecords, 2);
List<QuerySortBy> sortBy = new ArrayList<>();
sortBy.add(Post.RATING.ascending());
observeQueryExecutor.observeQuery(Post.class, new ObserveQueryOptions(null, sortBy), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
for (int i = 5; i < 11; i++) {
Post itemChange = Post.builder().title(i + "-title").status(PostStatus.INACTIVE).rating(i).build();
posts.add(itemChange);
subject.onNext(StorageItemChange.<Post>builder().changeId(UUID.randomUUID().toString()).initiator(StorageItemChange.Initiator.SYNC_ENGINE).item(itemChange).patchItem(SerializedModel.create(itemChange, ModelSchema.fromModelClass(Post.class))).modelSchema(ModelSchema.fromModelClass(BlogOwner.class)).predicate(QueryPredicates.all()).type(StorageItemChange.Type.CREATE).build());
}
Assert.assertTrue(changeLatch.await(5, TimeUnit.SECONDS));
}
use of com.amplifyframework.AmplifyException in project amplify-android by aws-amplify.
the class ObserveQueryExecutorTest method observeQueryReturnsRecordsBasedOnMaxRecords.
/**
* observe Query Returns Records Based On Max Records.
* @throws InterruptedException InterruptedException
* @throws DataStoreException DataStoreException
* @throws AmplifyException AmplifyException
*/
@Test
public void observeQueryReturnsRecordsBasedOnMaxRecords() throws InterruptedException, AmplifyException {
CountDownLatch latch = new CountDownLatch(1);
CountDownLatch changeLatch = new CountDownLatch(3);
AtomicInteger count = new AtomicInteger();
BlogOwner blogOwner = BlogOwner.builder().name("Alan Turing").build();
List<BlogOwner> datastoreResultList = new ArrayList<>();
int maxRecords = 2;
datastoreResultList.add(blogOwner);
Consumer<Cancelable> observationStarted = NoOpConsumer.create();
SyncStatus mockSyncStatus = mock(SyncStatus.class);
when(mockSyncStatus.get(any(), any())).thenReturn(false).thenReturn(true).thenReturn(true);
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(3, value.getItems().size());
Assert.assertTrue(value.getIsSynced());
changeLatch.countDown();
} else if (count.get() == 2) {
Assert.assertEquals(4, value.getItems().size());
changeLatch.countDown();
} else {
Assert.assertEquals(5, value.getItems().size());
changeLatch.countDown();
}
count.getAndIncrement();
};
Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
Action onObservationComplete = NoOpAction.create();
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, maxRecords);
observeQueryExecutor.observeQuery(BlogOwner.class, new ObserveQueryOptions(null, null), 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();
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());
}
Assert.assertTrue(changeLatch.await(7, TimeUnit.SECONDS));
}
Aggregations