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

The following examples show how to use org.alfresco.query.PagingRequest#getMaxItems() . 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: GetNodesWithAspectCannedQueryFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Retrieve an unsorted instance of a {@link CannedQuery} based on parameters including 
 * request for a total count (up to a given max)
 *
 * @param storeRef           the store to search in, if requested
 * @param aspectQNames       qnames of aspects to search for
 * @param pagingRequest      skipCount, maxItems - optionally queryExecutionId and requestTotalCountMax
 * 
 * @return                   an implementation that will execute the query
 */
public CannedQuery<NodeRef> getCannedQuery(StoreRef storeRef, Set<QName> aspectQNames, PagingRequest pagingRequest)
{
    ParameterCheck.mandatory("aspectQNames",  aspectQNames);
    ParameterCheck.mandatory("pagingRequest", pagingRequest);
    
    int requestTotalCountMax = pagingRequest.getRequestTotalCountMax();
    
    // specific query params - context (parent) and inclusive filters (child types, property values)
    GetNodesWithAspectCannedQueryParams paramBean = new GetNodesWithAspectCannedQueryParams(storeRef, aspectQNames);

    // page details
    CannedQueryPageDetails cqpd = new CannedQueryPageDetails(pagingRequest.getSkipCount(), pagingRequest.getMaxItems(), CannedQueryPageDetails.DEFAULT_PAGE_NUMBER, CannedQueryPageDetails.DEFAULT_PAGE_COUNT);
    
    // no sort details - no sorting done
    
    // create query params holder
    CannedQueryParameters params = new CannedQueryParameters(paramBean, cqpd, null, requestTotalCountMax, pagingRequest.getQueryExecutionId());
    
    // return canned query instance
    return getCannedQuery(params);
}
 
Example 2
Source File: SiteServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public PagingResults<SiteMembership> listMembersPaged(String shortName, boolean collapseGroups, List<Pair<SiteService.SortFields, Boolean>> sortProps, PagingRequest pagingRequest)
  {
      CannedQueryPageDetails pageDetails = new CannedQueryPageDetails(pagingRequest.getSkipCount(), pagingRequest.getMaxItems());

      // sort details
      CannedQuerySortDetails sortDetails = null;
      if(sortProps != null)
      {
          List<Pair<? extends Object, SortOrder>> sortPairs = new ArrayList<Pair<? extends Object, SortOrder>>(sortProps.size());
          for (Pair<SiteService.SortFields, Boolean> sortProp : sortProps)
          {
              sortPairs.add(new Pair<SiteService.SortFields, SortOrder>(sortProp.getFirst(), (sortProp.getSecond() ? SortOrder.ASCENDING : SortOrder.DESCENDING)));
          }
          
          sortDetails = new CannedQuerySortDetails(sortPairs);
      }

      SiteMembersCannedQueryParams parameterBean = new SiteMembersCannedQueryParams(shortName, collapseGroups);
      CannedQueryParameters params = new CannedQueryParameters(parameterBean, pageDetails, sortDetails, pagingRequest.getRequestTotalCountMax(), pagingRequest.getQueryExecutionId());

CannedQuery<SiteMembership> query = new SiteMembersCannedQuery(this, personService, nodeService, params);

      CannedQueryResults<SiteMembership> results = query.execute();

      return getPagingResults(pagingRequest, results);
  }
 
Example 3
Source File: SiteServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public PagingResults<FileInfo> listContainers(String shortName, PagingRequest pagingRequest)
{
    SiteContainersCannedQueryFactory sitesContainersCannedQueryFactory = (SiteContainersCannedQueryFactory)cannedQueryRegistry.getNamedObject("siteContainersCannedQueryFactory");

    CannedQueryPageDetails pageDetails = new CannedQueryPageDetails(pagingRequest.getSkipCount(), pagingRequest.getMaxItems());
    CannedQuerySortDetails sortDetails = new CannedQuerySortDetails(new Pair<Object, SortOrder>(SiteContainersCannedQueryParams.SortFields.ContainerName, SortOrder.ASCENDING));
    SiteContainersCannedQueryParams parameterBean = new SiteContainersCannedQueryParams(getSiteNodeRef(shortName));
    CannedQueryParameters params = new CannedQueryParameters(parameterBean, pageDetails, sortDetails, pagingRequest.getRequestTotalCountMax(), pagingRequest.getQueryExecutionId());

    CannedQuery<FileInfo> query = sitesContainersCannedQueryFactory.getCannedQuery(params);
    
    CannedQueryResults<FileInfo> results = query.execute();

    return getPagingResults(pagingRequest, results);        
}
 
Example 4
Source File: DiscussionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Finds nodes in the specified parent container, with the given
 *  type, optionally filtered by creator
 */
