Search in sources :

Example 1 with SortColumn

use of org.alfresco.rest.framework.resource.parameters.SortColumn in project alfresco-remote-api by Alfresco.

the class GroupsTest method canGetGroupsForUserId.

private void canGetGroupsForUserId() throws Exception {
    Person personAlice;
    {
        publicApiClient.setRequestContext(new RequestContext(networkOne.getId(), networkAdmin, "admin"));
        personAlice = new Person();
        String aliceId = "alice-" + UUID.randomUUID() + "@" + networkOne.getId();
        personAlice.setUserName(aliceId);
        personAlice.setId(aliceId);
        personAlice.setFirstName("Alice");
        personAlice.setEmail("alison.smith@example.com");
        personAlice.setPassword("password");
        personAlice.setEnabled(true);
        PublicApiClient.People people = publicApiClient.people();
        people.create(personAlice);
    }
    Groups groupsProxy = publicApiClient.groups();
    // As admin
    setRequestContext(networkOne.getId(), networkAdmin, "admin");
    // New user has only the one default group.
    {
        ListResponse<Group> groups = groupsProxy.getGroupsByPersonId(personAlice.getId(), null, "Couldn't get user's groups", 200);
        assertEquals(1L, (long) groups.getPaging().getTotalItems());
        Iterator<Group> it = groups.getList().iterator();
        assertEquals(GROUP_EVERYONE, it.next().getId());
    }
    // Add the user to a couple more groups and list them.
    {
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
        authorityService.addAuthority(groupA.getId(), personAlice.getId());
        authorityService.addAuthority(groupB.getId(), personAlice.getId());
        ListResponse<Group> groups = groupsProxy.getGroupsByPersonId(personAlice.getId(), null, "Couldn't get user's groups", 200);
        assertEquals(4L, (long) groups.getPaging().getTotalItems());
        Iterator<Group> it = groups.getList().iterator();
        assertEquals(groupA, it.next());
        assertEquals(groupB, it.next());
        assertEquals(GROUP_EVERYONE, it.next().getId());
        assertEquals(rootGroup, it.next());
    }
    {
        Group aardvark = new Group();
        try {
            aardvark.setId("GROUP_AARDVARK");
            aardvark.setDisplayName("Aardvark");
            authorityService.createAuthority(AuthorityType.GROUP, aardvark.getId());
            authorityService.setAuthorityDisplayName(aardvark.getId(), aardvark.getDisplayName());
            Person personBob;
            personBob = new Person();
            String bobId = "bob-" + UUID.randomUUID() + "@" + networkOne.getId();
            personBob.setUserName(bobId);
            personBob.setId(bobId);
            personBob.setFirstName("Bob");
            personBob.setEmail("bob.cratchet@example.com");
            personBob.setPassword("password");
            personBob.setEnabled(true);
            PublicApiClient.People people = publicApiClient.people();
            people.create(personBob);
            authorityService.addAuthority(aardvark.getId(), personBob.getId());
            // Check sorting by ID when groups have no display name (REPO-1844)
            // We don't want the GROUP_EVERYONE group to be sorted as an empty string, for example,
            // which is what the comparator was doing.
            Map<String, String> params = new HashMap<>();
            addOrderBy(params, org.alfresco.rest.api.Groups.PARAM_ID, true);
            ListResponse<Group> groups = groupsProxy.getGroupsByPersonId(personBob.getId(), params, "Couldn't get user's groups", 200);
            assertEquals(2L, (long) groups.getPaging().getTotalItems());
            Iterator<Group> it = groups.getList().iterator();
            assertEquals(aardvark.getId(), it.next().getId());
            assertEquals("GROUP_EVERYONE", it.next().getId());
        } finally {
            authorityService.deleteAuthority(aardvark.getId());
        }
    }
    // Get network admin's groups by explicit ID.
    {
        ListResponse<Group> groups = groupsProxy.getGroupsByPersonId(networkAdmin, null, "Couldn't get user's groups", 200);
        assertEquals(6L, (long) groups.getPaging().getTotalItems());
    }
    // test -me- alias (as network admin)
    {
        ListResponse<Group> groups = groupsProxy.getGroupsByPersonId("-me-", null, "Couldn't get user's groups", 200);
        assertEquals(6L, (long) groups.getPaging().getCount());
        Iterator<Group> it = groups.getList().iterator();
        assertEquals("GROUP_ALFRESCO_ADMINISTRATORS", it.next().getId());
    }
    // Filter by isRoot
    {
        Map<String, String> params = new HashMap<>();
        params.put("where", "(isRoot=true)");
        ListResponse<Group> response = groupsProxy.getGroupsByPersonId("-me-", params, "Couldn't get user's groups", 200);
        List<Group> groups = response.getList();
        assertFalse(groups.isEmpty());
        // All groups should be root groups.
        groups.forEach(group -> assertTrue(group.getIsRoot()));
        params.put("where", "(isRoot=false)");
        response = groupsProxy.getGroupsByPersonId("-me-", params, "Couldn't get user's groups", 200);
        groups = response.getList();
        assertFalse(groups.isEmpty());
        // All groups should be non-root groups.
        groups.forEach(group -> assertFalse(group.getIsRoot()));
    }
    // -ve test: attempt to get groups for non-existent person
    {
        groupsProxy.getGroupsByPersonId("i-do-not-exist", null, "Incorrect response", 404);
    }
    // As Alice
    setRequestContext(networkOne.getId(), personAlice.getId(), "password");
    // test -me- alias as Alice
    {
        ListResponse<Group> groups = groupsProxy.getGroupsByPersonId("-me-", null, "Couldn't get user's groups", 200);
        assertEquals(4L, (long) groups.getPaging().getCount());
        Iterator<Group> it = groups.getList().iterator();
        assertEquals(groupA, it.next());
        assertEquals(groupB, it.next());
        assertEquals(GROUP_EVERYONE, it.next().getId());
        assertEquals(rootGroup, it.next());
    }
    // +ve: check skip count.
    {
        // Sort params
        Map<String, String> otherParams = new HashMap<>();
        addOrderBy(otherParams, org.alfresco.rest.api.Groups.PARAM_DISPLAY_NAME, false);
        // Paging and list groups
        int skipCount = 0;
        int maxItems = 4;
        Paging paging = getPaging(skipCount, maxItems);
        ListResponse<Group> resp = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        // Paging and list groups with skip count.
        skipCount = 2;
        maxItems = 2;
        paging = getPaging(skipCount, maxItems);
        ListResponse<Group> sublistResponse = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        List<Group> expectedSublist = sublist(resp.getList(), skipCount, maxItems);
        checkList(expectedSublist, sublistResponse.getPaging(), sublistResponse);
    }
    // -ve: check skip count.
    {
        getGroupsByPersonId(personAlice.getId(), getPaging(-1, null), null, HttpServletResponse.SC_BAD_REQUEST);
    }
    // orderBy=sortColumn should be the same to orderBy=sortColumn ASC
    {
        // paging
        Paging paging = getPaging(0, Integer.MAX_VALUE);
        Map<String, String> otherParams = new HashMap<>();
        // Default order.
        addOrderBy(otherParams, org.alfresco.rest.api.Groups.PARAM_DISPLAY_NAME, null);
        ListResponse<Group> resp = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        List<Group> groups = resp.getList();
        assertTrue("groups order not valid", groups.indexOf(groupA) < groups.indexOf(groupB));
        // Ascending order.
        addOrderBy(otherParams, org.alfresco.rest.api.Groups.PARAM_DISPLAY_NAME, true);
        ListResponse<Group> respOrderAsc = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        checkList(respOrderAsc.getList(), resp.getPaging(), resp);
    }
    // Sorting should be the same regardless of implementation (canned query
    // or postprocessing).
    {
        // paging
        Paging paging = getPaging(0, Integer.MAX_VALUE);
        Map<String, String> otherParams = new HashMap<>();
        addOrderBy(otherParams, org.alfresco.rest.api.Groups.PARAM_DISPLAY_NAME, null);
        // Get and sort groups using canned query.
        ListResponse<Group> respCannedQuery = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        // Get and sort groups using postprocessing.
        otherParams.put("where", "(isRoot=true)");
        ListResponse<Group> respPostProcess = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        List<Group> expected = respCannedQuery.getList();
        expected.retainAll(respPostProcess.getList());
        // If this assertion fails, then the tests aren't providing any value - change them!
        assertTrue("List doesn't contain enough items for test to be conclusive.", expected.size() > 0);
        checkList(expected, respPostProcess.getPaging(), respPostProcess);
    }
    {
        // paging
        Paging paging = getPaging(0, Integer.MAX_VALUE);
        Map<String, String> otherParams = new HashMap<>();
        addOrderBy(otherParams, org.alfresco.rest.api.Groups.PARAM_ID, null);
        // Get and sort groups using canned query.
        ListResponse<Group> respCannedQuery = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        // Get and sort groups using postprocessing.
        otherParams.put("where", "(isRoot=true)");
        ListResponse<Group> respPostProcess = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        List<Group> expected = respCannedQuery.getList();
        expected.retainAll(respPostProcess.getList());
        // If this assertion fails, then the tests aren't providing any value - change them!
        assertTrue("List doesn't contain enough items for test to be conclusive.", expected.size() > 0);
        checkList(expected, respPostProcess.getPaging(), respPostProcess);
    }
    // Sort by id.
    {
        Paging paging = getPaging(0, Integer.MAX_VALUE);
        Map<String, String> otherParams = new HashMap<>();
        Group groupEveryone = new Group();
        groupEveryone.setId(PermissionService.ALL_AUTHORITIES);
        // Sort by ID ascending
        addOrderBy(otherParams, org.alfresco.rest.api.Groups.PARAM_ID, true);
        ListResponse<Group> resp = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        assertEquals(4, resp.getList().size());
        Iterator<Group> it = resp.getList().iterator();
        // GROUP_EVERYONE
        assertEquals(groupEveryone, it.next());
        // GROUP_Group_ROOT<UUID>
        assertEquals(rootGroup, it.next());
        // GROUP_Test_GroupA<UUID>
        assertEquals(groupA, it.next());
        // GROUP_Test_GroupB<UUID>
        assertEquals(groupB, it.next());
        // Sort by ID descending
        addOrderBy(otherParams, org.alfresco.rest.api.Groups.PARAM_ID, false);
        resp = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        assertEquals(4, resp.getList().size());
        it = resp.getList().iterator();
        // GROUP_Test_GroupB<UUID>
        assertEquals(groupB, it.next());
        // GROUP_Test_GroupA<UUID>
        assertEquals(groupA, it.next());
        // GROUP_Group_ROOT<UUID>
        assertEquals(rootGroup, it.next());
        // GROUP_EVERYONE
        assertEquals(groupEveryone, it.next());
    }
    // Multiple sort fields not allowed.
    {
        // paging
        Paging paging = getPaging(0, Integer.MAX_VALUE);
        Map<String, String> otherParams = new HashMap<>();
        otherParams.put("orderBy", org.alfresco.rest.api.Groups.PARAM_ID + " ASC," + org.alfresco.rest.api.Groups.PARAM_DISPLAY_NAME + " ASC");
        getGroupsByPersonId(personAlice.getId(), paging, otherParams, HttpServletResponse.SC_BAD_REQUEST);
    }
    // Check include parent ids.
    {
        Paging paging = getPaging(0, Integer.MAX_VALUE);
        Map<String, String> otherParams = new HashMap<>();
        otherParams.put("include", org.alfresco.rest.api.Groups.PARAM_INCLUDE_PARENT_IDS);
        ListResponse<Group> resp = getGroupsByPersonId(personAlice.getId(), paging, otherParams);
        assertEquals(4, resp.getList().size());
        Iterator<Group> it = resp.getList().iterator();
        Group group = it.next();
        assertEquals(groupA.getId(), group.getId());
        assertEquals(1, group.getParentIds().size());
        assertTrue(group.getParentIds().contains(rootGroup.getId()));
        group = it.next();
        assertEquals(groupB.getId(), group.getId());
        assertEquals(1, group.getParentIds().size());
        assertTrue(group.getParentIds().contains(rootGroup.getId()));
        group = it.next();
        assertEquals(PermissionService.ALL_AUTHORITIES, group.getId());
        assertEquals(0, group.getParentIds().size());
        group = it.next();
        assertEquals(rootGroup.getId(), group.getId());
        assertEquals(0, group.getParentIds().size());
    }
    // Filter by zone, use the -me- alias.
    {
        Map<String, String> params = new HashMap<>();
        params.put("include", org.alfresco.rest.api.Groups.PARAM_INCLUDE_ZONES);
        params.put("where", "(zones in ('APP.DEFAULT'))");
        // Use the -me- alias
        ListResponse<Group> response = groupsProxy.getGroupsByPersonId("-me-", params, "Couldn't get user's groups", 200);
        List<Group> groups = response.getList();
        assertFalse(groups.isEmpty());
        // All groups should contain the selected zone.
        groups.forEach(group -> assertTrue(group.getZones().contains("APP.DEFAULT")));
    }
    // Filter by zone, use the -me- alias.
    {
        Map<String, String> params = new HashMap<>();
        params.put("include", org.alfresco.rest.api.Groups.PARAM_INCLUDE_ZONES);
        params.put("where", "(zones in ('APITEST.MYZONE'))");
        // Use the -me- alias
        ListResponse<Group> response = groupsProxy.getGroupsByPersonId("-me-", params, "Couldn't get user's groups", 200);
        List<Group> groups = response.getList();
        assertEquals(3, groups.size());
        // All groups should contain the selected zone.
        groups.forEach(group -> assertTrue(group.getZones().contains("APITEST.MYZONE")));
    }
    // Filter by zone - use the person's ID, without "include"-ing zones
    {
        Map<String, String> params = new HashMap<>();
        params.put("where", "(zones in ('APITEST.ANOTHER'))");
        ListResponse<Group> response = groupsProxy.getGroupsByPersonId(personAlice.getId(), params, "Couldn't get user's groups", 200);
        List<Group> groups = response.getList();
        assertEquals(1, groups.size());
        // We haven't included the zone info
        groups.forEach(group -> assertNull(group.getZones()));
    }
    // Filter zones while using where isRoot=true
    // (this causes a different query path to be used)
    {
        Map<String, String> otherParams = new HashMap<>();
        // Ensure predictable result ordering
        addOrderBy(otherParams, org.alfresco.rest.api.Groups.PARAM_DISPLAY_NAME, true);
        otherParams.put("include", org.alfresco.rest.api.Groups.PARAM_INCLUDE_ZONES);
        otherParams.put("where", "(isRoot=true AND zones in ('APITEST.MYZONE'))");
        ListResponse<Group> response = groupsProxy.getGroupsByPersonId("-me-", otherParams, "Unexpected response", 200);
        List<Group> groups = response.getList();
        assertEquals(1, groups.size());
        assertEquals(rootGroup, groups.get(0));
        assertTrue(groups.get(0).getZones().contains("APITEST.MYZONE"));
        // Zone that doesn't exist.
        otherParams.put("where", "(isRoot=true AND zones in ('I.DO.NOT.EXIST'))");
        response = groupsProxy.getGroupsByPersonId("-me-", otherParams, "Unexpected response", 200);
        groups = response.getList();
        assertTrue(groups.isEmpty());
    }
    // Filter zones while using where isRoot=false
    {
        Map<String, String> otherParams = new HashMap<>();
        // Ensure predictable result ordering
        addOrderBy(otherParams, org.alfresco.rest.api.Groups.PARAM_DISPLAY_NAME, true);
        otherParams.put("where", "(isRoot=false AND zones in ('APITEST.MYZONE'))");
        ListResponse<Group> response = groupsProxy.getGroupsByPersonId("-me-", otherParams, "Unexpected response", 200);
        List<Group> groups = response.getList();
        assertEquals(2, groups.size());
        assertEquals(groupA, groups.get(0));
        assertEquals(groupB, groups.get(1));
        // We haven't included the zones info.
        groups.forEach(group -> assertNull(group.getZones()));
        // Zone that doesn't exist.
        otherParams.put("where", "(isRoot=false AND zones in ('I.DO.NOT.EXIST'))");
        response = groupsProxy.getGroupsByPersonId("-me-", otherParams, "Unexpected response", 200);
        groups = response.getList();
        assertTrue(groups.isEmpty());
    }
    // -ve test: invalid zones clause
    {
        Paging paging = getPaging(0, Integer.MAX_VALUE);
        Map<String, String> otherParams = new HashMap<>();
        otherParams.put("include", org.alfresco.rest.api.Groups.PARAM_INCLUDE_ZONES);
        // Empty zone list
        otherParams.put("where", "(zones in ())");
        groupsProxy.getGroupsByPersonId(personAlice.getId(), otherParams, "Incorrect response", 400);
        // Empty zone name
        otherParams.put("where", "(zones in (''))");
        groupsProxy.getGroupsByPersonId(personAlice.getId(), otherParams, "Incorrect response", 400);
        // Too many zones
        otherParams.put("where", "(zones in ('APP.DEFAULT', 'APITEST.MYZONE'))");
        groupsProxy.getGroupsByPersonId(personAlice.getId(), otherParams, "Incorrect response", 400);
        // "A series of unfortunate errors"
        otherParams.put("where", "(zones in ('', 'APP.DEFAULT', '', 'APITEST.MYZONE'))");
        groupsProxy.getGroupsByPersonId(personAlice.getId(), otherParams, "Incorrect response", 400);
        // OR operator not currently supported
        otherParams.put("where", "(isRoot=true OR zones in ('APP.DEFAULT'))");
        groupsProxy.getGroupsByPersonId(personAlice.getId(), otherParams, "Incorrect response", 400);
    }
}
Also used : AuthorityDAOImpl(org.alfresco.repo.security.authority.AuthorityDAOImpl) java.util(java.util) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) GroupMember(org.alfresco.rest.api.tests.client.data.GroupMember) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) Mock(org.mockito.Mock) Paging(org.alfresco.rest.api.tests.client.PublicApiClient.Paging) Groups(org.alfresco.rest.api.tests.client.PublicApiClient.Groups) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) PermissionService(org.alfresco.service.cmr.security.PermissionService) GUID(org.alfresco.util.GUID) After(org.junit.After) ListResponse(org.alfresco.rest.api.tests.client.PublicApiClient.ListResponse) AuthorityType(org.alfresco.service.cmr.security.AuthorityType) LuceneTests(org.alfresco.util.testing.category.LuceneTests) Before(org.junit.Before) SortColumn(org.alfresco.rest.framework.resource.parameters.SortColumn) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) PublicApiClient(org.alfresco.rest.api.tests.client.PublicApiClient) Category(org.junit.experimental.categories.Category) AbstractSingleNetworkSiteTest(org.alfresco.rest.AbstractSingleNetworkSiteTest) Group(org.alfresco.rest.api.tests.client.data.Group) AuthenticationUtil(org.alfresco.repo.security.authentication.AuthenticationUtil) Person(org.alfresco.rest.api.tests.client.data.Person) ResultSetRow(org.alfresco.service.cmr.search.ResultSetRow) Assert(org.junit.Assert) Group(org.alfresco.rest.api.tests.client.data.Group) ListResponse(org.alfresco.rest.api.tests.client.PublicApiClient.ListResponse) Paging(org.alfresco.rest.api.tests.client.PublicApiClient.Paging) Groups(org.alfresco.rest.api.tests.client.PublicApiClient.Groups) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Person(org.alfresco.rest.api.tests.client.data.Person)

