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

The following are top voted examples for showing how to use org.alfresco.service.cmr.search.ResultSet. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: ACLEntryAfterInvocationProvider.java   View source code 6 votes vote down vote up
private QueryEngineResults decide(Authentication authentication, Object object, ConfigAttributeDefinition config, QueryEngineResults returnedObject)
        throws AccessDeniedException

{
    Map<Set<String>, ResultSet> map = returnedObject.getResults();
    Map<Set<String>, ResultSet> answer = new HashMap<Set<String>, ResultSet>(map.size(), 1.0f);

    for (Set<String> group : map.keySet())
    {
        ResultSet raw = map.get(group);
        ResultSet permed;
        if (PagingLuceneResultSet.class.isAssignableFrom(raw.getClass()))
        {
            permed = decide(authentication, object, config, (PagingLuceneResultSet)raw);
        }
        else
        {
            permed = decide(authentication, object, config, raw);
        }
        answer.put(group, permed);
    }
    return new QueryEngineResults(answer);
}
 
Example 2
Project: alfresco-repository   File: ADMLuceneSearcherImpl.java   View source code 6 votes vote down vote up
public ResultSet query(StoreRef store, QName queryId, QueryParameter[] queryParameters)
{
    CannedQueryDef definition = queryRegister.getQueryDefinition(queryId);

    // Do parameter replacement
    // As lucene phrases are tokensied it is correct to just do straight
    // string replacement.
    // The string will be formatted by the tokeniser.
    //
    // For non phrase queries this is incorrect but string replacement is
    // probably the best we can do.
    // As numbers and text are indexed specially, direct term queries only
    // make sense against textual data

    checkParameters(definition, queryParameters);

    String queryString = parameterise(definition.getQuery(), definition.getQueryParameterMap(), queryParameters, definition.getNamespacePrefixResolver());

    return query(store, definition.getLanguage(), queryString, null);
}
 
Example 3
Project: alfresco-repository   File: LuceneCategoryServiceImpl.java   View source code 6 votes vote down vote up
private Collection<ChildAssociationRef> resultSetToChildAssocCollection(ResultSet resultSet)
{
    List<ChildAssociationRef> collection = new LinkedList<ChildAssociationRef>();
    if (resultSet != null)
    {
        for (ResultSetRow row : resultSet)
        {
            try
            {
                ChildAssociationRef car = nodeService.getPrimaryParent(row.getNodeRef());
                collection.add(car);
            }
            catch(InvalidNodeRefException inre)
            {
                // keep going the node has gone beneath us just skip it
            }
        }
    }
    return collection;
    // The caller closes the result set
}
 
Example 4
Project: alfresco-repository   File: LuceneCategoryServiceImpl.java   View source code 6 votes vote down vote up
public Collection<ChildAssociationRef> getClassifications(StoreRef storeRef)
{
    ResultSet resultSet = null;
    try
    {
        resultSet = indexerAndSearcher.getSearcher(storeRef, false).query(storeRef, "lucene", "PATH:\"//cm:categoryRoot/*\"", null);
        return resultSetToChildAssocCollection(resultSet);
    }
    finally
    {
        if (resultSet != null)
        {
            resultSet.close();
        }
    }
}
 
Example 5
Project: alfresco-repository   File: SolrSearchService.java   View source code 6 votes vote down vote up
@Override
public ResultSet query(StoreRef store, QName queryId, QueryParameter[] queryParameters)
{
    CannedQueryDef definition = queryRegister.getQueryDefinition(queryId);

    // Do parameter replacement
    // As lucene phrases are tokensied it is correct to just do straight
    // string replacement.
    // The string will be formatted by the tokeniser.
    //
    // For non phrase queries this is incorrect but string replacement is
    // probably the best we can do.
    // As numbers and text are indexed specially, direct term queries only
    // make sense against textual data

    checkParameters(definition, queryParameters);

    String queryString = parameterise(definition.getQuery(), definition.getQueryParameterMap(), queryParameters, definition.getNamespacePrefixResolver());

    return query(store, definition.getLanguage(), queryString, null);
}
 
