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);
  }
  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;
  }
  @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;
  }
  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);
  }
Exemple #6
0
  @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;
  }
  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;
  }
  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";
  }