Example usage for com.liferay.portal.kernel.search Hits toList

List of usage examples for com.liferay.portal.kernel.search Hits toList

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.search Hits toList.

Prototype

public List<Document> toList();

Source Link

Usage

From source file:com.liferay.bookmarks.service.test.BookmarksFolderServiceTest.java

License:Open Source License

@Test
public void testSearchAndVerifyDocs() throws Exception {
    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(_group.getGroupId());

    BookmarksFolder folder = BookmarksTestUtil.addFolder(_group.getGroupId(), RandomTestUtil.randomString());

    BookmarksEntry entry = BookmarksTestUtil.addEntry(folder.getFolderId(), true, serviceContext);

    SearchContext searchContext = BookmarksTestUtil.getSearchContext(entry.getCompanyId(), entry.getGroupId(),
            entry.getFolderId(), "test");

    Indexer<BookmarksEntry> indexer = IndexerRegistryUtil.getIndexer(BookmarksEntry.class);

    Hits hits = indexer.search(searchContext);

    Assert.assertEquals(1, hits.getLength());

    List<Document> results = hits.toList();

    for (Document doc : results) {
        Assert.assertEquals(entry.getCompanyId(), GetterUtil.getLong(doc.get(Field.COMPANY_ID)));
        Assert.assertEquals(BookmarksEntry.class.getName(), doc.get(Field.ENTRY_CLASS_NAME));
        Assert.assertEquals(entry.getEntryId(), GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)));
        AssertUtils.assertEqualsIgnoreCase(entry.getName(), doc.get(Field.TITLE));
        Assert.assertEquals(entry.getUrl(), doc.get(Field.URL));
    }/* w  w w.  j ava2 s.co  m*/
}

From source file:com.liferay.content.targeting.util.CampaignUtil.java

License:Open Source License

public static List<Campaign> getCampaigns(Hits hits) throws PortalException, SystemException {

    List<Document> documents = hits.toList();

    List<Campaign> campaigns = new ArrayList<Campaign>(documents.size());

    for (Document document : documents) {
        long campaignId = GetterUtil.getLong(document.get("campaignId"));

        Campaign campaign = CampaignLocalServiceUtil.fetchCampaign(campaignId);

        if (campaign == null) {
            campaigns = null;//  w  ww .  ja va 2  s. c om

            Indexer indexer = IndexerRegistryUtil.getIndexer(Campaign.class);

            long companyId = GetterUtil.getLong(document.get(Field.COMPANY_ID));

            indexer.delete(companyId, document.getUID());
        } else if (campaigns != null) {
            campaigns.add(campaign);
        }
    }

    return campaigns;
}

From source file:com.liferay.content.targeting.util.UserSegmentUtil.java

License:Open Source License

public static List<UserSegment> getUserSegments(Hits hits) throws PortalException, SystemException {

    List<Document> documents = hits.toList();

    List<UserSegment> userSegments = new ArrayList<UserSegment>(documents.size());

    for (com.liferay.portal.kernel.search.Document document : documents) {
        long userSegmentId = GetterUtil.getLong(document.get("userSegmentId"));

        UserSegment userSegment = UserSegmentLocalServiceUtil.fetchUserSegment(userSegmentId);

        if (userSegment == null) {
            userSegments = null;//  w  ww  .  j av a 2  s.  c o m

            Indexer indexer = IndexerRegistryUtil.getIndexer(UserSegment.class);

            long companyId = GetterUtil.getLong(document.get(Field.COMPANY_ID));

            indexer.delete(companyId, document.getUID());
        } else if (userSegments != null) {
            userSegments.add(userSegment);
        }
    }

    return userSegments;
}

From source file:com.liferay.document.library.search.test.DLFileEntryIndexerLocalizedContentTest.java

License:Open Source License

private Document _getSingleDocument(String searchTerm, Hits hits) {
    List<Document> documents = hits.toList();

    if (documents.size() == 1) {
        return documents.get(0);
    }//from  w w w .java 2  s  . c o m

    throw new AssertionError(searchTerm + "->" + documents);
}

From source file:com.liferay.dynamic.data.lists.service.impl.DDLRecordLocalServiceImpl.java

License:Open Source License

