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());
}
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);
}
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);
}
}
}
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;
}
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);
}
Aggregations