Search in sources :

Example 21 with Response

use of io.crnk.core.engine.dispatcher.Response in project crnk-framework by crnk-project.

the class FieldResourceGetTest method onGivenIncludeRequestFieldResourcesGetShouldHandleIt.

@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void onGivenIncludeRequestFieldResourcesGetShouldHandleIt() throws Exception {
    // get repositories
    ResourceRepositoryAdapter userRepo = resourceRegistry.getEntry(User.class).getResourceRepository(null);
    ResourceRepositoryAdapter projectRepo = resourceRegistry.getEntry(Project.class).getResourceRepository(null);
    ResourceRepositoryAdapter taskRepo = resourceRegistry.getEntry(Task.class).getResourceRepository(null);
    RelationshipRepositoryAdapter relRepositoryUserToProject = resourceRegistry.getEntry(User.class).getRelationshipRepository("assignedProjects", null);
    RelationshipRepositoryAdapter relRepositoryProjectToTask = resourceRegistry.getEntry(Project.class).getRelationshipRepository("tasks", null);
    ResourceInformation userInfo = resourceRegistry.getEntry(User.class).getResourceInformation();
    ResourceInformation projectInfo = resourceRegistry.getEntry(Project.class).getResourceInformation();
    ResourceField includedTaskField = projectInfo.findRelationshipFieldByName("includedTask");
    ResourceField assignedProjectsField = userInfo.findRelationshipFieldByName("assignedProjects");
    // setup test data
    User user = new User();
    user.setId(1L);
    userRepo.create(user, emptyUserQuery);
    Project project = new Project();
    project.setId(2L);
    projectRepo.create(project, emptyProjectQuery);
    Task task = new Task();
    task.setId(3L);
    taskRepo.create(task, emptyTaskQuery);
    relRepositoryUserToProject.setRelations(user, Collections.singletonList(project.getId()), assignedProjectsField, emptyProjectQuery);
    relRepositoryProjectToTask.setRelation(project, task.getId(), includedTaskField, emptyTaskQuery);
    Map<String, Set<String>> params = new HashMap<String, Set<String>>();
    addParams(params, "include[projects]", "includedTask");
    QueryParams queryParams = queryParamsBuilder.buildQueryParams(params);
    QueryAdapter queryAdapter = new QueryParamsAdapter(projectInfo, queryParams, moduleRegistry);
    JsonPath jsonPath = pathBuilder.build("/users/1/assignedProjects");
    FieldResourceGet sut = new FieldResourceGet(resourceRegistry, typeParser, documentMapper);
    Response response = sut.handle(jsonPath, queryAdapter, null, null);
    // THEN
    Assert.assertNotNull(response);
    Assert.assertNotNull(response.getDocument().getData());
    List<Resource> entityList = ((List<Resource>) response.getDocument().getData().get());
    Assert.assertEquals(true, entityList.size() > 0);
    Assert.assertEquals("projects", entityList.get(0).getType());
    Resource returnedProject = entityList.get(0);
    Assert.assertEquals(project.getId().toString(), returnedProject.getId());
    Relationship relationship = returnedProject.getRelationships().get("includedTask");
    Assert.assertNotNull(relationship);
    Assert.assertEquals(task.getId().toString(), relationship.getSingleData().get().getId());
}
Also used : Task(io.crnk.core.mock.models.Task) ResourceInformation(io.crnk.core.engine.information.resource.ResourceInformation) User(io.crnk.core.mock.models.User) FieldResourceGet(io.crnk.core.engine.internal.dispatcher.controller.FieldResourceGet) QueryAdapter(io.crnk.core.engine.query.QueryAdapter) Resource(io.crnk.core.engine.document.Resource) JsonPath(io.crnk.core.engine.internal.dispatcher.path.JsonPath) RelationshipRepositoryAdapter(io.crnk.core.engine.internal.repository.RelationshipRepositoryAdapter) Response(io.crnk.core.engine.dispatcher.Response) Project(io.crnk.core.mock.models.Project) ResourceField(io.crnk.core.engine.information.resource.ResourceField) ResourceRepositoryAdapter(io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter) Relationship(io.crnk.core.engine.document.Relationship) QueryParams(io.crnk.legacy.queryParams.QueryParams) QueryParamsAdapter(io.crnk.legacy.internal.QueryParamsAdapter) BaseControllerTest(io.crnk.core.engine.internal.dispatcher.controller.BaseControllerTest) Test(org.junit.Test)

Example 22 with Response

use of io.crnk.core.engine.dispatcher.Response in project crnk-framework by crnk-project.

the class FieldResourceGetTest method onGivenRequestFieldResourcesGetShouldHandleIt.

