Java Code Examples for org.alfresco.query.PagingRequest#setRequestTotalCountMax()

The following examples show how to use org.alfresco.query.PagingRequest#setRequestTotalCountMax() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ArchivedNodesCannedQueryBuilder.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ArchivedNodesCannedQueryBuilder(Builder builder)
{
    ParameterCheck.mandatory("storeRef", (this.archiveRootNodeRef = builder.archiveRootNodeRef));
    ParameterCheck.mandatory("pagingRequest", builder.pagingRequest);        
  
    // Defensive copy
    PagingRequest pr = new PagingRequest(builder.pagingRequest.getSkipCount(),
                builder.pagingRequest.getMaxItems(),
                builder.pagingRequest.getQueryExecutionId());
    pr.setRequestTotalCountMax(builder.pagingRequest.getRequestTotalCountMax());
    this.pagingRequest = pr;
    this.filter = builder.filter;        
    this.sortOrderAscending = builder.sortOrderAscending;
}
 
Example 2
Source File: ArchivedNodesCannedQueryBuilder.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public PagingRequest getPagingRequest()
{
    PagingRequest pr = new PagingRequest(this.pagingRequest.getSkipCount(),
                this.pagingRequest.getMaxItems(), this.pagingRequest.getQueryExecutionId());
    pr.setRequestTotalCountMax(this.pagingRequest.getRequestTotalCountMax());
    
    return pr;
}
 
Example 3
Source File: GetChildrenCannedQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private PagingResults<NodeRef> list(NodeRef parentNodeRef, final int skipCount, final int maxItems, final int requestTotalCountMax, String pattern, List<Pair<QName, Boolean>> sortProps)
{
    PagingRequest pagingRequest = new PagingRequest(skipCount, maxItems, null);
    pagingRequest.setRequestTotalCountMax(requestTotalCountMax);
    
    // get canned query
    GetChildrenCannedQueryFactory getChildrenCannedQueryFactory = (GetChildrenCannedQueryFactory)cannedQueryRegistry.getNamedObject(CQ_FACTORY_NAME);
    final GetChildrenCannedQuery cq = (GetChildrenCannedQuery)getChildrenCannedQueryFactory.getCannedQuery(parentNodeRef, pattern, null, null, null, null,  null, sortProps, pagingRequest);
    
    // execute canned query
    RetryingTransactionCallback<CannedQueryResults<NodeRef>> callback = new RetryingTransactionCallback<CannedQueryResults<NodeRef>>()
    {
        @Override
        public CannedQueryResults<NodeRef> execute() throws Throwable
        {
            return cq.execute();
        }
    };
    CannedQueryResults<NodeRef> results = transactionService.getRetryingTransactionHelper().doInTransaction(callback, true);
    
    List<NodeRef> nodeRefs = results.getPages().get(0);
    
    Integer totalCount = null;
    if (requestTotalCountMax > 0)
    {
        totalCount = results.getTotalResultCount().getFirst();
    }
    
    return new PagingNodeRefResultsImpl(nodeRefs, results.hasMoreItems(), totalCount, false);
}
 