Example 6
Project: tieto-alfresco-repository_monitor   File: MonitorSitesCountAction.java   View source code 6 votes vote down vote up
@Override
protected void executeImpl(NodeRef actionedUponNodeRef) {
	
	final SearchParameters sp = new SearchParameters();
	sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
	sp.setLanguage(SearchService.LANGUAGE_CMIS_ALFRESCO);
	sp.setQuery(QUERY);
	try {
		final ResultSet rs = searchService.query(sp);
		LOGGER.info("Actual number of sites: {}", rs.length());
		final String message = rs.length() < 5000?"Count of sites is OK":"Count of sites exceed recomended limit";
		setOutput(actionedUponNodeRef, new JSONSitesBuilder().setSitesCount(rs.length()).generateOutput());
		updateStatus(actionedUponNodeRef, JobStatus.Status.FINISHED, message);
	} catch (RuntimeException e) {
		updateStatus(actionedUponNodeRef, JobStatus.Status.ERROR, "Error to get number of sites.");
	}
}
 
Example 7
Project: alfresco-repository   File: TaggingServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.tagging.TaggingService#findTaggedNodes(StoreRef, java.lang.String)
 */
public List<NodeRef> findTaggedNodes(StoreRef storeRef, String tag)
{
    // Lower the case of the tag
    tag = tag.toLowerCase();
    ResultSet resultSet= null;
    
    try
    {
        // Do the search for nodes
        resultSet = this.searchService.query(
            storeRef, 
            SearchService.LANGUAGE_LUCENE, 
            "+PATH:\"/cm:taggable/cm:" + ISO9075.encode(tag) + "/member\"");
        List<NodeRef> nodeRefs = resultSet.getNodeRefs();
        return nodeRefs;
    }
    finally
    {
        if(resultSet != null) {resultSet.close();}
    }
}
 
Example 8
Project: alfresco-repository   File: TaggingServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.tagging.TaggingService#findTaggedNodes(StoreRef, java.lang.String, org.alfresco.service.cmr.repository.NodeRef)
 */
public List<NodeRef> findTaggedNodes(StoreRef storeRef, String tag, NodeRef nodeRef)
{
    // Lower the case of the tag
    tag = tag.toLowerCase();
    
    // Get path
    Path nodePath = this.nodeService.getPath(nodeRef);
    String pathString = nodePath.toPrefixString(this.namespaceService);
    ResultSet resultSet = null;
    
    try
    {
        // Do query
        resultSet = this.searchService.query(
            storeRef, 
            SearchService.LANGUAGE_LUCENE, 
            "+PATH:\"" + pathString + "//*\" +PATH:\"/cm:taggable/cm:" + ISO9075.encode(tag) + "/member\"");
        List<NodeRef> nodeRefs = resultSet.getNodeRefs();
        return nodeRefs;
    }
    finally
    {
        if(resultSet != null) {resultSet.close();}
    }
}
 
Example 9
Project: alfresco-repository   File: LockServiceImpl.java   View source code 6 votes vote down vote up
/**
 * Get the locks given a store and query string.
 * 
 * @param storeRef      the store reference
 * @param query         the query string
 * @return              the locked nodes
 * @deprecated Uses search and does not report on ephemeral locks.
 */
@Deprecated
private List<NodeRef> getLocks(StoreRef storeRef, String query)
{
    List<NodeRef> result = new ArrayList<NodeRef>();
    ResultSet resultSet = null;
    try
    {
        resultSet = this.searchService.query(
                storeRef,
                SearchService.LANGUAGE_LUCENE, 
                query);
        result = resultSet.getNodeRefs();
    }
    finally
    {
        if (resultSet != null)
        {
            resultSet.close();
        }
    }
    return result;
}
 
Example 10
Project: alfresco-repository   File: CMISQueryServiceImpl.java   View source code 6 votes vote down vote up
private ResultSet filterNotExistingNodes(ResultSet resultSet)
{
    if (resultSet instanceof PagingLuceneResultSet)
    {
        ResultSet wrapped = ((PagingLuceneResultSet)resultSet).getWrapped();
        
        if (wrapped instanceof FilteringResultSet)
        {
            FilteringResultSet filteringResultSet = (FilteringResultSet)wrapped;
            
            for (int i = 0; i < filteringResultSet.length(); i++)
            {
                NodeRef nodeRef = filteringResultSet.getNodeRef(i);
                /* filter node if it does not exist */
                if (!nodeService.exists(nodeRef))
                {
                    filteringResultSet.setIncluded(i, false);
                }
            }
        }
    }
    
    return resultSet;
}
 
