Search in sources :

Example 61 with Document

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

the class InconsistentRelationshipTest method check.

private void check(boolean setRelatedEntity, boolean setRelatedId) {
    RelationIdTestResource entity = new RelationIdTestResource();
    entity.setId(2L);
    entity.setName("test");
    if (setRelatedId) {
        entity.setTestResourceIdRefId(new ResourceIdentifier("3", "schedules"));
    }
    if (setRelatedEntity) {
        entity.setTestResourceIdRef(schedule);
    }
    QuerySpec querySpec = new QuerySpec(RelationIdTestResource.class);
    querySpec.includeRelation(Arrays.asList("testResourceIdRef"));
    Document document = mapper.toDocument(toResponse(entity), toAdapter(querySpec));
    Resource resource = document.getSingleData().get();
    Assert.assertEquals("2", resource.getId());
    Assert.assertEquals("relationIdTest", resource.getType());
    Assert.assertEquals("test", resource.getAttributes().get("name").asText());
    Nullable<ResourceIdentifier> data = resource.getRelationships().get("testResourceIdRef").getSingleData();
    Assert.assertTrue(data.isPresent());
    if (setRelatedId) {
        Assert.assertNotNull(data.get());
        Assert.assertEquals(1, document.getIncluded().size());
        Assert.assertEquals("3", document.getIncluded().get(0).getId());
        Assert.assertEquals(setRelatedEntity ? 0 : 1, scheduleRepository.getNumFindAll());
    } else {
        Assert.assertNull(data.get());
        Assert.assertEquals(0, scheduleRepository.getNumFindAll());
    }
}
Also used : ResourceIdentifier(io.crnk.core.engine.document.ResourceIdentifier) RelationIdTestResource(io.crnk.core.mock.models.RelationIdTestResource) Resource(io.crnk.core.engine.document.Resource) QuerySpec(io.crnk.core.queryspec.QuerySpec) Document(io.crnk.core.engine.document.Document) RelationIdTestResource(io.crnk.core.mock.models.RelationIdTestResource)

Example 62 with Document

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

the class BasicSpringBootTest method testErrorsSerializedAsJsonApi.

@Test
public void testErrorsSerializedAsJsonApi() throws IOException {
    RestTemplate testRestTemplate = new RestTemplate();
    try {
        testRestTemplate.getForEntity("http://localhost:" + this.port + "/doesNotExist", String.class);
        Assert.fail();
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());
        String body = e.getResponseBodyAsString();
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(JacksonModule.createJacksonModule());
        Document document = mapper.readerFor(Document.class).readValue(body);
        Assert.assertEquals(1, document.getErrors().size());
        ErrorData errorData = document.getErrors().get(0);
        Assert.assertEquals("404", errorData.getStatus());
        Assert.assertEquals("Not Found", errorData.getTitle());
        Assert.assertEquals("No message available", errorData.getDetail());
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) RestTemplate(org.springframework.web.client.RestTemplate) Document(io.crnk.core.engine.document.Document) ErrorData(io.crnk.core.engine.document.ErrorData) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 63 with Document

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

the class CrnkErrorController method errorToJsonApi.

// TODO for whatever reason this is not called directly
@RequestMapping(produces = HttpHeaders.JSONAPI_CONTENT_TYPE)
@ResponseBody
public ResponseEntity<Document> errorToJsonApi(HttpServletRequest request) {
    Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
    HttpStatus status = getStatus(request);
    ErrorDataBuilder errorDataBuilder = ErrorData.builder();
    for (Map.Entry<String, Object> attribute : body.entrySet()) {
        if (attribute.getKey().equals("status")) {
            errorDataBuilder.setStatus(attribute.getValue().toString());
        } else if (attribute.getKey().equals("error")) {
            errorDataBuilder.setTitle(attribute.getValue().toString());
        } else if (attribute.getKey().equals("message")) {
            errorDataBuilder.setDetail(attribute.getValue().toString());
        } else {
            errorDataBuilder.addMetaField(attribute.getKey(), attribute.getValue());
        }
    }
    Document document = new Document();
    document.setErrors(Arrays.asList(errorDataBuilder.build()));
    return new ResponseEntity<>(document, status);
}
Also used : ErrorDataBuilder(io.crnk.core.engine.document.ErrorDataBuilder) ResponseEntity(org.springframework.http.ResponseEntity) HttpStatus(org.springframework.http.HttpStatus) Document(io.crnk.core.engine.document.Document) Map(java.util.Map) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 64 with Document

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

