Search in sources :

Example 56 with PersistentResource

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

the class NotifyTopicLifeCycleHookTest method testManagedModelNotification.

@Test
public void testManagedModelNotification() {
    NotifyTopicLifeCycleHook<Book> bookHook = new NotifyTopicLifeCycleHook<Book>(connectionFactory, JMSContext::createProducer, new GsonBuilder().create());
    Book book = new Book();
    PersistentResource<Book> resource = new PersistentResource<>(book, "123", scope);
    bookHook.execute(LifeCycleHookBinding.Operation.CREATE, LifeCycleHookBinding.TransactionPhase.PRECOMMIT, new CRUDEvent(LifeCycleHookBinding.Operation.CREATE, resource, "", Optional.empty()));
    ArgumentCaptor<String> topicCaptor = ArgumentCaptor.forClass(String.class);
    verify(context).createTopic(topicCaptor.capture());
    assertEquals("bookAdded", topicCaptor.getValue());
    verify(producer, times(1)).send(isA(Destination.class), isA(String.class));
}
Also used : PersistentResource(com.yahoo.elide.core.PersistentResource) Destination(javax.jms.Destination) CRUDEvent(com.yahoo.elide.core.lifecycle.CRUDEvent) GsonBuilder(com.google.gson.GsonBuilder) Book(example.Book) JMSContext(javax.jms.JMSContext) Test(org.junit.jupiter.api.Test)

Example 57 with PersistentResource

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

the class LogMessageImplTest method init.

@BeforeAll
public static void init() {
    final EntityDictionary dictionary = EntityDictionary.builder().build();
    dictionary.bindEntity(Child.class);
    dictionary.bindEntity(Parent.class);
    final Child child = new Child();
    child.setId(5);
    final Parent parent = new Parent();
    parent.setId(7);
    final Child friend = new Child();
    friend.setId(9);
    child.setFriends(Sets.newHashSet(friend));
    final RequestScope requestScope = new RequestScope(null, null, NO_VERSION, null, null, new TestUser("aaron"), null, null, UUID.randomUUID(), new ElideSettingsBuilder(null).withAuditLogger(new TestAuditLogger()).withEntityDictionary(dictionary).build());
    final PersistentResource<Parent> parentRecord = new PersistentResource<>(parent, requestScope.getUUIDFor(parent), requestScope);
    childRecord = new PersistentResource<>(child, parentRecord, "children", requestScope.getUUIDFor(child), requestScope);
    friendRecord = new PersistentResource<>(friend, childRecord, "friends", requestScope.getUUIDFor(friend), requestScope);
}
Also used : PersistentResource(com.yahoo.elide.core.PersistentResource) ElideSettingsBuilder(com.yahoo.elide.ElideSettingsBuilder) Parent(example.Parent) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) Child(example.Child) RequestScope(com.yahoo.elide.core.RequestScope) TestUser(com.yahoo.elide.core.security.TestUser) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 58 with PersistentResource

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

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

the class JSONExportFormatter method resourceToJSON.

public static String resourceToJSON(ObjectMapper mapper, PersistentResource resource) {
    if (resource == null || resource.getObject() == null) {
        return null;
    }
    StringBuilder str = new StringBuilder();
    try {
        Resource jsonResource = resource.toResource(getRelationships(resource), getAttributes(resource));
        str.append(mapper.writeValueAsString(jsonResource.getAttributes()));
    } catch (JsonProcessingException e) {
        log.error("Exception when converting to JSON {}", e.getMessage());
        throw new IllegalStateException(e);
    }
    return str.toString();
}
Also used : Resource(com.yahoo.elide.jsonapi.models.Resource) PersistentResource(com.yahoo.elide.core.PersistentResource) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 60 with PersistentResource

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

the class BaseState method getResponseBody.

protected static JsonNode getResponseBody(PersistentResource resource, RequestScope requestScope) {
    MultivaluedMap<String, String> queryParams = requestScope.getQueryParams();
    JsonApiDocument jsonApiDocument = new JsonApiDocument();
    // TODO Make this a document processor
    Data<Resource> data = resource == null ? null : new Data<>(resource.toResource());
    jsonApiDocument.setData(data);
    // TODO Iterate over set of document processors
    DocumentProcessor includedProcessor = new IncludedProcessor();
    includedProcessor.execute(jsonApiDocument, resource, queryParams);
    return requestScope.getMapper().toJsonObject(jsonApiDocument);
}
Also used : JsonApiDocument(com.yahoo.elide.jsonapi.models.JsonApiDocument) DocumentProcessor(com.yahoo.elide.jsonapi.document.processors.DocumentProcessor) Resource(com.yahoo.elide.jsonapi.models.Resource) PersistentResource(com.yahoo.elide.core.PersistentResource) IncludedProcessor(com.yahoo.elide.jsonapi.document.processors.IncludedProcessor)

Aggregations

PersistentResource (com.yahoo.elide.core.PersistentResource)100 Test (org.junit.jupiter.api.Test)71 RequestScope (com.yahoo.elide.core.RequestScope)60 ReadPermission (com.yahoo.elide.annotation.ReadPermission)18 UpdatePermission (com.yahoo.elide.annotation.UpdatePermission)18 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)17 Include (com.yahoo.elide.annotation.Include)16 Entity (javax.persistence.Entity)16 Resource (com.yahoo.elide.jsonapi.models.Resource)13 AndFilterExpression (com.yahoo.elide.core.filter.expression.AndFilterExpression)10 NotFilterExpression (com.yahoo.elide.core.filter.expression.NotFilterExpression)10 OrFilterExpression (com.yahoo.elide.core.filter.expression.OrFilterExpression)10 PermissionExecutor (com.yahoo.elide.core.security.PermissionExecutor)10 JsonApiDocument (com.yahoo.elide.jsonapi.models.JsonApiDocument)10 Book (example.Book)10 LinkedHashSet (java.util.LinkedHashSet)9 EntityDictionary (com.yahoo.elide.core.dictionary.EntityDictionary)8 BadRequestException (com.yahoo.elide.core.exceptions.BadRequestException)8 FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)8 RSQLFilterDialect (com.yahoo.elide.core.filter.dialect.RSQLFilterDialect)7