Search in sources :

Example 16 with BadRequestException

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

the class TableExportOperation method call.

@Override
public AsyncAPIResult call() {
    log.debug("TableExport Object from request: {}", exportObj);
    Elide elide = service.getElide();
    TableExportResult exportResult = new TableExportResult();
    UUID requestId = UUID.fromString(exportObj.getRequestId());
    try (DataStoreTransaction tx = elide.getDataStore().beginTransaction()) {
        // Do Not Cache Export Results
        Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>();
        requestHeaders.put("bypasscache", new ArrayList<String>(Arrays.asList("true")));
        RequestScope requestScope = getRequestScope(exportObj, scope, tx, requestHeaders);
        Collection<EntityProjection> projections = getProjections(exportObj, requestScope);
        validateProjections(projections);
        EntityProjection projection = projections.iterator().next();
        Observable<PersistentResource> observableResults = Observable.empty();
        elide.getTransactionRegistry().addRunningTransaction(requestId, tx);
        // TODO - we need to add the baseUrlEndpoint to the queryObject.
        // TODO - Can we have projectionInfo as null?
        requestScope.setEntityProjection(projection);
        if (projection != null) {
            projection.setPagination(null);
            observableResults = PersistentResource.loadRecords(projection, Collections.emptyList(), requestScope);
        }
        Observable<String> results = Observable.empty();
        String preResult = formatter.preFormat(projection, exportObj);
        results = observableResults.map(resource -> {
            this.recordNumber++;
            return formatter.format(resource, recordNumber);
        });
        String postResult = formatter.postFormat(projection, exportObj);
        // Stitch together Pre-Formatted, Formatted, Post-Formatted results of Formatter in single observable.
        Observable<String> interimResults = concatStringWithObservable(preResult, results, true);
        Observable<String> finalResults = concatStringWithObservable(postResult, interimResults, false);
        TableExportResult result = storeResults(exportObj, engine, finalResults);
        if (result != null && result.getMessage() != null) {
            throw new IllegalStateException(result.getMessage());
        }
        exportResult.setUrl(new URL(generateDownloadURL(exportObj, scope)));
        exportResult.setRecordCount(recordNumber);
        tx.flush(requestScope);
        elide.getAuditLogger().commit();
        tx.commit(requestScope);
    } catch (BadRequestException e) {
        exportResult.setMessage(e.getMessage());
    } catch (MalformedURLException e) {
        exportResult.setMessage("Download url generation failure.");
    } catch (IOException e) {
        log.error("IOException during TableExport", e);
        exportResult.setMessage(e.getMessage());
    } catch (Exception e) {
        exportResult.setMessage(e.getMessage());
    } finally {
        // Follows same flow as GraphQL. The query may result in failure but request was successfully processed.
        exportResult.setHttpStatus(200);
        exportResult.setCompletedOn(new Date());
        elide.getTransactionRegistry().removeRunningTransaction(requestId);
        elide.getAuditLogger().clear();
    }
    return exportResult;
}
Also used : Arrays(java.util.Arrays) Getter(lombok.Getter) ResultStorageEngine(com.yahoo.elide.async.service.storageengine.ResultStorageEngine) AsyncAPIResult(com.yahoo.elide.async.models.AsyncAPIResult) URL(java.net.URL) Date(java.util.Date) SingleRootProjectionValidator(com.yahoo.elide.async.export.validator.SingleRootProjectionValidator) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) ArrayList(java.util.ArrayList) Validator(com.yahoo.elide.async.export.validator.Validator) Map(java.util.Map) PersistentResource(com.yahoo.elide.core.PersistentResource) Observable(io.reactivex.Observable) AsyncAPI(com.yahoo.elide.async.models.AsyncAPI) TableExport(com.yahoo.elide.async.models.TableExport) RequestScope(com.yahoo.elide.core.RequestScope) Elide(com.yahoo.elide.Elide) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) FileExtensionType(com.yahoo.elide.async.models.FileExtensionType) MalformedURLException(java.net.MalformedURLException) Collection(java.util.Collection) EntityProjection(com.yahoo.elide.core.request.EntityProjection) IOException(java.io.IOException) TableExportFormatter(com.yahoo.elide.async.export.formatter.TableExportFormatter) UUID(java.util.UUID) TableExportResult(com.yahoo.elide.async.models.TableExportResult) AsyncExecutorService(com.yahoo.elide.async.service.AsyncExecutorService) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) Collections(java.util.Collections) EntityProjection(com.yahoo.elide.core.request.EntityProjection) PersistentResource(com.yahoo.elide.core.PersistentResource) MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) IOException(java.io.IOException) RequestScope(com.yahoo.elide.core.RequestScope) TableExportResult(com.yahoo.elide.async.models.TableExportResult) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) Date(java.util.Date) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) ArrayList(java.util.ArrayList) List(java.util.List) Elide(com.yahoo.elide.Elide) UUID(java.util.UUID)

