Java Code Examples for org.alfresco.query.PagingResults#getPage()

The following examples show how to use org.alfresco.query.PagingResults#getPage() . 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: CopyServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public List<NodeRef> getCopies(NodeRef nodeRef)
{
    PagingRequest pagingRequest = new PagingRequest(1000);
    PagingResults<CopyInfo> page = getCopies(nodeRef, pagingRequest);
    if (page.hasMoreItems())
    {
        logger.warn("Trimmed page size for deprecated getCopies() call.");
    }
    List<CopyInfo> pageResults = page.getPage();
    List<NodeRef> results = new ArrayList<NodeRef>(pageResults.size());
    for (CopyInfo copyInfo : pageResults)
    {
        results.add(copyInfo.getNodeRef());
    }
    return results;
}
 
Example 2
Source File: FavouritesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private CollectionWithPagingInfo<Favourite> wrap(Paging paging, PagingResults<PersonFavourite> personFavourites, Parameters parameters)
  {
  	final List<PersonFavourite> page = personFavourites.getPage();
  	final List<Favourite> list = new AbstractList<Favourite>()
{
	@Override
	public Favourite get(int index)
	{
		PersonFavourite personFavourite = page.get(index);
		Favourite fav = getFavourite(personFavourite, parameters);
		return fav;
	}

	@Override
	public int size()
	{
		return page.size();
	}
};
Pair<Integer, Integer> pair = personFavourites.getTotalResultCount();
Integer total = null;
if(pair.getFirst().equals(pair.getSecond()))
{
	total = pair.getFirst();
}
  	return CollectionWithPagingInfo.asPaged(paging, list, personFavourites.hasMoreItems(), total);
  }
 
Example 3
Source File: ArchivedNodesGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    Map<String, Object> model = new HashMap<String, Object>();
    
    // We want to get all nodes in the archive which were originally
    // contained in the following StoreRef.
    StoreRef storeRef = parseRequestForStoreRef(req);
    
    // Create paging
    ScriptPagingDetails paging = new ScriptPagingDetails(getIntParameter(req, MAX_ITEMS, DEFAULT_MAX_ITEMS_PER_PAGE),
                getIntParameter(req, SKIP_COUNT, 0));
    
    PagingResults<NodeRef> result = getArchivedNodesFrom(storeRef, paging, req.getParameter(NAME_FILTER));
    List<NodeRef> nodeRefs = result.getPage();

    List<ArchivedNodeState> deletedNodes = new ArrayList<ArchivedNodeState>(nodeRefs.size());
    for (NodeRef archivedNode : nodeRefs)
    {
        ArchivedNodeState state = ArchivedNodeState.create(archivedNode, serviceRegistry);
        deletedNodes.add(state);
    }

    // Now do the paging
    // ALF-19111. Note: Archived nodes CQ, supports Paging, 
    // so no need to use the ModelUtil.page method to build the page again.        
    model.put(DELETED_NODES, deletedNodes);
    // Because we haven't used ModelUtil.page method, we need to set the total items manually.
    paging.setTotalItems(deletedNodes.size());
    model.put("paging", ModelUtil.buildPaging(paging));
    
    return model;
}
 
Example 4
Source File: PreferencesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public CollectionWithPagingInfo<Preference> getPreferences(String personId, Paging paging)
{
	personId = people.validatePerson(personId);

	PagingResults<Pair<String, Serializable>> preferences = preferenceService.getPagedPreferences(personId, null, Util.getPagingRequest(paging));
	List<Preference> ret = new ArrayList<Preference>(preferences.getPage().size());
	for(Pair<String, Serializable> prefEntity : preferences.getPage())
	{
		Preference pref = new Preference(prefEntity.getFirst(), prefEntity.getSecond());
		ret.add(pref);
	}

       return CollectionWithPagingInfo.asPaged(paging, ret, preferences.hasMoreItems(), preferences.getTotalResultCount().getFirst());
}
 
