Search in sources :

Example 61 with RequestScope

use of com.yahoo.elide.core.RequestScope 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 62 with RequestScope

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

Example 63 with RequestScope

use of com.yahoo.elide.core.RequestScope in project elide by yahoo.

the class GraphQLTableExportOperationTest method dataPrep.

/**
 * Prepping and Storing an TableExport entry to be queried later on.
 * @throws IOException  IOException
 */
private void dataPrep() throws IOException {
    TableExport temp = new TableExport();
    DataStoreTransaction tx = dataStore.beginTransaction();
    RequestScope scope = new RequestScope(null, null, NO_VERSION, null, tx, user, null, Collections.emptyMap(), UUID.randomUUID(), elide.getElideSettings());
    tx.save(temp, scope);
    tx.commit(scope);
    tx.close();
}
Also used : TableExport(com.yahoo.elide.async.models.TableExport) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) RequestScope(com.yahoo.elide.core.RequestScope)

Example 64 with RequestScope

use of com.yahoo.elide.core.RequestScope in project elide by yahoo.

the class JsonAPITableExportOperationTest method dataPrep.

/**
 * Prepping and Storing an TableExport entry to be queried later on.
 * @throws IOException  IOException
 */
private void dataPrep() throws IOException {
    TableExport temp = new TableExport();
    DataStoreTransaction tx = dataStore.beginTransaction();
    RequestScope scope = new RequestScope(null, null, NO_VERSION, null, tx, user, null, Collections.emptyMap(), UUID.randomUUID(), elide.getElideSettings());
    tx.save(temp, scope);
    tx.commit(scope);
    tx.close();
}
Also used : TableExport(com.yahoo.elide.async.models.TableExport) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) RequestScope(com.yahoo.elide.core.RequestScope)

Example 65 with RequestScope

use of com.yahoo.elide.core.RequestScope in project elide by yahoo.

the class JMSDataStoreTest method testLoadObjects.

@Test
public void testLoadObjects() throws Exception {
    Author author1 = new Author();
    author1.setId(1);
    author1.setName("Jon Doe");
    Book book1 = new Book();
    book1.setTitle("Enders Game");
    book1.setId(1);
    book1.setAuthors(Sets.newHashSet(author1));
    Book book2 = new Book();
    book2.setTitle("Grapes of Wrath");
    book2.setId(2);
    try (DataStoreTransaction tx = store.beginReadTransaction()) {
        RequestScope scope = new RequestScope("/json", "/", NO_VERSION, null, tx, null, null, Collections.EMPTY_MAP, UUID.randomUUID(), new ElideSettingsBuilder(store).withEntityDictionary(dictionary).build());
        Iterable<Book> books = tx.loadObjects(EntityProjection.builder().argument(Argument.builder().name("topic").value(TopicType.ADDED).build()).type(Book.class).build(), scope);
        JMSContext context = connectionFactory.createContext();
        Destination destination = context.createTopic("bookAdded");
        JMSProducer producer = context.createProducer();
        ObjectMapper mapper = new ObjectMapper();
        producer.send(destination, mapper.writeValueAsString(book1));
        producer.send(destination, mapper.writeValueAsString(book2));
        Iterator<Book> booksIterator = books.iterator();
        assertTrue(booksIterator.hasNext());
        Book receivedBook = booksIterator.next();
        assertEquals("Enders Game", receivedBook.getTitle());
        assertEquals(1, receivedBook.getId());
        Set<Author> receivedAuthors = Sets.newHashSet((Iterable) tx.getToManyRelation(tx, receivedBook, Relationship.builder().name("authors").projection(EntityProjection.builder().type(Author.class).build()).build(), scope));
        assertTrue(receivedAuthors.contains(author1));
        assertTrue(booksIterator.hasNext());
        receivedBook = booksIterator.next();
        assertEquals("Grapes of Wrath", receivedBook.getTitle());
        assertEquals(2, receivedBook.getId());
        assertFalse(booksIterator.hasNext());
    }
}
Also used : Destination(javax.jms.Destination) ElideSettingsBuilder(com.yahoo.elide.ElideSettingsBuilder) Book(example.Book) Author(example.Author) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) JMSProducer(javax.jms.JMSProducer) RequestScope(com.yahoo.elide.core.RequestScope) JMSContext(javax.jms.JMSContext) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test)

Aggregations

RequestScope (com.yahoo.elide.core.RequestScope)132 Test (org.junit.jupiter.api.Test)99 PersistentResource (com.yahoo.elide.core.PersistentResource)63 TestRequestScope (com.yahoo.elide.core.TestRequestScope)28 Include (com.yahoo.elide.annotation.Include)27 Entity (javax.persistence.Entity)27 EntityDictionary (com.yahoo.elide.core.dictionary.EntityDictionary)26 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)23 ReadPermission (com.yahoo.elide.annotation.ReadPermission)22 EntityProjection (com.yahoo.elide.core.request.EntityProjection)22 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)22 Book (example.Book)19 UpdatePermission (com.yahoo.elide.annotation.UpdatePermission)17 JsonApiDocument (com.yahoo.elide.jsonapi.models.JsonApiDocument)15 HashSet (java.util.HashSet)15 Publisher (example.Publisher)14 FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)12 Author (example.Author)10 Editor (example.Editor)10 Collection (java.util.Collection)10