Search in sources :

Example 21 with EntityDictionary

use of com.yahoo.elide.core.dictionary.EntityDictionary in project elide by yahoo.

the class PersistentResourceFetcher method fetchRelationship.

/**
 * Fetches a relationship for a top-level entity.
 *
 * @param parentResource Parent object
 * @param relationship constructed relationship object with entityProjection
 * @param ids List of ids
 * @return persistence resource object(s)
 */
public static ConnectionContainer fetchRelationship(PersistentResource<?> parentResource, @NotNull Relationship relationship, Optional<List<String>> ids) {
    EntityDictionary dictionary = parentResource.getRequestScope().getDictionary();
    Type relationshipClass = dictionary.getParameterizedType(parentResource.getObject(), relationship.getName());
    String relationshipType = dictionary.getJsonAliasFor(relationshipClass);
    Set<PersistentResource> relationResources;
    if (ids.isPresent()) {
        relationResources = parentResource.getRelation(ids.get(), relationship).toList(LinkedHashSet::new).blockingGet();
    } else {
        relationResources = parentResource.getRelationCheckedFiltered(relationship).toList(LinkedHashSet::new).blockingGet();
    }
    return new ConnectionContainer(relationResources, Optional.ofNullable(relationship.getProjection().getPagination()), relationshipType);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) PersistentResource(com.yahoo.elide.core.PersistentResource) ClassType(com.yahoo.elide.core.type.ClassType) Type(com.yahoo.elide.core.type.Type) ConnectionContainer(com.yahoo.elide.graphql.containers.ConnectionContainer) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary)

Example 22 with EntityDictionary

use of com.yahoo.elide.core.dictionary.EntityDictionary in project elide by yahoo.

the class MultiplexManagerTest method partialCommitFailure.

@Test
public void partialCommitFailure() throws IOException {
    final EntityDictionary entityDictionary = EntityDictionary.builder().build();
    final HashMapDataStore ds1 = new HashMapDataStore(DefaultClassScanner.getInstance(), FirstBean.class.getPackage());
    final DataStore ds2 = new TestDataStore(OtherBean.class.getPackage());
    final MultiplexManager multiplexManager = new MultiplexManager(ds1, ds2);
    multiplexManager.populateEntityDictionary(entityDictionary);
    assertEquals(ds1, multiplexManager.getSubManager(ClassType.of(FirstBean.class)));
    assertEquals(ds2, multiplexManager.getSubManager(ClassType.of(OtherBean.class)));
    try (DataStoreTransaction t = ds1.beginTransaction()) {
        assertFalse(t.loadObjects(EntityProjection.builder().type(FirstBean.class).build(), null).iterator().hasNext());
        FirstBean firstBean = FirstBean.class.newInstance();
        firstBean.setName("name");
        t.createObject(firstBean, null);
        // t.save(firstBean);
        assertFalse(t.loadObjects(EntityProjection.builder().type(FirstBean.class).build(), null).iterator().hasNext());
        t.commit(null);
    } catch (InstantiationException | IllegalAccessException e) {
        log.error("", e);
    }
    try (DataStoreTransaction t = multiplexManager.beginTransaction()) {
        FirstBean firstBean = (FirstBean) t.loadObjects(EntityProjection.builder().type(FirstBean.class).build(), null).iterator().next();
        firstBean.setName("update");
        t.save(firstBean, null);
        OtherBean otherBean = OtherBean.class.newInstance();
        t.createObject(otherBean, null);
        // t.save(firstBean);
        assertThrows(TransactionException.class, () -> t.commit(null));
    } catch (InstantiationException | IllegalAccessException e) {
        log.error("", e);
    }
    // verify state
    try (DataStoreTransaction t = ds1.beginTransaction()) {
        Iterable<Object> beans = t.loadObjects(EntityProjection.builder().type(FirstBean.class).build(), null);
        assertNotNull(beans);
        ArrayList<Object> list = Lists.newArrayList(beans.iterator());
        assertEquals(list.size(), 1);
        assertEquals(((FirstBean) list.get(0)).getName(), "name");
    }
}
Also used : OtherBean(com.yahoo.elide.example.other.OtherBean) HashMapDataStore(com.yahoo.elide.core.datastore.inmemory.HashMapDataStore) FirstBean(com.yahoo.elide.example.beans.FirstBean) HashMapDataStore(com.yahoo.elide.core.datastore.inmemory.HashMapDataStore) DataStore(com.yahoo.elide.core.datastore.DataStore) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) Test(org.junit.jupiter.api.Test)