Example 5
Source File: SitesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public CollectionWithPagingInfo<SiteMember> getSiteMembers(String siteId, Parameters parameters)
{
    SiteInfo siteInfo = validateSite(siteId);
    if(siteInfo == null)
    {
        // site does not exist
        throw new EntityNotFoundException(siteId);
    }
    // set the site id to the short name (to deal with case sensitivity issues with using the siteId from the url)
    siteId = siteInfo.getShortName();

    Paging paging = parameters.getPaging();

    PagingRequest pagingRequest = Util.getPagingRequest(paging);

    final List<Pair<SiteService.SortFields, Boolean>> sort = new ArrayList<Pair<SiteService.SortFields, Boolean>>();
    sort.add(new Pair<SiteService.SortFields, Boolean>(SiteService.SortFields.LastName, Boolean.TRUE));
    sort.add(new Pair<SiteService.SortFields, Boolean>(SiteService.SortFields.FirstName, Boolean.TRUE));
    sort.add(new Pair<SiteService.SortFields, Boolean>(SiteService.SortFields.Role, Boolean.TRUE));
    sort.add(new Pair<SiteService.SortFields, Boolean>(SiteService.SortFields.Username, Boolean.TRUE));
    PagingResults<SiteMembership> pagedResults = siteService.listMembersPaged(siteId, true, sort, pagingRequest);

    List<SiteMembership> siteMembers = pagedResults.getPage();
    List<SiteMember> ret = new ArrayList<SiteMember>(siteMembers.size());
    for(SiteMembership siteMembership : siteMembers)
    {
        SiteMember siteMember = new SiteMember(siteMembership.getPersonId(), siteMembership.getRole());
        ret.add(siteMember);
    }

    return CollectionWithPagingInfo.asPaged(paging, ret, pagedResults.hasMoreItems(), null);
}
 
Example 6
Source File: CommentsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public CollectionWithPagingInfo<Comment> getComments(String nodeId, Paging paging, List<String> include)
  {
final NodeRef nodeRef = nodes.validateNode(nodeId);
      
      /* MNT-10536 : fix */
      final Set<QName> contentAndFolders = 
              new HashSet<>(Arrays.asList(ContentModel.TYPE_FOLDER, ContentModel.TYPE_CONTENT));
      if (!nodes.nodeMatches(nodeRef, contentAndFolders, null))
      {
          throw new InvalidArgumentException("NodeId of folder or content is expected");
      }

  	PagingRequest pagingRequest = Util.getPagingRequest(paging);
      final PagingResults<NodeRef> pagingResults = commentService.listComments(nodeRef, pagingRequest);
      
final List<NodeRef> page = pagingResults.getPage();
List<Comment> comments = new AbstractList<>()
{
	@Override
	public Comment get(int index)
	{
		return toComment(nodeRef, page.get(index), include);
	}

	@Override
	public int size()
	{
		return page.size();
	}
};

      return CollectionWithPagingInfo.asPaged(paging, comments, pagingResults.hasMoreItems(), pagingResults.getTotalResultCount().getFirst());
  }
 
Example 7
Source File: PageCollatorTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void assertCollate(List<Integer> results, Integer[] source, int skip, int pageSize, boolean boundsError)
            throws Exception
{
    Arrays.sort(source);
    Collections.sort(results);
    int[] expected = createMergedPage(skip,
                                      pageSize,
                                      results,
                                      source);
    PagingResults<Integer> actualResults = new PageCollator<Integer>().collate(results,
                                                                               new ArrayPageSource(source),
                                                                               new PagingRequest(skip,
                                                                                                 pageSize),
                                                                               new ComparableComparator<Integer>());
    List<Integer> actualPage = actualResults.getPage();

    final String message = "[" + results + " + " + Arrays.toString(source) + " ] -> " + Arrays.toString(expected)
                + " != " + actualPage;
    assertEqualPages(message,
                     expected,
                     actualPage);
    assertEquals("Invalid moreItems info!",
                 (pageSize != 0) && (skip + pageSize < results.size() + source.length),
                 actualResults.hasMoreItems());
    assertTrue(message,
               (pageSize == 0) || actualPage.size() <= pageSize);
    final int expectedTotal = source.length + results.size();
    if (boundsError && !new Pair<Integer, Integer>(null,
                                                   null).equals(actualResults.getTotalResultCount()))
    {
        assertEquals("Invalid total info",
                     new Pair<Integer, Integer>(expectedTotal,
                                                expectedTotal),
                     actualResults.getTotalResultCount());
    }
    logger.info(actualPage);
}
 