Example 2 with SortColumn

use of org.alfresco.rest.framework.resource.parameters.SortColumn in project alfresco-remote-api by Alfresco.

the class RecognizedParamsExtractor method getSort.

/**
 * Takes the Sort parameter as a String and parses it into a List of SortColumn objects.
 * The format is a comma seperated list of "columnName sortDirection",
 * e.g. "name DESC, age ASC".  It is not case sensitive and the sort direction is optional
 * It default to sort ASCENDING.
 *
 * @param sortParams - String passed in on the request
 * @return - the sort columns or an empty list if the params were invalid.
 */
default List<SortColumn> getSort(String sortParams) {
    if (sortParams != null) {
        StringTokenizer st = new StringTokenizer(sortParams, ",");
        List<SortColumn> sortedColumns = new ArrayList<SortColumn>(st.countTokens());
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            StringTokenizer columnDesc = new StringTokenizer(token, " ");
            if (columnDesc.countTokens() <= 2) {
                String columnName = columnDesc.nextToken();
                String sortOrder = SortColumn.ASCENDING;
                if (columnDesc.hasMoreTokens()) {
                    String sortDef = columnDesc.nextToken().toUpperCase();
                    if (SortColumn.ASCENDING.equals(sortDef) || SortColumn.DESCENDING.equals(sortDef)) {
                        sortOrder = sortDef;
                    } else {
                        rpeLogger().debug("Invalid sort order direction (" + sortDef + ").  Valid values are " + SortColumn.ASCENDING + " or " + SortColumn.DESCENDING + ".");
                        throw new InvalidArgumentException("Unknown sort order direction '" + sortDef + "', expected asc or desc");
                    }
                }
                sortedColumns.add(new SortColumn(columnName, SortColumn.ASCENDING.equals(sortOrder)));
            } else {
                rpeLogger().debug("Invalid sort order definition (" + token + ")");
                throw new InvalidArgumentException("Unknown sort order definition '" + token + "', expected 'field1,field2' or 'field1 asc,field2 desc' or similar");
            }
        // filteredProperties.add();
        }
        // BeanPropertiesFilter filter = new BeanPropertiesFilter(filteredProperties);
        return sortedColumns;
    }
    return Collections.emptyList();
}
Also used : StringTokenizer(java.util.StringTokenizer) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ArrayList(java.util.ArrayList) SortColumn(org.alfresco.rest.framework.resource.parameters.SortColumn)

