Search in sources :

Example 16 with RegistryEntry

use of io.crnk.core.engine.registry.RegistryEntry in project crnk-framework by crnk-project.

the class CollectionGetTest method onGivenRequestResourceShouldNotLoadAutoIncludeFields.

@Test
public void onGivenRequestResourceShouldNotLoadAutoIncludeFields() throws Exception {
    // GIVEN
    Document newTaskBody = new Document();
    Resource data = createTask();
    newTaskBody.setData(Nullable.of((Object) data));
    data.setType("tasks");
    JsonPath taskPath = pathBuilder.build("/tasks");
    ResourcePost resourcePost = new ResourcePost(resourceRegistry, PROPERTIES_PROVIDER, typeParser, objectMapper, documentMapper, new ArrayList<ResourceModificationFilter>());
    // WHEN -- adding a task
    Response taskResponse = resourcePost.handle(taskPath, emptyTaskQuery, null, newTaskBody);
    // THEN
    assertThat(taskResponse.getDocument().getSingleData().get().getType()).isEqualTo("tasks");
    Long taskId = Long.parseLong(taskResponse.getDocument().getSingleData().get().getId());
    assertThat(taskId).isNotNull();
    /* ------- */
    // GIVEN
    Document newProjectBody = new Document();
    data = createProject();
    newProjectBody.setData(Nullable.of((Object) data));
    JsonPath projectPath = pathBuilder.build("/projects");
    // WHEN -- adding a project
    Response projectResponse = resourcePost.handle(projectPath, emptyProjectQuery, null, newProjectBody);
    // THEN
    assertThat(projectResponse.getDocument().getSingleData().get().getType()).isEqualTo("projects");
    assertThat(projectResponse.getDocument().getSingleData().get().getId()).isNotNull();
    assertThat(projectResponse.getDocument().getSingleData().get().getAttributes().get("name").asText()).isEqualTo("sample project");
    Long projectId = Long.parseLong(projectResponse.getDocument().getSingleData().get().getId());
    assertThat(projectId).isNotNull();
    /* ------- */
    // GIVEN
    Document newTaskToProjectBody = new Document();
    data = new Resource();
    newTaskToProjectBody.setData(Nullable.of((Object) Collections.singletonList(data)));
    data.setType("projects");
    data.setId(projectId.toString());
    JsonPath savedTaskPath = pathBuilder.build("/tasks/" + taskId + "/relationships/projects");
    RelationshipsResourcePost sut = new RelationshipsResourcePost(resourceRegistry, typeParser, new ArrayList<ResourceModificationFilter>());
    // WHEN -- adding a relation between task and project
    Response projectRelationshipResponse = sut.handle(savedTaskPath, emptyProjectQuery, null, newTaskToProjectBody);
    assertThat(projectRelationshipResponse).isNotNull();
    // THEN
    TaskToProjectRepository taskToProjectRepository = new TaskToProjectRepository();
    Project project = taskToProjectRepository.findOneTarget(taskId, "projects", new QueryParams());
    assertThat(project.getId()).isNotNull();
    // Given
    JsonPath jsonPath = pathBuilder.build("/tasks/" + taskId);
    ResourceGet responseGetResp = new ResourceGet(resourceRegistry, typeParser, documentMapper);
    Map<String, Set<String>> queryParams = new HashMap<>();
    queryParams.put(RestrictedQueryParamsMembers.include.name() + "[tasks]", Collections.singleton("[\"projects\"]"));
    QueryParams requestParams = new QueryParamsBuilder(new DefaultQueryParamsParser()).buildQueryParams(queryParams);
    // WHEN
    Response response = responseGetResp.handle(jsonPath, new QueryParamsAdapter(resourceRegistry.getEntry(Task.class).getResourceInformation(), requestParams, moduleRegistry), null, null);
    // THEN
    Assert.assertNotNull(response);
    assertThat(response.getDocument().getSingleData().get().getType()).isEqualTo("tasks");
    // eager loading but no inclusion
    RegistryEntry entry = resourceRegistry.getEntry(Task.class);
    ResourceField projectsField = entry.getResourceInformation().findFieldByUnderlyingName("projects");
    Assert.assertEquals(SerializeType.ONLY_ID, projectsField.getSerializeType());
    assertThat(response.getDocument().getSingleData().get().getRelationships().get("projects").getData().isPresent()).isTrue();
}
Also used : Task(io.crnk.core.mock.models.Task) Resource(io.crnk.core.engine.document.Resource) Document(io.crnk.core.engine.document.Document) JsonPath(io.crnk.core.engine.internal.dispatcher.path.JsonPath) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) DefaultQueryParamsParser(io.crnk.legacy.queryParams.DefaultQueryParamsParser) Response(io.crnk.core.engine.dispatcher.Response) Project(io.crnk.core.mock.models.Project) ResourceField(io.crnk.core.engine.information.resource.ResourceField) TaskToProjectRepository(io.crnk.core.mock.repository.TaskToProjectRepository) QueryParamsBuilder(io.crnk.legacy.queryParams.QueryParamsBuilder) ResourceModificationFilter(io.crnk.core.engine.filter.ResourceModificationFilter) QueryParams(io.crnk.legacy.queryParams.QueryParams) QueryParamsAdapter(io.crnk.legacy.internal.QueryParamsAdapter) Test(org.junit.Test)

