Search in sources :

Example 11 with JsonApiResponse

use of io.crnk.core.repository.response.JsonApiResponse in project crnk-framework by crnk-project.

the class IncludeLookupSetter method lookupRelatedResourcesWithId.

private Set<Resource> lookupRelatedResourcesWithId(Collection<Resource> sourceResources, ResourceField relationshipField, QueryAdapter queryAdapter, RepositoryMethodParameterProvider parameterProvider, Map<ResourceIdentifier, Resource> resourceMap, Map<ResourceIdentifier, Object> entityMap, ResourceMappingConfig resourceMappingConfig) {
    String oppositeResourceType = relationshipField.getOppositeResourceType();
    RegistryEntry oppositeEntry = resourceRegistry.getEntry(oppositeResourceType);
    if (oppositeEntry == null) {
        throw new RepositoryNotFoundException("no resource with type " + oppositeResourceType + " found");
    }
    ResourceInformation oppositeResourceInformation = oppositeEntry.getResourceInformation();
    ResourceRepositoryAdapter oppositeResourceRepository = oppositeEntry.getResourceRepository(parameterProvider);
    if (oppositeResourceRepository == null) {
        throw new RepositoryNotFoundException("no relationship repository found for " + oppositeResourceInformation.getResourceType());
    }
    Set<Resource> related = new HashSet<>();
    Set<Object> relatedIdsToLoad = new HashSet<>();
    for (Resource sourceResource : sourceResources) {
        Relationship relationship = sourceResource.getRelationships().get(relationshipField.getJsonName());
        PreconditionUtil.assertTrue("expected relationship data to be loaded for @JsonApiResourceId annotated field", relationship.getData().isPresent());
        if (relationship.getData().get() != null) {
            for (ResourceIdentifier id : relationship.getCollectionData().get()) {
                if (resourceMap.containsKey(id)) {
                    // load from cache
                    related.add(resourceMap.get(id));
                } else {
                    relatedIdsToLoad.add(oppositeResourceInformation.parseIdString(id.getId()));
                }
            }
        }
    }
    if (!relatedIdsToLoad.isEmpty()) {
        JsonApiResponse response = oppositeResourceRepository.findAll(relatedIdsToLoad, queryAdapter);
        Collection responseList = (Collection) response.getEntity();
        for (Object responseEntity : responseList) {
            Resource relatedResource = mergeResource(responseEntity, queryAdapter, resourceMap, entityMap, resourceMappingConfig);
            related.add(relatedResource);
            Object responseEntityId = oppositeResourceInformation.getId(responseEntity);
            relatedIdsToLoad.remove(responseEntityId);
        }
        if (!relatedIdsToLoad.isEmpty()) {
            throw new ResourceNotFoundException("type=" + relationshipField.getOppositeResourceType() + ", " + "ids=" + relatedIdsToLoad);
        }
    }
    return related;
}
Also used : ResourceInformation(io.crnk.core.engine.information.resource.ResourceInformation) Resource(io.crnk.core.engine.document.Resource) RepositoryNotFoundException(io.crnk.core.exception.RepositoryNotFoundException) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) ResourceIdentifier(io.crnk.core.engine.document.ResourceIdentifier) ResourceRepositoryAdapter(io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter) Relationship(io.crnk.core.engine.document.Relationship) Collection(java.util.Collection) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) ResourceNotFoundException(io.crnk.core.exception.ResourceNotFoundException) HashSet(java.util.HashSet)

Example 12 with JsonApiResponse

use of io.crnk.core.repository.response.JsonApiResponse in project crnk-framework by crnk-project.

the class FieldResourceGet method handle.

