Search in sources :

Example 1 with EventException

use of org.b3log.latke.event.EventException in project solo by b3log.

the class ArticleMgmtService method updateArticle.

/**
     * Updates an article by the specified request json object.
     *
     * @param requestJSONObject the specified request json object, for example,
     * <pre>
     * {
     *     "article": {
     *         "oId": "",
     *         "articleTitle": "",
     *         "articleAbstract": "",
     *         "articleContent": "",
     *         "articleTags": "tag1,tag2,tag3",
     *         "articlePermalink": "", // optional
     *         "articleIsPublished": boolean,
     *         "articleSignId": "", // optional
     *         "articleCommentable": boolean,
     *         "articleViewPwd": "",
     *         "articleEditorType": "" // optional, preference specified if not exists this key
     *     }
     * }
     * </pre>
     * @throws ServiceException service exception
     */
public void updateArticle(final JSONObject requestJSONObject) throws ServiceException {
    final JSONObject ret = new JSONObject();
    final Transaction transaction = articleRepository.beginTransaction();
    try {
        final JSONObject article = requestJSONObject.getJSONObject(ARTICLE);
        final String tagsString = article.optString(Article.ARTICLE_TAGS_REF);
        article.put(Article.ARTICLE_TAGS_REF, tagsString.replaceAll(",", ",").replaceAll("、", ","));
        final String articleId = article.getString(Keys.OBJECT_ID);
        // Set permalink
        final JSONObject oldArticle = articleRepository.get(articleId);
        final String permalink = getPermalinkForUpdateArticle(oldArticle, article, (Date) oldArticle.get(ARTICLE_CREATE_DATE));
        article.put(ARTICLE_PERMALINK, permalink);
        processTagsForArticleUpdate(oldArticle, article);
        if (!oldArticle.getString(Article.ARTICLE_PERMALINK).equals(permalink)) {
            // The permalink has been updated
            // Updates related comments' links
            processCommentsForArticleUpdate(article);
        }
        // Fill auto properties
        fillAutoProperties(oldArticle, article);
        // Set date
        article.put(ARTICLE_UPDATE_DATE, oldArticle.get(ARTICLE_UPDATE_DATE));
        final JSONObject preference = preferenceQueryService.getPreference();
        final Date date = new Date();
        // The article to update has no sign
        if (!article.has(Article.ARTICLE_SIGN_ID)) {
            article.put(Article.ARTICLE_SIGN_ID, "0");
        }
        if (article.getBoolean(ARTICLE_IS_PUBLISHED)) {
            // Publish it
            if (articleQueryService.hadBeenPublished(oldArticle)) {
                // Edit update date only for published article
                article.put(ARTICLE_UPDATE_DATE, date);
            } else {
                // This article is a draft and this is the first time to publish it
                article.put(ARTICLE_CREATE_DATE, date);
                article.put(ARTICLE_UPDATE_DATE, date);
                article.put(ARTICLE_HAD_BEEN_PUBLISHED, true);
            }
        } else {
            // Save as draft
            if (articleQueryService.hadBeenPublished(oldArticle)) {
                // Save update date only for published article
                article.put(ARTICLE_UPDATE_DATE, date);
            } else {
                // Reset create/update date to indicate this is an new draft
                article.put(ARTICLE_CREATE_DATE, date);
                article.put(ARTICLE_UPDATE_DATE, date);
            }
        }
        // Set editor type
        if (!article.has(Article.ARTICLE_EDITOR_TYPE)) {
            article.put(Article.ARTICLE_EDITOR_TYPE, preference.optString(Option.ID_C_EDITOR_TYPE));
        }
        final boolean publishNewArticle = !oldArticle.getBoolean(ARTICLE_IS_PUBLISHED) && article.getBoolean(ARTICLE_IS_PUBLISHED);
        // Set statistic
        if (publishNewArticle) {
            // This article is updated from unpublished to published
            statisticMgmtService.incPublishedBlogArticleCount();
            final int blogCmtCnt = statisticQueryService.getPublishedBlogCommentCount();
            final int articleCmtCnt = article.getInt(ARTICLE_COMMENT_COUNT);
            statisticMgmtService.setPublishedBlogCommentCount(blogCmtCnt + articleCmtCnt);
            final JSONObject author = userRepository.getByEmail(article.optString(Article.ARTICLE_AUTHOR_EMAIL));
            author.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, author.optInt(UserExt.USER_PUBLISHED_ARTICLE_COUNT) + 1);
            userRepository.update(author.optString(Keys.OBJECT_ID), author);
        }
        if (publishNewArticle) {
            incArchiveDatePublishedRefCount(articleId);
        }
        // Update
        final boolean postToCommunity = article.optBoolean(Common.POST_TO_COMMUNITY, true);
        // Do not persist this property
        article.remove(Common.POST_TO_COMMUNITY);
        articleRepository.update(articleId, article);
        // Restores the property
        article.put(Common.POST_TO_COMMUNITY, postToCommunity);
        if (publishNewArticle) {
            // Fire add article event
            final JSONObject eventData = new JSONObject();
            eventData.put(ARTICLE, article);
            eventData.put(Keys.RESULTS, ret);
            try {
                eventManager.fireEventSynchronously(new Event<JSONObject>(EventTypes.ADD_ARTICLE, eventData));
            } catch (final EventException e) {
                LOGGER.log(Level.ERROR, e.getMessage(), e);
            }
        } else {
            // Fire update article event
            final JSONObject eventData = new JSONObject();
            eventData.put(ARTICLE, article);
            eventData.put(Keys.RESULTS, ret);
            try {
                eventManager.fireEventSynchronously(new Event<JSONObject>(EventTypes.UPDATE_ARTICLE, eventData));
            } catch (final EventException e) {
                LOGGER.log(Level.ERROR, e.getMessage(), e);
            }
        }
        transaction.commit();
    } catch (final ServiceException e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        LOGGER.log(Level.ERROR, "Updates an article failed", e);
        throw e;
    } catch (final Exception e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        LOGGER.log(Level.ERROR, "Updates an article failed", e);
        throw new ServiceException(e.getMessage());
    }
}
Also used : JSONObject(org.json.JSONObject) Transaction(org.b3log.latke.repository.Transaction) ServiceException(org.b3log.latke.service.ServiceException) EventException(org.b3log.latke.event.EventException) Date(java.util.Date) ArchiveDate(org.b3log.solo.model.ArchiveDate) EventException(org.b3log.latke.event.EventException) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) ParseException(java.text.ParseException) RepositoryException(org.b3log.latke.repository.RepositoryException)