private CannedQueryResults<NodeBackedEntity> listEntries(NodeRef parent, 
      QName nodeType, String creatorUsername, Date from, Date to, 
      boolean oldestFirst, PagingRequest paging) 
{
   // The Canned Query system doesn't allow for zero sized pages
   // If they asked for that (bits of share sometimes do), bail out now
   if (paging != null && paging.getMaxItems() == 0)
   {
      return new EmptyCannedQueryResults<NodeBackedEntity>(null);
   }
   
   // Grab the factory
   GetChildrenAuditableCannedQueryFactory getChildrenCannedQueryFactory = (GetChildrenAuditableCannedQueryFactory)cannedQueryRegistry.getNamedObject(CANNED_QUERY_GET_CHILDREN);
   
   // Do the sorting, newest first or last by created date (as requested)
   CannedQuerySortDetails sorting = null;
   if (oldestFirst)
   {
      sorting = getChildrenCannedQueryFactory.createDateAscendingCQSortDetails();
   }
   else
   {
      sorting = getChildrenCannedQueryFactory.createDateDescendingCQSortDetails();
   }
   
   // Run the canned query
   GetChildrenAuditableCannedQuery cq = (GetChildrenAuditableCannedQuery)getChildrenCannedQueryFactory.getCannedQuery(
         parent, nodeType, creatorUsername, from, to, null,
         null, null, sorting, paging);
   
   // Execute the canned query
   CannedQueryResults<NodeBackedEntity> results = cq.execute();
   
   // Return for wrapping
   return results;
}
 
Example 5
Source File: GetChildrenCannedQueryFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Retrieve an optionally filtered/sorted instance of a {@link CannedQuery} based on parameters including request for a total count (up to a given max)
 * 
 * Note: if both filtering and sorting is required then the combined total of unique QName properties should be the 0 to 3.
 *
 * @param parentRef             parent node ref
 * @param pattern			    the pattern to use to filter children (wildcard character is '*')
 * @param assocTypeQNames	    qnames of assocs to include (may be null)
 * @param childTypeQNames       type qnames of children nodes (pre-filter)
 * @param inclusiveAspects      If not null, only child nodes with any aspect in this collection will be included in the results.
 * @param exclusiveAspects      If not null, any child nodes with any aspect in this collection will be excluded in the results.
 * @param filterProps           filter properties
 * @param sortProps             sort property pairs (QName and Boolean - true if ascending)
 * @param pagingRequest         skipCount, maxItems - optionally queryExecutionId and requestTotalCountMax
 * 
 * @return                      an implementation that will execute the query
 */
public CannedQuery<NodeRef> getCannedQuery(NodeRef parentRef, String pattern, Set<QName> assocTypeQNames, Set<QName> childTypeQNames, Set<QName> inclusiveAspects, Set<QName> exclusiveAspects, List<FilterProp> filterProps, List<Pair<QName, Boolean>> sortProps, PagingRequest pagingRequest)
{
    ParameterCheck.mandatory("parentRef", parentRef);
    ParameterCheck.mandatory("pagingRequest", pagingRequest);
    
    int requestTotalCountMax = pagingRequest.getRequestTotalCountMax();
    
    // specific query params - context (parent) and inclusive filters (child types, property values)
    GetChildrenCannedQueryParams paramBean = new GetChildrenCannedQueryParams(tenantService.getName(parentRef), assocTypeQNames, childTypeQNames, inclusiveAspects, exclusiveAspects, filterProps, pattern);

    // page details
    CannedQueryPageDetails cqpd = new CannedQueryPageDetails(pagingRequest.getSkipCount(), pagingRequest.getMaxItems(), CannedQueryPageDetails.DEFAULT_PAGE_NUMBER, CannedQueryPageDetails.DEFAULT_PAGE_COUNT);
    
    // sort details
    CannedQuerySortDetails cqsd = null;
    if (sortProps != null)
    {
        List<Pair<? extends Object, SortOrder>> sortPairs = new ArrayList<Pair<? extends Object, SortOrder>>(sortProps.size());
        for (Pair<QName, Boolean> sortProp : sortProps)
        {
            sortPairs.add(new Pair<QName, SortOrder>(sortProp.getFirst(), (sortProp.getSecond() ? SortOrder.ASCENDING : SortOrder.DESCENDING)));
        }
        
        cqsd = new CannedQuerySortDetails(sortPairs);
    }
    
    // create query params holder
    CannedQueryParameters params = new CannedQueryParameters(paramBean, cqpd, cqsd, requestTotalCountMax, pagingRequest.getQueryExecutionId());
    
    // return canned query instance
    return getCannedQuery(params);
}
 
