Java Code Examples for org.alfresco.service.cmr.search.SearchParameters

The following examples show how to use org.alfresco.service.cmr.search.SearchParameters. These examples are extracted from open source projects. 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
/**
 ** SearchParameters from List<FacetQuery>
 * @param sp
 * @param facetQueries
 */
public void fromFacetQuery(SearchParameters sp, List<FacetQuery> facetQueries)
{
    if (facetQueries != null && !facetQueries.isEmpty())
    {
        for (FacetQuery fq:facetQueries)
        {
            ParameterCheck.mandatoryString("facetQuery query", fq.getQuery());
            String query = fq.getQuery();
            String label = fq.getLabel()!=null?fq.getLabel():query;

            if (query.startsWith("{!afts"))
            {
                throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_MESSAGE_ID,
                            new Object[] { ": Facet queries should not start with !afts" });
            }
            query = "{!afts key='"+label+"'}"+query;
            sp.addFacetQuery(query);
        }
    }
}
 
Example 2
/**
 * SearchParameters from SpellCheck object
 * @param sp SearchParameters
 * @param defaults SpellCheck
 */
public void fromSpellCheck(SearchParameters sp, Spelling spelling)
{
    if (spelling != null)
    {
        if (spelling.getQuery() != null && !spelling.getQuery().isEmpty())
        {
            sp.setSearchTerm(spelling.getQuery());
        }
        else
        {
            if (sp.getSearchTerm() == null || sp.getSearchTerm().isEmpty())
            {
                //We don't have a valid search term to use with the spelling
                throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_MESSAGE_ID,
                            new Object[] { ": userQuery or spelling.query required." });
            }
        }
        sp.setSpellCheck(true);
    }
}
 
Example 3
@Override
public Query parse() throws SyntaxError
{
    Pair<SearchParameters, Boolean> searchParametersAndFilter = getSearchParameters();
    SearchParameters searchParameters = searchParametersAndFilter.getFirst();
    Boolean isFilter = searchParametersAndFilter.getSecond();
    
    Solr4QueryParser qp = AlfrescoSolrDataModel.getInstance().getLuceneQueryParser(searchParameters, req, FTSQueryParser.RerankPhase.SINGLE_PASS_WITH_AUTO_PHRASE);
    Query query;
    try
    {
        // escape / not in a string and not already escaped
        String escapedQ = escape(searchParameters.getQuery());
        query = qp.parse(escapedQ);
    }
    catch (ParseException pe)
    {
        throw new SyntaxError(pe);
    }
    ContextAwareQuery contextAwareQuery = new ContextAwareQuery(query, Boolean.TRUE.equals(isFilter) ? null : searchParameters);
    if(log.isDebugEnabled())
    {
        log.debug("Lucene QP query as lucene:\t    "+contextAwareQuery);
    }
    return contextAwareQuery;
}
 
Example 4
/**
 * SearchParameters from the Query object
 * @param sp SearchParameters
 * @param q Query
 */
public void fromQuery(SearchParameters sp, Query q)
{
    ParameterCheck.mandatoryString("query", q.getQuery());
    String lang = q.getLanguage()==null?AFTS:q.getLanguage();

    switch (lang.toLowerCase())
    {
        case AFTS:
            sp.setLanguage(LANGUAGE_FTS_ALFRESCO);
            break;
        case LUCENE:
            sp.setLanguage(LANGUAGE_LUCENE);
            break;
        case CMIS:
            sp.setLanguage(LANGUAGE_CMIS_ALFRESCO);
            break;
        default:
            throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_MESSAGE_ID,
                        new Object[] { ": language allowed values: afts,lucene,cmis" });
    }
    sp.setQuery(q.getQuery());
    sp.setSearchTerm(q.getUserQuery());
}
 
Example 5
@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 6
public Query getCMISQuery(CMISQueryMode mode, Pair<SearchParameters, Boolean> searchParametersAndFilter, SolrQueryRequest req, org.alfresco.repo.search.impl.querymodel.Query queryModelQuery, CmisVersion cmisVersion, String alternativeDictionary) throws ParseException
{
    SearchParameters searchParameters = searchParametersAndFilter.getFirst();
    Boolean isFilter = searchParametersAndFilter.getSecond();

    CmisFunctionEvaluationContext functionContext = getCMISFunctionEvaluationContext(mode, cmisVersion, alternativeDictionary);

    Set<String> selectorGroup = queryModelQuery.getSource().getSelectorGroups(functionContext).get(0);

    LuceneQueryBuilderContext<Query, Sort, ParseException> luceneContext = getLuceneQueryBuilderContext(searchParameters, req, alternativeDictionary, FTSQueryParser.RerankPhase.SINGLE_PASS);
    @SuppressWarnings("unchecked")
    LuceneQueryBuilder<Query, Sort, ParseException> builder = (LuceneQueryBuilder<Query, Sort, ParseException>) queryModelQuery;
    org.apache.lucene.search.Query luceneQuery = builder.buildQuery(selectorGroup, luceneContext, functionContext);

    return new ContextAwareQuery(luceneQuery, Boolean.TRUE.equals(isFilter) ? null : searchParameters);
}
 
