Search in sources :

Example 31 with Resource

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

the class PersistentResourceTest method testRelationshipMissingData.

/**
 * Verify that Relationship toMany cannot contain null resources, but toOne can.
 *
 * @throws Exception
 */
@Test
public void testRelationshipMissingData() throws Exception {
    User goodUser = new TestUser("1");
    @SuppressWarnings("resource") DataStoreTransaction tx = mock(DataStoreTransaction.class);
    RequestScope goodScope = new RequestScope(null, null, NO_VERSION, null, tx, goodUser, null, null, UUID.randomUUID(), elideSettings);
    // null resource in toMany relationship is not valid
    List<Resource> idList = new ArrayList<>();
    idList.add(new ResourceIdentifier("child", "3").castToResource());
    idList.add(new ResourceIdentifier("child", "6").castToResource());
    idList.add(null);
    assertThrows(NullPointerException.class, () -> new Relationship(Collections.emptyMap(), new Data<>(idList)));
    // However null toOne relationship is valid
    Relationship toOneRelationship = new Relationship(Collections.emptyMap(), new Data<>((Resource) null));
    assertTrue(toOneRelationship.getData().get().isEmpty());
    assertNull(toOneRelationship.toPersistentResources(goodScope));
    // no Data
    Relationship nullRelationship = new Relationship(Collections.emptyMap(), null);
    assertNull(nullRelationship.getData());
    assertNull(nullRelationship.toPersistentResources(goodScope));
}
Also used : ResourceIdentifier(com.yahoo.elide.jsonapi.models.ResourceIdentifier) TestUser(com.yahoo.elide.core.security.TestUser) User(com.yahoo.elide.core.security.User) Relationship(com.yahoo.elide.jsonapi.models.Relationship) Resource(com.yahoo.elide.jsonapi.models.Resource) ArrayList(java.util.ArrayList) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) Data(com.yahoo.elide.jsonapi.models.Data) TestUser(com.yahoo.elide.core.security.TestUser) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) Test(org.junit.jupiter.api.Test)

Example 32 with Resource

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

the class PersistentResourceTest method testSuccessfulOneToOneRelationshipAddNull.

/**
 * Avoid NPE when PATCH or POST defines relationship with null id
 * <pre>
 * <code>
 * "relationships": {
 *   "left": {
 *     "data": {
 *       "type": "right",
 *       "id": null
 *     }
 *   }
 * }
 * </code>
 * </pre>
 */
@Test
public void testSuccessfulOneToOneRelationshipAddNull() throws Exception {
    Left left = new Left();
    left.setId(2);
    RequestScope goodScope = buildRequestScope(tx, goodUser);
    PersistentResource<Left> leftResource = new PersistentResource<>(left, "2", goodScope);
    Relationship ids = new Relationship(null, new Data<>(new Resource("right", null, null, null, null, null)));
    InvalidObjectIdentifierException thrown = assertThrows(InvalidObjectIdentifierException.class, () -> leftResource.updateRelation("one2one", ids.toPersistentResources(goodScope)));
    assertEquals("Unknown identifier null for right", thrown.getMessage());
}
Also used : Left(example.Left) Relationship(com.yahoo.elide.jsonapi.models.Relationship) Resource(com.yahoo.elide.jsonapi.models.Resource) InvalidObjectIdentifierException(com.yahoo.elide.core.exceptions.InvalidObjectIdentifierException) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) Test(org.junit.jupiter.api.Test)

Example 33 with Resource

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

the class PersistentResourceTest method testTransferPermissionSuccessOnUpdateSingularRelationship.