Example 8
Source File: NetworksImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public CollectionWithPagingInfo<PersonNetwork> getNetworks(String personId, Paging paging)
  {
  	// check that personId is the current user
  	personId = people.validatePerson(personId, true);

  	PagingResults<org.alfresco.repo.tenant.Network> networks = networksService.getNetworks(Util.getPagingRequest(paging));
  	List<PersonNetwork> ret = new ArrayList<PersonNetwork>(networks.getPage().size());
  	for(org.alfresco.repo.tenant.Network network : networks.getPage())
{
  		PersonNetwork personNetwork = getPersonNetwork(network);
  		ret.add(personNetwork);
}
  	return CollectionWithPagingInfo.asPaged(paging, ret, networks.hasMoreItems(), networks.getTotalResultCount().getFirst());
  }
 
Example 9
Source File: FileFolderServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testListNotIgnoreSpaces()
{
    String [] foldersToTest = new String[] { 
        "A B", 
        "AA", 
        "AC" 
    };
    
    NodeRef testFolder = fileFolderService.create(workingRootNodeRef, "" + System.currentTimeMillis(), ContentModel.TYPE_FOLDER).getNodeRef();
    
    // create provided nodes
    for (String folder : foldersToTest)
    {
        fileFolderService.create(testFolder, folder, ContentModel.TYPE_FOLDER).getNodeRef();
    }
    
    PagingRequest pagingRequest = new PagingRequest(100, null);
    // ensure sort by property name
    List<Pair<QName, Boolean>> sortProps = new ArrayList<Pair<QName, Boolean>>(1);
    sortProps.add(new Pair<QName, Boolean>(ContentModel.PROP_NAME, true));
    // list nodes
    PagingResults<FileInfo> pagingResults = fileFolderService.list(testFolder, true, true, null, null, sortProps, pagingRequest);
    List<FileInfo> files = pagingResults.getPage();
     
    assertEquals(files.size(), foldersToTest.length);
    
    for (int index = 0; index < files.size(); index++)
    {
        // ensure node order is expected
        String folderName = files.get(index).getName();
        String excpectedFolderName = foldersToTest[index];
        assertEquals(folderName, excpectedFolderName);
    }
    
    System.out.println(files);
}
 
Example 10
Source File: HiddenAspect.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void applyHidden(NodeRef nodeRef, HiddenFileInfo filter, boolean checkChildren)
{
    if(!hasHiddenAspect(nodeRef))
    {
        addHiddenAspect(nodeRef, filter);
    }
    else
    {
        nodeService.setProperty(nodeRef, ContentModel.PROP_VISIBILITY_MASK, filter.getVisibilityMask());
        nodeService.setProperty(nodeRef, ContentModel.PROP_CASCADE_HIDDEN, filter.cascadeHiddenAspect());
        nodeService.setProperty(nodeRef, ContentModel.PROP_CASCADE_INDEX_CONTROL, filter.cascadeIndexControlAspect());
    }

    if(!hasIndexControlAspect(nodeRef))
    {
        addIndexControlAspect(nodeRef);
    }

    QName typeQName = nodeService.getType(nodeRef);
    FileFolderServiceType type = fileFolderService.getType(typeQName);
    boolean isFolder = type.equals(FileFolderServiceType.FOLDER) || type.equals(FileFolderServiceType.SYSTEM_FOLDER);
    if(isFolder && checkChildren && (filter.cascadeHiddenAspect() || filter.cascadeIndexControlAspect()))
    {
        PagingRequest pagingRequest = new PagingRequest(0, Integer.MAX_VALUE, null);
        PagingResults<FileInfo> results = fileFolderService.list(nodeRef, true, true, null, null, pagingRequest);
        List<FileInfo> files = results.getPage();

        // apply the hidden aspect to all folders and folders and then recursively to all sub-folders, unless the sub-folder
        // already has the hidden aspect applied (it may have been applied for a different pattern).
        for(FileInfo file : files)
        {
            behaviourFilter.disableBehaviour(file.getNodeRef(), ContentModel.ASPECT_LOCKABLE);
            try
            {
                applyHidden(file, filter);
            }
            finally
            {
                behaviourFilter.enableBehaviour(file.getNodeRef(), ContentModel.ASPECT_LOCKABLE);
            }
        }
    }
}
 