Example 4
Source File: GetChildrenCannedQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private PagingResults<NodeRef> list(NodeRef parentNodeRef, final int skipCount, final int maxItems, final int requestTotalCountMax, Set<QName> childTypeQNames, List<FilterProp> filterProps, List<Pair<QName, Boolean>> sortProps)
{
    PagingRequest pagingRequest = new PagingRequest(skipCount, maxItems, null);
    pagingRequest.setRequestTotalCountMax(requestTotalCountMax);
    
    // get canned query (note: test the fileFolder extension - including support for sorting folders first)
    GetChildrenCannedQueryFactory getChildrenCannedQueryFactory = (GetChildrenCannedQueryFactory)cannedQueryRegistry.getNamedObject(CQ_FACTORY_NAME);
    final GetChildrenCannedQuery cq = (GetChildrenCannedQuery)getChildrenCannedQueryFactory.getCannedQuery(parentNodeRef, null, null, childTypeQNames, null, null, filterProps, sortProps, pagingRequest);
    
    // execute canned query
    RetryingTransactionCallback<CannedQueryResults<NodeRef>> callback = new RetryingTransactionCallback<CannedQueryResults<NodeRef>>()
    {
        @Override
        public CannedQueryResults<NodeRef> execute() throws Throwable
        {
            return cq.execute();
        }
    };
    CannedQueryResults<NodeRef> results = transactionService.getRetryingTransactionHelper().doInTransaction(callback, true);
    
    List<NodeRef> nodeRefs = results.getPages().get(0);
    
    Integer totalCount = null;
    if (requestTotalCountMax > 0)
    {
        totalCount = results.getTotalResultCount().getFirst();
    }
    
    return new PagingNodeRefResultsImpl(nodeRefs, results.hasMoreItems(), totalCount, false);
}
 
Example 5
Source File: GetChildrenCannedQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private PagingResults<NodeRef> list(NodeRef parentNodeRef, final int skipCount, final int maxItems, final int requestTotalCountMax, Set<QName> assocTypeQNames, Set<QName> childTypeQNames, List<FilterProp> filterProps, List<Pair<QName, Boolean>> sortProps, Set<QName> inclusiveAspects, Set<QName> exclusiveAspects)
{
    PagingRequest pagingRequest = new PagingRequest(skipCount, maxItems, null);
    pagingRequest.setRequestTotalCountMax(requestTotalCountMax);
    
    // get canned query
    GetChildrenCannedQueryFactory getChildrenCannedQueryFactory = (GetChildrenCannedQueryFactory)cannedQueryRegistry.getNamedObject(CQ_FACTORY_NAME);
    final GetChildrenCannedQuery cq = (GetChildrenCannedQuery)getChildrenCannedQueryFactory.getCannedQuery(parentNodeRef, null, assocTypeQNames, childTypeQNames, inclusiveAspects, exclusiveAspects, filterProps, sortProps, pagingRequest);
    
    // execute canned query
    RetryingTransactionCallback<CannedQueryResults<NodeRef>> callback = new RetryingTransactionCallback<CannedQueryResults<NodeRef>>()
    {
        @Override
        public CannedQueryResults<NodeRef> execute() throws Throwable
        {
            return cq.execute();
        }
    };
    CannedQueryResults<NodeRef> results = transactionService.getRetryingTransactionHelper().doInTransaction(callback, true);
    
    List<NodeRef> nodeRefs = results.getPages().get(0);
    
    Integer totalCount = null;
    if (requestTotalCountMax > 0)
    {
        totalCount = results.getTotalResultCount().getFirst();
    }
    
    return new PagingNodeRefResultsImpl(nodeRefs, results.hasMoreItems(), totalCount, false);
}
 
Example 6
Source File: AbstractSubscriptionServiceWebScript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected PagingRequest createPagingRequest(WebScriptRequest req)
{
    int skipCount = parseNumber("skipCount", req.getParameter("skipCount"), 0);
    int maxItems = parseNumber("maxItems", req.getParameter("maxItems"), -1);

    PagingRequest result = new PagingRequest(skipCount, maxItems, null);
    result.setRequestTotalCountMax(Integer.MAX_VALUE);

    return result;
}
 
Example 7
Source File: PageCollator.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @param objects
 * @param objectPageSurce
 * @param pagingRequest
 * @param comparator
 * @return a {@link PagingResults} R objects obtained from merging a
 *         collection of R objects with a paged result obtained from a
 *         {@link PagingResultsSource} considering the a merged result
 *         {@link PagingRequest}
 * @throws PageCollationException
 */
