Search in sources :

Example 21 with ModelSchema

use of com.amplifyframework.core.model.ModelSchema 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)

Example 22 with ModelSchema

use of com.amplifyframework.core.model.ModelSchema in project amplify-android by aws-amplify.

the class SQLCommandProcessorTest method executeExistsReturnsFalseWhenItemDoesntExist.

/**
 * Create a BlogOwner, but don't insert it.  Then verify that executeExists returns false.
 * @throws AmplifyException on failure to create ModelSchema from class.
 */
@Test
public void executeExistsReturnsFalseWhenItemDoesntExist() throws AmplifyException {
    // Create a BlogOwner, but don't insert it
    ModelSchema blogOwnerSchema = ModelSchema.fromModelClass(BlogOwner.class);
    BlogOwner abigailMcGregor = BlogOwner.builder().name("Abigail McGregor").build();
    QueryPredicate predicate = BlogOwner.ID.eq(abigailMcGregor.getId());
    SqlCommand existsCommand = sqlCommandFactory.existsFor(blogOwnerSchema, predicate);
    assertFalse(sqlCommandProcessor.executeExists(existsCommand));
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 23 with ModelSchema

use of com.amplifyframework.core.model.ModelSchema in project amplify-android by aws-amplify.

the class SerializedModelAdapter method serialize.

@Override
public JsonElement serialize(SerializedModel src, Type typeOfSrc, JsonSerializationContext context) {
    ModelSchema schema = src.getModelSchema();
    JsonObject result = new JsonObject();
    result.add("id", context.serialize(src.getId()));
    result.add("modelSchema", context.serialize(schema));
    JsonObject serializedData = new JsonObject();
    for (Map.Entry<String, Object> entry : src.getSerializedData().entrySet()) {
        if (entry.getValue() instanceof SerializedModel) {
            SerializedModel serializedModel = (SerializedModel) entry.getValue();
            serializedData.add(entry.getKey(), new JsonPrimitive(serializedModel.getId()));
        } else {
            serializedData.add(entry.getKey(), context.serialize(entry.getValue()));
        }
    }
    result.add("serializedData", serializedData);
    return result;
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) JsonObject(com.google.gson.JsonObject) SerializedModel(com.amplifyframework.core.model.SerializedModel) HashMap(java.util.HashMap) Map(java.util.Map)

Example 24 with ModelSchema

use of com.amplifyframework.core.model.ModelSchema in project amplify-android by aws-amplify.

the class MultiAuthModeStrategy method authTypesFor.

@Override
public AuthorizationTypeIterator authTypesFor(@NonNull ModelSchema modelSchema, @NonNull ModelOperation operation) {
    final List<AuthRule> applicableRules = new ArrayList<>();
    Consumer<List<AuthRule>> filterAuthRules = authRules -> {
        for (AuthRule rule : authRules) {
            if (rule.getOperationsOrDefault().contains(operation)) {
                applicableRules.add(rule);
            }
        }
    };
    filterAuthRules.accept(modelSchema.getAuthRules());
    for (ModelField field : modelSchema.getFields().values()) {
        filterAuthRules.accept(field.getAuthRules());
    }
    return new MultiAuthorizationTypeIterator(applicableRules);
}
Also used : Consumer(com.amplifyframework.core.Consumer) List(java.util.List) AuthorizationTypeIterator(com.amplifyframework.core.model.auth.AuthorizationTypeIterator) MultiAuthorizationTypeIterator(com.amplifyframework.core.model.auth.MultiAuthorizationTypeIterator) NonNull(androidx.annotation.NonNull) AuthRule(com.amplifyframework.core.model.AuthRule) ModelSchema(com.amplifyframework.core.model.ModelSchema) ModelOperation(com.amplifyframework.core.model.ModelOperation) ModelField(com.amplifyframework.core.model.ModelField) ArrayList(java.util.ArrayList) MultiAuthorizationTypeIterator(com.amplifyframework.core.model.auth.MultiAuthorizationTypeIterator) ModelField(com.amplifyframework.core.model.ModelField) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) AuthRule(com.amplifyframework.core.model.AuthRule)

Example 25 with ModelSchema

use of com.amplifyframework.core.model.ModelSchema in project amplify-android by aws-amplify.

the class SelectionSetTest method nestedSerializedModelAndSerializedCustomType.

/**
 * Test generating SelectionSet for ModelSchema that nests CustomTypeSchema.
 * @throws AmplifyException if a ModelSchema can't be derived from OwnerAuth.class
 */
