PageRenderTime 139ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/b3log-solo/core/src/main/java/org/b3log/solo/util/Articles.java

http://b3log-solo.googlecode.com/
Java | 305 lines | 137 code | 32 blank | 136 comment | 15 complexity | 19bac3f5a3b8e43167c29907362d1977 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1
  1. /*
  2. * Copyright (c) 2009, 2010, 2011, 2012, B3log Team
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.b3log.solo.util;
  17. import java.io.UnsupportedEncodingException;
  18. import java.net.URLEncoder;
  19. import java.util.Date;
  20. import java.util.HashMap;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.logging.Level;
  24. import java.util.logging.Logger;
  25. import javax.servlet.http.HttpServletRequest;
  26. import javax.servlet.http.HttpSession;
  27. import org.b3log.solo.model.Article;
  28. import org.b3log.latke.Keys;
  29. import org.b3log.latke.repository.FilterOperator;
  30. import org.b3log.latke.repository.Query;
  31. import org.b3log.latke.repository.RepositoryException;
  32. import org.b3log.latke.repository.SortDirection;
  33. import org.b3log.latke.service.ServiceException;
  34. import org.b3log.latke.user.UserService;
  35. import org.b3log.latke.user.UserServiceFactory;
  36. import org.b3log.latke.util.CollectionUtils;
  37. import org.b3log.latke.util.Strings;
  38. import org.b3log.solo.model.Common;
  39. import org.b3log.solo.model.Preference;
  40. import org.b3log.solo.repository.ArticleRepository;
  41. import org.b3log.solo.repository.UserRepository;
  42. import org.b3log.solo.repository.impl.ArticleRepositoryImpl;
  43. import org.b3log.solo.repository.impl.UserRepositoryImpl;
  44. import org.json.JSONArray;
  45. import org.json.JSONException;
  46. import org.json.JSONObject;
  47. /**
  48. * Article utilities.
  49. *
  50. * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
  51. * @version 1.0.2.8, May 6, 2012
  52. * @since 0.3.1
  53. */
  54. public final class Articles {
  55. /**
  56. * Logger.
  57. */
  58. private static final Logger LOGGER = Logger.getLogger(Articles.class.getName());
  59. /**
  60. * Article repository.
  61. */
  62. private ArticleRepository articleRepository = ArticleRepositoryImpl.getInstance();
  63. /**
  64. * User repository.
  65. */
  66. private UserRepository userRepository = UserRepositoryImpl.getInstance();
  67. /**
  68. * User service.
  69. */
  70. private UserService userService = UserServiceFactory.getUserService();
  71. /**
  72. * Builds article view password form parameters with the specified article.
  73. *
  74. * @param article the specified article
  75. * @return parameters string, for example,
  76. * <pre>
  77. * "?articleId=xxx&articleTitle=xxx&articlePermalink=xxx&articleAbstract=xxx"
  78. * </pre>
  79. * @throws UnsupportedEncodingException if can not encode the arguments
  80. */
  81. public String buildArticleViewPwdFormParameters(final JSONObject article) throws UnsupportedEncodingException {
  82. final StringBuilder parametersBuilder =
  83. new StringBuilder("?articleId=").append(article.optString(Keys.OBJECT_ID)).
  84. append("&articleTitle=").append(URLEncoder.encode(article.optString(Article.ARTICLE_TITLE), "UTF-8")).
  85. append("&articlePermalink=").append(URLEncoder.encode(article.optString(Article.ARTICLE_PERMALINK), "UTF-8")).
  86. append("&articleAbstract=").append(URLEncoder.encode(article.optString(Article.ARTICLE_ABSTRACT, " "), "UTF-8"));
  87. return parametersBuilder.toString();
  88. }
  89. /**
  90. * Checks whether need password to view the specified article with the specified request.
  91. *
  92. * <p>
  93. * Checks session, if not represents, checks article property {@link Article#ARTICLE_VIEW_PWD view password}.
  94. * </p>
  95. *
  96. * <p>
  97. * The blogger itself dose not need view password never.
  98. * </p>
  99. *
  100. * @param request the specified request
  101. * @param article the specified article
  102. * @return {@code true} if need, returns {@code false} otherwise
  103. */
  104. public boolean needViewPwd(final HttpServletRequest request, final JSONObject article) {
  105. final String articleViewPwd = article.optString(Article.ARTICLE_VIEW_PWD);
  106. if (Strings.isEmptyOrNull(articleViewPwd)) {
  107. return false;
  108. }
  109. final HttpSession session = request.getSession(false);
  110. if (null != session) {
  111. @SuppressWarnings("unchecked")
  112. Map<String, String> viewPwds = (Map<String, String>) session.getAttribute(Common.ARTICLES_VIEW_PWD);
  113. if (null == viewPwds) {
  114. viewPwds = new HashMap<String, String>();
  115. }
  116. if (articleViewPwd.equals(viewPwds.get(article.optString(Keys.OBJECT_ID)))) {
  117. return false;
  118. }
  119. }
  120. if (null != userService.getCurrentUser(request)) {
  121. return false;
  122. }
  123. return true;
  124. }
  125. /**
  126. * Gets the specified article's author.
  127. *
  128. * <p>
  129. * The specified article has a property
  130. * {@value Article#ARTICLE_AUTHOR_EMAIL}, this method will use this property
  131. * to get a user from users.
  132. * </p>
  133. *
  134. * <p>
  135. * If can't find the specified article's author (i.e. the author has been
  136. * removed by administrator), returns administrator.
  137. * </p>
  138. *
  139. * @param article the specified article
  140. * @return user, {@code null} if not found
  141. * @throws ServiceException service exception
  142. */
  143. public JSONObject getAuthor(final JSONObject article) throws ServiceException {
  144. try {
  145. final String email = article.getString(Article.ARTICLE_AUTHOR_EMAIL);
  146. JSONObject ret = userRepository.getByEmail(email);
  147. if (null == ret) {
  148. LOGGER.log(Level.WARNING,
  149. "Gets author of article failed, assumes the administrator is the author of this article[id={0}]",
  150. article.getString(Keys.OBJECT_ID));
  151. // This author may be deleted by admin, use admin as the author
  152. // of this article
  153. ret = userRepository.getAdmin();
  154. }
  155. return ret;
  156. } catch (final RepositoryException e) {
  157. LOGGER.log(Level.SEVERE, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID));
  158. throw new ServiceException(e);
  159. } catch (final JSONException e) {
  160. LOGGER.log(Level.SEVERE, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID));
  161. throw new ServiceException(e);
  162. }
  163. }
  164. /**
  165. * Article comment count +1 for an article specified by the given article id.
  166. *
  167. * @param articleId the given article id
  168. * @throws JSONException json exception
  169. * @throws RepositoryException repository exception
  170. */
  171. public void incArticleCommentCount(final String articleId) throws JSONException, RepositoryException {
  172. final JSONObject article = articleRepository.get(articleId);
  173. final JSONObject newArticle = new JSONObject(article, JSONObject.getNames(article));
  174. final int commentCnt = article.getInt(Article.ARTICLE_COMMENT_COUNT);
  175. newArticle.put(Article.ARTICLE_COMMENT_COUNT, commentCnt + 1);
  176. articleRepository.update(articleId, newArticle);
  177. }
  178. /**
  179. * Gets the sign of an article specified by the sign id.
  180. *
  181. * @param signId the specified article id
  182. * @param preference the specified preference
  183. * @return article sign, returns the default sign (which oId is "1") if not found
  184. * @throws RepositoryException repository exception
  185. * @throws JSONException json exception
  186. */
  187. public JSONObject getSign(final String signId, final JSONObject preference) throws JSONException, RepositoryException {
  188. final JSONArray signs = new JSONArray(preference.getString(Preference.SIGNS));
  189. JSONObject defaultSign = null;
  190. for (int i = 0; i < signs.length(); i++) {
  191. final JSONObject ret = signs.getJSONObject(i);
  192. if (signId.equals(ret.optString(Keys.OBJECT_ID))) {
  193. return ret;
  194. }
  195. if ("1".equals(ret.optString(Keys.OBJECT_ID))) {
  196. defaultSign = ret;
  197. }
  198. }
  199. LOGGER.log(Level.WARNING, "Can not find the sign[id={0}], returns a default sign[id=1]", signId);
  200. if (null == defaultSign) {
  201. throw new IllegalStateException("Can not find the default sign which id equals to 1");
  202. }
  203. return defaultSign;
  204. }
  205. /**
  206. * Determines the specified article has updated.
  207. *
  208. * @param article the specified article
  209. * @return {@code true} if it has updated, {@code false} otherwise
  210. * @throws JSONException json exception
  211. */
  212. public boolean hasUpdated(final JSONObject article) throws JSONException {
  213. final Date updateDate = (Date) article.get(Article.ARTICLE_UPDATE_DATE);
  214. final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE);
  215. return !createDate.equals(updateDate);
  216. }
  217. /**
  218. * Determines the specified article had been published.
  219. *
  220. * @param article the specified article
  221. * @return {@code true} if it had been published, {@code false} otherwise
  222. * @throws JSONException json exception
  223. */
  224. public boolean hadBeenPublished(final JSONObject article) throws JSONException {
  225. return article.getBoolean(Article.ARTICLE_HAD_BEEN_PUBLISHED);
  226. }
  227. /**
  228. * Gets all unpublished articles.
  229. *
  230. * @return articles all unpublished articles
  231. * @throws RepositoryException repository exception
  232. * @throws JSONException json exception
  233. */
  234. public List<JSONObject> getUnpublishedArticles() throws RepositoryException, JSONException {
  235. final Map<String, SortDirection> sorts = new HashMap<String, SortDirection>();
  236. sorts.put(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING);
  237. sorts.put(Article.ARTICLE_PUT_TOP, SortDirection.DESCENDING);
  238. final Query query = new Query().addFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true);
  239. final JSONObject result = articleRepository.get(query);
  240. final JSONArray articles = result.getJSONArray(Keys.RESULTS);
  241. return CollectionUtils.jsonArrayToList(articles);
  242. }
  243. /**
  244. * Gets the {@link Articles} singleton.
  245. *
  246. * @return the singleton
  247. */
  248. public static Articles getInstance() {
  249. return SingletonHolder.SINGLETON;
  250. }
  251. /**
  252. * Private default constructor.
  253. */
  254. private Articles() {
  255. }
  256. /**
  257. * Singleton holder.
  258. *
  259. * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
  260. * @version 1.0.0.0, Jan 12, 2011
  261. */
  262. private static final class SingletonHolder {
  263. /**
  264. * Singleton.
  265. */
  266. private static final Articles SINGLETON = new Articles();
  267. /**
  268. * Private default constructor.
  269. */
  270. private SingletonHolder() {
  271. }
  272. }
  273. }