Search in sources :

Example 11 with Pair

use of org.alfresco.util.Pair in project alfresco-remote-api by Alfresco.

the class SitesImpl method getSiteMembers.

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);
}
Also used : SiteInfo(org.alfresco.service.cmr.site.SiteInfo) Paging(org.alfresco.rest.framework.resource.parameters.Paging) ArrayList(java.util.ArrayList) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) PagingRequest(org.alfresco.query.PagingRequest) SiteMembership(org.alfresco.repo.site.SiteMembership) SiteService(org.alfresco.service.cmr.site.SiteService) FilterPropBoolean(org.alfresco.repo.node.getchildren.FilterPropBoolean) Pair(org.alfresco.util.Pair)

Example 12 with Pair

use of org.alfresco.util.Pair in project alfresco-remote-api by Alfresco.

the class SitesImpl method getSites.

public CollectionWithPagingInfo<MemberOfSite> getSites(String personId, Parameters parameters) {
    Paging paging = parameters.getPaging();
    personId = people.validatePerson(personId);
    PagingRequest pagingRequest = Util.getPagingRequest(paging);
    // get the sorting options
    List<Pair<? extends Object, SortOrder>> sortPairs = new ArrayList<>(parameters.getSorting().size());
    List<SortColumn> sortCols = parameters.getSorting();
    if ((sortCols != null) && (sortCols.size() > 0)) {
        for (SortColumn sortCol : sortCols) {
            SiteService.SortFields sortProp = SORT_SITE_MEMBERSHIP.get(sortCol.column);
            if (sortProp == null) {
                throw new InvalidArgumentException("Invalid sort field: " + sortCol.column);
            }
            sortPairs.add(new Pair<>(sortProp, (sortCol.asc ? SortOrder.ASCENDING : SortOrder.DESCENDING)));
        }
    } else {
        // default sort order
        sortPairs.add(new Pair<SiteService.SortFields, SortOrder>(SiteService.SortFields.SiteTitle, SortOrder.ASCENDING));
    }
    // get the unsorted list of site memberships
    List<SiteMembership> siteMembers = siteService.listSiteMemberships(personId, 0);
    // sort the list of site memberships
    int totalSize = siteMembers.size();
    final List<SiteMembership> sortedSiteMembers = new ArrayList<>(siteMembers);
    Collections.sort(sortedSiteMembers, new SiteMembershipComparator(sortPairs, SiteMembershipComparator.Type.SITES));
    PageDetails pageDetails = PageDetails.getPageDetails(pagingRequest, totalSize);
    List<MemberOfSite> ret = new ArrayList<>(totalSize);
    List<FilterProp> filterProps = getFilterPropListOfSites(parameters);
    int counter;
    int totalItems = 0;
    Iterator<SiteMembership> it = sortedSiteMembers.iterator();
    for (counter = 0; it.hasNext(); ) {
        SiteMembership siteMember = it.next();
        if (filterProps != null && !includeFilter(siteMember, filterProps)) {
            continue;
        }
        if (counter < pageDetails.getSkipCount()) {
            totalItems++;
            counter++;
            continue;
        }
        if (counter <= pageDetails.getEnd() - 1) {
            SiteInfo siteInfo = siteMember.getSiteInfo();
            MemberOfSite memberOfSite = new MemberOfSite(siteInfo.getShortName(), siteInfo.getNodeRef(), siteMember.getRole());
            ret.add(memberOfSite);
            counter++;
        }
        totalItems++;
    }
    return CollectionWithPagingInfo.asPaged(paging, ret, counter < totalItems, totalItems);
}
Also used : SiteMembershipComparator(org.alfresco.repo.site.SiteMembershipComparator) ArrayList(java.util.ArrayList) SortColumn(org.alfresco.rest.framework.resource.parameters.SortColumn) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) SiteMembership(org.alfresco.repo.site.SiteMembership) SiteService(org.alfresco.service.cmr.site.SiteService) Pair(org.alfresco.util.Pair) SiteInfo(org.alfresco.service.cmr.site.SiteInfo) FilterProp(org.alfresco.repo.node.getchildren.FilterProp) Paging(org.alfresco.rest.framework.resource.parameters.Paging) SortOrder(org.alfresco.query.CannedQuerySortDetails.SortOrder) PagingRequest(org.alfresco.query.PagingRequest) PageDetails(org.alfresco.query.PageDetails)