Example 2 with EventException

use of org.b3log.latke.event.EventException in project solo by b3log.

the class ArticleCommentReplyNotifier method action.

@Override
public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject eventData = event.getData();
    final JSONObject comment = eventData.optJSONObject(Comment.COMMENT);
    final JSONObject article = eventData.optJSONObject(Article.ARTICLE);
    LOGGER.log(Level.DEBUG, "Processing an event[type={0}, data={1}] in listener[className={2}]", new Object[] { event.getType(), eventData, ArticleCommentReplyNotifier.class.getName() });
    final String originalCommentId = comment.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID);
    if (Strings.isEmptyOrNull(originalCommentId)) {
        LOGGER.log(Level.DEBUG, "This comment[id={0}] is not a reply", comment.optString(Keys.OBJECT_ID));
        return;
    }
    if (Latkes.getServePath().contains("localhost")) {
        LOGGER.log(Level.INFO, "Solo runs on local server, so should not send mail");
        return;
    }
    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final PreferenceQueryService preferenceQueryService = beanManager.getReference(PreferenceQueryService.class);
    final CommentRepository commentRepository = beanManager.getReference(CommentRepositoryImpl.class);
    try {
        final String commentEmail = comment.getString(Comment.COMMENT_EMAIL);
        final JSONObject originalComment = commentRepository.get(originalCommentId);
        final String originalCommentEmail = originalComment.getString(Comment.COMMENT_EMAIL);
        if (originalCommentEmail.equalsIgnoreCase(commentEmail)) {
            return;
        }
        final JSONObject preference = preferenceQueryService.getPreference();
        if (null == preference) {
            throw new EventException("Not found preference");
        }
        final String blogTitle = preference.getString(Option.ID_C_BLOG_TITLE);
        final String adminEmail = preference.getString(Option.ID_C_ADMIN_EMAIL);
        final String commentContent = comment.getString(Comment.COMMENT_CONTENT);
        final String commentSharpURL = comment.getString(Comment.COMMENT_SHARP_URL);
        final Message message = new Message();
        message.setFrom(adminEmail);
        message.addRecipient(originalCommentEmail);
        final JSONObject replyNotificationTemplate = preferenceQueryService.getReplyNotificationTemplate();
        final String articleTitle = article.getString(Article.ARTICLE_TITLE);
        final String articleLink = Latkes.getServePath() + article.getString(Article.ARTICLE_PERMALINK);
        final String commentName = comment.getString(Comment.COMMENT_NAME);
        final String commentURL = comment.getString(Comment.COMMENT_URL);
        String commenter;
        if (!"http://".equals(commentURL)) {
            commenter = "<a target=\"_blank\" " + "href=\"" + commentURL + "\">" + commentName + "</a>";
        } else {
            commenter = commentName;
        }
        final String mailSubject = replyNotificationTemplate.getString("subject").replace("${postLink}", articleLink).replace("${postTitle}", articleTitle).replace("${replier}", commenter).replace("${blogTitle}", blogTitle).replace("${replyURL}", Latkes.getServePath() + commentSharpURL).replace("${replyContent}", commentContent);
        message.setSubject(mailSubject);
        final String mailBody = replyNotificationTemplate.getString("body").replace("${postLink}", articleLink).replace("${postTitle}", articleTitle).replace("${replier}", commenter).replace("${blogTitle}", blogTitle).replace("${replyURL}", Latkes.getServePath() + commentSharpURL).replace("${replyContent}", commentContent);
        message.setHtmlBody(mailBody);
        LOGGER.log(Level.DEBUG, "Sending a mail[mailSubject={0}, mailBody=[{1}] to [{2}]", new Object[] { mailSubject, mailBody, originalCommentEmail });
        mailService.send(message);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        throw new EventException("Reply notifier error!");
    }
}
Also used : PreferenceQueryService(org.b3log.solo.service.PreferenceQueryService) JSONObject(org.json.JSONObject) Message(org.b3log.latke.mail.MailService.Message) EventException(org.b3log.latke.event.EventException) CommentRepository(org.b3log.solo.repository.CommentRepository) EventException(org.b3log.latke.event.EventException) LatkeBeanManager(org.b3log.latke.ioc.LatkeBeanManager)

