Java Code Examples for org.alfresco.service.cmr.search.ResultSet#length()

The following examples show how to use org.alfresco.service.cmr.search.ResultSet#length() . 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: ACLEntryAfterInvocationProvider.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Compute a (Weak)FilteringResultSet by selecting the first maxSize elements from returnedObject.
 *
 * @param maxSize
 * @param returnedObject
 * @return
 */
private ResultSet filterMaxCount(Integer maxSize, ResultSet returnedObject)
{
    // If maxsize is not defined, than return the entire resultset.
    if (maxSize == null)
    {
        return returnedObject;
    }

    WeakFilteringResultSet filteringResultSet = new WeakFilteringResultSet(returnedObject);

    for (int i = 0; i < maxSize && i < returnedObject.length(); i++)
    {
        filteringResultSet.setIncluded(i, true);
    }

    LimitBy limitBy = returnedObject.length() > maxSize? LimitBy.FINAL_SIZE : LimitBy.UNLIMITED;

    filteringResultSet.setResultSetMetaData(new SimpleResultSetMetaData(limitBy,
            PermissionEvaluationMode.EAGER, returnedObject.getResultSetMetaData().getSearchParameters()));


    return filteringResultSet;
}
 
Example 2
Source File: LuceneCategoryServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Set<NodeRef> getClassificationNodes(StoreRef storeRef, QName qname)
{
    ResultSet resultSet = null;
    try
    {
        resultSet = indexerAndSearcher.getSearcher(storeRef, false).query(storeRef, "lucene",
                "PATH:\"/" + getPrefix(qname.getNamespaceURI()) + ISO9075.encode(qname.getLocalName()) + "\"", null);
        
        Set<NodeRef> nodeRefs = new HashSet<NodeRef>(resultSet.length());
        for (ResultSetRow row : resultSet)
        {
            nodeRefs.add(row.getNodeRef());
        }
        
        return nodeRefs;
    }
    finally
    {
        if (resultSet != null)
        {
            resultSet.close();
        }
    }
}
 
Example 3
Source File: AbstractResultSetRowIterator.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create an iterator over the result set. Follows stadard ListIterator
 * conventions
 * 
 * @param resultSet ResultSet
 */
public AbstractResultSetRowIterator(ResultSet resultSet)
{
    super();
    this.resultSet = resultSet;
    this.max = resultSet.length();
}
 
Example 4
Source File: DetachedResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Detached result set based on that provided
 * @param resultSet ResultSet
 */
public DetachedResultSet(ResultSet resultSet)
{
    super();
    rsmd = resultSet.getResultSetMetaData();
    rows = new ArrayList<ResultSetRow>(resultSet.length());
    for (ResultSetRow row : resultSet)
    {
        rows.add(new DetachedResultSetRow(this, row));
    }
    numberFound = resultSet.getNumberFound();
}
 
Example 5
Source File: CMISResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public int getLength()
{
    for (ResultSet resultSet : wrapped.values())
    {
        return resultSet.length();
    }
    throw new IllegalStateException();
}
 
Example 6
Source File: CronScheduledQueryBasedTemplateActionDefinitionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Check the nodes to be indexed
 * 
 * @param nodes
 * @throws Exception
 */
private void checkNodes(List<FileInfo> nodes) throws Exception
{
    SearchService searchService = registry.getSearchService();
    
    boolean notFound = false;
    for (int i = 1; i <= 40; i++)
    {
        notFound = false;
        for (FileInfo fileInfo : nodes)
        {
            ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, "PATH:\"/app:company_home//cm:" + TEST_FOLDER_NAME + "//cm:" + fileInfo.getName() + "\"");
            if (resultSet.length() == 0)
            {
                notFound = true;
                break;
            }
        }
        if (notFound)
        {
            Thread.sleep(500);
        }
        else
        {
            break;
        }
    }
    assertFalse("The content was not created or indexed correctly.", notFound);
}
 
Example 7
Source File: EmailServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Authenticate in Alfresco repository by sender's e-mail address.
 * 
 * @param from Sender's email address
 * @return User name or null if the user does not exist.
 * @throws EmailMessageException Exception will be thrown if authentication is failed.
 */
