Search in sources :

Example 36 with Resource

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

the class PersistentResource method toResource.

/**
 * Convert a persistent resource to a resource.
 *
 * @param relationships The relationships
 * @param attributes    The attributes
 * @return The Resource
 */
public Resource toResource(final Map<String, Relationship> relationships, final Map<String, Object> attributes) {
    final Resource resource = new Resource(typeName, (obj == null) ? uuid.orElseThrow(() -> new InvalidEntityBodyException("No id found on object")) : dictionary.getId(obj));
    resource.setRelationships(relationships);
    resource.setAttributes(attributes);
    if (requestScope.getElideSettings().isEnableJsonLinks()) {
        resource.setLinks(requestScope.getElideSettings().getJsonApiLinks().getResourceLevelLinks(this));
    }
    return resource;
}
Also used : InvalidEntityBodyException(com.yahoo.elide.core.exceptions.InvalidEntityBodyException) Resource(com.yahoo.elide.jsonapi.models.Resource)

Example 37 with Resource

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

the class PersistentResource method createObject.

/**
 * Create a resource in the database.
 *
 * @param parent             - The immediate ancestor in the lineage or null if this is a root.
 * @param parentRelationship - The name of the parent relationship traversed to create this object.
 * @param entityClass        the entity class
 * @param requestScope       the request scope
 * @param uuid               the (optional) uuid
 * @param <T>                object type
 * @return persistent resource
 */
public static <T> PersistentResource<T> createObject(PersistentResource<?> parent, String parentRelationship, Type<T> entityClass, RequestScope requestScope, Optional<String> uuid) {
    T obj = requestScope.getTransaction().createNewObject(entityClass, requestScope);
    String id = uuid.orElse(null);
    PersistentResource<T> newResource = new PersistentResource<>(obj, parent, parentRelationship, id, requestScope);
    // The ID must be assigned before we add it to the new resources set.  Persistent resource
    // hashcode and equals are only based on the ID/UUID & type.
    assignId(newResource, id);
    // Keep track of new resources for non-transferable resources
    requestScope.getNewPersistentResources().add(newResource);
    checkPermission(CreatePermission.class, newResource);
    newResource.auditClass(Audit.Action.CREATE, new ChangeSpec(newResource, null, null, newResource.getObject()));
    requestScope.publishLifecycleEvent(newResource, CREATE);
    requestScope.setUUIDForObject(newResource.type, id, newResource.getObject());
    // Initialize null ToMany collections
    requestScope.getDictionary().getRelationships(entityClass).stream().filter(relationName -> newResource.getRelationshipType(relationName).isToMany() && newResource.getValueUnchecked(relationName) == null).forEach(relationName -> newResource.setValue(relationName, new LinkedHashSet<>()));
    newResource.markDirty();
    return newResource;
}
Also used : Resource(com.yahoo.elide.jsonapi.models.Resource) Data(com.yahoo.elide.jsonapi.models.Data) StringUtils(org.apache.commons.lang3.StringUtils) UpdatePermission(com.yahoo.elide.annotation.UpdatePermission) ClassType(com.yahoo.elide.core.type.ClassType) DeletePermission(com.yahoo.elide.annotation.DeletePermission) Argument(com.yahoo.elide.core.request.Argument) InvalidSyntaxException(com.yahoo.elide.core.audit.InvalidSyntaxException) Map(java.util.Map) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) LifeCycleHookBinding(com.yahoo.elide.annotation.LifeCycleHookBinding) EntityBinding(com.yahoo.elide.core.dictionary.EntityBinding) NonNull(lombok.NonNull) Collection(java.util.Collection) Set(java.util.Set) CoerceUtil(com.yahoo.elide.core.utils.coerce.CoerceUtil) Collectors(java.util.stream.Collectors) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) Sets(com.google.common.collect.Sets) Serializable(java.io.Serializable) Objects(java.util.Objects) ExpressionResult(com.yahoo.elide.core.security.permissions.ExpressionResult) List(java.util.List) Annotation(java.lang.annotation.Annotation) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) Optional(java.util.Optional) RelationshipType(com.yahoo.elide.core.dictionary.RelationshipType) Attribute(com.yahoo.elide.core.request.Attribute) InvalidAttributeException(com.yahoo.elide.core.exceptions.InvalidAttributeException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) IterableUtils(org.apache.commons.collections4.IterableUtils) LogMessageImpl(com.yahoo.elide.core.audit.LogMessageImpl) DELETE(com.yahoo.elide.annotation.LifeCycleHookBinding.Operation.DELETE) EntityDictionary.getType(com.yahoo.elide.core.dictionary.EntityDictionary.getType) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) Predicates(com.google.common.base.Predicates) InternalServerErrorException(com.yahoo.elide.core.exceptions.InternalServerErrorException) CanPaginateVisitor(com.yahoo.elide.core.security.visitors.CanPaginateVisitor) Observable(io.reactivex.Observable) LogMessage(com.yahoo.elide.core.audit.LogMessage) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) LinkedHashSet(java.util.LinkedHashSet) UPDATE(com.yahoo.elide.annotation.LifeCycleHookBinding.Operation.UPDATE) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) VerifyFieldAccessFilterExpressionVisitor(com.yahoo.elide.core.filter.visitors.VerifyFieldAccessFilterExpressionVisitor) ChangeSpec(com.yahoo.elide.core.security.ChangeSpec) COLLECTION_TYPE(com.yahoo.elide.core.type.ClassType.COLLECTION_TYPE) Sorting(com.yahoo.elide.core.request.Sorting) InvalidEntityBodyException(com.yahoo.elide.core.exceptions.InvalidEntityBodyException) InvalidObjectIdentifierException(com.yahoo.elide.core.exceptions.InvalidObjectIdentifierException) InPredicate(com.yahoo.elide.core.filter.predicates.InPredicate) EntityProjection(com.yahoo.elide.core.request.EntityProjection) Relationship(com.yahoo.elide.jsonapi.models.Relationship) ForbiddenAccessException(com.yahoo.elide.core.exceptions.ForbiddenAccessException) ReadPermission(com.yahoo.elide.annotation.ReadPermission) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) Pagination(com.yahoo.elide.core.request.Pagination) ResourceIdentifier(com.yahoo.elide.jsonapi.models.ResourceIdentifier) TreeMap(java.util.TreeMap) CreatePermission(com.yahoo.elide.annotation.CreatePermission) CREATE(com.yahoo.elide.annotation.LifeCycleHookBinding.Operation.CREATE) Type(com.yahoo.elide.core.type.Type) Preconditions(com.google.common.base.Preconditions) Comparator(java.util.Comparator) Collections(java.util.Collections) EMPTY_BINDING(com.yahoo.elide.core.dictionary.EntityBinding.EMPTY_BINDING) Audit(com.yahoo.elide.annotation.Audit) NonTransferable(com.yahoo.elide.annotation.NonTransferable) LinkedHashSet(java.util.LinkedHashSet) ChangeSpec(com.yahoo.elide.core.security.ChangeSpec)