Example 3 with EventException

use of org.b3log.latke.event.EventException in project solo by b3log.

the class AddArticleGoogleBlogSearchPinger method action.

@Override
public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject eventData = event.getData();
    String articleTitle = null;
    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final PreferenceQueryService preferenceQueryService = beanManager.getReference(PreferenceQueryService.class);
    try {
        final JSONObject article = eventData.getJSONObject(Article.ARTICLE);
        articleTitle = article.getString(Article.ARTICLE_TITLE);
        final JSONObject preference = preferenceQueryService.getPreference();
        final String blogTitle = preference.getString(Option.ID_C_BLOG_TITLE);
        if (Latkes.getServePath().contains("localhost")) {
            LOGGER.log(Level.TRACE, "Solo runs on local server, so should not ping " + "Google Blog Search Service for the article[title={0}]", new Object[] { article.getString(Article.ARTICLE_TITLE) });
            return;
        }
        final String articlePermalink = Latkes.getServePath() + article.getString(Article.ARTICLE_PERMALINK);
        final String spec = "http://blogsearch.google.com/ping?name=" + URLEncoder.encode(blogTitle, "UTF-8") + "&url=" + URLEncoder.encode(Latkes.getServePath(), "UTF-8") + "&changesURL=" + URLEncoder.encode(articlePermalink, "UTF-8");
        LOGGER.log(Level.DEBUG, "Request Google Blog Search Service API[{0}] while adding an " + "article[title=" + articleTitle + "]", spec);
        final HTTPRequest request = new HTTPRequest();
        request.setURL(new URL(spec));
        URL_FETCH_SERVICE.fetchAsync(request);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Ping Google Blog Search Service fail while adding an article[title=" + articleTitle + "]", e);
    }
}
Also used : PreferenceQueryService(org.b3log.solo.service.PreferenceQueryService) HTTPRequest(org.b3log.latke.urlfetch.HTTPRequest) JSONObject(org.json.JSONObject) URL(java.net.URL) EventException(org.b3log.latke.event.EventException) LatkeBeanManager(org.b3log.latke.ioc.LatkeBeanManager)