@Test
public void nestedSerializedModelAndSerializedCustomType() throws AmplifyException {
    SchemaRegistry schemaRegistry = SchemaRegistry.instance();
    CustomTypeField phoneCountryField = CustomTypeField.builder().targetType("String").isRequired(true).build();
    CustomTypeField phoneAreaField = CustomTypeField.builder().targetType("String").isRequired(true).build();
    CustomTypeField phoneNumber = CustomTypeField.builder().targetType("String").isRequired(true).build();
    Map<String, CustomTypeField> phoneFields = new HashMap<>();
    phoneFields.put("country", phoneCountryField);
    phoneFields.put("area", phoneAreaField);
    phoneFields.put("number", phoneNumber);
    CustomTypeSchema phoneSchema = CustomTypeSchema.builder().fields(phoneFields).name("Phone").pluralName("Phones").build();
    CustomTypeField addressCityField = CustomTypeField.builder().targetType("String").isRequired(true).build();
    CustomTypeField addressPhoneNumberField = CustomTypeField.builder().targetType("Phone").isCustomType(true).build();
    CustomTypeField addressLine1Field = CustomTypeField.builder().targetType("String").isRequired(true).build();
    CustomTypeField addressLine2Field = CustomTypeField.builder().targetType("String").build();
    CustomTypeField addressStateField = CustomTypeField.builder().targetType("String").isRequired(true).build();
    CustomTypeField addressPostalCodeField = CustomTypeField.builder().targetType("String").isRequired(true).build();
    Map<String, CustomTypeField> addressFields = new HashMap<>();
    addressFields.put("city", addressCityField);
    addressFields.put("phoneNumber", addressPhoneNumberField);
    addressFields.put("line1", addressLine1Field);
    addressFields.put("line2", addressLine2Field);
    addressFields.put("state", addressStateField);
    addressFields.put("postalCode", addressPostalCodeField);
    CustomTypeSchema addressSchema = CustomTypeSchema.builder().fields(addressFields).name("Address").pluralName("Addresses").build();
    ModelField personAddressField = ModelField.builder().name("address").isCustomType(true).targetType("Address").isRequired(true).build();
    ModelField personNameField = ModelField.builder().name("name").targetType("String").isRequired(true).build();
    ModelField personPhonesField = ModelField.builder().name("phoneNumbers").targetType("Phone").isCustomType(true).isArray(true).build();
    Map<String, ModelField> personFields = new HashMap<>();
    personFields.put("address", personAddressField);
    personFields.put("name", personNameField);
    personFields.put("phones", personPhonesField);
    ModelSchema personSchema = ModelSchema.builder().fields(personFields).name("Person").pluralName("People").modelClass(SerializedModel.class).build();
    // Register custom type schema for usage in SelectionSet
    schemaRegistry.register("Address", addressSchema);
    schemaRegistry.register("Phone", phoneSchema);
    // Register model schema for usage in SelectionSet
    schemaRegistry.register("Person", personSchema);
    SelectionSet selectionSet = SelectionSet.builder().modelClass(SerializedModel.class).modelSchema(personSchema).operation(QueryType.GET).requestOptions(new DefaultGraphQLRequestOptions()).build();
    String result = selectionSet.toString();
    assertEquals(Resources.readAsString("selection-set-nested-serialized-model-serialized-custom-type.txt"), result + "\n");
}
Also used : CustomTypeSchema(com.amplifyframework.core.model.CustomTypeSchema) ModelSchema(com.amplifyframework.core.model.ModelSchema) ModelField(com.amplifyframework.core.model.ModelField) HashMap(java.util.HashMap) CustomTypeField(com.amplifyframework.core.model.CustomTypeField) SerializedModel(com.amplifyframework.core.model.SerializedModel) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Test(org.junit.Test)

Aggregations

ModelSchema (com.amplifyframework.core.model.ModelSchema)109 Test (org.junit.Test)69 SerializedModel (com.amplifyframework.core.model.SerializedModel)34 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)30 Model (com.amplifyframework.core.model.Model)28 DataStoreException (com.amplifyframework.datastore.DataStoreException)26 HashMap (java.util.HashMap)23 ArrayList (java.util.ArrayList)22 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)21 AmplifyException (com.amplifyframework.AmplifyException)19 Consumer (com.amplifyframework.core.Consumer)19 List (java.util.List)17 NonNull (androidx.annotation.NonNull)14 Cancelable (com.amplifyframework.core.async.Cancelable)14 TimeUnit (java.util.concurrent.TimeUnit)14 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)13 Action (com.amplifyframework.core.Action)12 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)12 Collections (java.util.Collections)12 ModelProvider (com.amplifyframework.core.model.ModelProvider)11