添加帖子是否展示的功能(三)查询优选贴、关注贴、城市贴、标签贴、近期热议、随便看看、PerfectArticle、关注标签

查询

"/perfect" 优选贴

IndexProcessor.java

@RequestProcessing(value = "/perfect", method = HttpMethod.GET)
    @Before({StopwatchStartAdvice.class, AnonymousViewCheck.class})
    @After({PermissionGrant.class, StopwatchEndAdvice.class})
    public void showPerfectArticles(final RequestContext context) {
......

        final JSONObject result = articleQueryService.getPerfectArticles(pageNum, pageSize);
......
        
    }

ArticleQueryService.java

public JSONObject getPerfectArticles(final int currentPageNum, final int fetchSize) {
        final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
                setPage(currentPageNum, fetchSize);
        /**
         * create by: qiankunpingtai
         * create time: 2019/5/14 22:45
         * website:https://qiankunpingtai.cn
         * description:
         * 过滤不展示的帖子
         */
        query.setFilter(CompositeFilterOperator.and(
                new PropertyFilter(Article.ARTICLE_PERFECT, FilterOperator.EQUAL, Article.ARTICLE_PERFECT_C_PERFECT),
                new PropertyFilter(Article.ARTICLE_DISPLAYABLE, FilterOperator.NOT_EQUAL, Article.ARTICLE_DISPLAYABLE_NOT)));
        final JSONObject ret = new JSONObject();

        JSONObject result;
        try {
            Stopwatchs.start("Query perfect articles");

            result = articleRepository.get(query);
        } catch (final RepositoryException e) {
            LOGGER.log(Level.ERROR, "Gets articles failed", e);

            return null;
        } finally {
            Stopwatchs.end();
        }

        final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT);

        final JSONObject pagination = new JSONObject();
        ret.put(Pagination.PAGINATION, pagination);

        final int windowSize = Symphonys.ARTICLE_LIST_WIN_SIZE;

        final List<Integer> pageNums = Paginator.paginate(currentPageNum, fetchSize, pageCount, windowSize);
        pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
        pagination.put(Pagination.PAGINATION_PAGE_NUMS, (Object) pageNums);

        final JSONArray data = result.optJSONArray(Keys.RESULTS);
        final List<JSONObject> articles = CollectionUtils.jsonArrayToList(data);
        organizeArticles(articles);

        //final Integer participantsCnt = Symphonys.getInt("latestArticleParticipantsCnt");
        //genParticipants(articles, participantsCnt);
        ret.put(Article.ARTICLES, (Object) articles);

        return ret;
    }

"/watch", "/watch/users" 关注贴

IndexProcessor.java

    @RequestProcessing(value = {"/watch", "/watch/users"}, method = HttpMethod.GET)
    @Before({StopwatchStartAdvice.class, AnonymousViewCheck.class})
    @After({PermissionGrant.class, StopwatchEndAdvice.class})
    public void showWatch(final RequestContext context) {
......
                    final List<JSONObject> followingTagArticles = articleQueryService.getFollowingTagArticles(user.optString(Keys.OBJECT_ID), 1, pageSize);
......                   
    }

