Search in sources :

Example 6 with ResourceNotFoundException

use of io.crnk.core.exception.ResourceNotFoundException in project crnk-framework by crnk-project.

the class MetaRelationshipRepositoryImpl method getSource.

private MetaElement getSource(String sourceId) {
    MetaLookup lookup = lookupSupplier.get();
    MetaElement source = lookup.getMetaById().get(sourceId);
    if (source == null) {
        throw new ResourceNotFoundException(sourceId);
    }
    return source;
}
Also used : MetaLookup(io.crnk.meta.MetaLookup) MetaElement(io.crnk.meta.model.MetaElement) ResourceNotFoundException(io.crnk.core.exception.ResourceNotFoundException)

Example 7 with ResourceNotFoundException

use of io.crnk.core.exception.ResourceNotFoundException 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 8 with ResourceNotFoundException

use of io.crnk.core.exception.ResourceNotFoundException 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 9 with ResourceNotFoundException

use of io.crnk.core.exception.ResourceNotFoundException in project crnk-framework by crnk-project.

the class ClientStubBaseTest method checkBodyWithErrors.

@Test
public void checkBodyWithErrors() throws IOException {
    Document document = new Document();
    ErrorData errorData = new ErrorDataBuilder().setCode("404").setDetail("detail").build();
    document.setErrors(Arrays.asList(errorData));
    String body = client.getObjectMapper().writeValueAsString(document);
    HttpAdapterResponse response = Mockito.mock(HttpAdapterResponse.class);
    Mockito.when(response.body()).thenReturn(body);
    Mockito.when(response.getResponseHeader(HttpHeaders.HTTP_CONTENT_TYPE)).thenReturn(HttpHeaders.JSONAPI_CONTENT_TYPE);
    Mockito.when(response.code()).thenReturn(404);
    RuntimeException exception = stub.handleError(response);
    Assert.assertTrue(exception instanceof ResourceNotFoundException);
    Assert.assertEquals("detail", exception.getMessage());
}
Also used : ErrorDataBuilder(io.crnk.core.engine.document.ErrorDataBuilder) HttpAdapterResponse(io.crnk.client.http.HttpAdapterResponse) Document(io.crnk.core.engine.document.Document) ResourceNotFoundException(io.crnk.core.exception.ResourceNotFoundException) ErrorData(io.crnk.core.engine.document.ErrorData) Test(org.junit.Test)

Example 10 with ResourceNotFoundException

use of io.crnk.core.exception.ResourceNotFoundException in project crnk-framework by crnk-project.

the class ResourceRepositoryAdapter method findOne.

public JsonApiResponse findOne(I id, QueryAdapter queryAdapter) {
    RepositoryRequestFilterChainImpl chain = new RepositoryRequestFilterChainImpl() {

        @SuppressWarnings("rawtypes")
        @Override
        protected JsonApiResponse invoke(RepositoryFilterContext context) {
            RepositoryRequestSpec request = context.getRequest();
            QueryAdapter queryAdapter = request.getQueryAdapter();
            Serializable id = request.getId();
            Object resource;
            if (isAnnotated) {
                resource = ((AnnotatedResourceRepositoryAdapter) resourceRepository).findOne(id, queryAdapter);
            } else if (resourceRepository instanceof ResourceRepositoryV2) {
                resource = ((ResourceRepositoryV2) resourceRepository).findOne(id, request.getQuerySpec(resourceInformation));
            } else {
                resource = ((ResourceRepository) resourceRepository).findOne(id, request.getQueryParams());
            }
            if (resource == null && return404OnNull) {
                throw new ResourceNotFoundException(resourceInformation.getResourceType());
            }
            return getResponse(resourceRepository, resource, request);
        }
    };
    RepositoryRequestSpec requestSpec = RepositoryRequestSpecImpl.forFindId(moduleRegistry, resourceInformation, queryAdapter, id);
    return chain.doFilter(newRepositoryFilterContext(requestSpec));
}
Also used : Serializable(java.io.Serializable) RepositoryRequestSpec(io.crnk.core.engine.dispatcher.RepositoryRequestSpec) QueryAdapter(io.crnk.core.engine.query.QueryAdapter) ResourceRepositoryV2(io.crnk.core.repository.ResourceRepositoryV2) RepositoryFilterContext(io.crnk.core.engine.filter.RepositoryFilterContext) ResourceRepository(io.crnk.legacy.repository.ResourceRepository) ResourceNotFoundException(io.crnk.core.exception.ResourceNotFoundException)

Aggregations

ResourceNotFoundException (io.crnk.core.exception.ResourceNotFoundException)18 Test (org.junit.Test)7 RegistryEntry (io.crnk.core.engine.registry.RegistryEntry)6 QuerySpec (io.crnk.core.queryspec.QuerySpec)5 Document (io.crnk.core.engine.document.Document)4 Serializable (java.io.Serializable)4 HttpAdapterResponse (io.crnk.client.http.HttpAdapterResponse)3 Response (io.crnk.core.engine.dispatcher.Response)3 ResourceInformation (io.crnk.core.engine.information.resource.ResourceInformation)3 ResourceRepositoryAdapter (io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter)3 JsonApiResponse (io.crnk.core.repository.response.JsonApiResponse)3 ApproveTask (io.crnk.activiti.example.model.ApproveTask)2 ErrorData (io.crnk.core.engine.document.ErrorData)2 ErrorDataBuilder (io.crnk.core.engine.document.ErrorDataBuilder)2 Resource (io.crnk.core.engine.document.Resource)2 MetaLookup (io.crnk.meta.MetaLookup)2 MetaElement (io.crnk.meta.model.MetaElement)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ScheduleApprovalProcessInstance (io.crnk.activiti.example.model.ScheduleApprovalProcessInstance)1 RepositoryRequestSpec (io.crnk.core.engine.dispatcher.RepositoryRequestSpec)1