Example 11
Source File: TaggingServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.tagging.TaggingService#getTags(org.alfresco.service.cmr.repository.StoreRef, org.alfresco.query.PagingRequest)
 */
public PagingResults<Pair<NodeRef, String>> getTags(StoreRef storeRef, PagingRequest pagingRequest)
{
    ParameterCheck.mandatory("storeRef", storeRef);

	PagingResults<ChildAssociationRef> rootCategories = this.categoryService.getRootCategories(storeRef, ContentModel.ASPECT_TAGGABLE, pagingRequest, true);
    final List<Pair<NodeRef, String>> result = new ArrayList<Pair<NodeRef, String>>(rootCategories.getPage().size());
    for (ChildAssociationRef rootCategory : rootCategories.getPage())
    {
        String name = (String)this.nodeService.getProperty(rootCategory.getChildRef(), ContentModel.PROP_NAME);
        result.add(new Pair<NodeRef, String>(rootCategory.getChildRef(), name));
    }
    final boolean hasMoreItems = rootCategories.hasMoreItems();
    final Pair<Integer, Integer> totalResultCount = rootCategories.getTotalResultCount();
    final String queryExecutionId = rootCategories.getQueryExecutionId();
    rootCategories = null;

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

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

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

    	@Override
    	public String getQueryExecutionId()
    	{
    		return queryExecutionId;
    	}
    };
}
 
Example 12
Source File: SiteAdminSitesGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
    // check the current user access rights
    if (!siteService.isSiteAdmin(currentUser))
    {
        // Note: security, no message to indicate why
        throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Resource not found.");
    }

    // Create paging
    final ScriptPagingDetails paging = new ScriptPagingDetails(getIntParameter(req, MAX_ITEMS,
                DEFAULT_MAX_ITEMS_PER_PAGE), getIntParameter(req, SKIP_COUNT, 0));

    // request a total count of found items
    paging.setRequestTotalCountMax(Integer.MAX_VALUE);

    final List<FilterProp> filterProp = getFilterProperties(req.getParameter(NAME_FILTER));

    final List<Pair<QName, Boolean>> sortProps = new ArrayList<Pair<QName, Boolean>>();
    sortProps.add(new Pair<QName, Boolean>(ContentModel.PROP_NAME, true));

    PagingResults<SiteInfo> pagingResults = AuthenticationUtil.runAs(
                new AuthenticationUtil.RunAsWork<PagingResults<SiteInfo>>()
                {
                    public PagingResults<SiteInfo> doWork() throws Exception
                    {
                        return siteService.listSites(filterProp, sortProps, paging);
                    }
                }, AuthenticationUtil.getAdminUserName());

    List<SiteInfo> result = pagingResults.getPage();
    List<SiteState> sites = new ArrayList<SiteState>(result.size());
    for (SiteInfo info : result)
    {
        sites.add(SiteState.create(info,
                    siteService.listMembers(info.getShortName(), null, SiteModel.SITE_MANAGER, 0), currentUser,
                    nodeService, personService));
    }

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

    // Site data
    sitesData.put("items", sites);
    // Paging data
    sitesData.put("count", result.size());
    sitesData.put("hasMoreItems", pagingResults.hasMoreItems());
    sitesData.put("totalItems", (pagingResults.getTotalResultCount() == null ? -1 : pagingResults.getTotalResultCount().getFirst()));
    sitesData.put("skipCount", paging.getSkipCount());
    sitesData.put("maxItems", paging.getMaxItems());
    
    // Create the model from the site and pagination data
    Map<String, Object> model = new HashMap<String, Object>(1);
    model.put("data", sitesData);

    return model;
}
 
