Search in sources :

Example 11 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class CollectionTerminalState method handlePost.

@Override
public Supplier<Pair<Integer, JsonNode>> handlePost(StateContext state) {
    RequestScope requestScope = state.getRequestScope();
    JsonApiMapper mapper = requestScope.getMapper();
    newObject = createObject(requestScope);
    parent.ifPresent(persistentResource -> persistentResource.addRelation(relationName.get(), newObject));
    return () -> {
        JsonApiDocument returnDoc = new JsonApiDocument();
        returnDoc.setData(new Data<>(newObject.toResource()));
        JsonNode responseBody = mapper.getObjectMapper().convertValue(returnDoc, JsonNode.class);
        return Pair.of(HttpStatus.SC_CREATED, responseBody);
    };
}
Also used : JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) Data(com.yahoo.elide.jsonapi.models.Data) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonApiMapper(com.yahoo.elide.jsonapi.JsonApiMapper) RequestScope(com.yahoo.elide.core.RequestScope)

Example 12 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class CollectionTerminalState method handleGet.

@Override
public Supplier<Pair<Integer, JsonNode>> handleGet(StateContext state) {
    JsonApiDocument jsonApiDocument = new JsonApiDocument();
    RequestScope requestScope = state.getRequestScope();
    MultivaluedMap<String, String> queryParams = requestScope.getQueryParams();
    Set<PersistentResource> collection = getResourceCollection(requestScope).toList(LinkedHashSet::new).blockingGet();
    // Set data
    jsonApiDocument.setData(getData(collection, requestScope.getDictionary()));
    // Run include processor
    DocumentProcessor includedProcessor = new IncludedProcessor();
    includedProcessor.execute(jsonApiDocument, collection, queryParams);
    Pagination pagination = parentProjection.getPagination();
    if (parent.isPresent()) {
        pagination = parentProjection.getRelationship(relationName.orElseThrow(IllegalStateException::new)).get().getProjection().getPagination();
    }
    // Add pagination meta data
    if (!pagination.isDefaultInstance()) {
        Map<String, Number> pageMetaData = new HashMap<>();
        pageMetaData.put("number", (pagination.getOffset() / pagination.getLimit()) + 1);
        pageMetaData.put("limit", pagination.getLimit());
        // Get total records if it has been requested and add to the page meta data
        if (pagination.returnPageTotals()) {
            Long totalRecords = pagination.getPageTotals();
            pageMetaData.put("totalPages", totalRecords / pagination.getLimit() + ((totalRecords % pagination.getLimit()) > 0 ? 1 : 0));
            pageMetaData.put("totalRecords", totalRecords);
        }
        Map<String, Object> allMetaData = new HashMap<>();
        allMetaData.put("page", pageMetaData);
        Meta meta = new Meta(allMetaData);
        jsonApiDocument.setMeta(meta);
    }
    JsonNode responseBody = requestScope.getMapper().toJsonObject(jsonApiDocument);
    return () -> Pair.of(HttpStatus.SC_OK, responseBody);
}
Also used : PersistentResource(com.yahoo.elide.core.PersistentResource) Meta(com.yahoo.elide.jsonapi.models.Meta) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) DocumentProcessor(com.yahoo.elide.jsonapi.document.processors.DocumentProcessor) HashMap(java.util.HashMap) JsonNode(com.fasterxml.jackson.databind.JsonNode) ToString(lombok.ToString) RequestScope(com.yahoo.elide.core.RequestScope) Pagination(com.yahoo.elide.core.request.Pagination) IncludedProcessor(com.yahoo.elide.jsonapi.document.processors.IncludedProcessor)

Example 13 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class RecordTerminalState method handlePatch.

@Override
public Supplier<Pair<Integer, JsonNode>> handlePatch(StateContext state) {
    JsonApiDocument jsonApiDocument = state.getJsonApiDocument();
    Data<Resource> data = jsonApiDocument.getData();
    if (data == null) {
        throw new InvalidEntityBodyException("Expected data but found null");
    }
    if (!data.isToOne()) {
        throw new InvalidEntityBodyException("Expected single element but found list");
    }
    Resource resource = data.getSingleValue();
    if (!record.matchesId(resource.getId())) {
        throw new InvalidEntityBodyException("Id in response body does not match requested id to update from path");
    }
    patch(resource, state.getRequestScope());
    return constructPatchResponse(record, state);
}
Also used : InvalidEntityBodyException(com.yahoo.elide.core.exceptions.InvalidEntityBodyException) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) Resource(com.yahoo.elide.jsonapi.models.Resource) PersistentResource(com.yahoo.elide.core.PersistentResource)

