Search in sources :

Example 21 with BadRequestException

use of com.yahoo.elide.core.exceptions.BadRequestException in project elide by yahoo.

the class SearchDataTransaction method search.

/**
 * Perform the full-text search.
 * @param entityType The class to search
 * @param filterExpression The filter expression to apply
 * @param sorting Optional sorting
 * @param pagination Optional pagination
 * @return A list of records of type entityClass.
 */
private <T> List<T> search(Type<?> entityType, FilterExpression filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination) {
    Query query;
    Class<?> entityClass = null;
    if (entityType != null) {
        Preconditions.checkState(entityType instanceof ClassType);
        entityClass = ((ClassType) entityType).getCls();
    }
    try {
        query = filterExpression.accept(new FilterExpressionToLuceneQuery(em, entityClass));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
    FullTextQuery fullTextQuery = em.createFullTextQuery(query, entityClass);
    if (mustSort(sorting)) {
        fullTextQuery = fullTextQuery.setSort(buildSort(sorting.get(), entityType));
    }
    if (pagination.isPresent()) {
        fullTextQuery = fullTextQuery.setMaxResults(pagination.get().getLimit());
        fullTextQuery = fullTextQuery.setFirstResult(pagination.get().getOffset());
    }
    List<T[]> results = fullTextQuery.setProjection(ProjectionConstants.THIS).getResultList();
    if (pagination.filter(Pagination::returnPageTotals).isPresent()) {
        pagination.get().setPageTotals((long) fullTextQuery.getResultSize());
    }
    if (results.isEmpty()) {
        return Collections.emptyList();
    }
    return results.stream().map(result -> result[0]).collect(Collectors.toList());
}
Also used : PredicateExtractionVisitor(com.yahoo.elide.core.filter.expression.PredicateExtractionVisitor) Query(org.apache.lucene.search.Query) FilterPredicate(com.yahoo.elide.core.filter.predicates.FilterPredicate) Arrays(java.util.Arrays) Path(com.yahoo.elide.core.Path) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) ProjectionConstants(org.hibernate.search.engine.ProjectionConstants) SortableField(org.hibernate.search.annotations.SortableField) FullTextQuery(org.hibernate.search.jpa.FullTextQuery) Index(org.hibernate.search.annotations.Index) ClassType(com.yahoo.elide.core.type.ClassType) Fields(org.hibernate.search.annotations.Fields) ArrayList(java.util.ArrayList) Map(java.util.Map) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) TransactionWrapper(com.yahoo.elide.core.datastore.wrapped.TransactionWrapper) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) RequestScope(com.yahoo.elide.core.RequestScope) FullTextEntityManager(org.hibernate.search.jpa.FullTextEntityManager) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) HttpStatusException(com.yahoo.elide.core.exceptions.HttpStatusException) Sorting(com.yahoo.elide.core.request.Sorting) Sort(org.apache.lucene.search.Sort) Collection(java.util.Collection) Field(org.hibernate.search.annotations.Field) EntityProjection(com.yahoo.elide.core.request.EntityProjection) Collectors(java.util.stream.Collectors) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) SortFieldContext(org.hibernate.search.query.dsl.sort.SortFieldContext) List(java.util.List) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) Pagination(com.yahoo.elide.core.request.Pagination) InvalidValueException(com.yahoo.elide.core.exceptions.InvalidValueException) Type(com.yahoo.elide.core.type.Type) Operator(com.yahoo.elide.core.filter.Operator) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Comparator(java.util.Comparator) Collections(java.util.Collections) QueryBuilder(org.hibernate.search.query.dsl.QueryBuilder) Query(org.apache.lucene.search.Query) FullTextQuery(org.hibernate.search.jpa.FullTextQuery) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) ClassType(com.yahoo.elide.core.type.ClassType) FullTextQuery(org.hibernate.search.jpa.FullTextQuery)

Example 22 with BadRequestException

use of com.yahoo.elide.core.exceptions.BadRequestException in project elide by yahoo.

the class PersistentResourceFetcher method upsertOrUpdateObjects.

/**
 * handle UPSERT or UPDATE operation.
 * @param context Environment encapsulating graphQL's request environment
 * @param updateFunc controls the behavior of how the update (or upsert) is performed.
 * @return Connection object.
 */
private ConnectionContainer upsertOrUpdateObjects(Environment context, Executor<?> updateFunc, RelationshipOp operation) {
    /* sanity check for id and data argument w UPSERT/UPDATE */
    if (context.ids.isPresent()) {
        throw new BadRequestException(operation + " must not include ids");
    }
    if (!context.data.isPresent()) {
        throw new BadRequestException(operation + " must include data argument");
    }
    Type<?> entityClass;
    EntityDictionary dictionary = context.requestScope.getDictionary();
    if (context.isRoot()) {
        entityClass = dictionary.getEntityClass(context.field.getName(), context.requestScope.getApiVersion());
    } else {
        assert context.parentResource != null;
        entityClass = dictionary.getParameterizedType(context.parentResource.getResourceType(), context.field.getName());
    }
    /* form entities */
    Optional<Entity> parentEntity;
    if (!context.isRoot()) {
        assert context.parentResource != null;
        parentEntity = Optional.of(new Entity(Optional.empty(), null, context.parentResource.getResourceType(), context.requestScope));
    } else {
        parentEntity = Optional.empty();
    }
    LinkedHashSet<Entity> entitySet = new LinkedHashSet<>();
    for (Map<String, Object> input : context.data.orElseThrow(IllegalStateException::new)) {
        entitySet.add(new Entity(parentEntity, input, entityClass, context.requestScope));
    }
    /* apply function to upsert/update the object */
    for (Entity entity : entitySet) {
        graphWalker(entity, updateFunc, context);
    }
    /* fixup relationships */
    for (Entity entity : entitySet) {
        graphWalker(entity, this::updateRelationship, context);
        PersistentResource<?> childResource = entity.toPersistentResource();
        if (!context.isRoot()) {
            /* add relation between parent and nested entity */
            assert context.parentResource != null;
            context.parentResource.addRelation(context.field.getName(), childResource);
        }
    }
    String entityName = dictionary.getJsonAliasFor(entityClass);
    Set<PersistentResource> resources = entitySet.stream().map(Entity::toPersistentResource).collect(Collectors.toCollection(LinkedHashSet::new));
    return new ConnectionContainer(resources, Optional.empty(), entityName);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) PersistentResource(com.yahoo.elide.core.PersistentResource) ConnectionContainer(com.yahoo.elide.graphql.containers.ConnectionContainer) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary)