@Override
public Response handle(JsonPath jsonPath, QueryAdapter queryAdapter, RepositoryMethodParameterProvider parameterProvider, Document requestBody) {
    PathIds resourceIds = jsonPath.getIds();
    String resourceName = jsonPath.getResourceType();
    String elementName = jsonPath.getElementName();
    RegistryEntry registryEntry = resourceRegistry.getEntry(resourceName);
    Serializable castedResourceId = getResourceId(resourceIds, registryEntry);
    ResourceField relationshipField = registryEntry.getResourceInformation().findRelationshipFieldByName(elementName);
    verifyFieldNotNull(relationshipField, elementName);
    // TODO remove Class usage and replace by resourceId
    Class<?> baseRelationshipFieldClass = relationshipField.getType();
    RelationshipRepositoryAdapter relationshipRepositoryForClass = registryEntry.getRelationshipRepository(relationshipField, parameterProvider);
    JsonApiResponse entities;
    if (Iterable.class.isAssignableFrom(baseRelationshipFieldClass)) {
        entities = relationshipRepositoryForClass.findManyTargets(castedResourceId, relationshipField, queryAdapter);
    } else {
        entities = relationshipRepositoryForClass.findOneTarget(castedResourceId, relationshipField, queryAdapter);
    }
    Document responseDocument = documentMapper.toDocument(entities, queryAdapter, parameterProvider);
    // return explicit { data : null } if values found
    if (!responseDocument.getData().isPresent()) {
        responseDocument.setData(Nullable.nullValue());
    }
    return new Response(responseDocument, 200);
}
Also used : JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) Response(io.crnk.core.engine.dispatcher.Response) ResourceField(io.crnk.core.engine.information.resource.ResourceField) Serializable(java.io.Serializable) PathIds(io.crnk.core.engine.internal.dispatcher.path.PathIds) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) Document(io.crnk.core.engine.document.Document) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) RelationshipRepositoryAdapter(io.crnk.core.engine.internal.repository.RelationshipRepositoryAdapter)

Example 13 with JsonApiResponse

use of io.crnk.core.repository.response.JsonApiResponse in project crnk-framework by crnk-project.

the class FieldResourcePost method handle.

@Override
public Response handle(JsonPath jsonPath, QueryAdapter queryAdapter, RepositoryMethodParameterProvider parameterProvider, Document requestDocument) {
    RegistryEntry endpointRegistryEntry = getRegistryEntry(jsonPath);
    Resource resourceBody = getRequestBody(requestDocument, jsonPath, HttpMethod.POST);
    PathIds resourceIds = jsonPath.getIds();
    RegistryEntry bodyRegistryEntry = resourceRegistry.getEntry(resourceBody.getType());
    Serializable castedResourceId = getResourceId(resourceIds, endpointRegistryEntry);
    ResourceField relationshipField = endpointRegistryEntry.getResourceInformation().findRelationshipFieldByName(jsonPath.getElementName());
    verifyFieldNotNull(relationshipField, jsonPath.getElementName());
    Class<?> baseRelationshipFieldClass = relationshipField.getType();
    RegistryEntry relationshipRegistryEntry = resourceRegistry.getEntry(relationshipField.getOppositeResourceType());
    String relationshipResourceType = relationshipField.getOppositeResourceType();
    verifyTypes(HttpMethod.POST, relationshipRegistryEntry, bodyRegistryEntry);
    Object newResource = buildNewResource(relationshipRegistryEntry, resourceBody, relationshipResourceType);
    setAttributes(resourceBody, newResource, relationshipRegistryEntry.getResourceInformation());
    ResourceRepositoryAdapter resourceRepository = relationshipRegistryEntry.getResourceRepository(parameterProvider);
    Document savedResourceResponse = documentMapper.toDocument(resourceRepository.create(newResource, queryAdapter), queryAdapter, parameterProvider);
    setRelations(newResource, bodyRegistryEntry, resourceBody, queryAdapter, parameterProvider, false);
    ResourceIdentifier resourceId1 = savedResourceResponse.getSingleData().get();
    RelationshipRepositoryAdapter relationshipRepositoryForClass = endpointRegistryEntry.getRelationshipRepository(relationshipField, parameterProvider);
    @SuppressWarnings("unchecked") JsonApiResponse parent = endpointRegistryEntry.getResourceRepository(parameterProvider).findOne(castedResourceId, queryAdapter);
    if (Iterable.class.isAssignableFrom(baseRelationshipFieldClass)) {
        List<ResourceIdentifier> resourceIdList = Collections.singletonList(resourceId1);
        for (ResourceModificationFilter filter : modificationFilters) {
            resourceIdList = filter.modifyManyRelationship(parent.getEntity(), relationshipField, ResourceRelationshipModificationType.ADD, resourceIdList);
        }
        List<Serializable> parsedIds = new ArrayList<>();
        for (ResourceIdentifier resourceId : resourceIdList) {
            parsedIds.add(relationshipRegistryEntry.getResourceInformation().parseIdString(resourceId.getId()));
        }
        // noinspection unchecked
        relationshipRepositoryForClass.addRelations(parent.getEntity(), parsedIds, relationshipField, queryAdapter);
    } else {
        // noinspection unchecked
        for (ResourceModificationFilter filter : modificationFilters) {
            resourceId1 = filter.modifyOneRelationship(parent.getEntity(), relationshipField, resourceId1);
        }
        Serializable parseId = relationshipRegistryEntry.getResourceInformation().parseIdString(resourceId1.getId());
        relationshipRepositoryForClass.setRelation(parent.getEntity(), parseId, relationshipField, queryAdapter);
    }
    return new Response(savedResourceResponse, HttpStatus.CREATED_201);
}
Also used : Serializable(java.io.Serializable) Resource(io.crnk.core.engine.document.Resource) ArrayList(java.util.ArrayList) Document(io.crnk.core.engine.document.Document) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) RelationshipRepositoryAdapter(io.crnk.core.engine.internal.repository.RelationshipRepositoryAdapter) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) Response(io.crnk.core.engine.dispatcher.Response) ResourceField(io.crnk.core.engine.information.resource.ResourceField) ResourceIdentifier(io.crnk.core.engine.document.ResourceIdentifier) ResourceRepositoryAdapter(io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter) PathIds(io.crnk.core.engine.internal.dispatcher.path.PathIds) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) ResourceModificationFilter(io.crnk.core.engine.filter.ResourceModificationFilter)

