Search in sources :

Example 1 with ResultSetRow

use of org.alfresco.service.cmr.search.ResultSetRow in project alfresco-remote-api by Alfresco.

the class ForumTopicsFilteredGet method wrap.

/**
 * Wrap up search results as {@link TopicInfo} instances
 *
 * @param finalResults ResultSet
 * @param paging PagingRequest
 */
protected PagingResults<TopicInfo> wrap(final ResultSet finalResults, PagingRequest paging) {
    int maxItems = paging.getMaxItems();
    Comparator<TopicInfo> lastPostDesc = new Comparator<TopicInfo>() {

        @Override
        public int compare(TopicInfo t1, TopicInfo t2) {
            Date t1LastPostDate = t1.getCreatedAt();
            if (discussionService.getMostRecentPost(t1) != null) {
                t1LastPostDate = discussionService.getMostRecentPost(t1).getCreatedAt();
            }
            Date t2LastPostDate = t2.getCreatedAt();
            if (discussionService.getMostRecentPost(t2) != null) {
                t2LastPostDate = discussionService.getMostRecentPost(t2).getCreatedAt();
            }
            return t2LastPostDate.compareTo(t1LastPostDate);
        }
    };
    final Set<TopicInfo> topics = new TreeSet<TopicInfo>(lastPostDesc);
    for (ResultSetRow row : finalResults) {
        Pair<TopicInfo, PostInfo> pair = discussionService.getForNodeRef(row.getNodeRef());
        TopicInfo topic = pair.getFirst();
        if (topic != null) {
            String path = nodeService.getPath(topic.getNodeRef()).toDisplayPath(nodeService, permissionService);
            String site = path.split("/")[3];
            TopicInfoImpl tii = (TopicInfoImpl) topic;
            tii.setShortSiteName(site);
            topics.add(tii);
            if (topics.size() >= maxItems) {
                break;
            }
        }
    }
    // Wrap
    return new PagingResults<TopicInfo>() {

        @Override
        public boolean hasMoreItems() {
            try {
                return finalResults.hasMore();
            } catch (UnsupportedOperationException e) {
                // Not all search results support paging
                return false;
            }
        }

        @Override
        public Pair<Integer, Integer> getTotalResultCount() {
            int skipCount = 0;
            int itemsRemainingAfterThisPage = 0;
            try {
                skipCount = finalResults.getStart();
            } catch (UnsupportedOperationException e) {
            }
            try {
                itemsRemainingAfterThisPage = finalResults.length();
            } catch (UnsupportedOperationException e) {
            }
            final int totalItemsInUnpagedResultSet = skipCount + itemsRemainingAfterThisPage;
            return new Pair<Integer, Integer>(totalItemsInUnpagedResultSet, totalItemsInUnpagedResultSet);
        }

        @Override
        public List<TopicInfo> getPage() {
            return new ArrayList<TopicInfo>(topics);
        }

        @Override
        public String getQueryExecutionId() {
            return null;
        }
    };
}
Also used : PagingResults(org.alfresco.query.PagingResults) EmptyPagingResults(org.alfresco.query.EmptyPagingResults) TopicInfoImpl(org.alfresco.repo.discussion.TopicInfoImpl) ArrayList(java.util.ArrayList) ResultSetRow(org.alfresco.service.cmr.search.ResultSetRow) TopicInfo(org.alfresco.service.cmr.discussion.TopicInfo) Date(java.util.Date) Comparator(java.util.Comparator) TreeSet(java.util.TreeSet) PostInfo(org.alfresco.service.cmr.discussion.PostInfo) Pair(org.alfresco.util.Pair)

Example 2 with ResultSetRow

use of org.alfresco.service.cmr.search.ResultSetRow in project acs-community-packaging by Alfresco.

the class BrowseBean method searchBrowseNodes.

/**
 * Search for a list of nodes using the specific search context
 *
 * @param searchContext    To use to perform the search
 */