ArticleQueryService.java

    public List<JSONObject> getFollowingTagArticles(final String userId, final int currentPageNum, final int pageSize) {
...... 
        return getArticlesByTags(currentPageNum, pageSize, articleFields, tags.toArray(new JSONObject[0]));
    }
    public List<JSONObject> getArticlesByTags(final int currentPageNum, final int pageSize,
                                              final List<String> articleFields, final JSONObject... tags) {
        try {
            final List<Filter> filters = new ArrayList<>();
            for (final JSONObject tag : tags) {
                filters.add(new PropertyFilter(Tag.TAG + '_' + Keys.OBJECT_ID, FilterOperator.EQUAL, tag.optString(Keys.OBJECT_ID)));
            }

            Filter filter;
            if (filters.size() >= 2) {
                filter = new CompositeFilter(CompositeFilterOperator.OR, filters);
            } else {
                filter = filters.get(0);
            }
            /**
             * create by: qiankunpingtai
             * create time: 2019/5/14 22:45
             * website:https://qiankunpingtai.cn
             * description:
             * 过滤不展示的帖子
             */
            // XXX: 这里的分页是有问题的,后面取文章的时候会少(因为一篇文章可以有多个标签,但是文章 id 一样)
            Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
                    .setFilter(CompositeFilterOperator.and(filter,
                            new PropertyFilter(Article.ARTICLE_DISPLAYABLE, FilterOperator.NOT_EQUAL, Article.ARTICLE_DISPLAYABLE_NOT)))
                    .setPageCount(1).setPage(currentPageNum, pageSize);

            JSONObject result = tagArticleRepository.get(query);
            final JSONArray tagArticleRelations = result.optJSONArray(Keys.RESULTS);

            final Set<String> articleIds = new HashSet<>();
            for (int i = 0; i < tagArticleRelations.length(); i++) {
                articleIds.add(tagArticleRelations.optJSONObject(i).optString(Article.ARTICLE + '_' + Keys.OBJECT_ID));
            }

            query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)).
                    addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
            for (final String articleField : articleFields) {
                query.select(articleField);
            }

            result = articleRepository.get(query);

            final List<JSONObject> ret = CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));
            organizeArticles(ret);

            return ret;
        } catch (final RepositoryException e) {
            LOGGER.log(Level.ERROR, "Gets articles by tags [tagLength=" + tags.length + "] failed", e);

            return Collections.emptyList();
        }
    }
"/city/{city}", "/city/{city}/articles"城市帖

CityProcessor.java

@RequestProcessing(value = {"/city/{city}", "/city/{city}/articles"}, method = HttpMethod.GET)
    @Before({StopwatchStartAdvice.class, LoginCheck.class})
    @After({PermissionGrant.class, StopwatchEndAdvice.class})
    public void showCityArticles(final RequestContext context) {
......
            articles = articleQueryService.getArticlesByCity(queryCity, pageNum, pageSize);
......   
    }

ArticleQueryService.java

    public List<JSONObject> getArticlesByCity(final String city, final int currentPageNum, final int pageSize) {
        try {
            /**
             * create by: qiankunpingtai
             * create time: 2019/5/14 22:45
             * website:https://qiankunpingtai.cn
             * description:
             * 过滤不展示的帖子
             */
            final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
                    .setFilter(CompositeFilterOperator.and(new PropertyFilter(Article.ARTICLE_CITY, FilterOperator.EQUAL, city),
                    new PropertyFilter(Article.ARTICLE_DISPLAYABLE, FilterOperator.NOT_EQUAL, Article.ARTICLE_DISPLAYABLE_NOT)))
                    .setPageCount(1).setPage(currentPageNum, pageSize);

            final JSONObject result = articleRepository.get(query);

            final List<JSONObject> ret = CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));
            organizeArticles(ret);

            final Integer participantsCnt = Symphonys.ARTICLE_LIST_PARTICIPANTS_CNT;
            genParticipants(ret, participantsCnt);

            return ret;
        } catch (final RepositoryException e) {
            LOGGER.log(Level.ERROR, "Gets articles by city [" + city + "] failed", e);

            return Collections.emptyList();
        }
    }
"/tag/{tagURI}", "/tag/{tagURI}/hot", "/tag/{tagURI}/good", "/tag/{tagURI}/reply","/tag/{tagURI}/perfect"标签贴