Example 14 with JsonApiResponse

use of io.crnk.core.repository.response.JsonApiResponse in project crnk-framework by crnk-project.

the class ResourcePost method handle.

@Override
public Response handle(JsonPath jsonPath, QueryAdapter queryAdapter, RepositoryMethodParameterProvider parameterProvider, Document requestDocument) {
    RegistryEntry endpointRegistryEntry = getRegistryEntry(jsonPath);
    Resource resourceBody = getRequestBody(requestDocument, jsonPath, HttpMethod.POST);
    RegistryEntry bodyRegistryEntry = resourceRegistry.getEntry(resourceBody.getType());
    verifyTypes(HttpMethod.POST, endpointRegistryEntry, bodyRegistryEntry);
    ResourceRepositoryAdapter resourceRepository = endpointRegistryEntry.getResourceRepository(parameterProvider);
    JsonApiResponse apiResponse;
    if (Resource.class.equals(resourceRepository.getResourceClass())) {
        apiResponse = resourceRepository.create(resourceBody, queryAdapter);
    } else {
        Object newResource = newResource(bodyRegistryEntry.getResourceInformation(), resourceBody);
        setId(resourceBody, newResource, bodyRegistryEntry.getResourceInformation());
        setAttributes(resourceBody, newResource, bodyRegistryEntry.getResourceInformation());
        setRelations(newResource, bodyRegistryEntry, resourceBody, queryAdapter, parameterProvider, false);
        apiResponse = resourceRepository.create(newResource, queryAdapter);
    }
    if (apiResponse.getEntity() == null) {
        throw new IllegalStateException("repository did not return the created resource");
    }
    Set<String> loadedRelationshipNames = getLoadedRelationshipNames(resourceBody);
    Document responseDocument = documentMapper.toDocument(apiResponse, queryAdapter, parameterProvider, loadedRelationshipNames);
    return new Response(responseDocument, HttpStatus.CREATED_201);
}
Also used : JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) Response(io.crnk.core.engine.dispatcher.Response) ResourceRepositoryAdapter(io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter) Resource(io.crnk.core.engine.document.Resource) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) Document(io.crnk.core.engine.document.Document) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry)

Example 15 with JsonApiResponse

use of io.crnk.core.repository.response.JsonApiResponse in project crnk-framework by crnk-project.

the class QuerySpecRepositoryTest method checkCrud.

