Commit c3574d1a authored by Liang Ding's avatar Liang Ding

c

parent b9b2d102
/* /*
* Copyright (c) 2009, 2010, 2011, 2012, B3log Team * Copyright (c) 2009, 2010, 2011, 2012, B3log Team
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.b3log.solo.service; package org.b3log.solo.service;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.b3log.latke.Keys; import org.b3log.latke.Keys;
import org.b3log.latke.repository.Query; import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.RepositoryException; import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.service.ServiceException; import org.b3log.latke.service.ServiceException;
import org.b3log.latke.util.CollectionUtils; import org.b3log.latke.util.CollectionUtils;
import org.b3log.solo.model.Tag; import org.b3log.solo.model.Tag;
import org.b3log.solo.repository.TagRepository; import org.b3log.solo.repository.TagRepository;
import org.b3log.solo.repository.impl.TagRepositoryImpl; import org.b3log.solo.repository.impl.TagRepositoryImpl;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
/** /**
* Tag query service. * Tag query service.
* *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
<<<<<<< HEAD * @version 1.0.0.3, Jun 28, 2012
* @version 1.0.0.2, Nov 11, 2011 * @since 0.4.0
======= */
* @version 1.0.0.3, Jun 28, 2012 public final class TagQueryService {
>>>>>>> origin/0.4.6
* @since 0.4.0 /**
*/ * Logger.
public final class TagQueryService { */
private static final Logger LOGGER = Logger.getLogger(TagQueryService.class.getName());
/** /**
* Logger. * Tag repository.
*/ */
<<<<<<< HEAD private TagRepository tagRepository = TagRepositoryImpl.getInstance();
private static final Logger LOGGER =
Logger.getLogger(TagQueryService.class.getName()); /**
======= * Gets a tag by the specified tag title.
private static final Logger LOGGER = Logger.getLogger(TagQueryService.class.getName()); *
>>>>>>> origin/0.4.6 * @param tagTitle the specified tag title
/** * @return for example,
* Tag repository. * <pre>
*/ * {
private TagRepository tagRepository = TagRepositoryImpl.getInstance(); * "tag": {
* "oId": "",
/** * "tagTitle": "",
* Gets a tag by the specified tag title. * "tagReferenceCount": int,
* * "tagPublishedRefCount": int
* @param tagTitle the specified tag title * }
* @return for example, * }
* <pre> * </pre>, returns {@code null} if not found
* { * @throws ServiceException service exception
* "tag": { */
* "oId": "", public JSONObject getTagByTitle(final String tagTitle) throws ServiceException {
* "tagTitle": "", try {
* "tagReferenceCount": int, final JSONObject ret = new JSONObject();
* "tagPublishedRefCount": int
* } final JSONObject tag = tagRepository.getByTitle(tagTitle);
* }
* </pre>, returns {@code null} if not found if (null == tag) {
* @throws ServiceException service exception return null;
*/ }
<<<<<<< HEAD
public JSONObject getTagByTitle(final String tagTitle) ret.put(Tag.TAG, tag);
throws ServiceException {
======= LOGGER.log(Level.FINER, "Got an tag[title={0}]", tagTitle);
public JSONObject getTagByTitle(final String tagTitle) throws ServiceException {
>>>>>>> origin/0.4.6 return ret;
try { } catch (final RepositoryException e) {
final JSONObject ret = new JSONObject(); LOGGER.log(Level.SEVERE, "Gets an article failed", e);
throw new ServiceException(e);
final JSONObject tag = tagRepository.getByTitle(tagTitle); }
}
if (null == tag) {
return null; /**
} * Gets the count of tags.
*
ret.put(Tag.TAG, tag); * @return count of tags
* @throws ServiceException service exception
LOGGER.log(Level.FINER, "Got an tag[title={0}]", tagTitle); */
public long getTagCount() throws ServiceException {
return ret; try {
} catch (final RepositoryException e) { return tagRepository.count();
LOGGER.log(Level.SEVERE, "Gets an article failed", e); } catch (final RepositoryException e) {
throw new ServiceException(e); LOGGER.log(Level.SEVERE, "Gets tags failed", e);
}
} throw new ServiceException(e);
}
/** }
<<<<<<< HEAD
======= /**
* Gets the count of tags. >>>>>>> origin/0.4.6
* * Gets all tags.
* @return count of tags *
* @throws ServiceException service exception * @return for example,
*/ * <pre>
public long getTagCount() throws ServiceException { * [
try { * {"tagTitle": "", "tagReferenceCount": int, ....},
return tagRepository.count(); * ....
} catch (final RepositoryException e) { * ]
LOGGER.log(Level.SEVERE, "Gets tags failed", e); * </pre>, returns an empty list if not found
* @throws ServiceException service exception
throw new ServiceException(e); */
} public List<JSONObject> getTags() throws ServiceException {
} try {
final Query query = new Query().setPageCount(1);
/**
>>>>>>> origin/0.4.6 final JSONObject result = tagRepository.get(query);
* Gets all tags. final JSONArray tagArray = result.optJSONArray(Keys.RESULTS);
*
* @return for example, return CollectionUtils.jsonArrayToList(tagArray);
* <pre> } catch (final RepositoryException e) {
* [ LOGGER.log(Level.SEVERE, "Gets tags failed", e);
* {"tagTitle": "", "tagReferenceCount": int, ....},
* .... throw new ServiceException(e);
* ] }
* </pre>, returns an empty list if not found }
* @throws ServiceException service exception
*/ /**
public List<JSONObject> getTags() throws ServiceException { * Gets the {@link TagQueryService} singleton.
try { *
final Query query = new Query().setPageCount(1); * @return the singleton
*/
final JSONObject result = tagRepository.get(query); public static TagQueryService getInstance() {
final JSONArray tagArray = result.optJSONArray(Keys.RESULTS); return SingletonHolder.SINGLETON;
}
return CollectionUtils.jsonArrayToList(tagArray);
} catch (final RepositoryException e) { /**
LOGGER.log(Level.SEVERE, "Gets tags failed", e); * Private constructor.
*/
throw new ServiceException(e); private TagQueryService() {
} }
}
/**
/** * Singleton holder.
* Gets the {@link TagQueryService} singleton. *
* * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @return the singleton * @version 1.0.0.0, Oct 24, 2011
*/ */
public static TagQueryService getInstance() { private static final class SingletonHolder {
return SingletonHolder.SINGLETON;
} /**
* Singleton.
/** */
* Private constructor. private static final TagQueryService SINGLETON =
*/ new TagQueryService();
private TagQueryService() {
} /**
* Private default constructor.
/** */
* Singleton holder. private SingletonHolder() {
* }
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> }
* @version 1.0.0.0, Oct 24, 2011 }
*/
private static final class SingletonHolder {
/**
* Singleton.
*/
private static final TagQueryService SINGLETON =
new TagQueryService();
/**
* Private default constructor.
*/
private SingletonHolder() {
}
}
}
<<<<<<< HEAD /*
<<<<<<< HEAD * Copyright (c) 2009, 2010, 2011, 2012, B3log Team
======= *
>>>>>>> origin/0.4.6 * Licensed under the Apache License, Version 2.0 (the "License");
/* * you may not use this file except in compliance with the License.
* Copyright (c) 2009, 2010, 2011, 2012, B3log Team * You may obtain a copy of the License at
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * http://www.apache.org/licenses/LICENSE-2.0
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* http://www.apache.org/licenses/LICENSE-2.0 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* Unless required by applicable law or agreed to in writing, software * limitations under the License.
* distributed under the License is distributed on an "AS IS" BASIS, */
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. package org.b3log.solo.util;
* See the License for the specific language governing permissions and
* limitations under the License. import java.io.UnsupportedEncodingException;
*/ import java.net.URLEncoder;
package org.b3log.solo.util; import java.util.Date;
import java.util.HashMap;
import java.io.UnsupportedEncodingException; import java.util.List;
import java.net.URLEncoder; import java.util.Map;
import java.util.Date; import java.util.logging.Level;
import java.util.HashMap; import java.util.logging.Logger;
import java.util.List; import javax.servlet.http.HttpServletRequest;
import java.util.Map; import javax.servlet.http.HttpSession;
import java.util.logging.Level; import org.b3log.solo.model.Article;
import java.util.logging.Logger; import org.b3log.latke.Keys;
import javax.servlet.http.HttpServletRequest; import org.b3log.latke.repository.*;
import javax.servlet.http.HttpSession; import org.b3log.latke.service.ServiceException;
import org.b3log.solo.model.Article; import org.b3log.latke.user.UserService;
import org.b3log.latke.Keys; import org.b3log.latke.user.UserServiceFactory;
<<<<<<< HEAD import org.b3log.latke.util.CollectionUtils;
import org.b3log.latke.repository.FilterOperator; import org.b3log.latke.util.Strings;
import org.b3log.latke.repository.Query; import org.b3log.solo.model.Common;
import org.b3log.latke.repository.RepositoryException; import org.b3log.solo.model.Preference;
import org.b3log.latke.repository.SortDirection; import org.b3log.solo.repository.ArticleRepository;
======= import org.b3log.solo.repository.UserRepository;
import org.b3log.latke.repository.*; import org.b3log.solo.repository.impl.ArticleRepositoryImpl;
>>>>>>> origin/0.4.6 import org.b3log.solo.repository.impl.UserRepositoryImpl;
import org.b3log.latke.service.ServiceException; import org.json.JSONArray;
import org.b3log.latke.user.UserService; import org.json.JSONException;
import org.b3log.latke.user.UserServiceFactory; import org.json.JSONObject;
import org.b3log.latke.util.CollectionUtils;
import org.b3log.latke.util.Strings; /**
import org.b3log.solo.model.Common; * Article utilities.
import org.b3log.solo.model.Preference; *
import org.b3log.solo.repository.ArticleRepository; * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
import org.b3log.solo.repository.UserRepository; * @version 1.0.2.8, May 6, 2012
import org.b3log.solo.repository.impl.ArticleRepositoryImpl; * @since 0.3.1
import org.b3log.solo.repository.impl.UserRepositoryImpl; */
import org.json.JSONArray; public final class Articles {
import org.json.JSONException;
import org.json.JSONObject; /**
* Logger.
/** */
* Article utilities. private static final Logger LOGGER = Logger.getLogger(Articles.class.getName());
* /**
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * Article repository.
* @version 1.0.2.8, May 6, 2012 */
* @since 0.3.1 private ArticleRepository articleRepository = ArticleRepositoryImpl.getInstance();
*/ /**
public final class Articles { * User repository.
*/
/** private UserRepository userRepository = UserRepositoryImpl.getInstance();
* Logger. /**
*/ * User service.
private static final Logger LOGGER = Logger.getLogger(Articles.class.getName()); */
/** private UserService userService = UserServiceFactory.getUserService();
* Article repository.
*/ /**
private ArticleRepository articleRepository = ArticleRepositoryImpl.getInstance(); * Builds article view password form parameters with the specified article.
/** *
* User repository. * @param article the specified article
*/ * @return parameters string, for example,
private UserRepository userRepository = UserRepositoryImpl.getInstance(); * <pre>
/** * "?articleId=xxx&articleTitle=xxx&articlePermalink=xxx&articleAbstract=xxx"
* User service. * </pre>
*/ * @throws UnsupportedEncodingException if can not encode the arguments
private UserService userService = UserServiceFactory.getUserService(); */
public String buildArticleViewPwdFormParameters(final JSONObject article) throws UnsupportedEncodingException {
/** final StringBuilder parametersBuilder =
* Builds article view password form parameters with the specified article. new StringBuilder("?articleId=").append(article.optString(Keys.OBJECT_ID)).
* append("&articleTitle=").append(URLEncoder.encode(article.optString(Article.ARTICLE_TITLE), "UTF-8")).
* @param article the specified article append("&articlePermalink=").append(URLEncoder.encode(article.optString(Article.ARTICLE_PERMALINK), "UTF-8")).
* @return parameters string, for example, append("&articleAbstract=").append(URLEncoder.encode(article.optString(Article.ARTICLE_ABSTRACT, " "), "UTF-8"));
* <pre>
* "?articleId=xxx&articleTitle=xxx&articlePermalink=xxx&articleAbstract=xxx" return parametersBuilder.toString();
* </pre> }
* @throws UnsupportedEncodingException if can not encode the arguments
*/ /**
public String buildArticleViewPwdFormParameters(final JSONObject article) throws UnsupportedEncodingException { * Checks whether need password to view the specified article with the specified request.
final StringBuilder parametersBuilder = *
new StringBuilder("?articleId=").append(article.optString(Keys.OBJECT_ID)). * <p>
append("&articleTitle=").append(URLEncoder.encode(article.optString(Article.ARTICLE_TITLE), "UTF-8")). * Checks session, if not represents, checks article property {@link Article#ARTICLE_VIEW_PWD view password}.
append("&articlePermalink=").append(URLEncoder.encode(article.optString(Article.ARTICLE_PERMALINK), "UTF-8")). * </p>
append("&articleAbstract=").append(URLEncoder.encode(article.optString(Article.ARTICLE_ABSTRACT, " "), "UTF-8")); *
* <p>
return parametersBuilder.toString(); * The blogger itself dose not need view password never.
} * </p>
*
/** * @param request the specified request
* Checks whether need password to view the specified article with the specified request. * @param article the specified article
* * @return {@code true} if need, returns {@code false} otherwise
* <p> */
* Checks session, if not represents, checks article property {@link Article#ARTICLE_VIEW_PWD view password}. public boolean needViewPwd(final HttpServletRequest request, final JSONObject article) {
* </p> final String articleViewPwd = article.optString(Article.ARTICLE_VIEW_PWD);
*
* <p> if (Strings.isEmptyOrNull(articleViewPwd)) {
* The blogger itself dose not need view password never. return false;
* </p> }
*
* @param request the specified request final HttpSession session = request.getSession(false);
* @param article the specified article if (null != session) {
* @return {@code true} if need, returns {@code false} otherwise @SuppressWarnings("unchecked")
*/ Map<String, String> viewPwds = (Map<String, String>) session.getAttribute(Common.ARTICLES_VIEW_PWD);
public boolean needViewPwd(final HttpServletRequest request, final JSONObject article) { if (null == viewPwds) {
final String articleViewPwd = article.optString(Article.ARTICLE_VIEW_PWD); viewPwds = new HashMap<String, String>();
}
if (Strings.isEmptyOrNull(articleViewPwd)) {
return false; if (articleViewPwd.equals(viewPwds.get(article.optString(Keys.OBJECT_ID)))) {
} return false;
}
final HttpSession session = request.getSession(false); }
if (null != session) {
@SuppressWarnings("unchecked") if (null != userService.getCurrentUser(request)) {
Map<String, String> viewPwds = (Map<String, String>) session.getAttribute(Common.ARTICLES_VIEW_PWD); return false;
if (null == viewPwds) { }
viewPwds = new HashMap<String, String>();
} return true;
}
if (articleViewPwd.equals(viewPwds.get(article.optString(Keys.OBJECT_ID)))) {
return false; /*
} * Gets time of the recent updated article.
} *
* @return time of the recent updated article, returns {@code 0} if not found
if (null != userService.getCurrentUser(request)) { * @throws ServiceException service exception
return false; */
} public long getRecentArticleTime() throws ServiceException {
try {
return true; final List<JSONObject> recentArticles = articleRepository.getRecentArticles(1);
} if (recentArticles.isEmpty()) {
return 0;
/** }
<<<<<<< HEAD
* Gets the specified article's author. final JSONObject recentArticle = recentArticles.get(0);
* return ((Date) recentArticle.get(Article.ARTICLE_UPDATE_DATE)).getTime();
* <p> } catch (final Exception e) {
* The specified article has a property LOGGER.log(Level.SEVERE, e.getMessage(), e);
* {@value Article#ARTICLE_AUTHOR_EMAIL}, this method will use this property throw new ServiceException("Gets recent article time failed");
* to get a user from users. }
* </p> }
*
* <p> /**
* If can't find the specified article's author (i.e. the author has been * Gets the specified article's author.
* removed by administrator), returns administrator. *
* </p> * <p>
* * The specified article has a property
* @param article the specified article * {@value Article#ARTICLE_AUTHOR_EMAIL}, this method will use this property
* @return user, {@code null} if not found * to get a user from users.
* @throws ServiceException service exception * </p>
*/ *
public JSONObject getAuthor(final JSONObject article) throws ServiceException { * <p>
try { * If can't find the specified article's author (i.e. the author has been
final String email = article.getString(Article.ARTICLE_AUTHOR_EMAIL); * removed by administrator), returns administrator.
* </p>
JSONObject ret = userRepository.getByEmail(email); *
* @param article the specified article
if (null == ret) { * @return user, {@code null} if not found
LOGGER.log(Level.WARNING, * @throws ServiceException service exception
"Gets author of article failed, assumes the administrator is the author of this article[id={0}]", */
article.getString(Keys.OBJECT_ID)); public JSONObject getAuthor(final JSONObject article) throws ServiceException {
// This author may be deleted by admin, use admin as the author try {
// of this article final String email = article.getString(Article.ARTICLE_AUTHOR_EMAIL);
ret = userRepository.getAdmin();
} JSONObject ret = userRepository.getByEmail(email);
return ret; if (null == ret) {
} catch (final RepositoryException e) { LOGGER.log(Level.WARNING,
LOGGER.log(Level.SEVERE, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID)); "Gets author of article failed, assumes the administrator is the author of this article[id={0}]",
throw new ServiceException(e); article.getString(Keys.OBJECT_ID));
} catch (final JSONException e) { // This author may be deleted by admin, use admin as the author
LOGGER.log(Level.SEVERE, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID)); // of this article
throw new ServiceException(e); ret = userRepository.getAdmin();
} }
}
return ret;
/** } catch (final RepositoryException e) {
* Article comment count +1 for an article specified by the given article id. LOGGER.log(Level.SEVERE, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID));
* throw new ServiceException(e);
* @param articleId the given article id } catch (final JSONException e) {
* @throws JSONException json exception LOGGER.log(Level.SEVERE, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID));
* @throws RepositoryException repository exception throw new ServiceException(e);
*/ }
public void incArticleCommentCount(final String articleId) throws JSONException, RepositoryException { }
final JSONObject article = articleRepository.get(articleId);
final JSONObject newArticle = new JSONObject(article, JSONObject.getNames(article)); /**
final int commentCnt = article.getInt(Article.ARTICLE_COMMENT_COUNT); * Article comment count +1 for an article specified by the given article id.
newArticle.put(Article.ARTICLE_COMMENT_COUNT, commentCnt + 1); *
* @param articleId the given article id
articleRepository.update(articleId, newArticle); * @throws JSONException json exception
} * @throws RepositoryException repository exception
*/
/** public void incArticleCommentCount(final String articleId) throws JSONException, RepositoryException {
* Gets the sign of an article specified by the sign id. final JSONObject article = articleRepository.get(articleId);
* final JSONObject newArticle = new JSONObject(article, JSONObject.getNames(article));
* @param signId the specified article id final int commentCnt = article.getInt(Article.ARTICLE_COMMENT_COUNT);
* @param preference the specified preference newArticle.put(Article.ARTICLE_COMMENT_COUNT, commentCnt + 1);
* @return article sign, returns the default sign (which oId is "1") if not found
* @throws RepositoryException repository exception articleRepository.update(articleId, newArticle);
* @throws JSONException json exception }
*/
public JSONObject getSign(final String signId, final JSONObject preference) throws JSONException, RepositoryException { /**
final JSONArray signs = new JSONArray(preference.getString(Preference.SIGNS)); * Gets the sign of an article specified by the sign id.
*
JSONObject defaultSign = null; * @param signId the specified article id
for (int i = 0; i < signs.length(); i++) { * @param preference the specified preference
final JSONObject ret = signs.getJSONObject(i); * @return article sign, returns the default sign (which oId is "1") if not found
if (signId.equals(ret.optString(Keys.OBJECT_ID))) { * @throws RepositoryException repository exception
return ret; * @throws JSONException json exception
} */
public JSONObject getSign(final String signId, final JSONObject preference) throws JSONException, RepositoryException {
if ("1".equals(ret.optString(Keys.OBJECT_ID))) { final JSONArray signs = new JSONArray(preference.getString(Preference.SIGNS));
defaultSign = ret;
} JSONObject defaultSign = null;
} for (int i = 0; i < signs.length(); i++) {
final JSONObject ret = signs.getJSONObject(i);
LOGGER.log(Level.WARNING, "Can not find the sign[id={0}], returns a default sign[id=1]", signId); if (signId.equals(ret.optString(Keys.OBJECT_ID))) {
if (null == defaultSign) { return ret;
throw new IllegalStateException("Can not find the default sign which id equals to 1"); }
}
if ("1".equals(ret.optString(Keys.OBJECT_ID))) {
return defaultSign; defaultSign = ret;
} }
}
/**
* Determines the specified article has updated. LOGGER.log(Level.WARNING, "Can not find the sign[id={0}], returns a default sign[id=1]", signId);
* if (null == defaultSign) {
* @param article the specified article throw new IllegalStateException("Can not find the default sign which id equals to 1");
* @return {@code true} if it has updated, {@code false} otherwise }
* @throws JSONException json exception
*/ return defaultSign;
public boolean hasUpdated(final JSONObject article) throws JSONException { }
final Date updateDate = (Date) article.get(Article.ARTICLE_UPDATE_DATE);
final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE); /**
* Determines the specified article has updated.
return !createDate.equals(updateDate); *
} * @param article the specified article
* @return {@code true} if it has updated, {@code false} otherwise
/** * @throws JSONException json exception
* Determines the specified article had been published. */
* public boolean hasUpdated(final JSONObject article) throws JSONException {
* @param article the specified article final Date updateDate = (Date) article.get(Article.ARTICLE_UPDATE_DATE);
* @return {@code true} if it had been published, {@code false} otherwise final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE);
* @throws JSONException json exception
*/ return !createDate.equals(updateDate);
public boolean hadBeenPublished(final JSONObject article) throws JSONException { }
return article.getBoolean(Article.ARTICLE_HAD_BEEN_PUBLISHED);
} /**
* Determines the specified article had been published.
/** *
* Gets all unpublished articles. * @param article the specified article
* * @return {@code true} if it had been published, {@code false} otherwise
* @return articles all unpublished articles * @throws JSONException json exception
* @throws RepositoryException repository exception */
* @throws JSONException json exception public boolean hadBeenPublished(final JSONObject article) throws JSONException {
*/ return article.getBoolean(Article.ARTICLE_HAD_BEEN_PUBLISHED);
public List<JSONObject> getUnpublishedArticles() throws RepositoryException, JSONException { }
final Map<String, SortDirection> sorts = new HashMap<String, SortDirection>();
sorts.put(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING); /**
sorts.put(Article.ARTICLE_PUT_TOP, SortDirection.DESCENDING); * Gets all unpublished articles.
final Query query = new Query().addFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true); *
final JSONObject result = articleRepository.get(query); * @return articles all unpublished articles
final JSONArray articles = result.getJSONArray(Keys.RESULTS); * @throws RepositoryException repository exception
* @throws JSONException json exception
return CollectionUtils.jsonArrayToList(articles); */
} public List<JSONObject> getUnpublishedArticles() throws RepositoryException, JSONException {
final Map<String, SortDirection> sorts = new HashMap<String, SortDirection>();
/** sorts.put(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING);
* Gets the {@link Articles} singleton. sorts.put(Article.ARTICLE_PUT_TOP, SortDirection.DESCENDING);
* final Query query = new Query().setFilter(
* @return the singleton new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true));
*/ final JSONObject result = articleRepository.get(query);
public static Articles getInstance() { final JSONArray articles = result.getJSONArray(Keys.RESULTS);
return SingletonHolder.SINGLETON;
} return CollectionUtils.jsonArrayToList(articles);
}
/**
* Private default constructor. /**
*/ * Gets the {@link Articles} singleton.
private Articles() { *
} * @return the singleton
*/
/** public static Articles getInstance() {
* Singleton holder. return SingletonHolder.SINGLETON;
* }
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.0, Jan 12, 2011 /**
*/ * Private default constructor.
private static final class SingletonHolder { */
private Articles() {
/** }
* Singleton.
*/ /**
private static final Articles SINGLETON = new Articles(); * Singleton holder.
*
/** * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* Private default constructor. * @version 1.0.0.0, Jan 12, 2011
*/ */
private SingletonHolder() { private static final class SingletonHolder {
}
} /**
} * Singleton.
======= */
/* private static final Articles SINGLETON = new Articles();
* Copyright (c) 2009, 2010, 2011, 2012, B3log Team
* /**
* Licensed under the Apache License, Version 2.0 (the "License"); * Private default constructor.
* you may not use this file except in compliance with the License. */
* You may obtain a copy of the License at private SingletonHolder() {
* }
* http://www.apache.org/licenses/LICENSE-2.0 }
* }
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.solo.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.b3log.solo.model.Article;
import org.b3log.latke.Keys;
import org.b3log.latke.repository.*;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.user.UserService;
import org.b3log.latke.user.UserServiceFactory;
import org.b3log.latke.util.CollectionUtils;
import org.b3log.latke.util.Strings;
import org.b3log.solo.model.Common;
import org.b3log.solo.model.Preference;
import org.b3log.solo.repository.ArticleRepository;
import org.b3log.solo.repository.UserRepository;
import org.b3log.solo.repository.impl.ArticleRepositoryImpl;
import org.b3log.solo.repository.impl.UserRepositoryImpl;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Article utilities.
*
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.2.8, May 6, 2012
* @since 0.3.1
*/
public final class Articles {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(Articles.class.getName());
/**
* Article repository.
*/
private ArticleRepository articleRepository = ArticleRepositoryImpl.getInstance();
/**
* User repository.
*/
private UserRepository userRepository = UserRepositoryImpl.getInstance();
/**
* User service.
*/
private UserService userService = UserServiceFactory.getUserService();
/**
* Builds article view password form parameters with the specified article.
*
* @param article the specified article
* @return parameters string, for example,
* <pre>
* "?articleId=xxx&articleTitle=xxx&articlePermalink=xxx&articleAbstract=xxx"
* </pre>
* @throws UnsupportedEncodingException if can not encode the arguments
*/
public String buildArticleViewPwdFormParameters(final JSONObject article) throws UnsupportedEncodingException {
final StringBuilder parametersBuilder =
new StringBuilder("?articleId=").append(article.optString(Keys.OBJECT_ID)).
append("&articleTitle=").append(URLEncoder.encode(article.optString(Article.ARTICLE_TITLE), "UTF-8")).
append("&articlePermalink=").append(URLEncoder.encode(article.optString(Article.ARTICLE_PERMALINK), "UTF-8")).
append("&articleAbstract=").append(URLEncoder.encode(article.optString(Article.ARTICLE_ABSTRACT, " "), "UTF-8"));
return parametersBuilder.toString();
}
/**
* Checks whether need password to view the specified article with the specified request.
*
* <p>
* Checks session, if not represents, checks article property {@link Article#ARTICLE_VIEW_PWD view password}.
* </p>
*
* <p>
* The blogger itself dose not need view password never.
* </p>
*
* @param request the specified request
* @param article the specified article
* @return {@code true} if need, returns {@code false} otherwise
*/
public boolean needViewPwd(final HttpServletRequest request, final JSONObject article) {
final String articleViewPwd = article.optString(Article.ARTICLE_VIEW_PWD);
if (Strings.isEmptyOrNull(articleViewPwd)) {
return false;
}
final HttpSession session = request.getSession(false);
if (null != session) {
@SuppressWarnings("unchecked")
Map<String, String> viewPwds = (Map<String, String>) session.getAttribute(Common.ARTICLES_VIEW_PWD);
if (null == viewPwds) {
viewPwds = new HashMap<String, String>();
}
if (articleViewPwd.equals(viewPwds.get(article.optString(Keys.OBJECT_ID)))) {
return false;
}
}
if (null != userService.getCurrentUser(request)) {
return false;
}
return true;
=======
* Gets time of the recent updated article.
*
* @return time of the recent updated article, returns {@code 0} if not found
* @throws ServiceException service exception
*/
public long getRecentArticleTime() throws ServiceException {
try {
final List<JSONObject> recentArticles = articleRepository.getRecentArticles(1);
if (recentArticles.isEmpty()) {
return 0;
}
final JSONObject recentArticle = recentArticles.get(0);
return ((Date) recentArticle.get(Article.ARTICLE_UPDATE_DATE)).getTime();
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
throw new ServiceException("Gets recent article time failed");
}
>>>>>>> origin/0.4.6
}
/**
* 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.WARNING,
"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.SEVERE, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID));
throw new ServiceException(e);
} catch (final JSONException e) {
LOGGER.log(Level.SEVERE, "Gets author of article[id={0}] failed", article.optString(Keys.OBJECT_ID));
throw new ServiceException(e);
}
}
/**
* Article comment count +1 for an article specified by the given article id.
*
* @param articleId the given article id
* @throws JSONException json exception
* @throws RepositoryException repository exception
*/
public void incArticleCommentCount(final String articleId) throws JSONException, RepositoryException {
final JSONObject article = articleRepository.get(articleId);
final JSONObject newArticle = new JSONObject(article, JSONObject.getNames(article));
final int commentCnt = article.getInt(Article.ARTICLE_COMMENT_COUNT);
newArticle.put(Article.ARTICLE_COMMENT_COUNT, commentCnt + 1);
articleRepository.update(articleId, newArticle);
}
/**
* Gets the sign of an article specified by the sign id.
*
* @param signId the specified article id
* @param preference the specified preference
* @return article sign, returns the default sign (which oId is "1") if not found
* @throws RepositoryException repository exception
* @throws JSONException json exception
*/
public JSONObject getSign(final String signId, final JSONObject preference) throws JSONException, RepositoryException {
final JSONArray signs = new JSONArray(preference.getString(Preference.SIGNS));
JSONObject defaultSign = null;
for (int i = 0; i < signs.length(); i++) {
final JSONObject ret = signs.getJSONObject(i);
if (signId.equals(ret.optString(Keys.OBJECT_ID))) {
return ret;
}
if ("1".equals(ret.optString(Keys.OBJECT_ID))) {
defaultSign = ret;
}
}
LOGGER.log(Level.WARNING, "Can not find the sign[id={0}], returns a default sign[id=1]", signId);
if (null == defaultSign) {
throw new IllegalStateException("Can not find the default sign which id equals to 1");
}
return defaultSign;
}
/**
* Determines the specified article has updated.
*
* @param article the specified article
* @return {@code true} if it has updated, {@code false} otherwise
* @throws JSONException json exception
*/
public boolean hasUpdated(final JSONObject article) throws JSONException {
final Date updateDate = (Date) article.get(Article.ARTICLE_UPDATE_DATE);
final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE);
return !createDate.equals(updateDate);
}
/**
* Determines the specified article had been published.
*
* @param article the specified article
* @return {@code true} if it had been published, {@code false} otherwise
* @throws JSONException json exception
*/
public boolean hadBeenPublished(final JSONObject article) throws JSONException {
return article.getBoolean(Article.ARTICLE_HAD_BEEN_PUBLISHED);
}
/**
* Gets all unpublished articles.
*
* @return articles all unpublished articles
* @throws RepositoryException repository exception
* @throws JSONException json exception
*/
public List<JSONObject> getUnpublishedArticles() throws RepositoryException, JSONException {
final Map<String, SortDirection> sorts = new HashMap<String, SortDirection>();
sorts.put(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING);
sorts.put(Article.ARTICLE_PUT_TOP, SortDirection.DESCENDING);
final Query query = new Query().setFilter(
new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true));
final JSONObject result = articleRepository.get(query);
final JSONArray articles = result.getJSONArray(Keys.RESULTS);
return CollectionUtils.jsonArrayToList(articles);
}
/**
* Gets the {@link Articles} singleton.
*
* @return the singleton
*/
public static Articles getInstance() {
return SingletonHolder.SINGLETON;
}
/**
* Private default constructor.
*/
private Articles() {
}
/**
* Singleton holder.
*
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.0, Jan 12, 2011
*/
private static final class SingletonHolder {
/**
* Singleton.
*/
private static final Articles SINGLETON = new Articles();
/**
* Private default constructor.
*/
private SingletonHolder() {
}
}
}
<<<<<<< HEAD
>>>>>>> origin/0.4.6
=======
>>>>>>> origin/0.4.6
<<<<<<< HEAD /*
<<<<<<< HEAD * Copyright (c) 2009, 2010, 2011, 2012, B3log Team
/* *
* Copyright (c) 2009, 2010, 2011, 2012, B3log Team * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0
* *
* http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* distributed under the License is distributed on an "AS IS" BASIS, * See the License for the specific language governing permissions and
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * limitations under the License.
* See the License for the specific language governing permissions and */
* limitations under the License. package org.b3log.solo.repository.impl;
*/
package org.b3log.solo.repository.impl; import org.b3log.latke.Keys;
import org.b3log.latke.model.Role;
import org.b3log.latke.Keys; import org.b3log.latke.model.User;
import org.b3log.latke.model.Role; import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.model.User; import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.FilterOperator; import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.Query; import org.b3log.latke.repository.Transaction;
import org.b3log.latke.repository.Transaction; import org.b3log.solo.AbstractTestCase;
import org.b3log.solo.AbstractTestCase; import org.b3log.solo.model.UserExt;
import org.b3log.solo.model.UserExt; import org.b3log.solo.repository.UserRepository;
import org.b3log.solo.repository.UserRepository; import org.json.JSONArray;
import org.json.JSONArray; import org.json.JSONObject;
import org.json.JSONObject; import org.testng.Assert;
import org.testng.Assert; import org.testng.annotations.Test;
import org.testng.annotations.Test;
/**
/** * {@link UserRepositoryImpl} test case.
* {@link UserRepositoryImpl} test case. *
* * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @version 1.0.0.1, Feb 21, 2012
* @version 1.0.0.1, Feb 21, 2012 */
*/ @Test(suiteName = "repository")
@Test(suiteName = "repository") public final class UserRepositoryImplTestCase extends AbstractTestCase {
public final class UserRepositoryImplTestCase extends AbstractTestCase {
/**
/** * Tests.
* Tests. *
* * @throws Exception exception
* @throws Exception exception */
*/ @Test
@Test public void test() throws Exception {
public void test() throws Exception { final UserRepository userRepository = getUserRepository();
final UserRepository userRepository = getUserRepository();
final JSONObject another = new JSONObject();
final JSONObject another = new JSONObject(); another.put(User.USER_NAME, "test1");
another.put(User.USER_NAME, "test1"); another.put(User.USER_EMAIL, "test1@gmail.com");
another.put(User.USER_EMAIL, "test1@gmail.com"); another.put(User.USER_PASSWORD, "pass1");
another.put(User.USER_PASSWORD, "pass1"); another.put(User.USER_ROLE, Role.DEFAULT_ROLE);
another.put(User.USER_ROLE, Role.DEFAULT_ROLE); another.put(UserExt.USER_ARTICLE_COUNT, 0);
another.put(UserExt.USER_ARTICLE_COUNT, 0); another.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, 0);
another.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, 0);
Transaction transaction = userRepository.beginTransaction();
Transaction transaction = userRepository.beginTransaction(); userRepository.add(another);
userRepository.add(another); transaction.commit();
transaction.commit();
Assert.assertNull(userRepository.getAdmin());
Assert.assertNull(userRepository.getAdmin());
JSONObject admin = new JSONObject();
JSONObject admin = new JSONObject(); admin.put(User.USER_NAME, "test");
admin.put(User.USER_NAME, "test"); admin.put(User.USER_EMAIL, "test@gmail.com");
admin.put(User.USER_EMAIL, "test@gmail.com"); admin.put(User.USER_PASSWORD, "pass");
admin.put(User.USER_PASSWORD, "pass"); admin.put(User.USER_ROLE, Role.ADMIN_ROLE);
admin.put(User.USER_ROLE, Role.ADMIN_ROLE); admin.put(UserExt.USER_ARTICLE_COUNT, 0);
admin.put(UserExt.USER_ARTICLE_COUNT, 0); admin.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, 0);
admin.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, 0);
transaction = userRepository.beginTransaction();
transaction = userRepository.beginTransaction(); userRepository.add(admin);
userRepository.add(admin); transaction.commit();
transaction.commit();
Assert.assertTrue(userRepository.isAdminEmail("test@gmail.com"));
Assert.assertTrue(userRepository.isAdminEmail("test@gmail.com")); Assert.assertFalse(userRepository.isAdminEmail("notFound@gmail.com"));
Assert.assertFalse(userRepository.isAdminEmail("notFound@gmail.com"));
admin = userRepository.getAdmin();
admin = userRepository.getAdmin();
Assert.assertNotNull(admin);
Assert.assertNotNull(admin); Assert.assertEquals("test", admin.optString(User.USER_NAME));
Assert.assertEquals("test", admin.optString(User.USER_NAME));
final JSONObject result = userRepository.get(new Query().setFilter(
final JSONObject result = new PropertyFilter(User.USER_NAME, FilterOperator.EQUAL, "test1")));
userRepository.get(new Query().addFilter(User.USER_NAME,
FilterOperator.EQUAL, final JSONArray users = result.getJSONArray(Keys.RESULTS);
"test1")); Assert.assertEquals(users.length(), 1);
Assert.assertEquals(users.getJSONObject(0).getString(User.USER_EMAIL), "test1@gmail.com");
final JSONArray users = result.getJSONArray(Keys.RESULTS);
Assert.assertEquals(users.length(), 1); final JSONObject notFound = userRepository.getByEmail("not.found@gmail.com");
Assert.assertEquals(users.getJSONObject(0).getString(User.USER_EMAIL), Assert.assertNull(notFound);
"test1@gmail.com");
final JSONObject found = userRepository.getByEmail("test1@gmail.com");
final JSONObject notFound = Assert.assertNotNull(found);
userRepository.getByEmail("not.found@gmail.com"); Assert.assertEquals(found.getString(User.USER_PASSWORD), "pass1");
Assert.assertNull(notFound); }
}
final JSONObject found = userRepository.getByEmail("test1@gmail.com");
Assert.assertNotNull(found);
Assert.assertEquals(found.getString(User.USER_PASSWORD), "pass1");
}
}
=======
=======
>>>>>>> origin/0.4.6
/*
* Copyright (c) 2009, 2010, 2011, 2012, B3log Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.solo.repository.impl;
import org.b3log.latke.Keys;
import org.b3log.latke.model.Role;
import org.b3log.latke.model.User;
import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.Transaction;
import org.b3log.solo.AbstractTestCase;
import org.b3log.solo.model.UserExt;
import org.b3log.solo.repository.UserRepository;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* {@link UserRepositoryImpl} test case.
*
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.1, Feb 21, 2012
*/
@Test(suiteName = "repository")
public final class UserRepositoryImplTestCase extends AbstractTestCase {
/**
* Tests.
*
* @throws Exception exception
*/
@Test
public void test() throws Exception {
final UserRepository userRepository = getUserRepository();
final JSONObject another = new JSONObject();
another.put(User.USER_NAME, "test1");
another.put(User.USER_EMAIL, "test1@gmail.com");
another.put(User.USER_PASSWORD, "pass1");
another.put(User.USER_ROLE, Role.DEFAULT_ROLE);
another.put(UserExt.USER_ARTICLE_COUNT, 0);
another.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, 0);
Transaction transaction = userRepository.beginTransaction();
userRepository.add(another);
transaction.commit();
Assert.assertNull(userRepository.getAdmin());
JSONObject admin = new JSONObject();
admin.put(User.USER_NAME, "test");
admin.put(User.USER_EMAIL, "test@gmail.com");
admin.put(User.USER_PASSWORD, "pass");
admin.put(User.USER_ROLE, Role.ADMIN_ROLE);
admin.put(UserExt.USER_ARTICLE_COUNT, 0);
admin.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, 0);
transaction = userRepository.beginTransaction();
userRepository.add(admin);
transaction.commit();
Assert.assertTrue(userRepository.isAdminEmail("test@gmail.com"));
Assert.assertFalse(userRepository.isAdminEmail("notFound@gmail.com"));
admin = userRepository.getAdmin();
Assert.assertNotNull(admin);
Assert.assertEquals("test", admin.optString(User.USER_NAME));
final JSONObject result =
userRepository.get(new Query().setFilter(
new PropertyFilter(User.USER_NAME, FilterOperator.EQUAL, "test1")));
final JSONArray users = result.getJSONArray(Keys.RESULTS);
Assert.assertEquals(users.length(), 1);
Assert.assertEquals(users.getJSONObject(0).getString(User.USER_EMAIL),
"test1@gmail.com");
final JSONObject notFound =
userRepository.getByEmail("not.found@gmail.com");
Assert.assertNull(notFound);
final JSONObject found = userRepository.getByEmail("test1@gmail.com");
Assert.assertNotNull(found);
Assert.assertEquals(found.getString(User.USER_PASSWORD), "pass1");
}
}
<<<<<<< HEAD
>>>>>>> origin/0.4.6
=======
>>>>>>> origin/0.4.6
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment