Search in sources :

Example 51 with RequestScope

use of com.yahoo.elide.core.RequestScope 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 52 with RequestScope

use of com.yahoo.elide.core.RequestScope in project elide by yahoo.

the class FilteredIteratorTest method testFilteredResult.

@Test
public void testFilteredResult() throws Exception {
    EntityDictionary dictionary = EntityDictionary.builder().build();
    dictionary.bindEntity(Book.class);
    Book book1 = new Book();
    book1.setTitle("foo");
    Book book2 = new Book();
    book2.setTitle("bar");
    Book book3 = new Book();
    book3.setTitle("foobar");
    List<Book> books = List.of(book1, book2, book3);
    RSQLFilterDialect filterDialect = RSQLFilterDialect.builder().dictionary(dictionary).build();
    FilterExpression expression = filterDialect.parse(ClassType.of(Book.class), new HashSet<>(), "title==*bar", NO_VERSION);
    RequestScope scope = new TestRequestScope(null, null, dictionary);
    Iterator<Book> bookIterator = new FilteredIterator<>(expression, scope, books.iterator());
    assertTrue(bookIterator.hasNext());
    assertEquals("bar", bookIterator.next().getTitle());
    assertTrue(bookIterator.hasNext());
    assertEquals("foobar", bookIterator.next().getTitle());
    assertFalse(bookIterator.hasNext());
}
Also used : TestRequestScope(com.yahoo.elide.core.TestRequestScope) Book(example.Book) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) RSQLFilterDialect(com.yahoo.elide.core.filter.dialect.RSQLFilterDialect) RequestScope(com.yahoo.elide.core.RequestScope) TestRequestScope(com.yahoo.elide.core.TestRequestScope) Test(org.junit.jupiter.api.Test)

Example 53 with RequestScope

use of com.yahoo.elide.core.RequestScope in project elide by yahoo.

the class PersistentResourceFetcher method fetchObject.

/**
 * Fetches a root-level entity.
 * @param requestScope Request scope
 * @param projection constructed entityProjection for a class
 * @param ids List of ids (can be NULL)
 * @return {@link PersistentResource} object(s)
 */
public static ConnectionContainer fetchObject(RequestScope requestScope, EntityProjection projection, Optional<List<String>> ids) {
    EntityDictionary dictionary = requestScope.getDictionary();
    String typeName = dictionary.getJsonAliasFor(projection.getType());
    /* fetching a collection */
    Observable<PersistentResource> records = ids.map((idList) -> {
        /* handle empty list of ids */
        if (idList.isEmpty()) {
            throw new BadRequestException("Empty list passed to ids");
        }
        return PersistentResource.loadRecords(projection, idList, requestScope);
    }).orElseGet(() -> PersistentResource.loadRecords(projection, new ArrayList<>(), requestScope));
    return new ConnectionContainer(records.toList(LinkedHashSet::new).blockingGet(), Optional.ofNullable(projection.getPagination()), typeName);
}
Also used : MapEntryContainer(com.yahoo.elide.graphql.containers.MapEntryContainer) OperationDefinition(graphql.language.OperationDefinition) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) ConnectionContainer(com.yahoo.elide.graphql.containers.ConnectionContainer) ClassType(com.yahoo.elide.core.type.ClassType) ArrayList(java.util.ArrayList) Map(java.util.Map) PersistentResource(com.yahoo.elide.core.PersistentResource) DataFetcher(graphql.schema.DataFetcher) Relationship(com.yahoo.elide.core.request.Relationship) Observable(io.reactivex.Observable) LinkedHashSet(java.util.LinkedHashSet) RequestScope(com.yahoo.elide.core.RequestScope) ARGUMENT_OPERATION(com.yahoo.elide.graphql.ModelBuilder.ARGUMENT_OPERATION) FETCH(com.yahoo.elide.graphql.RelationshipOp.FETCH) InvalidObjectIdentifierException(com.yahoo.elide.core.exceptions.InvalidObjectIdentifierException) Set(java.util.Set) EntityProjection(com.yahoo.elide.core.request.EntityProjection) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) InvalidValueException(com.yahoo.elide.core.exceptions.InvalidValueException) Type(com.yahoo.elide.core.type.Type) Optional(java.util.Optional) GraphQLContainer(com.yahoo.elide.graphql.containers.GraphQLContainer) Queue(java.util.Queue) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) LinkedHashSet(java.util.LinkedHashSet) PersistentResource(com.yahoo.elide.core.PersistentResource) ConnectionContainer(com.yahoo.elide.graphql.containers.ConnectionContainer) ArrayList(java.util.ArrayList) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary)

