Search in sources :

Example 1 with TransactionException

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

the class AbstractJpaTransaction method flush.

@Override
public void flush(RequestScope requestScope) {
    if (!isOpen()) {
        return;
    }
    try {
        deferredTasks.forEach(Runnable::run);
        deferredTasks.clear();
        FlushModeType flushMode = em.getFlushMode();
        if (flushMode == FlushModeType.AUTO && isOpen()) {
            em.flush();
        }
    } catch (Exception e) {
        try {
            rollback();
        } catch (RuntimeException e2) {
            e.addSuppressed(e2);
        } finally {
            log.error("Caught entity manager exception during flush", e);
        }
        if (e instanceof ConstraintViolationException) {
            throw e;
        }
        throw new TransactionException(e);
    }
}
Also used : FlushModeType(javax.persistence.FlushModeType) TransactionException(com.yahoo.elide.core.exceptions.TransactionException) ConstraintViolationException(javax.validation.ConstraintViolationException) TransactionException(com.yahoo.elide.core.exceptions.TransactionException) NoResultException(javax.persistence.NoResultException) IOException(java.io.IOException) ConstraintViolationException(javax.validation.ConstraintViolationException)

Example 2 with TransactionException

use of com.yahoo.elide.core.exceptions.TransactionException in project faf-java-api by FAForever.

the class SpringHibernateTransaction method commit.

@Override
public void commit(RequestScope scope) {
    try {
        flush(scope);
        txManager.commit(txStatus);
    } catch (org.springframework.transaction.TransactionException e) {
        throw new TransactionException(e);
    }
}
Also used : TransactionException(com.yahoo.elide.core.exceptions.TransactionException)

Example 3 with TransactionException

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

the class HashMapStoreTransaction method createObject.

@Override
public void createObject(Object entity, RequestScope scope) {
    Type entityClass = EntityDictionary.getType(entity);
    String idFieldName = dictionary.getIdFieldName(entityClass);
    String id;
    if (containsObject(entity)) {
        throw new TransactionException(new IllegalStateException("Duplicate key"));
    }
    // GeneratedValue means the DB needs to assign the ID.
    if (dictionary.getAttributeOrRelationAnnotation(entityClass, GeneratedValue.class, idFieldName) != null) {
        // TODO: Id's are not necessarily numeric.
        AtomicLong nextId;
        synchronized (dataStore) {
            nextId = getId(entityClass);
        }
        id = String.valueOf(nextId.getAndIncrement());
        setId(entity, id);
    } else {
        id = dictionary.getId(entity);
    }
    replicateOperationToParent(entity, Operation.OpType.CREATE);
    operations.add(new Operation(id, entity, EntityDictionary.getType(entity), Operation.OpType.CREATE));
}
Also used : GeneratedValue(javax.persistence.GeneratedValue) Type(com.yahoo.elide.core.type.Type) AtomicLong(java.util.concurrent.atomic.AtomicLong) TransactionException(com.yahoo.elide.core.exceptions.TransactionException)

Example 4 with TransactionException

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

Example 5 with TransactionException

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

the class QueryRunner method executeGraphQLRequest.

