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

The following examples show how to use org.alfresco.service.cmr.search.SearchParameters#setLanguage() . 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: TaggingServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.tagging.TaggingService#findTaggedNodesAndCountByTagName(StoreRef)
 */
@Override
public List<Pair<String, Integer>> findTaggedNodesAndCountByTagName(StoreRef storeRef)
{
    String queryTaggeble = "ASPECT:\"" + ContentModel.ASPECT_TAGGABLE + "\"" + "-ASPECT:\"" + ContentModel.ASPECT_WORKING_COPY + "\"";
    SearchParameters sp = new SearchParameters();
    sp.setQuery(queryTaggeble);
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.addStore(storeRef);
    sp.addFieldFacet(new FieldFacet("TAG"));

    ResultSet resultSet = null;
    try
    {
        // Do the search for nodes
        resultSet = this.searchService.query(sp);
        return resultSet.getFieldFacet("TAG");
    }
    finally
    {
        if (resultSet != null)
        {
            resultSet.close();
        }
    }
}
 
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: DBQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void queryWithCount(String ql, String query, int count, QName property, Boolean ascending)
{
    SearchParameters sp = new SearchParameters();
    sp.setLanguage(ql);
    sp.setQueryConsistency(QueryConsistency.TRANSACTIONAL);
    sp.setQuery(query);
    sp.addStore(rootNodeRef.getStoreRef());
    ResultSet results = serviceRegistry.getSearchService().query(sp);
    HashSet<NodeRef> found = new HashSet<NodeRef>();
    Comparable last = null;
    for(ResultSetRow row :results)
    {
        assertFalse(found.contains( row.getNodeRef()));
        found.add(row.getNodeRef());
        if(property != null)
        {
            Comparable current = (Comparable)nodeService.getProperty(row.getNodeRef(), property);
            if(last != null)
            {
                if((ascending == null) || (ascending))
                {
                    assert(last.compareTo(current) >= 0);
                }
                else
                {
                    assert(last.compareTo(current) <= 0);
                }
                        
            }
            last = current;
        }
    }
    assertEquals(count, results.length());
    results.getResultSetMetaData();
    results.close();
}
 
Example 4
Source File: AuditMethodInterceptorTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Test for <a href="https://issues.alfresco.com/jira/browse/MNT-16748">MNT-16748</a> <br>
 * Use {@link SearchService#query(SearchParameters)} to perform a query.
 */
public void testAuditSearchServiceSearchParametersQuery() throws Exception
{
    // Run as admin
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    // Create SearchParameters to be used in query
    SearchParameters sp = new SearchParameters();
    sp.setLanguage(SearchService.LANGUAGE_XPATH);
    sp.setQuery("/app:company_home/app:dictionary");
    sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);

    // Perform a search
    @SuppressWarnings("unused")
    ResultSet rs = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<ResultSet>()
    {
        @Override
        public ResultSet execute() throws Throwable
        {
            return searchService.query(sp);
        }

    }, true, false);

    // Check the audit entries
    checkAuditEntries(APPLICATION_NAME_MNT_16748, SearchService.LANGUAGE_XPATH, "/app:company_home/app:dictionary", 1);
}
 
Example 5
Source File: SolrXPathQueryLanguage.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ResultSet executeQuery(SearchParameters searchParameters)
{
    String query = "PATH:\""+searchParameters.getQuery()+"\"";
    SearchParameters sp = searchParameters.copy();
    sp.setLanguage(SearchService.LANGUAGE_SOLR_FTS_ALFRESCO);
    sp.setQuery(query);
    return solrQueryLanguage.executeQuery(sp);
}
 
Example 6
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 7
Source File: HiddenAspect.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ResultSet searchForName(StoreRef storeRef, String name)
{
    SearchParameters sp = new SearchParameters();
    sp.addStore(storeRef);
    sp.setLanguage("lucene");
    sp.setQuery("@" + SearchLanguageConversion.escapeLuceneQuery(ContentModel.PROP_NAME.toString()) + ":\"" + name + "\"");
    sp.addLocale(new Locale("en"));
    return searchService.query(sp);
}
 
Example 8
Source File: VirtualQueryImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private SearchParameters createSearchParameters(boolean files, boolean folders, PagingRequest pagingRequest)
            throws VirtualizationException
{
    SearchParameters searchParameters = new SearchParameters();

    if (store != null)
    {
        searchParameters.addStore(new StoreRef(store));
    }
    else
    {
        searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    }
    searchParameters.setLanguage(language);
    searchParameters.setQuery(filter(language,
                                     query,
                                     files,
                                     folders));
    searchParameters.setQueryConsistency(QueryConsistency.TRANSACTIONAL_IF_POSSIBLE);

    if (pagingRequest != null)
    {
        searchParameters.setSkipCount(pagingRequest.getSkipCount());
        searchParameters.setMaxItems(pagingRequest.getMaxItems());
    }

    return searchParameters;
}
 
Example 9
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());
}
 
