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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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;
}
 
Example 41
Project: alfresco-repository   File: CMISResultSet.java   Source Code and License 5 votes vote down vote up
@Override
public long getNumberFound()
{
    for (ResultSet resultSet : wrapped.values())
    {
        return resultSet.getNumberFound();
    }
    throw new IllegalStateException();
}
 
Example 42
Project: alfresco-repository   File: DBQueryTest.java   Source Code and License 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 43
Project: alfresco-repository   File: InviteSenderTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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(NodeRef.class), any(String.class),
                any(QueryParameterDefinition[].class), any(NamespacePrefixResolver.class), eq(false)))
                .thenReturn(nodeRefs);
    return searchService;
}
 
Example 44
Project: alfresco-repository   File: InviteModeratedSenderTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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(emailTemplateNodeRef);
    when(results.getNodeRefs()).thenReturn(nodeRefs);
    when(searchService.query((SearchParameters) any())).thenReturn(results);
    when(searchService.selectNodes(any(NodeRef.class), any(String.class),
                any(QueryParameterDefinition[].class), any(NamespacePrefixResolver.class), eq(false)))
                .thenReturn(nodeRefs);
    return searchService;
}
 
Example 45
Project: alfresco-remote-api   File: ResultMapper.java   Source Code and License 5 votes vote down vote up
/**
 * Sets the total number found.
 * @param results
 * @return An integer total
 */
public Integer setTotal(ResultSet results)
{
    Long totalItems = results.getNumberFound();
    Integer total = totalItems.intValue();
    return total;
}
 
Example 46
Project: alfresco-repository   File: MultiTDemoTest.java   Source Code and License 5 votes vote down vote up
private int searchForDataDictionary(String tenantAdminName, final String query)
{
    return AuthenticationUtil.runAs(new RunAsWork<Integer>()
    {
        public Integer doWork() throws Exception
        {
            ResultSet resultSet = searchService.query(SPACES_STORE, SearchService.LANGUAGE_LUCENE, query, null);
            return resultSet.length();
        }
    }, tenantAdminName);
}
 