private void searchBrowseNodes(SearchContext searchContext) {
    long startTime = 0;
    if (logger.isDebugEnabled())
        startTime = System.currentTimeMillis();
    // get the searcher object to build the query
    String query = searchContext.buildQuery(getMinimumSearchLength());
    if (query == null) {
        // failed to build a valid query, the user probably did not enter the
        // minimum text required to construct a valid search
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), MSG_SEARCH_MINIMUM), new Object[] { getMinimumSearchLength() }));
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        return;
    }
    // perform the search against the repo
    UserTransaction tx = null;
    ResultSet results = null;
    try {
        tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
        tx.begin();
        // build up the search parameters
        SearchParameters sp = new SearchParameters();
        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
        sp.setQuery(query);
        sp.addStore(Repository.getStoreRef());
        // limit search results size as configured
        int searchLimit = Application.getClientConfig(FacesContext.getCurrentInstance()).getSearchMaxResults();
        if (searchLimit > 0) {
            sp.setLimitBy(LimitBy.FINAL_SIZE);
            sp.setLimit(searchLimit);
        }
        sp.setBulkFetchEnabled(Application.getClientConfig(FacesContext.getCurrentInstance()).isBulkFetchEnabled());
        results = this.getSearchService().query(sp);
        if (logger.isDebugEnabled())
            logger.debug("Search results returned: " + results.length());
        // create a list of items from the results
        this.containerNodes = new ArrayList<Node>(results.length());
        this.contentNodes = new ArrayList<Node>(results.length());
        if (results.length() != 0) {
            // in case of dynamic config, only lookup once
            Set<NodeEventListener> nodeEventListeners = getNodeEventListeners();
            for (ResultSetRow row : results) {
                NodeRef nodeRef = row.getNodeRef();
                if (this.getNodeService().exists(nodeRef)) {
                    // find it's type so we can see if it's a node we are interested in
                    QName type = this.getNodeService().getType(nodeRef);
                    // make sure the type is defined in the data dictionary
                    TypeDefinition typeDef = this.getDictionaryService().getType(type);
                    if (typeDef != null) {
                        MapNode node = null;
                        // look for Space or File nodes
                        if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) && this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                            // create our Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);
                            node.addPropertyResolver("path", this.resolverPath);
                            node.addPropertyResolver("displayPath", this.resolverDisplayPath);
                            node.addPropertyResolver("icon", this.resolverSpaceIcon);
                            node.addPropertyResolver("smallIcon", this.resolverSmallIcon);
                            this.containerNodes.add(node);
                        } else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)) {
                            // create our Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);
                            setupCommonBindingProperties(node);
                            node.addPropertyResolver("path", this.resolverPath);
                            node.addPropertyResolver("displayPath", this.resolverDisplayPath);
                            this.contentNodes.add(node);
                        } else // look for File Link object node
                        if (ApplicationModel.TYPE_FILELINK.equals(type)) {
                            // create our File Link Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);
                            // only display the user has the permissions to navigate to the target of the link
                            NodeRef destRef = (NodeRef) node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
                            if (new Node(destRef).hasPermission(PermissionService.READ) == true) {
                                node.addPropertyResolver("url", this.resolverLinkUrl);
                                node.addPropertyResolver("downloadUrl", this.resolverLinkDownload);
                                node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl);
                                node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath);
                                node.addPropertyResolver("fileType16", this.resolverFileType16);
                                node.addPropertyResolver("fileType32", this.resolverFileType32);
                                node.addPropertyResolver("lang", this.resolverLang);
                                node.addPropertyResolver("path", this.resolverPath);
                                node.addPropertyResolver("displayPath", this.resolverDisplayPath);
                                this.contentNodes.add(node);
                            }
                        } else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) {
                            // create our Folder Link Node representation
                            node = new MapNode(nodeRef, this.getNodeService(), false);
                            // only display the user has the permissions to navigate to the target of the link
                            NodeRef destRef = (NodeRef) node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
                            if (new Node(destRef).hasPermission(PermissionService.READ) == true) {
                                node.addPropertyResolver("icon", this.resolverSpaceIcon);
                                node.addPropertyResolver("smallIcon", this.resolverSmallIcon);
                                node.addPropertyResolver("path", this.resolverPath);
                                node.addPropertyResolver("displayPath", this.resolverDisplayPath);
                                this.containerNodes.add(node);
                            }
                        }
                        // inform any listeners that a Node wrapper has been created
                        if (node != null) {
                            for (NodeEventListener listener : nodeEventListeners) {
                                listener.created(node, type);
                            }
                        }
                    } else {
                        if (logger.isWarnEnabled())
                            logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type);
                    }
                } else {
                    if (logger.isWarnEnabled())
                        logger.warn("Missing object returned from search indexes: id = " + nodeRef + " search query: " + query);
                }
            }
        }
        // commit the transaction
        tx.commit();
    } catch (InvalidNodeRefException refErr) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] { refErr.getNodeRef() }), refErr);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (SearcherException serr) {
        logger.info("Search failed for: " + query, serr);
        Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_SEARCH), new Object[] { err.getMessage() }), err);
        this.containerNodes = Collections.<Node>emptyList();
        this.contentNodes = Collections.<Node>emptyList();
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } finally {
        if (results != null) {
            results.close();
        }
    }
    if (logger.isDebugEnabled()) {
        long endTime = System.currentTimeMillis();
        logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms");
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) QName(org.alfresco.service.namespace.QName) Node(org.alfresco.web.bean.repository.Node) MapNode(org.alfresco.web.bean.repository.MapNode) ResultSetRow(org.alfresco.service.cmr.search.ResultSetRow) MapNode(org.alfresco.web.bean.repository.MapNode) SearcherException(org.alfresco.repo.search.SearcherException) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) AbortProcessingException(javax.faces.event.AbortProcessingException) IOException(java.io.IOException) TypeDefinition(org.alfresco.service.cmr.dictionary.TypeDefinition) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) NodeRef(org.alfresco.service.cmr.repository.NodeRef) SearcherException(org.alfresco.repo.search.SearcherException) ResultSet(org.alfresco.service.cmr.search.ResultSet) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException)

