@Test public void testSearchAndDeleteFolderAndSearch() throws Exception { ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(_group.getGroupId()); BookmarksFolder folder = BookmarksTestUtil.addFolder(_group.getGroupId(), RandomTestUtil.randomString()); BookmarksEntry entry = BookmarksTestUtil.addEntry(folder.getFolderId(), true, serviceContext); long companyId = entry.getCompanyId(); long groupId = entry.getFolder().getGroupId(); long folderId = entry.getFolderId(); String keywords = "test"; SearchContext searchContext = BookmarksTestUtil.getSearchContext(companyId, groupId, folderId, keywords); Indexer indexer = IndexerRegistryUtil.getIndexer(BookmarksEntry.class); Hits hits = indexer.search(searchContext); Assert.assertEquals(1, hits.getLength()); BookmarksFolderLocalServiceUtil.deleteFolder(folderId); hits = indexer.search(searchContext); Query query = hits.getQuery(); Assert.assertEquals(query.toString(), 0, hits.getLength()); }
public void recordHits(Hits hits, long groupId, boolean privateLayout) throws Exception { setSearcher(((HitsImpl) hits).getSearcher()); // This can later be optimized according to LEP-915. List docs = new ArrayList(hits.getLength()); List scores = new ArrayList(hits.getLength()); for (int i = 0; i < hits.getLength(); i++) { Document doc = hits.doc(i); String articleId = doc.get("articleId"); long articleGroupId = GetterUtil.getLong(doc.get(LuceneFields.GROUP_ID)); if (JournalContentSearchLocalServiceUtil.getLayoutIdsCount(groupId, privateLayout, articleId) > 0) { docs.add(hits.doc(i)); scores.add(new Float(hits.score(i))); } else if (!isShowListed() && (articleGroupId == groupId)) { docs.add(hits.doc(i)); scores.add(new Float(hits.score(i))); } } setLength(docs.size()); setDocs((Document[]) docs.toArray(new Document[0])); setScores((Float[]) scores.toArray(new Float[0])); setSearchTime((float) (System.currentTimeMillis() - getStart()) / Time.SECOND); }
@Override public BaseModelSearchResult<UserGroup> searchUserGroups( long companyId, String name, String description, LinkedHashMap<String, Object> params, boolean andSearch, int start, int end, Sort sort) throws PortalException { Indexer<UserGroup> indexer = IndexerRegistryUtil.nullSafeGetIndexer(UserGroup.class); SearchContext searchContext = buildSearchContext(companyId, name, description, params, andSearch, start, end, sort); for (int i = 0; i < 10; i++) { Hits hits = indexer.search(searchContext); List<UserGroup> userGroups = UsersAdminUtil.getUserGroups(hits); if (userGroups != null) { return new BaseModelSearchResult<>(userGroups, hits.getLength()); } } throw new SearchException("Unable to fix the search index after 10 attempts"); }
public SearchContainer<MBMessage> getCommentsSearchContainer() throws PortalException { SearchContainer<MBMessage> searchContainer = new SearchContainer( _liferayPortletRequest, _liferayPortletResponse.createRenderURL(), null, null); SearchContext searchContext = SearchContextFactory.getInstance(_liferayPortletRequest.getHttpServletRequest()); searchContext.setAttribute( Field.CLASS_NAME_ID, PortalUtil.getClassNameId(JournalArticle.class)); searchContext.setAttribute("discussion", true); List<MBMessage> mbMessages = new ArrayList<>(); Indexer indexer = IndexerRegistryUtil.getIndexer(MBMessage.class); Hits hits = indexer.search(searchContext); for (Document document : hits.getDocs()) { long entryClassPK = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK)); MBMessage mbMessage = MBMessageLocalServiceUtil.fetchMBMessage(entryClassPK); mbMessages.add(mbMessage); } searchContainer.setResults(mbMessages); searchContainer.setTotal(hits.getLength()); return searchContainer; }
@Test public void testSearchRange() throws Exception { BookmarksEntry entry = BookmarksTestUtil.addEntry(_group.getGroupId(), true); BookmarksTestUtil.addEntry(_group.getGroupId(), true); BookmarksTestUtil.addEntry(_group.getGroupId(), true); BookmarksTestUtil.addEntry(_group.getGroupId(), true); SearchContext searchContext = BookmarksTestUtil.getSearchContext( _group.getCompanyId(), _group.getGroupId(), entry.getFolderId(), "test"); Indexer indexer = IndexerRegistryUtil.getIndexer(BookmarksEntry.class); searchContext.setEnd(3); searchContext.setFolderIds((long[]) null); searchContext.setStart(1); Hits hits = indexer.search(searchContext); Assert.assertEquals(4, hits.getLength()); Document[] documents = hits.getDocs(); Assert.assertEquals(2, documents.length); }
@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 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)); } }
protected int searchBaseModelsCount(Class<?> clazz, long groupId, SearchContext searchContext) throws Exception { Indexer indexer = IndexerRegistryUtil.getIndexer(clazz); searchContext.setGroupIds(new long[] {groupId}); Hits results = indexer.search(searchContext); return results.getLength(); }
public static BaseModelSearchResult<AssetEntry> searchAssetEntries( SearchContext searchContext, AssetEntryQuery assetEntryQuery, int start, int end) throws Exception { AssetSearcher assetSearcher = getAssetSearcher(searchContext, assetEntryQuery, start, end); Hits hits = assetSearcher.search(searchContext); List<AssetEntry> assetEntries = getAssetEntries(hits); return new BaseModelSearchResult<>(assetEntries, hits.getLength()); }
@Override protected long searchGroupEntriesCount(long groupId, long creatorUserId) throws Exception { Hits hits = MBThreadServiceUtil.search( groupId, creatorUserId, WorkflowConstants.STATUS_APPROVED, QueryUtil.ALL_POS, QueryUtil.ALL_POS); return hits.getLength(); }
protected BaseModelSearchResult<AssetVocabulary> searchVocabularies(SearchContext searchContext) throws PortalException { Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(AssetVocabulary.class); for (int i = 0; i < 10; i++) { Hits hits = indexer.search(searchContext); List<AssetVocabulary> vocabularies = getVocabularies(hits); if (vocabularies != null) { return new BaseModelSearchResult<>(vocabularies, hits.getLength()); } } throw new SearchException("Unable to fix the search index after 10 attempts"); }
@Test public void testSearch() 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 indexer = IndexerRegistryUtil.getIndexer(BookmarksEntry.class); Hits hits = indexer.search(searchContext); Assert.assertEquals(1, hits.getLength()); }
public String search( HttpServletRequest request, long groupId, long userId, String keywords, int startPage, int itemsPerPage, String format) throws SearchException { try { ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); int start = (startPage * itemsPerPage) - itemsPerPage; int end = startPage * itemsPerPage; Hits results = CompanyLocalServiceUtil.search(themeDisplay.getCompanyId(), userId, keywords, start, end); String[] queryTerms = results.getQueryTerms(); int total = results.getLength(); Object[] values = addSearchResults( queryTerms, keywords, startPage, itemsPerPage, total, start, "Liferay Portal Search: " + keywords, SEARCH_PATH, format, themeDisplay); com.liferay.portal.kernel.xml.Document doc = (com.liferay.portal.kernel.xml.Document) values[0]; Element root = (Element) values[1]; for (int i = 0; i < results.getDocs().length; i++) { Document result = results.doc(i); String portletId = result.get(Field.PORTLET_ID); Portlet portlet = PortletLocalServiceUtil.getPortletById(themeDisplay.getCompanyId(), portletId); if (portlet == null) { continue; } String portletTitle = PortalUtil.getPortletTitle(portletId, themeDisplay.getUser()); long resultGroupId = GetterUtil.getLong(result.get(Field.GROUP_ID)); String entryClassName = GetterUtil.getString(result.get(Field.ENTRY_CLASS_NAME)); long entryClassPK = GetterUtil.getLong(result.get(Field.ENTRY_CLASS_PK)); String title = StringPool.BLANK; PortletURL portletURL = getPortletURL(request, portletId, resultGroupId); String url = portletURL.toString(); Date modifedDate = result.getDate(Field.MODIFIED); String content = StringPool.BLANK; if (Validator.isNotNull(portlet.getIndexerClass())) { Indexer indexer = (Indexer) InstancePool.get(portlet.getIndexerClass()); String snippet = results.snippet(i); Summary summary = indexer.getSummary(result, snippet, portletURL); title = summary.getTitle(); url = portletURL.toString(); content = summary.getContent(); if (portlet.getPortletId().equals(PortletKeys.JOURNAL)) { url = getJournalURL(themeDisplay, resultGroupId, result); } } double score = results.score(i); addSearchResult( root, resultGroupId, entryClassName, entryClassPK, portletTitle + " " + CharPool.RAQUO + " " + title, url, modifedDate, content, score, format); } if (_log.isDebugEnabled()) { _log.debug("Return\n" + doc.asXML()); } return doc.asXML(); } catch (Exception e) { throw new SearchException(e); } }
@RenderMapping(params = "action=ricercaLibera") public String effettuaRicerca( RenderRequest renderRequest, RenderResponse renderResponse, Model model, @ModelAttribute("navigaProgetti") NavigaProgetti navigaProgetti, @RequestParam("cercaPerKeyword") String cercaPerKeyword) { model.addAttribute("currentAction", "ricercaLibera"); navigaProgetti.setCurrentAction("ricercaLibera"); model.addAttribute("cercaPerKeyword", cercaPerKeyword); model.addAttribute("navigaProgetti", navigaProgetti); logger.info("effettuaRicerca.cercaPerKeyword: " + cercaPerKeyword); try { Document[] documents = null; List<DocumentoDTO> risultatiGenerici = new ArrayList<DocumentoDTO>(); List<Progetto> risultatiProgetti = new ArrayList<Progetto>(); if (cercaPerKeyword != null && cercaPerKeyword.length() > 3) { Query query = StringQueryFactoryUtil.create( Field.TITLE + ":" + cercaPerKeyword + " or " + Field.CONTENT + ":" + cercaPerKeyword + " or " + Constants.RICERCALIBERA_FIELD_SEARCH + ":" + cercaPerKeyword + " or " + Constants.RICERCALIBERA_FIELD_LOCALIZZAZIONE + ":" + cercaPerKeyword + " or " + Constants.RICERCALIBERA_FIELD_CODICE_CUP + ":" + cercaPerKeyword); logger.debug("query = " + query.toString()); Hits hits = SearchEngineUtil.search( SearchEngineUtil.SYSTEM_ENGINE_ID, PortalUtil.getDefaultCompanyId(), query, -1, -1); logger.info("hits = " + hits.getLength()); documents = hits.getDocs(); model.addAttribute("valoreRicercaValido", "SI"); } else { SessionMessages.add(renderRequest, "valore-ricerca-non-valido"); model.addAttribute("valoreRicercaValido", "NO"); } if (documents != null) { DocumentoDTO documento = null; Progetto progetto = null; int contaDoc = 0; for (Document document : documents) { logger.debug("Document: " + document.getUID()); // for (Map.Entry<String, Field> entry : document.getFields().entrySet() ) { // logger.debug("-- " + entry.getKey() + ": " + entry.getValue().getValue() ); // } if (document.get(Field.ENTRY_CLASS_NAME).equals(Progetto.class.getName())) { progetto = getProgettoFromDocument(document); risultatiProgetti.add(progetto); } else { documento = new DocumentoDTO(); documento.setTitolo(document.getField(Field.TITLE).getValue()); String testo = "non disponibile"; if (document.getField(Field.CONTENT) != null) { testo = trunc(document.getField(Field.CONTENT).getValue(), 37); } documento.setTesto(testo); documento.setId(contaDoc++); AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry( document.get(Field.ENTRY_CLASS_NAME), Long.parseLong(document.get(Field.ENTRY_CLASS_PK))); documento.setUrl( getAssetViewURL(renderRequest, renderResponse, assetEntry, cercaPerKeyword)); risultatiGenerici.add(documento); } } } // model.addAttribute("risultatiGenerici", risultatiGenerici); model.addAttribute("risultatiGenericiSize", risultatiGenerici.size()); SearchContainer<DocumentoDTO> searchContainerElencoDoc = new SearchContainer<DocumentoDTO>( renderRequest, renderResponse.createRenderURL(), null, "Nessun dato trovato per la selezione fatta"); searchContainerElencoDoc.setDelta(risultatiGenerici.size()); searchContainerElencoDoc.setTotal(risultatiGenerici.size()); searchContainerElencoDoc.setResults(risultatiGenerici); model.addAttribute("searchContainerElencoDoc", searchContainerElencoDoc); // model.addAttribute("risultatiProgetti", risultatiProgetti); SearchContainer<Progetto> searchContainerElencoPro = new SearchContainer<Progetto>( renderRequest, renderResponse.createRenderURL(), null, "Nessun dato trovato per la selezione fatta"); searchContainerElencoPro.setDelta(risultatiProgetti.size()); searchContainerElencoPro.setTotal(risultatiProgetti.size()); searchContainerElencoPro.setResults(risultatiProgetti); model.addAttribute("searchContainerElenco", searchContainerElencoPro); } catch (SearchException e) { logger.error("SearchException: ", e); } catch (NumberFormatException e) { logger.error("NumberFormatException: ", e); } catch (PortalException e) { logger.error("PortalException: ", e); } catch (SystemException e) { logger.error("SystemException: ", e); } return "elenco-progetti-view"; }
@Override protected void doDelete(Object obj) throws Exception { SearchContext searchContext = new SearchContext(); searchContext.setSearchEngineId(getSearchEngineId()); if (obj instanceof Account) { Account account = (Account) obj; BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(searchContext); booleanQuery.addRequiredTerm(Field.PORTLET_ID, PORTLET_ID); booleanQuery.addRequiredTerm("accountId", account.getAccountId()); Hits hits = SearchEngineUtil.search( getSearchEngineId(), account.getCompanyId(), booleanQuery, QueryUtil.ALL_POS, QueryUtil.ALL_POS); for (int i = 0; i < hits.getLength(); i++) { Document document = hits.doc(i); SearchEngineUtil.deleteDocument( getSearchEngineId(), account.getCompanyId(), document.get(Field.UID)); } } else if (obj instanceof Folder) { Folder folder = (Folder) obj; BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(searchContext); booleanQuery.addRequiredTerm(Field.PORTLET_ID, PORTLET_ID); booleanQuery.addRequiredTerm("folderId", folder.getFolderId()); Hits hits = SearchEngineUtil.search( getSearchEngineId(), folder.getCompanyId(), booleanQuery, QueryUtil.ALL_POS, QueryUtil.ALL_POS); for (int i = 0; i < hits.getLength(); i++) { Document document = hits.doc(i); SearchEngineUtil.deleteDocument( getSearchEngineId(), folder.getCompanyId(), document.get(Field.UID)); } } else if (obj instanceof Message) { Message message = (Message) obj; Document document = new DocumentImpl(); document.addUID(PORTLET_ID, message.getMessageId()); SearchEngineUtil.deleteDocument( getSearchEngineId(), message.getCompanyId(), document.get(Field.UID)); } }