Example 23 with EntityDictionary

use of com.yahoo.elide.core.dictionary.EntityDictionary in project elide by yahoo.

the class ResourceIT method testSpecialCharacterLikeQueryHQL.

@ParameterizedTest
@MethodSource("queryProviderHQL")
public void testSpecialCharacterLikeQueryHQL(FilterPredicate filterPredicate, int noOfRecords) throws Exception {
    DataStoreTransaction tx = dataStore.beginReadTransaction();
    RequestScope scope = mock(RequestScope.class);
    EntityDictionary dictionary = EntityDictionary.builder().build();
    dictionary.bindEntity(Book.class);
    when(scope.getDictionary()).thenReturn(dictionary);
    PaginationImpl pagination = mock(PaginationImpl.class);
    when(pagination.returnPageTotals()).thenReturn(true);
    tx.loadObjects(EntityProjection.builder().type(Book.class).filterExpression(filterPredicate).pagination(pagination).build(), scope);
    tx.commit(scope);
    tx.close();
    verify(pagination).setPageTotals((long) noOfRecords);
}
Also used : PaginationImpl(com.yahoo.elide.core.pagination.PaginationImpl) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) RequestScope(com.yahoo.elide.core.RequestScope) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 24 with EntityDictionary

use of com.yahoo.elide.core.dictionary.EntityDictionary in project elide by yahoo.

the class TableExportIT method tableExportModelAdminReadPermissions.

/**
 * Tests Read Permissions on TableExport Model for Admin Role.
 * @throws IOException IOException
 */
@Test
public void tableExportModelAdminReadPermissions() throws IOException {
    ElideResponse response = null;
    String id = "edc4a871-dff2-4054-804e-d80075c08959";
    String query = "test-query";
    com.yahoo.elide.async.models.TableExport queryObj = new com.yahoo.elide.async.models.TableExport();
    queryObj.setId(id);
    queryObj.setQuery(query);
    queryObj.setResultType(ResultType.CSV);
    queryObj.setQueryType(QueryType.JSONAPI_V1_0);
    queryObj.setPrincipalName("owner-user");
    EntityDictionary dictionary = EntityDictionary.builder().checks(AsyncIntegrationTestApplicationResourceConfig.MAPPINGS).build();
    dataStore.populateEntityDictionary(dictionary);
    DataStoreTransaction tx = dataStore.beginTransaction();
    tx.createObject(queryObj, null);
    tx.commit(null);
    tx.close();
    Elide elide = new Elide(new ElideSettingsBuilder(dataStore).withEntityDictionary(dictionary).withAuditLogger(new TestAuditLogger()).build());
    User ownerUser = new User(() -> "owner-user");
    SecurityContextUser securityContextAdminUser = new SecurityContextUser(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> "1";
        }

        @Override
        public boolean isUserInRole(String s) {
            return true;
        }

        @Override
        public boolean isSecure() {
            return false;
        }

        @Override
        public String getAuthenticationScheme() {
            return null;
        }
    });
    SecurityContextUser securityContextNonAdminUser = new SecurityContextUser(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> "2";
        }

        @Override
        public boolean isUserInRole(String s) {
            return false;
        }

        @Override
        public boolean isSecure() {
            return false;
        }

        @Override
        public String getAuthenticationScheme() {
            return null;
        }
    });
    String baseUrl = "/";
    // Principal is Owner
    response = elide.get(baseUrl, "/tableExport/" + id, new MultivaluedHashMap<>(), ownerUser, NO_VERSION);
    assertEquals(HttpStatus.SC_OK, response.getResponseCode());
    // Principal has Admin Role
    response = elide.get(baseUrl, "/tableExport/" + id, new MultivaluedHashMap<>(), securityContextAdminUser, NO_VERSION);
    assertEquals(HttpStatus.SC_OK, response.getResponseCode());
    // Principal without Admin Role
    response = elide.get(baseUrl, "/tableExport/" + id, new MultivaluedHashMap<>(), securityContextNonAdminUser, NO_VERSION);
    assertEquals(HttpStatus.SC_NOT_FOUND, response.getResponseCode());
}
Also used : User(com.yahoo.elide.core.security.User) SecurityContextUser(com.yahoo.elide.jsonapi.resources.SecurityContextUser) SecurityContextUser(com.yahoo.elide.jsonapi.resources.SecurityContextUser) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ElideSettingsBuilder(com.yahoo.elide.ElideSettingsBuilder) ElideResponse(com.yahoo.elide.ElideResponse) SecurityContext(javax.ws.rs.core.SecurityContext) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) TestAuditLogger(com.yahoo.elide.core.audit.TestAuditLogger) Elide(com.yahoo.elide.Elide) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) Principal(java.security.Principal) Test(org.junit.jupiter.api.Test)

