org.alfresco.service.cmr.search.LimitBy Java Examples

The following examples show how to use org.alfresco.service.cmr.search.LimitBy. 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: 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 #2
Source File: ResultMapperTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ResultSet mockResultset(List<Long> archivedNodes, List<Long> versionNodes) throws JSONException
{

    NodeService nodeService = mock(NodeService.class);
    when(nodeService.getNodeRef(any())).thenAnswer(new Answer<NodeRef>() {
        @Override
        public NodeRef answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            //If the DBID is in the list archivedNodes, instead of returning a noderef return achivestore noderef
            if (archivedNodes.contains(args[0])) return new NodeRef(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE, GUID.generate());
            if (versionNodes.contains(args[0])) return new NodeRef(StoreMapper.STORE_REF_VERSION2_SPACESSTORE, GUID.generate()+args[0]);
            return new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate());
        }
    });

    SearchParameters sp = new SearchParameters();
    sp.setBulkFetchEnabled(false);
    JSONObject json = new JSONObject(new JSONTokener(JSON_REPONSE));
    ResultSet results = new SolrJSONResultSet(json,sp,nodeService, null, LimitBy.FINAL_SIZE, 10);
    return results;
}
 
Example #3
Source File: SearchMapperTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void facetFormatV2()
{
    Query query = new Query("afts", "a*", "");
    SearchQuery sq = new SearchQuery(query, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null,
                null, null,null, null,FacetFormat.V2);

    SearchRequestContext searchRequestContext = SearchRequestContext.from(sq);
    SearchParameters searchParameters = searchMapper.toSearchParameters(ResultMapperTests.EMPTY_PARAMS, sq, searchRequestContext);
    assertNotNull(searchParameters);

    //Test defaults
    assertEquals("There should be only 1 default store", 1,searchParameters.getStores().size());
    assertEquals("workspaces store is the default", StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, searchParameters.getStores().get(0));
    assertEquals(LimitBy.FINAL_SIZE, searchParameters.getLimitBy());
    assertEquals(100, searchParameters.getLimit());

    
}
 
Example #4
Source File: SearchMapperTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void toSearchParameters() throws Exception
{
    SearchRequestContext searchRequest = SearchRequestContext.from(minimalQuery());
    SearchParameters searchParameters = searchMapper.toSearchParameters(ResultMapperTests.EMPTY_PARAMS, minimalQuery(), searchRequest);
    assertNotNull(searchParameters);

    //Test defaults
    assertEquals("There should be only 1 default store", 1,searchParameters.getStores().size());
    assertEquals("workspaces store is the default", StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, searchParameters.getStores().get(0));
    assertEquals(LimitBy.FINAL_SIZE, searchParameters.getLimitBy());
    assertEquals(100, searchParameters.getLimit());

    searchParameters = searchMapper.toSearchParameters(ResultMapperTests.EMPTY_PARAMS, helper.searchQueryFromJson(), searchRequest);
    assertNotNull(searchParameters);
}
 
Example #5
Source File: SearchMapper.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * SearchParameters from the Limits object
 * @param sp SearchParameters
 * @param paging Paging
 */
public void fromLimits(SearchParameters sp, Limits limits)
{
    if (limits != null)
    {
        if (limits.getPermissionEvaluationCount() != null)
        {
            sp.setLimit(-1);
            sp.setLimitBy(LimitBy.NUMBER_OF_PERMISSION_EVALUATIONS);
            sp.setMaxPermissionChecks(limits.getPermissionEvaluationCount());
        }

        if (limits.getPermissionEvaluationTime() != null)
        {
            sp.setLimit(-1);
            sp.setLimitBy(LimitBy.NUMBER_OF_PERMISSION_EVALUATIONS);
            sp.setMaxPermissionCheckTimeMillis(limits.getPermissionEvaluationTime());
        }
    }
}
 
Example #6
Source File: FilteringResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public boolean hasMore()
{
    if(getResultSetMetaData().getLimitedBy() != LimitBy.UNLIMITED)
    {
        return true;
    }
    else
    {
        try
        {
            return (unfiltered.getStart()+unfiltered.length()) < unfiltered.getNumberFound();
        }
        catch(UnsupportedOperationException uoe)
        {
            return true;
        }
    }
}
 