Example 7
public Solr4QueryParser getLuceneQueryParser(SearchParameters searchParameters, SolrQueryRequest req, FTSQueryParser.RerankPhase rerankPhase)
{
    Analyzer analyzer =  req.getSchema().getQueryAnalyzer();
    Solr4QueryParser parser = new Solr4QueryParser(req, Version.LATEST, searchParameters.getDefaultFieldName(), analyzer, rerankPhase);
    parser.setNamespacePrefixResolver(namespaceDAO);
    parser.setDictionaryService(getDictionaryService(CMISStrictDictionaryService.DEFAULT));
    parser.setTenantService(tenantService);
    parser.setSearchParameters(searchParameters);
    parser.setAllowLeadingWildcard(true);

    Properties props = new CoreDescriptorDecorator(req.getCore().getCoreDescriptor()).getProperties();
    int topTermSpanRewriteLimit = Integer.parseInt(props.getProperty("alfresco.topTermSpanRewriteLimit", "1000"));
    parser.setTopTermSpanRewriteLimit(topTermSpanRewriteLimit);

    return parser;
}
 
Example 8
/**
 * 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 9
@Override
protected SearchParameters applyDecorations(ActualEnvironment environment, SearchParameters searchParameters,
            VirtualQuery query)
{
    if ((ignoreAspectQNames != null && !ignoreAspectQNames.isEmpty())
                || (ignoreTypeNames != null && !ignoreTypeNames.isEmpty()))
    {

        if (SearchService.LANGUAGE_FTS_ALFRESCO.equals(searchParameters.getLanguage()))
        {
            SearchParameters searchParametersCopy = searchParameters.copy();
            return applyFTSDecorations(searchParametersCopy,
                                       environment.getNamespacePrefixResolver());
        }
        else
        {
            throw new VirtualizationException("Unsupported constrating language " + searchParameters.getLanguage());
        }
    }
    else
    {
        return searchParameters;
    }
}
 
Example 10
private SearchParameters applyFTSDecorations(SearchParameters searchParameters, NamespacePrefixResolver nspResolver)
{
    SearchParameters constrainedParameters = searchParameters.copy();
    String theQuery = constrainedParameters.getQuery();
    theQuery = "(" + theQuery + ")";

    if (ignoreAspectQNames != null)
    {
        for (QName ignoredAspect : ignoreAspectQNames)
        {
            theQuery = theQuery + " and " + "!ASPECT:'" + ignoredAspect.toPrefixString(nspResolver) + "'";
        }
    }

    if (ignoreTypeNames != null)
    {
        for (QName ignoredType : ignoreTypeNames)
        {
            theQuery = theQuery + " and " + "!TYPE:'" + ignoredType.toPrefixString(nspResolver) + "'";
        }
    }

    constrainedParameters.setQuery(theQuery);

    return constrainedParameters;
}
 
Example 11
/**
     * Context for building lucene queries
     *
     * @param dictionaryService
     * @param namespacePrefixResolver
     * @param tenantService
     * @param searchParameters
     * @param defaultSearchMLAnalysisMode
     * @param req
     * @param model
     */
    public Lucene4QueryBuilderContextSolrImpl(DictionaryService dictionaryService, NamespacePrefixResolver namespacePrefixResolver, TenantService tenantService,
            SearchParameters searchParameters, MLAnalysisMode defaultSearchMLAnalysisMode, SolrQueryRequest req, AlfrescoSolrDataModel model, FTSQueryParser.RerankPhase rerankPhase)
    {
          lqp = new Solr4QueryParser(req, Version.LATEST, searchParameters.getDefaultFieldName(), req.getSchema().getQueryAnalyzer(), rerankPhase);
//        lqp.setDefaultOperator(AbstractLuceneQueryParser.OR_OPERATOR);
        lqp.setDictionaryService(dictionaryService);
        lqp.setNamespacePrefixResolver(namespacePrefixResolver);
        lqp.setTenantService(tenantService);
          lqp.setSearchParameters(searchParameters);
//        lqp.setDefaultSearchMLAnalysisMode(defaultSearchMLAnalysisMode);
//        lqp.setIndexReader(indexReader);
//        lqp.setAllowLeadingWildcard(true);
//        this.namespacePrefixResolver = namespacePrefixResolver;
        
          Properties props = new CoreDescriptorDecorator(req.getCore().getCoreDescriptor()).getProperties();
          int topTermSpanRewriteLimit = Integer.parseInt(props.getProperty("alfresco.topTermSpanRewriteLimit", "1000"));
          lqp.setTopTermSpanRewriteLimit(topTermSpanRewriteLimit);
          
          lqpa = new Lucene4QueryParserAdaptor(lqp);
    }
 