Example 13
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 14
Source File: VirtualFileFolderServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testLastDuplicate() throws Exception
{
    NodeRef lastDup = null;
    List<Pair<QName, Boolean>> sortProps = new ArrayList<Pair<QName, Boolean>>(1);
    sortProps.add(new Pair<QName, Boolean>(ContentModel.PROP_NAME,
                                           false));
    String name = "AName.txt";
    String nameAfter = "XXName.txt";

    NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(),
                                         "TestVirtualFileFolderService_testVirtualFolderVirtualChild",
                                         TEST_TEMPLATE_3_JSON_SYS_PATH);
    NodeRef node1 = nodeService.getChildByName(vf,
                                               ContentModel.ASSOC_CONTAINS,
                                               "Node1");
    createContent(node1,
                  name,
                  "0",
                  MimetypeMap.MIMETYPE_TEXT_PLAIN,
                  "UTF-8");
    NodeRef aNameNodeRef = nodeService.getChildByName(node1,
                                                      ContentModel.ASSOC_CHILDREN,
                                                      name);

    createContent(node1,
                  nameAfter,
                  "1",
                  MimetypeMap.MIMETYPE_TEXT_PLAIN,
                  "UTF-8");
    NodeRef nameAfterNodeRef = nodeService.getChildByName(node1,
                                                          ContentModel.ASSOC_CHILDREN,
                                                          nameAfter);

    String namePattern = addWildCardInName(name,
                                           fileAndFolderService
                                                       .getFileInfo(aNameNodeRef)
                                                           .getContentData()
                                                           .getMimetype());
    prepareMocks("=cm:name:AName", smartStore.materializeIfPossible(aNameNodeRef));
    try
    {
    PagingResults<FileInfo> results = fileAndFolderService
                .list(nodeService.getPrimaryParent(aNameNodeRef).getParentRef(),
                      true,
                      false,
                      namePattern,
                      null,
                      sortProps,
                      new PagingRequest(CannedQueryPageDetails.DEFAULT_PAGE_SIZE));

    List<FileInfo> page = results.getPage();

    assertTrue(page.size() > 0);

    assertFalse(page.get(0).getNodeRef().equals(nameAfterNodeRef));
    }
    finally
    {
        resetMocks();
    }
}
 
Example 15
Source File: GroupsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
private PagingResults<AuthorityInfo> getAuthoritiesInfo(AuthorityType authorityType, Boolean isRootParam, String zoneFilter, Set<String> rootAuthorities, Pair<String, Boolean> sortProp,
        Paging paging)
{
    PagingResults<AuthorityInfo> pagingResult;

    if (isRootParam != null)
    {
        List<AuthorityInfo> groupList;

        if (isRootParam)
        {
            // Limit the post processing work by using the already loaded
            // list of root authorities.
            List<AuthorityInfo> authorities = rootAuthorities.stream().
                    map(this::getAuthorityInfo).
                    filter(auth -> zonePredicate(auth.getAuthorityName(), zoneFilter)).
                    collect(Collectors.toList());
            groupList = new ArrayList<>(rootAuthorities.size());
            groupList.addAll(authorities);

            // Post process sorting - this should be moved to service
            // layer. It is done here because sorting is not supported at
            // service layer.
            AuthorityInfoComparator authorityComparator = new AuthorityInfoComparator(sortProp.getFirst(), sortProp.getSecond());
            Collections.sort(groupList, authorityComparator);
        }
        else
        {
            PagingRequest pagingNoMaxItems = new PagingRequest(CannedQueryPageDetails.DEFAULT_PAGE_SIZE);

            // Get authorities using canned query but without using
            // the requested paginating now because we need to filter out
            // the root authorities.
            PagingResults<AuthorityInfo> nonPagingResult = authorityService.getAuthoritiesInfo(authorityType, zoneFilter, null, sortProp.getFirst(), sortProp.getSecond(),
                    pagingNoMaxItems);

            // Post process filtering - this should be moved to service
            // layer. It is done here because filtering by "isRoot" is not
            // supported at service layer.
            groupList = nonPagingResult.getPage();
            if (groupList != null)
            {
                for (Iterator<AuthorityInfo> i = groupList.iterator(); i.hasNext();)
                {
                    AuthorityInfo authorityInfo = i.next();
                    if (!isRootParam.equals(isRootAuthority(rootAuthorities, authorityInfo.getAuthorityName())))
                    {
                        i.remove();
                    }
                }
            }
        }

        // Post process paging - this should be moved to service layer.
        pagingResult = Util.wrapPagingResults(paging, groupList);
    }
    else
    {
        PagingRequest pagingRequest = Util.getPagingRequest(paging);

        // Get authorities using canned query.
        pagingResult = authorityService.getAuthoritiesInfo(authorityType, zoneFilter, null, sortProp.getFirst(), sortProp.getSecond(), pagingRequest);
    }
    return pagingResult;
}
 