Example 10
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 11
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 12
Source File: CronScheduledQueryBasedTemplateActionDefinition.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public List<NodeRef> getNodes()
{
    LinkedList<NodeRef> nodeRefs = new LinkedList<NodeRef>();

    // Build the actual query string
    String queryTemplate = getQueryTemplate();

    // MNT-11598 workaround: de-escape \$\{foo\} or \#\{foo\}
    if (queryTemplate.contains("\\$\\{") || queryTemplate.contains("\\#\\{"))
    {
        queryTemplate = queryTemplate.replace("\\$\\{", "${");
        queryTemplate = queryTemplate.replace("\\#\\{", "#{");

        if (queryTemplate.contains("\\}"))
        {
            queryTemplate = queryTemplate.replace("\\}", "}");
        }
    }

    String query = templateService.processTemplateString(getTemplateActionModelFactory().getTemplateEngine(),
            queryTemplate, getTemplateActionModelFactory().getModel());

    // Execute the query
    SearchParameters sp = new SearchParameters();
    sp.setLanguage(getQueryLanguage());
    sp.setQuery(query);
    for (String storeRef : getStores())
    {
        sp.addStore(new StoreRef(storeRef));
    }

    // Transform the reults into a node list
    ResultSet results = null;
    try
    {
        results = searchService.query(sp);
        for (ResultSetRow row : results)
        {
            nodeRefs.add(row.getNodeRef());
        }
    }
    finally
    {
        if (results != null)
        {
            results.close();
        }
    }
    return nodeRefs;
}
 
Example 13
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 14
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 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: 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 17
Source File: SolrCategoryServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public List<Pair<NodeRef, Integer>> getTopCategories(StoreRef storeRef, QName aspectName, int count)
{
    AspectDefinition definition = dictionaryService.getAspect(aspectName);
    if(definition == null)
    {
        throw new IllegalStateException("Unknown aspect");
    }
    QName catProperty = null;
    Map<QName, PropertyDefinition> properties = definition.getProperties();
    for(QName pName : properties.keySet())
    {
        if(pName.getNamespaceURI().equals(aspectName.getNamespaceURI()))
        {
            if(pName.getLocalName().equalsIgnoreCase(aspectName.getLocalName()))
            {
                PropertyDefinition def = properties.get(pName);
                if(def.getDataType().getName().equals(DataTypeDefinition.CATEGORY))
                {
                    catProperty = pName;
                }
            }
        }
    }
    if(catProperty == null)
    {
        throw new IllegalStateException("Aspect does not have category property mirroring the aspect name");
    }
    
    String field = "@" + catProperty;
    
    SearchParameters sp = new SearchParameters();
    sp.setLanguage(SearchService.LANGUAGE_SOLR_FTS_ALFRESCO);
    sp.addStore(storeRef);
    sp.setQuery(catProperty+":*");
    FieldFacet ff = new FieldFacet(field);
    ff.setLimitOrNull(count);
    sp.addFieldFacet(ff);
    
    ResultSet resultSet = null;
    try
    {
        resultSet = indexerAndSearcher.getSearcher(storeRef, false).query(sp);
        List<Pair<String, Integer>> facetCounts = resultSet.getFieldFacet(field);
        List<Pair<NodeRef, Integer>> answer = new LinkedList<Pair<NodeRef, Integer>>();
        for (Pair<String, Integer> term : facetCounts)
        {
            Pair<NodeRef, Integer> toAdd;
            NodeRef nodeRef = new NodeRef(term.getFirst());
            if (nodeService.exists(nodeRef))
            {
                toAdd = new Pair<NodeRef, Integer>(nodeRef, term.getSecond());
            }
            else
            {
                toAdd = new Pair<NodeRef, Integer>(null, term.getSecond());
            }
            answer.add(toAdd);
        }
        return answer;
    }
    finally
    {
        if (resultSet != null)
        {
            resultSet.close();
        }
    }
    
}
 
Example 18
Source File: QueriesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
public CollectionWithPagingInfo<T> find(Parameters parameters,
    String termName, int minTermLength, String queryTemplateName,
    Sort sort, Map<String, QName> sortParamsToQNames, SortColumn... defaultSort)
{
    SearchParameters sp = new SearchParameters();
    sp.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);
    sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    sp.setDefaultFieldName(queryTemplateName);
    
    String term = getTerm(parameters, termName, minTermLength);

    StringBuilder query = new StringBuilder();
    buildQuery(query, term, sp, queryTemplateName);
    sp.setQuery(query.toString());

    Paging paging = parameters.getPaging();
    PagingRequest pagingRequest = Util.getPagingRequest(paging);
    
    List<SortColumn> defaultSortCols = (defaultSort != null ? Arrays.asList(defaultSort) : Collections.emptyList());
    if (sort == IN_QUERY_SORT)
    {
        addSortOrder(parameters, sortParamsToQNames, defaultSortCols, sp);

        sp.setSkipCount(pagingRequest.getSkipCount());
        sp.setMaxItems(pagingRequest.getMaxItems());
    }
    
    ResultSet queryResults = null;
    List<T> collection = null;
    try
    {
        queryResults = searchService.query(sp);
        
        List<NodeRef> nodeRefs = queryResults.getNodeRefs();
        
        if (sort == POST_QUERY_SORT)
        {
            nodeRefs = postQuerySort(parameters, sortParamsToQNames, defaultSortCols, nodeRefs);
        }
        
        collection = newList(nodeRefs.size());
        List<String> includeParam = parameters.getInclude();

        for (NodeRef nodeRef : nodeRefs)
        {
            T t = convert(nodeRef, includeParam);
            collection.add(t);
        }

        if (sort == POST_QUERY_SORT)
        {
            return listPage(collection, paging);
        }
        else
        {
            return CollectionWithPagingInfo.asPaged(paging, collection, queryResults.hasMore(), Long.valueOf(queryResults.getNumberFound()).intValue());
        }
    }
    finally
    {
        if (queryResults != null)
        {
            queryResults.close();
        }
    }
}
 
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: 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;
}