public PagingResults<R> collate(List<R> objects, PagingResultsSource<R> objectPageSurce,
            PagingRequest pagingRequest, Comparator<R> comparator) throws PageCollationException
{
    final int skip = pagingRequest.getSkipCount();
    final int pageSize = pagingRequest.getMaxItems();

    if (skip < 0 || pageSize < 0)
    {
        throw new InvalidPageBounds("Negative page skip index and/or bounds.");
    }

    int preemptiveSkip = Math.max(0,
                                  skip - objects.size());
    int pageSkip = skip - preemptiveSkip;
    int preemptiveSize = pageSize + pageSkip;
    PagingResults<R> pageResults = null;
    try
    {
        PagingRequest preemptiveRequest = new PagingRequest(preemptiveSkip,
                                                            preemptiveSize,
                                                            pagingRequest.getQueryExecutionId());
        preemptiveRequest.setRequestTotalCountMax(pagingRequest.getRequestTotalCountMax());
        pageResults = objectPageSurce.retrieve(preemptiveRequest);
    }
    catch (InvalidPageBounds e)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug(e);
        }
        pageResults = new PagingResults<R>()
        {

            @Override
            public List<R> getPage()
            {
                return Collections.emptyList();
            }

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

            @Override
            public Pair<Integer, Integer> getTotalResultCount()
            {
                return new Pair<Integer, Integer>(null,
                                                  null);
            }

            @Override
            public String getQueryExecutionId()
            {
                return null;
            }
        };
    }

    return collate(objects,
                   pageResults,
                   pageSkip,
                   pagingRequest,
                   comparator);
}
 
Example 8
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
/**
 * @param files                Return files extending from cm:content
 * @param folders              Return folders extending from cm:folder - ignoring sub-types of cm:systemfolder
 * @param ignoreTypes          Also optionally removes additional type qnames. The additional type can be
 *                             specified in short or long qname string form as a single string or an Array e.g. "fm:forum".
 * @param skipOffset           Items to skip (e.g. 0 or (num pages to skip * size of page)
 * @param maxItems             Max number of items (eg. size of page)
 * @param requestTotalCountMax Request total count (upto a given max total count)
 *                             Note: if 0 then total count is not requested and the query may be able to optimise/cutoff for max items)
 * @param sortProp             Optional sort property as a prefix qname string (e.g. "cm:name"). Also supports special 
 *                             content case (i.e. "cm:content.size" and "cm:content.mimetype")
 * @param sortAsc              Given a sort property, true => ascending, false => descending
 * @param queryExecutionId     If paging then can pass back the previous query execution (as a hint for possible query optimisation)
 *                             
 * @return Returns ScriptPagingNodes which includes a JavaScript array of child file/folder nodes for this nodes.
 *         Automatically retrieves all sub-types of cm:content and cm:folder, also removes
 *         system folder types from the results.
 *         This is equivalent to @see FileFolderService.listFiles() and @see FileFolderService.listFolders()
 *         
 * <br/><br/>author janv
 * @since 4.0
 */