the class JsonApiRequestProcessor method process.

@Override
public void process(HttpRequestContext requestContext) throws IOException {
    if (isJsonApiRequest(requestContext, isAcceptingPlainJson())) {
        ResourceRegistry resourceRegistry = moduleContext.getResourceRegistry();
        RequestDispatcher requestDispatcher = moduleContext.getRequestDispatcher();
        String path = requestContext.getPath();
        JsonPath jsonPath = new PathBuilder(resourceRegistry).build(path);
        Map<String, Set<String>> parameters = requestContext.getRequestParameters();
        String method = requestContext.getMethod();
        if (jsonPath instanceof ActionPath) {
            // inital implementation, has to improve
            requestDispatcher.dispatchAction(path, method, parameters);
        } else if (jsonPath != null) {
            byte[] requestBody = requestContext.getRequestBody();
            Document document = null;
            if (requestBody != null && requestBody.length > 0) {
                ObjectMapper objectMapper = moduleContext.getObjectMapper();
                try {
                    document = objectMapper.readerFor(Document.class).readValue(requestBody);
                } catch (JsonProcessingException e) {
                    final String message = "Json Parsing failed";
                    setResponse(requestContext, buildBadRequestResponse(message, e.getMessage()));
                    LOGGER.error(message, e);
                    return;
                }
            }
            RepositoryMethodParameterProvider parameterProvider = requestContext.getRequestParameterProvider();
            Response crnkResponse = requestDispatcher.dispatchRequest(path, method, parameters, parameterProvider, document);
            setResponse(requestContext, crnkResponse);
        } else {
        // no repositories invoked, we do nothing
        }
    }
}
Also used : Set(java.util.Set) ActionPath(io.crnk.core.engine.internal.dispatcher.path.ActionPath) ResourceRegistry(io.crnk.core.engine.registry.ResourceRegistry) JsonPath(io.crnk.core.engine.internal.dispatcher.path.JsonPath) Document(io.crnk.core.engine.document.Document) RequestDispatcher(io.crnk.core.engine.dispatcher.RequestDispatcher) Response(io.crnk.core.engine.dispatcher.Response) PathBuilder(io.crnk.core.engine.internal.dispatcher.path.PathBuilder) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) RepositoryMethodParameterProvider(io.crnk.legacy.internal.RepositoryMethodParameterProvider) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 65 with Document

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

the class JsonapiExceptionMapperBridge method toResponse.

@Override
public Response toResponse(RuntimeException exception) {
    CrnkBoot boot = this.feature.getBoot();
    ExceptionMapperRegistry exceptionMapperRegistry = boot.getExceptionMapperRegistry();
    Optional<JsonApiExceptionMapper> optional = exceptionMapperRegistry.findMapperFor(exception.getClass());
    if (!optional.isPresent()) {
        LOGGER.error("no exception mapper found", exception);
        exception = new InternalServerErrorException(exception.getMessage());
        optional = exceptionMapperRegistry.findMapperFor(exception.getClass());
    }
    JsonApiExceptionMapper exceptionMapper = optional.get();
    ErrorResponse errorResponse = exceptionMapper.toErrorResponse(exception);
    // use the Crnk document mapper to create a JSON API response
    Document doc = new Document();
    List<ErrorData> errors = new ArrayList<>();
    for (ErrorData error : errorResponse.getErrors()) {
        errors.add(error);
    }
    doc.setErrors(errors);
    return Response.status(errorResponse.getHttpStatus()).entity(doc).header("Content-Type", JsonApiMediaType.APPLICATION_JSON_API).build();
}
Also used : CrnkBoot(io.crnk.core.boot.CrnkBoot) ArrayList(java.util.ArrayList) InternalServerErrorException(io.crnk.core.exception.InternalServerErrorException) ExceptionMapperRegistry(io.crnk.core.engine.internal.exception.ExceptionMapperRegistry) Document(io.crnk.core.engine.document.Document) JsonApiExceptionMapper(io.crnk.core.engine.error.JsonApiExceptionMapper) ErrorData(io.crnk.core.engine.document.ErrorData) ErrorResponse(io.crnk.core.engine.error.ErrorResponse)

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