Example 11
Project: alfresco-remote-api   File: ResultMapperTests.java   View source code 6 votes vote down vote up
private ResultSet mockResultset(List<Long> archivedNodes, List<Long> versionNodes) throws JSONException
{

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

    SearchParameters sp = new SearchParameters();
    sp.setBulkFetchEnabled(false);
    JSONObject json = new JSONObject(new JSONTokener(JSON_REPONSE));
    ResultSet results = new SolrJSONResultSet(json,sp,nodeService, null, LimitBy.FINAL_SIZE, 10);
    return results;
}
 
Example 12
Project: alfresco-repository   File: AuditMethodInterceptorTest.java   View source code 6 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(StoreRef, String, String)} to perform a query.
 */
public void testAuditSearchServiceQuery() throws Exception
{
    // Run as admin
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    // Perform a search
    @SuppressWarnings("unused")
    ResultSet rs = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<ResultSet>()
    {
        @Override
        public ResultSet execute() throws Throwable
        {
            return searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_XPATH, "/app:company_home");
        }

    }, true, false);

    // Check the audit entries
    checkAuditEntries(APPLICATION_NAME_MNT_16748, SearchService.LANGUAGE_XPATH, "/app:company_home", 1);
}
 
Example 13
Project: alfresco-repository   File: LockServiceImplTest.java   View source code 6 votes vote down vote up
@Test
@Category(RedundantTests.class)
public void testEphemeralLockIndexing()
{
    TestWithUserUtils.authenticateUser(GOOD_USER_NAME, PWD, rootNodeRef, authenticationService);
    
    IndexerAndSearcher indexerAndSearcher = (IndexerAndSearcher)
                applicationContext.getBean("indexerAndSearcherFactory");
    SearcherComponent searcher = new SearcherComponent();
    searcher.setIndexerAndSearcherFactory(indexerAndSearcher);

    // Create a lock (owned by the current user)
    lockService.lock(noAspectNode, LockType.WRITE_LOCK, 86400, Lifetime.EPHEMERAL);
    
    // Query for the user's locks
    final String query = String.format("[email protected]\\:lockOwner:\"%s\" [email protected]\\:lockType:\"WRITE_LOCK\"", GOOD_USER_NAME);
    ResultSet rs = searcher.query(storeRef, "lucene", query);
    assertTrue(rs.getNodeRefs().contains(noAspectNode));
    
    // Unlock the node
    lockService.unlock(noAspectNode);
    
    // Perform a new search, the index should reflect that it is not locked.
    rs = searcher.query(storeRef, "lucene", query);
    assertFalse(rs.getNodeRefs().contains(noAspectNode));
}
 
Example 14
Project: alfresco-remote-api   File: ResultMapper.java   View source code 6 votes vote down vote up
/**
 * Gets SolrJSONResultSet class if there is one.
 * @param results
 * @return
 */
protected SolrJSONResultSet findSolrResultSet(ResultSet results)
{
    ResultSet theResultSet = results;

    if (results instanceof FilteringResultSet)
    {
        theResultSet = ((FilteringResultSet) results).getUnFilteredResultSet();
    }

    if (theResultSet instanceof SolrJSONResultSet)
    {
        return (SolrJSONResultSet) theResultSet;
    }

    return null;
}
 
Example 15
Project: alfresco-acl-templates   File: AclTemplateServiceImpl.java   View source code 5 votes vote down vote up
private AclTemplate getAclTemplate(String templateId) throws AclTemplateServiceException {

        // Find the JSON file with a name that matches the templateId by querying for the name
        // and the folder where ACL Templates live
        String query = "+PATH:\"" + aclTemplateFolderPath + "/*\" [email protected]\\:name:\"" + templateId + "\"";
        ResultSet results = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_LUCENE, query);
        if (results.length() <= 0) {
            throw new AclTemplateServiceException("ACL template not found: " + templateId);
        }
        NodeRef aclTemplateNodeRef = results.getNodeRef(0);
        logger.debug("Retrieved acl template nodeRef: " + aclTemplateNodeRef.getId());

        // Get the ACL template's content input stream
        ContentReader reader = contentService.getReader(aclTemplateNodeRef, ContentModel.PROP_CONTENT);
        InputStream inputStream = reader.getContentInputStream();

        // Read the JSON from the input stream into the POJO
        AclTemplate template = null;
        try {
            template = mapper.readValue(inputStream, AclTemplate.class);
        } catch (IOException ioe) {
            throw new AclTemplateServiceException("IO exception reading ACL template JSON: " + templateId + "(" + aclTemplateNodeRef.getId() + ")");
        }
        logger.debug("Parsed the acl template JSON");

        return template;
    }
 
