コード例 #1
0
  @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);
  }
コード例 #2
0
  @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");
  }
コード例 #3
0
  @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));
    }
  }
コード例 #4
0
  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;
  }
コード例 #5
0
  @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());
  }
コード例 #6
0
  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();
  }
コード例 #7
0
  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());
  }
コード例 #8
0
  protected void search(
      FileEntry fileEntry, boolean rootFolder, String keywords, boolean assertTrue)
      throws Exception {

    SearchContext searchContext = new SearchContext();

    searchContext.setAttribute("paginationType", "regular");
    searchContext.setCompanyId(fileEntry.getCompanyId());
    searchContext.setFolderIds(new long[] {fileEntry.getFolderId()});
    searchContext.setGroupIds(new long[] {fileEntry.getRepositoryId()});
    searchContext.setKeywords(keywords);

    QueryConfig queryConfig = new QueryConfig();

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

    searchContext.setQueryConfig(queryConfig);

    Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntryConstants.getClassName());

    Hits hits = indexer.search(searchContext);

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

    boolean found = false;

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

      if (fileEntryId == fileEntry.getFileEntryId()) {
        found = true;

        break;
      }
    }

    String message = "Search engine could not find ";

    if (rootFolder) {
      message += "root file entry by " + keywords;
    } else {
      message += "file entry by " + keywords;
    }

    message += " using query " + hits.getQuery();

    if (assertTrue) {
      Assert.assertTrue(message, found);
    } else {
      Assert.assertFalse(message, found);
    }
  }
コード例 #9
0
  @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();
  }
コード例 #10
0
  @Override
  public Hits search(SearchContext searchContext) throws SearchException {
    Hits hits = super.search(searchContext);

    String[] queryTerms = hits.getQueryTerms();

    String keywords = searchContext.getKeywords();

    queryTerms = ArrayUtil.append(queryTerms, KnowledgeBaseUtil.parseKeywords(keywords));

    hits.setQueryTerms(queryTerms);

    return hits;
  }
コード例 #11
0
ファイル: ContentHits.java プロジェクト: nykma/ykt4sungard
  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);
  }
コード例 #12
0
  @Override
  public List<AssetVocabulary> getVocabularies(Hits hits) throws PortalException {

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

    List<AssetVocabulary> vocabularies = new ArrayList<>(documents.size());

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

      AssetVocabulary vocabulary = fetchAssetVocabulary(vocabularyId);

      if (vocabulary == null) {
        vocabularies = null;

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

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

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

    return vocabularies;
  }
コード例 #13
0
  @Override
  public List<AssetCategory> getCategories(Hits hits) throws PortalException {
    List<Document> documents = hits.toList();

    List<AssetCategory> categories = new ArrayList<>(documents.size());

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

      AssetCategory category = fetchCategory(categoryId);

      if (category == null) {
        categories = null;

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

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

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

    return categories;
  }
コード例 #14
0
  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");
  }
コード例 #15
0
  @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());
  }
コード例 #16
0
  public Document getIndexedDocument(long id, SearchContext searchContext) {
    searchContext.setPortletIds(new String[] {EMInfo.PORTLET_ID});
    BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);
    BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(searchContext);
    booleanQuery.addRequiredTerm(Field.ENTRY_CLASS_NAME, EmpDiscipline.class.getName());
    booleanQuery.addExactTerm(EmpDisciplineField.ID, id);

    try {
      fullQuery.add(booleanQuery, BooleanClauseOccur.MUST);
      Hits hits = SearchEngineUtil.search(searchContext, fullQuery);
      return !hits.toList().isEmpty() ? hits.toList().get(0) : null;
    } catch (ParseException e) {
      LogFactoryUtil.getLog(EmpDisciplineLocalServiceImpl.class).info(e);
    } catch (SearchException e) {
      LogFactoryUtil.getLog(EmpDisciplineLocalServiceImpl.class).info(e);
    }

    return null;
  }
コード例 #17
0
  public static List<AssetEntry> getAssetEntries(Hits hits) {
    List<AssetEntry> assetEntries = new ArrayList<>();

    if (hits.getDocs() == null) {
      return assetEntries;
    }

    for (Document document : hits.getDocs()) {
      String className = GetterUtil.getString(document.get(Field.ENTRY_CLASS_NAME));
      long classPK = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK));

      try {
        AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(className, classPK);

        assetEntries.add(assetEntry);
      } catch (Exception e) {
      }
    }

    return assetEntries;
  }