Example 38 with Resource

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

the class JSONExportFormatter method resourceToJSON.

public static String resourceToJSON(ObjectMapper mapper, PersistentResource resource) {
    if (resource == null || resource.getObject() == null) {
        return null;
    }
    StringBuilder str = new StringBuilder();
    try {
        Resource jsonResource = resource.toResource(getRelationships(resource), getAttributes(resource));
        str.append(mapper.writeValueAsString(jsonResource.getAttributes()));
    } catch (JsonProcessingException e) {
        log.error("Exception when converting to JSON {}", e.getMessage());
        throw new IllegalStateException(e);
    }
    return str.toString();
}
Also used : Resource(com.yahoo.elide.jsonapi.models.Resource) PersistentResource(com.yahoo.elide.core.PersistentResource) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 39 with Resource

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

the class BaseState method getResponseBody.

protected static JsonNode getResponseBody(PersistentResource resource, RequestScope requestScope) {
    MultivaluedMap<String, String> queryParams = requestScope.getQueryParams();
    JsonApiDocument jsonApiDocument = new JsonApiDocument();
    // TODO Make this a document processor
    Data<Resource> data = resource == null ? null : new Data<>(resource.toResource());
    jsonApiDocument.setData(data);
    // TODO Iterate over set of document processors
    DocumentProcessor includedProcessor = new IncludedProcessor();
    includedProcessor.execute(jsonApiDocument, resource, queryParams);
    return requestScope.getMapper().toJsonObject(jsonApiDocument);
}
Also used : JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) DocumentProcessor(com.yahoo.elide.jsonapi.document.processors.DocumentProcessor) Resource(com.yahoo.elide.jsonapi.models.Resource) PersistentResource(com.yahoo.elide.core.PersistentResource) IncludedProcessor(com.yahoo.elide.jsonapi.document.processors.IncludedProcessor)

