use of io.crnk.core.engine.document.Relationship in project crnk-framework by crnk-project.
the class IncludeLookupSetter method lookupRelatedResourceWithRelationship.
private Set<Resource> lookupRelatedResourceWithRelationship(Collection<Resource> sourceResources, ResourceField relationshipField, QueryAdapter queryAdapter, RepositoryMethodParameterProvider parameterProvider, Map<ResourceIdentifier, Resource> resourceMap, Map<ResourceIdentifier, Object> entityMap, ResourceMappingConfig resourceMappingConfig) {
ResourceInformation resourceInformation = relationshipField.getParentResourceInformation();
RegistryEntry registyEntry = resourceRegistry.getEntry(resourceInformation.getResourceType());
List<Serializable> resourceIds = getIds(sourceResources, resourceInformation);
boolean isMany = Iterable.class.isAssignableFrom(relationshipField.getType());
Set<Resource> loadedTargets = new HashSet<>();
@SuppressWarnings("rawtypes") RelationshipRepositoryAdapter relationshipRepository = registyEntry.getRelationshipRepository(relationshipField, parameterProvider);
if (relationshipRepository != null) {
Map<Object, JsonApiResponse> responseMap;
if (isMany) {
responseMap = relationshipRepository.findBulkManyTargets(resourceIds, relationshipField, queryAdapter);
} else {
responseMap = relationshipRepository.findBulkOneTargets(resourceIds, relationshipField, queryAdapter);
}
for (Resource sourceResource : sourceResources) {
Serializable sourceId = resourceInformation.parseIdString(sourceResource.getId());
JsonApiResponse targetResponse = responseMap.get(sourceId);
if (targetResponse != null && targetResponse.getEntity() != null) {
Object targetEntity = targetResponse.getEntity();
List<Resource> targets = setupRelation(sourceResource, relationshipField, targetEntity, queryAdapter, resourceMap, entityMap, resourceMappingConfig);
loadedTargets.addAll(targets);
} else {
Nullable<Object> emptyData = (Nullable) Nullable.of(Iterable.class.isAssignableFrom(relationshipField.getType()) ? Collections.emptyList() : null);
Relationship relationship = sourceResource.getRelationships().get(relationshipField.getJsonName());
relationship.setData(emptyData);
}
}
} else {
throw new RepositoryNotFoundException("no relationship repository found for " + resourceInformation.getResourceType() + "." + relationshipField.getUnderlyingName());
}
return loadedTargets;
}
use of io.crnk.core.engine.document.Relationship in project crnk-framework by crnk-project.
the class IncludeLookupSetter method populateField.
private void populateField(ResourceField resourceField, QueryAdapter queryAdapter, List<ResourceField> fieldPath, PopulatedCache populatedCache, Collection<Resource> resourceList, Set<String> fieldsWithEnforceIdSerialization, RepositoryMethodParameterProvider parameterProvider, Map<ResourceIdentifier, Resource> resourceMap, Map<ResourceIdentifier, Object> entityMap, Set<ResourceIdentifier> inclusions, ResourceMappingConfig resourceMappingConfig) {
ResourceInformation resourceInformation = resourceField.getParentResourceInformation();
boolean includeRequested = util.isInclusionRequested(queryAdapter, fieldPath);
boolean includeResources = includeRequested || resourceField.getSerializeType() == SerializeType.EAGER;
boolean includeRelationId = resourceField.getSerializeType() != SerializeType.LAZY || fieldsWithEnforceIdSerialization.contains(resourceField.getJsonName());
boolean includeRelationshipData = includeRelationId || includeResources;
if (includeRelationshipData) {
Collection<Resource> unpopulatedResourceList = populatedCache.filterProcessed(resourceList, resourceField);
if (!unpopulatedResourceList.isEmpty()) {
// only handle resources from the proper subtype where the
// relationship is desired to be loaded
List<Resource> resourcesByType = util.filterByType(unpopulatedResourceList, resourceInformation);
List<Resource> resourcesWithField = util.filterByLoadedRelationship(resourcesByType, resourceField);
// lookup resources by inspecting the POJOs in entityMap
LookupIncludeBehavior fieldLookupIncludeBehavior = resourceField.getLookupIncludeAutomatically();
Set<Resource> populatedResources;
if (!includeResources && resourceField.hasIdField()) {
// fill in @JsonApiRelationId into Relationship where possible
fetchRelationFromEntity(resourcesWithField, resourceField, queryAdapter, resourceMap, entityMap, false, false, includeResources, resourceMappingConfig);
// only ID is required and no lookup must take place
// nothing to do
populatedResources = Collections.emptySet();
} else if (fieldLookupIncludeBehavior == LookupIncludeBehavior.AUTOMATICALLY_ALWAYS) {
// fill in @JsonApiRelationId into Relationship where possible
fetchRelationFromEntity(resourcesWithField, resourceField, queryAdapter, resourceMap, entityMap, false, false, includeResources, resourceMappingConfig);
// lookup resources by making repository calls
populatedResources = lookupRelatedResource(resourcesWithField, resourceField, queryAdapter, parameterProvider, resourceMap, entityMap, resourceMappingConfig);
} else if (fieldLookupIncludeBehavior == LookupIncludeBehavior.AUTOMATICALLY_WHEN_NULL) {
// try to populate from entities
Set<Resource> extractedResources = fetchRelationFromEntity(resourcesWithField, resourceField, queryAdapter, resourceMap, entityMap, true, true, includeResources, resourceMappingConfig);
// do lookups where relationship data is null
Collection<Resource> resourcesForLookup = util.findResourcesWithoutRelationshipToLoad(resourcesWithField, resourceField, resourceMap);
Collection<Resource> lookedupResources = lookupRelatedResource(resourcesForLookup, resourceField, queryAdapter, parameterProvider, resourceMap, entityMap, resourceMappingConfig);
populatedResources = util.union(lookedupResources, extractedResources);
} else {
// do not do any lookups
populatedResources = fetchRelationFromEntity(resourcesWithField, resourceField, queryAdapter, resourceMap, entityMap, false, true, includeResources, resourceMappingConfig);
// and be sure.
if (!Iterable.class.isAssignableFrom(resourceField.getType())) {
Nullable<Object> emptyData = Nullable.nullValue();
for (Resource resourceWithField : resourcesWithField) {
Relationship relationship = resourceWithField.getRelationships().get(resourceField.getJsonName());
if (!relationship.getData().isPresent()) {
relationship.setData(emptyData);
}
}
}
}
// such
if (includeResources && !populatedResources.isEmpty()) {
inclusions.addAll(util.toIds(populatedResources));
Set<String> additionalEagerLoadedNestedRelations = Collections.emptySet();
populate(populatedResources, inclusions, resourceMap, entityMap, fieldPath, queryAdapter, parameterProvider, additionalEagerLoadedNestedRelations, populatedCache, resourceMappingConfig);
}
}
}
}
use of io.crnk.core.engine.document.Relationship in project crnk-framework by crnk-project.
the class CollectionGetTest method onGivenRequestResourceShouldLoadAutoIncludeFields.
@Test
public void onGivenRequestResourceShouldLoadAutoIncludeFields() throws Exception {
// GIVEN
Document newTaskBody = new Document();
Resource data = createTask();
newTaskBody.setData(Nullable.of((Object) data));
JsonPath taskPath = pathBuilder.build("/tasks");
ResourcePost resourcePost = new ResourcePost(resourceRegistry, PROPERTIES_PROVIDER, typeParser, objectMapper, documentMapper, new ArrayList<ResourceModificationFilter>());
// WHEN -- adding a task
Response taskResponse = resourcePost.handle(taskPath, emptyTaskQuery, null, newTaskBody);
// THEN
assertThat(taskResponse.getDocument().getSingleData().get().getType()).isEqualTo("tasks");
Long taskId = Long.parseLong(taskResponse.getDocument().getSingleData().get().getId());
assertThat(taskId).isNotNull();
/* ------- */
// GIVEN
Document newProjectBody = new Document();
data = createProject();
newProjectBody.setData(Nullable.of((Object) data));
JsonPath projectPath = pathBuilder.build("/projects");
// WHEN -- adding a project
Response projectResponse = resourcePost.handle(projectPath, emptyProjectQuery, null, newProjectBody);
// THEN
assertThat(projectResponse.getDocument().getSingleData().get().getType()).isEqualTo("projects");
assertThat(projectResponse.getDocument().getSingleData().get().getId()).isNotNull();
assertThat(projectResponse.getDocument().getSingleData().get().getAttributes().get("name").asText()).isEqualTo("sample project");
Long projectId = Long.parseLong(projectResponse.getDocument().getSingleData().get().getId());
assertThat(projectId).isNotNull();
/* ------- */
// GIVEN
Document newTaskToProjectBody = new Document();
data = new Resource();
newTaskToProjectBody.setData(Nullable.of((Object) Collections.singletonList(data)));
data.setType("projects");
data.setId(projectId.toString());
JsonPath savedTaskPath = pathBuilder.build("/tasks/" + taskId + "/relationships/includedProjects");
RelationshipsResourcePost sut = new RelationshipsResourcePost(resourceRegistry, typeParser, new ArrayList<ResourceModificationFilter>());
// WHEN -- adding a relation between task and project
Response projectRelationshipResponse = sut.handle(savedTaskPath, emptyProjectQuery, null, newTaskToProjectBody);
assertThat(projectRelationshipResponse).isNotNull();
// THEN
TaskToProjectRepository taskToProjectRepository = new TaskToProjectRepository();
Project project = taskToProjectRepository.findOneTarget(taskId, "includedProjects", new QueryParams());
assertThat(project.getId()).isEqualTo(projectId);
// Given
JsonPath jsonPath = pathBuilder.build("/tasks/" + taskId);
ResourceGet responseGetResp = new ResourceGet(resourceRegistry, typeParser, documentMapper);
Map<String, Set<String>> queryParams = new HashMap<>();
queryParams.put(RestrictedQueryParamsMembers.include.name() + "[tasks]", Collections.singleton("includedProjects"));
QueryParams queryParams1 = new QueryParamsBuilder(new DefaultQueryParamsParser()).buildQueryParams(queryParams);
// WHEN
Response response = responseGetResp.handle(jsonPath, new QueryParamsAdapter(resourceRegistry.getEntry(Task.class).getResourceInformation(), queryParams1, moduleRegistry), null, null);
// THEN
Assert.assertNotNull(response);
data = response.getDocument().getSingleData().get();
assertThat(data.getType()).isEqualTo("tasks");
Relationship relationship = data.getRelationships().get("includedProjects");
assertThat(relationship.getCollectionData()).isNotNull();
assertThat(relationship.getCollectionData().get().size()).isEqualTo(1);
assertThat(relationship.getCollectionData().get().get(0).getId()).isEqualTo(projectId.toString());
}
use of io.crnk.core.engine.document.Relationship in project crnk-framework by crnk-project.
the class ResourcePatchTest method onUpdatedLazyRelationshipDataShouldReturnThatData.
@Test
public void onUpdatedLazyRelationshipDataShouldReturnThatData() throws Exception {
// GIVEN
Document newTaskBody = new Document();
Resource data = createTask();
newTaskBody.setData(Nullable.of((Object) data));
data.setType("tasks");
JsonPath taskPath = pathBuilder.build("/tasks");
ResourcePost post = new ResourcePost(resourceRegistry, PROPERTIES_PROVIDER, typeParser, objectMapper, documentMapper, modificationFilters);
Response taskResponse = post.handle(taskPath, emptyTaskQuery, null, newTaskBody);
Long taskId = Long.parseLong(taskResponse.getDocument().getSingleData().get().getId());
Document newProjectBody = new Document();
data = createProject();
data.setType("projects");
data.getRelationships().put("tasks", new Relationship(Collections.singletonList(new ResourceIdentifier(taskId.toString(), "tasks"))));
newProjectBody.setData(Nullable.of((Object) data));
JsonPath projectsPath = pathBuilder.build("/projects");
Response projectsResponse = post.handle(projectsPath, emptyProjectQuery, null, newProjectBody);
assertThat(projectsResponse.getDocument().getSingleData().get().getRelationships().get("tasks").getCollectionData().get()).hasSize(1);
// update relationship and availability in response
ResourcePatch patch = new ResourcePatch(resourceRegistry, PROPERTIES_PROVIDER, typeParser, objectMapper, documentMapper, modificationFilters);
Nullable<Object> emptyRelation = Nullable.of((Object) new ArrayList<ResourceIdentifier>());
data.getRelationships().get("tasks").setData(emptyRelation);
projectsResponse = patch.handle(pathBuilder.build("/projects/2"), emptyProjectQuery, null, newProjectBody);
assertThat(projectsResponse.getDocument().getSingleData().get().getType()).isEqualTo("projects");
assertThat(projectsResponse.getDocument().getSingleData().get().getAttributes().get("name").asText()).isEqualTo("sample project");
assertThat(projectsResponse.getDocument().getSingleData().get().getRelationships().get("tasks").getCollectionData().get()).hasSize(0);
}
use of io.crnk.core.engine.document.Relationship in project crnk-framework by crnk-project.
the class ResourcePatchTest method onUnchagedLazyRelationshipDataShouldNotReturnThatData.
@Test
public void onUnchagedLazyRelationshipDataShouldNotReturnThatData() throws Exception {
// GIVEN
Document newTaskBody = new Document();
Resource data = createTask();
newTaskBody.setData(Nullable.of((Object) data));
data.setType("tasks");
JsonPath taskPath = pathBuilder.build("/tasks");
ResourcePost post = new ResourcePost(resourceRegistry, PROPERTIES_PROVIDER, typeParser, objectMapper, documentMapper, modificationFilters);
Response taskResponse = post.handle(taskPath, emptyTaskQuery, null, newTaskBody);
Long taskId = Long.parseLong(taskResponse.getDocument().getSingleData().get().getId());
Document newProjectBody = new Document();
data = createProject();
data.setType("projects");
data.getRelationships().put("tasks", new Relationship(Collections.singletonList(new ResourceIdentifier(taskId.toString(), "tasks"))));
newProjectBody.setData(Nullable.of((Object) data));
JsonPath projectsPath = pathBuilder.build("/projects");
Response projectsResponse = post.handle(projectsPath, emptyProjectQuery, null, newProjectBody);
assertThat(projectsResponse.getDocument().getSingleData().get().getRelationships().get("tasks").getCollectionData().get()).hasSize(1);
// update relationship and availability in response
ResourcePatch patch = new ResourcePatch(resourceRegistry, PROPERTIES_PROVIDER, typeParser, objectMapper, documentMapper, modificationFilters);
data.getRelationships().remove("tasks");
data.getAttributes().put("name", objectMapper.readTree("\"updated project\""));
projectsResponse = patch.handle(pathBuilder.build("/projects/2"), emptyProjectQuery, null, newProjectBody);
assertThat(projectsResponse.getDocument().getSingleData().get().getType()).isEqualTo("projects");
assertThat(projectsResponse.getDocument().getSingleData().get().getAttributes().get("name").asText()).isEqualTo("updated project");
assertThat(projectsResponse.getDocument().getSingleData().get().getRelationships().get("tasks").getCollectionData().isPresent()).isFalse();
}
Aggregations