Example 3 with SortColumn

use of org.alfresco.rest.framework.resource.parameters.SortColumn in project alfresco-remote-api by Alfresco.

the class ProcessDefinitionsImpl method getProcessDefinitions.

@Override
public CollectionWithPagingInfo<ProcessDefinition> getProcessDefinitions(Parameters parameters) {
    ProcessDefinitionQuery query = activitiProcessEngine.getRepositoryService().createProcessDefinitionQuery().processDefinitionCategoryNotEquals(WorkflowDeployer.CATEGORY_ALFRESCO_INTERNAL);
    MapBasedQueryWalker propertyWalker = new MapBasedQueryWalker(PROCESS_DEFINITION_COLLECTION_EQUALS_QUERY_PROPERTIES, PROCESS_DEFINITION_COLLECTION_MATCHES_QUERY_PROPERTIES);
    boolean keyQueryIncluded = false;
    if (parameters.getQuery() != null) {
        QueryHelper.walk(parameters.getQuery(), propertyWalker);
        // Property equals
        String categoryProperty = propertyWalker.getProperty("category", WhereClauseParser.EQUALS);
        if (categoryProperty != null) {
            query.processDefinitionCategory(categoryProperty);
        }
        String keyProperty = propertyWalker.getProperty("key", WhereClauseParser.EQUALS);
        if (keyProperty != null) {
            query.processDefinitionKey(getProcessDefinitionKey(keyProperty));
            keyQueryIncluded = true;
        }
        String nameProperty = propertyWalker.getProperty("name", WhereClauseParser.EQUALS);
        if (nameProperty != null) {
            query.processDefinitionName(nameProperty);
        }
        Integer versionProperty = propertyWalker.getProperty("version", WhereClauseParser.EQUALS, Integer.class);
        if (versionProperty != null) {
            query.processDefinitionVersion(versionProperty);
        }
        String deploymentProperty = propertyWalker.getProperty("deploymentId", WhereClauseParser.EQUALS);
        if (deploymentProperty != null) {
            query.deploymentId(deploymentProperty);
        }
        // Property matches
        String categoryMatchesProperty = propertyWalker.getProperty("category", WhereClauseParser.MATCHES);
        if (categoryMatchesProperty != null) {
            query.processDefinitionCategoryLike(categoryMatchesProperty);
        }
        String keyMatchesProperty = propertyWalker.getProperty("key", WhereClauseParser.MATCHES);
        if (keyMatchesProperty != null) {
            query.processDefinitionKeyLike(getProcessDefinitionKey(keyMatchesProperty));
            keyQueryIncluded = true;
        }
        String nameLikeProperty = propertyWalker.getProperty("name", WhereClauseParser.MATCHES);
        if (nameLikeProperty != null) {
            query.processDefinitionNameLike(nameLikeProperty);
        }
    }
    // Filter based on tenant, if required
    if (keyQueryIncluded == false && tenantService.isEnabled() && deployWorkflowsInTenant) {
        query.processDefinitionKeyLike("@" + TenantUtil.getCurrentDomain() + "@%");
    }
    List<SortColumn> sortList = parameters.getSorting();
    SortColumn sortColumn = null;
    if (sortList != null && sortList.size() > 0) {
        if (sortList.size() != 1) {
            throw new InvalidArgumentException("Only one orderBy parameter is supported");
        }
        sortColumn = sortList.get(0);
        switch(sortColumn.column) {
            case "id":
                query.orderByProcessDefinitionId();
                break;
            case "deploymentId":
                query.orderByDeploymentId();
                break;
            case "key":
                query.orderByProcessDefinitionKey();
                break;
            case "category":
                query.orderByProcessDefinitionCategory();
                break;
            case "version":
                query.orderByProcessDefinitionVersion();
                break;
            case "name":
                query.orderByProcessDefinitionName();
                break;
            default:
                throw new InvalidArgumentException("OrderBy " + sortColumn.column + " is not supported, supported items are " + PROCESS_DEFINITION_COLLECTION_SORT_PROPERTIES);
        }
        if (sortColumn.asc) {
            query.asc();
        } else {
            query.desc();
        }
    } else {
        query.orderByProcessDefinitionId().asc();
    }
    List<org.activiti.engine.repository.ProcessDefinition> processDefinitions = query.listPage(parameters.getPaging().getSkipCount(), parameters.getPaging().getMaxItems());
    int totalCount = (int) query.count();
    List<ProcessDefinition> page = new ArrayList<ProcessDefinition>(processDefinitions.size());
    for (org.activiti.engine.repository.ProcessDefinition processDefinition : processDefinitions) {
        page.add(createProcessDefinitionRest((ProcessDefinitionEntity) processDefinition));
    }
    return CollectionWithPagingInfo.asPaged(parameters.getPaging(), page, (page.size() + parameters.getPaging().getSkipCount()) < totalCount, totalCount);
}
Also used : ArrayList(java.util.ArrayList) ProcessDefinitionQuery(org.activiti.engine.repository.ProcessDefinitionQuery) ProcessDefinition(org.alfresco.rest.workflow.api.model.ProcessDefinition) SortColumn(org.alfresco.rest.framework.resource.parameters.SortColumn) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ProcessDefinitionEntity(org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity)