Example 17 with BadRequestException

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

the class FilterTranslator method apply.

/**
 * Transforms a filter predicate into a JPQL query fragment.
 * @param filterPredicate The predicate to transform.
 * @param aliasGenerator Function which supplies a HQL fragment which represents the column in the predicate.
 * @return The hql query fragment.
 */
protected String apply(FilterPredicate filterPredicate, Function<Path, String> aliasGenerator) {
    Function<Path, String> removeThisFromAlias = (path) -> {
        String fieldPath = aliasGenerator.apply(path);
        // JPQL doesn't support 'this', but it does support aliases.
        return fieldPath.replaceAll("\\.this", "");
    };
    Path.PathElement last = filterPredicate.getPath().lastElement().get();
    Operator op = filterPredicate.getOperator();
    JPQLPredicateGenerator generator = predicateOverrides.get(Triple.of(op, last.getType(), last.getFieldName()));
    if (generator == null) {
        generator = operatorGenerators.get(op);
    }
    if (generator == null) {
        throw new BadRequestException("Operator not implemented: " + filterPredicate.getOperator());
    }
    return generator.generate(filterPredicate, removeThisFromAlias);
}
Also used : Path(com.yahoo.elide.core.Path) FilterPredicate(com.yahoo.elide.core.filter.predicates.FilterPredicate) Path(com.yahoo.elide.core.Path) LE(com.yahoo.elide.core.filter.Operator.LE) FilterOperation(com.yahoo.elide.core.filter.FilterOperation) NOT(com.yahoo.elide.core.filter.Operator.NOT) HashMap(java.util.HashMap) NOTBETWEEN(com.yahoo.elide.core.filter.Operator.NOTBETWEEN) POSTFIX(com.yahoo.elide.core.filter.Operator.POSTFIX) Function(java.util.function.Function) ISNULL(com.yahoo.elide.core.filter.Operator.ISNULL) PREFIX(com.yahoo.elide.core.filter.Operator.PREFIX) BETWEEN(com.yahoo.elide.core.filter.Operator.BETWEEN) IN(com.yahoo.elide.core.filter.Operator.IN) ISEMPTY(com.yahoo.elide.core.filter.Operator.ISEMPTY) OrFilterExpression(com.yahoo.elide.core.filter.expression.OrFilterExpression) Map(java.util.Map) GT(com.yahoo.elide.core.filter.Operator.GT) IN_INSENSITIVE(com.yahoo.elide.core.filter.Operator.IN_INSENSITIVE) HASMEMBER(com.yahoo.elide.core.filter.Operator.HASMEMBER) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) Triple(org.apache.commons.lang3.tuple.Triple) INFIX_CASE_INSENSITIVE(com.yahoo.elide.core.filter.Operator.INFIX_CASE_INSENSITIVE) FilterParameter(com.yahoo.elide.core.filter.predicates.FilterPredicate.FilterParameter) FilterExpressionVisitor(com.yahoo.elide.core.filter.expression.FilterExpressionVisitor) NOT_INSENSITIVE(com.yahoo.elide.core.filter.Operator.NOT_INSENSITIVE) NOTEMPTY(com.yahoo.elide.core.filter.Operator.NOTEMPTY) TRUE(com.yahoo.elide.core.filter.Operator.TRUE) NotFilterExpression(com.yahoo.elide.core.filter.expression.NotFilterExpression) EnumMap(java.util.EnumMap) TypeHelper.getPathAlias(com.yahoo.elide.core.utils.TypeHelper.getPathAlias) GE(com.yahoo.elide.core.filter.Operator.GE) FALSE(com.yahoo.elide.core.filter.Operator.FALSE) Collectors(java.util.stream.Collectors) NOTNULL(com.yahoo.elide.core.filter.Operator.NOTNULL) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) INFIX(com.yahoo.elide.core.filter.Operator.INFIX) PREFIX_CASE_INSENSITIVE(com.yahoo.elide.core.filter.Operator.PREFIX_CASE_INSENSITIVE) List(java.util.List) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) HASNOMEMBER(com.yahoo.elide.core.filter.Operator.HASNOMEMBER) LT(com.yahoo.elide.core.filter.Operator.LT) Type(com.yahoo.elide.core.type.Type) Operator(com.yahoo.elide.core.filter.Operator) AndFilterExpression(com.yahoo.elide.core.filter.expression.AndFilterExpression) Preconditions(com.google.common.base.Preconditions) TypeHelper.getFieldAlias(com.yahoo.elide.core.utils.TypeHelper.getFieldAlias) POSTFIX_CASE_INSENSITIVE(com.yahoo.elide.core.filter.Operator.POSTFIX_CASE_INSENSITIVE) Operator(com.yahoo.elide.core.filter.Operator) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException)

