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

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

Introduction

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

Prototype

public Document doc(int n);

Source Link

Usage

From source file:com.liferay.journal.content.search.web.internal.util.ContentHits.java

License:Open Source License

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<>();
    List<Float> scores = new ArrayList<>();

    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);//from  w  w w  .j a v  a2 s  .  c o m

        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);
}

From source file:com.liferay.mail.util.AccountIndexer.java

License:Open Source License

@Override
protected void doDelete(Account account) throws Exception {
    SearchContext searchContext = new SearchContext();

    searchContext.setCompanyId(account.getCompanyId());
    searchContext.setEnd(QueryUtil.ALL_POS);
    searchContext.setSearchEngineId(getSearchEngineId());
    searchContext.setSorts(SortFactoryUtil.getDefaultSorts());
    searchContext.setStart(QueryUtil.ALL_POS);

    BooleanQuery booleanQuery = new BooleanQueryImpl();

    booleanQuery.addRequiredTerm(Field.ENTRY_CLASS_NAME, CLASS_NAME);

    booleanQuery.addRequiredTerm("accountId", account.getAccountId());

    Hits hits = IndexSearcherHelperUtil.search(searchContext, booleanQuery);

    List<String> uids = new ArrayList<>(hits.getLength());

    for (int i = 0; i < hits.getLength(); i++) {
        Document document = hits.doc(i);

        uids.add(document.get(Field.UID));
    }/*from  ww  w.j ava 2s. co m*/

    IndexWriterHelperUtil.deleteDocuments(getSearchEngineId(), account.getCompanyId(), uids,
            isCommitImmediately());
}

From source file:com.liferay.mail.util.FolderIndexer.java

License:Open Source License

@Override
protected void doDelete(Folder folder) throws Exception {
    SearchContext searchContext = new SearchContext();

    searchContext.setCompanyId(folder.getCompanyId());
    searchContext.setEnd(QueryUtil.ALL_POS);
    searchContext.setSearchEngineId(getSearchEngineId());
    searchContext.setSorts(SortFactoryUtil.getDefaultSorts());
    searchContext.setStart(QueryUtil.ALL_POS);

    BooleanQuery booleanQuery = new BooleanQueryImpl();

    booleanQuery.addRequiredTerm(Field.ENTRY_CLASS_NAME, CLASS_NAME);

    booleanQuery.addRequiredTerm("folderId", folder.getFolderId());

    Hits hits = IndexSearcherHelperUtil.search(searchContext, booleanQuery);

    List<String> uids = new ArrayList<>(hits.getLength());

    for (int i = 0; i < hits.getLength(); i++) {
        Document document = hits.doc(i);

        uids.add(document.get(Field.UID));
    }//from www  .j  a va  2 s  . c  o m

    IndexWriterHelperUtil.deleteDocuments(getSearchEngineId(), folder.getCompanyId(), uids,
            isCommitImmediately());
}

From source file:com.liferay.mail.util.MessageIndexer.java

License:Open Source License

@Override
protected void doDelete(Object obj) throws Exception {
    SearchContext searchContext = new SearchContext();

    searchContext.setSearchEngineId(getSearchEngineId());

    if (obj instanceof Account) {
        Account account = (Account) obj;

        searchContext.setCompanyId(account.getCompanyId());
        searchContext.setEnd(QueryUtil.ALL_POS);
        searchContext.setSorts(SortFactoryUtil.getDefaultSorts());
        searchContext.setStart(QueryUtil.ALL_POS);

        BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(searchContext);

        booleanQuery.addRequiredTerm(Field.PORTLET_ID, PORTLET_ID);

        booleanQuery.addRequiredTerm("accountId", account.getAccountId());

        Hits hits = SearchEngineUtil.search(searchContext, booleanQuery);

        List<String> uids = new ArrayList<String>(hits.getLength());

        for (int i = 0; i < hits.getLength(); i++) {
            Document document = hits.doc(i);

            uids.add(document.get(Field.UID));
        }/*from   w ww . j  av  a  2  s . c om*/

        SearchEngineUtil.deleteDocuments(getSearchEngineId(), account.getCompanyId(), uids,
                isCommitImmediately());
    } else if (obj instanceof Folder) {
        Folder folder = (Folder) obj;

        searchContext.setCompanyId(folder.getCompanyId());
        searchContext.setEnd(QueryUtil.ALL_POS);
        searchContext.setSorts(SortFactoryUtil.getDefaultSorts());
        searchContext.setStart(QueryUtil.ALL_POS);

        BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(searchContext);

        booleanQuery.addRequiredTerm(Field.PORTLET_ID, PORTLET_ID);

        booleanQuery.addRequiredTerm("folderId", folder.getFolderId());

        Hits hits = SearchEngineUtil.search(searchContext, booleanQuery);

        List<String> uids = new ArrayList<String>(hits.getLength());

        for (int i = 0; i < hits.getLength(); i++) {
            Document document = hits.doc(i);

            uids.add(document.get(Field.UID));
        }

        SearchEngineUtil.deleteDocuments(getSearchEngineId(), folder.getCompanyId(), uids,
                isCommitImmediately());
    } 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),
                isCommitImmediately());
    }
}

