use of org.b3log.latke.event.EventException in project solo by b3log.
the class AdminConsole method fireFreeMarkerActionEvent.
/**
* Fires FreeMarker action event with the host template name and data model.
*
* @param hostTemplateName the specified host template name
* @param dataModel the specified data model
*/
private void fireFreeMarkerActionEvent(final String hostTemplateName, final Map<String, Object> dataModel) {
try {
final ViewLoadEventData data = new ViewLoadEventData();
data.setViewName(hostTemplateName);
data.setDataModel(dataModel);
eventManager.fireEventSynchronously(new Event<ViewLoadEventData>(Keys.FREEMARKER_ACTION, data));
if (Strings.isEmptyOrNull((String) dataModel.get(Plugin.PLUGINS))) {
// There is no plugin for this template, fill ${plugins} with blank.
dataModel.put(Plugin.PLUGINS, "");
}
} catch (final EventException e) {
LOGGER.log(Level.WARN, "Event[FREEMARKER_ACTION] handle failed, ignores this exception for kernel health", e);
}
}
use of org.b3log.latke.event.EventException in project solo by b3log.
the class Filler method fillBlogFooter.
/**
* Fills footer.ftl.
*
* @param request the specified HTTP servlet request
* @param dataModel data model
* @param preference the specified preference
* @throws ServiceException service exception
*/
public void fillBlogFooter(final HttpServletRequest request, final Map<String, Object> dataModel, final JSONObject preference) throws ServiceException {
Stopwatchs.start("Fill Footer");
try {
LOGGER.debug("Filling footer....");
final String blogTitle = preference.getString(Option.ID_C_BLOG_TITLE);
dataModel.put(Option.ID_C_BLOG_TITLE, blogTitle);
dataModel.put("blogHost", Latkes.getServerHost() + ":" + Latkes.getServerPort());
dataModel.put(Common.VERSION, SoloServletListener.VERSION);
dataModel.put(Common.STATIC_RESOURCE_VERSION, Latkes.getStaticResourceVersion());
dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
String footerContent = "";
final JSONObject opt = optionQueryService.getOptionById(Option.ID_C_FOOTER_CONTENT);
if (null != opt) {
footerContent = opt.optString(Option.OPTION_VALUE);
}
dataModel.put(Option.ID_C_FOOTER_CONTENT, footerContent);
dataModel.put(Keys.Server.STATIC_SERVER, Latkes.getStaticServer());
dataModel.put(Keys.Server.SERVER, Latkes.getServer());
dataModel.put(Common.IS_INDEX, "/".equals(request.getRequestURI()));
dataModel.put(User.USER_NAME, "");
final JSONObject currentUser = userQueryService.getCurrentUser(request);
if (null != currentUser) {
final String userAvatar = currentUser.optString(UserExt.USER_AVATAR);
if (!Strings.isEmptyOrNull(userAvatar)) {
dataModel.put(Common.GRAVATAR, userAvatar);
} else {
final String email = currentUser.optString(User.USER_EMAIL);
final String gravatar = Thumbnails.getGravatarURL(email, "128");
dataModel.put(Common.GRAVATAR, gravatar);
}
dataModel.put(User.USER_NAME, currentUser.optString(User.USER_NAME));
}
// Activates plugins
try {
final ViewLoadEventData data = new ViewLoadEventData();
data.setViewName("footer.ftl");
data.setDataModel(dataModel);
eventManager.fireEventSynchronously(new Event<ViewLoadEventData>(Keys.FREEMARKER_ACTION, data));
if (Strings.isEmptyOrNull((String) dataModel.get(Plugin.PLUGINS))) {
// There is no plugin for this template, fill ${plugins} with blank.
dataModel.put(Plugin.PLUGINS, "");
}
} catch (final EventException e) {
LOGGER.log(Level.WARN, "Event[FREEMARKER_ACTION] handle failed, ignores this exception for kernel health", e);
}
} catch (final JSONException e) {
LOGGER.log(Level.ERROR, "Fills blog footer failed", e);
throw new ServiceException(e);
} finally {
Stopwatchs.end();
}
}
use of org.b3log.latke.event.EventException in project solo by b3log.
the class ArticleMgmtService method addArticleInternal.
/**
* Adds the specified article for internal invocation purposes.
*
* @param article the specified article
* @return generated article id
* @throws ServiceException service exception
*/
public String addArticleInternal(final JSONObject article) throws ServiceException {
String ret = article.optString(Keys.OBJECT_ID);
if (Strings.isEmptyOrNull(ret)) {
ret = Ids.genTimeMillisId();
article.put(Keys.OBJECT_ID, ret);
}
try {
// Step 1: Add tags
String tagsString = article.optString(Article.ARTICLE_TAGS_REF);
tagsString = tagsString.replaceAll(",", ",").replaceAll("、", ",");
article.put(Article.ARTICLE_TAGS_REF, tagsString);
final String[] tagTitles = tagsString.split(",");
final JSONArray tags = tag(tagTitles, article);
// Step 2; Set comment/view count to 0
article.put(Article.ARTICLE_COMMENT_COUNT, 0);
article.put(Article.ARTICLE_VIEW_COUNT, 0);
// Step 3: Set create/updat date
final JSONObject preference = preferenceQueryService.getPreference();
final Date date = new Date();
if (!article.has(Article.ARTICLE_CREATE_DATE)) {
article.put(Article.ARTICLE_CREATE_DATE, date);
}
article.put(Article.ARTICLE_UPDATE_DATE, article.opt(Article.ARTICLE_CREATE_DATE));
// Step 4: Set put top to false
article.put(Article.ARTICLE_PUT_TOP, false);
// Step 5: Add tag-article relations
addTagArticleRelation(tags, article);
// Step 6: Inc blog article count statictis
statisticMgmtService.incBlogArticleCount();
if (article.optBoolean(Article.ARTICLE_IS_PUBLISHED)) {
statisticMgmtService.incPublishedBlogArticleCount();
}
// Step 7: Add archive date-article relations
archiveDate(article);
// Step 8: Set permalink
final String permalink = getPermalinkForAddArticle(article);
article.put(Article.ARTICLE_PERMALINK, permalink);
// Step 9: Add article sign id
final String signId = article.optString(Article.ARTICLE_SIGN_ID, "1");
article.put(Article.ARTICLE_SIGN_ID, signId);
// Step 10: Set had been published status
article.put(Article.ARTICLE_HAD_BEEN_PUBLISHED, false);
if (article.optBoolean(Article.ARTICLE_IS_PUBLISHED)) {
// Publish it directly
article.put(Article.ARTICLE_HAD_BEEN_PUBLISHED, true);
}
// Step 11: Set random double
article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random());
// Step 12: Set post to community
final boolean postToCommunity = article.optBoolean(Common.POST_TO_COMMUNITY, true);
// Do not persist this property
article.remove(Common.POST_TO_COMMUNITY);
// Setp 13: Update user article statistic
final JSONObject author = userRepository.getByEmail(article.optString(Article.ARTICLE_AUTHOR_EMAIL));
final int userArticleCnt = author.optInt(UserExt.USER_ARTICLE_COUNT);
author.put(UserExt.USER_ARTICLE_COUNT, userArticleCnt + 1);
if (article.optBoolean(Article.ARTICLE_IS_PUBLISHED)) {
author.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, author.optInt(UserExt.USER_PUBLISHED_ARTICLE_COUNT) + 1);
}
userRepository.update(author.optString(Keys.OBJECT_ID), author);
// Step 14: Set editor type
if (!article.has(Article.ARTICLE_EDITOR_TYPE)) {
article.put(Article.ARTICLE_EDITOR_TYPE, preference.optString(Option.ID_C_EDITOR_TYPE));
}
// Step 15: Add article
articleRepository.add(article);
// Restores the property
article.put(Common.POST_TO_COMMUNITY, postToCommunity);
if (article.optBoolean(Article.ARTICLE_IS_PUBLISHED)) {
// Fire add article event
final JSONObject eventData = new JSONObject();
eventData.put(Article.ARTICLE, article);
eventManager.fireEventSynchronously(new Event<JSONObject>(EventTypes.ADD_ARTICLE, eventData));
}
article.remove(Common.POST_TO_COMMUNITY);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Adds an article failed", e);
throw new ServiceException(e);
} catch (final EventException e) {
LOGGER.log(Level.WARN, "Adds an article event process failed", e);
}
return ret;
}
use of org.b3log.latke.event.EventException in project solo by b3log.
the class PageCommentReplyNotifier 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 page = eventData.optJSONObject(Page.PAGE);
LOGGER.log(Level.DEBUG, "Processing an event[type={0}, data={1}] in listener[className={2}]", new Object[] { event.getType(), eventData, PageCommentReplyNotifier.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;
}
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 mailSubject = replyNotificationTemplate.getString("subject").replace("${blogTitle}", blogTitle);
message.setSubject(mailSubject);
final String pageTitle = page.getString(Page.PAGE_TITLE);
final String pageLink = Latkes.getServePath() + page.getString(Page.PAGE_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 mailBody = replyNotificationTemplate.getString("body").replace("${postLink}", pageLink).replace("${postTitle}", pageTitle).replace("${replier}", commenter).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!");
}
}
use of org.b3log.latke.event.EventException in project solo by b3log.
the class ArticleProcessor method showArticle.
/**
* Shows an article with the specified context.
*
* @param context the specified context
* @param request the specified HTTP servlet request
* @param response the specified HTTP servlet response
* @throws IOException io exception
*/
@RequestProcessing(value = "/article", method = HTTPRequestMethod.GET)
public void showArticle(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws IOException {
// See PermalinkFilter#dispatchToArticleOrPageProcessor()
final JSONObject article = (JSONObject) request.getAttribute(Article.ARTICLE);
if (null == article) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
final String articleId = article.optString(Keys.OBJECT_ID);
LOGGER.log(Level.DEBUG, "Article[id={0}]", articleId);
final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
context.setRenderer(renderer);
renderer.setTemplateName("article.ftl");
try {
final JSONObject preference = preferenceQueryService.getPreference();
final boolean allowVisitDraftViaPermalink = preference.getBoolean(Option.ID_C_ALLOW_VISIT_DRAFT_VIA_PERMALINK);
if (!article.optBoolean(Article.ARTICLE_IS_PUBLISHED) && !allowVisitDraftViaPermalink) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
LOGGER.log(Level.TRACE, "Article[title={0}]", article.getString(Article.ARTICLE_TITLE));
articleQueryService.markdown(article);
// For <meta name="description" content="${article.articleAbstract}"/>
final String metaDescription = Jsoup.parse(article.optString(Article.ARTICLE_ABSTRACT)).text();
article.put(Article.ARTICLE_ABSTRACT, metaDescription);
if (preference.getBoolean(Option.ID_C_ENABLE_ARTICLE_UPDATE_HINT)) {
article.put(Common.HAS_UPDATED, articleQueryService.hasUpdated(article));
} else {
article.put(Common.HAS_UPDATED, false);
}
final JSONObject author = articleQueryService.getAuthor(article);
final String authorName = author.getString(User.USER_NAME);
article.put(Common.AUTHOR_NAME, authorName);
final String authorId = author.getString(Keys.OBJECT_ID);
article.put(Common.AUTHOR_ID, authorId);
article.put(Common.AUTHOR_ROLE, author.getString(User.USER_ROLE));
final String userAvatar = author.optString(UserExt.USER_AVATAR);
if (!Strings.isEmptyOrNull(userAvatar)) {
article.put(Common.AUTHOR_THUMBNAIL_URL, userAvatar);
} else {
final String thumbnailURL = Thumbnails.getGravatarURL(author.optString(User.USER_EMAIL), "128");
article.put(Common.AUTHOR_THUMBNAIL_URL, thumbnailURL);
}
final Map<String, Object> dataModel = renderer.getDataModel();
prepareShowArticle(preference, dataModel, article);
filler.fillBlogHeader(request, response, dataModel, preference);
filler.fillBlogFooter(request, dataModel, preference);
filler.fillSide(request, dataModel, preference);
Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);
if (!Requests.hasBeenServed(request, response)) {
articleMgmtService.incViewCount(articleId);
}
statisticMgmtService.incBlogViewCount(request, response);
// Fire [Before Render Article] event
final JSONObject eventData = new JSONObject();
eventData.put(Article.ARTICLE, article);
try {
eventManager.fireEventSynchronously(new Event<JSONObject>(EventTypes.BEFORE_RENDER_ARTICLE, eventData));
} catch (final EventException e) {
LOGGER.log(Level.ERROR, "Fires [" + EventTypes.BEFORE_RENDER_ARTICLE + "] event failed", e);
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, e.getMessage(), e);
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (final IOException ex) {
LOGGER.error(ex.getMessage());
}
}
}
Aggregations