Example 16
Project: alfresco-acl-templates   File: AclTemplateServiceImpl.java   View source code 5 votes vote down vote up
public Set<String> getAclTemplates() {
    String query = "+PATH:\"" + aclTemplateFolderPath + "/*\"";
    ResultSet results = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_LUCENE, query);
    Set<String> aclTemplates = new HashSet<>();
    for (int i = 0; i < results.length(); i++) {
        NodeRef nodeRef = results.getNodeRef(i);
        aclTemplates.add((String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME));
    }
    return aclTemplates;
}
 
Example 17
Project: alfresco-remote-api   File: ResultMapperTests.java   View source code 5 votes vote down vote up
@Test
public void testRangeExclusiec() throws Exception
{
    ResultSet results = mockResultset(Collections.emptyList(),Collections.emptyList());
    String updatedJSON = helper.JSON.replace("lower", "upper");
    SearchQuery searchQuery = helper.extractFromJson(updatedJSON);
    SearchRequestContext searchRequest = SearchRequestContext.from(searchQuery);
    SearchParameters searchParams = searchMapper.toSearchParameters(EMPTY_PARAMS, searchQuery, searchRequest);
    SearchContext searchContext = mapper.toSearchContext((SolrJSONResultSet) results, searchRequest, searchQuery, 0);
    
    //Numeric facet range 
    List<GenericFacetResponse> rangeFacets = searchContext.getFacets().stream()
                .filter(f -> f.getType().equals(FACET_TYPE.range)).collect(Collectors.toList());
    assertEquals(2, rangeFacets.size());
    assertEquals(4, rangeFacets.get(0).getBuckets().size());
    assertEquals(3, rangeFacets.get(1).getBuckets().size());
    assertEquals("content.size",rangeFacets.get(1).getLabel());
    assertEquals("(0 - 100]",rangeFacets.get(1).getBuckets().get(0).getLabel());
    Object[] metrics = rangeFacets.get(1).getBuckets().get(0).getMetrics().toArray();
    assertEquals("4",((SimpleMetric) metrics[0]).getValue().get("count"));
    assertEquals("content.size:<\"0\" TO \"100\"]", rangeFacets.get(1).getBuckets().get(0).getFilterQuery());
    assertEquals(null,rangeFacets.get(1).getBuckets().get(0).getBucketInfo().get("count"));
    Map<String, String> facetInfo = rangeFacets.get(1).getBuckets().get(0).getBucketInfo();
    assertEquals("0",facetInfo.get("start"));
    assertEquals("100",facetInfo.get("end"));
    assertEquals("false",facetInfo.get("startInclusive"));
    assertEquals("true",facetInfo.get("endInclusive"));
    
}
 
Example 18
Project: alfresco-repository   File: SearcherComponent.java   View source code 5 votes vote down vote up
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
Project: alfresco-repository   File: AbstractResultSetRow.java   View source code 5 votes vote down vote up
/**
 * The row needs the result set and the index for lookup.
 * 
 * @param resultSet ResultSet
 * @param index int
 */
public AbstractResultSetRow(ResultSet resultSet, int index)
{
    super();
    this.resultSet = resultSet;
    this.index = index;
}
 
Example 20
Project: alfresco-better-trashmanagement   File: AbstractArchivedItemsRetrievalWebScript.java   View source code 5 votes vote down vote up
protected List<Map<String, Object>> processResults(final ResultSet resultSet)
{
    final List<Map<String, Object>> results = new ArrayList<>();
    final Map<String, Map<String, Object>> userObjByUserName = new HashMap<>();

    resultSet.getNodeRefs().forEach((result) -> {
        final Map<String, Object> itemObj = this.buildResultEntry(result, userObjByUserName);
        results.add(itemObj);
    });
    return results;
}
 
