Java Code Examples for org.alfresco.service.cmr.search.SearchParameters#addSort()

The following examples show how to use org.alfresco.service.cmr.search.SearchParameters#addSort() . 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: SortConstraint.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected SearchParameters applyDecorations(ActualEnvironment environment, SearchParameters searchParameters,
            VirtualQuery query)
{
    SearchParameters searchParametersCopy = searchParameters.copy();
    for (Pair<QName, Boolean> sort : sortProps)
    {
        if (!IGNORED_SORT_PROPERTIES.contains(sort.getFirst()))
        {
            SortDefinition sortDefinition = new SortDefinition(SortType.FIELD,
                                                               sort.getFirst().getPrefixString(),
                                                               sort.getSecond());
            searchParametersCopy.addSort(sortDefinition);
        }
    }
    return searchParametersCopy;
}
 
Example 2
Source File: Search.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Execute the query
 * 
 * Removes any duplicates that may be present (ID search can cause duplicates -
 * it is better to remove them here)
 * 
 * @param store         StoreRef to search against - null for default configured store
 * @param search        Lucene search to execute
 * @param sort          Columns to sort by
 * @param language      Search language to use e.g. SearchService.LANGUAGE_LUCENE
 * @param maxResults    Maximum results to return if > 0
 * @param skipResults   Results to skip in the result set
 * 
 * @return Array of Node objects
 */
protected Object[] query(String store, String search, SortColumn[] sort, String language, int maxResults, int skipResults)
{   
    SearchParameters sp = new SearchParameters();
    sp.addStore(store != null ? new StoreRef(store) : this.storeRef);
    sp.setLanguage(language != null ? language : SearchService.LANGUAGE_LUCENE);
    sp.setQuery(search);
    if (maxResults > 0)
    {
        sp.setLimit(maxResults);
        sp.setLimitBy(LimitBy.FINAL_SIZE);
    }
    if (skipResults > 0)
    {
        sp.setSkipCount(skipResults);
    }
    if (sort != null)
    {
        for (SortColumn sd : sort)
        {
            sp.addSort(sd.column, sd.asc);
        }
    }
    
    return query(sp, true);
}
 
Example 3
Source File: SearchMapper.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * SearchParameters from List<SortDef>
 * @param sp SearchParameters
 * @param sort List<SortDef>
 */
public void fromSort(SearchParameters sp, List<SortDef> sort)
{
    if (sort != null && !sort.isEmpty())
    {
        if (LANGUAGE_CMIS_ALFRESCO.equals(sp.getLanguage()))
        {
            throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_MESSAGE_ID,
                        new Object[] { ": sort {} not allowed with cmis language" });
        }
        for (SortDef sortDef:sort)
        {

            try
            {
                SortType sortType = SortType.valueOf(sortDef.getType());
                String field = sortDef.getField();
                sp.addSort(new SortDefinition(sortType, field, sortDef.isAscending()));
            }
            catch (IllegalArgumentException e)
            {
                throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_MESSAGE_ID, new Object[] { sortDef.getType() });
            }
        }
    }
}
 
Example 4
Source File: QueriesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Adds sort order to the SearchParameters.
 */
protected void addSortOrder(Parameters parameters, Map<String, QName> sortParamsToQNames,
    List<SortColumn> defaultSortCols, SearchParameters sp)
{
    List<SortColumn> sortCols = getSorting(parameters, defaultSortCols);
    for (SortColumn sortCol : sortCols)
    {
        QName sortPropQName = sortParamsToQNames.get(sortCol.column);
        if (sortPropQName == null)
        {
            throw new InvalidArgumentException("Invalid sort field: "+sortCol.column);
        }
        sp.addSort("@" + sortPropQName,  sortCol.asc);
    }
}
 
