Search in sources :

Example 6 with BadRequestException

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

the class PersistentResource method loadRecords.

/**
 * Load a collection from the datastore.
 *
 * @param projection   the projection to load
 * @param requestScope the request scope
 * @param ids          a list of object identifiers to optionally load.  Can be empty.
 * @return a filtered collection of resources loaded from the datastore.
 */
public static Observable<PersistentResource> loadRecords(EntityProjection projection, List<String> ids, RequestScope requestScope) {
    Type<?> loadClass = projection.getType();
    Pagination pagination = projection.getPagination();
    Sorting sorting = projection.getSorting();
    FilterExpression filterExpression = projection.getFilterExpression();
    EntityDictionary dictionary = requestScope.getDictionary();
    DataStoreTransaction tx = requestScope.getTransaction();
    if (shouldSkipCollection(loadClass, ReadPermission.class, requestScope, projection.getRequestedFields())) {
        if (ids.isEmpty()) {
            return Observable.empty();
        }
        throw new InvalidObjectIdentifierException(ids.toString(), dictionary.getJsonAliasFor(loadClass));
    }
    Set<String> requestedFields = projection.getRequestedFields();
    if (pagination != null && !pagination.isDefaultInstance() && !CanPaginateVisitor.canPaginate(loadClass, dictionary, requestScope, requestedFields)) {
        throw new BadRequestException(String.format("Cannot paginate %s", dictionary.getJsonAliasFor(loadClass)));
    }
    Set<PersistentResource> newResources = new LinkedHashSet<>();
    if (!ids.isEmpty()) {
        String typeAlias = dictionary.getJsonAliasFor(loadClass);
        newResources = requestScope.getNewPersistentResources().stream().filter(resource -> typeAlias.equals(resource.getTypeName()) && ids.contains(resource.getUUID().orElse(""))).collect(Collectors.toSet());
        FilterExpression idExpression = buildIdFilterExpression(ids, loadClass, dictionary, requestScope);
        // Combine filters if necessary
        filterExpression = Optional.ofNullable(filterExpression).map(fe -> (FilterExpression) new AndFilterExpression(idExpression, fe)).orElse(idExpression);
    }
    Optional<FilterExpression> permissionFilter = getPermissionFilterExpression(loadClass, requestScope, requestedFields);
    if (permissionFilter.isPresent()) {
        if (filterExpression != null) {
            filterExpression = new AndFilterExpression(filterExpression, permissionFilter.get());
        } else {
            filterExpression = permissionFilter.get();
        }
    }
    EntityProjection modifiedProjection = projection.copyOf().filterExpression(filterExpression).sorting(sorting).pagination(pagination).build();
    Observable<PersistentResource> existingResources = filter(ReadPermission.class, Optional.ofNullable(modifiedProjection.getFilterExpression()), projection.getRequestedFields(), Observable.fromIterable(new PersistentResourceSet(tx.loadObjects(modifiedProjection, requestScope), requestScope)));
    // 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(), dictionary.getJsonAliasFor(loadClass));
        }
    });
    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) EntityProjection(com.yahoo.elide.core.request.EntityProjection) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Sorting(com.yahoo.elide.core.request.Sorting) Pagination(com.yahoo.elide.core.request.Pagination) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) InvalidObjectIdentifierException(com.yahoo.elide.core.exceptions.InvalidObjectIdentifierException) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 7 with BadRequestException

use of com.yahoo.elide.core.exceptions.BadRequestException 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)

Example 8 with BadRequestException

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

the class MetricRatio method make.

@Override
public MetricProjection make(Metric metric, String alias, Map<String, Argument> arguments) {
    Argument numerator = arguments.get("numerator");
    Argument denominator = arguments.get("denominator");
    if (numerator == null || denominator == null) {
        throw new BadRequestException("'numerator' and 'denominator' arguments are required for " + metric.getName());
    }
    return SQLMetricProjection.builder().alias(alias).arguments(arguments).name(metric.getName()).expression("{{" + numerator.getValue() + "}} / {{" + denominator.getValue() + "}}").valueType(metric.getValueType()).columnType(metric.getColumnType()).build();
}
Also used : Argument(com.yahoo.elide.core.request.Argument) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException)

Example 9 with BadRequestException

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

the class SubscriptionDataFetcherTest method testErrorBeforeStream.

@Test
void testErrorBeforeStream() {
    Book book1 = new Book();
    book1.setTitle("Book 1");
    book1.setId(1);
    Book book2 = new Book();
    book2.setTitle("Book 2");
    book2.setId(2);
    when(dataStoreTransaction.loadObjects(any(), any())).thenThrow(new BadRequestException("Bad Request"));
    List<String> responses = List.of("null");
    List<String> errors = List.of("Bad Request");
    String graphQLRequest = "subscription {book(topic:ADDED) {id title}}";
    assertSubscriptionEquals(graphQLRequest, responses, errors);
}
Also used : Book(example.Book) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) Test(org.junit.jupiter.api.Test) GraphQLTest(com.yahoo.elide.graphql.GraphQLTest)

Example 10 with BadRequestException

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

the class MapEntryContainer method processFetch.

@Override
public Object processFetch(Environment context) {
    NonEntityDictionary nonEntityDictionary = context.nonEntityDictionary;
    String fieldName = context.field.getName();
    Object returnObject;
    if (KEY.equalsIgnoreCase(fieldName)) {
        returnObject = entry.getKey();
    } else if (VALUE.equalsIgnoreCase(fieldName)) {
        returnObject = entry.getValue();
    } else {
        throw new BadRequestException("Invalid field: '" + fieldName + "'. Maps only contain fields 'key' and 'value'");
    }
    if (nonEntityDictionary.hasBinding(EntityDictionary.getType(returnObject))) {
        return new NonEntityContainer(returnObject);
    }
    return returnObject;
}
Also used : BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) NonEntityDictionary(com.yahoo.elide.graphql.NonEntityDictionary)

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