Example 12
/**
 * 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 13
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 14
@Test
public void testBuildTimezone() throws UnsupportedEncodingException
{
    SearchParameters params = new SearchParameters();
    params.setTimezone("");
    StringBuilder urlBuilder = new StringBuilder();
    client.buildUrlParameters(params, false, encoder, urlBuilder);
    String url = urlBuilder.toString();
    assertFalse(url.contains("&TZ"));

    params.setTimezone("bob");
    urlBuilder = new StringBuilder();
    client.buildUrlParameters(params, false, encoder, urlBuilder);
    url = urlBuilder.toString();

    //Timezone formats are not validated here so its just passing a string.
    assertTrue(url.contains("&TZ=bob"));;
}
 
Example 15
@Test
public void testSearchQueryParamsFormatNull() throws Exception
{
    String query = "select SITE from alfresco";
    SearchSQLQuery searchQuery = new SearchSQLQuery(query, "", emptyList(), 1000, false, "", emptyList());
    SearchParameters sparams = webscript.buildSearchParameters(searchQuery);
    
    assertNotNull(sparams);
    assertEquals(query, sparams.getQuery());
    assertEquals(false, sparams.isIncludeMetadata());
    assertEquals(Collections.EMPTY_LIST, sparams.getLocales());
    assertEquals(null, sparams.getExtraParameters().get("format"));
    assertEquals(null, sparams.getTimezone());
    
    searchQuery = new SearchSQLQuery(query, null, emptyList(), 1000, true, "", emptyList());
    sparams = webscript.buildSearchParameters(searchQuery);
    
    assertNotNull(sparams);
    assertEquals(query, sparams.getQuery());
    assertEquals(true, sparams.isIncludeMetadata());
    assertEquals(Collections.EMPTY_LIST, sparams.getLocales());
    assertEquals(null, sparams.getExtraParameters().get("format"));
    assertEquals(null, sparams.getTimezone());
}
 
Example 16
@Test
public void testBuildRangeDate() throws UnsupportedEncodingException
{
    TimeZone defaultTimeZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

    SearchParameters params = new SearchParameters();
    params.setSearchTerm("A*");
    List<RangeParameters> ranges = new ArrayList<RangeParameters>();
    ranges.add(new RangeParameters("created", "2015", "2016", "+1MONTH", true, Collections.emptyList(), Collections.emptyList(), null, null));
    params.setRanges(ranges);
    StringBuilder urlBuilder = new StringBuilder();
    client.buildRangeParameters(params, encoder, urlBuilder);
    String url = urlBuilder.toString();
    assertNotNull(url);
    assertTrue(url.contains("&facet=true"));
    assertTrue(url.contains("&facet.range=created"));
    assertTrue(url.contains("&f.created.facet.range.start=2015-01-01T00%3A00%3A00.000Z"));
    assertTrue(url.contains("&f.created.facet.range.end=2016-12-31T23%3A59%3A59.999Z"));
    assertTrue(url.contains("&f.created.facet.range.gap=%2B1MONTH"));

    TimeZone.setDefault(defaultTimeZone);
}
 
Example 17
/**
 * 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 18
public ResultSet query(SearchParameters searchParameters)
{
    if(searchParameters.getStores().size() == 0)
    {
        throw new IllegalStateException("At least one store must be defined to search");
    }
    StoreRef storeRef = searchParameters.getStores().get(0);
    SearchService searcher = indexerAndSearcherFactory.getSearcher(storeRef, !searchParameters.excludeDataInTheCurrentTransaction());
    return searcher.query(searchParameters);
}
 
Example 19
/**
 * Mocks up a SearchService that will return the template NodeRef when
 * queried.
 * 
 * @return SearchService
 */
private SearchService mockSearchService()
{
    SearchService searchService = mock(SearchService.class);
    ResultSet results = mock(ResultSet.class);
    List<NodeRef> nodeRefs = Arrays.asList(template);
    when(results.getNodeRefs()).thenReturn(nodeRefs);
    when(searchService.query((SearchParameters) any())).thenReturn(results);
    when(searchService.selectNodes(any(), any(String.class),
                any(), any(), eq(false)))
                .thenReturn(nodeRefs);
    return searchService;
}
 