Example 13 with Pair

use of org.alfresco.util.Pair in project alfresco-remote-api by Alfresco.

the class TagsImpl method getTags.

public CollectionWithPagingInfo<Tag> getTags(StoreRef storeRef, Parameters params) {
    Paging paging = params.getPaging();
    PagingResults<Pair<NodeRef, String>> results = taggingService.getTags(storeRef, Util.getPagingRequest(paging));
    taggingService.getPagedTags(storeRef, 0, paging.getMaxItems());
    Integer totalItems = results.getTotalResultCount().getFirst();
    List<Pair<NodeRef, String>> page = results.getPage();
    List<Tag> tags = new ArrayList<Tag>(page.size());
    List<Pair<String, Integer>> tagsByCount = null;
    Map<String, Integer> tagsByCountMap = new HashMap<String, Integer>();
    if (params.getInclude().contains(PARAM_INCLUDE_COUNT)) {
        tagsByCount = taggingService.findTaggedNodesAndCountByTagName(storeRef);
        if (tagsByCount != null) {
            for (Pair<String, Integer> tagByCountElem : tagsByCount) {
                tagsByCountMap.put(tagByCountElem.getFirst(), tagByCountElem.getSecond());
            }
        }
    }
    for (Pair<NodeRef, String> pair : page) {
        Tag selectedTag = new Tag(pair.getFirst(), pair.getSecond());
        selectedTag.setCount(tagsByCountMap.get(selectedTag.getTag()));
        tags.add(selectedTag);
    }
    return CollectionWithPagingInfo.asPaged(paging, tags, results.hasMoreItems(), (totalItems == null ? null : totalItems.intValue()));
}
Also used : HashMap(java.util.HashMap) Paging(org.alfresco.rest.framework.resource.parameters.Paging) ArrayList(java.util.ArrayList) NodeRef(org.alfresco.service.cmr.repository.NodeRef) Tag(org.alfresco.rest.api.model.Tag) Pair(org.alfresco.util.Pair)

Example 14 with Pair

use of org.alfresco.util.Pair in project alfresco-remote-api by Alfresco.

the class ForumTopicsFilteredGet method wrap.

/**
 * Wrap up search results as {@link TopicInfo} instances
 *
 * @param finalResults ResultSet
 * @param paging PagingRequest
 */
protected PagingResults<TopicInfo> wrap(final ResultSet finalResults, PagingRequest paging) {
    int maxItems = paging.getMaxItems();
    Comparator<TopicInfo> lastPostDesc = new Comparator<TopicInfo>() {

        @Override
        public int compare(TopicInfo t1, TopicInfo t2) {
            Date t1LastPostDate = t1.getCreatedAt();
            if (discussionService.getMostRecentPost(t1) != null) {
                t1LastPostDate = discussionService.getMostRecentPost(t1).getCreatedAt();
            }
            Date t2LastPostDate = t2.getCreatedAt();
            if (discussionService.getMostRecentPost(t2) != null) {
                t2LastPostDate = discussionService.getMostRecentPost(t2).getCreatedAt();
            }
            return t2LastPostDate.compareTo(t1LastPostDate);
        }
    };
    final Set<TopicInfo> topics = new TreeSet<TopicInfo>(lastPostDesc);
    for (ResultSetRow row : finalResults) {
        Pair<TopicInfo, PostInfo> pair = discussionService.getForNodeRef(row.getNodeRef());
        TopicInfo topic = pair.getFirst();
        if (topic != null) {
            String path = nodeService.getPath(topic.getNodeRef()).toDisplayPath(nodeService, permissionService);
            String site = path.split("/")[3];
            TopicInfoImpl tii = (TopicInfoImpl) topic;
            tii.setShortSiteName(site);
            topics.add(tii);
            if (topics.size() >= maxItems) {
                break;
            }
        }
    }
    // Wrap
    return new PagingResults<TopicInfo>() {

        @Override
        public boolean hasMoreItems() {
            try {
                return finalResults.hasMore();
            } catch (UnsupportedOperationException e) {
                // Not all search results support paging
                return false;
            }
        }

        @Override
        public Pair<Integer, Integer> getTotalResultCount() {
            int skipCount = 0;
            int itemsRemainingAfterThisPage = 0;
            try {
                skipCount = finalResults.getStart();
            } catch (UnsupportedOperationException e) {
            }
            try {
                itemsRemainingAfterThisPage = finalResults.length();
            } catch (UnsupportedOperationException e) {
            }
            final int totalItemsInUnpagedResultSet = skipCount + itemsRemainingAfterThisPage;
            return new Pair<Integer, Integer>(totalItemsInUnpagedResultSet, totalItemsInUnpagedResultSet);
        }

        @Override
        public List<TopicInfo> getPage() {
            return new ArrayList<TopicInfo>(topics);
        }

        @Override
        public String getQueryExecutionId() {
            return null;
        }
    };
}
Also used : PagingResults(org.alfresco.query.PagingResults) EmptyPagingResults(org.alfresco.query.EmptyPagingResults) TopicInfoImpl(org.alfresco.repo.discussion.TopicInfoImpl) ArrayList(java.util.ArrayList) ResultSetRow(org.alfresco.service.cmr.search.ResultSetRow) TopicInfo(org.alfresco.service.cmr.discussion.TopicInfo) Date(java.util.Date) Comparator(java.util.Comparator) TreeSet(java.util.TreeSet) PostInfo(org.alfresco.service.cmr.discussion.PostInfo) Pair(org.alfresco.util.Pair)