Example 3 with ResultSetRow

use of org.alfresco.service.cmr.search.ResultSetRow in project acs-community-packaging by Alfresco.

the class TrashcanDialog method getItems.

/**
 * @return the list of deleted items to display
 */
public List<Node> getItems() {
    // to get deleted items from deleted items store
    // use a search to find the items - also filters by name/username
    List<Node> itemNodes = null;
    UserTransaction tx = null;
    ResultSet results = null;
    try {
        tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
        tx.begin();
        // get the root node to the deleted items store
        if (getArchiveRootRef() != null && property.isShowItems()) {
            String query = buildSearchQuery();
            SearchParameters sp = new SearchParameters();
            sp.setLanguage(SearchService.LANGUAGE_LUCENE);
            sp.setQuery(query);
            // the Archived Node store
            sp.addStore(getArchiveRootRef().getStoreRef());
            results = getSearchService().query(sp);
            itemNodes = new ArrayList<Node>(results.length());
        }
        if (results != null && results.length() != 0) {
            for (ResultSetRow row : results) {
                NodeRef nodeRef = row.getNodeRef();
                if (getNodeService().exists(nodeRef)) {
                    QName type = getNodeService().getType(nodeRef);
                    MapNode node = new MapNode(nodeRef, getNodeService(), false);
                    node.addPropertyResolver("locationPath", resolverLocationPath);
                    node.addPropertyResolver("displayPath", resolverDisplayPath);
                    node.addPropertyResolver("deletedDate", resolverDeletedDate);
                    node.addPropertyResolver("deletedBy", resolverDeletedBy);
                    node.addPropertyResolver("isFolder", resolverIsFolder);
                    if (getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true && getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) {
                        node.addPropertyResolver("typeIcon", this.resolverSmallIcon);
                    } else {
                        node.addPropertyResolver("typeIcon", this.resolverFileType16);
                    }
                    itemNodes.add(node);
                }
            }
        }
        tx.commit();
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), new Object[] { err.getMessage() }), err);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
    } finally {
        if (results != null) {
            results.close();
        }
    }
    property.setListedItems((itemNodes != null ? itemNodes : Collections.<Node>emptyList()));
    return property.getListedItems();
}
Also used : UserTransaction(javax.transaction.UserTransaction) QName(org.alfresco.service.namespace.QName) Node(org.alfresco.web.bean.repository.Node) MapNode(org.alfresco.web.bean.repository.MapNode) ResultSetRow(org.alfresco.service.cmr.search.ResultSetRow) MapNode(org.alfresco.web.bean.repository.MapNode) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ResultSet(org.alfresco.service.cmr.search.ResultSet)

Example 4 with ResultSetRow

use of org.alfresco.service.cmr.search.ResultSetRow in project alfresco-remote-api by Alfresco.

the class QuickShareLinksImpl method findLinks.