TagProcessor.java

    @RequestProcessing(value = {"/tag/{tagURI}", "/tag/{tagURI}/hot", "/tag/{tagURI}/good", "/tag/{tagURI}/reply",
            "/tag/{tagURI}/perfect"}, method = HttpMethod.GET)
    @Before({StopwatchStartAdvice.class, AnonymousViewCheck.class})
    @After({PermissionGrant.class, StopwatchEndAdvice.class})
    public void showTagArticles(final RequestContext context) {
        final String tagURI = context.pathVar("tagURI");
        final HttpServletRequest request = context.getRequest();

        final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "tag-articles.ftl");
        final Map<String, Object> dataModel = renderer.getDataModel();
        dataModelService.fillHeaderAndFooter(context, dataModel);
        final int pageNum = Paginator.getPage(request);
        int pageSize = Symphonys.ARTICLE_LIST_CNT;

        final JSONObject user = Sessions.getUser();
        if (null != user) {
            pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE);

            if (!UserExt.finshedGuide(user)) {
                context.sendRedirect(Latkes.getServePath() + "/guide");

                return;
            }
        }

        final JSONObject tag = tagQueryService.getTagByURI(tagURI);
        if (null == tag) {
            context.sendError(HttpServletResponse.SC_NOT_FOUND);

            return;
        }
        tag.put(Common.IS_RESERVED, tagQueryService.isReservedTag(tag.optString(Tag.TAG_TITLE)));
        dataModel.put(Tag.TAG, tag);
        final String tagId = tag.optString(Keys.OBJECT_ID);
        final List<JSONObject> relatedTags = tagQueryService.getRelatedTags(tagId, Symphonys.TAG_RELATED_TAGS_CNT);
        tag.put(Tag.TAG_T_RELATED_TAGS, (Object) relatedTags);

        final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
        if (isLoggedIn) {
            final JSONObject currentUser = Sessions.getUser();
            final String followerId = currentUser.optString(Keys.OBJECT_ID);

            final boolean isFollowing = followQueryService.isFollowing(followerId, tagId, Follow.FOLLOWING_TYPE_C_TAG);
            dataModel.put(Common.IS_FOLLOWING, isFollowing);
        }

        String sortModeStr = StringUtils.substringAfter(context.requestURI(), "/tag/" + tagURI);
        int sortMode;
        switch (sortModeStr) {
            case "":
                sortMode = 0;

                break;
            case "/hot":
                sortMode = 1;

                break;
            case "/good":
                sortMode = 2;

                break;
            case "/reply":
                sortMode = 3;

                break;
            case "/perfect":
                sortMode = 4;

                break;
            default:
                sortMode = 0;
        }

        final List<JSONObject> articles = articleQueryService.getArticlesByTag(sortMode, tag, pageNum, pageSize);
        dataModel.put(Article.ARTICLES, articles);
        final JSONObject tagCreator = tagQueryService.getCreator(tagId);
        tag.put(Tag.TAG_T_CREATOR_THUMBNAIL_URL, tagCreator.optString(Tag.TAG_T_CREATOR_THUMBNAIL_URL));
        tag.put(Tag.TAG_T_CREATOR_NAME, tagCreator.optString(Tag.TAG_T_CREATOR_NAME));
        tag.put(Tag.TAG_T_PARTICIPANTS, (Object) tagQueryService.getParticipants(tagId, Symphonys.ARTICLE_LIST_PARTICIPANTS_CNT));

        final int tagRefCnt = tag.getInt(Tag.TAG_REFERENCE_CNT);
        final int pageCount = (int) Math.ceil(tagRefCnt / (double) pageSize);
        final int windowSize = Symphonys.ARTICLE_LIST_WIN_SIZE;
        final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
        if (!pageNums.isEmpty()) {
            dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
            dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
        }

        dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
        dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
        dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);

        dataModelService.fillRandomArticles(dataModel);
        dataModelService.fillSideHotArticles(dataModel);
        dataModelService.fillSideTags(dataModel);
        dataModelService.fillLatestCmts(dataModel);

        dataModel.put(Common.CURRENT, StringUtils.substringAfter(URLs.decode(context.requestURI()),
                "/tag/" + tagURI));
    }

ArticleQueryService.java