Example 20
@Test
public void fromTemplate() throws Exception
{
    SearchParameters searchParameters = new SearchParameters();
    //Doesn't error
    searchMapper.fromTemplate(searchParameters, null);

    searchMapper.fromTemplate(searchParameters, Arrays.asList(new Template("hedge", "hog"), new Template("king", "kong"), new Template("bish", "bash")));
    assertEquals(3 ,searchParameters.getQueryTemplates().size());
    assertEquals("hog" ,searchParameters.getQueryTemplates().get("hedge"));
    assertEquals("kong" ,searchParameters.getQueryTemplates().get("king"));
    assertEquals("bash" ,searchParameters.getQueryTemplates().get("bish"));
}
 
Example 21
@Test
public void fromSpelling() throws Exception
{
    SearchParameters searchParameters = new SearchParameters();
    //Doesn't error
    searchMapper.fromSpellCheck(searchParameters, null);
    assertFalse(searchParameters.isSpellCheck());

    try
    {
        searchMapper.fromSpellCheck(searchParameters, new Spelling(null));
        fail();
    }
    catch (InvalidArgumentException iae)
    {
        //Can't be null
        assertNotNull(iae);
    }

    //Now set search term first
    searchParameters.setSearchTerm("fred");
    searchMapper.fromSpellCheck(searchParameters, new Spelling(null));
    assertEquals("fred",searchParameters.getSearchTerm());

    //Now query replaces userQuery (search term)
    searchMapper.fromSpellCheck(searchParameters, new Spelling("favourit"));
    assertEquals("favourit",searchParameters.getSearchTerm());
    assertTrue(searchParameters.isSpellCheck());
}
 
Example 22
/**
 * 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 23
/**
 * Wrap a lucene seach result with node support
 * 
 * @param hits Hits
 * @param searcher Searcher
 * @param nodeService nodeService
 * @param tenantService tenant service
 * @param searchParameters SearchParameters
 * @param config - lucene config
 */
public LuceneResultSet(Hits hits, Searcher searcher, NodeService nodeService, TenantService tenantService, SearchParameters searchParameters,
        LuceneConfig config)
{
    super();
    this.hits = hits;
    this.searcher = searcher;
    this.nodeService = nodeService;
    this.tenantService = tenantService;
    this.searchParameters = searchParameters;
    this.config = config;
    prefetch = new BitSet(hits.length());
}
 
Example 24
@Override
public void execute(WebScriptRequest webScriptRequest, WebScriptResponse res) throws IOException
{
    try
    {
        //Turn JSON into a Java object representation
        SearchSQLQuery searchQuery = extractJsonContent(webScriptRequest, assistant.getJsonHelper(), SearchSQLQuery.class);
        SearchParameters sparams = buildSearchParameters(searchQuery);

        ResultSet results = searchService.query(sparams);
        FilteringResultSet frs = (FilteringResultSet) results;
        SolrSQLJSONResultSet ssjr = (SolrSQLJSONResultSet) frs.getUnFilteredResultSet();
        //When solr format is requested pass the solr output directly.
        if(searchQuery.getFormat().equalsIgnoreCase("solr"))
        {
            res.getWriter().write(ssjr.getSolrResponse());
        }
        else
        {
            CollectionWithPagingInfo<TupleList> nodes = resultMapper.toCollectionWithPagingInfo(ssjr.getDocs(), searchQuery);
            renderJsonResponse(res, nodes, assistant.getJsonHelper());
        }
        setResponse(res, DEFAULT_SUCCESS);
    }
    catch (Exception exception) 
    {
        if (exception instanceof LuceneQueryParserException)
        {
            renderException(exception,res,assistant);
        }
        else
        {
            renderException(new WebScriptException(400, exception.getMessage()), res, assistant);
        }
    }
}
 
Example 25
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 26
public LuceneQueryBuilderContext<Query, Sort, ParseException> getLuceneQueryBuilderContext(SearchParameters searchParameters, SolrQueryRequest req, String alternativeDictionary, FTSQueryParser.RerankPhase rerankPhase)
{
    return new Lucene4QueryBuilderContextSolrImpl(
            getDictionaryService(alternativeDictionary),
            namespaceDAO,
            tenantService,
            searchParameters,
            MLAnalysisMode.EXACT_LANGUAGE,
            req,
            this,
            rerankPhase);
}
 
