Search in sources :

Example 16 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class Elide method patch.

/**
 * Handle PATCH.
 *
 * @param baseUrlEndPoint base URL with prefix endpoint
 * @param contentType the content type
 * @param accept the accept
 * @param path the path
 * @param jsonApiDocument the json api document
 * @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 patch(String baseUrlEndPoint, String contentType, String accept, String path, String jsonApiDocument, MultivaluedMap<String, String> queryParams, Map<String, List<String>> requestHeaders, User opaqueUser, String apiVersion, UUID requestId) {
    Handler<DataStoreTransaction, User, HandlerResult> handler;
    if (JsonApiPatch.isPatchExtension(contentType) && JsonApiPatch.isPatchExtension(accept)) {
        handler = (tx, user) -> {
            PatchRequestScope requestScope = new PatchRequestScope(baseUrlEndPoint, path, apiVersion, tx, user, requestId, queryParams, requestHeaders, elideSettings);
            try {
                Supplier<Pair<Integer, JsonNode>> responder = JsonApiPatch.processJsonPatch(dataStore, path, jsonApiDocument, requestScope);
                return new HandlerResult(requestScope, responder);
            } catch (RuntimeException e) {
                return new HandlerResult(requestScope, e);
            }
        };
    } else {
        handler = (tx, user) -> {
            JsonApiDocument jsonApiDoc = mapper.readJsonApiDocument(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 PatchVisitor(requestScope);
            return visit(path, requestScope, visitor);
        };
    }
    return handleRequest(false, opaqueUser, dataStore::beginTransaction, requestId, handler);
}
Also used : PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) User(com.yahoo.elide.core.security.User) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) PatchVisitor(com.yahoo.elide.jsonapi.parser.PatchVisitor) EntityProjectionMaker(com.yahoo.elide.jsonapi.EntityProjectionMaker) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) RequestScope(com.yahoo.elide.core.RequestScope) BaseVisitor(com.yahoo.elide.jsonapi.parser.BaseVisitor) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) Pair(org.apache.commons.lang3.tuple.Pair)

Example 17 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class Elide method post.

/**
 * Handle POST.
 *
 * @param baseUrlEndPoint base URL with prefix endpoint
 * @param path the path
 * @param jsonApiDocument the json api document
 * @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 post(String baseUrlEndPoint, String path, String jsonApiDocument, MultivaluedMap<String, String> queryParams, Map<String, List<String>> requestHeaders, User opaqueUser, String apiVersion, UUID requestId) {
    return handleRequest(false, opaqueUser, dataStore::beginTransaction, requestId, (tx, user) -> {
        JsonApiDocument jsonApiDoc = mapper.readJsonApiDocument(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 PostVisitor(requestScope);
        return visit(path, requestScope, visitor);
    });
}
Also used : JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) BaseVisitor(com.yahoo.elide.jsonapi.parser.BaseVisitor) EntityProjectionMaker(com.yahoo.elide.jsonapi.EntityProjectionMaker) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) RequestScope(com.yahoo.elide.core.RequestScope) PostVisitor(com.yahoo.elide.jsonapi.parser.PostVisitor)

Example 18 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class Elide method delete.

/**
 * Handle DELETE.
 *
 * @param baseUrlEndPoint base URL with prefix endpoint
 * @param path the path
 * @param jsonApiDocument the json api document
 * @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 delete(String baseUrlEndPoint, String path, String jsonApiDocument, MultivaluedMap<String, String> queryParams, Map<String, List<String>> requestHeaders, User opaqueUser, String apiVersion, UUID requestId) {
    return handleRequest(false, opaqueUser, dataStore::beginTransaction, requestId, (tx, user) -> {
        JsonApiDocument jsonApiDoc = StringUtils.isEmpty(jsonApiDocument) ? new JsonApiDocument() : mapper.readJsonApiDocument(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 DeleteVisitor(requestScope);
        return visit(path, requestScope, visitor);
    });
}
Also used : JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) BaseVisitor(com.yahoo.elide.jsonapi.parser.BaseVisitor) EntityProjectionMaker(com.yahoo.elide.jsonapi.EntityProjectionMaker) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) RequestScope(com.yahoo.elide.core.RequestScope) DeleteVisitor(com.yahoo.elide.jsonapi.parser.DeleteVisitor)

Example 19 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class AsyncAPICancelRunnable method cancelAsyncAPI.

/**
 * This method cancels queries based on threshold.
 * @param type AsyncAPI Type Implementation.
 */