Example 4 with EventException

use of org.b3log.latke.event.EventException in project solo by b3log.

the class PluginRefresher method action.

@Override
public void action(final Event<List<AbstractPlugin>> event) throws EventException {
    final List<AbstractPlugin> plugins = event.getData();
    LOGGER.log(Level.DEBUG, "Processing an event[type={0}, data={1}] in listener[className={2}]", new Object[] { event.getType(), plugins, PluginRefresher.class.getName() });
    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final PluginRepository pluginRepository = beanManager.getReference(PluginRepositoryImpl.class);
    final Transaction transaction = pluginRepository.beginTransaction();
    try {
        final PluginMgmtService pluginMgmtService = beanManager.getReference(PluginMgmtService.class);
        pluginMgmtService.refresh(plugins);
        transaction.commit();
    } catch (final Exception e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        LOGGER.log(Level.ERROR, "Processing plugin loaded event error", e);
        throw new EventException(e);
    }
}
Also used : PluginMgmtService(org.b3log.solo.service.PluginMgmtService) Transaction(org.b3log.latke.repository.Transaction) EventException(org.b3log.latke.event.EventException) PluginRepository(org.b3log.solo.repository.PluginRepository) AbstractPlugin(org.b3log.latke.plugin.AbstractPlugin) EventException(org.b3log.latke.event.EventException) LatkeBeanManager(org.b3log.latke.ioc.LatkeBeanManager)

Example 5 with EventException

use of org.b3log.latke.event.EventException in project solo by b3log.

the class ArticleSender method action.