Example 27
private void assertPerform2Results()
{
    ArgumentCaptor<SearchParameters> queryCaptor = ArgumentCaptor.forClass(SearchParameters.class);
    Mockito.verify(mockitoActualEnvironment).query(queryCaptor.capture());

    assertEquals("((QUERY_TEST_STRING_QUERY) and TYPE:\"cm:folder\") and !ASPECT:'tst:testQName1' and !TYPE:'tst:testQName2'",
                 queryCaptor.getValue().getQuery());

    ArrayList<SortDefinition> sortDefinitions = queryCaptor.getValue().getSortDefinitions();

    assertNotNull(sortDefinitions);
    assertEquals(0,
                 sortDefinitions.size());
}
 
Example 28
@Before
public void setUp() throws Exception
{
    queryLang = new DbOrIndexSwitchingQueryLanguage();
    queryLang.setDbQueryLanguage(dbQueryLang);
    queryLang.setIndexQueryLanguage(indexQueryLang);
    queryLang.setSolrDao(solrDAO);
    searchParameters = new SearchParameters();
    changedNodes = new ArrayList<>();
    
    // By default, tests will have hybrid enabled.
    queryLang.setHybridEnabled(true);
}
 
Example 29
private ResultSet executeQueryImpl(SearchParameters searchParameters)
    {
        CMISQueryOptions options = CMISQueryOptions.create(searchParameters);
        options.setQueryMode(CMISQueryMode.CMS_WITH_ALFRESCO_EXTENSIONS);

        CapabilityJoin joinSupport = CapabilityJoin.INNERANDOUTER;
        BaseTypeId[] validScopes = CmisFunctionEvaluationContext.ALFRESCO_SCOPES;
        CmisFunctionEvaluationContext functionContext = new CmisFunctionEvaluationContext();
        functionContext.setCmisDictionaryService(cmisDictionaryService);
        functionContext.setValidScopes(validScopes);

        CMISQueryParser parser = new CMISQueryParser(options, cmisDictionaryService, joinSupport);
        org.alfresco.repo.search.impl.querymodel.Query queryModelQuery = parser.parse(new DBQueryModelFactory(), functionContext);

// TODO: Remove as this appears to be dead code
//        // build lucene query
//        Set<String> selectorGroup = null;
//        if (queryModelQuery.getSource() != null)
//        {
//            List<Set<String>> selectorGroups = queryModelQuery.getSource().getSelectorGroups(functionContext);
//            if (selectorGroups.size() == 0)
//            {
//                throw new UnsupportedOperationException("No selectors");
//            }
//            if (selectorGroups.size() > 1)
//            {
//                throw new UnsupportedOperationException("Advanced join is not supported");
//            }
//            selectorGroup = selectorGroups.get(0);
//        }
//
        QueryEngineResults results = queryEngine.executeQuery(queryModelQuery, options, functionContext);
        ResultSet resultSet = results.getResults().values().iterator().next();
        return resultSet;
    }
 
Example 30
private ServiceRegistry mockServiceRegistry()
{

    SearchService searchService = mock(SearchService.class);
    ResultSet results = mock(ResultSet.class);

    List<Pair<String, Integer>> fieldFacets1 = new ArrayList<>();
    fieldFacets1.add(new Pair<>(mimetype1, 1));
    fieldFacets1.add(new Pair<>(mimetype2, 2));

    List<Pair<String, Integer>> fieldFacets2 = new ArrayList<>();
    fieldFacets2.add(new Pair<>(modifier, 1));

    when(results.getFieldFacet(fieldFacet1)).thenReturn(fieldFacets1);
    when(results.getFieldFacet(fieldFacet2)).thenReturn(fieldFacets2);

    when(results.getFacetQueries()).thenReturn(new HashMap<>());
    when(searchService.query((SearchParameters) any())).thenReturn(results);

    FacetLabelDisplayHandlerRegistry displayHandlerRegistry = mock(FacetLabelDisplayHandlerRegistry.class);
    ServiceRegistry services = mock(ServiceRegistry.class);
    when(services.getSearchService()).thenReturn(searchService);
    when(displayHandlerRegistry.getDisplayHandler(fieldFacet1)).thenReturn(new MimetypeOrderDisplayHandler());
    when(displayHandlerRegistry.getDisplayHandler(fieldFacet2)).thenReturn(null);

    SolrFacetHelper solrFacetHelper = mock(SolrFacetHelper.class);
    when(solrFacetHelper.getBucketedFieldFacets()).thenReturn(new HashSet<>());

    when(services.getSolrFacetHelper()).thenReturn(solrFacetHelper);
    when(services.getFacetLabelDisplayHandlerRegistry()).thenReturn(displayHandlerRegistry);
    return services;
}