Example 6
Source File: DocumentLinkServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public List<Long> getNodeLinksIds(NodeRef nodeRef)
{
    /* Validate input */
    PropertyCheck.mandatory(this, "nodeRef", nodeRef);

    /* Get all links of the given nodeRef */
    PagingRequest pagingRequest = new PagingRequest(0, 100000);
    List<Long> nodeLinks = new ArrayList<Long>();

    Pair<Long, QName> nameQName = qnameDAO.getQName(ContentModel.PROP_LINK_DESTINATION);
    if (nameQName != null)
    {
        // Execute the canned query if there are links in the database
        GetDoclinkNodesCannedQueryParams parameterBean = new GetDoclinkNodesCannedQueryParams(nodeRef.toString(), 
                                                                                              nameQName.getFirst(), 
                                                                                              pagingRequest.getMaxItems());
        CannedQueryParameters params = new CannedQueryParameters(parameterBean, 
                                                                 null, 
                                                                 null, 
                                                                 pagingRequest.getRequestTotalCountMax(), 
                                                                 pagingRequest.getQueryExecutionId());
        CannedQuery<Long> query = new GetDoclinkNodesCannedQuery(cannedQueryDAO, 
                                                                 params);
        CannedQueryResults<Long> results = query.execute();

        for (Long nodeId : results.getPage())
        {
            nodeLinks.add(nodeId);
        }
    }

    return nodeLinks;
}
 
Example 7
Source File: RemoteCredentialsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * TODO This would probably be better done as a dedicated Canned Query
 * We want to filter by Assoc Type and Child Node Type, and the node service
 *  currently only allows you to do one or the other 
 */
private PagingResults<? extends BaseCredentialsInfo> listCredentials(NodeRef[] containers, String remoteSystem, 
        QName credentialsType, PagingRequest paging)
{
    // NodeService wants an exhaustive list of the types
    // Expand our single Credentials Type to cover all subtypes of it too
    Set<QName> types = null;
    if (credentialsType != null)
    {
        types = new HashSet<QName>( dictionaryService.getSubTypes(credentialsType, true) );
        
        if (logger.isDebugEnabled())
            logger.debug("Searching for credentials of " + credentialsType + " as types " + types);
    }
    
    // Find all the credentials
    List<ChildAssociationRef> credentials = new ArrayList<ChildAssociationRef>();
    for (NodeRef nodeRef : containers)
    {
        if (nodeRef != null)
        {
            // Find the credentials in the node
            List<ChildAssociationRef> allCreds = nodeService.getChildAssocs(
                    nodeRef, RemoteCredentialsModel.ASSOC_CREDENTIALS, RegexQNamePattern.MATCH_ALL);
            
            // Filter them by type, if needed
            if (types == null || types.isEmpty())
            {
                // No type filtering needed
                credentials.addAll(allCreds);
            }
            else
            {
                // Check the type of each one, and add if it matches
                for (ChildAssociationRef ref : allCreds)
                {
                    NodeRef credNodeRef = ref.getChildRef();
                    QName credType = nodeService.getType(credNodeRef);
                    if (types.contains(credType))
                    {
                        // Matching type, accept
                        credentials.add(ref);
                    }
                }
            }
        }
    }
    
    // Did we find any?
    if (credentials.isEmpty())
    {
        return new EmptyPagingResults<BaseCredentialsInfo>();
    }
    
    // Excerpt
    int start = paging.getSkipCount();
    int end = Math.min(credentials.size(), start + paging.getMaxItems());
    if (paging.getMaxItems() == 0)
    {
        end = credentials.size();
    }
    boolean hasMore = (end < credentials.size());
    
    List<ChildAssociationRef> wanted = credentials.subList(start, end);
    
    // Wrap and return
    return new CredentialsPagingResults(wanted, credentials.size(), hasMore, remoteSystem); 
}
 
Example 8
Source File: ScriptPagingDetails.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public ScriptPagingDetails(PagingRequest paging)
{
   super(paging.getSkipCount(), paging.getMaxItems(), paging.getQueryExecutionId());
   setRequestTotalCountMax(paging.getRequestTotalCountMax());
}
 