protected List<DDLRecord> getRecords(Hits hits) throws PortalException {
    List<DDLRecord> records = new ArrayList<>();

    for (Document document : hits.toList()) {
        long recordId = GetterUtil.getLong(document.get(com.liferay.portal.kernel.search.Field.ENTRY_CLASS_PK));

        try {//  w  ww .  j  a  va  2 s . c  o m
            DDLRecord record = getRecord(recordId);

            records.add(record);
        } catch (NoSuchRecordException nsre) {
            if (_log.isWarnEnabled()) {
                _log.warn("DDL record index is stale and contains record " + recordId, nsre);
            }

            long companyId = GetterUtil
                    .getLong(document.get(com.liferay.portal.kernel.search.Field.COMPANY_ID));

            Indexer<DDLRecord> indexer = getDDLRecordIndexer();

            indexer.delete(companyId, document.getUID());
        }
    }

    return records;
}

From source file:com.liferay.dynamic.data.mapping.service.impl.DDMFormInstanceRecordLocalServiceImpl.java

License:Open Source License

protected List<DDMFormInstanceRecord> getFormInstanceRecords(Hits hits) throws PortalException {

    List<DDMFormInstanceRecord> formInstanceRecords = new ArrayList<>();

    for (Document document : hits.toList()) {
        long recordId = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK));

        try {/* w ww .ja v  a2 s  .  com*/
            DDMFormInstanceRecord formInstanceRecord = getFormInstanceRecord(recordId);

            formInstanceRecords.add(formInstanceRecord);
        } catch (NoSuchFormInstanceRecordException nsfire) {
            if (_log.isWarnEnabled()) {
                _log.warn("DDM form instance record index is stale and" + "contains record " + recordId,
                        nsfire);
            }

            long companyId = GetterUtil.getLong(document.get(Field.COMPANY_ID));

            Indexer<DDMFormInstanceRecord> indexer = getDDMFormInstanceRecordIndexer();

            indexer.delete(companyId, document.getUID());
        }
    }

    return formInstanceRecords;
}

From source file:com.liferay.experts.questions.util.QuestionsUtil.java

License:Open Source License

public static List<Question> getQuestions(Hits hits) throws PortalException, SystemException {

    List<Question> questions = new ArrayList<Question>();

    List<Document> documents = hits.toList();

    for (Document document : documents) {
        long questionId = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK));

        try {/*from  w  w w  .  ja  v a  2s .c  om*/
            Question question = QuestionLocalServiceUtil.getQuestion(questionId);

            questions.add(question);
        } catch (NoSuchQuestionException nsae) {
            Indexer indexer = IndexerRegistryUtil.getIndexer(Question.class);

            long companyId = GetterUtil.getLong(document.get(Field.COMPANY_ID));

            indexer.delete(companyId, String.valueOf(questionId));
        }
    }

    return questions;
}

From source file:com.liferay.faces.demos.list.UserLazyDataModel.java

License:Open Source License

/**
 * This method is called by the PrimeFaces {@link DataTable} according to the rows specified in the currently
 * displayed page of data.//from w ww.  j  a v a 2s  . c  o  m
 *
 * @param  first      The zero-relative first row index.
 * @param  pageSize   The number of rows to fetch.
 * @param  sortField  The name of the field which the table is sorted by.
 * @param  sortOrder  The sort order, which can be either ascending (default) or descending.
 * @param  filters    The query criteria. Note that in order for the filtering to work with the Liferay API, the
 *                    end-user must specify complete, matching words. Wildcards and partial matches are not
 *                    supported.
 */