public List<JSONObject> getArticlesByTag(final int sortMode, final JSONObject tag, final int currentPageNum, final int pageSize) {
        try {
            /**
             * create by: qiankunpingtai
             * create time: 2019/5/14 22:45
             * website:https://qiankunpingtai.cn
             * description:
             * 过滤不展示的帖子
             * 这个地方过滤的字段在多个表中,只能使用原生sql进行处理
             *
             */
            StringBuffer queryCount=new StringBuffer("select count(0) ").append(" from ");
            StringBuffer queryList=new StringBuffer("select symphony_article.oId").append(" from ");
            StringBuffer queryStr=new StringBuffer(articleRepository.getName()+" symphony_article, ").append(tagArticleRepository.getName()+" symphony_tag_article ");
            queryStr.append("where symphony_article.oId=symphony_tag_article.article_oId and symphony_article.articleDisplayable != ? ");
            switch (sortMode) {
                case 0:
                    queryStr.append(" and ").append( "symphony_tag_article."+Tag.TAG + '_' + Keys.OBJECT_ID).append("=").append(tag.optString(Keys.OBJECT_ID))
                            .append(" order by ").append("symphony_tag_article."+Keys.OBJECT_ID+" ").append(" desc ");

                    break;
                case 1:
                    queryStr.append(" and ").append( "symphony_tag_article."+Tag.TAG + '_' + Keys.OBJECT_ID).append("=").append(tag.optString(Keys.OBJECT_ID))
                            .append(" order by ").append("symphony_tag_article."+Article.ARTICLE_COMMENT_CNT+" ").append(" desc ")
                            .append(",").append("symphony_tag_article."+Keys.OBJECT_ID+" ").append(" desc ");
                    break;
                case 2:
                    queryStr.append(" and ").append( "symphony_tag_article."+Tag.TAG + '_' + Keys.OBJECT_ID).append("=").append(tag.optString(Keys.OBJECT_ID))
                            .append(" order by ").append("symphony_tag_article."+Article.REDDIT_SCORE+" ").append(" desc ")
                            .append(",").append("symphony_tag_article."+Keys.OBJECT_ID+" ").append(" desc ");
                    break;
                case 3:
                    queryStr.append(" and ").append( "symphony_tag_article."+Tag.TAG + '_' + Keys.OBJECT_ID).append("=").append(tag.optString(Keys.OBJECT_ID))
                            .append(" order by ").append("symphony_tag_article."+Article.ARTICLE_LATEST_CMT_TIME+" ").append(" desc ")
                            .append(",").append("symphony_tag_article."+Keys.OBJECT_ID+" ").append(" desc ");
                    break;
                case 4:
                    queryStr.append(" and ").append( "symphony_tag_article."+Tag.TAG + '_' + Keys.OBJECT_ID).append("=").append(tag.optString(Keys.OBJECT_ID))
                            .append(" order by ").append("symphony_tag_article."+Article.ARTICLE_PERFECT+" ").append(" desc ")
                            .append(",").append("symphony_tag_article."+Keys.OBJECT_ID+" ").append(" desc ");
                    break;
                default:
                    LOGGER.warn("Unknown sort mode [" + sortMode + "]");
                    queryStr.append(" and ").append( "symphony_tag_article."+Tag.TAG + '_' + Keys.OBJECT_ID).append("=").append(tag.optString(Keys.OBJECT_ID))
                            .append(" order by ").append(",").append("symphony_tag_article."+Keys.OBJECT_ID+" ").append(" desc ");

            }
            final List<JSONObject> tagArticleTotalCount=articleRepository.select(queryCount.append(queryStr.toString()).toString(),Article.ARTICLE_DISPLAYABLE_NOT);
            tag.put(Tag.TAG_REFERENCE_CNT,tagArticleTotalCount==null?0:tagArticleTotalCount.get(0).optInt("count(0)"));
            queryStr.append(" limit ").append((currentPageNum-1)*pageSize).append(",")
                    .append(currentPageNum*pageSize);
            final List<JSONObject> tagArticleRelations=articleRepository.select(queryList.append(queryStr.toString()).toString(),Article.ARTICLE_DISPLAYABLE_NOT);
            final List<String> articleIds = new ArrayList<>();
            for (int i = 0; i < tagArticleRelations.size(); i++) {
                articleIds.add(tagArticleRelations.get(i).optString(Keys.OBJECT_ID));
            }
            Query query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds));
            addListProjections(query);

            JSONObject result = articleRepository.get(query);

            final List<JSONObject> ret = CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));

            switch (sortMode) {
                default:
                    LOGGER.warn("Unknown sort mode [" + sortMode + "]");
                case 0:
                    Collections.sort(ret, (o1, o2) -> o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID)));

                    break;
                case 1:
                    Collections.sort(ret, (o1, o2) -> {
                        final int v = o2.optInt(Article.ARTICLE_COMMENT_CNT) - o1.optInt(Article.ARTICLE_COMMENT_CNT);
                        if (0 == v) {
                            return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID));
                        }

                        return v > 0 ? 1 : -1;
                    });

                    break;
                case 2:
                    Collections.sort(ret, (o1, o2) -> {
                        final double v = o2.optDouble(Article.REDDIT_SCORE) - o1.optDouble(Article.REDDIT_SCORE);
                        if (0 == v) {
                            return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID));
                        }

                        return v > 0 ? 1 : -1;
                    });

                    break;
                case 3:
                    Collections.sort(ret, (o1, o2) -> {
                        final long v = (o2.optLong(Article.ARTICLE_LATEST_CMT_TIME)
                                - o1.optLong(Article.ARTICLE_LATEST_CMT_TIME));
                        if (0 == v) {
                            return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID));
                        }

                        return v > 0 ? 1 : -1;
                    });

                    break;
                case 4:
                    Collections.sort(ret, (o1, o2) -> {
                        final long v = (o2.optLong(Article.ARTICLE_PERFECT) - o1.optLong(Article.ARTICLE_PERFECT));
                        if (0 == v) {
                            return o2.optString(Keys.OBJECT_ID).compareTo(o1.optString(Keys.OBJECT_ID));
                        }

                        return v > 0 ? 1 : -1;
                    });

                    break;
            }

            organizeArticles(ret);

            final Integer participantsCnt = Symphonys.ARTICLE_LIST_PARTICIPANTS_CNT;
            genParticipants(ret, participantsCnt);

            return ret;
        } catch (final RepositoryException e) {
            LOGGER.log(Level.ERROR, "Gets articles by tag [tagTitle=" + tag.optString(Tag.TAG_TITLE) + "] failed", e);

            return Collections.emptyList();
        }