Example 21
Project: alfresco-repository   File: ADMLuceneSearcherImpl.java   View source code 5 votes vote down vote up
public ResultSet query(SearchParameters searchParameters)
{
    if (searchParameters.getStores().size() != 1)
    {
        throw new IllegalStateException("Only one store can be searched at present");
    }

    ArrayList<StoreRef> stores = searchParameters.getStores();
    stores.set(0, tenantService.getName(searchParameters.getStores().get(0)));

    String parameterisedQueryString;
    if (searchParameters.getQueryParameterDefinitions().size() > 0)
    {
        Map<QName, QueryParameterDefinition> map = new HashMap<QName, QueryParameterDefinition>();

        for (QueryParameterDefinition qpd : searchParameters.getQueryParameterDefinitions())
        {
            map.put(qpd.getQName(), qpd);
        }

        parameterisedQueryString = parameterise(searchParameters.getQuery(), map, null, namespacePrefixResolver);
    }
    else
    {
        parameterisedQueryString = searchParameters.getQuery();
    }
    // TODO: add another property so the set query is not changed ...
    // May be good to return the query as run ??
    searchParameters.setQuery(parameterisedQueryString);

    LuceneQueryLanguageSPI language = queryLanguages.get(searchParameters.getLanguage().toLowerCase());
    if (language != null)
    {
        return language.executeQuery(searchParameters, this);
    }
    else
    {
        throw new SearcherException("Unknown query language: " + searchParameters.getLanguage());
    }        
}
 
Example 22
Project: alfresco-remote-api   File: ResultMapperTests.java   View source code 5 votes vote down vote up
private ResultSet mockResultset(String json) throws Exception
{
    NodeService nodeService = mock(NodeService.class);
    JSONObject jsonObj = new JSONObject(new JSONTokener(json));
    SearchParameters sp = new SearchParameters();
    sp.setBulkFetchEnabled(false);
    ResultSet results = new SolrJSONResultSet(jsonObj,
                                              sp,
                                              nodeService,
                                              null,
                                              LimitBy.FINAL_SIZE,
                                              10);
    return results;
}
 
Example 23
Project: alfresco-remote-api   File: SearchApiWebscript.java   View source code 5 votes vote down vote up
@Override
public void execute(WebScriptRequest webScriptRequest, WebScriptResponse webScriptResponse) throws IOException
{

    try {
        //Turn JSON into a Java object respresentation
        SearchQuery searchQuery = extractJsonContent(webScriptRequest, assistant.getJsonHelper(), SearchQuery.class);

        //Parse the parameters
        Params params = getParams(webScriptRequest, searchQuery.getFields(), searchQuery.getInclude(), searchQuery.getPaging());

        //Make a copy of the request
        SearchRequestContext searchRequestContext = SearchRequestContext.from(searchQuery);

        //Turn the SearchQuery json into the Java SearchParameters object
        SearchParameters searchParams = searchMapper.toSearchParameters(params, searchQuery, searchRequestContext);

        //Call searchService
        ResultSet results = searchService.query(searchParams);

        //Turn solr results into JSON
        CollectionWithPagingInfo<Node> resultJson = resultMapper.toCollectionWithPagingInfo(params, searchRequestContext, searchQuery, results);
        //Post-process the request and pass in params, eg. params.getFilter()
        Object toRender = helper.processAdditionsToTheResponse(null, null, null, params, resultJson);

        //Write response
        setResponse(webScriptResponse, DEFAULT_SUCCESS);
        renderJsonResponse(webScriptResponse, toRender, assistant.getJsonHelper());

    } catch (Exception exception) {
        renderException(exception,webScriptResponse,assistant);
    }
}
 