Example 16
Source File: ForumTopicsHotGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected Map<String, Object> executeImpl(SiteInfo site, NodeRef nodeRef,
      TopicInfo topic, PostInfo post, WebScriptRequest req, JSONObject json,
      Status status, Cache cache) 
{
   // They shouldn't be trying to list of an existing Post or Topic
   if (topic != null || post != null)
   {
      String error = "Can't list Topics inside an existing Topic or Post";
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
   }
   
   // Grab the date range to search over
   String numDaysS = req.getParameter("numdays");
   int numDays = RECENT_POSTS_PERIOD_DAYS;
   if (numDaysS != null)
   {
      numDays = Integer.parseInt(numDaysS);  
   }
   
   Date now = new Date();
   Date since = new Date(now.getTime() - numDays*ONE_DAY_MS);
   
   // Get the topics with recent replies
   PagingResults<Pair<TopicInfo,Integer>> topicsAndCounts = null;
   PagingRequest paging = buildPagingRequest(req);
   if (site != null)
   {
      topicsAndCounts = discussionService.listHotTopics(site.getShortName(), since, paging);
   }
   else
   {
      topicsAndCounts = discussionService.listHotTopics(nodeRef, since, paging);
   }
   
   // For this, we actually only need the topics, not their counts too
   List<TopicInfo> topics = new ArrayList<TopicInfo>();
   for (Pair<TopicInfo,Integer> tc : topicsAndCounts.getPage())
   {
      topics.add(tc.getFirst());
   }
   
   
   // If they did a site based search, and the component hasn't
   //  been created yet, use the site for the permissions checking
   if (site != null && nodeRef == null)
   {
      nodeRef = site.getNodeRef();
   }
   
   
   // Build the common model parts
   Map<String, Object> model = buildCommonModel(site, topic, post, req);
   model.put("forum", nodeRef);
   
   // Have the topics rendered
   model.put("data", renderTopics(topics, topicsAndCounts.getTotalResultCount(), paging, site));
   
   // All done
   return model;
}
 