Example 4 with SortColumn

use of org.alfresco.rest.framework.resource.parameters.SortColumn in project alfresco-remote-api by Alfresco.

the class ProcessesImpl method getProcesses.

@Override
public CollectionWithPagingInfo<ProcessInfo> getProcesses(Parameters parameters) {
    Paging paging = parameters.getPaging();
    MapBasedQueryWalker propertyWalker = new MapBasedQueryWalker(PROCESS_COLLECTION_EQUALS_QUERY_PROPERTIES, null);
    propertyWalker.setSupportedGreaterThanParameters(PROCESS_COLLECTION_GREATERTHAN_QUERY_PROPERTIES);
    propertyWalker.setSupportedLessThanParameters(PROCESS_COLLECTION_LESSTHAN_QUERY_PROPERTIES);
    propertyWalker.enableVariablesSupport(namespaceService, dictionaryService);
    if (parameters.getQuery() != null) {
        QueryHelper.walk(parameters.getQuery(), propertyWalker);
    }
    String status = propertyWalker.getProperty("status", WhereClauseParser.EQUALS);
    String processDefinitionId = propertyWalker.getProperty("processDefinitionId", WhereClauseParser.EQUALS);
    String businessKey = propertyWalker.getProperty("businessKey", WhereClauseParser.EQUALS);
    String processDefinitionKey = propertyWalker.getProperty("processDefinitionKey", WhereClauseParser.EQUALS);
    String startUserId = propertyWalker.getProperty("startUserId", WhereClauseParser.EQUALS);
    Date startedAtGreaterThan = propertyWalker.getProperty("startedAt", WhereClauseParser.GREATERTHAN, Date.class);
    Date startedAtLessThan = propertyWalker.getProperty("startedAt", WhereClauseParser.LESSTHAN, Date.class);
    Date endedAtGreaterThan = propertyWalker.getProperty("endedAt", WhereClauseParser.GREATERTHAN, Date.class);
    Date endedAtLessThan = propertyWalker.getProperty("endedAt", WhereClauseParser.LESSTHAN, Date.class);
    Boolean includeVariables = propertyWalker.getProperty("includeVariables", WhereClauseParser.EQUALS, Boolean.class);
    if (status != null && PROCESS_STATUS_LIST.contains(status) == false) {
        throw new InvalidArgumentException("Invalid status parameter: " + status);
    }
    List<SortColumn> sortList = parameters.getSorting();
    SortColumn sortColumn = null;
    if (sortList != null && sortList.size() > 0) {
        if (sortList.size() != 1) {
            throw new InvalidArgumentException("Only one order by parameter is supported");
        }
        sortColumn = sortList.get(0);
    }
    final HistoricProcessInstanceQuery query = activitiProcessEngine.getHistoryService().createHistoricProcessInstanceQuery();
    if (processDefinitionId != null)
        query.processDefinitionId(processDefinitionId);
    if (businessKey != null)
        query.processInstanceBusinessKey(businessKey);
    if (processDefinitionKey != null) {
        if (tenantService.isEnabled() && deployWorkflowsInTenant) {
            if (processDefinitionKey.startsWith("@" + TenantUtil.getCurrentDomain() + "@")) {
                query.processDefinitionKey(processDefinitionKey);
            } else {
                query.processDefinitionKey("@" + TenantUtil.getCurrentDomain() + "@" + processDefinitionKey);
            }
        } else {
            query.processDefinitionKey(processDefinitionKey);
        }
    }
    if (startUserId != null)
        query.startedBy(startUserId);
    if (startedAtGreaterThan != null)
        query.startedAfter(startedAtGreaterThan);
    if (startedAtLessThan != null)
        query.startedBefore(startedAtLessThan);
    if (endedAtGreaterThan != null)
        query.finishedAfter(endedAtGreaterThan);
    if (endedAtLessThan != null)
        query.finishedBefore(endedAtLessThan);
    if (status == null || PROCESS_STATUS_ACTIVE.equals(status)) {
        query.unfinished();
    } else if (PROCESS_STATUS_COMPLETED.equals(status)) {
        query.finished();
        query.notDeleted();
    } else if (PROCESS_STATUS_DELETED.equals(status)) {
        query.deleted();
    }
    if (includeVariables != null && includeVariables) {
        query.includeProcessVariables();
    }
    List<QueryVariableHolder> variableProperties = propertyWalker.getVariableProperties();
    if (variableProperties != null) {
        for (QueryVariableHolder queryVariableHolder : variableProperties) {
            if (queryVariableHolder.getOperator() == WhereClauseParser.EQUALS) {
                query.variableValueEquals(queryVariableHolder.getPropertyName(), queryVariableHolder.getPropertyValue());
            } else if (queryVariableHolder.getOperator() == WhereClauseParser.GREATERTHAN) {
                query.variableValueGreaterThan(queryVariableHolder.getPropertyName(), queryVariableHolder.getPropertyValue());
            } else if (queryVariableHolder.getOperator() == WhereClauseParser.GREATERTHANOREQUALS) {
                query.variableValueGreaterThanOrEqual(queryVariableHolder.getPropertyName(), queryVariableHolder.getPropertyValue());
            } else if (queryVariableHolder.getOperator() == WhereClauseParser.LESSTHAN) {
                query.variableValueLessThan(queryVariableHolder.getPropertyName(), queryVariableHolder.getPropertyValue());
            } else if (queryVariableHolder.getOperator() == WhereClauseParser.LESSTHANOREQUALS) {
                query.variableValueLessThanOrEqual(queryVariableHolder.getPropertyName(), queryVariableHolder.getPropertyValue());
            } else if (queryVariableHolder.getOperator() == WhereClauseParser.MATCHES) {
                if (queryVariableHolder.getPropertyValue() instanceof String == false) {
                    throw new InvalidArgumentException("the matches operator can only be used with a String value for property " + queryVariableHolder.getPropertyName());
                }
                if (((String) queryVariableHolder.getPropertyValue()).startsWith("(?i)")) {
                    query.variableValueLikeIgnoreCase(queryVariableHolder.getPropertyName(), ((String) queryVariableHolder.getPropertyValue()).substring("(?i)".length()).toLowerCase());
                } else {
                    query.variableValueLike(queryVariableHolder.getPropertyName(), (String) queryVariableHolder.getPropertyValue());
                }
            } else if (queryVariableHolder.getOperator() == WhereClauseParser.NEGATION) {
                query.variableValueNotEquals(queryVariableHolder.getPropertyName(), queryVariableHolder.getPropertyValue());
            } else {
                throw new InvalidArgumentException("variable " + queryVariableHolder.getPropertyName() + " can only be used with an =, >, >=, <=, <, not, matches comparison type");
            }
        }
    }
    if (authorityService.isAdminAuthority(AuthenticationUtil.getRunAsUser())) {
        // Admin is allowed to read all processes in the current tenant
        if (tenantService.isEnabled()) {
            query.variableValueEquals(ActivitiConstants.VAR_TENANT_DOMAIN, TenantUtil.getCurrentDomain());
        }
    } else {
        // If non-admin user, involvement in the process is required (either owner, assignee or externally involved).
        query.involvedUser(AuthenticationUtil.getRunAsUser());
    }
    if (sortColumn != null) {
        if (PROCESS_COLLECTION_SORT_PROPERTIES.contains(sortColumn.column)) {
            if ("processDefinitionId".equalsIgnoreCase(sortColumn.column)) {
                query.orderByProcessDefinitionId();
            } else if ("id".equalsIgnoreCase(sortColumn.column)) {
                query.orderByProcessInstanceId();
            } else if ("businessKey".equalsIgnoreCase(sortColumn.column)) {
                query.orderByProcessInstanceBusinessKey();
            } else if ("startedAt".equalsIgnoreCase(sortColumn.column)) {
                query.orderByProcessInstanceStartTime();
            } else if ("endedAt".equalsIgnoreCase(sortColumn.column)) {
                query.orderByProcessInstanceEndTime();
            } else if ("durationInMillis".equalsIgnoreCase(sortColumn.column)) {
                query.orderByProcessInstanceDuration();
            }
        } else {
            throw new InvalidArgumentException("sort " + sortColumn.column + " is not supported, supported items are " + Arrays.toString(PROCESS_COLLECTION_SORT_PROPERTIES.toArray()));
        }
        if (sortColumn.asc) {
            query.asc();
        } else {
            query.desc();
        }
    } else {
        query.orderByProcessInstanceStartTime().desc();
    }
    List<HistoricProcessInstance> processInstances = query.listPage(paging.getSkipCount(), paging.getMaxItems());
    int totalCount = (int) query.count();
    List<ProcessInfo> page = new ArrayList<ProcessInfo>(processInstances.size());
    Map<String, TypeDefinition> definitionTypeMap = new HashMap<String, TypeDefinition>();
    for (HistoricProcessInstance processInstance : processInstances) {
        ProcessInfo processInfo = createProcessInfo(processInstance);
        if (includeVariables != null && includeVariables) {
            if (definitionTypeMap.containsKey(processInfo.getProcessDefinitionId()) == false) {
                StartFormData startFormData = activitiProcessEngine.getFormService().getStartFormData(processInfo.getProcessDefinitionId());
                if (startFormData != null) {
                    String formKey = startFormData.getFormKey();
                    definitionTypeMap.put(processInfo.getProcessDefinitionId(), getWorkflowFactory().getTaskFullTypeDefinition(formKey, true));
                }
            }
            if (definitionTypeMap.containsKey(processInfo.getProcessDefinitionId())) {
                // Convert raw variables to Variable objects
                List<Variable> resultingVariables = restVariableHelper.getVariables(processInstance.getProcessVariables(), definitionTypeMap.get(processInfo.getProcessDefinitionId()));
                processInfo.setProcessVariables(resultingVariables);
            }
        }
        page.add(processInfo);
    }
    return CollectionWithPagingInfo.asPaged(paging, page, (page.size() + paging.getSkipCount()) < totalCount, totalCount);
}
Also used : Variable(org.alfresco.rest.workflow.api.model.Variable) HistoricProcessInstanceQuery(org.activiti.engine.history.HistoricProcessInstanceQuery) HashMap(java.util.HashMap) Paging(org.alfresco.rest.framework.resource.parameters.Paging) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) ArrayList(java.util.ArrayList) QueryVariableHolder(org.alfresco.rest.workflow.api.impl.MapBasedQueryWalker.QueryVariableHolder) ProcessInfo(org.alfresco.rest.workflow.api.model.ProcessInfo) SortColumn(org.alfresco.rest.framework.resource.parameters.SortColumn) Date(java.util.Date) TypeDefinition(org.alfresco.service.cmr.dictionary.TypeDefinition) DataTypeDefinition(org.alfresco.service.cmr.dictionary.DataTypeDefinition) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) StartFormData(org.activiti.engine.form.StartFormData)