Example 17 with RegistryEntry

use of io.crnk.core.engine.registry.RegistryEntry in project crnk-framework by crnk-project.

the class ResourceFilterTest method checkFilterGetOnResourceField.

@Test
public void checkFilterGetOnResourceField() {
    // setup test data
    RegistryEntry entry = resourceRegistry.getEntry(Task.class);
    ResourceRepositoryAdapter resourceRepository = entry.getResourceRepository();
    Project project = new Project();
    project.setId(13L);
    project.setName("myProject");
    Task task = new Task();
    task.setId(12L);
    task.setName("myTask");
    task.setProject(project);
    resourceRepository.create(task, new QuerySpecAdapter(new QuerySpec(Task.class), resourceRegistry));
    // get information
    ResourceInformation resourceInformation = entry.getResourceInformation();
    ResourceField projectField = resourceInformation.findFieldByUnderlyingName("project");
    ResourceField nameField = resourceInformation.findFieldByUnderlyingName("name");
    String path = "/tasks/";
    String method = HttpMethod.GET.toString();
    Map<String, Set<String>> parameters = Collections.emptyMap();
    Document requestBody = null;
    // forbid field
    Mockito.when(filter.filterField(Mockito.eq(projectField), Mockito.any(HttpMethod.class))).thenReturn(FilterBehavior.FORBIDDEN);
    Response response = boot.getRequestDispatcher().dispatchRequest(path, method, parameters, null, requestBody);
    Assert.assertEquals(HttpStatus.OK_200, response.getHttpStatus().intValue());
    Resource taskResource = response.getDocument().getCollectionData().get().get(0);
    Assert.assertTrue(taskResource.getRelationships().containsKey("projects"));
    Assert.assertFalse(taskResource.getRelationships().containsKey("project"));
    Assert.assertTrue(taskResource.getAttributes().containsKey("name"));
    // allow resource
    Mockito.when(filter.filterField(Mockito.eq(nameField), Mockito.any(HttpMethod.class))).thenReturn(FilterBehavior.FORBIDDEN);
    response = boot.getRequestDispatcher().dispatchRequest(path, method, parameters, null, requestBody);
    Assert.assertEquals(HttpStatus.OK_200, response.getHttpStatus().intValue());
    taskResource = response.getDocument().getCollectionData().get().get(0);
    Assert.assertTrue(taskResource.getRelationships().containsKey("projects"));
    Assert.assertFalse(taskResource.getRelationships().containsKey("project"));
    Assert.assertFalse(taskResource.getAttributes().containsKey("name"));
}
Also used : Task(io.crnk.core.mock.models.Task) ResourceInformation(io.crnk.core.engine.information.resource.ResourceInformation) Set(java.util.Set) Resource(io.crnk.core.engine.document.Resource) QuerySpecAdapter(io.crnk.core.queryspec.internal.QuerySpecAdapter) Document(io.crnk.core.engine.document.Document) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) Response(io.crnk.core.engine.dispatcher.Response) Project(io.crnk.core.mock.models.Project) ResourceField(io.crnk.core.engine.information.resource.ResourceField) ResourceRepositoryAdapter(io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter) QuerySpec(io.crnk.core.queryspec.QuerySpec) HttpMethod(io.crnk.core.engine.http.HttpMethod) ResourceRegistryTest(io.crnk.core.resource.registry.ResourceRegistryTest) Test(org.junit.Test)