Example 23 with BadRequestException

use of com.yahoo.elide.core.exceptions.BadRequestException in project elide by yahoo.

the class PersistentResourceFetcher method updateObject.

private PersistentResource updateObject(Entity entity, Environment context) {
    Set<Entity.Attribute> attributes = entity.getAttributes();
    Optional<String> id = entity.getId();
    RequestScope requestScope = entity.getRequestScope();
    PersistentResource<?> updatedResource;
    if (!id.isPresent()) {
        throw new BadRequestException("UPDATE data objects must include ids");
    }
    Set<PersistentResource> loadedResource = fetchObject(requestScope, entity.getProjection(), Optional.of(Collections.singletonList(id.get()))).getPersistentResources();
    updatedResource = loadedResource.iterator().next();
    return updateAttributes(updatedResource, entity, attributes);
}
Also used : PersistentResource(com.yahoo.elide.core.PersistentResource) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) RequestScope(com.yahoo.elide.core.RequestScope)

Example 24 with BadRequestException

use of com.yahoo.elide.core.exceptions.BadRequestException in project elide by yahoo.

the class GraphQLEntityProjectionMaker method addSorting.

/**
 * Creates a {@link Sorting} object from sorting GraphQL argument value and attaches it to the entity sorted
 * according to the newly created {@link Sorting} object.
 *
 * @param argument An argument that contains the value of sorting spec
 * @param projectionBuilder projection that is being built
 */
private void addSorting(Argument argument, EntityProjectionBuilder projectionBuilder) {
    String sortRule = (String) variableResolver.resolveValue(argument.getValue());
    try {
        Sorting sorting = SortingImpl.parseSortRule(sortRule, projectionBuilder.getType(), projectionBuilder.getAttributes(), entityDictionary);
        projectionBuilder.sorting(sorting);
    } catch (InvalidValueException e) {
        throw new BadRequestException("Invalid sorting clause " + sortRule + " for type " + entityDictionary.getJsonAliasFor(projectionBuilder.getType()));
    }
}
Also used : InvalidValueException(com.yahoo.elide.core.exceptions.InvalidValueException) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) Sorting(com.yahoo.elide.core.request.Sorting)

Example 25 with BadRequestException

use of com.yahoo.elide.core.exceptions.BadRequestException in project elide by yahoo.

the class VariableResolver method addVariable.

/**
 * Resolve {@link VariableDefinition} and store result in the variable map.
 * We don't need to worry about resolving graphql {@link graphql.language.TypeName} here because Elide-core
 * knows the correct type of each field/argument.
 *
 * @param definition definition to resolve
 */
private void addVariable(VariableDefinition definition) {
    Type variableType = definition.getType();
    String variableName = definition.getName();
    Value defaultValue = definition.getDefaultValue();
    if (defaultValue == null) {
        if (variableType instanceof NonNullType && scopeVariables.get(variableName) == null) {
            // value of non-null variable must be resolvable
            throw new BadRequestException("Undefined non-null variable " + variableName);
        }
        // this would put 'null' for this variable if it is not stored in the map
        scopeVariables.put(variableName, scopeVariables.get(variableName));
    } else {
        if (!scopeVariables.containsKey(variableName)) {
            // create a new variable with default value
            scopeVariables.put(variableName, resolveValue(defaultValue));
        }
    }
}
Also used : Type(graphql.language.Type) NonNullType(graphql.language.NonNullType) NonNullType(graphql.language.NonNullType) NullValue(graphql.language.NullValue) ObjectValue(graphql.language.ObjectValue) FloatValue(graphql.language.FloatValue) Value(graphql.language.Value) EnumValue(graphql.language.EnumValue) StringValue(graphql.language.StringValue) ArrayValue(graphql.language.ArrayValue) IntValue(graphql.language.IntValue) BooleanValue(graphql.language.BooleanValue) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException)

Aggregations

BadRequestException (com.yahoo.elide.core.exceptions.BadRequestException)28 PersistentResource (com.yahoo.elide.core.PersistentResource)8 Map (java.util.Map)8 RequestScope (com.yahoo.elide.core.RequestScope)7 EntityDictionary (com.yahoo.elide.core.dictionary.EntityDictionary)7 List (java.util.List)7 EntityProjection (com.yahoo.elide.core.request.EntityProjection)5 Type (com.yahoo.elide.core.type.Type)5 HashMap (java.util.HashMap)5 Collectors (java.util.stream.Collectors)5 GraphQLTest (com.yahoo.elide.graphql.GraphQLTest)4 ConnectionContainer (com.yahoo.elide.graphql.containers.ConnectionContainer)4 ArrayList (java.util.ArrayList)4 Collection (java.util.Collection)4 Collections (java.util.Collections)4 Optional (java.util.Optional)4 Test (org.junit.jupiter.api.Test)4 Preconditions (com.google.common.base.Preconditions)3 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)3 FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)3