From source file:com.liferay.portlet.journalcontentsearch.util.ContentHits.java

License:Open Source License

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>();
    List<String> snippets = new ArrayList<String>();

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

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

        if (JournalContentSearchLocalServiceUtil.getLayoutIdsCount(groupId, privateLayout, articleId) > 0) {

            docs.add(hits.doc(i));//from www.  j a  v  a 2s. com
            scores.add(hits.score(i));
            snippets.add(hits.snippet(i));
        } else if (!isShowListed() && (articleGroupId == groupId)) {
            docs.add(hits.doc(i));
            scores.add(hits.score(i));
            snippets.add(hits.snippet(i));
        }
    }

    int length = docs.size();

    hits.setLength(length);

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

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

    hits.setDocs(docs.toArray(new Document[docs.size()]));
    hits.setScores(scores.toArray(new Float[docs.size()]));
    hits.setSnippets(snippets.toArray(new String[docs.size()]));

    hits.setSearchTime((float) (System.currentTimeMillis() - hits.getStart()) / Time.SECOND);
}

From source file:com.liferay.portlet.messageboards.util.MBIndexer.java

License:Open Source License

@Override
protected void doDelete(Object obj) throws Exception {
    SearchContext searchContext = new SearchContext();

    searchContext.setSearchEngineId(SearchEngineUtil.SYSTEM_ENGINE_ID);

    if (obj instanceof MBCategory) {
        MBCategory category = (MBCategory) obj;

        BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(searchContext);

        booleanQuery.addRequiredTerm(Field.PORTLET_ID, PORTLET_ID);

        booleanQuery.addRequiredTerm("categoryId", category.getCategoryId());

        Hits hits = SearchEngineUtil.search(category.getCompanyId(), booleanQuery, QueryUtil.ALL_POS,
                QueryUtil.ALL_POS);/*w  w  w.  j  a v a  2  s  .com*/

        for (int i = 0; i < hits.getLength(); i++) {
            Document document = hits.doc(i);

            SearchEngineUtil.deleteDocument(category.getCompanyId(), document.get(Field.UID));
        }
    } else if (obj instanceof MBMessage) {
        MBMessage message = (MBMessage) obj;

        Document document = new DocumentImpl();

        document.addUID(PORTLET_ID, message.getMessageId());

        SearchEngineUtil.deleteDocument(message.getCompanyId(), document.get(Field.UID));
    } else if (obj instanceof MBThread) {
        MBThread thread = (MBThread) obj;

        MBMessage message = MBMessageLocalServiceUtil.getMessage(thread.getRootMessageId());

        BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(searchContext);

        booleanQuery.addRequiredTerm(Field.PORTLET_ID, PORTLET_ID);

        booleanQuery.addRequiredTerm("threadId", thread.getThreadId());

        Hits hits = SearchEngineUtil.search(message.getCompanyId(), booleanQuery, QueryUtil.ALL_POS,
                QueryUtil.ALL_POS);

        for (int i = 0; i < hits.getLength(); i++) {
            Document document = hits.doc(i);

            SearchEngineUtil.deleteDocument(message.getCompanyId(), document.get(Field.UID));
        }
    }
}

From source file:com.liferay.portlet.wiki.util.WikiIndexer.java

License:Open Source License

@Override
protected void doDelete(Object obj) throws Exception {
    SearchContext searchContext = new SearchContext();

    searchContext.setSearchEngineId(SearchEngineUtil.SYSTEM_ENGINE_ID);

    if (obj instanceof Object[]) {
        Object[] array = (Object[]) obj;

        long companyId = (Long) array[0];
        long nodeId = (Long) array[1];
        String title = (String) array[2];

        Document document = new DocumentImpl();

        document.addUID(PORTLET_ID, nodeId, title);

        SearchEngineUtil.deleteDocument(companyId, document.get(Field.UID));

    } else if (obj instanceof WikiNode) {
        WikiNode node = (WikiNode) obj;//w  w w .  ja  v  a2 s .co  m

        BooleanQuery booleanQuery = BooleanQueryFactoryUtil.create(searchContext);

        booleanQuery.addRequiredTerm(Field.PORTLET_ID, PORTLET_ID);

        booleanQuery.addRequiredTerm("nodeId", node.getNodeId());

        Hits hits = SearchEngineUtil.search(node.getCompanyId(), booleanQuery, QueryUtil.ALL_POS,
                QueryUtil.ALL_POS);

        for (int i = 0; i < hits.getLength(); i++) {
            Document document = hits.doc(i);

            SearchEngineUtil.deleteDocument(node.getCompanyId(), document.get(Field.UID));
        }
    } else if (obj instanceof WikiPage) {
        WikiPage page = (WikiPage) obj;

        Document document = new DocumentImpl();

        document.addUID(PORTLET_ID, page.getNodeId(), page.getTitle());

        SearchEngineUtil.deleteDocument(page.getCompanyId(), document.get(Field.UID));
    }
}