Example 24
Project: alfresco-repository   File: AbstractAlfrescoFtsQueryLanguage.java   View source code 5 votes vote down vote up
public ResultSet executeQuery(SearchParameters searchParameters, ADMLuceneSearcherImpl admLuceneSearcher)
{
    String ftsExpression = searchParameters.getQuery();
    QueryModelFactory factory = queryEngine.getQueryModelFactory();
    AlfrescoFunctionEvaluationContext context = new AlfrescoFunctionEvaluationContext(getNamespacePrefixResolver(admLuceneSearcher), getDictionaryService(admLuceneSearcher),
            searchParameters.getNamespace());

    QueryOptions options = QueryOptions.create(searchParameters);

    FTSParser.Mode mode;

    if(options.getDefaultFTSConnective() == Connective.AND)
    {
        mode = FTSParser.Mode.DEFAULT_CONJUNCTION;
    }
    else
    {
        mode = FTSParser.Mode.DEFAULT_DISJUNCTION;
    }
        
    Constraint constraint = FTSQueryParser.buildFTS(ftsExpression, factory, context, null, null, mode, options.getDefaultFTSFieldConnective(),
            searchParameters.getQueryTemplates(), options.getDefaultFieldName(), FTSQueryParser.RerankPhase.SINGLE_PASS);
    org.alfresco.repo.search.impl.querymodel.Query query = factory.createQuery(null, null, constraint, buildOrderings(factory, searchParameters));

    QueryEngineResults results = queryEngine.executeQuery(query, options, context);
    ResultSet resultSet = results.getResults().values().iterator().next();
    return resultSet;
}
 
Example 25
Project: alfresco-remote-api   File: ResultMapperTests.java   View source code 5 votes vote down vote up
@Test
public void testInterval() throws Exception
{
    ResultSet results = mockResultset(Collections.emptyList(),Collections.emptyList());
    SearchQuery searchQuery = helper.searchQueryFromJson();
    SearchRequestContext searchRequest = SearchRequestContext.from(searchQuery);
    SearchParameters searchParams = searchMapper.toSearchParameters(EMPTY_PARAMS, searchQuery, searchRequest);
    SearchContext searchContext = mapper.toSearchContext((SolrJSONResultSet) results, searchRequest, searchQuery, 0);

    //Facet intervals
    List<GenericFacetResponse> intervalFacets = searchContext.getFacets().stream()
                .filter(f -> f.getType().equals(FACET_TYPE.interval)).collect(Collectors.toList());
    assertEquals(2, intervalFacets.size());
    assertEquals("creator",intervalFacets.get(0).getLabel());
    assertEquals("last",intervalFacets.get(0).getBuckets().get(0).getLabel());
    assertEquals("cm:creator:<\"a\" TO \"b\"]",intervalFacets.get(0).getBuckets().get(0).getFilterQuery());

    Object[] metrics = intervalFacets.get(0).getBuckets().get(0).getMetrics().toArray();
    assertEquals(METRIC_TYPE.count,((SimpleMetric) metrics[0]).getType());
    assertEquals("4",((SimpleMetric) metrics[0]).getValue().get("count"));

    metrics = intervalFacets.get(1).getBuckets().get(0).getMetrics().toArray();
    assertEquals("TheCreated",intervalFacets.get(1).getLabel());
    assertEquals("earlier",intervalFacets.get(1).getBuckets().get(0).getLabel());
    assertEquals("cm:created:[\"*\" TO \"2016\">",intervalFacets.get(1).getBuckets().get(0).getFilterQuery());
    assertEquals(METRIC_TYPE.count,((SimpleMetric) metrics[0]).getType());
    assertEquals("5",((SimpleMetric) metrics[0]).getValue().get("count"));

    metrics = intervalFacets.get(1).getBuckets().get(1).getMetrics().toArray();
    assertEquals("lastYear",intervalFacets.get(1).getBuckets().get(1).getLabel());
    assertEquals("cm:created:[\"2016\" TO \"2017\">",intervalFacets.get(1).getBuckets().get(1).getFilterQuery());
    assertEquals(METRIC_TYPE.count,((SimpleMetric) metrics[0]).getType());
    assertEquals("0",((SimpleMetric) metrics[0]).getValue().get("count"));

    metrics = intervalFacets.get(1).getBuckets().get(2).getMetrics().toArray();
    assertEquals("currentYear",intervalFacets.get(1).getBuckets().get(2).getLabel());
    assertEquals("cm:created:[\"NOW/YEAR\" TO \"NOW/YEAR+1YEAR\"]",intervalFacets.get(1).getBuckets().get(2).getFilterQuery());
    assertEquals(METRIC_TYPE.count,((SimpleMetric) metrics[0]).getType());
    assertEquals("854",((SimpleMetric) metrics[0]).getValue().get("count"));
}
 
