Search in sources :

Example 46 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class ArticleQueryService method getAuthor.

/**
     * Gets the specified article's author.
     *
     * <p>
     * The specified article has a property {@value Article#ARTICLE_AUTHOR_EMAIL}, this method will use this property to
     * get a user from users.
     * </p>
     *
     * <p>
     * If can't find the specified article's author (i.e. the author has been removed by administrator), returns
     * administrator.
     * </p>
     *
     * @param article the specified article
     * @return user, {@code null} if not found
     * @throws ServiceException service exception
     */
public JSONObject getAuthor(final JSONObject article) throws ServiceException {
    try {
        final String email = article.getString(Article.ARTICLE_AUTHOR_EMAIL);
        JSONObject ret = userRepository.getByEmail(email);
        if (null == ret) {
            LOGGER.log(Level.WARN, "Gets author of article failed, assumes the administrator is the author of this article[id={0}]", article.getString(Keys.OBJECT_ID));
            // This author may be deleted by admin, use admin as the author
            // of this article
            ret = userRepository.getAdmin();
        }
        return ret;
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID));
        throw new ServiceException(e);
    } catch (final JSONException e) {
        LOGGER.log(Level.ERROR, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID));
        throw new ServiceException(e);
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException)

Example 47 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class ArticleQueryService method getArticlesByTag.

/**
     * Gets a list of published articles with the specified tag id, current page number and page size.
     *
     * @param tagId the specified tag id
     * @param currentPageNum the specified current page number
     * @param pageSize the specified page size
     * @return a list of articles, returns an empty list if not found
     * @throws ServiceException service exception
     */
public List<JSONObject> getArticlesByTag(final String tagId, final int currentPageNum, final int pageSize) throws ServiceException {
    try {
        JSONObject result = tagArticleRepository.getByTagId(tagId, currentPageNum, pageSize);
        final JSONArray tagArticleRelations = result.getJSONArray(Keys.RESULTS);
        if (0 == tagArticleRelations.length()) {
            return Collections.emptyList();
        }
        final Set<String> articleIds = new HashSet<String>();
        for (int i = 0; i < tagArticleRelations.length(); i++) {
            final JSONObject tagArticleRelation = tagArticleRelations.getJSONObject(i);
            final String articleId = tagArticleRelation.getString(Article.ARTICLE + "_" + Keys.OBJECT_ID);
            articleIds.add(articleId);
        }
        final List<JSONObject> ret = new ArrayList<JSONObject>();
        final Query query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)).setPageCount(1).index(Article.ARTICLE_PERMALINK);
        result = articleRepository.get(query);
        final JSONArray articles = result.getJSONArray(Keys.RESULTS);
        for (int i = 0; i < articles.length(); i++) {
            final JSONObject article = articles.getJSONObject(i);
            if (!article.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
                // Skips the unpublished article
                continue;
            }
            article.put(ARTICLE_CREATE_TIME, ((Date) article.get(ARTICLE_CREATE_DATE)).getTime());
            ret.add(article);
        }
        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets articles by tag[id=" + tagId + "] failed", e);
        throw new ServiceException(e);
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) HashSet(java.util.HashSet)

Example 48 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class CommentMgmtService method addArticleComment.

/**
     * Adds an article comment with the specified request json object.
     *
     * @param requestJSONObject the specified request json object, for example,      <pre>
     * {
     *     "oId": "", // article id
     *     "commentName": "",
     *     "commentEmail": "",
     *     "commentURL": "", // optional
     *     "commentContent": "",
     *     "commentOriginalCommentId": "" // optional
     * }
     * </pre>
     *
     * @return add result, for example,      <pre>
     * {
     *     "oId": "", // generated comment id
     *     "commentDate": "", // format: yyyy-MM-dd HH:mm:ss
     *     "commentOriginalCommentName": "" // optional, corresponding to argument "commentOriginalCommentId"
     *     "commentThumbnailURL": "",
     *     "commentSharpURL": "",
     *     "commentContent": "", // processed XSS HTML
     *     "commentName": "", // processed XSS
     *     "commentURL": "", // optional
     *     "isReply": boolean,
     *     "article": {},
     *     "commentOriginalCommentId": "", // optional
     *     "commentable": boolean,
     *     "permalink": "" // article.articlePermalink
     * }
     * </pre>
     *
     * @throws ServiceException service exception
     */