Example 9
Source File: ActivityFeedDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private List<ActivityFeedEntity> filterByNetwork(String networkId, String siteId, String sql, ActivityFeedQueryEntity params, PagingRequest pagingRequest)
{
    int expectedSkipCount = pagingRequest.getSkipCount();
    // +1 to calculate hasMoreItems
    int expectedMaxItems = (pagingRequest.getMaxItems() == CannedQueryPageDetails.DEFAULT_PAGE_SIZE ? pagingRequest.getMaxItems() : pagingRequest.getMaxItems() + 1);

    int skipCount = 0;
    int maxItems = fetchBatchSize;

    List<ActivityFeedEntity> ret = new LinkedList<ActivityFeedEntity>();

    int numMatchingItems = 0;
    int numAddedItems = 0;
    boolean skipping = true;

    List<ActivityFeedEntity> feedEntries = null;

    // fetch activities in batches of size "maxItems"
    // iterate through them, filtering out any that don't match the networkId
    do
    {
        RowBounds rowBounds = new RowBounds(skipCount, maxItems);

        feedEntries = template.selectList(sql, params, rowBounds);
        Iterator<ActivityFeedEntity> feedEntriesIt = feedEntries.iterator();

        while(feedEntriesIt.hasNext() && numAddedItems < expectedMaxItems)
        {
            ActivityFeedEntity activityFeedEntry = feedEntriesIt.next();
            
            if(siteId == null)
            {
                // note: pending requirements for THOR-224, for now assume all activities are within context of site and filter by current tenant
                if(!networkId.equals(tenantService.getDomain(activityFeedEntry.getSiteNetwork())))
                {
                    continue;
                }
            }

            numMatchingItems++;

            if(skipping)
            {
                if(numMatchingItems > expectedSkipCount)
                {
                    skipping = false;
                }
                else
                {
                    continue;
                }
            }

            ret.add(activityFeedEntry);
            
            numAddedItems++;
        }

        skipCount += feedEntries.size();
    }
    while(feedEntries != null && feedEntries.size() > 0 && numAddedItems < expectedMaxItems);

    return ret;
}
 
Example 10
Source File: SubscriptionsDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public PagingFollowingResults selectFollowers(String userId, PagingRequest pagingRequest)
{
    if (userId == null)
    {
        throw new IllegalArgumentException("User Id may not be null!");
    }

    NodeRef userNodeRef = getUserNodeRef(userId);
    if (userNodeRef == null)
    {
        throw new IllegalArgumentException("User does not exist!");
    }

    Long dbid = (Long) nodeService.getProperty(userNodeRef, PROP_SYS_NODE_DBID);

    Map<String, Object> map = new HashMap<String, Object>();

    Pair<Long, QName> qNamePair = qnameDAO.getQName(ContentModel.PROP_USERNAME);
    if (null != qNamePair)
    {
        map.put("userIdQname", qNamePair.getFirst());
    }

    map.put("userNodeId", dbid);

    int maxItems = (pagingRequest.getMaxItems() < 0 || pagingRequest.getMaxItems() > Integer.MAX_VALUE - 1 ? Integer.MAX_VALUE - 1
            : pagingRequest.getMaxItems() + 1);

    @SuppressWarnings("unchecked")
    List<String> userList = template.selectList("alfresco.subscriptions.select_Followers", map,
            new RowBounds(pagingRequest.getSkipCount(), maxItems + 1));

    boolean hasMore = userList.size() > maxItems;
    if (hasMore && userList.size() > 0)
    {
        userList.remove(userList.size() - 1);
    }

    Integer totalCount = null;
    if (pagingRequest.getRequestTotalCountMax() > 0)
    {
        totalCount = countFollowers(userId);
    }

    return new PagingFollowingResultsImpl(userList, hasMore, totalCount);
}
 
Example 11
Source File: ForumTopicsFilteredGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Do the actual search
 * 
 * @param searchQuery Pair with query string in first and query language in second
 * @param sortAscending boolean
 * @param paging PagingRequest
 */
protected PagingResults<TopicInfo> doSearch(Pair<String, String> searchQuery, boolean sortAscending, PagingRequest paging)
{
   ResultSet resultSet = null;
   PagingResults<TopicInfo> pagedResults = new EmptyPagingResults<TopicInfo>();

   String sortOn = "@{http://www.alfresco.org/model/content/1.0}created";

   // Setup the search parameters
   SearchParameters sp = new SearchParameters();
   sp.addStore(SPACES_STORE);
   sp.setQuery(searchQuery.getFirst());
   sp.setLanguage(searchQuery.getSecond());
   sp.addSort(sortOn, sortAscending);
   if (paging.getMaxItems() > 0)
   {
      //Multiply maxItems by 10.  This is to catch topics that have multiple replies and ensure that the maximum number of topics is shown.
      sp.setLimit(paging.getMaxItems()*10);
      sp.setLimitBy(LimitBy.FINAL_SIZE);
   }
   if (paging.getSkipCount() > 0)
   {
      sp.setSkipCount(paging.getSkipCount());
   }

   try
   {
      resultSet = searchService.query(sp);
      pagedResults = wrap(resultSet, paging);
   }
   finally
   {
      try
      {
         resultSet.close();
      }
      catch(Exception e)
      {
         //do nothing
      }
   }

   return pagedResults;
}
 
