Search in sources :

Example 1 with Paging

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

the class SerializeTests method testExpandRelations.

@Test
public void testExpandRelations() throws IOException {
    assertNotNull(helper);
    Map<String, BeanPropertiesFilter> rFilter = getRelationFilter("blacksheep,baaahh");
    ExecutionResult res = (ExecutionResult) helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, "sheep", ParamsExtender.valueOf(rFilter, "1"), new Farmer("180"));
    assertNotNull(res);
    String out = writeResponse(res);
    assertTrue(Farmer.class.equals(res.getRoot().getClass()));
    assertTrue("There must be json output", StringUtils.isNotBlank(out));
    Paging pageRequest = Paging.valueOf(1, 2);
    Object resultCollection = helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, "sheep", ParamsExtender.valueOf(rFilter, "1"), CollectionWithPagingInfo.asPaged(pageRequest, Arrays.asList(new Farmer("180"), new Farmer("190"), new Farmer("280"))));
    assertNotNull(resultCollection);
    out = writeResponse(resultCollection);
    assertTrue("There must be json output", StringUtils.isNotBlank(out));
}
Also used : Paging(org.alfresco.rest.framework.resource.parameters.Paging) WebScriptResponse(org.springframework.extensions.webscripts.WebScriptResponse) ExecutionResult(org.alfresco.rest.framework.jacksonextensions.ExecutionResult) JSONObject(org.json.JSONObject) Farmer(org.alfresco.rest.framework.tests.api.mocks.Farmer) BeanPropertiesFilter(org.alfresco.rest.framework.jacksonextensions.BeanPropertiesFilter) Test(org.junit.Test)

Example 2 with Paging

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

the class RecognizedParamsExtractorTest method findPagingTest.

@Test
public void findPagingTest() {
    WebScriptRequest request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn("34");
    when(request.getParameter("maxItems")).thenReturn("50");
    Paging pagin = findPaging(request);
    assertNotNull(pagin);
    assertTrue(pagin.getSkipCount() == 34);
    assertTrue(pagin.getMaxItems() == 50);
    request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn(null);
    when(request.getParameter("maxItems")).thenReturn(null);
    pagin = findPaging(request);
    assertNotNull(pagin);
    assertTrue(pagin.getSkipCount() == Paging.DEFAULT_SKIP_COUNT);
    assertTrue(pagin.getMaxItems() == Paging.DEFAULT_MAX_ITEMS);
    request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn("55");
    pagin = findPaging(request);
    assertNotNull(pagin);
    assertTrue(pagin.getSkipCount() == 55);
    assertTrue(pagin.getMaxItems() == Paging.DEFAULT_MAX_ITEMS);
    request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn(null);
    when(request.getParameter("maxItems")).thenReturn("45");
    pagin = findPaging(request);
    assertNotNull(pagin);
    assertTrue(pagin.getMaxItems() == 45);
    assertTrue(pagin.getSkipCount() == Paging.DEFAULT_SKIP_COUNT);
    request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn("apple");
    when(request.getParameter("maxItems")).thenReturn("pear");
    try {
        pagin = findPaging(request);
        fail("Should not get here.");
    } catch (InvalidArgumentException iae) {
        // Must throw this exceptions
        assertNotNull(iae);
    }
    request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn("0");
    when(request.getParameter("maxItems")).thenReturn("0");
    try {
        pagin = findPaging(request);
        fail("Should not get here.");
    } catch (InvalidArgumentException iae) {
        // Must throw this exceptions
        assertNotNull(iae);
    }
    // Test Case cloud-2198
    request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn("0");
    when(request.getParameter("maxItems")).thenReturn("a");
    try {
        pagin = findPaging(request);
        fail("Should not get here.");
    } catch (InvalidArgumentException iae) {
        // Must throw this exceptions
        assertNotNull(iae);
    }
    request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn("s");
    when(request.getParameter("maxItems")).thenReturn("5");
    try {
        pagin = findPaging(request);
        fail("Should not get here.");
    } catch (InvalidArgumentException iae) {
        // Must throw this exceptions
        assertNotNull(iae);
    }
    request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn("0");
    when(request.getParameter("maxItems")).thenReturn("-2");
    try {
        pagin = findPaging(request);
        fail("Should not get here.");
    } catch (InvalidArgumentException iae) {
        // Must throw this exceptions
        assertNotNull(iae);
    }
    request = mock(WebScriptRequest.class);
    when(request.getParameter("skipCount")).thenReturn("-3");
    when(request.getParameter("maxItems")).thenReturn("5");
    try {
        pagin = findPaging(request);
        fail("Should not get here.");
    } catch (InvalidArgumentException iae) {
        // Must throw this exceptions
        assertNotNull(iae);
    }
    request = mock(WebScriptRequest.class);
    when(request.getParameter("maxItems")).thenReturn("5");
    pagin = findPaging(request);
    assertNotNull(pagin);
    assertTrue("skip count defaults to 0", pagin.getSkipCount() == Paging.DEFAULT_SKIP_COUNT);
// End of Test Case cloud-2198
}
Also used : WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) Paging(org.alfresco.rest.framework.resource.parameters.Paging) Test(org.junit.Test)

Example 3 with Paging

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

the class AuditImpl method listAuditEntriesByNodeId.