private String getUsername(String from)
{
    String userName = null;
    
    if(from == null || from.length()==0)
    {
        return null;
    }
    
    if(logger.isDebugEnabled())
    {
        logger.debug("getUsername from: " + from);
    }
    
    
    StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
    String query = "TYPE:cm\\:person AND =@cm\\:email:\"" + from + "\"";

    ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_FTS_ALFRESCO, query);
    try
    {
        if (resultSet == null || resultSet.length() == 0)
        {
            return null;
        }
        if (resultSet.length() > 1)
        {
            if(logger.isWarnEnabled())
            {
                logger.warn("found more as one result for email '" + from + "'. The first will be used");
            }
        }
        NodeRef userNode = resultSet.getNodeRef(0);
        if (nodeService.exists(userNode))
        {
            userName = DefaultTypeConverter.INSTANCE.convert(
                    String.class,
                    nodeService.getProperty(userNode, ContentModel.PROP_USERNAME));

            if(logger.isDebugEnabled())
            {
                logger.debug("found username: " + userName);
            }
        }
        else
        {
            // The Lucene index returned a dead result
            throw new EmailMessageException(ERR_UNKNOWN_SOURCE_ADDRESS, from);
        }
    }
    finally
    {
        if(resultSet != null)
        {
            resultSet.close();
        }
    }

    return userName;
}
 
Example 8
Source File: FilteringResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public FilteringResultSet(ResultSet unfiltered)
{
    super();
    this.unfiltered = unfiltered;
    inclusionMask = new BitSet(unfiltered.length());
}
 
Example 9
Source File: SiteServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public List<SiteInfo> findSites(String filter, int size)
{
    List<SiteInfo> result;
    
    NodeRef siteRoot = getSiteRoot();
    if (siteRoot == null)
    {
        result = Collections.emptyList();
    }
    else
    {
        // get the sites that match the specified names
        StringBuilder query = new StringBuilder(128);
        query.append("+TYPE:\"").append(SiteModel.TYPE_SITE).append('"');
        
        final boolean filterIsPresent = filter != null && filter.length() > 0;

        if (filterIsPresent)
        {
            query.append(" AND (");
            String escNameFilter = SearchLanguageConversion.escapeLuceneQuery(filter.replace('"', ' '));
            String[] tokenizedFilter = SearchLanguageConversion.tokenizeString(escNameFilter);
            
            //cm:name
            query.append(" cm:name:\" ");
            for( int i = 0; i < tokenizedFilter.length; i++)
            {
              if (i!=0) //Not first element 
              {
                  query.append("?");
              }
              query.append(tokenizedFilter[i].toLowerCase());
            }
            query.append("*\"");
            
            //cm:title
            query.append(" OR ")
                 .append(" cm:title: (");
            for( int i = 0; i < tokenizedFilter.length; i++)
            {
              if (i!=0) //Not first element 
              {
                  query.append(" AND ");
              }
              query.append("\""+tokenizedFilter[i]+"*\" ");
            }
            query.append(")");

            query.append(" OR cm:description:\"" + escNameFilter + "\"");            
            query.append(")");
        }
        
        SearchParameters sp = new SearchParameters();
        sp.addStore(siteRoot.getStoreRef());
        sp.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);
        sp.setQuery(query.toString());
        if (size > 0)
        {
            sp.setLimit(size);
            sp.setLimitBy(LimitBy.FINAL_SIZE);
        }
        
        if(logger.isDebugEnabled())
        {
           logger.debug("Search parameters are: " + sp);
        }
        
        ResultSet results = null;
        try
        {
            results = this.searchService.query(sp);
            result = new ArrayList<SiteInfo>(results.length());
            for (NodeRef site : results.getNodeRefs())
            {
              result.add(createSiteInfo(site));
            }
        }
        catch (LuceneQueryParserException lqpe)
        {
           //Log the error but suppress is from the user
           logger.error("LuceneQueryParserException with findSites()", lqpe);
           result = Collections.emptyList();
        }
        finally
        {
            if (results != null) results.close();
        }
    }
    
    return result;
}
 