Example 17
Source File: CopyActionExecuter.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef)
{
    if (!nodeService.exists(actionedUponNodeRef))
    {
        return;
    }
    NodeRef destinationParent = (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER);

    // Check the destination not to be in a pending delete list
    // MNT-11695
    Set<QName> destinationAspects = nodeService.getAspects(destinationParent);
    if (destinationAspects.contains(ContentModel.ASPECT_PENDING_DELETE))
    {
        return;
    }

    // Get the deep copy value
    boolean deepCopy = false;
    Boolean deepCopyValue = (Boolean)ruleAction.getParameterValue(PARAM_DEEP_COPY);
    if (deepCopyValue != null)
    {
        deepCopy = deepCopyValue.booleanValue();
    }
        
    // Get the overwirte value
    boolean overwrite = true;
    Boolean overwriteValue = (Boolean)ruleAction.getParameterValue(PARAM_OVERWRITE_COPY);
    if (overwriteValue != null)
    {
        overwrite = overwriteValue.booleanValue();
    }
    
    // Since we are overwriting we need to figure out whether the destination node exists
    NodeRef copyNodeRef = null;
    if (overwrite == true)
    {
        // Try and find copies of the actioned upon node reference.
        // Include the parent folder because that's where the copy will be if this action
        // had done the first copy.
        PagingResults<CopyInfo> copies = copyService.getCopies(
                actionedUponNodeRef,
                destinationParent,
                new PagingRequest(1000));
        for (CopyInfo copyInfo : copies.getPage())
        {
            NodeRef copy = copyInfo.getNodeRef();
            // We know that it is in the destination parent, but avoid working copies
            if (checkOutCheckInService.isWorkingCopy(copy))
            {
                continue;
            }
            if (copyNodeRef == null)
            {
                copyNodeRef = copy;
            }
            else
            {
                throw new RuleServiceException(ERR_OVERWRITE);
            }
        }
    }
    
    if (copyNodeRef != null)
    {
        // Overwrite the state of the destination node ref with the actioned upon node state
        this.copyService.copy(actionedUponNodeRef, copyNodeRef);
    }
    else
    {
        ChildAssociationRef originalAssoc = nodeService.getPrimaryParent(actionedUponNodeRef);
        // Create a new copy of the node
        this.copyService.copyAndRename(
                actionedUponNodeRef, 
                destinationParent,
                originalAssoc.getTypeQName(),
                originalAssoc.getQName(),
                deepCopy);
    }
}
 
Example 18
Source File: SitesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public PagingResults<SiteContainer> getSiteContainers(String siteId, Paging paging)
{
    SiteInfo siteInfo = validateSite(siteId);
    if(siteInfo == null)
    {
        // site does not exist
        throw new EntityNotFoundException(siteId);
    }

    final PagingResults<FileInfo> pagingResults = siteService.listContainers(siteInfo.getShortName(), Util.getPagingRequest(paging));
    List<FileInfo> containerFileInfos = pagingResults.getPage();
    final List<SiteContainer> siteContainers = new ArrayList<SiteContainer>(containerFileInfos.size());
    for(FileInfo containerFileInfo : containerFileInfos)
    {
        NodeRef nodeRef = containerFileInfo.getNodeRef();
        String containerId = (String)nodeService.getProperty(nodeRef, SiteModel.PROP_COMPONENT_ID);
        SiteContainer siteContainer = new SiteContainer(containerId, nodeRef);
        siteContainers.add(siteContainer);
    }

    return new PagingResults<SiteContainer>()
    {
        @Override
        public List<SiteContainer> getPage()
        {
            return siteContainers;
        }

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

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

        @Override
        public String getQueryExecutionId()
        {
            return null;
        }
    };
}
 