From source file:com.slayer.service.impl.LMSBookLocalServiceImpl.java

License:Open Source License

public List<LMSBook> advancedSearch(long companyId, long groupId, String bookTitle, String author,
        boolean andSearch) {

    Hits hits = null;
    try {//w  ww  .  ja v  a  2 s.c  o m
        hits = getHits(companyId, groupId, bookTitle, author, andSearch);
    } catch (SystemException e) {
        e.printStackTrace();
    }

    if (hits == null || hits.getLength() == 0)
        return null;

    List<LMSBook> books = new ArrayList<LMSBook>();
    for (int i = 0; i < hits.getLength(); i++) {
        Document doc = hits.doc(i);

        long bookId = GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK));
        try {
            LMSBook book = fetchLMSBook(bookId);
            books.add(book);
        } catch (SystemException e) {
            e.printStackTrace();
        }
    }

    return books;
}

From source file:com.vportal.portal.search.HitsOpenSearchImpl.java

License:Open Source License

public String search(HttpServletRequest request, long groupId, long userId, String keywords, int startPage,
        int itemsPerPage, String format) throws SearchException {

    try {/*  w  w  w. ja v  a 2 s  . co m*/
        ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

        int start = (startPage * itemsPerPage) - itemsPerPage;
        int end = startPage * itemsPerPage;

        SearchContext searchContext = SearchContextFactory.getInstance(request);

        searchContext.setGroupIds(new long[] { groupId });
        searchContext.setEnd(end);
        searchContext.setKeywords(keywords);
        searchContext.setScopeStrict(false);
        searchContext.setStart(start);
        searchContext.setUserId(userId);

        addSearchAttributes(themeDisplay.getCompanyId(), searchContext, keywords);

        Portlet portlet = PortletLocalServiceUtil.getPortletById(themeDisplay.getCompanyId(), getPortletId());

        Indexer indexer = portlet.getIndexerInstance();

        Hits results = indexer.search(searchContext);

        String[] queryTerms = results.getQueryTerms();

        int total = results.getLength();

        Object[] values = addSearchResults(queryTerms, keywords, startPage, itemsPerPage, total, start,
                getTitle(keywords), getSearchPath(), 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);

            String snippet = results.snippet(i);

            long resultGroupId = GetterUtil.getLong(result.get(Field.GROUP_ID));

            PortletURL portletURL = getPortletURL(request, portletId, resultGroupId);

            Summary summary = getSummary(indexer, result, snippet, portletURL);

            String title = summary.getTitle();
            String url = getURL(themeDisplay, resultGroupId, result, portletURL);
            Date modifedDate = result.getDate(Field.MODIFIED);
            String content = summary.getContent();

            String[] tags = new String[0];

            Field assetTagNamesField = result.getFields().get(Field.ASSET_TAG_NAMES);

            if (assetTagNamesField != null) {
                tags = assetTagNamesField.getValues();
            }

            double ratings = 0.0;

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

            if ((Validator.isNotNull(entryClassName)) && (entryClassPK > 0)) {

                RatingsStats stats = RatingsStatsLocalServiceUtil.getStats(entryClassName, entryClassPK);

                ratings = stats.getTotalScore();
            }

            double score = results.score(i);

            addSearchResult(root, resultGroupId, entryClassName, entryClassPK, title, url, modifedDate, content,
                    tags, ratings, score, format);
        }

        if (_log.isDebugEnabled()) {
            _log.debug("Return\n" + doc.asXML());
        }

        return doc.asXML();
    } catch (Exception e) {
        throw new SearchException(e);
    }
}

From source file:org.xmlportletfactory.olafk.customer.CustomerPortlet.java

License:Open Source License