コード例 #18
0
  @Override
  public List<TrashEntry> getEntries(Hits hits) {
    List<TrashEntry> entries = new ArrayList<>();

    for (Document document : hits.getDocs()) {
      String entryClassName = GetterUtil.getString(document.get(Field.ENTRY_CLASS_NAME));
      long classPK = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK));

      try {
        TrashEntry entry = TrashEntryLocalServiceUtil.fetchEntry(entryClassName, classPK);

        if (entry == null) {
          String userName = GetterUtil.getString(document.get(Field.REMOVED_BY_USER_NAME));

          Date removedDate = document.getDate(Field.REMOVED_DATE);

          entry = new TrashEntryImpl();

          entry.setUserName(userName);
          entry.setCreateDate(removedDate);

          TrashHandler trashHandler = TrashHandlerRegistryUtil.getTrashHandler(entryClassName);

          TrashRenderer trashRenderer = trashHandler.getTrashRenderer(classPK);

          entry.setClassName(trashRenderer.getClassName());
          entry.setClassPK(trashRenderer.getClassPK());

          String rootEntryClassName =
              GetterUtil.getString(document.get(Field.ROOT_ENTRY_CLASS_NAME));
          long rootEntryClassPK = GetterUtil.getLong(document.get(Field.ROOT_ENTRY_CLASS_PK));

          TrashEntry rootTrashEntry =
              TrashEntryLocalServiceUtil.fetchEntry(rootEntryClassName, rootEntryClassPK);

          if (rootTrashEntry != null) {
            entry.setRootEntry(rootTrashEntry);
          }
        }

        entries.add(entry);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(
              "Unable to find trash entry for " + entryClassName + " with primary key " + classPK);
        }
      }
    }

    return entries;
  }
コード例 #19
0
  public void recordHits(Hits hits, long groupId, boolean privateLayout, int start, int end)
      throws Exception {

    // This can later be optimized according to LEP-915.

    List<Document> docs = new ArrayList<Document>();
    List<Float> scores = new ArrayList<Float>();

    Document[] docsArray = hits.getDocs();

    for (int i = 0; i < docsArray.length; i++) {
      Document doc = hits.doc(i);

      String articleId = doc.get(Field.ARTICLE_ID);
      long articleGroupId = GetterUtil.getLong(doc.get(Field.GROUP_ID));

      int layoutIdsCount =
          JournalContentSearchLocalServiceUtil.getLayoutIdsCount(groupId, privateLayout, articleId);

      if ((layoutIdsCount > 0) || (!isShowListed() && (articleGroupId == groupId))) {

        docs.add(hits.doc(i));
        scores.add(hits.score(i));
      }
    }

    int length = docs.size();

    hits.setLength(length);

    if (end > length) {
      end = length;
    }

    docs = docs.subList(start, end);
    scores = scores.subList(start, end);

    hits.setDocs(docs.toArray(new Document[docs.size()]));
    hits.setScores(ArrayUtil.toFloatArray(scores));

    hits.setSearchTime((float) (System.currentTimeMillis() - hits.getStart()) / Time.SECOND);
  }
コード例 #20
0
ファイル: DLImpl.java プロジェクト: einsty/liferay-portal
  @Override
  public List<Object> getEntries(Hits hits) {
    List<Object> entries = new ArrayList<Object>();

    for (Document document : hits.getDocs()) {
      String entryClassName = GetterUtil.getString(document.get(Field.ENTRY_CLASS_NAME));
      long entryClassPK = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK));

      try {
        Object obj = null;

        if (entryClassName.equals(DLFileEntry.class.getName())) {
          obj = DLAppLocalServiceUtil.getFileEntry(entryClassPK);
        } else if (entryClassName.equals(MBMessage.class.getName())) {
          long classPK = GetterUtil.getLong(document.get(Field.CLASS_PK));

          DLAppLocalServiceUtil.getFileEntry(classPK);

          obj = MBMessageLocalServiceUtil.getMessage(entryClassPK);
        }

        entries.add(obj);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(
              "Documents and Media search index is stale and "
                  + "contains entry {className="
                  + entryClassName
                  + ", classPK="
                  + entryClassPK
                  + "}");
        }
      }
    }

    return entries;
  }