@Test
public void onGivenRequestFieldResourcesGetShouldHandleIt() throws Exception {
    // GIVEN
    JsonPath jsonPath = pathBuilder.build("/users/1/assignedProjects");
    FieldResourceGet sut = new FieldResourceGet(resourceRegistry, typeParser, documentMapper);
    // WHEN
    Response response = sut.handle(jsonPath, emptyProjectQuery, null, null);
    // THEN
    Assert.assertNotNull(response);
}
Also used : Response(io.crnk.core.engine.dispatcher.Response) FieldResourceGet(io.crnk.core.engine.internal.dispatcher.controller.FieldResourceGet) JsonPath(io.crnk.core.engine.internal.dispatcher.path.JsonPath) BaseControllerTest(io.crnk.core.engine.internal.dispatcher.controller.BaseControllerTest) Test(org.junit.Test)

Example 23 with Response

use of io.crnk.core.engine.dispatcher.Response in project crnk-framework by crnk-project.

the class OperationsModule method fetchUpToDateResponses.

protected void fetchUpToDateResponses(List<OrderedOperation> orderedOperations, OperationResponse[] responses) {
    RequestDispatcher requestDispatcher = moduleContext.getRequestDispatcher();
    // get current set of resources after all the updates have been applied
    for (OrderedOperation orderedOperation : orderedOperations) {
        Operation operation = orderedOperation.getOperation();
        OperationResponse operationResponse = responses[orderedOperation.getOrdinal()];
        boolean isPost = operation.getOp().equalsIgnoreCase(HttpMethod.POST.toString());
        boolean isPatch = operation.getOp().equalsIgnoreCase(HttpMethod.PATCH.toString());
        if (isPost || isPatch) {
            Resource resource = operationResponse.getSingleData().get();
            String path = resource.getType() + "/" + resource.getId();
            String method = HttpMethod.GET.toString();
            RepositoryMethodParameterProvider parameterProvider = null;
            Map<String, Set<String>> parameters = new HashMap<>();
            parameters.put("include", getLoadedRelationshipNames(resource));
            Response response = requestDispatcher.dispatchRequest(path, method, parameters, parameterProvider, null);
            copyDocument(operationResponse, response.getDocument());
            operationResponse.setIncluded(null);
        }
    }
}
Also used : Response(io.crnk.core.engine.dispatcher.Response) OperationResponse(io.crnk.operations.OperationResponse) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) Resource(io.crnk.core.engine.document.Resource) OrderedOperation(io.crnk.operations.server.order.OrderedOperation) OrderedOperation(io.crnk.operations.server.order.OrderedOperation) Operation(io.crnk.operations.Operation) OperationResponse(io.crnk.operations.OperationResponse) RepositoryMethodParameterProvider(io.crnk.legacy.internal.RepositoryMethodParameterProvider) RequestDispatcher(io.crnk.core.engine.dispatcher.RequestDispatcher)

Example 24 with Response

use of io.crnk.core.engine.dispatcher.Response in project crnk-framework by crnk-project.

the class OperationsModule method executeOperation.

protected OperationResponse executeOperation(Operation operation) {
    RequestDispatcher requestDispatcher = moduleContext.getRequestDispatcher();
    String path = OperationParameterUtils.parsePath(operation.getPath());
    Map<String, Set<String>> parameters = OperationParameterUtils.parseParameters(operation.getPath());
    String method = operation.getOp();
    RepositoryMethodParameterProvider parameterProvider = null;
    Document requestBody = new Document();
    requestBody.setData((Nullable) Nullable.of(operation.getValue()));
    Response response = requestDispatcher.dispatchRequest(path, method, parameters, parameterProvider, requestBody);
    OperationResponse operationResponse = new OperationResponse();
    operationResponse.setStatus(response.getHttpStatus());
    copyDocument(operationResponse, response.getDocument());
    return operationResponse;
}
Also used : Response(io.crnk.core.engine.dispatcher.Response) OperationResponse(io.crnk.operations.OperationResponse) HashSet(java.util.HashSet) Set(java.util.Set) Document(io.crnk.core.engine.document.Document) OperationResponse(io.crnk.operations.OperationResponse) RepositoryMethodParameterProvider(io.crnk.legacy.internal.RepositoryMethodParameterProvider) RequestDispatcher(io.crnk.core.engine.dispatcher.RequestDispatcher)

Example 25 with Response

use of io.crnk.core.engine.dispatcher.Response in project crnk-framework by crnk-project.

the class ResourcePatch method handle.