Example 18 with RegistryEntry

use of io.crnk.core.engine.registry.RegistryEntry in project crnk-framework by crnk-project.

the class CrnkBootTest method boot.

@Test
public void boot() {
    CrnkBoot boot = new CrnkBoot();
    boot.setDefaultServiceUrlProvider(new ServiceUrlProvider() {

        @Override
        public String getUrl() {
            return "http://127.0.0.1";
        }
    });
    boot.setServiceDiscovery(new ReflectionsServiceDiscovery(MockConstants.TEST_MODELS_PACKAGE));
    boot.addModule(new SimpleModule("test"));
    boot.boot();
    RequestDispatcher requestDispatcher = boot.getRequestDispatcher();
    ResourceRegistry resourceRegistry = boot.getResourceRegistry();
    RegistryEntry taskEntry = resourceRegistry.getEntry(Task.class);
    Assert.assertNotEquals(0, taskEntry.getRelationshipEntries().size());
    ResourceRepositoryAdapter<?, ?> repositoryAdapter = taskEntry.getResourceRepository(null);
    Assert.assertNotNull(repositoryAdapter.getResourceRepository());
    JsonApiResponse response = repositoryAdapter.findAll(new QueryParamsAdapter(taskEntry.getResourceInformation(), new QueryParams(), boot.getModuleRegistry()));
    Assert.assertNotNull(response);
    Assert.assertNotNull(requestDispatcher);
    ServiceDiscovery serviceDiscovery = boot.getServiceDiscovery();
    Assert.assertNotNull(serviceDiscovery);
    Assert.assertNotNull(boot.getModuleRegistry());
    Assert.assertNotNull(boot.getExceptionMapperRegistry());
    List<Module> modules = boot.getModuleRegistry().getModules();
    Assert.assertEquals(4, modules.size());
    boot.setDefaultPageLimit(20L);
    boot.setMaxPageLimit(100L);
    Assert.assertEquals(1, boot.getPagingBehaviors().size());
    Assert.assertTrue(boot.getPagingBehaviors().get(0) instanceof OffsetLimitPagingBehavior);
}
Also used : OffsetLimitPagingBehavior(io.crnk.core.queryspec.pagingspec.OffsetLimitPagingBehavior) ConstantServiceUrlProvider(io.crnk.core.engine.url.ConstantServiceUrlProvider) ServiceUrlProvider(io.crnk.core.engine.url.ServiceUrlProvider) ResourceRegistry(io.crnk.core.engine.registry.ResourceRegistry) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) RequestDispatcher(io.crnk.core.engine.dispatcher.RequestDispatcher) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) QueryParams(io.crnk.legacy.queryParams.QueryParams) ReflectionsServiceDiscovery(io.crnk.core.module.discovery.ReflectionsServiceDiscovery) QueryParamsAdapter(io.crnk.legacy.internal.QueryParamsAdapter) SimpleModule(io.crnk.core.module.SimpleModule) Module(io.crnk.core.module.Module) SimpleModule(io.crnk.core.module.SimpleModule) ServiceDiscovery(io.crnk.core.module.discovery.ServiceDiscovery) ReflectionsServiceDiscovery(io.crnk.core.module.discovery.ReflectionsServiceDiscovery) Test(org.junit.Test)