protected <T extends AsyncAPI> void cancelAsyncAPI(Class<T> type) {
    try {
        TransactionRegistry transactionRegistry = elide.getTransactionRegistry();
        Map<UUID, DataStoreTransaction> runningTransactionMap = transactionRegistry.getRunningTransactions();
        // Running transaction UUIDs
        Set<UUID> runningTransactionUUIDs = runningTransactionMap.keySet();
        // Construct filter expression
        PathElement statusPathElement = new PathElement(type, QueryStatus.class, "status");
        FilterExpression fltStatusExpression = new InPredicate(statusPathElement, QueryStatus.CANCELLED, QueryStatus.PROCESSING, QueryStatus.QUEUED);
        Iterable<T> asyncAPIIterable = asyncAPIDao.loadAsyncAPIByFilter(fltStatusExpression, type);
        // Active AsyncAPI UUIDs
        Set<UUID> asyncTransactionUUIDs = StreamSupport.stream(asyncAPIIterable.spliterator(), false).filter(query -> query.getStatus() == QueryStatus.CANCELLED || TimeUnit.SECONDS.convert(Math.abs(new Date(System.currentTimeMillis()).getTime() - query.getCreatedOn().getTime()), TimeUnit.MILLISECONDS) > maxRunTimeSeconds).map(query -> UUID.fromString(query.getRequestId())).collect(Collectors.toSet());
        // AsyncAPI UUIDs that have active transactions
        Set<UUID> queryUUIDsToCancel = Sets.intersection(runningTransactionUUIDs, asyncTransactionUUIDs);
        // AsyncAPI IDs that need to be cancelled
        Set<String> queryIDsToCancel = queryUUIDsToCancel.stream().map(uuid -> StreamSupport.stream(asyncAPIIterable.spliterator(), false).filter(query -> query.getRequestId().equals(uuid.toString())).map(T::getId).findFirst().orElseThrow(IllegalStateException::new)).collect(Collectors.toSet());
        // Cancel Transactions
        queryUUIDsToCancel.stream().forEach((uuid) -> {
            DataStoreTransaction runningTransaction = transactionRegistry.getRunningTransaction(uuid);
            if (runningTransaction != null) {
                JsonApiDocument jsonApiDoc = new JsonApiDocument();
                MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
                RequestScope scope = new RequestScope("", "query", NO_VERSION, jsonApiDoc, runningTransaction, null, queryParams, Collections.emptyMap(), uuid, elide.getElideSettings());
                runningTransaction.cancel(scope);
            }
        });
        // Change queryStatus for cancelled queries
        if (!queryIDsToCancel.isEmpty()) {
            PathElement idPathElement = new PathElement(type, String.class, "id");
            FilterExpression fltIdExpression = new InPredicate(idPathElement, queryIDsToCancel);
            asyncAPIDao.updateStatusAsyncAPIByFilter(fltIdExpression, QueryStatus.CANCEL_COMPLETE, type);
        }
    } catch (Exception e) {
        log.error("Exception in scheduled cancellation: {}", e.toString());
    }
}
Also used : TransactionRegistry(com.yahoo.elide.core.TransactionRegistry) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) Date(java.util.Date) AsyncAPIDAO(com.yahoo.elide.async.service.dao.AsyncAPIDAO) Map(java.util.Map) NO_VERSION(com.yahoo.elide.core.dictionary.EntityDictionary.NO_VERSION) StreamSupport(java.util.stream.StreamSupport) AsyncAPI(com.yahoo.elide.async.models.AsyncAPI) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) QueryStatus(com.yahoo.elide.async.models.QueryStatus) RequestScope(com.yahoo.elide.core.RequestScope) Elide(com.yahoo.elide.Elide) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) InPredicate(com.yahoo.elide.core.filter.predicates.InPredicate) AsyncQuery(com.yahoo.elide.async.models.AsyncQuery) Set(java.util.Set) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Sets(com.google.common.collect.Sets) TimeUnit(java.util.concurrent.TimeUnit) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Slf4j(lombok.extern.slf4j.Slf4j) Data(lombok.Data) AllArgsConstructor(lombok.AllArgsConstructor) PathElement(com.yahoo.elide.core.Path.PathElement) Collections(java.util.Collections) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) TransactionRegistry(com.yahoo.elide.core.TransactionRegistry) InPredicate(com.yahoo.elide.core.filter.predicates.InPredicate) RequestScope(com.yahoo.elide.core.RequestScope) Date(java.util.Date) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) PathElement(com.yahoo.elide.core.Path.PathElement) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) UUID(java.util.UUID) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression)