public CollectionWithPagingInfo<QuickShareLink> findLinks(Parameters parameters) {
    checkEnabled();
    String queryString = "ASPECT:\"" + QuickShareModel.ASPECT_QSHARE.toString() + "\"";
    SearchParameters sp = new SearchParameters();
    // note: REST API query parameter (ie. where clause filter) - not to be confused with search query ;-)
    Query q = parameters.getQuery();
    if (q != null) {
        // filtering via "where" clause
        MapBasedQueryWalker propertyWalker = new MapBasedQueryWalker(FIND_SHARED_LINKS_QUERY_PROPERTIES, null);
        QueryHelper.walk(q, propertyWalker);
        String sharedByUserId = propertyWalker.getProperty(PARAM_SHAREDBY, WhereClauseParser.EQUALS, String.class);
        if (sharedByUserId != null) {
            if (People.DEFAULT_USER.equalsIgnoreCase(sharedByUserId)) {
                sharedByUserId = AuthenticationUtil.getFullyAuthenticatedUser();
            }
            QueryParameterDefinition qpd = new QueryParameterDefImpl(QuickShareModel.PROP_QSHARE_SHAREDBY, dictionaryService.getDataType(DataTypeDefinition.TEXT), true, sharedByUserId);
            sp.addQueryParameterDefinition(qpd);
            String qsharedBy = QuickShareModel.PROP_QSHARE_SHAREDBY.toPrefixString(namespaceService);
            queryString += " +@" + SearchLanguageConversion.escapeLuceneQuery(qsharedBy) + ":\"${" + qsharedBy + "}\"";
        }
    }
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery(queryString);
    sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    Paging paging = parameters.getPaging();
    PagingRequest pagingRequest = Util.getPagingRequest(paging);
    sp.setSkipCount(pagingRequest.getSkipCount());
    sp.setMaxItems(pagingRequest.getMaxItems());
    sp.addSort("@" + ContentModel.PROP_MODIFIED, false);
    ResultSet results = searchService.query(sp);
    List<QuickShareLink> qsLinks = new ArrayList<>(results.length());
    List<String> includeParam = parameters.getInclude();
    for (ResultSetRow row : results) {
        NodeRef nodeRef = row.getNodeRef();
        qsLinks.add(getQuickShareInfo(nodeRef, false, includeParam));
    }
    results.close();
    return CollectionWithPagingInfo.asPaged(paging, qsLinks, results.hasMore(), Long.valueOf(results.getNumberFound()).intValue());
}
Also used : QueryParameterDefImpl(org.alfresco.repo.search.QueryParameterDefImpl) Query(org.alfresco.rest.framework.resource.parameters.where.Query) Paging(org.alfresco.rest.framework.resource.parameters.Paging) ArrayList(java.util.ArrayList) ResultSetRow(org.alfresco.service.cmr.search.ResultSetRow) PagingRequest(org.alfresco.query.PagingRequest) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) NodeRef(org.alfresco.service.cmr.repository.NodeRef) MapBasedQueryWalker(org.alfresco.rest.workflow.api.impl.MapBasedQueryWalker) ResultSet(org.alfresco.service.cmr.search.ResultSet) QuickShareLink(org.alfresco.rest.api.model.QuickShareLink) QueryParameterDefinition(org.alfresco.service.cmr.search.QueryParameterDefinition)

Example 5 with ResultSetRow

use of org.alfresco.service.cmr.search.ResultSetRow in project alfresco-remote-api by Alfresco.

the class ResultMapper method toCollectionWithPagingInfo.

/**
 * 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);
}
Also used : HashMap(java.util.HashMap) Node(org.alfresco.rest.api.model.Node) ArrayList(java.util.ArrayList) SearchContext(org.alfresco.rest.api.search.context.SearchContext) UserInfo(org.alfresco.rest.api.model.UserInfo) ResultSetRow(org.alfresco.service.cmr.search.ResultSetRow) SolrJSONResultSet(org.alfresco.repo.search.impl.lucene.SolrJSONResultSet) NodeRef(org.alfresco.service.cmr.repository.NodeRef) List(java.util.List) TupleList(org.alfresco.rest.api.search.model.TupleList) ArrayList(java.util.ArrayList) SearchEntry(org.alfresco.rest.api.search.model.SearchEntry) HighlightEntry(org.alfresco.rest.api.search.model.HighlightEntry) Pair(org.alfresco.util.Pair)

Aggregations

ResultSetRow (org.alfresco.service.cmr.search.ResultSetRow)5 NodeRef (org.alfresco.service.cmr.repository.NodeRef)4 ArrayList (java.util.ArrayList)3 ResultSet (org.alfresco.service.cmr.search.ResultSet)3 SearchParameters (org.alfresco.service.cmr.search.SearchParameters)3 UserTransaction (javax.transaction.UserTransaction)2 InvalidNodeRefException (org.alfresco.service.cmr.repository.InvalidNodeRefException)2 QName (org.alfresco.service.namespace.QName)2 Pair (org.alfresco.util.Pair)2 MapNode (org.alfresco.web.bean.repository.MapNode)2 Node (org.alfresco.web.bean.repository.Node)2 IOException (java.io.IOException)1 Comparator (java.util.Comparator)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 List (java.util.List)1 TreeSet (java.util.TreeSet)1 AbortProcessingException (javax.faces.event.AbortProcessingException)1 EmptyPagingResults (org.alfresco.query.EmptyPagingResults)1 PagingRequest (org.alfresco.query.PagingRequest)1