Example #7
Source File: PagingLuceneResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public boolean hasMore()
{

    if (wrapped.getResultSetMetaData().getLimitedBy() != LimitBy.UNLIMITED)
    {
        return true;
    }
    else
    {
        if (wrapped.length() - getStart() > getLength())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}
 
Example #8
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 #9
Source File: SearchServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testAndyCMIS()
{
    authenticationComponent.setCurrentUser("andy");
    SearchParameters sp = new SearchParameters();
    sp.setLanguage(SearchService.LANGUAGE_CMIS_ALFRESCO);
    sp.setQuery("select * from cmis:folder");
    sp.addStore(rootNodeRef.getStoreRef());
    ResultSet results = pubSearchService.query(sp);
    assertEquals(results.length(), 5);
    assertNotNull(results.getResultSetMetaData());
    assertEquals(results.getResultSetMetaData().getLimitedBy(), LimitBy.UNLIMITED);
    assertEquals(results.getResultSetMetaData().getPermissionEvaluationMode(), PermissionEvaluationMode.EAGER);
    results.close();
}
 
Example #10
Source File: ResultMapperTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ResultSet mockResultset(String json) throws Exception
{
    NodeService nodeService = mock(NodeService.class);
    JSONObject jsonObj = new JSONObject(new JSONTokener(json));
    SearchParameters sp = new SearchParameters();
    sp.setBulkFetchEnabled(false);
    ResultSet results = new SolrJSONResultSet(jsonObj,
                                              sp,
                                              nodeService,
                                              null,
                                              LimitBy.FINAL_SIZE,
                                              10);
    return results;
}
 
Example #11
Source File: ACLEntryAfterInvocationProvider.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the max size from the search parameters.
 * The max size is the maximum number of elements to be returned, It is computed considering various
 * parameters in the searchParameters : maxSize, limitBy and skipCount.
 *
 * @param searchParameters
 * @return
 */
private Integer getMaxSize(SearchParameters searchParameters)
{
    Integer maxSize = null;
    if (searchParameters.getMaxItems() >= 0)
    {
        maxSize = searchParameters.getMaxItems() + searchParameters.getSkipCount();
    }
    else if (searchParameters.getLimitBy() == LimitBy.FINAL_SIZE)
    {
        maxSize = searchParameters.getLimit() + searchParameters.getSkipCount();
    }

    return maxSize;
}
 
Example #12
Source File: SearchMapper.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * SearchParameters from the Paging object
 * @param sp SearchParameters
 * @param paging Paging
 */
public void fromPaging(SearchParameters sp, Paging paging)
{
    if (paging != null)
    {
        sp.setLimitBy(LimitBy.FINAL_SIZE);
        sp.setLimit(paging.getMaxItems());
        sp.setSkipCount(paging.getSkipCount());
    }
}
 
Example #13
Source File: CMISQueryOptions.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static CMISQueryOptions create(SearchParameters searchParameters)
{
    String sql = searchParameters.getQuery();

    CMISQueryOptions options = new CMISQueryOptions(sql, searchParameters.getStores().get(0));
    options.setIncludeInTransactionData(!searchParameters.excludeDataInTheCurrentTransaction());
    options.setDefaultFTSConnective(searchParameters.getDefaultOperator() == SearchParameters.Operator.OR ? Connective.OR : Connective.AND);
    options.setDefaultFTSFieldConnective(searchParameters.getDefaultOperator() == SearchParameters.Operator.OR ? Connective.OR : Connective.AND);
    options.setSkipCount(searchParameters.getSkipCount());
    options.setMaxPermissionChecks(searchParameters.getMaxPermissionChecks());
    options.setMaxPermissionCheckTimeMillis(searchParameters.getMaxPermissionCheckTimeMillis());
    if (searchParameters.getLimitBy() == LimitBy.FINAL_SIZE)
    {
        options.setMaxItems(searchParameters.getLimit());
    }
    else
    {
        options.setMaxItems(searchParameters.getMaxItems());
    }
    options.setMlAnalaysisMode(searchParameters.getMlAnalaysisMode());
    options.setLocales(searchParameters.getLocales());
    options.setStores(searchParameters.getStores());
    options.setUseInMemorySort(searchParameters.getUseInMemorySort());
    options.setMaxRawResultSetSizeForInMemorySort(searchParameters.getMaxRawResultSetSizeForInMemorySort());
    //options.setQuery(); Done on conbstruction
    //options.setQueryMode(); Should set afterwards
    options.setQueryParameterDefinitions(searchParameters.getQueryParameterDefinitions());
    options.setDefaultFieldName(searchParameters.getDefaultFieldName());
    options.setBulkFetchEnabled(searchParameters.isBulkFetchEnabled());
    options.setExcludeTenantFilter(searchParameters.getExcludeTenantFilter());
    options.setSinceTxId(searchParameters.getSinceTxId());
    for(String name : searchParameters.getQueryTemplates().keySet())
    {
    	String template = searchParameters.getQueryTemplates().get(name);
    	options.addQueryTemplate(name, template);
    }
    return options;
}
 
Example #14
Source File: QueryOptions.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static QueryOptions create(SearchParameters searchParameters)
{
    QueryOptions options = new QueryOptions(searchParameters.getQuery(), null);
    options.setIncludeInTransactionData(!searchParameters.excludeDataInTheCurrentTransaction());
    options.setDefaultFTSConnective(searchParameters.getDefaultOperator() == SearchParameters.Operator.OR ? Connective.OR : Connective.AND);
    options.setDefaultFTSFieldConnective(searchParameters.getDefaultOperator() == SearchParameters.Operator.OR ? Connective.OR : Connective.AND);
    options.setSkipCount(searchParameters.getSkipCount());
    options.setMaxPermissionChecks(searchParameters.getMaxPermissionChecks());
    options.setMaxPermissionCheckTimeMillis(searchParameters.getMaxPermissionCheckTimeMillis());
    options.setDefaultFieldName(searchParameters.getDefaultFieldName());
    if (searchParameters.getLimitBy() == LimitBy.FINAL_SIZE)
    {
        options.setMaxItems(searchParameters.getLimit());
    }
    else
    {
        options.setMaxItems(searchParameters.getMaxItems());
    }
    options.setMlAnalaysisMode(searchParameters.getMlAnalaysisMode());
    options.setLocales(searchParameters.getLocales());
    options.setStores(searchParameters.getStores());
    options.setQueryParameterDefinitions(searchParameters.getQueryParameterDefinitions());
    ///options.setQuery(query); Done on construction.
    options.setUseInMemorySort(searchParameters.getUseInMemorySort());
    options.setMaxRawResultSetSizeForInMemorySort(searchParameters.getMaxRawResultSetSizeForInMemorySort());
    options.setBulkFetchEnabled(searchParameters.isBulkFetchEnabled());
    options.setExcludeTenantFilter(searchParameters.getExcludeTenantFilter());
    options.setQueryConsistency(searchParameters.getQueryConsistency());
    options.setSinceTxId(searchParameters.getSinceTxId());
    for(String name : searchParameters.getQueryTemplates().keySet())
    {
    	String template = searchParameters.getQueryTemplates().get(name);
    	options.addQueryTemplate(name, template);
    }
    return options;
}
 
Example #15
Source File: CMISResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public CMISResultSet(Map<String, ResultSet> wrapped, CMISQueryOptions options, LimitBy limitBy,
        NodeService nodeService, Query query, CMISDictionaryService cmisDictionaryService,
        DictionaryService alfrescoDictionaryService)
{
    this.wrapped = wrapped;
    this.options = options;
    this.limitBy = limitBy;
    this.nodeService = nodeService;
    this.query = query;
    this.cmisDictionaryService = cmisDictionaryService;
    this.alfrescoDictionaryService = alfrescoDictionaryService;
    this.nodeInfos = new HashMap<NodeRef, CMISNodeInfo>();
}
 
Example #16
Source File: DBResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public DBResultSet(SearchParameters searchParameters, List<Long> dbids, NodeDAO nodeDao,  NodeService nodeService, TenantService tenantService, int maximumResultsFromUnlimitedQuery)
{
    this.nodeDao = nodeDao;
    this.dbids = dbids;
    this.nodeService = nodeService;
    this.tenantService = tenantService;
    this.prefetch = new BitSet(dbids.size());
    nodeRefs= new NodeRef[(dbids.size())];
    
    final LimitBy limitBy;
    int maxResults = -1;
    if (searchParameters.getMaxItems() >= 0)
    {
        maxResults = searchParameters.getMaxItems();
        limitBy = LimitBy.FINAL_SIZE;
    }
    else if(searchParameters.getLimitBy() == LimitBy.FINAL_SIZE && searchParameters.getLimit() >= 0)
    {
        maxResults = searchParameters.getLimit();
        limitBy = LimitBy.FINAL_SIZE;
    }
    else
    {
        maxResults = searchParameters.getMaxPermissionChecks();
        if (maxResults < 0)
        {
            maxResults = maximumResultsFromUnlimitedQuery;
        }
        limitBy = LimitBy.NUMBER_OF_PERMISSION_EVALUATIONS;
    }
    
    this.resultSetMetaData = new SimpleResultSetMetaData(
            maxResults > 0 && dbids.size() < maxResults ? LimitBy.UNLIMITED : limitBy,
            PermissionEvaluationMode.EAGER, searchParameters);
}
 
Example #17
Source File: SolrSQLJSONResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public SolrSQLJSONResultSet(JSONObject json, SearchParameters searchParameters)
{
    try
    {
        solrResponse = ((JSONObject) json).toString();
        JSONObject res = (JSONObject) json.get("result-set");
        docs = (JSONArray) res.get("docs");
        /*
         * Check that there is no error, which is returned in the first object.
         */
        
        JSONObject obj1 = docs.getJSONObject(0);
        if(obj1.has(SOLR_STREAM_EXCEPTION)) 
        {
            String error =  obj1.get(SOLR_STREAM_EXCEPTION).toString();
            if(error.equalsIgnoreCase("/sql handler only works in Solr Cloud mode"))
            {
                throw new RuntimeException("Unable to execute the query, this API requires InsightEngine.");
            }
            else
            {
                throw new RuntimeException("Unable to execute the query, error caused by: " + error);
            }
        }
        //Check if it has an error
        this.length = docs.length();
        //Last element will contain the object that hold the solr response time.
        JSONObject time = (JSONObject) docs.get(length -1);
        this.numberFound = length - 1;
        queryTime = new Long((Integer) time.get("RESPONSE_TIME"));
        // Were hard coding this as we have a hard limit of 1000 results, any more will not be readable.
        this.resultSetMetaData = new SimpleResultSetMetaData(LimitBy.FINAL_SIZE, 
                PermissionEvaluationMode.EAGER, (SearchParameters)searchParameters);
    } 
    catch (JSONException e)
    {
        logger.info(e.getMessage());
    }
}
 
Example #18
Source File: SimpleResultSetMetaData.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Default properties.
 * 
 * @param limitedBy LimitBy
 * @param permissoinEvaluationMode PermissionEvaluationMode
 * @param searchParameters SearchParameters
 */
public SimpleResultSetMetaData(LimitBy limitedBy, PermissionEvaluationMode permissoinEvaluationMode, SearchParameters searchParameters)
{
    super();
    this.limitedBy = limitedBy;
    this.permissoinEvaluationMode = permissoinEvaluationMode;
    this.searchParameters = searchParameters;
}
 
Example #19
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 #20
Source File: ChildAssocRefResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public ResultSetMetaData getResultSetMetaData()
{
    return new SimpleResultSetMetaData(LimitBy.UNLIMITED, PermissionEvaluationMode.EAGER, new SearchParameters());
}
 
Example #21
Source File: CMISResultSetMetaData.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public LimitBy getLimitedBy()
{
    return limitBy;
}
 
Example #22
Source File: SimpleResultSetMetaData.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public LimitBy getLimitedBy()
{
    return limitedBy;
}
 
Example #23
Source File: EmptyResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public ResultSetMetaData getResultSetMetaData()
{
    return new SimpleResultSetMetaData(LimitBy.UNLIMITED, PermissionEvaluationMode.EAGER, new SearchParameters());
}
 
Example #24
Source File: QueryOptions.java    From alfresco-data-model with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @return SearchParameters
 */
public SearchParameters getAsSearchParmeters()
{
    SearchParameters searchParameters = new SearchParameters();
    searchParameters.setDefaultFieldName(this.getDefaultFieldName());
    searchParameters.setDefaultFTSFieldConnective(this.getDefaultFTSFieldConnective() == Connective.OR ? SearchParameters.Operator.OR : SearchParameters.Operator.AND);
    searchParameters.setDefaultFTSOperator(this.getDefaultFTSConnective() == Connective.OR ? SearchParameters.Operator.OR : SearchParameters.Operator.AND);
    searchParameters.setDefaultOperator(this.getDefaultFTSConnective() == Connective.OR ? SearchParameters.Operator.OR : SearchParameters.Operator.AND);
    searchParameters.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);
    if(this.getMaxItems() > 0)
    {
        searchParameters.setLimit(this.getMaxItems());
        searchParameters.setLimitBy(LimitBy.FINAL_SIZE);
        searchParameters.setMaxItems(this.getMaxItems());
    }
    searchParameters.setMaxPermissionChecks(this.getMaxPermissionChecks());
    searchParameters.setMaxPermissionCheckTimeMillis(this.getMaxPermissionCheckTimeMillis());
    searchParameters.setMlAnalaysisMode(this.getMlAnalaysisMode());
    //searchParameters.setNamespace()   TODO: Fix
    //searchParameters.setPermissionEvaluation()
    searchParameters.setQuery(this.getQuery());
    searchParameters.setSkipCount(this.getSkipCount());
    //searchParameters.addAllAttribute()
    for(Locale locale : this.getLocales())
    {
        searchParameters.addLocale(locale);
    }
    for(QueryParameterDefinition queryParameterDefinition: this.getQueryParameterDefinitions())
    {
        searchParameters.addQueryParameterDefinition(queryParameterDefinition);
    }
    //searchParameters.addQueryTemplate(name, template)
    //searchParameters.addSort()
    for(StoreRef storeRef : this.getStores())
    {
        searchParameters.addStore(storeRef);
    }
    //searchParameters.addTextAttribute()
    searchParameters.setQueryConsistency(this.getQueryConsistency());
    searchParameters.setSinceTxId(getSinceTxId());
    for(String name : getQueryTemplates().keySet())
    {
    	String template = getQueryTemplates().get(name);
    	searchParameters.addQueryTemplate(name, template);
    }
    
    return searchParameters;
}
 