Example 18 with BadRequestException

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

the class SubscriptionDataFetcherTest method testErrorInSubscriptionStream.

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

Example 19 with BadRequestException

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

the class SubscriptionWebSocketTest method testErrorPriorToStream.

@Test
void testErrorPriorToStream() throws IOException {
    SubscriptionWebSocket endpoint = SubscriptionWebSocket.builder().executorService(executorService).elide(elide).build();
    reset(dataStoreTransaction);
    when(dataStoreTransaction.loadObjects(any(), any())).thenThrow(new BadRequestException("Bad Request"));
    ConnectionInit init = new ConnectionInit();
    endpoint.onOpen(session);
    endpoint.onMessage(session, mapper.writeValueAsString(init));
    Subscribe subscribe = Subscribe.builder().id("1").payload(Subscribe.Payload.builder().query("subscription {book(topic: ADDED) {id title}}").build()).build();
    endpoint.onMessage(session, mapper.writeValueAsString(subscribe));
    List<String> expected = List.of("{\"type\":\"connection_ack\"}", "{\"type\":\"next\",\"id\":\"1\",\"payload\":{\"data\":null,\"errors\":[{\"message\":\"Exception while fetching data (/book) : Bad Request\",\"locations\":[{\"line\":1,\"column\":15}],\"path\":[\"book\"],\"extensions\":{\"classification\":\"DataFetchingException\"}}]}}", "{\"type\":\"complete\",\"id\":\"1\"}");
    ArgumentCaptor<String> message = ArgumentCaptor.forClass(String.class);
    verify(remote, times(3)).sendText(message.capture());
    assertEquals(expected, message.getAllValues());
}
Also used : SubscriptionWebSocket(com.yahoo.elide.graphql.subscriptions.websocket.SubscriptionWebSocket) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) ConnectionInit(com.yahoo.elide.graphql.subscriptions.websocket.protocol.ConnectionInit) Subscribe(com.yahoo.elide.graphql.subscriptions.websocket.protocol.Subscribe) Test(org.junit.jupiter.api.Test) GraphQLTest(com.yahoo.elide.graphql.GraphQLTest)

Example 20 with BadRequestException

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

the class Elide method handleRequest.

/**
 * Handle JSON API requests.
 *
 * @param isReadOnly if the transaction is read only
 * @param user the user object from the container
 * @param transaction a transaction supplier
 * @param requestId the Request ID
 * @param handler a function that creates the request scope and request handler
 * @return the response
 */
protected ElideResponse handleRequest(boolean isReadOnly, User user, Supplier<DataStoreTransaction> transaction, UUID requestId, Handler<DataStoreTransaction, User, HandlerResult> handler) {
    boolean isVerbose = false;
    try (DataStoreTransaction tx = transaction.get()) {
        transactionRegistry.addRunningTransaction(requestId, tx);
        HandlerResult result = handler.handle(tx, user);
        RequestScope requestScope = result.getRequestScope();
        isVerbose = requestScope.getPermissionExecutor().isVerbose();
        Supplier<Pair<Integer, JsonNode>> responder = result.getResponder();
        tx.preCommit(requestScope);
        requestScope.runQueuedPreSecurityTriggers();
        requestScope.getPermissionExecutor().executeCommitChecks();
        requestScope.runQueuedPreFlushTriggers();
        if (!isReadOnly) {
            requestScope.saveOrCreateObjects();
        }
        tx.flush(requestScope);
        requestScope.runQueuedPreCommitTriggers();
        ElideResponse response = buildResponse(responder.get());
        auditLogger.commit();
        tx.commit(requestScope);
        requestScope.runQueuedPostCommitTriggers();
        if (log.isTraceEnabled()) {
            requestScope.getPermissionExecutor().logCheckStats();
        }
        return response;
    } catch (JacksonException e) {
        String message = (e.getLocation() != null && e.getLocation().getSourceRef() != null) ? // This will leak Java class info if the location isn't known.
        e.getMessage() : e.getOriginalMessage();
        return buildErrorResponse(new BadRequestException(message), isVerbose);
    } catch (IOException e) {
        log.error("IO Exception uncaught by Elide", e);
        return buildErrorResponse(new TransactionException(e), isVerbose);
    } catch (RuntimeException e) {
        return handleRuntimeException(e, isVerbose);
    } finally {
        transactionRegistry.removeRunningTransaction(requestId);
        auditLogger.clear();
    }
}
Also used : JacksonException(com.fasterxml.jackson.core.JacksonException) IOException(java.io.IOException) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) RequestScope(com.yahoo.elide.core.RequestScope) TransactionException(com.yahoo.elide.core.exceptions.TransactionException) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) Pair(org.apache.commons.lang3.tuple.Pair)

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