Example 19 with RegistryEntry

use of io.crnk.core.engine.registry.RegistryEntry in project crnk-framework by crnk-project.

the class RepositoryFilterTest method prepare.

@Before
public void prepare() {
    boot = new CrnkBoot();
    boot.setServiceDiscovery(new ReflectionsServiceDiscovery(MockConstants.TEST_MODELS_PACKAGE));
    boot.setServiceUrlProvider(new ConstantServiceUrlProvider(ResourceRegistryTest.TEST_MODELS_URL));
    SimpleModule filterModule = new SimpleModule("filter");
    filterModule.addRepositoryFilter(filter);
    boot.addModule(filterModule);
    boot.boot();
    resourceRegistry = boot.getResourceRegistry();
    querySpec = new QuerySpec(User.class);
    querySpec.setPagingSpec(new OffsetLimitPagingSpec());
    queryAdapter = new QuerySpecAdapter(querySpec, resourceRegistry);
    scheduleInfo = resourceRegistry.getEntry(Schedule.class).getResourceInformation();
    RegistryEntry userEntry = resourceRegistry.getEntry(User.class);
    resourceAdapter = userEntry.getResourceRepository(null);
    projectRelationAdapter = userEntry.getRelationshipRepository("assignedProjects", null);
    taskRelationAdapter = userEntry.getRelationshipRepository("assignedTasks", null);
    userInfo = userEntry.getResourceInformation();
    UserRepository resourceRepository = (UserRepository) resourceAdapter.getResourceRepository();
    user1 = new User();
    user1.setId(1L);
    resourceRepository.save(user1);
    user2 = new User();
    user2.setId(2L);
    resourceRepository.save(user2);
    UserToProjectRepository userProjectRepository = (UserToProjectRepository) ((AnnotatedRelationshipRepositoryAdapter<?, ?, ?, ?>) projectRelationAdapter.getRelationshipRepository()).getImplementationObject();
    userProjectRepository.setRelation(user1, 11L, "assignedProjects");
    UserToTaskRepository userTaskRepository = new UserToTaskRepository();
    userTaskRepository.addRelations(user1, Arrays.asList(21L), "assignedTasks");
    userTaskRepository.addRelations(user2, Arrays.asList(22L), "assignedTasks");
    assignedTasksField = resourceRegistry.getEntry(User.class).getResourceInformation().findRelationshipFieldByName("assignedTasks");
    assignedProjectsField = resourceRegistry.getEntry(User.class).getResourceInformation().findRelationshipFieldByName("assignedProjects");
}
Also used : UserToProjectRepository(io.crnk.core.mock.repository.UserToProjectRepository) CrnkBoot(io.crnk.core.boot.CrnkBoot) User(io.crnk.core.mock.models.User) UserRepository(io.crnk.core.mock.repository.UserRepository) OffsetLimitPagingSpec(io.crnk.core.queryspec.pagingspec.OffsetLimitPagingSpec) UserToTaskRepository(io.crnk.core.mock.repository.UserToTaskRepository) ReflectionsServiceDiscovery(io.crnk.core.module.discovery.ReflectionsServiceDiscovery) ConstantServiceUrlProvider(io.crnk.core.engine.url.ConstantServiceUrlProvider) QuerySpec(io.crnk.core.queryspec.QuerySpec) QuerySpecAdapter(io.crnk.core.queryspec.internal.QuerySpecAdapter) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) SimpleModule(io.crnk.core.module.SimpleModule) Before(org.junit.Before)

Example 20 with RegistryEntry

use of io.crnk.core.engine.registry.RegistryEntry in project crnk-framework by crnk-project.

the class GetFromOwnerStrategy method findTargets.