Example 54 with RequestScope

use of com.yahoo.elide.core.RequestScope in project elide by yahoo.

the class PersistentResourceFetcher method upsertObject.

/**
 * updates or creates existing/new entities.
 * @param entity Resource entity
 * @param context The request context
 * @return {@link PersistentResource} object
 */
private PersistentResource upsertObject(Entity entity, Environment context) {
    Set<Entity.Attribute> attributes = entity.getAttributes();
    Optional<String> id = entity.getId();
    RequestScope requestScope = entity.getRequestScope();
    PersistentResource upsertedResource;
    EntityDictionary dictionary = requestScope.getDictionary();
    PersistentResource parentResource = entity.getParentResource().map(Entity::toPersistentResource).orElse(null);
    if (!id.isPresent()) {
        // If the ID is generated, it is safe to assign a temporary UUID.  Otherwise the client must provide one.
        if (dictionary.isIdGenerated(entity.getEntityClass())) {
            // Assign a temporary UUID.
            entity.setId();
            id = entity.getId();
        }
        upsertedResource = PersistentResource.createObject(parentResource, context.field.getName(), entity.getEntityClass(), requestScope, id);
    } else {
        try {
            Set<PersistentResource> loadedResource = fetchObject(requestScope, entity.getProjection(), Optional.of(Collections.singletonList(id.get()))).getPersistentResources();
            upsertedResource = loadedResource.iterator().next();
        // The ID doesn't exist yet.  Let's create the object.
        } catch (InvalidObjectIdentifierException | InvalidValueException e) {
            upsertedResource = PersistentResource.createObject(parentResource, context.field.getName(), entity.getEntityClass(), requestScope, id);
        }
    }
    return updateAttributes(upsertedResource, entity, attributes);
}
Also used : InvalidValueException(com.yahoo.elide.core.exceptions.InvalidValueException) PersistentResource(com.yahoo.elide.core.PersistentResource) InvalidObjectIdentifierException(com.yahoo.elide.core.exceptions.InvalidObjectIdentifierException) RequestScope(com.yahoo.elide.core.RequestScope) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary)

Example 55 with RequestScope

use of com.yahoo.elide.core.RequestScope in project elide by yahoo.

the class NoopTransactionTest method setup.

@BeforeAll
public void setup() {
    dictionary = EntityDictionary.builder().build();
    dictionary.bindEntity(NoopBean.class);
    requestScope = mock(RequestScope.class);
    JsonApiMapper mapper = mock(JsonApiMapper.class);
    when(requestScope.getDictionary()).thenReturn(dictionary);
    when(requestScope.getObjectEntityCache()).thenReturn(new ObjectEntityCache());
    when(requestScope.getMapper()).thenReturn(mapper);
    when(mapper.getObjectMapper()).thenReturn(new ObjectMapper());
}
Also used : ObjectEntityCache(com.yahoo.elide.core.ObjectEntityCache) JsonApiMapper(com.yahoo.elide.jsonapi.JsonApiMapper) RequestScope(com.yahoo.elide.core.RequestScope) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) BeforeAll(org.junit.jupiter.api.BeforeAll)

Aggregations

RequestScope (com.yahoo.elide.core.RequestScope)132 Test (org.junit.jupiter.api.Test)99 PersistentResource (com.yahoo.elide.core.PersistentResource)63 TestRequestScope (com.yahoo.elide.core.TestRequestScope)28 Include (com.yahoo.elide.annotation.Include)27 Entity (javax.persistence.Entity)27 EntityDictionary (com.yahoo.elide.core.dictionary.EntityDictionary)26 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)23 ReadPermission (com.yahoo.elide.annotation.ReadPermission)22 EntityProjection (com.yahoo.elide.core.request.EntityProjection)22 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)22 Book (example.Book)19 UpdatePermission (com.yahoo.elide.annotation.UpdatePermission)17 JsonApiDocument (com.yahoo.elide.jsonapi.models.JsonApiDocument)15 HashSet (java.util.HashSet)15 Publisher (example.Publisher)14 FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)12 Author (example.Author)10 Editor (example.Editor)10 Collection (java.util.Collection)10