Example 10
Source File: SiteServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public List<SiteInfo> findSites(String filter, String sitePresetFilter, int size)
{
    List<SiteInfo> result;
    
    NodeRef siteRoot = getSiteRoot();
    if (siteRoot == null)
    {
        result = Collections.emptyList();
    }
    else
    {
        // get the sites that match the specified names
        StringBuilder query = new StringBuilder(128);
        query.append("+PARENT:\"").append(siteRoot.toString()).append('"');

        final boolean filterIsPresent = filter != null && filter.length() > 0;
        // The filter string is only used in the Lucene query if it restricts results.
        // A search for name/title/description = "*" does not need to be put into the Lucene query.
        // This allows users to search for "*" in the site-finder.
        final boolean filterIsPresentAndNecessary = filterIsPresent && !filter.equals("*");
        final boolean sitePresetFilterIsPresent = sitePresetFilter != null && sitePresetFilter.length() > 0;
        
        if (filterIsPresentAndNecessary || sitePresetFilterIsPresent)
        {
            query.append(" +(");
            if (filterIsPresentAndNecessary)
            {
                String escNameFilter = SearchLanguageConversion.escapeLuceneQuery(filter.replace('"', ' '));
                
                query.append(" @cm\\:name:\"*" + escNameFilter + "*\"")
                     .append(" @cm\\:title:\"" + escNameFilter + "\"")
                     .append(" @cm\\:description:\"" + escNameFilter + "\"");
            }
            if (sitePresetFilterIsPresent)
            {
                String escPresetFilter = SearchLanguageConversion.escapeLuceneQuery(sitePresetFilter.replace('"', ' '));
                query.append(" @st\\:sitePreset:\"" + escPresetFilter + "\"");
            }
            
            query.append(")");
        }
        
        SearchParameters sp = new SearchParameters();
        sp.addStore(siteRoot.getStoreRef());
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(query.toString());
        if (size > 0)
        {
            sp.setLimit(size);
            sp.setLimitBy(LimitBy.FINAL_SIZE);
        }
        ResultSet results = this.searchService.query(sp);
        try
        {
            result = new ArrayList<SiteInfo>(results.length());
            for (NodeRef site : results.getNodeRefs())
            {
                // Ignore any node type that is not a "site"
                QName siteClassName = this.nodeService.getType(site);
                if (this.dictionaryService.isSubClass(siteClassName, SiteModel.TYPE_SITE))
                {
                    result.add(createSiteInfo(site));
                }
            }
        }
        finally
        {
            results.close();
        }
    }
    
    return result;
}
 
Example 11
Source File: SolrSearchService.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public boolean contains(NodeRef nodeRef, QName propertyQName, String googleLikePattern, Operator defaultOperator) throws InvalidNodeRefException
{
    ResultSet resultSet = null;
    try
    {
        // build Lucene search string specific to the node
        StringBuilder sb = new StringBuilder();
        sb.append("+ID:\"").append(nodeRef.toString()).append("\" +(TEXT:(").append(googleLikePattern.toLowerCase()).append(") ");
        if (propertyQName != null)
        {
            sb.append(" OR @").append(SearchLanguageConversion.escapeLuceneQuery(QName.createQName(propertyQName.getNamespaceURI(), ISO9075.encode(propertyQName.getLocalName())).toString()));
            sb.append(":(").append(googleLikePattern.toLowerCase()).append(")");
        }
        else
        {
            for (QName key : nodeService.getProperties(nodeRef).keySet())
            {
                sb.append(" OR @").append(SearchLanguageConversion.escapeLuceneQuery(QName.createQName(key.getNamespaceURI(), ISO9075.encode(key.getLocalName())).toString()));
                sb.append(":(").append(googleLikePattern.toLowerCase()).append(")");
            }
        }
        sb.append(")");

        SearchParameters sp = new SearchParameters();
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(sb.toString());
        sp.setDefaultOperator(defaultOperator);
        sp.addStore(nodeRef.getStoreRef());

        resultSet = this.query(sp);
        boolean answer = resultSet.length() > 0;
        return answer;
    }
    finally
    {
        if (resultSet != null)
        {
            resultSet.close();
        }
    }
}
 
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: BaseSearchResultsMap.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Perform a SearchService query with the given Lucene search string
 */