Example 47
Project: alfresco-repository   File: ConcurrentNodeServiceSearchTest.java   Source Code and License 5 votes vote down vote up
public void testConcurrent() throws Exception
{
    int count = 10;
    int repeats = 10;

    SearchService searcher = (SearchService) ctx.getBean(ServiceRegistry.SEARCH_SERVICE.getLocalName());

    Map<QName, ChildAssociationRef> assocRefs = commitNodeGraph();
    Thread runner = null;

    for (int i = 0; i < count; i++)
    {
        runner = new Nester("Concurrent-" + i, runner, repeats, searcher);
    }
    if (runner != null)
    {
        runner.start();

        try
        {
            runner.join();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    assertEquals(2, searcher.selectNodes(rootNodeRef, "/*", null,
            getNamespacePrefixReolsver(""), false).size());
    ResultSet results = searcher.query(rootNodeRef.getStoreRef(), "lucene", "PATH:\"/*\"");
    // n6 has root aspect - there are three things at the root level in the
    // index
    assertEquals(3, results.length());
    results.close();
}
 
Example 48
Project: alfresco-repository   File: CronScheduledQueryBasedTemplateActionDefinitionTest.java   Source Code and License 5 votes vote down vote up
/**
 * Check the nodes to be indexed
 * 
 * @param nodes
 * @throws Exception
 */
private void checkNodes(List<FileInfo> nodes) throws Exception
{
    SearchService searchService = registry.getSearchService();
    
    boolean notFound = false;
    for (int i = 1; i <= 40; i++)
    {
        notFound = false;
        for (FileInfo fileInfo : nodes)
        {
            ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, "PATH:\"/app:company_home//cm:" + TEST_FOLDER_NAME + "//cm:" + fileInfo.getName() + "\"");
            if (resultSet.length() == 0)
            {
                notFound = true;
                break;
            }
        }
        if (notFound)
        {
            Thread.sleep(500);
        }
        else
        {
            break;
        }
    }
    assertFalse("The content was not created or indexed correctly.", notFound);
}
 
Example 49
Project: alfresco-expirable-content   File: DeleteExpiredContent.java   Source Code and License 5 votes vote down vote up
@Override
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {
    List<ReportData> reportDataList = new ArrayList<ReportData>();
    ResultSet expiredDocs = getExpiredContent();
    for (int i = 0; i < expiredDocs.length(); i++) {
        NodeRef expiredDoc = expiredDocs.getNodeRef(i);

        if (nodeService.exists(expiredDoc)) {
            ReportData reportData = new ReportData();
            reportData.setName((String) nodeService.getProperty(expiredDoc, ContentModel.PROP_NAME));
            String nodeRefStr = expiredDoc.toString();
            reportData.setNodeRef(nodeRefStr);
            reportData.setExpirationDate((Date) nodeService.getProperty(expiredDoc, ExpirableContentModel.PROP_EXPIRATION_DATE));
            reportData.setPath(nodeService.getPath(expiredDoc).toString());

            try {
                nodeService.deleteNode(expiredDoc);
            } catch (InvalidNodeRefException inre) {
                LOG.warn("Tried to delete an invalid node, skipping: " + nodeRefStr);
                continue;
            }

            reportDataList.add(reportData);
        }
    }
    if (reportDataList.size() > 0) {
        LOG.info("Delete expired content action deleted: " + reportDataList.size() + " documents.");
        reportWriter.save(reportDataList);
    } else {
        LOG.info("Delete expired content action found nothing to delete.");
    }
}
 
Example 50
Project: alfresco-repository   File: EmailServiceImpl.java   Source Code and License 4 votes vote down vote up
/**
 * Authenticate in Alfresco repository by sender's e-mail address.
 * 
 * @param from Sender's email address
 * @return User name or null if the user does not exist.
 * @throws EmailMessageException Exception will be thrown if authentication is failed.
 */
private String getUsername(String from)
{
    String userName = null;
    
    if(from == null || from.length()==0)
    {
        return null;
    }
    
    if(logger.isDebugEnabled())
    {
        logger.debug("getUsername from: " + from);
    }
    
    
    StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
    String query = "TYPE:cm\\:person AND [email protected]\\:email:\"" + from + "\"";

    ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_FTS_ALFRESCO, query);
    try
    {
        if (resultSet == null || resultSet.length() == 0)
        {
            return null;
        }
        if (resultSet.length() > 1)
        {
            if(logger.isWarnEnabled())
            {
                logger.warn("found more as one result for email '" + from + "'. The first will be used");
            }
        }
        NodeRef userNode = resultSet.getNodeRef(0);
        if (nodeService.exists(userNode))
        {
            userName = DefaultTypeConverter.INSTANCE.convert(
                    String.class,
                    nodeService.getProperty(userNode, ContentModel.PROP_USERNAME));

            if(logger.isDebugEnabled())
            {
                logger.debug("found username: " + userName);
            }
        }
        else
        {
            // The Lucene index returned a dead result
            throw new EmailMessageException(ERR_UNKNOWN_SOURCE_ADDRESS, from);
        }
    }
    finally
    {
        if(resultSet != null)
        {
            resultSet.close();
        }
    }

    return userName;
}
 
Example 51
Project: alfresco-repository   File: FilteringResultSet.java   Source Code and License 4 votes vote down vote up
public FilteringResultSet(ResultSet unfiltered)
{
    super();
    this.unfiltered = unfiltered;
    inclusionMask = new BitSet(unfiltered.length());
}
 
Example 52
Project: alfresco-repository   File: FilteringResultSet.java   Source Code and License 4 votes vote down vote up
public FilteringResultSet(ResultSet unfiltered, BitSet inclusionMask)
{
    super();
    this.unfiltered = unfiltered;
    this.inclusionMask = inclusionMask;
}
 
Example 53
Project: alfresco-repository   File: FilteringResultSet.java   Source Code and License 4 votes vote down vote up
public ResultSet getUnFilteredResultSet()
{
    return unfiltered;
}
 