Example 12
Source File: BlogServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public PagingResults<BlogPostInfo> findBlogPosts(
      final NodeRef blogContainerNode, final RangedDateProperty dateRange, 
      final String tag, final PagingRequest pagingReq)
{
    StringBuilder luceneQuery = new StringBuilder();
    luceneQuery.append("+TYPE:\"").append(ContentModel.TYPE_CONTENT).append("\" ")
               .append("+PARENT:\"").append(blogContainerNode.toString()).append("\" ");
    if (tag != null && !tag.trim().isEmpty())
    {
        luceneQuery.append("+PATH:\"/cm:taggable/cm:").append(ISO9075.encode(tag)).append("/member\"");
    }
    if (dateRange != null)
    {
        luceneQuery.append(createDateRangeQuery(dateRange.getFromDate(), dateRange.getToDate(), dateRange.getDateProperty()));
    }

    SearchParameters sp = new SearchParameters();
    sp.addStore(blogContainerNode.getStoreRef());
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery(luceneQuery.toString());
    sp.addSort(ContentModel.PROP_PUBLISHED.toString(), false);

    sp.setMaxItems(pagingReq.getMaxItems() * MIN_NUMBER_OF_PAGES_FOR_THE_USER_TO_LOOP_THROUGH); 
    sp.setSkipCount(pagingReq.getSkipCount());
    ResultSet luceneResults = null;
    PagingResults<BlogPostInfo> results = null;
    try
    {
        luceneResults = searchService.query(sp);
        final ResultSet finalLuceneResults = luceneResults;
        
        final List<NodeRef> nodeRefs = finalLuceneResults.getNodeRefs().subList(0, min(pagingReq.getMaxItems(), finalLuceneResults.length()));
        
        results = new PagingResults<BlogPostInfo>()
        {
            
            @Override
            public List<BlogPostInfo> getPage()
            {
                List<BlogPostInfo> blogPostInfos = new ArrayList<BlogPostInfo>(nodeRefs.size());
                for (NodeRef nodeRef : nodeRefs)
                {
                    String postName = (String)nodeService.getProperty(nodeRef, ContentModel.PROP_NAME); 
                    blogPostInfos.add(new BlogPostInfoImpl(nodeRef, blogContainerNode, postName));
                }
                return blogPostInfos;
            }
            
            @Override
            public String getQueryExecutionId()
            {
                return null;
            }
            
            @Override
            public Pair<Integer, Integer> getTotalResultCount()
            { 
                long totalResultCount = finalLuceneResults.getNumberFound();
                /*if (finalLuceneResults.hasMore()){
                    totalResultCount++;
                }*/ 
                return new Pair<Integer, Integer>((int)totalResultCount, (int)totalResultCount);
            }
            
            @Override
            public boolean hasMoreItems()
            {
                return finalLuceneResults.length() > pagingReq.getMaxItems();
            }
        };
    }
    finally
    {
        if (luceneResults != null) luceneResults.close();
    }
    
    
    return results;
}
 
Example 13
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 14
Source File: PageCollator.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private PagingResults<R> collate(List<R> objects, final PagingResults<R> objectPageSurce, int pageSkip,
            final PagingRequest pagingRequest, Comparator<R> comparator)
{
    final int pageSize = pagingRequest.getMaxItems();
    final List<R> inPageList = objectPageSurce.getPage();
    final List<R> collatedPageList = new LinkedList<>();
    final boolean endOfCollation = collate(objects,
                                           inPageList,
                                           pageSkip,
                                           pageSize,
                                           comparator,
                                           collatedPageList);
    final int resultsSize = objects.size();

    final Pair<Integer, Integer> pageTotal = objectPageSurce.getTotalResultCount();
    Integer pageTotalFirst = null;
    Integer pageTotalSecond = null;

    if (pageTotal != null)
    {
        pageTotalFirst = pageTotal.getFirst();
        pageTotalSecond = pageTotal.getSecond();
    }

    final Pair<Integer, Integer> total = new Pair<>(pageTotalFirst == null ? null : pageTotalFirst + resultsSize,
                                                    pageTotalSecond == null ? null : pageTotalSecond + resultsSize);

    final boolean hasMoreItems = objectPageSurce.hasMoreItems() || !endOfCollation;

    return new PagingResults<R>()
    {

        @Override
        public List<R> getPage()
        {
            return collatedPageList;
        }

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

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

        @Override
        public String getQueryExecutionId()
        {
            return pagingRequest.getQueryExecutionId();
        }

    };
}
 