Example 19
Source File: GetChildrenCannedQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testPagingGetChildrenCannedQueryWithoutProps() throws Exception
{
    try
    {
        long startTime = System.currentTimeMillis();

        int itemCount = 1500;
        int repeatListCount = 5;

        Set<QName> assocTypeQNames = new HashSet<>(1);
        assocTypeQNames.add(ContentModel.ASSOC_CONTAINS);

        Set<QName> childTypeQNames = new HashSet<>(1);
        childTypeQNames.add(ContentModel.TYPE_FOLDER);

        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

        NodeRef testFolder = repositoryHelper.getCompanyHome();

        NodeRef parentFolder = createFolder(testFolder, "testCreateList-"+ GUID.generate(), ContentModel.TYPE_FOLDER);

        for (int i = 1; i <= itemCount; i++)
        {
            String folderName = "folder_" + GUID.generate();
            createFolder(parentFolder, folderName, ContentModel.TYPE_FOLDER);
        }

        for (int j = 1; j <= repeatListCount; j++)
        {
            // page/iterate through the children
            boolean hasMore = true;
            int skipCount = 0;
            int maxItems = 100;

            int count = 0;
            Set<String> docIds = new HashSet<>(itemCount);

            while (hasMore)
            {
                // note: mimic similar to AlfrescoServiceCmisServiceImpl
                PagingResults<NodeRef> results = list(parentFolder, skipCount, maxItems, skipCount + 10000, assocTypeQNames, childTypeQNames, null, null, null, null);
                hasMore = results.hasMoreItems();
                skipCount = skipCount + maxItems;

                for (NodeRef nodeRef : results.getPage())
                {
                    docIds.add(nodeRef.getId());
                    count++;
                }
            }

            assertEquals(itemCount, count);
            assertEquals(itemCount, docIds.size());
        }

        System.out.println("Test time: " + (System.currentTimeMillis() - startTime) + " ms");
    } 
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example 20
Source File: GroupsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public CollectionWithPagingInfo<Group> getGroupsByPersonId(String requestedPersonId, Parameters parameters)
{
    // Canonicalize the person ID, performing -me- alias substitution.
    final String personId = people.validatePerson(requestedPersonId);

    // Non-admins can only access their own data
    // TODO: this is also in PeopleImpl.update(personId,personInfo) - refactor?
    boolean isAdmin = authorityService.hasAdminAuthority();
    String currentUserId = AuthenticationUtil.getFullyAuthenticatedUser();
    if (!isAdmin && !currentUserId.equalsIgnoreCase(personId))
    {
        // The user is not an admin user and is not attempting to retrieve *their own* details.
        throw new PermissionDeniedException();
    }

    Query q = parameters.getQuery();
    Boolean isRootParam = null;
    String zoneFilter = null;
    if (q != null)
    {
        GroupsQueryWalker propertyWalker = new GroupsQueryWalker();
        QueryHelper.walk(q, propertyWalker);

        isRootParam = propertyWalker.getIsRoot();
        List<String> zonesParam = propertyWalker.getZones();
        if (zonesParam != null)
        {
            validateZonesParam(zonesParam);
            zoneFilter = zonesParam.get(0);
        }
    }

    final List<String> includeParam = parameters.getInclude();
    Paging paging = parameters.getPaging();

    // Retrieve sort column. This is limited for now to sort column due to
    // v0 api implementation. Should be improved in the future.
    Pair<String, Boolean> sortProp = getGroupsSortProp(parameters);

    // Get all the authorities for a user, including but not limited to, groups.
    Set<String> userAuthorities = runAsSystem(
            () -> authorityService.getAuthoritiesForUser(personId));

    final Set<String> rootAuthorities = getAllRootAuthorities(AuthorityType.GROUP);

    // Filter, transform and sort the list of user authorities into
    // a suitable list of AuthorityInfo objects.
    final String finalZoneFilter = zoneFilter;
    final Boolean finalIsRootParam = isRootParam;
    List<AuthorityInfo> groupAuthorities = userAuthorities.stream().
            filter(a -> a.startsWith(AuthorityType.GROUP.getPrefixString())).
            filter(a -> isRootPredicate(finalIsRootParam, rootAuthorities, a)).
            filter(a -> zonePredicate(a, finalZoneFilter)).
            map(this::getAuthorityInfo).
            sorted(new AuthorityInfoComparator(sortProp.getFirst(), sortProp.getSecond())).
            collect(Collectors.toList());

    PagingResults<AuthorityInfo> pagingResult = Util.wrapPagingResults(paging, groupAuthorities);

    // Create response.
    final List<AuthorityInfo> page = pagingResult.getPage();
    int totalItems = pagingResult.getTotalResultCount().getFirst();

    // Transform the page of results into Group objects
    List<Group> groups = page.stream().
            map(authority -> getGroup(authority, includeParam, rootAuthorities)).
            collect(Collectors.toList());

    return CollectionWithPagingInfo.asPaged(paging, groups, pagingResult.hasMoreItems(), totalItems);
}