Example 26
Project: alfresco-repository   File: SolrXPathQueryLanguage.java   View source code 5 votes vote down vote up
@Override
public ResultSet executeQuery(SearchParameters searchParameters, ADMLuceneSearcherImpl admLuceneSearcher)
{
    String query = "PATH:\""+searchParameters.getQuery()+"\"";
    SearchParameters sp = searchParameters.copy();
    sp.setLanguage(SearchService.LANGUAGE_SOLR_FTS_ALFRESCO);
    sp.setQuery(query);
    return solrQueryLanguage.executeQuery(sp, admLuceneSearcher);
}
 
Example 27
Project: alfresco-repository   File: DbCmisQueryLanguage.java   View source code 5 votes vote down vote up
private ResultSet executeQueryImpl(SearchParameters searchParameters, ADMLuceneSearcherImpl admLuceneSearcher)
{
    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);

    // 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 28
Project: alfresco-repository   File: SolrSearchService.java   View source code 5 votes vote down vote up
@Override
public ResultSet query(SearchParameters searchParameters)
{
    if(searchParameters.getStores().size() == 0)
    {
        throw new IllegalStateException("At least one store must be defined to search");
    }
    
    String parameterisedQueryString;
    if (searchParameters.getQueryParameterDefinitions().size() > 0)
    {
        Map<QName, QueryParameterDefinition> map = new HashMap<QName, QueryParameterDefinition>();

        for (QueryParameterDefinition qpd : searchParameters.getQueryParameterDefinitions())
        {
            map.put(qpd.getQName(), qpd);
        }

        parameterisedQueryString = parameterise(searchParameters.getQuery(), map, null, namespacePrefixResolver);
    }
    else
    {
        parameterisedQueryString = searchParameters.getQuery();
    }
    // TODO: add another property so the set query is not changed ...
    // May be good to return the query as run ??
    searchParameters.setQuery(parameterisedQueryString);

    LuceneQueryLanguageSPI language = queryLanguages.get(searchParameters.getLanguage().toLowerCase());
    if (language != null)
    {
        return language.executeQuery(searchParameters, null);
    }
    else
    {
        throw new SearcherException("Unknown query language: " + searchParameters.getLanguage());
    }
}
 
Example 29
Project: alfresco-repository   File: DbAftsQueryLanguage.java   View source code 5 votes vote down vote up
@Override
public ResultSet executeQuery(SearchParameters searchParameters, ADMLuceneSearcherImpl admLuceneSearcher)
{
    if(metadataIndexCheck1.getPatchApplied())
    {
        return super.executeQuery(searchParameters, admLuceneSearcher);
    }
    else
    {
        throw new QueryModelException("The patch to add the indexes to support in-transactional metadata queries has not been applied");
    }
}
 
Example 30
Project: alfresco-repository   File: AbstractResultSetRowIterator.java   View source code 5 votes vote down vote up
/**
 * Create an iterator over the result set. Follows stadard ListIterator
 * conventions
 * 
 * @param resultSet ResultSet
 */
public AbstractResultSetRowIterator(ResultSet resultSet)
{
    super();
    this.resultSet = resultSet;
    this.max = resultSet.length();
}
 
Example 31
Project: alfresco-repository   File: DetachedResultSet.java   View source code 5 votes vote down vote up
/**
 * Detached result set based on that provided
 * @param resultSet ResultSet
 */
public DetachedResultSet(ResultSet resultSet)
{
    super();
    rsmd = resultSet.getResultSetMetaData();
    rows = new ArrayList<ResultSetRow>(resultSet.length());
    for (ResultSetRow row : resultSet)
    {
        rows.add(new DetachedResultSetRow(this, row));
    }
    numberFound = resultSet.getNumberFound();
}
 
Example 32
Project: alfresco-repository   File: DetachedResultSetRow.java   View source code 5 votes vote down vote up
/**
 * Detached result set row
 * @param resultSet ResultSet
 * @param row ResultSetRow
 */
public DetachedResultSetRow(ResultSet resultSet, ResultSetRow row)
{
    super(resultSet, row.getIndex());
    car = row.getChildAssocRef();
    properties = row.getValues();
}
 