protected List<TemplateNode> query(String search)
{
    List<TemplateNode> nodes = null;
    HashSet<NodeRef> nodeRefs = new HashSet<NodeRef>();

    // check if a full Lucene search string has been supplied or extracted from XML
    if (search != null && search.length() != 0)
    {
        // perform the search against the repo
        ResultSet results = null;
        try
        {
            results = this.services.getSearchService().query(this.parent.getNodeRef().getStoreRef(),
                    SearchService.LANGUAGE_LUCENE, search);

            if (results.length() != 0)
            {
                NodeService nodeService = this.services.getNodeService();
                
                nodes = new ArrayList<TemplateNode>(results.length());
                for (ResultSetRow row : results)
                {
                    NodeRef nodeRef = row.getNodeRef();
                    if (!nodeRefs.contains(nodeRef) && (nodeService.exists(nodeRef)))
                    {
                        nodes.add(new TemplateNode(nodeRef, services, this.parent.getImageResolver()));
                        nodeRefs.add(nodeRef);
                    }
                }
            }
        }
        catch (Throwable err)
        {
            throw new AlfrescoRuntimeException("Failed to execute search: " + search, err);
        }
        finally
        {
            if (results != null)
            {
                results.close();
            }
        }
    }

    return nodes != null ? nodes : (List) Collections.emptyList();
}
 
Example 14
Source File: MultiTDemoTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void createCategoriesImpl(String tenantDomain)
{
    if (tenantDomain.equals(TenantService.DEFAULT_DOMAIN))
    {
        Collection<ChildAssociationRef> childAssocs = categoryService.getRootCategories(SPACES_STORE, ContentModel.ASPECT_GEN_CLASSIFIABLE);
        
        for (ChildAssociationRef childAssoc : childAssocs)
        {
            if (nodeService.getProperty(childAssoc.getChildRef(), ContentModel.PROP_NAME).equals("CatA"))
            {
                return; // re-runnable, else we need to delete the created categories
            }
        }
    }
    
    // Find all root categories
    String query = "PATH:\"/cm:generalclassifiable/*\"";
    ResultSet resultSet = searchService.query(SPACES_STORE, SearchService.LANGUAGE_LUCENE, query);
    int cnt = resultSet.length();
    
    NodeRef catA = createCategory(SPACES_STORE, null, "CatA", "CatA-"+tenantDomain);
    createCategory(SPACES_STORE, catA, "SubCatA", "SubCatA-"+tenantDomain); // ignore return
    
    NodeRef catB = createCategory(SPACES_STORE, null, "CatB", "CatB-"+tenantDomain);
    createCategory(SPACES_STORE, catB, "SubCatB", "SubCatB-"+tenantDomain); // ignore return
    
    cnt = cnt + 2;
    
    if (tenantDomain.equals(TEST_TENANT_DOMAIN2))
    {
        NodeRef catC = createCategory(SPACES_STORE, null, "CatC", "CatC-"+tenantDomain);
        createCategory(SPACES_STORE, catC, "SubCatC", "SubCatC-"+tenantDomain); // ignore return
        
        cnt = cnt + 1;
    }
    resultSet.close();
    
    // Find all root categories
    resultSet = searchService.query(SPACES_STORE, SearchService.LANGUAGE_LUCENE, query);
    assertEquals(cnt, resultSet.length());
    resultSet.close();
    
    String queryMembers = "PATH:\"/cm:generalclassifiable//cm:catA/member\"";
    resultSet = searchService.query(SPACES_STORE, SearchService.LANGUAGE_LUCENE, queryMembers);
    assertEquals(0, resultSet.length());
    resultSet.close();
    
    NodeRef homeSpaceRef = getHomeSpaceFolderNode(AuthenticationUtil.getRunAsUser());
    NodeRef contentRef = addContent(homeSpaceRef, "tqbfjotld.txt", "The quick brown fox jumps over the lazy dog (tenant " + tenantDomain + ")", MimetypeMap.MIMETYPE_TEXT_PLAIN);
    
    assertFalse(nodeService.hasAspect(contentRef, ContentModel.ASPECT_GEN_CLASSIFIABLE));
    
    List<NodeRef> categories = (List<NodeRef>)nodeService.getProperty(contentRef, ContentModel.PROP_CATEGORIES);
    assertNull(categories);
    
    // Classify the node (ie. assign node to a particular category in a classification)
    categories = new ArrayList<NodeRef>(1);
    categories.add(catA);
    
    HashMap<QName, Serializable> catProps = new HashMap<QName, Serializable>();
    catProps.put(ContentModel.PROP_CATEGORIES, (Serializable)categories);
    nodeService.addAspect(contentRef, ContentModel.ASPECT_GEN_CLASSIFIABLE, catProps);
    
    assertTrue(nodeService.hasAspect(contentRef, ContentModel.ASPECT_GEN_CLASSIFIABLE));
    
    categories = (List<NodeRef>)nodeService.getProperty(contentRef, ContentModel.PROP_CATEGORIES);
    assertEquals(1, categories.size());
    
    // test ETHREEOH-210
    queryMembers = "PATH:\"/cm:generalclassifiable//cm:CatA/member\"";
    resultSet = searchService.query(SPACES_STORE, SearchService.LANGUAGE_LUCENE, queryMembers);
    assertEquals(1, resultSet.length());
    resultSet.close();
}
 