Example 54
Project: alfresco-repository   File: FilteringResultSet.java   Source Code and License 4 votes vote down vote up
public ResultSet getResultSet()
{
    return FilteringResultSet.this;
}
 
Example 55
Project: alfresco-repository   File: SiteServiceImpl.java   Source Code and License 4 votes vote down vote up
@Override
public List<SiteInfo> findSites(String filter, String sitePresetFilter, int size)
{
    List<SiteInfo> result;
    
    NodeRef siteRoot = getSiteRoot();
    if (siteRoot == null)
    {
        result = Collections.emptyList();
    }
    else
    {
        // get the sites that match the specified names
        StringBuilder query = new StringBuilder(128);
        query.append("+PARENT:\"").append(siteRoot.toString()).append('"');

        final boolean filterIsPresent = filter != null && filter.length() > 0;
        // The filter string is only used in the Lucene query if it restricts results.
        // A search for name/title/description = "*" does not need to be put into the Lucene query.
        // This allows users to search for "*" in the site-finder.
        final boolean filterIsPresentAndNecessary = filterIsPresent && !filter.equals("*");
        final boolean sitePresetFilterIsPresent = sitePresetFilter != null && sitePresetFilter.length() > 0;
        
        if (filterIsPresentAndNecessary || sitePresetFilterIsPresent)
        {
            query.append(" +(");
            if (filterIsPresentAndNecessary)
            {
                String escNameFilter = SearchLanguageConversion.escapeLuceneQuery(filter.replace('"', ' '));
                
                query.append(" @cm\\:name:\"*" + escNameFilter + "*\"")
                     .append(" @cm\\:title:\"" + escNameFilter + "\"")
                     .append(" @cm\\:description:\"" + escNameFilter + "\"");
            }
            if (sitePresetFilterIsPresent)
            {
                String escPresetFilter = SearchLanguageConversion.escapeLuceneQuery(sitePresetFilter.replace('"', ' '));
                query.append(" @st\\:sitePreset:\"" + escPresetFilter + "\"");
            }
            
            query.append(")");
        }
        
        SearchParameters sp = new SearchParameters();
        sp.addStore(siteRoot.getStoreRef());
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(query.toString());
        if (size > 0)
        {
            sp.setLimit(size);
            sp.setLimitBy(LimitBy.FINAL_SIZE);
        }
        ResultSet results = this.searchService.query(sp);
        try
        {
            result = new ArrayList<SiteInfo>(results.length());
            for (NodeRef site : results.getNodeRefs())
            {
                // Ignore any node type that is not a "site"
                QName siteClassName = this.nodeService.getType(site);
                if (this.dictionaryService.isSubClass(siteClassName, SiteModel.TYPE_SITE))
                {
                    result.add(createSiteInfo(site));
                }
            }
        }
        finally
        {
            results.close();
        }
    }
    
    return result;
}
 
Example 56
Project: alfresco-remote-api   File: PatchThumbnailsAsRenditionsGet.java   Source Code and License 4 votes vote down vote up
@Override
public Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
{
    if (logger.isInfoEnabled())
    {
        logger.debug("Patching legacy thumbnails by applying appropriate rendition aspect");
    }
    List<NodeRef> resultNodeRefs = null; 
    ResultSet types = null;

    try
    {
        types = searchService.query(SPACES_STORE, SearchService.LANGUAGE_LUCENE, QUERY);
        resultNodeRefs = types.getNodeRefs();
    }
    finally
    {
        if (types != null) {types.close();}
    }
    
    long patchedNodeRefs = 0;
    
    for (NodeRef nodeRef : resultNodeRefs)
    {
        if (nodeService.exists(nodeRef) == false ||
                renditionService.isRendition(nodeRef))
        {
            continue;
        }
        
        // Now add one of the two aspects depending on parent location.
        ChildAssociationRef sourceNode = renditionService.getSourceNode(nodeRef);
        ChildAssociationRef primaryParent = nodeService.getPrimaryParent(nodeRef);
        QName aspectToApply;
        if (primaryParent.getParentRef().equals(sourceNode.getParentRef()))
        {
            aspectToApply = RenditionModel.ASPECT_HIDDEN_RENDITION;
        }
        else
        {
            aspectToApply = RenditionModel.ASPECT_VISIBLE_RENDITION;
        }

        if (logger.isDebugEnabled())
        {
            StringBuilder msg = new StringBuilder();
            msg.append("Applying aspect ")
                .append(aspectToApply)
                .append(" to node ")
                .append(nodeRef);
            logger.debug(msg.toString());
        }
        nodeService.addAspect(nodeRef, aspectToApply, null);
        patchedNodeRefs++;
    }

    Map<String, Object> model = new HashMap<String, Object>();
	model.put("patchedNodeCount", new Long(patchedNodeRefs));
	
    return model;
}
 