Example 33
Project: alfresco-repository   File: HiddenAspect.java   View source code 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 34
Project: alfresco-repository   File: VirtualQueryImpl.java   View source code 5 votes vote down vote up
@Override
public PagingResults<Reference> perform(ActualEnvironment environment, VirtualQueryConstraint constraint,
            PagingRequest pagingRequest, Reference parentReference) throws VirtualizationException
{
    VirtualQueryConstraint theConstraint = constraint;

    if (pagingRequest != null)
    {
        theConstraint = new PagingRequestConstraint(theConstraint,
                                                    pagingRequest);
    }

    SearchParameters searchParameters = theConstraint.apply(environment,
                                                            this);

    ResultSet result = environment.query(searchParameters);

    if (logger.isDebugEnabled())
    {
        logger.debug("Constrained query " + searchParameters + " resulted in " + result.length() + " rows.");
    }

    return asPagingResults(environment,
                           pagingRequest,
                           result,
                           parentReference);
}
 
Example 35
Project: alfresco-repository   File: AbstractReindexComponent.java   View source code 5 votes vote down vote up
/**
 * @return                  Returns true if the given transaction is present in the index
 */
private boolean isTxnIdPresentInIndex(StoreRef storeRef, Transaction txn)
{
    long txnId = txn.getId();
    String changeTxnId = txn.getChangeTxnId();
    // do the most update check, which is most common
    ResultSet results = null;
    try
    {
        SearchParameters sp = new SearchParameters();
        sp.addStore(storeRef);
        // search for it in the index, sorting with youngest first, fetching only 1
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery("TX:" + SearchLanguageConversion.escapeLuceneQuery(changeTxnId));
        sp.setLimit(1);
        
        results = searcher.query(sp);
        
        if (results.length() > 0)
        {
            if (logger.isTraceEnabled())
            {
                logger.trace("Index has results for txn " + txnId + " for store " + storeRef);
            }
            return true;        // there were updates/creates and results for the txn were found
        }
        else
        {
            if (logger.isTraceEnabled())
            {
                logger.trace("Transaction " + txnId + " not in index for store " + storeRef + ".  Possibly out of date.");
            }
            return false;
        }
    }
    finally
    {
        if (results != null) { results.close(); }
    }
}
 
Example 36
Project: alfresco-repository   File: CMISResultSet.java   View source code 5 votes vote down vote up
public CMISResultSet(Map<String, ResultSet> wrapped, CMISQueryOptions options, LimitBy limitBy,
        NodeService nodeService, Query query, CMISDictionaryService cmisDictionaryService,
        DictionaryService alfrescoDictionaryService)
{
    this.wrapped = wrapped;
    this.options = options;
    this.limitBy = limitBy;
    this.nodeService = nodeService;
    this.query = query;
    this.cmisDictionaryService = cmisDictionaryService;
    this.alfrescoDictionaryService = alfrescoDictionaryService;
    this.nodeInfos = new HashMap<NodeRef, CMISNodeInfo>();
}
 
Example 37
Project: alfresco-repository   File: CMISResultSet.java   View source code 5 votes vote down vote up
public void close()
{
    // results sets can be used for more than one selector so we need to
    // keep track of what we have closed
    Set<ResultSet> closed = new HashSet<ResultSet>();
    for (ResultSet resultSet : wrapped.values())
    {
        if (!closed.contains(resultSet))
        {
            resultSet.close();
            closed.add(resultSet);
        }
    }
}
 
Example 38
Project: alfresco-repository   File: CMISResultSet.java   View source code 5 votes vote down vote up
public boolean hasMore()
{
    for (ResultSet resultSet : wrapped.values())
    {
        if (resultSet.hasMore())
        {
            return true;
        }
    }
    return false;
}
 
Example 39
Project: alfresco-repository   File: CMISResultSet.java   View source code 5 votes vote down vote up
private Map<String, NodeRef> getNodeRefs(int i)
{
    HashMap<String, NodeRef> refs = new HashMap<String, NodeRef>();
    for (String selector : wrapped.keySet())
    {
        ResultSet rs = wrapped.get(selector);
        refs.put(selector, rs.getNodeRef(i));
    }
    return refs;
}
 
Example 40
Project: alfresco-repository   File: CMISResultSet.java   View source code 5 votes vote down vote up
private Map<String, Float> getScores(int i)
{
    HashMap<String, Float> scores = new HashMap<String, Float>();
    for (String selector : wrapped.keySet())
    {
        ResultSet rs = wrapped.get(selector);
        scores.put(selector, Float.valueOf(rs.getScore(i)));
    }
    return scores;
}