@Override
public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject data = event.getData();
    LOGGER.log(Level.DEBUG, "Processing an event[type={0}, data={1}] in listener[className={2}]", new Object[] { event.getType(), data, ArticleSender.class.getName() });
    try {
        final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
        if (!originalArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
            LOGGER.log(Level.DEBUG, "Ignores post article[title={0}] to Rhythm", originalArticle.getString(Article.ARTICLE_TITLE));
            return;
        }
        final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
        final PreferenceQueryService preferenceQueryService = beanManager.getReference(PreferenceQueryService.class);
        final JSONObject preference = preferenceQueryService.getPreference();
        if (null == preference) {
            throw new EventException("Not found preference");
        }
        if (!Strings.isEmptyOrNull(originalArticle.optString(Article.ARTICLE_VIEW_PWD))) {
            return;
        }
        if (Latkes.getServePath().contains("localhost")) {
            LOGGER.log(Level.INFO, "Solo runs on local server, so should not send this article[id={0}, title={1}] to Rhythm", new Object[] { originalArticle.getString(Keys.OBJECT_ID), originalArticle.getString(Article.ARTICLE_TITLE) });
            return;
        }
        final HTTPRequest httpRequest = new HTTPRequest();
        httpRequest.setURL(ADD_ARTICLE_URL);
        httpRequest.setRequestMethod(HTTPRequestMethod.POST);
        final JSONObject requestJSONObject = new JSONObject();
        final JSONObject article = new JSONObject();
        article.put(Keys.OBJECT_ID, originalArticle.getString(Keys.OBJECT_ID));
        article.put(Article.ARTICLE_TITLE, originalArticle.getString(Article.ARTICLE_TITLE));
        article.put(Article.ARTICLE_PERMALINK, originalArticle.getString(Article.ARTICLE_PERMALINK));
        article.put(Article.ARTICLE_TAGS_REF, originalArticle.getString(Article.ARTICLE_TAGS_REF));
        article.put(Article.ARTICLE_AUTHOR_EMAIL, originalArticle.getString(Article.ARTICLE_AUTHOR_EMAIL));
        article.put(Article.ARTICLE_CONTENT, originalArticle.getString(Article.ARTICLE_CONTENT));
        article.put(Article.ARTICLE_CREATE_DATE, ((Date) originalArticle.get(Article.ARTICLE_CREATE_DATE)).getTime());
        article.put(Common.POST_TO_COMMUNITY, originalArticle.getBoolean(Common.POST_TO_COMMUNITY));
        // Removes this property avoid to persist
        originalArticle.remove(Common.POST_TO_COMMUNITY);
        requestJSONObject.put(Article.ARTICLE, article);
        requestJSONObject.put(Common.BLOG_VERSION, SoloServletListener.VERSION);
        requestJSONObject.put(Common.BLOG, "B3log Solo");
        requestJSONObject.put(Option.ID_C_BLOG_TITLE, preference.getString(Option.ID_C_BLOG_TITLE));
        requestJSONObject.put("blogHost", Latkes.getServePath());
        requestJSONObject.put("userB3Key", preference.optString(Option.ID_C_KEY_OF_SOLO));
        requestJSONObject.put("clientAdminEmail", preference.optString(Option.ID_C_ADMIN_EMAIL));
        requestJSONObject.put("clientRuntimeEnv", Latkes.getRuntimeEnv().name());
        httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8"));
        urlFetchService.fetchAsync(httpRequest);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Sends an article to Rhythm error: {0}", e.getMessage());
    }
    LOGGER.log(Level.DEBUG, "Sent an article to Rhythm");
}
Also used : PreferenceQueryService(org.b3log.solo.service.PreferenceQueryService) HTTPRequest(org.b3log.latke.urlfetch.HTTPRequest) JSONObject(org.json.JSONObject) EventException(org.b3log.latke.event.EventException) MalformedURLException(java.net.MalformedURLException) EventException(org.b3log.latke.event.EventException) LatkeBeanManager(org.b3log.latke.ioc.LatkeBeanManager)

Aggregations

EventException (org.b3log.latke.event.EventException)13 JSONObject (org.json.JSONObject)11 LatkeBeanManager (org.b3log.latke.ioc.LatkeBeanManager)8 PreferenceQueryService (org.b3log.solo.service.PreferenceQueryService)7 HTTPRequest (org.b3log.latke.urlfetch.HTTPRequest)5 ServiceException (org.b3log.latke.service.ServiceException)4 MalformedURLException (java.net.MalformedURLException)3 JSONException (org.json.JSONException)3 URL (java.net.URL)2 Date (java.util.Date)2 Message (org.b3log.latke.mail.MailService.Message)2 ViewLoadEventData (org.b3log.latke.plugin.ViewLoadEventData)2 RepositoryException (org.b3log.latke.repository.RepositoryException)2 Transaction (org.b3log.latke.repository.Transaction)2 ArchiveDate (org.b3log.solo.model.ArchiveDate)2 CommentRepository (org.b3log.solo.repository.CommentRepository)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ParseException (java.text.ParseException)1 AbstractPlugin (org.b3log.latke.plugin.AbstractPlugin)1