@Override
public List<User> load(int first, int pageSize, String sortField, SortOrder sortOrder,
        Map<String, Object> filters) {

    List<User> users = null;

    Sort sort;

    // sort
    if (sortField != null) {

        if (sortOrder.equals(SortOrder.DESCENDING)) {
            sort = SortFactoryUtil.getSort(User.class, sortField, "desc");
        } else {
            sort = SortFactoryUtil.getSort(User.class, sortField, "asc");
        }
    } else {
        sort = SortFactoryUtil.getSort(User.class, DEFAULT_SORT_CRITERIA, "asc");
    }

    try {
        LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
        int liferayOneRelativeFinishRow = first + pageSize + 1;

        boolean andSearch = true;
        int status = WorkflowConstants.STATUS_ANY;

        String firstName = trimExpresssion((String) filters.get("firstName"));
        String middleName = trimExpresssion((String) filters.get("middleName"));
        String lastName = trimExpresssion((String) filters.get("lastName"));
        String screenName = trimExpresssion((String) filters.get("screenName"));
        String emailAddress = trimExpresssion((String) filters.get("emailAddress"));

        // For the sake of speed, search for users in the index rather than
        // querying the database directly.
        Hits hits = UserLocalServiceUtil.search(companyId, firstName, middleName, lastName, screenName,
                emailAddress, status, params, andSearch, first, liferayOneRelativeFinishRow, sort);

        List<Document> documentHits = hits.toList();

        logger.debug(
                ("filters firstName=[{0}] middleName=[{1}] lastName=[{2}] screenName=[{3}] emailAddress=[{4}] active=[{5}] andSearch=[{6}] startRow=[{7}] liferayOneRelativeFinishRow=[{8}] sortColumn=[{9}] reverseOrder=[{10}] hitCount=[{11}]"),
                firstName, middleName, lastName, screenName, emailAddress, status, andSearch, first,
                liferayOneRelativeFinishRow, sortField, sort.isReverse(), documentHits.size());

        // Convert the results from the search index into a list of user
        // objects.
        users = new ArrayList<User>(documentHits.size());

        for (Document document : documentHits) {

            long userId = GetterUtil.getLong(document.get(Field.USER_ID));

            try {
                User user = UserLocalServiceUtil.getUserById(userId);
                users.add(user);
            } catch (NoSuchUserException nsue) {
                logger.error("User with userId=[{0}] does not exist in the search index. Please reindex.");
            }
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    return users;

}

From source file:com.liferay.journal.util.impl.JournalUtil.java

License:Open Source License

/**
 * @deprecated As of 4.0.0, with no direct replacement
 *///from  w  ww . j  ava2s .  co  m
@Deprecated
public static List<JournalArticle> getArticles(Hits hits) throws PortalException {

    List<com.liferay.portal.kernel.search.Document> documents = hits.toList();

    List<JournalArticle> articles = new ArrayList<>(documents.size());

    for (com.liferay.portal.kernel.search.Document document : documents) {
        String articleId = document.get(Field.ARTICLE_ID);
        long groupId = GetterUtil.getLong(document.get(Field.SCOPE_GROUP_ID));

        JournalArticle article = JournalArticleLocalServiceUtil.fetchLatestArticle(groupId, articleId,
                WorkflowConstants.STATUS_APPROVED);

        if (article == null) {
            articles = null;

            Indexer<JournalArticle> indexer = IndexerRegistryUtil.getIndexer(JournalArticle.class);

            long companyId = GetterUtil.getLong(document.get(Field.COMPANY_ID));

            indexer.delete(companyId, document.getUID());
        } else if (articles != null) {
            articles.add(article);
        }
    }

    return articles;
}

From source file:com.liferay.portlet.bookmarks.service.BookmarksFolderServiceTest.java

License:Open Source License

public void testSearch() throws Exception {
    BookmarksEntry entry = addEntry();//from  ww w.  j  a  v  a 2 s .  c o m

    Thread.sleep(1000);

    long companyId = entry.getCompanyId();
    long groupId = entry.getFolder().getGroupId();
    long folderId = entry.getFolderId();
    String keywords = "test";

    SearchContext searchContext = new SearchContext();

    searchContext.setCompanyId(companyId);
    searchContext.setFolderIds(new long[] { folderId });
    searchContext.setGroupIds(new long[] { groupId });
    searchContext.setKeywords(keywords);

    QueryConfig queryConfig = new QueryConfig();

    queryConfig.setHighlightEnabled(false);
    queryConfig.setScoreEnabled(false);

    searchContext.setQueryConfig(queryConfig);

    Indexer indexer = IndexerRegistryUtil.getIndexer(BookmarksEntry.class);

    Hits hits = indexer.search(searchContext);

    assertEquals(1, hits.getLength());

    List<Document> results = hits.toList();

    for (Document doc : results) {
        assertEquals(companyId, GetterUtil.getLong(doc.get(Field.COMPANY_ID)));

        assertEquals(groupId, GetterUtil.getLong(doc.get(Field.GROUP_ID)));

        assertEqualsIgnoreCase(entry.getName(), doc.get(Field.TITLE));
        assertEquals(entry.getUrl(), doc.get(Field.URL));
        assertEqualsIgnoreCase(entry.getDescription(), doc.get(Field.DESCRIPTION));

        assertEquals(folderId, GetterUtil.getLong(doc.get("folderId")));
        assertEquals(entry.getEntryId(), GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK)));
    }

    BookmarksFolderLocalServiceUtil.deleteFolder(folderId);

    Thread.sleep(1000);

    hits = indexer.search(searchContext);

    Query query = hits.getQuery();

    assertEquals(query.toString(), 0, hits.getLength());

    addEntry();
    addEntry();
    addEntry();
    addEntry();

    Thread.sleep(1000);

    searchContext.setEnd(3);
    searchContext.setFolderIds(null);
    searchContext.setStart(1);

    hits = indexer.search(searchContext);

    assertEquals(4, hits.getLength());
    assertEquals(2, hits.getDocs().length);
}