public ScriptPagingNodes childFileFolders(boolean files, boolean folders, Object ignoreTypes, int skipOffset, int maxItems, int requestTotalCountMax, String sortProp, Boolean sortAsc, String queryExecutionId)
{
    Object[] results;
    
    Set<QName> ignoreTypeQNames = new HashSet<QName>(5);
    
    // Add user defined types to ignore
    if (ignoreTypes instanceof ScriptableObject)
    {
        Serializable types = getValueConverter().convertValueForRepo((ScriptableObject)ignoreTypes);
        if (types instanceof List)
        {
            for (Serializable typeObj : (List<Serializable>)types)
            {
                ignoreTypeQNames.add(createQName(typeObj.toString()));
            }
        }
        else if (types instanceof String)
        {
            ignoreTypeQNames.add(createQName(types.toString()));
        }
    }
    else if (ignoreTypes instanceof String)
    {
        ignoreTypeQNames.add(createQName(ignoreTypes.toString()));
    }
    
    // ALF-13968 - sort folders before files (for Share) - TODO should be optional sort param
    List<Pair<QName, Boolean>> sortProps = new ArrayList<Pair<QName, Boolean>>(2);
    if ((sortProp == null) || (! sortProp.equals(GetChildrenCannedQuery.SORT_QNAME_NODE_TYPE.getLocalName())))
    {
        sortProps.add(new Pair<QName, Boolean>(GetChildrenCannedQuery.SORT_QNAME_NODE_IS_FOLDER, false));
    }
    if (sortProp != null)
    {
        sortProps.add(new Pair<QName, Boolean>(createQName(sortProp), sortAsc));
    }
    
    PagingRequest pageRequest = new PagingRequest(skipOffset, maxItems, queryExecutionId);
    pageRequest.setRequestTotalCountMax(requestTotalCountMax);
    
    PagingResults<FileInfo> pageOfNodeInfos = null;
    FileFilterMode.setClient(Client.script);
    try
    {
        pageOfNodeInfos = this.fileFolderService.list(this.nodeRef, files, folders, null, ignoreTypeQNames, sortProps, pageRequest);
    }
    finally
    {
        FileFilterMode.clearClient();
    }

    List<FileInfo> nodeInfos = pageOfNodeInfos.getPage();
    int size = nodeInfos.size();
    results = new Object[size];
    for (int i=0; i<size; i++)
    {
        FileInfo nodeInfo = nodeInfos.get(i);
        results[i] = newInstance(nodeInfo, this.services, this.scope);
    }
    
    int totalResultCountLower = -1;
    int totalResultCountUpper = -1;
    
    Pair<Integer, Integer> totalResultCount = pageOfNodeInfos.getTotalResultCount();
    if (totalResultCount != null)
    {
        totalResultCountLower = (totalResultCount.getFirst() != null ? totalResultCount.getFirst() : -1);
        totalResultCountUpper = (totalResultCount.getSecond() != null ? totalResultCount.getSecond() : -1);
    }
    
    return new ScriptPagingNodes(Context.getCurrentContext().newArray(this.scope, results), pageOfNodeInfos.hasMoreItems(), totalResultCountLower, totalResultCountUpper);
}
 
Example 9
Source File: FileFolderServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testList_HiddenFiles()
{
    // Test that hidden files are not returned for clients that should not be able to see them,
    // and that the total result count is correct.

    Client saveClient = FileFilterMode.setClient(Client.webdav);
    try
    {
        // create some hidden files
        NodeRef nodeRef = fileFolderService.create(workingRootNodeRef, "" + System.currentTimeMillis(), ContentModel.TYPE_CONTENT).getNodeRef();
        NodeRef nodeRef1 = fileFolderService.create(nodeRef, "parent", ContentModel.TYPE_CONTENT).getNodeRef();
        for(int i = 0; i < 10; i++)
        {
            fileFolderService.create(nodeRef1, ".child" + i, ContentModel.TYPE_CONTENT).getNodeRef();
        }
        
        // and some visible files
        for(int i = 0; i < 10; i++)
        {
            fileFolderService.create(nodeRef1, "visiblechild" + i, ContentModel.TYPE_CONTENT).getNodeRef();
        }

        // switch to a client that should not see the hidden files
        saveClient = FileFilterMode.setClient(Client.cmis);
        PagingRequest pagingRequest = new PagingRequest(0, Integer.MAX_VALUE);
        pagingRequest.setRequestTotalCountMax(10000); // need this so that total count is set

        PagingResults<FileInfo> results = fileFolderService.list(nodeRef1, true, true, null, null, pagingRequest);
        Pair<Integer, Integer> totalResultCount = results.getTotalResultCount();
        assertNotNull(totalResultCount.getFirst());
        assertEquals("Total result lower count should be 10", 10, totalResultCount.getFirst().intValue());
        assertNotNull(totalResultCount.getSecond());
        assertEquals("Total result upper count should be 10", 10, totalResultCount.getSecond().intValue());
        for(FileInfo fileInfo : results.getPage())
        {
            assertTrue(fileInfo.getName().startsWith("visiblechild"));
        }
        assertEquals("Expected only 10 results", 10, results.getPage().size());
    }
    finally
    {
        FileFilterMode.setClient(saveClient);
    }
}
 