Example 5
Source File: LuceneCategoryServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private Collection<ChildAssociationRef> getChildren(NodeRef categoryRef, Mode mode, Depth depth, boolean sortByName, String filter, int fetchSize)
{
    if (categoryRef == null)
    {
        return Collections.<ChildAssociationRef> emptyList();
    }
    
    categoryRef = tenantService.getBaseName(categoryRef); // for solr
    
    ResultSet resultSet = null;
    try
    {
        StringBuilder luceneQuery = new StringBuilder(64);

        switch (mode)
        {
        case ALL:
            luceneQuery.append("PATH:\"");
            luceneQuery.append(buildXPath(nodeService.getPath(categoryRef))).append("/");
            if (depth.equals(Depth.ANY))
            {
                luceneQuery.append("/");
            }
            luceneQuery.append("*").append("\" ");
            break;
        case MEMBERS:
            luceneQuery.append("PATH:\"");
            luceneQuery.append(buildXPath(nodeService.getPath(categoryRef))).append("/");
            if (depth.equals(Depth.ANY))
            {
                luceneQuery.append("/");
            }
            luceneQuery.append("member").append("\" ");
            break;
        case SUB_CATEGORIES:
            luceneQuery.append("+PATH:\"");
            luceneQuery.append(buildXPath(nodeService.getPath(categoryRef))).append("/");
            if (depth.equals(Depth.ANY))
            {
                luceneQuery.append("/");
            }
            luceneQuery.append("*").append("\" ");
            luceneQuery.append("+TYPE:\"" + ContentModel.TYPE_CATEGORY.toString() + "\"");
            break;
        }
        if (filter != null)
        {
            luceneQuery.append(" " + "+@cm\\:name:\"*" + filter + "*\"");
        }

        // Get a searcher that will include Categories added in this transaction
        SearchService searcher = indexerAndSearcher.getSearcher(categoryRef.getStoreRef(), true);
        
        // Perform the search
        SearchParameters searchParameters = new SearchParameters();
        resultSet = searcher.query(categoryRef.getStoreRef(), "lucene", luceneQuery.toString(), null);
        searchParameters.setLanguage("lucene");
        if(sortByName)
        {
        	searchParameters.addSort("@" + ContentModel.PROP_NAME, true);
        }
        searchParameters.setQuery(luceneQuery.toString());
        searchParameters.setLimit(-1);
        searchParameters.setMaxItems(fetchSize);
        searchParameters.setLimitBy(LimitBy.FINAL_SIZE);
        searchParameters.addStore(categoryRef.getStoreRef());
        resultSet = searcher.query(searchParameters);

        // Convert from search results to the required Child Assocs
        return resultSetToChildAssocCollection(resultSet);
    }
    finally
    {
        if (resultSet != null)
        {
            resultSet.close();
        }
    }
}
 
Example 6
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 7
Source File: LinksServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public PagingResults<LinkInfo> findLinks(String siteShortName, String user,
      Date from, Date to, String tag, PagingRequest paging) 
{
   NodeRef container = getSiteLinksContainer(siteShortName, false);
   if (container == null)
   {
      // No links
      return new EmptyPagingResults<LinkInfo>();
   }
   
   // Build the query
   StringBuilder luceneQuery = new StringBuilder();
   luceneQuery.append(" +TYPE:\"" + LinksModel.TYPE_LINK + "\"");
   luceneQuery.append(" +PATH:\"" + nodeService.getPath(container).toPrefixString(namespaceService) + "/*\"");

   if (user != null)
   {
      luceneQuery.append(" +@cm\\:creator:\"" + user + "\"");
   }
   if (from != null && to != null)
   {
      luceneQuery.append(LuceneUtils.createDateRangeQuery(
            from, to, ContentModel.PROP_CREATED, dictionaryService, namespaceService));
   }
   if (tag != null)
   {
      luceneQuery.append(" +PATH:\"/cm:taggable/cm:" + ISO9075.encode(tag) + "/member\"");
   }
   
   String sortOn = "@{http://www.alfresco.org/model/content/1.0}created";

   // Query
   SearchParameters sp = new SearchParameters();
   sp.addStore(container.getStoreRef());
   sp.setLanguage(SearchService.LANGUAGE_LUCENE);
   sp.setQuery(luceneQuery.toString());
   sp.addSort(sortOn, false);
   if (paging.getSkipCount() > 0)
   {
       sp.setSkipCount(paging.getSkipCount());
   }
   
   
   // Build the results
   PagingResults<LinkInfo> pagedResults = new EmptyPagingResults<LinkInfo>();
   ResultSet results = null;
   
   try 
   {
      results = searchService.query(sp);
      pagedResults = wrap(results, container, paging);
   }
   finally
   {
      if (results != null)
      {
         results.close();
      }
   }
   
   return pagedResults;
}
 