Example #25
Source File: CMISQueryOptions.java    From alfresco-data-model with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @return SearchParameters
 */
public SearchParameters getAsSearchParmeters()
{
    SearchParameters searchParameters = new SearchParameters();
    searchParameters.setDefaultFieldName(this.getDefaultFieldName());
    searchParameters.setDefaultFTSFieldConnective(this.getDefaultFTSFieldConnective() == Connective.OR ? SearchParameters.Operator.OR : SearchParameters.Operator.AND);
    searchParameters.setDefaultFTSOperator(this.getDefaultFTSConnective() == Connective.OR ? SearchParameters.Operator.OR : SearchParameters.Operator.AND);
    searchParameters.setDefaultOperator(this.getDefaultFTSConnective() == Connective.OR ? SearchParameters.Operator.OR : SearchParameters.Operator.AND);
    searchParameters.setLanguage(SearchService.LANGUAGE_CMIS_ALFRESCO);
    if(this.getMaxItems() > 0)
    {
        searchParameters.setLimit(this.getMaxItems());
        searchParameters.setLimitBy(LimitBy.FINAL_SIZE);
        searchParameters.setMaxItems(this.getMaxItems());
    }
    searchParameters.setMaxPermissionChecks(this.getMaxPermissionChecks());
    searchParameters.setMaxPermissionCheckTimeMillis(this.getMaxPermissionCheckTimeMillis());
    searchParameters.setMlAnalaysisMode(this.getMlAnalaysisMode());
    //searchParameters.setNamespace()   TODO: Fix
    //searchParameters.setPermissionEvaluation()
    searchParameters.setQuery(this.getQuery());
    searchParameters.setSkipCount(this.getSkipCount());
    //searchParameters.addAllAttribute()
    for(Locale locale : this.getLocales())
    {
        searchParameters.addLocale(locale);
    }
    for(QueryParameterDefinition queryParameterDefinition: this.getQueryParameterDefinitions())
    {
        searchParameters.addQueryParameterDefinition(queryParameterDefinition);
    }
    //searchParameters.addQueryTemplate(name, template)
    //searchParameters.addSort()
    for(StoreRef storeRef : this.getStores())
    {
        searchParameters.addStore(storeRef);
    }
    //searchParameters.addTextAttribute()
    searchParameters.setBulkFetchEnabled(isBulkFetchEnabled());
    searchParameters.setQueryConsistency(this.getQueryConsistency());
    searchParameters.setSinceTxId(getSinceTxId());
    for(String name : getQueryTemplates().keySet())
    {
    	String template = getQueryTemplates().get(name);
    	searchParameters.addQueryTemplate(name, template);
    }
    return searchParameters;
}
 
Example #26
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 #27
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 #28
Source File: PersonServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private List<NodeRef> getPeopleFtsList(String pattern, PagingRequest pagingRequest) throws Throwable
{
    // Think this code is based on org.alfresco.repo.jscript.People.getPeopleImplSearch(String, StringTokenizer, int, int)
    List<NodeRef> people = null;

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

    StringBuilder query = new StringBuilder(256);

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

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

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

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

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

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

    return people;
}
 
Example #29
Source File: LuceneResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public ResultSetMetaData getResultSetMetaData()
{
    return new SimpleResultSetMetaData(LimitBy.UNLIMITED, PermissionEvaluationMode.EAGER, searchParameters);
}
 
Example #30
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();
        }
    }
}