近期热议

CacheMgmtService.java

public void refreshCache() {
        final String lockName = "refreshCaches";
        if (!lock(lockName)) {
            return;
        }
        try {
            LOGGER.info("Refreshing cache");
            domainCache.loadDomains();
            articleCache.loadPerfectArticles();
            articleCache.loadSideHotArticles();
            articleCache.loadSideRandomArticles();
            tagCache.loadTags();
            final StatisticProcessor statisticProcessor = BeanManager.getInstance().getReference(StatisticProcessor.class);
            statisticProcessor.loadStatData();
            userQueryService.loadUserNames();
            statusReport();
            LOGGER.info("Refreshed cache");
        } finally {
            unlock(lockName);
        }
    }

ArticleCache.java

    public void loadSideHotArticles() {
        final BeanManager beanManager = BeanManager.getInstance();
        final ArticleRepository articleRepository = beanManager.getReference(ArticleRepository.class);
        final ArticleQueryService articleQueryService = beanManager.getReference(ArticleQueryService.class);

        Stopwatchs.start("Load side hot articles");
        try {
            final String id = String.valueOf(DateUtils.addDays(new Date(), -7).getTime());
            final Query query = new Query().addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING).
                    addSort(Keys.OBJECT_ID, SortDirection.ASCENDING).
                    setPage(1, Symphonys.SIDE_HOT_ARTICLES_CNT);

            final List<Filter> filters = new ArrayList<>();
            filters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, id));
            filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION));
            filters.add(new PropertyFilter(Article.ARTICLE_TAGS, FilterOperator.NOT_EQUAL, Tag.TAG_TITLE_C_SANDBOX));
            /**
             * create by: qiankunpingtai
             * create time: 2019/5/14 22:45
             * website:https://qiankunpingtai.cn
             * description:
             * 过滤不展示的帖子
             */
            filters.add( new PropertyFilter(Article.ARTICLE_DISPLAYABLE, FilterOperator.NOT_EQUAL, Article.ARTICLE_DISPLAYABLE_NOT));
            query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).
                    select(Article.ARTICLE_TITLE, Article.ARTICLE_PERMALINK, Article.ARTICLE_AUTHOR_ID, Article.ARTICLE_ANONYMOUS);

            final JSONObject result = articleRepository.get(query);
            final List<JSONObject> articles = CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));
            articleQueryService.organizeArticles(articles);

            SIDE_HOT_ARTICLES.clear();
            SIDE_HOT_ARTICLES.addAll(articles);
        } catch (final RepositoryException e) {
            LOGGER.log(Level.ERROR, "Loads side hot articles failed", e);
        } finally {
            Stopwatchs.end();
        }
    }