@SuppressWarnings("unchecked")
public MultivaluedMap<I, D> findTargets(Iterable<I> sourceIds, String fieldName, QuerySpec querySpec) {
    RegistryEntry sourceEntry = context.getSourceEntry();
    ResourceInformation sourceInformation = sourceEntry.getResourceInformation();
    ResourceField field = sourceInformation.findFieldByUnderlyingName(fieldName);
    RegistryEntry targetEntry = context.getTargetEntry(field);
    List sources = (List) sourceEntry.getResourceRepository().findAll(sourceIds, context.createSaveQueryAdapter(fieldName)).getEntity();
    ResourceInformation targetInformation = targetEntry.getResourceInformation();
    List<D> targets;
    if (field.hasIdField()) {
        Set targetIds = new HashSet();
        for (Object source : sources) {
            Object targetId = field.getIdAccessor().getValue(source);
            if (field.isCollection()) {
                targetIds.addAll((Collection) targetId);
            } else {
                targetIds.add(targetId);
            }
        }
        QuerySpec idQuerySpec = new QuerySpec(targetInformation);
        ResourceRepositoryAdapter<D, J> targetAdapter = targetEntry.getResourceRepository();
        JsonApiResponse response = targetAdapter.findAll(targetIds, context.createQueryAdapter(idQuerySpec));
        targets = (List<D>) response.getEntity();
        return toResult(field, targetInformation, sources, targets);
    } else {
        MultivaluedMap bulkResult = new MultivaluedMap<I, D>() {

            @Override
            protected List<D> newList() {
                return new DefaultResourceList<>();
            }
        };
        for (Object source : sources) {
            Object sourceId = sourceInformation.getId(source);
            Object target = field.getAccessor().getValue(source);
            if (target != null) {
                if (field.isCollection()) {
                    bulkResult.addAll(sourceId, (Collection) target);
                } else {
                    bulkResult.add(sourceId, target);
                }
            }
        }
        return bulkResult;
    }
}
Also used : ResourceInformation(io.crnk.core.engine.information.resource.ResourceInformation) Set(java.util.Set) HashSet(java.util.HashSet) RegistryEntry(io.crnk.core.engine.registry.RegistryEntry) ResourceField(io.crnk.core.engine.information.resource.ResourceField) DefaultResourceList(io.crnk.core.resource.list.DefaultResourceList) DefaultResourceList(io.crnk.core.resource.list.DefaultResourceList) List(java.util.List) JsonApiResponse(io.crnk.core.repository.response.JsonApiResponse) QuerySpec(io.crnk.core.queryspec.QuerySpec) MultivaluedMap(io.crnk.core.engine.internal.utils.MultivaluedMap) HashSet(java.util.HashSet)

Aggregations

RegistryEntry (io.crnk.core.engine.registry.RegistryEntry)119 ResourceInformation (io.crnk.core.engine.information.resource.ResourceInformation)60 Test (org.junit.Test)38 ResourceField (io.crnk.core.engine.information.resource.ResourceField)36 ResourceRegistry (io.crnk.core.engine.registry.ResourceRegistry)19 QuerySpec (io.crnk.core.queryspec.QuerySpec)18 JsonApiResponse (io.crnk.core.repository.response.JsonApiResponse)14 Serializable (java.io.Serializable)14 Task (io.crnk.core.mock.models.Task)13 Response (io.crnk.core.engine.dispatcher.Response)12 Document (io.crnk.core.engine.document.Document)11 Resource (io.crnk.core.engine.document.Resource)11 ResourceRegistryTest (io.crnk.core.resource.registry.ResourceRegistryTest)10 ResourceRepositoryAdapter (io.crnk.core.engine.internal.repository.ResourceRepositoryAdapter)9 FilterSpec (io.crnk.core.queryspec.FilterSpec)9 QuerySpecAdapter (io.crnk.core.queryspec.internal.QuerySpecAdapter)8 Before (org.junit.Before)8 Collection (java.util.Collection)7 HashSet (java.util.HashSet)7 HttpMethod (io.crnk.core.engine.http.HttpMethod)6