private ElideResponse executeGraphQLRequest(String baseUrlEndPoint, ObjectMapper mapper, User principal, String graphQLDocument, GraphQLQuery query, UUID requestId, Map<String, List<String>> requestHeaders) {
    boolean isVerbose = false;
    String queryText = query.getQuery();
    boolean isMutation = isMutation(queryText);
    try (DataStoreTransaction tx = isMutation ? elide.getDataStore().beginTransaction() : elide.getDataStore().beginReadTransaction()) {
        elide.getTransactionRegistry().addRunningTransaction(requestId, tx);
        if (query.getQuery() == null || query.getQuery().isEmpty()) {
            return ElideResponse.builder().responseCode(HttpStatus.SC_BAD_REQUEST).body("A `query` key is required.").build();
        }
        // get variables from request for constructing entityProjections
        Map<String, Object> variables = query.getVariables();
        // TODO - get API version.
        GraphQLProjectionInfo projectionInfo = new GraphQLEntityProjectionMaker(elide.getElideSettings(), variables, apiVersion).make(queryText);
        GraphQLRequestScope requestScope = new GraphQLRequestScope(baseUrlEndPoint, tx, principal, apiVersion, elide.getElideSettings(), projectionInfo, requestId, requestHeaders);
        isVerbose = requestScope.getPermissionExecutor().isVerbose();
        // Logging all queries. It is recommended to put any private information that shouldn't be logged into
        // the "variables" section of your query. Variable values are not logged.
        log.info("Processing GraphQL query:\n{}", queryText);
        ExecutionInput.Builder executionInput = new ExecutionInput.Builder().localContext(requestScope).query(queryText);
        if (query.getOperationName() != null) {
            executionInput.operationName(query.getOperationName());
        }
        executionInput.variables(variables);
        ExecutionResult result = api.execute(executionInput);
        tx.preCommit(requestScope);
        requestScope.getPermissionExecutor().executeCommitChecks();
        if (isMutation) {
            if (!result.getErrors().isEmpty()) {
                HashMap<String, Object> abortedResponseObject = new HashMap<>();
                abortedResponseObject.put("errors", result.getErrors());
                abortedResponseObject.put("data", null);
                // Do not commit. Throw OK response to process tx.close correctly.
                throw new WebApplicationException(Response.ok(mapper.writeValueAsString(abortedResponseObject)).build());
            }
            requestScope.saveOrCreateObjects();
        }
        tx.flush(requestScope);
        requestScope.runQueuedPreCommitTriggers();
        elide.getAuditLogger().commit();
        tx.commit(requestScope);
        requestScope.runQueuedPostCommitTriggers();
        if (log.isTraceEnabled()) {
            requestScope.getPermissionExecutor().logCheckStats();
        }
        return ElideResponse.builder().responseCode(HttpStatus.SC_OK).body(mapper.writeValueAsString(result)).build();
    } catch (JsonProcessingException e) {
        log.debug("Invalid json body provided to GraphQL", e);
        return buildErrorResponse(mapper, new InvalidEntityBodyException(graphQLDocument), isVerbose);
    } catch (IOException e) {
        log.error("Uncaught IO Exception by Elide in GraphQL", e);
        return buildErrorResponse(mapper, new TransactionException(e), isVerbose);
    } catch (RuntimeException e) {
        return handleRuntimeException(elide, e, isVerbose);
    } finally {
        elide.getTransactionRegistry().removeRunningTransaction(requestId);
        elide.getAuditLogger().clear();
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) GraphQLProjectionInfo(com.yahoo.elide.graphql.parser.GraphQLProjectionInfo) ExecutionResult(graphql.ExecutionResult) IOException(java.io.IOException) InvalidEntityBodyException(com.yahoo.elide.core.exceptions.InvalidEntityBodyException) TransactionException(com.yahoo.elide.core.exceptions.TransactionException) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) GraphQLEntityProjectionMaker(com.yahoo.elide.graphql.parser.GraphQLEntityProjectionMaker) ExecutionInput(graphql.ExecutionInput) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

TransactionException (com.yahoo.elide.core.exceptions.TransactionException)6 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)3 IOException (java.io.IOException)3 WebApplicationException (javax.ws.rs.WebApplicationException)2 JacksonException (com.fasterxml.jackson.core.JacksonException)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 RequestScope (com.yahoo.elide.core.RequestScope)1 DataStore (com.yahoo.elide.core.datastore.DataStore)1 BadRequestException (com.yahoo.elide.core.exceptions.BadRequestException)1 HttpStatusException (com.yahoo.elide.core.exceptions.HttpStatusException)1 InvalidEntityBodyException (com.yahoo.elide.core.exceptions.InvalidEntityBodyException)1 Type (com.yahoo.elide.core.type.Type)1 GraphQLEntityProjectionMaker (com.yahoo.elide.graphql.parser.GraphQLEntityProjectionMaker)1 GraphQLProjectionInfo (com.yahoo.elide.graphql.parser.GraphQLProjectionInfo)1 PatchRequestScope (com.yahoo.elide.jsonapi.extensions.PatchRequestScope)1 ExecutionInput (graphql.ExecutionInput)1 ExecutionResult (graphql.ExecutionResult)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 AtomicLong (java.util.concurrent.atomic.AtomicLong)1