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

The following examples show how to use org.alfresco.service.cmr.search.SearchParameters#setQuery() . 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: BasicConstraint.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public SearchParameters apply(ActualEnvironment environment, VirtualQuery query) throws VirtualizationException
{
    SearchParameters searchParameters = new SearchParameters();

    String storeRefString = query.getStoreRef();
    if (storeRefString != null)
    {
        searchParameters.addStore(new StoreRef(storeRefString));
    }
    else
    {
        searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    }

    searchParameters.setLanguage(query.getLanguage());
    searchParameters.setQuery(query.getQueryString());
    searchParameters.setQueryConsistency(QueryConsistency.TRANSACTIONAL_IF_POSSIBLE);

    return searchParameters;
}
 
Example 2
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 3
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 4
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 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: AuthQueryIT.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Queries the index and asserts if the count matches documents returned.
 * @param queryString
 * @param count
 * @throws IOException
 * @throws org.apache.lucene.queryparser.classic.ParseException
 */
private void assertFTSQuery(String queryString,
                          int count,
                          String... name) throws IOException, ParseException
{
    SolrServletRequest solrQueryRequest = null;
    RefCounted<SolrIndexSearcher>refCounted = null;
    try
    {
        solrQueryRequest = new SolrServletRequest(getCore(), null);
        refCounted = getCore().getSearcher(false, true, null);
        SolrIndexSearcher solrIndexSearcher = refCounted.get();
        
        SearchParameters searchParameters = new SearchParameters();
        searchParameters.setQuery(queryString);
        Query query = dataModel.getFTSQuery(new Pair<SearchParameters, Boolean>(searchParameters, Boolean.FALSE),
                solrQueryRequest, FTSQueryParser.RerankPhase.SINGLE_PASS);
        TopDocs docs = solrIndexSearcher.search(query, count * 2 + 10);
    
        Assert.assertEquals(count, docs.totalHits);
    } 
    finally
    {
        refCounted.decref();
        solrQueryRequest.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: SearchSQLApiWebscript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public SearchParameters buildSearchParameters(SearchSQLQuery searchQuery)
{
    SearchParameters sparams = new SearchParameters();
    sparams.setLanguage(SearchService.LANGUAGE_SOLR_SQL);
    sparams.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    if(StringUtils.isEmpty(searchQuery.getStmt()))
    {
        throw new AlfrescoRuntimeException("Required stmt parameter is missing.");
    }
    if(searchQuery.getFormat().equalsIgnoreCase("solr"))
    {
        sparams.addExtraParameter("format", "solr");
    }
    if(!StringUtils.isEmpty(searchQuery.getTimezone()))
    {
        sparams.setTimezone(searchQuery.getTimezone());
    }
    sparams.setQuery(searchQuery.getStmt());
    searchQuery.getLocales().forEach(action->{
        Locale locale = new Locale(action);
        sparams.addLocale(locale);
    });
    searchQuery.getFilterQueries().forEach(sparams::addFilterQuery);
    
    sparams.setIncludeMetadata(searchQuery.isIncludeMetadata());
    return sparams;
}
 
Example 9
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 10
Source File: NamePatternPropertyValueConstraint.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected SearchParameters applyFTS(SearchParameters searchParameters)
{
    String filePattern;
    StringBuffer luceneReserved = new StringBuffer();
    for(int i=0;i<value.toString().length();i++){
        if(SearchLanguageConversion.DEF_LUCENE.isReserved(value.toString().charAt(i))){
            luceneReserved.append(value.toString().charAt(i));
        }
    }
    String luceneReservedStr=luceneReserved.toString();
    String pattern =org.alfresco.util.ISO9075.encode(value.toString());
    for (int i = 0; i < luceneReservedStr.length(); i++)
    {
        pattern = pattern.replace(org.alfresco.util.ISO9075.encode(luceneReservedStr.substring(i,i + 1)),
                                  luceneReservedStr.substring(i,i + 1));
    }
    filePattern=SearchLanguageConversion.escapeForLucene(pattern);

    SearchParameters constrainedParameters = searchParameters.copy();
    String theQuery = constrainedParameters.getQuery();

    StringBuilder sb = new StringBuilder();
    sb.append("(" + theQuery + ")");
    sb.append(" and (");
    sb.append("TEXT:(").append(filePattern).append(") ");
    sb.append("or (");
    sb.append(" =").append(property.toPrefixString(this.nspResolver));
    sb.append(":").append(filePattern);
    sb.append(" ) ");
    sb.append(")");
    theQuery = sb.toString();
    constrainedParameters.setQuery(theQuery);

    return constrainedParameters;
}
 
Example 11
Source File: FilesFoldersConstraint.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected SearchParameters applyDecorations(ActualEnvironment environment, SearchParameters searchParameters,
            VirtualQuery query)
{
    String queryString = searchParameters.getQuery();
    String language = searchParameters.getLanguage();
    String filteredQuery = filter(language,
                                  queryString,
                                  files,
                                  folders);
    SearchParameters searchParametersCopy = searchParameters.copy();
    searchParametersCopy.setQuery(filteredQuery);
    return searchParametersCopy;
}
 
Example 12
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 13
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 14
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 15
Source File: QuickShareServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Pair<String, NodeRef> getTenantNodeRefFromSharedId(final String sharedId)
{
    NodeRef nodeRef = TenantUtil.runAsDefaultTenant(new TenantRunAsWork<NodeRef>()
    {
        public NodeRef doWork() throws Exception
        {
            return (NodeRef) attributeService.getAttribute(ATTR_KEY_SHAREDIDS_ROOT, sharedId);
        }
    });

    if (nodeRef == null)
    {
        /* TODO
         * Temporary fix for RA-1093 and MNT-16224. The extra lookup should be
         * removed (the same as before, just throw the 'InvalidSharedIdException' exception) when we
         * have a system wide patch to remove the 'shared' aspect of the nodes that have been archived while shared.
         */
        // TMDQ
        final String query = "+TYPE:\"cm:content\" AND +ASPECT:\"qshare:shared\" AND =qshare:sharedId:\"" + sharedId + "\"";
        SearchParameters sp = new SearchParameters();
        sp.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);
        sp.setQuery(query);
        sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);

        List<NodeRef> nodeRefs = null;
        ResultSet results = null;
        try
        {
            results = searchService.query(sp);
            nodeRefs = results.getNodeRefs();
        }
        catch (Exception ex)
        {
            throw new InvalidSharedIdException(sharedId);
        }
        finally
        {
            if (results != null)
            {
                results.close();
            }
        }
        if (nodeRefs.size() != 1)
        {
            throw new InvalidSharedIdException(sharedId);
        }
        nodeRef = tenantService.getName(nodeRefs.get(0));
    }

    // note: relies on tenant-specific (ie. mangled) nodeRef
    String tenantDomain = tenantService.getDomain(nodeRef.getStoreRef().getIdentifier());
    return new Pair<>(tenantDomain, tenantService.getBaseName(nodeRef));
}
 
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: 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 18
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 19
Source File: ApplyTemplateMethodTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Category(RedundantTests.class)
@Test
public void testExecute_vanillaISO9075ActualPath() throws Exception
{
    ChildAssociationRef iso9075FolderAssoc = createFolder(testRootFolder.getNodeRef(),
                                                          "Acutal ISO9075 Node");
    NodeRef iso9075Folder = iso9075FolderAssoc.getChildRef();

    NewVirtualReferenceMethod newVirtualReferenceMethod = new NewVirtualReferenceMethod(TEST_TEMPLATE_5_JSON_SYS_PATH,
                                                                                        "/",
                                                                                        iso9075Folder,
                                                                                        VANILLA_PROCESSOR_JS_CLASSPATH);

    ApplyTemplateMethod applyTemplateMethod = new ApplyTemplateMethod(environment);

    Reference ref = Protocols.VANILLA.protocol.dispatch(newVirtualReferenceMethod,
                                                        null);
    VirtualFolderDefinition structure = ref.execute(applyTemplateMethod);

    VirtualFolderDefinition sfp5 = structure.findChildByName("SpecialFilingPath5");
    VirtualQuery query = sfp5.getQuery();

    assertEquals("(PATH:'/app:company_home/cm:TestFolder/cm:Acutal_x0020_ISO9075_x0020_Node/cm:Space_x0020_Sub_x0020_Folder/*')  and =cm:description:'SpecialFilingPath_5'",
                 query.getQueryString());

    ChildAssociationRef iso9075SubFolderAssoc = createFolder(iso9075Folder,
                                                             "Space Sub Folder");

    ChildAssociationRef someContentAssoc = createContent(iso9075SubFolderAssoc.getChildRef(),
                                                         "someContent");

    nodeService.setProperty(someContentAssoc.getChildRef(),
                            ContentModel.PROP_DESCRIPTION,
                            "SpecialFilingPath_5");

    // check query for validity
    SearchParameters searchParameters = new SearchParameters();
    
    searchParameters.setQuery(query.getQueryString());
    searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    searchParameters.setLanguage(query.getLanguage());
    
    /* Code commented out as part of REPO-2028
     * If this test needs to be reactivated, please refactor this to use the prepareMocks/resetMocks methods
     */ 
    // ResultSet qresult = searchService.query(searchParameters);
    // assertEquals(1, qresult.getNumberFound());

}
 
Example 20
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();
        }
    }
}