Example 15
Source File: PreferenceServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public PagingResults<Pair<String, Serializable>> getPagedPreferences(String userName, String preferenceFilter, PagingRequest pagingRequest)
{
    final Map<String, Serializable> prefs = getPreferences(userName, preferenceFilter);

    int totalSize = prefs.size();
    int skipCount = pagingRequest.getSkipCount();
    int maxItems = pagingRequest.getMaxItems();
    int end = maxItems == CannedQueryPageDetails.DEFAULT_PAGE_SIZE ? totalSize : skipCount + maxItems;
    int pageSize = (maxItems == CannedQueryPageDetails.DEFAULT_PAGE_SIZE ? totalSize : Math.max(maxItems, totalSize - skipCount));
    final boolean hasMoreItems = end < totalSize;

    final List<Pair<String, Serializable>> page = new ArrayList<Pair<String, Serializable>>(pageSize);
    Iterator<Map.Entry<String, Serializable>> it = prefs.entrySet().iterator();
    for(int counter = 0; counter < end && it.hasNext(); counter++)
    {
        Map.Entry<String, Serializable> pref = it.next();

        if(counter < skipCount)
        {
            continue;
        }
        
        if(counter > end - 1)
        {
            break;
        }

        page.add(new Pair<String, Serializable>(pref.getKey(), pref.getValue()));
    }

    return new PagingResults<Pair<String, Serializable>>()
    {
        @Override
        public List<Pair<String, Serializable>> getPage()
        {
            return page;
        }

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

        @Override
        public Pair<Integer, Integer> getTotalResultCount()
        {
            Integer total = Integer.valueOf(prefs.size());
            return new Pair<Integer, Integer>(total, total);
        }

        @Override
        public String getQueryExecutionId()
        {
            return null;
        }
    };
}
 
Example 16
Source File: SubscriptionsDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public PagingFollowingResults selectFollowing(String userId, PagingRequest pagingRequest)
{
    if (userId == null)
    {
        throw new IllegalArgumentException("User Id may not be null!");
    }

    NodeRef userNodeRef = getUserNodeRef(userId);
    if (userNodeRef == null)
    {
        throw new IllegalArgumentException("User does not exist!");
    }

    Long dbid = (Long) nodeService.getProperty(userNodeRef, PROP_SYS_NODE_DBID);

    Map<String, Object> map = new HashMap<String, Object>();

    Pair<Long, QName> qNamePair = qnameDAO.getQName(ContentModel.PROP_USERNAME);
    if (null != qNamePair)
    {
        map.put("userIdQname", qNamePair.getFirst());
    }

    map.put("userNodeId", dbid);

    int maxItems = (pagingRequest.getMaxItems() < 0 || pagingRequest.getMaxItems() > Integer.MAX_VALUE - 1 ? Integer.MAX_VALUE - 1
            : pagingRequest.getMaxItems() + 1);

    @SuppressWarnings("unchecked")
    List<String> userList = template.selectList("alfresco.subscriptions.select_Following", map,
            new RowBounds(pagingRequest.getSkipCount(), maxItems + 1));

    boolean hasMore = userList.size() > maxItems;
    if (hasMore && userList.size() > 0)
    {
        userList.remove(userList.size() - 1);
    }

    Integer totalCount = null;
    if (pagingRequest.getRequestTotalCountMax() > 0)
    {
        totalCount = countSubscriptions(userId, SubscriptionItemTypeEnum.USER);
    }

    return new PagingFollowingResultsImpl(userList, hasMore, totalCount);
}
 