@Override
public Response handle(JsonPath jsonPath, QueryAdapter queryAdapter, RepositoryMethodParameterProvider parameterProvider, Document requestDocument) {
    RegistryEntry endpointRegistryEntry = getRegistryEntry(jsonPath);
    final Resource resourceBody = getRequestBody(requestDocument, jsonPath, HttpMethod.PATCH);
    RegistryEntry bodyRegistryEntry = resourceRegistry.getEntry(resourceBody.getType());
    String idString = jsonPath.getIds().getIds().get(0);
    ResourceInformation resourceInformation = bodyRegistryEntry.getResourceInformation();
    Serializable resourceId = resourceInformation.parseIdString(idString);
    verifyTypes(HttpMethod.PATCH, endpointRegistryEntry, bodyRegistryEntry);
    ResourceRepositoryAdapter resourceRepository = endpointRegistryEntry.getResourceRepository(parameterProvider);
    JsonApiResponse resourceFindResponse = resourceRepository.findOne(resourceId, queryAdapter);
    Object resource = resourceFindResponse.getEntity();
    if (resource == null) {
        throw new ResourceNotFoundException(jsonPath.toString());
    }
    final Resource resourceFindData = documentMapper.toDocument(resourceFindResponse, queryAdapter, parameterProvider).getSingleData().get();
    resourceInformation.verify(resource, requestDocument);
    // extract current attributes from findOne without any manipulation by query params (such as sparse fieldsets)
    ExceptionUtil.wrapCatchedExceptions(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            String attributesFromFindOne = extractAttributesFromResourceAsJson(resourceFindData);
            Map<String, Object> attributesToUpdate = new HashMap<>(emptyIfNull(objectMapper.readValue(attributesFromFindOne, Map.class)));
            // deserialize the request JSON's attributes object into a map
            String attributesAsJson = objectMapper.writeValueAsString(resourceBody.getAttributes());
            Map<String, Object> attributesFromRequest = emptyIfNull(objectMapper.readValue(attributesAsJson, Map.class));
            // remove attributes that were omitted in the request
            Iterator<String> it = attributesToUpdate.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                if (!attributesFromRequest.containsKey(key)) {
                    it.remove();
                }
            }
            // walk the source map and apply target values from request
            updateValues(attributesToUpdate, attributesFromRequest);
            Map<String, JsonNode> upsertedAttributes = new HashMap<>();
            for (Map.Entry<String, Object> entry : attributesToUpdate.entrySet()) {
                JsonNode value = objectMapper.valueToTree(entry.getValue());
                upsertedAttributes.put(entry.getKey(), value);
            }
            resourceBody.setAttributes(upsertedAttributes);
            return null;
        }
    }, "failed to merge patched attributes");
    JsonApiResponse updatedResource;
    Set<String> loadedRelationshipNames;
    if (resourceInformation.getResourceClass() == Resource.class) {
        loadedRelationshipNames = getLoadedRelationshipNames(resourceBody);
        updatedResource = resourceRepository.update(resourceBody, queryAdapter);
    } else {
        setAttributes(resourceBody, resource, bodyRegistryEntry.getResourceInformation());
        setRelations(resource, bodyRegistryEntry, resourceBody, queryAdapter, parameterProvider, false);
        loadedRelationshipNames = getLoadedRelationshipNames(resourceBody);
        updatedResource = resourceRepository.update(resource, queryAdapter);
    }
    Document responseDocument = documentMapper.toDocument(updatedResource, queryAdapter, parameterProvider, loadedRelationshipNames);
    return new Response(responseDocument, 200);
}
Also used : ResourceInformation(io.crnk.core.engine.information.resource.ResourceInformation) Serializable(java.io.Serializable) Resource(io.crnk.core.engine.document.Resource) JsonNode(com.fasterxml.jackson.databind.JsonNode) Document(io.crnk.core.engine.document.Document) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) ResourceNotFoundException(io.crnk.core.exception.ResourceNotFoundException) IOException(java.io.IOException) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) Response(io.crnk.core.engine.dispatcher.Response) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) ResourceRepositoryAdapter(io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) ResourceNotFoundException(io.crnk.core.exception.ResourceNotFoundException)

Aggregations

Response (io.crnk.core.engine.dispatcher.Response)72 Document (io.crnk.core.engine.document.Document)56 Test (org.junit.Test)54 JsonPath (io.crnk.core.engine.internal.dispatcher.path.JsonPath)52 Resource (io.crnk.core.engine.document.Resource)43 BaseControllerTest (io.crnk.core.engine.internal.dispatcher.controller.BaseControllerTest)41 ResourcePost (io.crnk.core.engine.internal.dispatcher.controller.ResourcePost)30 JsonApiResponse (io.crnk.core.repository.response.JsonApiResponse)18 Project (io.crnk.core.mock.models.Project)15 Relationship (io.crnk.core.engine.document.Relationship)14 ResourceIdentifier (io.crnk.core.engine.document.ResourceIdentifier)14 ResourceField (io.crnk.core.engine.information.resource.ResourceField)12 ResourcePatch (io.crnk.core.engine.internal.dispatcher.controller.ResourcePatch)12 RegistryEntry (io.crnk.core.engine.registry.RegistryEntry)12 Task (io.crnk.core.mock.models.Task)12 ResourceRepositoryAdapter (io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter)11 QuerySpec (io.crnk.core.queryspec.QuerySpec)11 TaskToProjectRepository (io.crnk.core.mock.repository.TaskToProjectRepository)9 QueryParams (io.crnk.legacy.queryParams.QueryParams)9 RelationshipsResourcePost (io.crnk.core.engine.internal.dispatcher.controller.RelationshipsResourcePost)8