Example 10
Source File: FileFolderServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void checkPages(NodeRef parentRef, int pageSize, int totalItems, boolean hideCheckedOut, int checkedOutChildIdx)
{
    Set<QName> ignoreQNameTypes = null;
    if (hideCheckedOut)
    {
        ignoreQNameTypes = new HashSet<QName>(1);
        ignoreQNameTypes.add(ContentModel.ASPECT_CHECKED_OUT);
    }
    else
    {
        if (checkedOutChildIdx > -1)
        {
            totalItems++;
        }
    }
    
    List<Pair<QName, Boolean>> sortProps = new ArrayList<Pair<QName, Boolean>>(1);
    sortProps.add(new Pair<QName, Boolean>(ContentModel.PROP_NAME, true));
    
    int pageCount = (totalItems / pageSize) + 1;
    
    for (int i = 1; i <= pageCount; i++)
    {
        int offset = (i-1)*pageSize;
        
        PagingRequest pagingRequest = new PagingRequest(offset, pageSize);
        pagingRequest.setRequestTotalCountMax(10000); // need this so that total count is set
        
        PagingResults<FileInfo> results = fileFolderService.list(parentRef, true, true, ignoreQNameTypes, sortProps, pagingRequest);
        
        Pair<Integer, Integer> totalResultCount = results.getTotalResultCount();
        assertNotNull(totalResultCount.getFirst());
        assertEquals(totalItems, totalResultCount.getFirst().intValue());
        assertNotNull(totalResultCount.getSecond());
        assertEquals(totalItems, totalResultCount.getSecond().intValue());
        
        assertEquals((i != pageCount ? pageSize : (totalItems - ((pageCount-1)*pageSize))), results.getPage().size());
        
        int j = offset;
        for (FileInfo fileInfo : results.getPage())
        {
            String suffix = String.format("%05d", j);
            if (checkedOutChildIdx > -1)
            {
                if (! hideCheckedOut)
                {
                    if (j == checkedOutChildIdx+1)
                    {
                        suffix = String.format("%05d", j-1) + " (Working Copy)";
                    }
                    else if (j > checkedOutChildIdx+1)
                    {
                        suffix = String.format("%05d", j-1);
                    }
                }
                else
                {
                    if (j == checkedOutChildIdx)
                    {
                        suffix = String.format("%05d", j) + " (Working Copy)";
                    }
                }
            }
            
            String actual = fileInfo.getName();
            String expected = "child-"+suffix;
            assertTrue("Expected: "+expected+", Actual: "+actual+" (j="+j+")", expected.equals(actual));
            j++;
        }
    }
}
 
Example 11
Source File: CopyServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * <a href="https://issues.alfresco.com/jira/browse/MNT-9580">
 *      MNT-9580: Daisy chained cm:original associations are cascade-deleted when the first original is deleted
 * </a>
 */