@Override
public CollectionWithPagingInfo<AuditEntry> listAuditEntriesByNodeId(String nodeId, Parameters parameters) {
    AuthenticationUtil.runAs(new RunAsWork<Void>() {

        public Void doWork() throws Exception {
            checkEnabled();
            return null;
        }
    }, AuthenticationUtil.getSystemUserName());
    // note: node read permission is checked later - see nodeService.getPath
    NodeRef nodeRef = nodes.validateNode(nodeId);
    List<AuditEntry> entriesAudit = new ArrayList<>();
    // adding orderBy property
    Pair<String, Boolean> sortProp = getAuditEntrySortProp(parameters);
    Boolean forward = true;
    if ((sortProp != null) && (sortProp.getFirst().equals(CREATED_AT))) {
        forward = sortProp.getSecond();
    }
    // paging
    Paging paging = parameters.getPaging();
    int skipCount = paging.getSkipCount();
    int maxItems = paging.getMaxItems();
    // to detect hasMoreItems
    int limit = skipCount + maxItems + 1;
    Query q = parameters.getQuery();
    if (q != null) {
        // filtering via "where" clause
        AuditEntriesByNodeIdQueryWalker propertyWalker = new AuditEntriesByNodeIdQueryWalker();
        QueryHelper.walk(q, propertyWalker);
        entriesAudit = getQueryResultAuditEntriesByNodeRef(nodeRef, propertyWalker, parameters.getInclude(), forward, limit);
    }
    // clear null elements
    entriesAudit.removeAll(Collections.singleton(null));
    int totalItems = entriesAudit.size();
    if (skipCount >= totalItems) {
        List<AuditEntry> empty = Collections.emptyList();
        return CollectionWithPagingInfo.asPaged(paging, empty, false, totalItems);
    } else {
        int end = Math.min(limit - 1, totalItems);
        boolean hasMoreItems = totalItems > end;
        entriesAudit = entriesAudit.subList(skipCount, end);
        return CollectionWithPagingInfo.asPaged(paging, entriesAudit, hasMoreItems, totalItems);
    }
}
Also used : Query(org.alfresco.rest.framework.resource.parameters.where.Query) Paging(org.alfresco.rest.framework.resource.parameters.Paging) ArrayList(java.util.ArrayList) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) DisabledServiceException(org.alfresco.rest.framework.core.exceptions.DisabledServiceException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) AuditEntry(org.alfresco.rest.api.model.AuditEntry)

Example 4 with Paging

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

the class AuditImpl method listAuditEntries.

@Override
public CollectionWithPagingInfo<AuditEntry> listAuditEntries(String auditAppId, Parameters parameters) {
    checkEnabled();
    AuditService.AuditApplication auditApplication = findAuditAppByIdOr404(auditAppId);
    // adding orderBy property
    Pair<String, Boolean> sortProp = getAuditEntrySortProp(parameters);
    Boolean forward = true;
    if ((sortProp != null) && (sortProp.getFirst().equals(CREATED_AT))) {
        forward = sortProp.getSecond();
    }
    // Parse where clause properties.
    List<AuditEntry> entriesAudit = new ArrayList<>();
    Query q = parameters.getQuery();
    // paging
    Paging paging = parameters.getPaging();
    int skipCount = paging.getSkipCount();
    int maxItems = paging.getMaxItems();
    // to detect hasMoreItems
    int limit = skipCount + maxItems + 1;
    if (q != null) {
        // filtering via "where" clause
        AuditEntryQueryWalker propertyWalker = new AuditEntryQueryWalker();
        QueryHelper.walk(q, propertyWalker);
        entriesAudit = getQueryResultAuditEntries(auditApplication, propertyWalker, parameters.getInclude(), limit, forward);
    }
    // clear null elements
    entriesAudit.removeAll(Collections.singleton(null));
    int totalItems = entriesAudit.size();
    if (skipCount >= totalItems) {
        List<AuditEntry> empty = Collections.emptyList();
        return CollectionWithPagingInfo.asPaged(paging, empty, false, totalItems);
    } else {
        int end = Math.min(limit - 1, totalItems);
        boolean hasMoreItems = totalItems > end;
        entriesAudit = entriesAudit.subList(skipCount, end);
        return CollectionWithPagingInfo.asPaged(paging, entriesAudit, hasMoreItems, totalItems);
    }
}
Also used : Query(org.alfresco.rest.framework.resource.parameters.where.Query) Paging(org.alfresco.rest.framework.resource.parameters.Paging) ArrayList(java.util.ArrayList) AuditApplication(org.alfresco.service.cmr.audit.AuditService.AuditApplication) AuditEntry(org.alfresco.rest.api.model.AuditEntry) AuditService(org.alfresco.service.cmr.audit.AuditService)

Example 5 with Paging

use of org.alfresco.rest.framework.resource.parameters.Paging 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)

Aggregations

Paging (org.alfresco.rest.framework.resource.parameters.Paging)34 ArrayList (java.util.ArrayList)18 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)11 Query (org.alfresco.rest.framework.resource.parameters.where.Query)10 PagingRequest (org.alfresco.query.PagingRequest)9 SortColumn (org.alfresco.rest.framework.resource.parameters.SortColumn)8 Pair (org.alfresco.util.Pair)8 AbstractList (java.util.AbstractList)7 HashMap (java.util.HashMap)6 List (java.util.List)6 Test (org.junit.Test)6 EntityNotFoundException (org.alfresco.rest.framework.core.exceptions.EntityNotFoundException)5 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)5 HashSet (java.util.HashSet)4 AuthorityInfo (org.alfresco.repo.security.authority.AuthorityInfo)4 NodeRef (org.alfresco.service.cmr.repository.NodeRef)4 Map (java.util.Map)3 Set (java.util.Set)3 EmptyPagingResults (org.alfresco.query.EmptyPagingResults)3 GroupMember (org.alfresco.rest.api.model.GroupMember)3