Example 17
Source File: NodeArchiveServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public PagingResults<NodeRef> listArchivedNodes(ArchivedNodesCannedQueryBuilder cannedQueryBuilder)
{
    ParameterCheck.mandatory("cannedQueryBuilder", cannedQueryBuilder);

    Long start = (logger.isDebugEnabled() ? System.currentTimeMillis() : null);

    // get canned query
    GetArchivedNodesCannedQueryFactory getArchivedNodesCannedQueryFactory = (GetArchivedNodesCannedQueryFactory) cannedQueryRegistry
                .getNamedObject(CANNED_QUERY_ARCHIVED_NODES_LIST);

    Pair<NodeRef, QName> archiveNodeRefAssocTypePair = getArchiveNodeRefAssocTypePair(cannedQueryBuilder.getArchiveRootNodeRef());
    GetArchivedNodesCannedQuery cq = (GetArchivedNodesCannedQuery) getArchivedNodesCannedQueryFactory
                .getCannedQuery(archiveNodeRefAssocTypePair.getFirst(), archiveNodeRefAssocTypePair.getSecond(),
                            cannedQueryBuilder.getFilter(),
                            cannedQueryBuilder.isFilterIgnoreCase(),
                            cannedQueryBuilder.getPagingRequest(),
                            cannedQueryBuilder.getSortOrderAscending());

    // execute canned query
    final CannedQueryResults<ArchivedNodeEntity> results = ((CannedQuery<ArchivedNodeEntity>) cq).execute();

    final List<ArchivedNodeEntity> page;
    if (results.getPageCount() > 0)
    {
        page = results.getPages().get(0);
    }
    else
    {
        page = Collections.emptyList();
    }
    
    // set total count
    final Pair<Integer, Integer> totalCount;
    PagingRequest pagingRequest = cannedQueryBuilder.getPagingRequest();
    if (pagingRequest.getRequestTotalCountMax() > 0)
    {
        totalCount = results.getTotalResultCount();
    }
    else
    {
        totalCount = null;
    }

    if (start != null)
    {
        int skipCount = pagingRequest.getSkipCount();
        int maxItems = pagingRequest.getMaxItems();
        int pageNum = (skipCount / maxItems) + 1;
        
        if (logger.isDebugEnabled())
        {
            StringBuilder sb = new StringBuilder(300);
            sb.append("listArchivedNodes: ").append(page.size()).append(" items in ")
                        .append((System.currentTimeMillis() - start)).append("ms ")
                        .append("[pageNum=").append(pageNum).append(", skip=").append(skipCount)
                        .append(", max=").append(maxItems).append(", hasMorePages=")
                        .append(results.hasMoreItems()).append(", totalCount=")
                        .append(totalCount).append(", filter=")
                        .append(cannedQueryBuilder.getFilter()).append(", sortOrderAscending=")
                        .append(cannedQueryBuilder.getSortOrderAscending()).append("]");

            logger.debug(sb.toString());
        }
    }
    return new PagingResults<NodeRef>()
    {
        @Override
        public String getQueryExecutionId()
        {
            return results.getQueryExecutionId();
        }

        @Override
        public List<NodeRef> getPage()
        {
            List<NodeRef> nodeRefs = new ArrayList<NodeRef>(page.size());
            for (ArchivedNodeEntity entity : page)
            {
                nodeRefs.add(entity.getNodeRef());
            }
            return nodeRefs;
        }

        @Override
        public boolean hasMoreItems()
        {
            return results.hasMoreItems();
        }

        @Override
        public Pair<Integer, Integer> getTotalResultCount()
        {
            return totalCount;
        }
    };
}
 
Example 18
Source File: PersonServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private List<NodeRef> getPeopleFtsList(String pattern, PagingRequest pagingRequest) throws Throwable
{
    // Think this code is based on org.alfresco.repo.jscript.People.getPeopleImplSearch(String, StringTokenizer, int, int)
    List<NodeRef> people = null;

    SearchParameters params = new SearchParameters();
    params.addQueryTemplate("_PERSON", "|%firstName OR |%lastName OR |%userName");
    params.setDefaultFieldName("_PERSON");

    StringBuilder query = new StringBuilder(256);

    query.append("TYPE:\"").append(ContentModel.TYPE_PERSON).append("\" AND (");

    StringTokenizer t = new StringTokenizer(pattern, " ");

    if (t.countTokens() == 1)
    {
        // fts-alfresco property search i.e. location:"maidenhead"
        query.append('"').append(pattern).append("*\"");
    }
    else
    {
        // multiple terms supplied - look for first and second name etc.
        // assume first term is first name, any more are second i.e.
        // "Fraun van de Wiels"
        // also allow fts-alfresco property search to reduce results
        params.setDefaultOperator(SearchParameters.Operator.AND);
        StringBuilder multiPartNames = new StringBuilder(pattern.length());
        int numOfTokens = t.countTokens();
        int counter = 1;
        String term = null;
        // MNT-8539, in order to support firstname and lastname search
        while (t.hasMoreTokens())
        {
            term = t.nextToken();
            // ALF-11311, in order to support multi-part
            // firstNames/lastNames, we need to use the whole tokenized term for both
            // firstName and lastName
            if (term.endsWith("*"))
            {
                term = term.substring(0, term.lastIndexOf("*"));
            }
            multiPartNames.append("\"");
            multiPartNames.append(term);
            multiPartNames.append("*\"");
            if (numOfTokens > counter)
            {
                multiPartNames.append(' ');
            }
            counter++;
        }
        // ALF-11311, in order to support multi-part firstNames/lastNames,
        // we need to use the whole tokenized term for both firstName and lastName.
        // e.g. "john junior lewis martinez", where "john junior" is the first
        // name and "lewis martinez" is the last name.
        if (multiPartNames.length() > 0)
        {
            query.append("firstName:");
            query.append(multiPartNames);
            query.append(" OR lastName:");
            query.append(multiPartNames);
        }
    }
    query.append(")");

    // define the search parameters
    params.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);
    params.addStore(this.storeRef);
    params.setQuery(query.toString());
    if (pagingRequest.getMaxItems() > 0)
    {
        params.setLimitBy(LimitBy.FINAL_SIZE);
        params.setLimit(pagingRequest.getMaxItems());
    }

    ResultSet results = null;
    try
    {
        results = searchService.query(params);
        people = results.getNodeRefs();
    }
    catch (Throwable err)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Failed to execute people search: " + query.toString(), err);
        }

        throw err;
    }
    finally
    {
        if (results != null)
        {
            results.close();
        }
    }

    return people;
}
 