Example 25 with EntityDictionary

use of com.yahoo.elide.core.dictionary.EntityDictionary in project elide by yahoo.

the class VerboseErrorResponsesTestBinder method configure.

@Override
protected void configure() {
    EntityDictionary dictionary = EntityDictionary.builder().injector(injector::inject).checks(TestCheckMappings.MAPPINGS).build();
    bind(dictionary).to(EntityDictionary.class);
    // Elide instance
    bindFactory(new Factory<Elide>() {

        @Override
        public Elide provide() {
            DefaultFilterDialect defaultFilterStrategy = new DefaultFilterDialect(dictionary);
            RSQLFilterDialect rsqlFilterStrategy = RSQLFilterDialect.builder().dictionary(dictionary).build();
            MultipleFilterDialect multipleFilterStrategy = new MultipleFilterDialect(Arrays.asList(rsqlFilterStrategy, defaultFilterStrategy), Arrays.asList(rsqlFilterStrategy, defaultFilterStrategy));
            Elide elide = new Elide(new ElideSettingsBuilder(getDataStore()).withAuditLogger(auditLogger).withJoinFilterDialect(multipleFilterStrategy).withSubqueryFilterDialect(multipleFilterStrategy).withEntityDictionary(dictionary).withVerboseErrors().build());
            elide.doScans();
            return elide;
        }

        @Override
        public void dispose(Elide elide) {
        // do nothing
        }
    }).to(Elide.class).named("elide");
    bind(new BillingService() {

        @Override
        public long purchase(Invoice invoice) {
            return 0;
        }
    }).to(BillingService.class);
}
Also used : ElideSettingsBuilder(com.yahoo.elide.ElideSettingsBuilder) Invoice(example.models.triggers.Invoice) MultipleFilterDialect(com.yahoo.elide.core.filter.dialect.jsonapi.MultipleFilterDialect) DefaultFilterDialect(com.yahoo.elide.core.filter.dialect.jsonapi.DefaultFilterDialect) Elide(com.yahoo.elide.Elide) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) RSQLFilterDialect(com.yahoo.elide.core.filter.dialect.RSQLFilterDialect) BillingService(example.models.triggers.services.BillingService)

Aggregations

EntityDictionary (com.yahoo.elide.core.dictionary.EntityDictionary)87 Test (org.junit.jupiter.api.Test)31 RequestScope (com.yahoo.elide.core.RequestScope)27 Include (com.yahoo.elide.annotation.Include)17 Entity (javax.persistence.Entity)17 HashSet (java.util.HashSet)16 Type (com.yahoo.elide.core.type.Type)13 FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)12 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)10 Map (java.util.Map)10 BeforeAll (org.junit.jupiter.api.BeforeAll)10 PersistentResource (com.yahoo.elide.core.PersistentResource)9 Set (java.util.Set)9 ReadPermission (com.yahoo.elide.annotation.ReadPermission)8 ClassType (com.yahoo.elide.core.type.ClassType)8 List (java.util.List)8 ElideSettingsBuilder (com.yahoo.elide.ElideSettingsBuilder)7 DataStore (com.yahoo.elide.core.datastore.DataStore)7 InvalidObjectIdentifierException (com.yahoo.elide.core.exceptions.InvalidObjectIdentifierException)7 Check (com.yahoo.elide.core.security.checks.Check)7