Example 20 with JsonApiDocument

use of com.yahoo.elide.jsonapi.models.JsonApiDocument in project elide by yahoo.

the class DefaultAsyncAPIDAO method executeInTransaction.

/**
 * This method creates a transaction from the datastore, performs the DB action using
 * a generic functional interface and closes the transaction.
 * @param dataStore Elide datastore retrieved from Elide object
 * @param action Functional interface to perform DB action
 * @return Object Returns Entity Object (AsyncAPIResult or AsyncResult)
 */
protected Object executeInTransaction(DataStore dataStore, Transactional action) {
    log.debug("executeInTransaction");
    Object result = null;
    try (DataStoreTransaction tx = dataStore.beginTransaction()) {
        JsonApiDocument jsonApiDoc = new JsonApiDocument();
        MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
        RequestScope scope = new RequestScope("", "query", NO_VERSION, jsonApiDoc, tx, null, queryParams, Collections.emptyMap(), UUID.randomUUID(), elideSettings);
        result = action.execute(tx, scope);
        tx.flush(scope);
        tx.commit(scope);
    } catch (IOException e) {
        log.error("IOException: {}", e.toString());
        throw new IllegalStateException(e);
    }
    return result;
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) IOException(java.io.IOException) RequestScope(com.yahoo.elide.core.RequestScope)

Aggregations

JsonApiDocument (com.yahoo.elide.jsonapi.models.JsonApiDocument)51 Resource (com.yahoo.elide.jsonapi.models.Resource)31 Test (org.junit.jupiter.api.Test)26 PersistentResource (com.yahoo.elide.core.PersistentResource)25 RequestScope (com.yahoo.elide.core.RequestScope)15 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)9 Data (com.yahoo.elide.jsonapi.models.Data)8 IOException (java.io.IOException)7 TestRequestScope (com.yahoo.elide.core.TestRequestScope)6 Parent (example.Parent)6 InvalidEntityBodyException (com.yahoo.elide.core.exceptions.InvalidEntityBodyException)5 EntityProjectionMaker (com.yahoo.elide.jsonapi.EntityProjectionMaker)4 PatchRequestScope (com.yahoo.elide.jsonapi.extensions.PatchRequestScope)4 Relationship (com.yahoo.elide.jsonapi.models.Relationship)4 BaseVisitor (com.yahoo.elide.jsonapi.parser.BaseVisitor)4 Child (example.Child)4 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)3 JsonApiMapper (com.yahoo.elide.jsonapi.JsonApiMapper)3 DocumentProcessor (com.yahoo.elide.jsonapi.document.processors.DocumentProcessor)3 IncludedProcessor (com.yahoo.elide.jsonapi.document.processors.IncludedProcessor)3