public JSONObject addArticleComment(final JSONObject requestJSONObject) throws ServiceException {
    final JSONObject ret = new JSONObject();
    ret.put(Common.IS_REPLY, false);
    final Transaction transaction = commentRepository.beginTransaction();
    try {
        final String articleId = requestJSONObject.getString(Keys.OBJECT_ID);
        final JSONObject article = articleRepository.get(articleId);
        ret.put(Article.ARTICLE, article);
        final String commentName = requestJSONObject.getString(Comment.COMMENT_NAME);
        final String commentEmail = requestJSONObject.getString(Comment.COMMENT_EMAIL).trim().toLowerCase();
        final String commentURL = requestJSONObject.optString(Comment.COMMENT_URL);
        final String commentContent = requestJSONObject.getString(Comment.COMMENT_CONTENT);
        final String originalCommentId = requestJSONObject.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID);
        ret.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, originalCommentId);
        // Step 1: Add comment
        final JSONObject comment = new JSONObject();
        comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, "");
        comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
        JSONObject originalComment = null;
        comment.put(Comment.COMMENT_NAME, commentName);
        comment.put(Comment.COMMENT_EMAIL, commentEmail);
        comment.put(Comment.COMMENT_URL, commentURL);
        comment.put(Comment.COMMENT_CONTENT, commentContent);
        comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, requestJSONObject.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID));
        comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, requestJSONObject.optString(Comment.COMMENT_ORIGINAL_COMMENT_NAME));
        final JSONObject preference = preferenceQueryService.getPreference();
        final Date date = new Date();
        comment.put(Comment.COMMENT_DATE, date);
        ret.put(Comment.COMMENT_DATE, DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
        ret.put("commentDate2", date);
        ret.put(Common.COMMENTABLE, preference.getBoolean(Option.ID_C_COMMENTABLE) && article.getBoolean(Article.ARTICLE_COMMENTABLE));
        ret.put(Common.PERMALINK, article.getString(Article.ARTICLE_PERMALINK));
        ret.put(Comment.COMMENT_NAME, commentName);
        ret.put(Comment.COMMENT_CONTENT, commentContent);
        ret.put(Comment.COMMENT_URL, commentURL);
        if (!Strings.isEmptyOrNull(originalCommentId)) {
            originalComment = commentRepository.get(originalCommentId);
            if (null != originalComment) {
                comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, originalCommentId);
                final String originalCommentName = originalComment.getString(Comment.COMMENT_NAME);
                comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
                ret.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
                ret.put(Common.IS_REPLY, true);
            } else {
                LOGGER.log(Level.WARN, "Not found orginal comment[id={0}] of reply[name={1}, content={2}]", new String[] { originalCommentId, commentName, commentContent });
            }
        }
        setCommentThumbnailURL(comment);
        ret.put(Comment.COMMENT_THUMBNAIL_URL, comment.getString(Comment.COMMENT_THUMBNAIL_URL));
        // Sets comment on article....
        comment.put(Comment.COMMENT_ON_ID, articleId);
        comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE);
        final String commentId = Ids.genTimeMillisId();
        comment.put(Keys.OBJECT_ID, commentId);
        ret.put(Keys.OBJECT_ID, commentId);
        final String commentSharpURL = Comments.getCommentSharpURLForArticle(article, commentId);
        comment.put(Comment.COMMENT_SHARP_URL, commentSharpURL);
        ret.put(Comment.COMMENT_SHARP_URL, commentSharpURL);
        commentRepository.add(comment);
        // Step 2: Update article comment count
        articleMgmtService.incArticleCommentCount(articleId);
        // Step 3: Update blog statistic comment count
        statisticMgmtService.incBlogCommentCount();
        statisticMgmtService.incPublishedBlogCommentCount();
        // Step 4: Send an email to admin
        try {
            sendNotificationMail(article, comment, originalComment, preference);
        } catch (final Exception e) {
            LOGGER.log(Level.WARN, "Send mail failed", e);
        }
        // Step 5: Fire add comment event
        final JSONObject eventData = new JSONObject();
        eventData.put(Comment.COMMENT, comment);
        eventData.put(Article.ARTICLE, article);
        eventManager.fireEventSynchronously(new Event<JSONObject>(EventTypes.ADD_COMMENT_TO_ARTICLE, eventData));
        transaction.commit();
    } catch (final Exception e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new ServiceException(e);
    }
    return ret;
}
Also used : JSONObject(org.json.JSONObject) Transaction(org.b3log.latke.repository.Transaction) ServiceException(org.b3log.latke.service.ServiceException) Date(java.util.Date) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) RepositoryException(org.b3log.latke.repository.RepositoryException) IOException(java.io.IOException)

Example 49 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class PageQueryService method getPages.

/**
     * Gets pages by the specified request json object.
     * 
     * @param requestJSONObject the specified request json object, for example,
     * <pre>
     * {
     *     "paginationCurrentPageNum": 1,
     *     "paginationPageSize": 20,
     *     "paginationWindowSize": 10
     * }, see {@link Pagination} for more details
     * </pre>
     * @return for example,
     * <pre>
     * {
     *     "pagination": {
     *         "paginationPageCount": 100,
     *         "paginationPageNums": [1, 2, 3, 4, 5]
     *     },
     *     "pages": [{
     *         "oId": "",
     *         "pageTitle": "",
     *         "pageCommentCount": int,
     *         "pageOrder": int,
     *         "pagePermalink": "",
     *         "pageCommentable": boolean,
     *         "pageType": "",
     *         "pageOpenTarget": ""
     *      }, ....]
     * }
     * </pre>
     * @throws ServiceException service exception
     * @see Pagination
     */