Example 15
Source File: KeywordSearch.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Execute the search
 */
private SearchResult search(String searchTerms, int startPage, int itemsPerPage, Locale locale, WebScriptRequest req)
{
    SearchResult searchResult = null;
    ResultSet results = null;
    
    try
    {
        // construct search statement
        String[] terms = searchTerms.split(" "); 
        searchTerms = searchTerms.replaceAll("\"", "&quot;"); 

        // Escape special characters in the terms, so that they can't confuse the parser 
        for (int i=0; i<terms.length; i++) 
        { 
            terms[i] = SearchLanguageConversion.escapeLuceneQuery(terms[i]); 
        } 

        Map<String, Object> statementModel = new HashMap<String, Object>(7, 1.0f);
        statementModel.put("args", createArgs(req));
        statementModel.put("terms", terms);
        Writer queryWriter = new StringWriter(1024);
        renderFormatTemplate(QUERY_FORMAT, statementModel, queryWriter);
        String query = queryWriter.toString();
        
        // execute query
        if (logger.isDebugEnabled())
        {
            logger.debug("Search parameters: searchTerms=" + searchTerms + ", startPage=" + startPage + ", itemsPerPage=" + itemsPerPage + ", search locale=" + locale.toString());
            logger.debug("Issuing lucene search: " + query);
        }

        SearchParameters parameters = new SearchParameters();
        parameters.addStore(SEARCH_STORE);
        parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
        parameters.setQuery(query);
        if (locale != null)
        {
            parameters.addLocale(locale);
        }
        results = searchService.query(parameters);
        int totalResults = results.length();
        
        if (logger.isDebugEnabled())
            logger.debug("Results: " + totalResults + " rows (limited: " + results.getResultSetMetaData().getLimitedBy() + ")");
        
        // are we out-of-range
        int totalPages = (totalResults / itemsPerPage);
        totalPages += (totalResults % itemsPerPage != 0) ? 1 : 0;
        if (totalPages != 0 && (startPage < 1 || startPage > totalPages))
        {
            throw new WebScriptException("Start page " + startPage + " is outside boundary of " + totalPages + " pages");
        }

        // construct search result
        searchResult = new SearchResult();
        searchResult.setSearchTerms(searchTerms);
        searchResult.setLocale(locale);
        searchResult.setItemsPerPage(itemsPerPage);
        searchResult.setStartPage(startPage);
        searchResult.setTotalResults(totalResults);
        if (totalResults == 0)
        {
            searchResult.setTotalPages(0);
            searchResult.setStartIndex(0);
            searchResult.setTotalPageItems(0);
        }
        else
        {
            searchResult.setTotalPages(totalPages);
            searchResult.setStartIndex(((startPage -1) * itemsPerPage) + 1);
            searchResult.setTotalPageItems(Math.min(itemsPerPage, totalResults - searchResult.getStartIndex() + 1));
        }
        SearchTemplateNode[] nodes = new SearchTemplateNode[searchResult.getTotalPageItems()];
        for (int i = 0; i < searchResult.getTotalPageItems(); i++)
        {
            NodeRef node = results.getNodeRef(i + searchResult.getStartIndex() - 1);
            // Make the search resilient to invalid nodes
            if (!nodeService.exists(node))
            {
                continue;
            }
            float score = results.getScore(i + searchResult.getStartIndex() - 1);
            nodes[i] = new SearchTemplateNode(node, score);
        }
        searchResult.setResults(nodes);
        return searchResult;
    }
    finally
    {
        if (results != null)
        {
            results.close();
        }
    }        
}
 
Example 16
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());
}