@SuppressWarnings("unchecked")
public void showViewDefault(RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {

    ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);

    long groupId = themeDisplay.getScopeGroupId();

    PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

    boolean hasAddPermission = CustomerPermission.contains(permissionChecker, groupId, "ADD_CUSTOMER");

    boolean hasModelPermissions = CustomerPermission.contains(permissionChecker, groupId,
            ActionKeys.PERMISSIONS);//from   ww  w. j  a  v a2 s.c o m

    List<Customer> tempResults = Collections.EMPTY_LIST;

    PortletPreferences prefs = renderRequest.getPreferences();

    String customersFilter = ParamUtil.getString(renderRequest, "customersFilter");

    String rowsPerPage = prefs.getValue("rows-per-page", "5");
    String viewType = prefs.getValue("view-type", "0");

    Integer cur = 1;
    int containerStart = 0;
    int containerEnd = 0;
    String orderByType = renderRequest.getParameter("orderByType");
    String orderByCol = renderRequest.getParameter("orderByCol");
    try {
        cur = ParamUtil.getInteger(renderRequest, "cur");

    } catch (Exception e) {
        cur = 1;
    }

    if (cur < 1) {
        cur = 1;
    }

    if (Validator.isNotNull(customersFilter) || !customersFilter.equalsIgnoreCase("")) {
        rowsPerPage = "100";
        cur = 1;
    }

    containerStart = (cur - 1) * Integer.parseInt(rowsPerPage);
    containerEnd = containerStart + Integer.parseInt(rowsPerPage);

    int total = 0;
    try {
        PortalPreferences portalPrefs = PortletPreferencesFactoryUtil.getPortalPreferences(renderRequest);

        if (Validator.isNull(orderByCol) && Validator.isNull(orderByType)) {
            orderByCol = portalPrefs.getValue("Customer_order", "Customer-order-by-col", "customerId");
            orderByType = portalPrefs.getValue("Customer_order", "Customer-order-by-type", "asc");
        }
        OrderByComparator comparator = CustomerComparator.getCustomerOrderByComparator(orderByCol, orderByType);

        if (customersFilter.equalsIgnoreCase("")) {

            if (viewType.equals("0")) {
                tempResults = CustomerLocalServiceUtil.findAllInGroup(groupId, containerStart, containerEnd,
                        comparator);
                total = CustomerLocalServiceUtil.countAllInGroup(groupId);
            } else if (viewType.equals("1")) {
                tempResults = CustomerLocalServiceUtil.findAllInUser(themeDisplay.getUserId(), containerStart,
                        containerEnd, comparator);
                total = CustomerLocalServiceUtil.countAllInUser(themeDisplay.getUserId());
            } else {
                tempResults = CustomerLocalServiceUtil.findAllInUserAndGroup(themeDisplay.getUserId(), groupId,
                        containerStart, containerEnd, comparator);
                total = CustomerLocalServiceUtil.countAllInUserAndGroup(themeDisplay.getUserId(), groupId);
            }

        } else {

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

            SearchContext searchContext = SearchContextFactory
                    .getInstance(PortalUtil.getHttpServletRequest(renderRequest));

            searchContext.setEnd(containerEnd);
            searchContext.setKeywords(customersFilter);
            searchContext.setStart(containerStart);

            Hits results = indexer.search(searchContext);

            total = results.getLength();

            if (total > 0) {
                tempResults = new ArrayList<Customer>(total);
            }
            for (int i = 0; i < results.getDocs().length; i++) {
                Document doc = results.doc(i);

                Customer resReg = null;

                // Entry
                long entryId = GetterUtil.getLong(doc.get(Field.ENTRY_CLASS_PK));

                try {
                    resReg = CustomerLocalServiceUtil.getCustomer(entryId);

                    resReg = resReg.toEscapedModel();

                    tempResults.add(resReg);
                } catch (Exception e) {
                    if (_log.isWarnEnabled()) {
                        _log.warn("Customer search index is stale and contains entry " + entryId);
                    }

                    continue;
                }
            }
        }

    } catch (Exception e) {
        _log.debug(e);
    }
    renderRequest.setAttribute("highlightRowWithKey", renderRequest.getParameter("highlightRowWithKey"));
    renderRequest.setAttribute("containerStart", containerStart);
    renderRequest.setAttribute("containerEnd", containerEnd);
    renderRequest.setAttribute("cur", cur);
    renderRequest.setAttribute("tempResults", tempResults);
    renderRequest.setAttribute("totalCount", total);
    renderRequest.setAttribute("rowsPerPage", rowsPerPage);
    renderRequest.setAttribute("hasAddPermission", hasAddPermission);
    renderRequest.setAttribute("hasModelPermissions", hasModelPermissions);
    renderRequest.setAttribute("orderByType", orderByType);
    renderRequest.setAttribute("orderByCol", orderByCol);
    renderRequest.setAttribute("customersFilter", customersFilter);

    PortletURL addCustomerURL = renderResponse.createActionURL();
    addCustomerURL.setParameter("javax.portlet.action", "newCustomer");
    renderRequest.setAttribute("addCustomerURL", addCustomerURL.toString());

    PortletURL customersFilterURL = renderResponse.createRenderURL();
    customersFilterURL.setParameter("javax.portlet.action", "doView");
    renderRequest.setAttribute("customersFilterURL", customersFilterURL.toString());

    include(viewJSP, renderRequest, renderResponse);
}