Example usage for com.liferay.portal.kernel.search SearchContext setKeywords

List of usage examples for com.liferay.portal.kernel.search SearchContext setKeywords

Introduction

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

Prototype

public void setKeywords(String keywords) 

Source Link

Usage

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 {/*from www .  ja  v  a 2 s  .  c  om*/
        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);/* w  w  w.  j  av a  2 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);
}