Example 15 with Pair

use of org.alfresco.util.Pair in project acs-community-packaging by Alfresco.

the class BaseAssociationEditor method getAvailableOptions.

/**
 * Retrieves the available options for the current association
 *
 * @param context Faces Context
 * @param contains The contains part of the query
 */
protected void getAvailableOptions(FacesContext context, String contains) {
    AssociationDefinition assocDef = getAssociationDefinition(context);
    if (assocDef != null) {
        // find and show all the available options for the current association
        String type = assocDef.getTargetClass().getName().toString();
        if (type.equals(ContentModel.TYPE_AUTHORITY_CONTAINER.toString())) {
            UserTransaction tx = null;
            try {
                tx = Repository.getUserTransaction(context, true);
                tx.begin();
                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }
                // get all available groups
                AuthorityService authorityService = Repository.getServiceRegistry(context).getAuthorityService();
                Set<String> groups = authorityService.getAllAuthoritiesInZone(AuthorityService.ZONE_APP_DEFAULT, AuthorityType.GROUP);
                this.availableOptions = new ArrayList<NodeRef>(groups.size());
                // get the NodeRef for each matching group
                AuthorityDAO authorityDAO = (AuthorityDAO) FacesContextUtils.getRequiredWebApplicationContext(context).getBean("authorityDAO");
                if (authorityDAO != null) {
                    List<String> matchingGroups = new ArrayList<String>();
                    String groupDisplayName;
                    for (String group : groups) {
                        // get display name, if not present strip prefix from group id
                        groupDisplayName = authorityService.getAuthorityDisplayName(group);
                        if (groupDisplayName == null || groupDisplayName.length() == 0) {
                            groupDisplayName = group.substring(PermissionService.GROUP_PREFIX.length());
                        }
                        // otherwise just add the group name to the sorted set
                        if (safeContains != null) {
                            if (groupDisplayName.toLowerCase().indexOf(safeContains) != -1) {
                                matchingGroups.add(group);
                            }
                        } else {
                            matchingGroups.add(group);
                        }
                    }
                    // sort the group names
                    Collections.sort(matchingGroups, new SimpleStringComparator());
                    // go through the sorted set and get the NodeRef for each group
                    for (String groupName : matchingGroups) {
                        NodeRef groupRef = authorityDAO.getAuthorityNodeRefOrNull(groupName);
                        if (groupRef != null) {
                            this.availableOptions.add(groupRef);
                        }
                    }
                }
                // commit the transaction
                tx.commit();
            } catch (Throwable err) {
                Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err);
                this.availableOptions = Collections.<NodeRef>emptyList();
                try {
                    if (tx != null) {
                        tx.rollback();
                    }
                } catch (Exception tex) {
                }
            }
        } else if (type.equals(ContentModel.TYPE_PERSON.toString())) {
            List<Pair<QName, String>> filter = (contains != null && contains.trim().length() > 0) ? Utils.generatePersonFilter(contains.trim()) : null;
            // Always sort by last name, then first name
            List<Pair<QName, Boolean>> sort = new ArrayList<Pair<QName, Boolean>>();
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_LASTNAME, true));
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_FIRSTNAME, true));
            // Log the filtering
            if (logger.isDebugEnabled())
                logger.debug("Query filter: " + filter);
            // How many to limit too?
            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();
            if (maxResults <= 0) {
                maxResults = Utils.getPersonMaxResults();
            }
            List<PersonInfo> persons = Repository.getServiceRegistry(context).getPersonService().getPeople(filter, true, sort, new PagingRequest(maxResults, null)).getPage();
            // Save the results
            List<NodeRef> nodes = new ArrayList<NodeRef>(persons.size());
            for (PersonInfo person : persons) {
                nodes.add(person.getNodeRef());
            }
            this.availableOptions = nodes;
        } else {
            // for all other types/aspects perform a lucene search
            StringBuilder query = new StringBuilder("+TYPE:\"");
            if (assocDef.getTargetClass().isAspect()) {
                query = new StringBuilder("+ASPECT:\"");
            } else {
                query = new StringBuilder("+TYPE:\"");
            }
            query.append(type);
            query.append("\"");
            if (contains != null && contains.trim().length() != 0) {
                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }
                query.append(" AND +@");
                String nameAttr = Repository.escapeQName(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "name"));
                query.append(nameAttr);
                query.append(":\"*" + safeContains + "*\"");
            }
            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();
            if (logger.isDebugEnabled()) {
                logger.debug("Query: " + query.toString());
                logger.debug("Max results size: " + maxResults);
            }
            SearchParameters searchParams = new SearchParameters();
            searchParams.addStore(Repository.getStoreRef());
            searchParams.setLanguage(SearchService.LANGUAGE_LUCENE);
            searchParams.setQuery(query.toString());
            if (maxResults > 0) {
                searchParams.setLimit(maxResults);
                searchParams.setLimitBy(LimitBy.FINAL_SIZE);
            }
            ResultSet results = null;
            try {
                results = Repository.getServiceRegistry(context).getSearchService().query(searchParams);
                this.availableOptions = results.getNodeRefs();
            } catch (SearcherException se) {
                logger.info("Search failed for: " + query, se);
                Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
            } finally {
                if (results != null) {
                    results.close();
                }
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Found " + this.availableOptions.size() + " available options");
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) PersonInfo(org.alfresco.service.cmr.security.PersonService.PersonInfo) QName(org.alfresco.service.namespace.QName) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) ArrayList(java.util.ArrayList) AuthorityDAO(org.alfresco.repo.security.authority.AuthorityDAO) SearcherException(org.alfresco.repo.search.SearcherException) AbortProcessingException(javax.faces.event.AbortProcessingException) IOException(java.io.IOException) PagingRequest(org.alfresco.query.PagingRequest) NodeRef(org.alfresco.service.cmr.repository.NodeRef) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) SearcherException(org.alfresco.repo.search.SearcherException) ResultSet(org.alfresco.service.cmr.search.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) Pair(org.alfresco.util.Pair)

Aggregations

Pair (org.alfresco.util.Pair)61 ArrayList (java.util.ArrayList)34 NodeRef (org.alfresco.service.cmr.repository.NodeRef)23 QName (org.alfresco.service.namespace.QName)22 HashMap (java.util.HashMap)16 PagingRequest (org.alfresco.query.PagingRequest)13 Paging (org.alfresco.rest.framework.resource.parameters.Paging)12 List (java.util.List)11 Serializable (java.io.Serializable)10 HashSet (java.util.HashSet)9 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)9 Set (java.util.Set)8 Map (java.util.Map)7 EntityNotFoundException (org.alfresco.rest.framework.core.exceptions.EntityNotFoundException)7 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)7 AbstractList (java.util.AbstractList)6 Arrays (java.util.Arrays)6 Collections (java.util.Collections)6 PagingResults (org.alfresco.query.PagingResults)6 Node (org.alfresco.rest.api.model.Node)6