Example 19
Source File: GetAuthoritiesCannedQueryFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public CannedQuery<AuthorityInfo> getCannedQuery(AuthorityType type, NodeRef containerRef, String displayNameFilter, String sortBy, boolean sortAscending, PagingRequest pagingRequest)
{
    ParameterCheck.mandatory("containerRef", containerRef);
    ParameterCheck.mandatory("pagingRequest", pagingRequest);
    
    int requestTotalCountMax = pagingRequest.getRequestTotalCountMax();
    
    Pair<Long, NodeRef> nodePair = nodeDAO.getNodePair(tenantService.getName(containerRef));
    if (nodePair == null)
    {
        throw new InvalidNodeRefException("Container ref does not exist: " + containerRef, containerRef);
    }
    
    Long containerNodeId = nodePair.getFirst();
    
    Long qnameAuthDisplayNameId = Long.MIN_VALUE;           // We query but using a value that won't return results
    Pair<Long, QName> qnameAuthDisplayNamePair = qnameDAO.getQName(ContentModel.PROP_AUTHORITY_DISPLAY_NAME);
    if (qnameAuthDisplayNamePair != null)
    {
        qnameAuthDisplayNameId = qnameAuthDisplayNamePair.getFirst();
    }
    
    // this can be null, in which case, there is no filtering on type, done at the database level
    Long typeQNameId = getQNameIdForType(type);
    // specific query params
    GetAuthoritiesCannedQueryParams paramBean = new GetAuthoritiesCannedQueryParams(type,
                                                                                    typeQNameId,
                                                                                    containerNodeId,
                                                                                    qnameAuthDisplayNameId,
                                                                                    displayNameFilter);
    
    // page details
    CannedQueryPageDetails cqpd = new CannedQueryPageDetails(pagingRequest.getSkipCount(), pagingRequest.getMaxItems(), CannedQueryPageDetails.DEFAULT_PAGE_NUMBER, CannedQueryPageDetails.DEFAULT_PAGE_COUNT);
    
    // sort details
    CannedQuerySortDetails cqsd = null;
    if (sortBy != null)
    {
        List<Pair<? extends Object, SortOrder>> sortPairs = new ArrayList<Pair<? extends Object, SortOrder>>(1);
        sortPairs.add(new Pair<String, SortOrder>(sortBy, (sortAscending ? SortOrder.ASCENDING : SortOrder.DESCENDING)));
        cqsd = new CannedQuerySortDetails(sortPairs);
    }
    
    // create query params holder
    CannedQueryParameters params = new CannedQueryParameters(paramBean, cqpd, cqsd, requestTotalCountMax, pagingRequest.getQueryExecutionId());
    
    // return canned query instance
    return getCannedQuery(params);
}
 
Example 20
Source File: SubscriptionsDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public PagingSubscriptionResults selectSubscriptions(String userId, SubscriptionItemTypeEnum type,
        PagingRequest pagingRequest)
{
    if (userId == null)
    {
        throw new IllegalArgumentException("User Id may not be null!");
    }

    if (type == null)
    {
        throw new IllegalArgumentException("Type may not be null!");
    }

    NodeRef userNodeRef = getUserNodeRef(userId);
    if (userNodeRef == null)
    {
        throw new IllegalArgumentException("User does not exist!");
    }

    Long dbid = (Long) nodeService.getProperty(userNodeRef, PROP_SYS_NODE_DBID);

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("userNodeId", dbid);

    int maxItems = (pagingRequest.getMaxItems() < 0 || pagingRequest.getMaxItems() > Integer.MAX_VALUE - 1 ? Integer.MAX_VALUE - 1
            : pagingRequest.getMaxItems() + 1);

    @SuppressWarnings("unchecked")
    List<SubscriptionNodeEntity> nodeList = template.selectList(
            "alfresco.subscriptions.select_Subscriptions", map, new RowBounds(pagingRequest.getSkipCount(),
                    maxItems + 1));

    boolean hasMore = nodeList.size() > maxItems;

    List<NodeRef> result = new ArrayList<NodeRef>(nodeList.size());
    for (SubscriptionNodeEntity sne : nodeList)
    {
        result.add(sne.getNodeRef());
        if (result.size() == pagingRequest.getMaxItems())
        {
            break;
        }
    }

    Integer totalCount = null;
    if (pagingRequest.getRequestTotalCountMax() > 0)
    {
        totalCount = countSubscriptions(userId, type);
    }

    return new PagingSubscriptionResultsImpl(result, hasMore, totalCount);
}