Example 8
Source File: DiscussionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public PagingResults<TopicInfo> findTopics(NodeRef nodeRef,
      String username, String tag, boolean sortAscending, PagingRequest paging) 
{
   // Build the query
   StringBuilder luceneQuery = new StringBuilder();
   luceneQuery.append(" +TYPE:\"" + ForumModel.TYPE_TOPIC + "\"");
   luceneQuery.append(" +PATH:\"" + nodeService.getPath(nodeRef).toPrefixString(namespaceService) + "/*\"");

   if (username != null)
   {
      luceneQuery.append(" +@cm\\:creator:\"" + username + "\"");
   }
   if (tag != null)
   {
      luceneQuery.append(" +PATH:\"/cm:taggable/cm:" + ISO9075.encode(tag) + "/member\"" );
   }
   
   String sortOn = "@{http://www.alfresco.org/model/content/1.0}created";

   // Query
   SearchParameters sp = new SearchParameters();
   sp.addStore(nodeRef.getStoreRef());
   sp.setLanguage(SearchService.LANGUAGE_LUCENE);
   sp.setQuery(luceneQuery.toString());
   sp.addSort(sortOn, sortAscending);
   if (paging.getSkipCount() > 0)
   {
       sp.setSkipCount(paging.getSkipCount());
   }
   
   
   // Build the results
   PagingResults<TopicInfo> pagedResults = new EmptyPagingResults<TopicInfo>();
   ResultSet results = null;
   
   try 
   {
      results = searchService.query(sp);
      pagedResults = wrap(results, nodeRef, paging);
   }
   finally
   {
      if (results != null)
      {
         results.close();
      }
   }
   
   return pagedResults;
}
 
Example 9
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 10
Source File: QuickShareLinksImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public CollectionWithPagingInfo<QuickShareLink> findLinks(Parameters parameters)
{
    checkEnabled();

    String queryString =
            "ASPECT:\"" + QuickShareModel.ASPECT_QSHARE.toString() + "\"";

    SearchParameters sp = new SearchParameters();

    // note: REST API query parameter (ie. where clause filter) - not to be confused with search query ;-)
    Query q = parameters.getQuery();
    if (q != null)
    {
        // filtering via "where" clause
        MapBasedQueryWalker propertyWalker = new MapBasedQueryWalker(FIND_SHARED_LINKS_QUERY_PROPERTIES, null);
        QueryHelper.walk(q, propertyWalker);

        String sharedByUserId = propertyWalker.getProperty(PARAM_SHAREDBY, WhereClauseParser.EQUALS, String.class);

        if (sharedByUserId != null)
        {
            if (People.DEFAULT_USER.equalsIgnoreCase(sharedByUserId))
            {
                sharedByUserId =  AuthenticationUtil.getFullyAuthenticatedUser();
            }

            QueryParameterDefinition qpd = new QueryParameterDefImpl(QuickShareModel.PROP_QSHARE_SHAREDBY, dictionaryService.getDataType(DataTypeDefinition.TEXT),
                    true, sharedByUserId);
            sp.addQueryParameterDefinition(qpd);

            String qsharedBy = QuickShareModel.PROP_QSHARE_SHAREDBY.toPrefixString(namespaceService);
            queryString += " +@"+SearchLanguageConversion.escapeLuceneQuery(qsharedBy)+":\"${"+qsharedBy+"}\"";
        }
    }

    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery(queryString);
    sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);

    Paging paging = parameters.getPaging();
    PagingRequest pagingRequest = Util.getPagingRequest(paging);

    sp.setSkipCount(pagingRequest.getSkipCount());
    sp.setMaxItems(pagingRequest.getMaxItems());

    sp.addSort("@" + ContentModel.PROP_MODIFIED, false);

    ResultSet results = searchService.query(sp);

    List<QuickShareLink> qsLinks = new ArrayList<>(results.length());

    List<String> includeParam = parameters.getInclude();

    for (ResultSetRow row : results)
    {
        NodeRef nodeRef = row.getNodeRef();
        qsLinks.add(getQuickShareInfo(nodeRef, false, includeParam));
    }

    results.close();

    return CollectionWithPagingInfo.asPaged(paging, qsLinks, results.hasMore(), Long.valueOf(results.getNumberFound()).intValue());
}