コード例 #21
0
ファイル: MBUtil.java プロジェクト: JamesLefeu/liferay-portal
  public static List<Object> getEntries(Hits hits) {
    List<Object> entries = new ArrayList<Object>();

    for (Document document : hits.getDocs()) {
      long categoryId = GetterUtil.getLong(document.get(Field.CATEGORY_ID));

      try {
        MBCategoryLocalServiceUtil.getCategory(categoryId);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(
              "Message boards search index is stale and contains " + "category " + categoryId);
        }

        continue;
      }

      long threadId = GetterUtil.getLong(document.get("threadId"));

      try {
        MBThreadLocalServiceUtil.getThread(threadId);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn("Message boards search index is stale and contains " + "thread " + threadId);
        }

        continue;
      }

      String entryClassName = document.get(Field.ENTRY_CLASS_NAME);
      long entryClassPK = GetterUtil.getLong(document.get(Field.ENTRY_CLASS_PK));

      Object obj = null;

      try {
        if (entryClassName.equals(DLFileEntry.class.getName())) {
          long classPK = GetterUtil.getLong(document.get(Field.CLASS_PK));

          MBMessageLocalServiceUtil.getMessage(classPK);

          obj = DLFileEntryLocalServiceUtil.getDLFileEntry(entryClassPK);
        } else if (entryClassName.equals(MBMessage.class.getName())) {
          obj = MBMessageLocalServiceUtil.getMessage(entryClassPK);
        }

        entries.add(obj);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(
              "Message boards search index is stale and contains "
                  + "entry {className="
                  + entryClassName
                  + ", "
                  + "classPK="
                  + entryClassPK
                  + "}");
        }

        continue;
      }
    }

    return entries;
  }
コード例 #22
0
  @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));
    }
  }
コード例 #23
0
  @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";
  }
コード例 #24
0
  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);
    }
  }
コード例 #25
0
  @Override
  public Hits search(SearchContext searchContext, Query query) throws SearchException {

    long startTime = System.currentTimeMillis();

    List<ExtRepositorySearchResult<?>> extRepositorySearchResults = null;

    try {
      extRepositorySearchResults =
          _extRepository.search(searchContext, query, new ExtRepositoryQueryMapperImpl(this));
    } catch (PortalException | SystemException e) {
      throw new SearchException("Unable to perform search", e);
    }

    QueryConfig queryConfig = searchContext.getQueryConfig();

    List<Document> documents = new ArrayList<>();
    List<String> snippets = new ArrayList<>();
    List<Float> scores = new ArrayList<>();

    int total = 0;

    for (ExtRepositorySearchResult<?> extRepositorySearchResult : extRepositorySearchResults) {

      try {
        ExtRepositoryObjectAdapter<?> extRepositoryEntryAdapter =
            _toExtRepositoryObjectAdapter(
                ExtRepositoryObjectAdapterType.OBJECT, extRepositorySearchResult.getObject());

        Document document = new DocumentImpl();

        document.addKeyword(Field.ENTRY_CLASS_NAME, extRepositoryEntryAdapter.getModelClassName());
        document.addKeyword(Field.ENTRY_CLASS_PK, extRepositoryEntryAdapter.getPrimaryKey());
        document.addKeyword(Field.TITLE, extRepositoryEntryAdapter.getName());

        documents.add(document);

        if (queryConfig.isScoreEnabled()) {
          scores.add(extRepositorySearchResult.getScore());
        } else {
          scores.add(1.0F);
        }

        snippets.add(extRepositorySearchResult.getSnippet());

        total++;
      } catch (PortalException | SystemException e) {
        if (_log.isWarnEnabled()) {
          _log.warn("Invalid entry returned from search", e);
        }
      }
    }

    float searchTime = (float) (System.currentTimeMillis() - startTime) / Time.SECOND;

    Hits hits = new HitsImpl();

    hits.setDocs(documents.toArray(new Document[documents.size()]));
    hits.setLength(total);
    hits.setQueryTerms(new String[0]);
    hits.setScores(ArrayUtil.toFloatArray(scores));
    hits.setSearchTime(searchTime);
    hits.setSnippets(snippets.toArray(new String[snippets.size()]));
    hits.setStart(startTime);

    return hits;
  }