Example 57
Project: alfresco-repository   File: AbstractResultSetRow.java   Source Code and License 4 votes vote down vote up
public ResultSet getResultSet()
{
    return resultSet;
}
 
Example 58
Project: alfresco-remote-api   File: ResultMapper.java   Source Code and License 4 votes vote down vote up
/**
 * Turns the results into a CollectionWithPagingInfo
 * @param params
 * @param searchQuery
 *@param results  @return CollectionWithPagingInfo<Node>
 */
public CollectionWithPagingInfo<Node> toCollectionWithPagingInfo(Params params, SearchRequestContext searchRequestContext, SearchQuery searchQuery, ResultSet results)
{
    SearchContext context = null;
    Integer total = null;
    List<Node> noderesults = new ArrayList<Node>();
    Map<String, UserInfo> mapUserInfo = new HashMap<>(10);
    Map<NodeRef, List<Pair<String, List<String>>>> hightLighting = results.getHighlighting();
    int notFound = 0;
    boolean isHistory = searchRequestContext.getStores().contains(StoreMapper.HISTORY);

    for (ResultSetRow row:results)
    {
        Node aNode = getNode(row, params, mapUserInfo, isHistory);

        if (aNode != null)
        {
            float f = row.getScore();
            List<HighlightEntry> highlightEntries = null;
            List<Pair<String, List<String>>> high = hightLighting.get(row.getNodeRef());

            if (high != null && !high.isEmpty())
            {
                highlightEntries = new ArrayList<HighlightEntry>(high.size());
                for (Pair<String, List<String>> highlight:high)
                {
                    highlightEntries.add(new HighlightEntry(highlight.getFirst(), highlight.getSecond()));
                }
            }
            aNode.setSearch(new SearchEntry(f, highlightEntries));
            noderesults.add(aNode);
        }
        else
        {
            logger.debug("Unknown noderef returned from search results "+row.getNodeRef());
            notFound++;
        }
    }

    SolrJSONResultSet solrResultSet = findSolrResultSet(results);

    if (solrResultSet != null)
    {
        //We used Solr for this query
        context = toSearchContext(solrResultSet, searchRequestContext, searchQuery, notFound);
        total = setTotal(solrResultSet);
    }
    else
    {
        //This probably wasn't solr
        if (!results.hasMore())
        {
            //If there are no more results then we are confident that the number found is correct
            //otherwise we are not confident enough that its accurate
            total = setTotal(results);
        }
    }

    return CollectionWithPagingInfo.asPaged(params.getPaging(), noderesults, results.hasMore(), total, null, context);
}
 
Example 59
Project: alfresco-data-model   File: QueryEngineResults.java   Source Code and License 4 votes vote down vote up
public Map<Set<String>, ResultSet> getResults()
{
    return results;
}
 
Example 60
Project: alfresco-repository   File: LuceneOpenCMISStrictSqlQueryLanguage.java   Source Code and License 4 votes vote down vote up
public ResultSet executeQuery(SearchParameters searchParameters, ADMLuceneSearcherImpl admLuceneSearcher)
{
    CMISQueryOptions options = CMISQueryOptions.create(searchParameters);
    options.setQueryMode(CMISQueryMode.CMS_STRICT);
    return new ResultSetSPIWrapper<CMISResultSetRow, CMISResultSetMetaData>(cmisQueryService.query(options));
}