public JSONObject getPages(final JSONObject requestJSONObject) throws ServiceException {
    final JSONObject ret = new JSONObject();
    try {
        final int currentPageNum = requestJSONObject.getInt(Pagination.PAGINATION_CURRENT_PAGE_NUM);
        final int pageSize = requestJSONObject.getInt(Pagination.PAGINATION_PAGE_SIZE);
        final int windowSize = requestJSONObject.getInt(Pagination.PAGINATION_WINDOW_SIZE);
        final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).addSort(Page.PAGE_ORDER, SortDirection.ASCENDING).setPageCount(1);
        final JSONObject result = pageRepository.get(query);
        final int pageCount = result.getJSONObject(Pagination.PAGINATION).getInt(Pagination.PAGINATION_PAGE_COUNT);
        final JSONObject pagination = new JSONObject();
        final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
        pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
        pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
        final JSONArray pages = result.getJSONArray(Keys.RESULTS);
        for (int i = 0; i < pages.length(); i++) {
            // remove unused properties
            final JSONObject page = pages.getJSONObject(i);
            page.remove(Page.PAGE_CONTENT);
        }
        ret.put(Pagination.PAGINATION, pagination);
        ret.put(Page.PAGES, pages);
        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets pages failed", e);
        throw new ServiceException(e);
    }
}
Also used : JSONObject(org.json.JSONObject) Query(org.b3log.latke.repository.Query) ServiceException(org.b3log.latke.service.ServiceException) JSONArray(org.json.JSONArray) ServiceException(org.b3log.latke.service.ServiceException)

Example 50 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class PluginQueryService method getPlugins.

/**
     * Gets plugins by the specified request json object.
     *
     * @param requestJSONObject the specified request json object, for example,
     * <pre>
     * {
     *     "paginationCurrentPageNum": 1,
     *     "paginationPageSize": 20,
     *     "paginationWindowSize": 10,
     * }, see {@link Pagination} for more details
     * </pre>
     * @return for example,
     * <pre>
     * {
     *     "pagination": {
     *         "paginationPageCount": 100,
     *         "paginationPageNums": [1, 2, 3, 4, 5]
     *     },
     *     "plugins": [{
     *         "name": "",
     *         "version": "",
     *         "author": "",
     *         "status": "", // Enumeration name of {@link org.b3log.latke.plugin.PluginStatus}
     *      }, ....]
     * }
     * </pre>
     * @throws ServiceException service exception
     * @see Pagination
     */
public JSONObject getPlugins(final JSONObject requestJSONObject) throws ServiceException {
    final JSONObject ret = new JSONObject();
    try {
        final int currentPageNum = requestJSONObject.getInt(Pagination.PAGINATION_CURRENT_PAGE_NUM);
        final int pageSize = requestJSONObject.getInt(Pagination.PAGINATION_PAGE_SIZE);
        final int windowSize = requestJSONObject.getInt(Pagination.PAGINATION_WINDOW_SIZE);
        final List<JSONObject> pluginJSONObjects = new ArrayList<JSONObject>();
        final List<AbstractPlugin> plugins = pluginManager.getPlugins();
        for (final AbstractPlugin plugin : plugins) {
            final JSONObject jsonObject = plugin.toJSONObject();
            pluginJSONObjects.add(jsonObject);
        }
        final int pageCount = (int) Math.ceil((double) pluginJSONObjects.size() / (double) pageSize);
        final JSONObject pagination = new JSONObject();
        ret.put(Pagination.PAGINATION, pagination);
        final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
        pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
        pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
        final int start = pageSize * (currentPageNum - 1);
        int end = start + pageSize;
        end = end > pluginJSONObjects.size() ? pluginJSONObjects.size() : end;
        ret.put(Plugin.PLUGINS, pluginJSONObjects.subList(start, end));
        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets plugins failed", e);
        throw new ServiceException(e);
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) ArrayList(java.util.ArrayList) AbstractPlugin(org.b3log.latke.plugin.AbstractPlugin) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) RepositoryException(org.b3log.latke.repository.RepositoryException)

Aggregations

ServiceException (org.b3log.latke.service.ServiceException)102 JSONObject (org.json.JSONObject)91 JSONException (org.json.JSONException)45 RepositoryException (org.b3log.latke.repository.RepositoryException)34 Transaction (org.b3log.latke.repository.Transaction)31 RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)23 JSONArray (org.json.JSONArray)17 JSONRenderer (org.b3log.latke.servlet.renderer.JSONRenderer)16 EventException (org.b3log.latke.event.EventException)14 IOException (java.io.IOException)11 ParseException (java.text.ParseException)10 ArrayList (java.util.ArrayList)8 Query (org.b3log.latke.repository.Query)8 Date (java.util.Date)7 AbstractFreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer)6 Template (freemarker.template.Template)3 FreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer)3 ArchiveDate (org.b3log.solo.model.ArchiveDate)3 URL (java.net.URL)2 HashMap (java.util.HashMap)2