use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.
the class CaptchaProcessor method get.
/**
* Gets captcha.
*
* @param context the specified context
*/
@RequestProcessing(value = "/captcha.do", method = HTTPRequestMethod.GET)
public void get(final HTTPRequestContext context) {
final PNGRenderer renderer = new PNGRenderer();
context.setRenderer(renderer);
if (null == captchas) {
loadCaptchas();
}
try {
final HttpServletRequest request = context.getRequest();
final HttpServletResponse response = context.getResponse();
final Random random = new Random();
final int index = random.nextInt(CAPTCHA_COUNT);
final Image captchaImg = captchas[index];
final String captcha = captchaImg.getName();
final HttpSession httpSession = request.getSession(false);
if (null != httpSession) {
LOGGER.log(Level.DEBUG, "Captcha[{0}] for session[id={1}]", new Object[] { captcha, httpSession.getId() });
httpSession.setAttribute(CAPTCHA, captcha);
}
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
renderer.setImage(captchaImg);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, e.getMessage(), e);
}
}
use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.
the class CommentProcessor method addPageComment.
/**
* Adds a comment to a page.
* <p>
* Renders the response with a json object, for example,
* <pre>
* {
* "oId": generatedCommentId,
* "sc": "COMMENT_PAGE_SUCC"
* "commentDate": "", // yyyy/MM/dd HH:mm:ss
* "commentSharpURL": "",
* "commentThumbnailURL": "",
* "commentOriginalCommentName": "" // if exists this key, the comment is an reply
* }
* </pre>
* </p>
*
* @param context the specified context, including a request json object, for example,
* "captcha": "",
* "oId": pageId,
* "commentName": "",
* "commentEmail": "",
* "commentURL": "",
* "commentContent": "", // HTML
* "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
* @throws ServletException servlet exception
* @throws IOException io exception
*/
@RequestProcessing(value = "/add-page-comment.do", method = HTTPRequestMethod.POST)
public void addPageComment(final HTTPRequestContext context) throws ServletException, IOException {
final HttpServletRequest httpServletRequest = context.getRequest();
final HttpServletResponse httpServletResponse = context.getResponse();
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(httpServletRequest, httpServletResponse);
requestJSONObject.put(Common.TYPE, Page.PAGE);
fillCommenter(requestJSONObject, httpServletRequest, httpServletResponse);
final JSONObject jsonObject = commentMgmtService.checkAddCommentRequest(requestJSONObject);
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
renderer.setJSONObject(jsonObject);
if (!jsonObject.optBoolean(Keys.STATUS_CODE)) {
LOGGER.log(Level.WARN, "Can't add comment[msg={0}]", jsonObject.optString(Keys.MSG));
return;
}
final HttpSession session = httpServletRequest.getSession(false);
if (null == session) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
final String storedCaptcha = (String) session.getAttribute(CaptchaProcessor.CAPTCHA);
session.removeAttribute(CaptchaProcessor.CAPTCHA);
if (!userQueryService.isLoggedIn(httpServletRequest, httpServletResponse)) {
final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA);
if (null == storedCaptcha || !storedCaptcha.equals(captcha)) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
}
try {
final JSONObject addResult = commentMgmtService.addPageComment(requestJSONObject);
final Map<String, Object> dataModel = new HashMap<>();
dataModel.put(Comment.COMMENT, addResult);
final JSONObject page = addResult.optJSONObject(Page.PAGE);
page.put(Common.COMMENTABLE, addResult.opt(Common.COMMENTABLE));
page.put(Common.PERMALINK, addResult.opt(Common.PERMALINK));
dataModel.put(Article.ARTICLE, page);
// https://github.com/b3log/solo/issues/12246
try {
final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
final Template template = Templates.MAIN_CFG.getTemplate("common-comment.ftl");
final JSONObject preference = preferenceQueryService.getPreference();
Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), skinDirName, dataModel);
Keys.fillServer(dataModel);
final StringWriter stringWriter = new StringWriter();
template.process(dataModel, stringWriter);
stringWriter.close();
addResult.put("cmtTpl", stringWriter.toString());
} catch (final Exception e) {
// 1.9.0 向后兼容
}
addResult.put(Keys.STATUS_CODE, true);
renderer.setJSONObject(addResult);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Can not add comment on page", e);
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
}
}
use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.
the class FeedProcessor method blogArticlesRSS.
/**
* Blog articles RSS output.
*
* @param context the specified context
*/
@RequestProcessing(value = { "/blog-articles-rss.do" }, method = { HTTPRequestMethod.GET, HTTPRequestMethod.HEAD })
public void blogArticlesRSS(final HTTPRequestContext context) {
final HttpServletResponse response = context.getResponse();
final RssRenderer renderer = new RssRenderer();
context.setRenderer(renderer);
final Channel channel = new Channel();
try {
final JSONObject preference = preferenceQueryService.getPreference();
if (null == preference) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
final String blogTitle = preference.getString(Option.ID_C_BLOG_TITLE);
final String blogSubtitle = preference.getString(Option.ID_C_BLOG_SUBTITLE);
final int outputCnt = preference.getInt(Option.ID_C_FEED_OUTPUT_CNT);
channel.setTitle(StringEscapeUtils.escapeXml(blogTitle));
channel.setLastBuildDate(new Date());
channel.setLink(Latkes.getServePath());
channel.setAtomLink(Latkes.getServePath() + "/blog-articles-rss.do");
channel.setGenerator("Solo, ver " + SoloServletListener.VERSION);
final String localeString = preference.getString(Option.ID_C_LOCALE_STRING);
final String country = Locales.getCountry(localeString).toLowerCase();
final String language = Locales.getLanguage(localeString).toLowerCase();
channel.setLanguage(language + '-' + country);
channel.setDescription(blogSubtitle);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true));
filters.add(new PropertyFilter(Article.ARTICLE_VIEW_PWD, FilterOperator.EQUAL, ""));
final Query query = new Query().setCurrentPageNum(1).setPageSize(outputCnt).setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).addSort(Article.ARTICLE_UPDATE_DATE, SortDirection.DESCENDING).setPageCount(1);
final JSONObject articleResult = articleRepository.get(query);
final JSONArray articles = articleResult.getJSONArray(Keys.RESULTS);
final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
String authorName = "";
if (!hasMultipleUsers && 0 != articles.length()) {
authorName = articleQueryService.getAuthor(articles.getJSONObject(0)).getString(User.USER_NAME);
}
final boolean isFullContent = "fullContent".equals(preference.getString(Option.ID_C_FEED_OUTPUT_MODE));
for (int i = 0; i < articles.length(); i++) {
Item item = getItem(articles, hasMultipleUsers, authorName, isFullContent, i);
channel.addItem(item);
}
renderer.setContent(channel.toString());
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Get blog article rss error", e);
try {
context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
}
}
use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.
the class FeedProcessor method tagArticlesAtom.
/**
* Tag articles Atom output.
*
* @param context the specified context
* @throws IOException io exception
*/
@RequestProcessing(value = { "/tag-articles-feed.do" }, method = { HTTPRequestMethod.GET, HTTPRequestMethod.HEAD })
public void tagArticlesAtom(final HTTPRequestContext context) throws IOException {
final AtomRenderer renderer = new AtomRenderer();
context.setRenderer(renderer);
final HttpServletRequest request = context.getRequest();
final HttpServletResponse response = context.getResponse();
final String queryString = request.getQueryString();
if (Strings.isEmptyOrNull(queryString)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
final String oIdMap = queryString.split("&")[0];
final String tagId = oIdMap.split("=")[1];
final Feed feed = new Feed();
try {
final JSONObject tag = tagRepository.get(tagId);
if (null == tag) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
final String tagTitle = tag.getString(Tag.TAG_TITLE);
final JSONObject preference = preferenceQueryService.getPreference();
if (null == preference) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
final String blogTitle = preference.getString(Option.ID_C_BLOG_TITLE);
final String blogSubtitle = preference.getString(Option.ID_C_BLOG_SUBTITLE) + ", " + tagTitle;
final int outputCnt = preference.getInt(Option.ID_C_FEED_OUTPUT_CNT);
feed.setTitle(StringEscapeUtils.escapeXml(blogTitle));
feed.setSubtitle(StringEscapeUtils.escapeXml(blogSubtitle));
feed.setUpdated(new Date());
feed.setAuthor(StringEscapeUtils.escapeXml(blogTitle));
feed.setLink(Latkes.getServePath() + "/tag-articles-feed.do");
feed.setId(Latkes.getServePath() + "/");
final JSONObject tagArticleResult = tagArticleRepository.getByTagId(tagId, 1, outputCnt);
final JSONArray tagArticleRelations = tagArticleResult.getJSONArray(Keys.RESULTS);
if (0 == tagArticleRelations.length()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
final List<JSONObject> articles = new ArrayList<JSONObject>();
for (int i = 0; i < tagArticleRelations.length(); i++) {
final JSONObject tagArticleRelation = tagArticleRelations.getJSONObject(i);
final String articleId = tagArticleRelation.getString(Article.ARTICLE + "_" + Keys.OBJECT_ID);
final JSONObject article = articleRepository.get(articleId);
if (// Skips the unpublished article
article.getBoolean(Article.ARTICLE_IS_PUBLISHED) && Strings.isEmptyOrNull(article.optString(Article.ARTICLE_VIEW_PWD))) {
// Skips article with password
articles.add(article);
}
}
final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
String authorName = "";
if (!hasMultipleUsers && !articles.isEmpty()) {
authorName = articleQueryService.getAuthor(articles.get(0)).getString(User.USER_NAME);
}
final boolean isFullContent = "fullContent".equals(preference.getString(Option.ID_C_FEED_OUTPUT_MODE));
for (int i = 0; i < articles.size(); i++) {
Entry entry = getEntryForArticle(articles, hasMultipleUsers, authorName, isFullContent, i);
feed.addEntry(entry);
}
renderer.setContent(feed.toString());
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Get tag article feed error", e);
try {
context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
}
}
use of org.b3log.latke.servlet.annotation.RequestProcessing in project solo by b3log.
the class FeedProcessor method blogArticlesAtom.
/**
* Blog articles Atom output.
*
* @param context the specified context
*/
@RequestProcessing(value = { "/blog-articles-feed.do" }, method = { HTTPRequestMethod.GET, HTTPRequestMethod.HEAD })
public void blogArticlesAtom(final HTTPRequestContext context) {
final AtomRenderer renderer = new AtomRenderer();
context.setRenderer(renderer);
final Feed feed = new Feed();
try {
final JSONObject preference = preferenceQueryService.getPreference();
final String blogTitle = preference.getString(Option.ID_C_BLOG_TITLE);
final String blogSubtitle = preference.getString(Option.ID_C_BLOG_SUBTITLE);
final int outputCnt = preference.getInt(Option.ID_C_FEED_OUTPUT_CNT);
feed.setTitle(StringEscapeUtils.escapeXml(blogTitle));
feed.setSubtitle(StringEscapeUtils.escapeXml(blogSubtitle));
feed.setUpdated(new Date());
feed.setAuthor(StringEscapeUtils.escapeXml(blogTitle));
feed.setLink(Latkes.getServePath() + "/blog-articles-feed.do");
feed.setId(Latkes.getServePath() + "/");
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true));
filters.add(new PropertyFilter(Article.ARTICLE_VIEW_PWD, FilterOperator.EQUAL, ""));
final Query query = new Query().setCurrentPageNum(1).setPageSize(outputCnt).setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)).addSort(Article.ARTICLE_UPDATE_DATE, SortDirection.DESCENDING).setPageCount(1);
final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
String authorName = "";
final JSONObject articleResult = articleRepository.get(query);
final JSONArray articles = articleResult.getJSONArray(Keys.RESULTS);
if (!hasMultipleUsers && 0 != articles.length()) {
authorName = articleQueryService.getAuthor(articles.getJSONObject(0)).getString(User.USER_NAME);
}
final boolean isFullContent = "fullContent".equals(preference.getString(Option.ID_C_FEED_OUTPUT_MODE));
for (int i = 0; i < articles.length(); i++) {
Entry entry = getEntry(hasMultipleUsers, authorName, articles, isFullContent, i);
feed.addEntry(entry);
}
renderer.setContent(feed.toString());
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Get blog article feed error", e);
try {
context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
}
}
Aggregations