Example 5 with SortColumn

use of org.alfresco.rest.framework.resource.parameters.SortColumn in project alfresco-remote-api by Alfresco.

the class GroupsImpl method getGroupsSortProp.

private Pair<String, Boolean> getGroupsSortProp(Parameters parameters) {
    Pair<String, Boolean> sortProp;
    List<SortColumn> sortCols = parameters.getSorting();
    if ((sortCols != null) && (sortCols.size() > 0)) {
        if (sortCols.size() > 1) {
            throw new InvalidArgumentException("Multiple sort fields not allowed.");
        }
        SortColumn sortCol = sortCols.get(0);
        String sortPropName = SORT_PARAMS_TO_NAMES.get(sortCol.column);
        if (sortPropName == null) {
            throw new InvalidArgumentException("Invalid sort field: " + sortCol.column);
        }
        sortProp = new Pair<>(sortPropName, (sortCol.asc ? Boolean.TRUE : Boolean.FALSE));
    } else {
        sortProp = getGroupsSortPropDefault();
    }
    return sortProp;
}
Also used : InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) SortColumn(org.alfresco.rest.framework.resource.parameters.SortColumn)

Aggregations

SortColumn (org.alfresco.rest.framework.resource.parameters.SortColumn)13 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)10 ArrayList (java.util.ArrayList)8 Paging (org.alfresco.rest.framework.resource.parameters.Paging)6 QName (org.alfresco.service.namespace.QName)3 Pair (org.alfresco.util.Pair)3 Date (java.util.Date)2 HashMap (java.util.HashMap)2 List (java.util.List)2 HistoricTaskInstance (org.activiti.engine.history.HistoricTaskInstance)2 HistoricTaskInstanceQuery (org.activiti.engine.history.HistoricTaskInstanceQuery)2 TaskQuery (org.activiti.engine.task.TaskQuery)2 PagingRequest (org.alfresco.query.PagingRequest)2 FilterProp (org.alfresco.repo.node.getchildren.FilterProp)2 BeanPropertiesFilter (org.alfresco.rest.framework.jacksonextensions.BeanPropertiesFilter)2 QueryVariableHolder (org.alfresco.rest.workflow.api.impl.MapBasedQueryWalker.QueryVariableHolder)2 Task (org.alfresco.rest.workflow.api.model.Task)2 DataTypeDefinition (org.alfresco.service.cmr.dictionary.DataTypeDefinition)2 TypeDefinition (org.alfresco.service.cmr.dictionary.TypeDefinition)2 java.util (java.util)1