随便看看

ArticleCache.java

    public void loadSideRandomArticles() {
 ......
            final List<JSONObject> articles = articleRepository.getRandomly(size * 5);
 ......
    }

ArticleRepository.java

    @Override
    public List<JSONObject> getRandomly(final int fetchSize) throws RepositoryException {
        final List<JSONObject> ret = new ArrayList<>();

        final double mid = Math.random();
        /**
         * create by: qiankunpingtai
         * create time: 2019/5/14 22:45
         * website:https://qiankunpingtai.cn
         * description:
         * 过滤不展示的帖子
         */
        Query query = new Query().
                setFilter(CompositeFilterOperator.and(new PropertyFilter(Article.ARTICLE_RANDOM_DOUBLE, FilterOperator.GREATER_THAN_OR_EQUAL, mid),
                        new PropertyFilter(Article.ARTICLE_RANDOM_DOUBLE, FilterOperator.LESS_THAN_OR_EQUAL, mid),
                        new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.NOT_EQUAL, Article.ARTICLE_STATUS_C_INVALID),
                        new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION),
                        new PropertyFilter(Article.ARTICLE_DISPLAYABLE, FilterOperator.NOT_EQUAL, Article.ARTICLE_DISPLAYABLE_NOT))).
                select(Article.ARTICLE_TITLE, Article.ARTICLE_PERMALINK, Article.ARTICLE_AUTHOR_ID).
                setPage(1, fetchSize).setPageCount(1);
        final List<JSONObject> list1 = getList(query);
        ret.addAll(list1);

        final int reminingSize = fetchSize - list1.size();
        if (0 != reminingSize) { // Query for remains
            /**
             * create by: qiankunpingtai
             * create time: 2019/5/14 22:45
             * website:https://qiankunpingtai.cn
             * description:
             * 过滤不展示的帖子
             */
            query = new Query().
                    setFilter(CompositeFilterOperator.and(new PropertyFilter(Article.ARTICLE_RANDOM_DOUBLE, FilterOperator.GREATER_THAN_OR_EQUAL, 0D),
                            new PropertyFilter(Article.ARTICLE_RANDOM_DOUBLE, FilterOperator.LESS_THAN_OR_EQUAL, mid),
                            new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.NOT_EQUAL, Article.ARTICLE_STATUS_C_INVALID),
                            new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION),
                            new PropertyFilter(Article.ARTICLE_DISPLAYABLE, FilterOperator.NOT_EQUAL, Article.ARTICLE_DISPLAYABLE_NOT))).
                    select(Article.ARTICLE_TITLE, Article.ARTICLE_PERMALINK, Article.ARTICLE_AUTHOR_ID).
                    setPage(1, reminingSize).setPageCount(1);
            final List<JSONObject> list2 = getList(query);

            ret.addAll(list2);
        }

        return ret;
    }
PerfectArticle

ArticleCache.java