Example 40 with Resource

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

the class CollectionTerminalState method createObject.

private PersistentResource createObject(RequestScope requestScope) throws ForbiddenAccessException, InvalidObjectIdentifierException {
    JsonApiDocument doc = requestScope.getJsonApiDocument();
    JsonApiMapper mapper = requestScope.getMapper();
    if (doc.getData() == null) {
        throw new InvalidEntityBodyException("Invalid JSON-API document: " + doc);
    }
    Data<Resource> data = doc.getData();
    Collection<Resource> resources = data.get();
    Resource resource = (resources.size() == 1) ? IterableUtils.first(resources) : null;
    if (resource == null) {
        try {
            throw new InvalidEntityBodyException(mapper.writeJsonApiDocument(doc));
        } catch (JsonProcessingException e) {
            throw new InternalServerErrorException(e);
        }
    }
    String id = resource.getId();
    Type<?> newObjectClass = requestScope.getDictionary().getEntityClass(resource.getType(), requestScope.getApiVersion());
    if (newObjectClass == null) {
        throw new UnknownEntityException("Entity " + resource.getType() + " not found");
    }
    if (!entityClass.isAssignableFrom(newObjectClass)) {
        throw new InvalidValueException("Cannot assign value of type: " + resource.getType() + " to type: " + entityClass);
    }
    PersistentResource pResource = PersistentResource.createObject(parent.orElse(null), relationName.orElse(null), newObjectClass, requestScope, Optional.ofNullable(id));
    Map<String, Object> attributes = resource.getAttributes();
    if (attributes != null) {
        for (Map.Entry<String, Object> entry : attributes.entrySet()) {
            String fieldName = entry.getKey();
            Object val = entry.getValue();
            pResource.updateAttribute(fieldName, val);
        }
    }
    Map<String, Relationship> relationships = resource.getRelationships();
    if (relationships != null) {
        for (Map.Entry<String, Relationship> entry : relationships.entrySet()) {
            String fieldName = entry.getKey();
            Relationship relationship = entry.getValue();
            Set<PersistentResource> resourceSet = (relationship == null) ? null : relationship.toPersistentResources(requestScope);
            pResource.updateRelation(fieldName, resourceSet);
        }
    }
    return pResource;
}
Also used : PersistentResource(com.yahoo.elide.core.PersistentResource) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) UnknownEntityException(com.yahoo.elide.core.exceptions.UnknownEntityException) Resource(com.yahoo.elide.jsonapi.models.Resource) PersistentResource(com.yahoo.elide.core.PersistentResource) ToString(lombok.ToString) InvalidValueException(com.yahoo.elide.core.exceptions.InvalidValueException) InvalidEntityBodyException(com.yahoo.elide.core.exceptions.InvalidEntityBodyException) Relationship(com.yahoo.elide.jsonapi.models.Relationship) InternalServerErrorException(com.yahoo.elide.core.exceptions.InternalServerErrorException) JsonApiMapper(com.yahoo.elide.jsonapi.JsonApiMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Aggregations

Resource (com.yahoo.elide.jsonapi.models.Resource)55 Test (org.junit.jupiter.api.Test)35 JsonApiDocument (com.yahoo.elide.jsonapi.models.JsonApiDocument)31 PersistentResource (com.yahoo.elide.core.PersistentResource)28 Relationship (com.yahoo.elide.jsonapi.models.Relationship)21 ArrayList (java.util.ArrayList)17 ResourceIdentifier (com.yahoo.elide.jsonapi.models.ResourceIdentifier)16 PatchRequestScope (com.yahoo.elide.jsonapi.extensions.PatchRequestScope)13 Data (com.yahoo.elide.jsonapi.models.Data)13 InvalidEntityBodyException (com.yahoo.elide.core.exceptions.InvalidEntityBodyException)9 LinkedHashSet (java.util.LinkedHashSet)9 Parent (example.Parent)8 HashSet (java.util.HashSet)8 EntityProjection (com.yahoo.elide.core.request.EntityProjection)7 Child (example.Child)7 LinkedHashMap (java.util.LinkedHashMap)7 RequestScope (com.yahoo.elide.core.RequestScope)6 TestUser (com.yahoo.elide.core.security.TestUser)6 User (com.yahoo.elide.core.security.User)6 TestRequestScope (com.yahoo.elide.core.TestRequestScope)5