@Test
public void testTransferPermissionSuccessOnUpdateSingularRelationship() {
    example.User userModel = new example.User();
    userModel.setId(1);
    NoShareEntity noShare = new NoShareEntity();
    /* The noshare already exists so no exception should be thrown */
    userModel.setNoShare(noShare);
    List<Resource> idList = new ArrayList<>();
    idList.add(new ResourceIdentifier("noshare", "1").castToResource());
    Relationship ids = new Relationship(null, new Data<>(idList));
    when(tx.getToOneRelation(any(), eq(userModel), any(), any())).thenReturn(noShare);
    when(tx.loadObject(any(), eq(1L), any())).thenReturn(noShare);
    RequestScope goodScope = buildRequestScope(tx, goodUser);
    PersistentResource<example.User> userResource = new PersistentResource<>(userModel, goodScope.getUUIDFor(userModel), goodScope);
    boolean returnVal = userResource.updateRelation("noShare", ids.toPersistentResources(goodScope));
    assertFalse(returnVal);
    assertEquals(noShare, userModel.getNoShare());
}
Also used : TestUser(com.yahoo.elide.core.security.TestUser) User(com.yahoo.elide.core.security.User) Resource(com.yahoo.elide.jsonapi.models.Resource) ArrayList(java.util.ArrayList) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) ResourceIdentifier(com.yahoo.elide.jsonapi.models.ResourceIdentifier) Relationship(com.yahoo.elide.jsonapi.models.Relationship) NoShareEntity(example.NoShareEntity) Test(org.junit.jupiter.api.Test)

Example 34 with Resource

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

the class DataDeserializer method deserialize.

@Override
public Data<Resource> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    if (node.isArray()) {
        List<Resource> resources = new ArrayList<>();
        for (JsonNode n : node) {
            Resource r = MAPPER.convertValue(n, Resource.class);
            validateResource(jsonParser, r);
            resources.add(r);
        }
        return new Data<>(resources);
    }
    Resource resource = MAPPER.convertValue(node, Resource.class);
    validateResource(jsonParser, resource);
    return new Data<>(resource);
}
Also used : Resource(com.yahoo.elide.jsonapi.models.Resource) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) Data(com.yahoo.elide.jsonapi.models.Data)

Example 35 with Resource

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

the class PersistentResource method getRelation.

/**
 * Load a relation from the PersistentResource.
 *
 * @param relationship the relation
 * @param ids          a list of object identifiers to optionally load.  Can be empty.
 * @return PersistentResource relation
 */
public Observable<PersistentResource> getRelation(List<String> ids, com.yahoo.elide.core.request.Relationship relationship) {
    FilterExpression filterExpression = Optional.ofNullable(relationship.getProjection().getFilterExpression()).orElse(null);
    assertPropertyExists(relationship.getName());
    Type<?> entityType = dictionary.getParameterizedType(getResourceType(), relationship.getName());
    Set<PersistentResource> newResources = new LinkedHashSet<>();
    /* If this is a bulk edit request and the ID we are fetching for is newly created... */
    if (!ids.isEmpty()) {
        // Fetch our set of new resources that we know about since we can't find them in the datastore
        newResources = requestScope.getNewPersistentResources().stream().filter(resource -> entityType.isAssignableFrom(resource.getResourceType()) && ids.contains(resource.getUUID().orElse(""))).collect(Collectors.toSet());
        FilterExpression idExpression = buildIdFilterExpression(ids, entityType, dictionary, requestScope);
        // Combine filters if necessary
        filterExpression = Optional.ofNullable(relationship.getProjection().getFilterExpression()).map(fe -> (FilterExpression) new AndFilterExpression(idExpression, fe)).orElse(idExpression);
    }
    // TODO: Filter on new resources?
    // TODO: Update pagination to subtract the number of new resources created?
    Observable<PersistentResource> existingResources = filter(ReadPermission.class, Optional.ofNullable(filterExpression), relationship.getProjection().getRequestedFields(), getRelation(relationship.copyOf().projection(relationship.getProjection().copyOf().filterExpression(filterExpression).build()).build(), true));
    // TODO: Sort again in memory now that two sets are glommed together?
    Observable<PersistentResource> allResources = Observable.fromIterable(newResources).mergeWith(existingResources);
    Set<String> foundIds = new HashSet<>();
    allResources = allResources.doOnNext((resource) -> {
        String id = (String) (resource.getUUID().orElseGet(resource::getId));
        if (ids.contains(id)) {
            foundIds.add(id);
        }
    });
    allResources = allResources.doOnComplete(() -> {
        Set<String> missedIds = Sets.difference(new HashSet<>(ids), foundIds);
        if (!missedIds.isEmpty()) {
            throw new InvalidObjectIdentifierException(missedIds.toString(), relationship.getName());
        }
    });
    return allResources;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) 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) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) InvalidObjectIdentifierException(com.yahoo.elide.core.exceptions.InvalidObjectIdentifierException) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

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