@SuppressWarnings({ "unchecked" })
private void checkCrud(QueryAdapter queryAdapter) {
    // setup data
    Project project = new Project();
    project.setId(3L);
    project.setName("myProject");
    projectAdapter.create(project, queryAdapter);
    Task task = new Task();
    task.setId(2L);
    task.setName("myTask");
    task.setProject(project);
    task.setProjects(Arrays.asList(project));
    taskAdapter.create(task, queryAdapter);
    // adapter
    List<Task> tasks = (List<Task>) taskAdapter.findAll(queryAdapter).getEntity();
    Assert.assertEquals(1, tasks.size());
    Assert.assertEquals(task, taskAdapter.findOne(2L, queryAdapter).getEntity());
    tasks = (List<Task>) taskAdapter.findAll(Arrays.asList(2L), queryAdapter).getEntity();
    Assert.assertEquals(1, tasks.size());
    // relation adapter
    ResourceField projectField = resourceRegistry.getEntry(Task.class).getResourceInformation().findRelationshipFieldByName("project");
    ResourceField tasksField = resourceRegistry.getEntry(Project.class).getResourceInformation().findRelationshipFieldByName("tasks");
    projectRelAdapter.setRelation(task, project.getId(), projectField, queryAdapter);
    Assert.assertNotNull(task.getProject());
    Assert.assertEquals(1, project.getTasks().size());
    JsonApiResponse response = projectRelAdapter.findOneTarget(2L, projectField, queryAdapter);
    Assert.assertEquals(project.getId(), ((Project) response.getEntity()).getId());
    projectRelAdapter.setRelation(task, null, projectField, queryAdapter);
    response = projectRelAdapter.findOneTarget(2L, projectField, queryAdapter);
    Assert.assertNull(task.getProject());
    // warning: bidirectionality not properly implemented here, would
    // require changes to the model used in many other places
    task.setProject(null);
    project.getTasks().clear();
    tasksRelAdapter.addRelations(project, Arrays.asList(task.getId()), tasksField, queryAdapter);
    Assert.assertEquals(project, task.getProject());
    Assert.assertEquals(1, project.getTasks().size());
    List<Project> projects = (List<Project>) tasksRelAdapter.findManyTargets(3L, tasksField, queryAdapter).getEntity();
    Assert.assertEquals(1, projects.size());
    tasksRelAdapter.removeRelations(project, Arrays.asList(task.getId()), tasksField, queryAdapter);
    Assert.assertEquals(0, project.getTasks().size());
    // fix bidirectionality
    task.setProject(null);
    projects = (List<Project>) tasksRelAdapter.findManyTargets(3L, tasksField, queryAdapter).getEntity();
    Assert.assertEquals(0, projects.size());
    tasksRelAdapter.setRelations(project, Arrays.asList(task.getId()), tasksField, queryAdapter);
    Assert.assertEquals(project, task.getProject());
    Assert.assertEquals(1, project.getTasks().size());
    projects = (List<Project>) tasksRelAdapter.findManyTargets(3L, tasksField, queryAdapter).getEntity();
    Assert.assertEquals(1, projects.size());
    // check bulk find
    Map<?, JsonApiResponse> bulkMap = tasksRelAdapter.findBulkManyTargets(Arrays.asList(3L), tasksField, queryAdapter);
    Assert.assertEquals(1, bulkMap.size());
    Assert.assertTrue(bulkMap.containsKey(3L));
    projects = (List<Project>) bulkMap.get(3L).getEntity();
    Assert.assertEquals(1, projects.size());
    bulkMap = projectRelAdapter.findBulkOneTargets(Arrays.asList(2L), projectField, queryAdapter);
    Assert.assertEquals(1, bulkMap.size());
    Assert.assertTrue(bulkMap.containsKey(2L));
    Assert.assertNotNull(bulkMap.get(2L));
    // deletion
    taskAdapter.delete(task.getId(), queryAdapter);
    tasks = (List<Task>) taskAdapter.findAll(queryAdapter).getEntity();
    Assert.assertEquals(0, tasks.size());
    tasks = (List<Task>) taskAdapter.findAll(Arrays.asList(2L), queryAdapter).getEntity();
    Assert.assertEquals(0, tasks.size());
}
Also used : Project(io.crnk.core.mock.models.Project) ResourceField(io.crnk.core.engine.information.resource.ResourceField) Task(io.crnk.core.mock.models.Task) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse)

Aggregations

JsonApiResponse (io.crnk.core.repository.response.JsonApiResponse)49 Document (io.crnk.core.engine.document.Document)16 Test (org.junit.Test)16 ResourceField (io.crnk.core.engine.information.resource.ResourceField)15 RegistryEntry (io.crnk.core.engine.registry.RegistryEntry)14 QuerySpecAdapter (io.crnk.core.queryspec.internal.QuerySpecAdapter)12 QueryAdapter (io.crnk.core.engine.query.QueryAdapter)11 QuerySpec (io.crnk.core.queryspec.QuerySpec)11 RepositoryRequestSpec (io.crnk.core.engine.dispatcher.RepositoryRequestSpec)10 RepositoryFilterContext (io.crnk.core.engine.filter.RepositoryFilterContext)10 ResourceInformation (io.crnk.core.engine.information.resource.ResourceInformation)10 ResourceRepositoryAdapter (io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter)10 Serializable (java.io.Serializable)10 Response (io.crnk.core.engine.dispatcher.Response)9 Resource (io.crnk.core.engine.document.Resource)9 Task (io.crnk.core.mock.models.Task)7 AbstractQuerySpecTest (io.crnk.core.queryspec.AbstractQuerySpecTest)6 BulkRelationshipRepositoryV2 (io.crnk.core.repository.BulkRelationshipRepositoryV2)6 PagedLinksInformation (io.crnk.core.resource.links.PagedLinksInformation)6 HashSet (java.util.HashSet)6