public void testCopyOfCopyOfCopy()
{
    IntegrityChecker integrityChecker = (IntegrityChecker) ctx.getBean("integrityChecker");

    // Create the node used for copying
    ChildAssociationRef childAssocRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}test"),
            TEST_TYPE_QNAME,
            createTypePropertyBag());
    NodeRef nodeRef = childAssocRef.getChildRef();

    PagingRequest pageRequest = new PagingRequest(10);
    pageRequest.setRequestTotalCountMax(200);
    PagingResults<CopyInfo> copies = null;
    
    NodeRef currentOriginal = nodeRef;
    NodeRef copyNodeRef = null;

    for (int i = 1; i <= 5; i++)
    {
        copyNodeRef = copyService.copy(
                currentOriginal,
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName("{test}copyAssoc"+i));
        copies = copyService.getCopies(currentOriginal, pageRequest);
        assertEquals("Incorrect number of copies on iteration " + i, 1, copies.getPage().size());

        // Check that the original node can be retrieved
        NodeRef originalCheck = copyService.getOriginal(copyNodeRef);
        assertEquals("Original is not as expected. ", currentOriginal, originalCheck);
        // Run integrity checks to ensure that commit has a chance
        integrityChecker.checkIntegrity();
        
        currentOriginal = copyNodeRef;
    }
    
    // Now, delete the nodes starting with the first original
    currentOriginal = nodeRef;
    copyNodeRef = null;
    for (int i = 1; i < 5; i++)
    {
        // Each node must be an original
        copies = copyService.getCopies(currentOriginal, pageRequest);
        assertEquals("Incorrect number of copies on iteration " + i, 1, copies.getPage().size());
        copyNodeRef = copies.getPage().get(0).getNodeRef();
        // Delete current original
        nodeService.deleteNode(currentOriginal);
        // Run integrity checks to ensure that commit has a chance
        integrityChecker.checkIntegrity();
        
        currentOriginal = copyNodeRef;
    }
}
 
Example 12
Source File: AbstractDiscussionWebScript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected Map<String, Object> renderTopic(TopicInfo topic, SiteInfo site)
{
   // Fetch the primary post
   PostInfo primaryPost = discussionService.getPrimaryPost(topic);
   if (primaryPost == null)
   {
      throw new WebScriptException(Status.STATUS_PRECONDITION_FAILED,
             "First (primary) post was missing from the topic, can't fetch");
   }
   
   // Fetch the most recent reply
   PostInfo mostRecentPost = discussionService.getMostRecentPost(topic);
   
   // Find out how many replies there are
   int numReplies;
   if (mostRecentPost.getNodeRef().equals( primaryPost.getNodeRef() ))
   {
      // Only the one post in the topic
      mostRecentPost = null;
      numReplies = 0;
   }
   else
   {
      // Use this trick to get the number of posts in the topic, 
      //  but without needing to get lots of data and objects
      PagingRequest paging = new PagingRequest(1);
      paging.setRequestTotalCountMax(MAX_QUERY_ENTRY_COUNT);
      PagingResults<PostInfo> posts = discussionService.listPosts(topic, paging);
      
      // The primary post is in the list, so exclude from the reply count 
      numReplies = posts.getTotalResultCount().getFirst() - 1;
   }
   
   // Build the details
   Map<String, Object> item = new HashMap<String, Object>();
   item.put(KEY_IS_TOPIC_POST, true);
   item.put(KEY_TOPIC, topic.getNodeRef());
   item.put(KEY_POST, primaryPost.getNodeRef());
   item.put(KEY_CAN_EDIT, canUserEditPost(primaryPost, site));
   item.put(KEY_AUTHOR, buildPerson(topic.getCreator()));
   
   // The reply count is one less than all posts (first is the primary one)
   item.put("totalReplyCount", numReplies);
   
   // Add the topic site 
   item.put("site", topic.getShortSiteName());
   
   // We want details on the most recent post
   if (mostRecentPost != null)
   {
      item.put("lastReply", mostRecentPost.getNodeRef());
      item.put("lastReplyBy", buildPerson(mostRecentPost.getCreator()));
   }
   
   // Include the tags
   item.put("tags", topic.getTags());
   
   // All done
   return item;
}
 
Example 13
Source File: Util.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static PagingRequest getPagingRequest(Paging paging)
{
    PagingRequest pagingRequest = new PagingRequest(paging.getSkipCount(), paging.getMaxItems());
    pagingRequest.setRequestTotalCountMax(CannedQueryPageDetails.DEFAULT_PAGE_SIZE);
    return pagingRequest;
}