Example 14 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class JsonApiPatch method handleRemoveOp.

/**
 * Remove data via patch extension.
 */
private Supplier<Pair<Integer, JsonNode>> handleRemoveOp(String path, JsonNode patchValue, PatchRequestScope requestScope) {
    try {
        JsonApiDocument value = requestScope.getMapper().readJsonApiPatchExtValue(patchValue);
        String fullPath;
        if (path.contains("relationships")) {
            // Reserved keyword for relationships
            fullPath = path;
        } else {
            Data<Resource> data = value.getData();
            if (data == null || data.get() == null) {
                fullPath = path;
            } else {
                Collection<Resource> resources = data.get();
                String id = getSingleResource(resources).getId();
                fullPath = path + "/" + id;
            }
        }
        DeleteVisitor visitor = new DeleteVisitor(new PatchRequestScope(path, value, requestScope));
        return visitor.visit(JsonApiParser.parse(fullPath));
    } catch (IOException e) {
        throw new InvalidEntityBodyException("Could not parse patch extension value: " + patchValue);
    }
}
Also used : InvalidEntityBodyException(com.yahoo.elide.core.exceptions.InvalidEntityBodyException) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) Resource(com.yahoo.elide.jsonapi.models.Resource) IOException(java.io.IOException) DeleteVisitor(com.yahoo.elide.jsonapi.parser.DeleteVisitor)

Example 15 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class Elide method get.

/**
 * Handle GET.
 *
 * @param baseUrlEndPoint base URL with prefix endpoint
 * @param path the path
 * @param queryParams the query params
 * @param requestHeaders the request headers
 * @param opaqueUser the opaque user
 * @param apiVersion the API version
 * @param requestId the request ID
 * @return Elide response object
 */
public ElideResponse get(String baseUrlEndPoint, String path, MultivaluedMap<String, String> queryParams, Map<String, List<String>> requestHeaders, User opaqueUser, String apiVersion, UUID requestId) {
    if (elideSettings.isStrictQueryParams()) {
        try {
            verifyQueryParams(queryParams);
        } catch (BadRequestException e) {
            return buildErrorResponse(e, false);
        }
    }
    return handleRequest(true, opaqueUser, dataStore::beginReadTransaction, requestId, (tx, user) -> {
        JsonApiDocument jsonApiDoc = new JsonApiDocument();
        RequestScope requestScope = new RequestScope(baseUrlEndPoint, path, apiVersion, jsonApiDoc, tx, user, queryParams, requestHeaders, requestId, elideSettings);
        requestScope.setEntityProjection(new EntityProjectionMaker(elideSettings.getDictionary(), requestScope).parsePath(path));
        BaseVisitor visitor = new GetVisitor(requestScope);
        return visit(path, requestScope, visitor);
    });
}
Also used : JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) BaseVisitor(com.yahoo.elide.jsonapi.parser.BaseVisitor) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) GetVisitor(com.yahoo.elide.jsonapi.parser.GetVisitor) EntityProjectionMaker(com.yahoo.elide.jsonapi.EntityProjectionMaker) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) RequestScope(com.yahoo.elide.core.RequestScope)

Aggregations

JsonApiDocument (com.yahoo.elide.jsonapi.models.JsonApiDocument)51 Resource (com.yahoo.elide.jsonapi.models.Resource)31 Test (org.junit.jupiter.api.Test)26 PersistentResource (com.yahoo.elide.core.PersistentResource)25 RequestScope (com.yahoo.elide.core.RequestScope)15 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)9 Data (com.yahoo.elide.jsonapi.models.Data)8 IOException (java.io.IOException)7 TestRequestScope (com.yahoo.elide.core.TestRequestScope)6 Parent (example.Parent)6 InvalidEntityBodyException (com.yahoo.elide.core.exceptions.InvalidEntityBodyException)5 EntityProjectionMaker (com.yahoo.elide.jsonapi.EntityProjectionMaker)4 PatchRequestScope (com.yahoo.elide.jsonapi.extensions.PatchRequestScope)4 Relationship (com.yahoo.elide.jsonapi.models.Relationship)4 BaseVisitor (com.yahoo.elide.jsonapi.parser.BaseVisitor)4 Child (example.Child)4 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)3 JsonApiMapper (com.yahoo.elide.jsonapi.JsonApiMapper)3 DocumentProcessor (com.yahoo.elide.jsonapi.document.processors.DocumentProcessor)3 IncludedProcessor (com.yahoo.elide.jsonapi.document.processors.IncludedProcessor)3