public void loadPerfectArticles() {
        final BeanManager beanManager = BeanManager.getInstance();
        final ArticleRepository articleRepository = beanManager.getReference(ArticleRepository.class);
        final ArticleQueryService articleQueryService = beanManager.getReference(ArticleQueryService.class);

        Stopwatchs.start("Query perfect articles");
        try {
            /**
             * create by: qiankunpingtai
             * create time: 2019/5/14 22:45
             * website:https://qiankunpingtai.cn
             * description:
             * 过滤不展示的帖子
             */
            final Query query = new Query().
                    addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).
                    setPageCount(1).setPage(1, 36);
            query.setFilter(CompositeFilterOperator.and(new PropertyFilter(Article.ARTICLE_PERFECT, FilterOperator.EQUAL, Article.ARTICLE_PERFECT_C_PERFECT),
                    new PropertyFilter(Article.ARTICLE_DISPLAYABLE, FilterOperator.NOT_EQUAL, Article.ARTICLE_DISPLAYABLE_NOT)));
            query.select(Keys.OBJECT_ID,
                    Article.ARTICLE_STICK,
                    Article.ARTICLE_CREATE_TIME,
                    Article.ARTICLE_UPDATE_TIME,
                    Article.ARTICLE_LATEST_CMT_TIME,
                    Article.ARTICLE_AUTHOR_ID,
                    Article.ARTICLE_TITLE,
                    Article.ARTICLE_STATUS,
                    Article.ARTICLE_VIEW_CNT,
                    Article.ARTICLE_TYPE,
                    Article.ARTICLE_PERMALINK,
                    Article.ARTICLE_TAGS,
                    Article.ARTICLE_LATEST_CMTER_NAME,
                    Article.ARTICLE_COMMENT_CNT,
                    Article.ARTICLE_ANONYMOUS,
                    Article.ARTICLE_PERFECT,
                    Article.ARTICLE_QNA_OFFER_POINT,
                    Article.ARTICLE_DISPLAYABLE);

            final JSONObject result = articleRepository.get(query);
            final List<JSONObject> articles = CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));

            articleQueryService.organizeArticles(articles);

            PERFECT_ARTICLES.clear();
            PERFECT_ARTICLES.addAll(articles);
        } catch (final RepositoryException e) {
            LOGGER.log(Level.ERROR, "Loads perfect articles failed", e);
        } finally {
            Stopwatchs.end();
        }
    }

关注标签

ArticleQueryService.java

public List<JSONObject> getArticlesByTags(final int currentPageNum, final int pageSize,
                                              final List<String> articleFields, final JSONObject... tags) {
        try {
            /**
             * create by: qiankunpingtai
             * create time: 2019/5/14 22:45
             * website:https://qiankunpingtai.cn
             * description:
             * 过滤不展示的帖子
             * 这个地方过滤的字段在多个表中,只能使用原生sql进行处理
             *
             */
            StringBuffer queryCount=new StringBuffer("select count(0) ").append(" from ");
            StringBuffer queryList=new StringBuffer("select symphony_article.oId ").append(" from ");
            StringBuffer queryStr=new StringBuffer(articleRepository.getName()+" symphony_article, ").append(tagArticleRepository.getName()+" symphony_tag_article ");
            queryStr.append(" where symphony_article.oId=symphony_tag_article.article_oId and symphony_article.articleDisplayable != ? ");
            if(tags!=null&&tags.length>0){
                queryStr.append(" and ").append( "symphony_tag_article."+Tag.TAG + '_' + Keys.OBJECT_ID).append(" in ( ");
                for(int i=0;i<tags.length; i++){
                    queryStr.append(" ").append(tags[i].optString(Keys.OBJECT_ID));
                    if(i<(tags.length-1)){
                        queryStr.append(",");
                    }
                }
                queryStr.append(")");
            }
            queryStr.append(" order by ").append("symphony_tag_article."+Keys.OBJECT_ID+" ").append(" desc ");
            final List<JSONObject> tagArticlesCount=articleRepository.
                    select(queryCount.append(queryStr.toString()).toString(),Article.ARTICLE_DISPLAYABLE_NOT);
            queryStr.append(" limit ").append((currentPageNum-1)*pageSize).append(",")
                    .append(currentPageNum*pageSize);
            final List<JSONObject> tagArticles=articleRepository.
                    select(queryList.append(queryStr.toString()).toString(),Article.ARTICLE_DISPLAYABLE_NOT);


            final Set<String> articleIds = new HashSet<>();
            for (int i = 0; i < tagArticles.size(); i++) {
                articleIds.add(tagArticles.get(i).optString( Keys.OBJECT_ID));
            }

            Query query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)).
                    addSort(Keys.OBJECT_ID, SortDirection.DESCENDING);
            for (final String articleField : articleFields) {
                query.select(articleField);
            }

            JSONObject result = articleRepository.get(query);

            final List<JSONObject> ret = CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));
            organizeArticles(ret);

            return ret;
        } catch (final RepositoryException e) {
            LOGGER.log(Level.ERROR, "Gets articles by tags [tagLength=" + tags.length + "] failed", e);

            return Collections.emptyList();
        }
    }

上一篇 添加帖子是否展示的功能(二)查询最新帖、领域贴、问答帖
下一篇 添加帖子是否展示的功能(四)algolia 、es、百度推送处理