Search in sources :

Example 21 with Document

use of io.crnk.core.engine.document.Document in project crnk-framework by crnk-project.

the class PerTypeIncludeBehaviorTest method includeParentChildren.

@Test
public void includeParentChildren() throws Exception {
    QuerySpec querySpec = new QuerySpec(HierarchicalTask.class);
    querySpec.includeRelation(Arrays.asList("parent", "children"));
    Document document = mapper.toDocument(toResponse(h11), toAdapter(querySpec));
    Resource taskResource = document.getSingleData().get();
    Relationship parentRelationship = taskResource.getRelationships().get("parent");
    assertNotNull(parentRelationship);
    assertNotNull(parentRelationship.getSingleData());
    ResourceIdentifier parentResource = parentRelationship.getSingleData().get();
    assertNotNull(h1.getId().toString(), parentResource.getId());
    List<Resource> included = document.getIncluded();
    // both parent and children recursively included
    assertEquals(3, included.size());
}
Also used : ResourceIdentifier(io.crnk.core.engine.document.ResourceIdentifier) Relationship(io.crnk.core.engine.document.Relationship) Resource(io.crnk.core.engine.document.Resource) QuerySpec(io.crnk.core.queryspec.QuerySpec) Document(io.crnk.core.engine.document.Document) Test(org.junit.Test)

Example 22 with Document

use of io.crnk.core.engine.document.Document in project crnk-framework by crnk-project.

the class PerTypeIncludeBehaviorTest method includeCyclicParent.

@Test
public void includeCyclicParent() throws Exception {
    h.setParent(h1);
    QuerySpec querySpec = new QuerySpec(HierarchicalTask.class);
    querySpec.includeRelation(Arrays.asList("parent"));
    Document document = mapper.toDocument(toResponse(h1), toAdapter(querySpec));
    Resource taskResource = document.getSingleData().get();
    Relationship parentRelationship = taskResource.getRelationships().get("parent");
    assertNotNull(parentRelationship);
    assertNotNull(parentRelationship.getSingleData());
    ResourceIdentifier parentResource = parentRelationship.getSingleData().get();
    assertNotNull(h.getId().toString(), parentResource.getId());
    List<Resource> included = document.getIncluded();
    assertEquals(1, included.size());
    assertNotNull(h.getId().toString(), included.get(0).getId());
    Relationship rootParent = included.get(0).getRelationships().get("parent");
    assertTrue(rootParent.getSingleData().isPresent());
    assertNotNull(h1.getId().toString(), rootParent.getSingleData().get().getId());
}
Also used : ResourceIdentifier(io.crnk.core.engine.document.ResourceIdentifier) Relationship(io.crnk.core.engine.document.Relationship) Resource(io.crnk.core.engine.document.Resource) QuerySpec(io.crnk.core.queryspec.QuerySpec) Document(io.crnk.core.engine.document.Document) Test(org.junit.Test)

Example 23 with Document

use of io.crnk.core.engine.document.Document 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 24 with Document

use of io.crnk.core.engine.document.Document 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)

Example 25 with Document

use of io.crnk.core.engine.document.Document 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)

Aggregations

Document (io.crnk.core.engine.document.Document)131 Test (org.junit.Test)95 Resource (io.crnk.core.engine.document.Resource)87 Response (io.crnk.core.engine.dispatcher.Response)56 JsonPath (io.crnk.core.engine.internal.dispatcher.path.JsonPath)47 QuerySpec (io.crnk.core.queryspec.QuerySpec)45 ResourceIdentifier (io.crnk.core.engine.document.ResourceIdentifier)40 BaseControllerTest (io.crnk.core.engine.internal.dispatcher.controller.BaseControllerTest)40 Relationship (io.crnk.core.engine.document.Relationship)39 ResourcePost (io.crnk.core.engine.internal.dispatcher.controller.ResourcePost)35 Task (io.crnk.core.mock.models.Task)34 Project (io.crnk.core.mock.models.Project)27 JsonApiResponse (io.crnk.core.repository.response.JsonApiResponse)25 LazyTask (io.crnk.core.mock.models.LazyTask)17 ResourcePatch (io.crnk.core.engine.internal.dispatcher.controller.ResourcePatch)14 RelationIdTestResource (io.crnk.core.mock.models.RelationIdTestResource)12 ResourceField (io.crnk.core.engine.information.resource.ResourceField)11 RegistryEntry (io.crnk.core.engine.registry.RegistryEntry)11 RelationshipsResourcePost (io.crnk.core.engine.internal.dispatcher.controller.RelationshipsResourcePost)10 AbstractDocumentMapperTest (io.crnk.core.engine.internal.document.mapper.AbstractDocumentMapperTest)10