Commit 4486b679 authored by Liang Ding's avatar Liang Ding

#199

完成社区同步更新博客(issue 描述里的第一点:1. 提供文章更新接口给社区)
parent 9e1d40df
...@@ -33,6 +33,7 @@ import org.b3log.solo.model.Article; ...@@ -33,6 +33,7 @@ import org.b3log.solo.model.Article;
import org.b3log.solo.model.Common; import org.b3log.solo.model.Common;
import org.b3log.solo.model.Preference; import org.b3log.solo.model.Preference;
import org.b3log.solo.service.ArticleMgmtService; import org.b3log.solo.service.ArticleMgmtService;
import org.b3log.solo.service.ArticleQueryService;
import org.b3log.solo.service.PreferenceQueryService; import org.b3log.solo.service.PreferenceQueryService;
import org.b3log.solo.service.UserQueryService; import org.b3log.solo.service.UserQueryService;
import org.b3log.solo.util.QueryResults; import org.b3log.solo.util.QueryResults;
...@@ -44,7 +45,7 @@ import org.jsoup.Jsoup; ...@@ -44,7 +45,7 @@ import org.jsoup.Jsoup;
* Article receiver (from B3log Symphony). * Article receiver (from B3log Symphony).
* *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.4, Jan 4, 2013 * @version 1.0.0.5, Mar 18, 2013
* @since 0.5.5 * @since 0.5.5
*/ */
@RequestProcessor @RequestProcessor
...@@ -65,6 +66,11 @@ public final class ArticleReceiver { ...@@ -65,6 +66,11 @@ public final class ArticleReceiver {
*/ */
private ArticleMgmtService articleMgmtService = ArticleMgmtService.getInstance(); private ArticleMgmtService articleMgmtService = ArticleMgmtService.getInstance();
/**
* Article query service.
*/
private ArticleQueryService articleQueryService = ArticleQueryService.getInstance();
/** /**
* Article abstract length. * Article abstract length.
*/ */
...@@ -101,7 +107,7 @@ public final class ArticleReceiver { ...@@ -101,7 +107,7 @@ public final class ArticleReceiver {
* @param context the specified http request context * @param context the specified http request context
* @throws Exception exception * @throws Exception exception
*/ */
@RequestProcessing(value = "/apis/symphony/article", method = HTTPRequestMethod.PUT) @RequestProcessing(value = "/apis/symphony/article", method = HTTPRequestMethod.POST)
public void addArticle(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) public void addArticle(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context)
throws Exception { throws Exception {
final JSONRenderer renderer = new JSONRenderer(); final JSONRenderer renderer = new JSONRenderer();
...@@ -142,7 +148,7 @@ public final class ArticleReceiver { ...@@ -142,7 +148,7 @@ public final class ArticleReceiver {
final String articleId = article.getString(Keys.OBJECT_ID); final String articleId = article.getString(Keys.OBJECT_ID);
content += "<br/><br/><p style='font-size: 12px;'><i>该文章同步自 <a href='http://symphony.b3log.org/article/" + articleId content += "<br/><br/><p style='font-size: 12px;'><i>该文章同步自 <a href='http://symphony.b3log.org/article/" + articleId
+ "' target='_blank>B3log 社区</a></i></p>"; + "' target='_blank'>B3log 社区</a></i></p>";
article.put(Article.ARTICLE_CONTENT, content); article.put(Article.ARTICLE_CONTENT, content);
articleMgmtService.addArticle(requestJSONObject); articleMgmtService.addArticle(requestJSONObject);
...@@ -161,4 +167,98 @@ public final class ArticleReceiver { ...@@ -161,4 +167,98 @@ public final class ArticleReceiver {
jsonObject.put(Keys.MSG, e.getMessage()); jsonObject.put(Keys.MSG, e.getMessage());
} }
} }
/**
* Updates an article with the specified request.
*
* <p>
* Renders the response with a json object, for example,
* <pre>
* {
* "sc": boolean,
* "msg": ""
* }
* </pre>
* </p>
*
* @param request the specified http servlet request, for example,
* <pre>
* {
* "article": {
* "oId": "", // Symphony Article#clientArticleId
* "articleTitle": "",
* "articleContent": "",
* "articleTags": "tag1,tag2,tag3",
* "userB3Key": "",
* "articleEditorType": ""
* }
* }
* </pre>
* @param response the specified http servlet response
* @param context the specified http request context
* @throws Exception exception
*/
@RequestProcessing(value = "/apis/symphony/article", method = HTTPRequestMethod.PUT)
public void updateArticle(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context)
throws Exception {
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
final JSONObject ret = new JSONObject();
renderer.setJSONObject(ret);
try {
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
final JSONObject article = requestJSONObject.optJSONObject(Article.ARTICLE);
final String userB3Key = article.optString("userB3Key");
final JSONObject preference = preferenceQueryService.getPreference();
if (!userB3Key.equals(preference.optString(Preference.KEY_OF_SOLO))) {
LOGGER.log(Level.WARNING, "B3 key not match, ignored update article");
return;
}
article.remove("userB3Key");
final String articleId = article.getString(Keys.OBJECT_ID);
if (null == articleQueryService.getArticleById(articleId)) {
ret.put(Keys.MSG, "No found article[oId=" + articleId + "] to update");
ret.put(Keys.STATUS_CODE, false);
return;
}
final String plainTextContent = Jsoup.parse(article.optString(Article.ARTICLE_CONTENT)).text();
if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) {
article.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH) + "....");
} else {
article.put(Article.ARTICLE_ABSTRACT, plainTextContent);
}
article.put(Article.ARTICLE_IS_PUBLISHED, true);
article.put(Common.POST_TO_COMMUNITY, false); // Do not send to rhythm
article.put(Article.ARTICLE_COMMENTABLE, true);
article.put(Article.ARTICLE_VIEW_PWD, "");
String content = article.getString(Article.ARTICLE_CONTENT);
content += "<br/><br/><p style='font-size: 12px;'><i>该文章同步自 <a href='http://symphony.b3log.org/article/" + articleId
+ "' target='_blank'>B3log 社区</a></i></p>";
article.put(Article.ARTICLE_CONTENT, content);
articleMgmtService.updateArticle(requestJSONObject);
ret.put(Keys.MSG, "update article succ");
ret.put(Keys.STATUS_CODE, true);
} catch (final ServiceException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
final JSONObject jsonObject = QueryResults.defaultResult();
renderer.setJSONObject(jsonObject);
jsonObject.put(Keys.MSG, e.getMessage());
}
}
} }
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
*/ */
package org.b3log.solo.processor; package org.b3log.solo.processor;
import java.io.IOException; import java.io.IOException;
import java.util.Calendar; import java.util.Calendar;
import java.util.Map; import java.util.Map;
...@@ -54,6 +55,7 @@ import org.b3log.solo.util.Randoms; ...@@ -54,6 +55,7 @@ import org.b3log.solo.util.Randoms;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/** /**
* Login/logout processor. * Login/logout processor.
* *
...@@ -72,30 +74,37 @@ public final class LoginProcessor { ...@@ -72,30 +74,37 @@ public final class LoginProcessor {
* Logger. * Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(LoginProcessor.class.getName()); private static final Logger LOGGER = Logger.getLogger(LoginProcessor.class.getName());
/** /**
* User query service. * User query service.
*/ */
private static UserQueryService userQueryService = UserQueryService.getInstance(); private static UserQueryService userQueryService = UserQueryService.getInstance();
/** /**
* User service. * User service.
*/ */
private UserService userService = UserServiceFactory.getUserService(); private UserService userService = UserServiceFactory.getUserService();
/** /**
* Mail service. * Mail service.
*/ */
private MailService mailService = MailServiceFactory.getMailService(); private MailService mailService = MailServiceFactory.getMailService();
/** /**
* User management service. * User management service.
*/ */
private UserMgmtService userMgmtService = UserMgmtService.getInstance(); private UserMgmtService userMgmtService = UserMgmtService.getInstance();
/** /**
* Language service. * Language service.
*/ */
private LangPropsService langPropsService = LangPropsService.getInstance(); private LangPropsService langPropsService = LangPropsService.getInstance();
/** /**
* Filler. * Filler.
*/ */
private Filler filler = Filler.getInstance(); private Filler filler = Filler.getInstance();
/** /**
* Preference query service. * Preference query service.
*/ */
...@@ -142,7 +151,7 @@ public final class LoginProcessor { ...@@ -142,7 +151,7 @@ public final class LoginProcessor {
* *
* @param context the specified context * @param context the specified context
*/ */
@RequestProcessing(value = {"/login"}, method = HTTPRequestMethod.POST) @RequestProcessing(value = { "/login"}, method = HTTPRequestMethod.POST)
public void login(final HTTPRequestContext context) { public void login(final HTTPRequestContext context) {
final HttpServletRequest request = context.getRequest(); final HttpServletRequest request = context.getRequest();
...@@ -200,7 +209,7 @@ public final class LoginProcessor { ...@@ -200,7 +209,7 @@ public final class LoginProcessor {
* @param context the specified context * @param context the specified context
* @throws IOException io exception * @throws IOException io exception
*/ */
@RequestProcessing(value = {"/logout"}, method = HTTPRequestMethod.GET) @RequestProcessing(value = { "/logout"}, method = HTTPRequestMethod.GET)
public void logout(final HTTPRequestContext context) throws IOException { public void logout(final HTTPRequestContext context) throws IOException {
final HttpServletRequest httpServletRequest = context.getRequest(); final HttpServletRequest httpServletRequest = context.getRequest();
...@@ -249,7 +258,7 @@ public final class LoginProcessor { ...@@ -249,7 +258,7 @@ public final class LoginProcessor {
* *
* @param context the specified context * @param context the specified context
*/ */
@RequestProcessing(value = {"/forgot"}, method = HTTPRequestMethod.POST) @RequestProcessing(value = { "/forgot"}, method = HTTPRequestMethod.POST)
public void forgot(final HTTPRequestContext context) { public void forgot(final HTTPRequestContext context) {
final HttpServletRequest request = context.getRequest(); final HttpServletRequest request = context.getRequest();
...@@ -376,7 +385,8 @@ public final class LoginProcessor { ...@@ -376,7 +385,8 @@ public final class LoginProcessor {
final String mailSubject = langPropsService.get("resetPwdMailSubject"); final String mailSubject = langPropsService.get("resetPwdMailSubject");
final String mailBody = langPropsService.get("resetPwdMailBody") + randomPwd; final String mailBody = langPropsService.get("resetPwdMailBody") + randomPwd;
final MailService.Message message = new MailService.Message(); final MailService.Message message = new MailService.Message();
//FIXME whether we should put the ever-hashed password here, rather during updating?
// FIXME whether we should put the ever-hashed password here, rather during updating?
user.put(User.USER_PASSWORD, randomPwd); user.put(User.USER_PASSWORD, randomPwd);
userMgmtService.updateUser(user); userMgmtService.updateUser(user);
...@@ -391,8 +401,7 @@ public final class LoginProcessor { ...@@ -391,8 +401,7 @@ public final class LoginProcessor {
jsonObject.put("to", Latkes.getServePath() + "/login"); jsonObject.put("to", Latkes.getServePath() + "/login");
jsonObject.put(Keys.MSG, langPropsService.get("resetPwdSuccessMsg")); jsonObject.put(Keys.MSG, langPropsService.get("resetPwdSuccessMsg"));
LOGGER.log(Level.FINER, "Sending a mail[mailSubject={0}, mailBody=[{1}] to [{2}]", LOGGER.log(Level.FINER, "Sending a mail[mailSubject={0}, mailBody=[{1}] to [{2}]", new Object[] {mailSubject, mailBody, userEmail});
new Object[]{mailSubject, mailBody, userEmail});
} }
/** /**
......
/* /*
* Copyright (c) 2009, 2010, 2011, 2012, 2013, B3log Team * Copyright (c) 2009, 2010, 2011, 2012, 2013, 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.util; package org.b3log.solo.util;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.b3log.latke.repository.RepositoryException; import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.util.Strings; import org.b3log.latke.util.Strings;
import org.b3log.solo.repository.ArticleRepository; import org.b3log.solo.repository.ArticleRepository;
import org.b3log.solo.repository.PageRepository; import org.b3log.solo.repository.PageRepository;
import org.b3log.solo.repository.impl.ArticleRepositoryImpl; import org.b3log.solo.repository.impl.ArticleRepositoryImpl;
import org.b3log.solo.repository.impl.PageRepositoryImpl; import org.b3log.solo.repository.impl.PageRepositoryImpl;
/** /**
* Permalink utilities. * Permalink utilities.
* *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.1.0.8, Aug 22, 2012 * @version 1.1.0.8, Aug 22, 2012
* @since 0.3.1 * @since 0.3.1
*/ */
public final class Permalinks { public final class Permalinks {
/** /**
* Logger. * Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(Permalinks.class.getName()); private static final Logger LOGGER = Logger.getLogger(Permalinks.class.getName());
/** /**
* Article repository. * Article repository.
*/ */
private ArticleRepository articleRepository = ArticleRepositoryImpl.getInstance(); private ArticleRepository articleRepository = ArticleRepositoryImpl.getInstance();
/** /**
* Page repository. * Page repository.
*/ */
private PageRepository pageRepository = PageRepositoryImpl.getInstance(); private PageRepository pageRepository = PageRepositoryImpl.getInstance();
/** /**
* Reserved permalinks. * Reserved permalinks.
*/ */
public static final String[] RESERVED_LINKS = new String[] { public static final String[] RESERVED_LINKS = new String[] {
"/", "/article", "/tags.html", "/tags", "/page", "/blog-articles-feed.do", "/tag-articles-feed.do", "/blog-articles-rss.do", "/", "/article", "/tags.html", "/tags", "/page", "/blog-articles-feed.do", "/tag-articles-feed.do", "/blog-articles-rss.do",
"/tag-articles-rss.do", "/get-random-articles.do", "/article-random-double-gen.do", "/captcha.do", "/kill-browser.html", "/tag-articles-rss.do", "/get-random-articles.do", "/article-random-double-gen.do", "/captcha.do", "/kill-browser.html",
"/add-article-comment.do", "/add-article-from-symphony-comment.do", "/add-page-comment.do", "/get-article-content", "/sitemap.xml", "/add-article-comment.do", "/add-article-from-symphony-comment.do", "/add-page-comment.do", "/get-article-content", "/sitemap.xml",
"/login", "/logout", "/forgot", "/get-article-content", "/admin-index.do", "/admin-article.do", "/admin-article-list.do", "/admin-link-list.do", "/login", "/logout", "/forgot", "/get-article-content", "/admin-index.do", "/admin-article.do", "/admin-article-list.do",
"/admin-preference.do", "/admin-file-list.do", "/admin-page-list.do", "/admin-others.do", "/admin-draft-list.do", "/admin-link-list.do", "/admin-preference.do", "/admin-file-list.do", "/admin-page-list.do", "/admin-others.do",
"/admin-user-list.do", "/admin-plugin-list.do", "/admin-main.do", "/admin-about.do", "/admin-label", "/admin-about.do", "/admin-draft-list.do", "/admin-user-list.do", "/admin-plugin-list.do", "/admin-main.do", "/admin-about.do", "/admin-label",
"/rm-all-data.do", "/init", "/clear-cache.do", "/admin-about.do", "/rm-all-data.do", "/init", "/clear-cache.do",
}; };
/** /**
* Checks whether the specified article permalink matches the system * Checks whether the specified article permalink matches the system
* generated format pattern ("/articles/yyyy/MM/dd/${articleId}.html"). * generated format pattern ("/articles/yyyy/MM/dd/${articleId}.html").
* *
* @param permalink the specified permalink * @param permalink the specified permalink
* @return {@code true} if matches, returns {@code false} otherwise * @return {@code true} if matches, returns {@code false} otherwise
*/ */
public static boolean matchDefaultArticlePermalinkFormat(final String permalink) { public static boolean matchDefaultArticlePermalinkFormat(final String permalink) {
final Pattern pattern = Pattern.compile("/articles/\\d{4}/\\d{2}/\\d{2}/\\d+\\.html"); final Pattern pattern = Pattern.compile("/articles/\\d{4}/\\d{2}/\\d{2}/\\d+\\.html");
final Matcher matcher = pattern.matcher(permalink); final Matcher matcher = pattern.matcher(permalink);
return matcher.matches(); return matcher.matches();
} }
/** /**
* Checks whether the specified page permalink matches the system generated * Checks whether the specified page permalink matches the system generated
* format pattern ("/pages/${pageId}.html"). * format pattern ("/pages/${pageId}.html").
* *
* @param permalink the specified permalink * @param permalink the specified permalink
* @return {@code true} if matches, returns {@code false} otherwise * @return {@code true} if matches, returns {@code false} otherwise
*/ */
public static boolean matchDefaultPagePermalinkFormat(final String permalink) { public static boolean matchDefaultPagePermalinkFormat(final String permalink) {
final Pattern pattern = Pattern.compile("/pages/\\d+\\.html"); final Pattern pattern = Pattern.compile("/pages/\\d+\\.html");
final Matcher matcher = pattern.matcher(permalink); final Matcher matcher = pattern.matcher(permalink);
return matcher.matches(); return matcher.matches();
} }
/** /**
* Checks whether the specified permalink is a * Checks whether the specified permalink is a
* {@link #invalidArticlePermalinkFormat(java.lang.String) invalid article * {@link #invalidArticlePermalinkFormat(java.lang.String) invalid article
* permalink format} and {@link #invalidPagePermalinkFormat(java.lang.String) * permalink format} and {@link #invalidPagePermalinkFormat(java.lang.String)
* invalid page permalink format}. * invalid page permalink format}.
* *
* @param permalink the specified permalink * @param permalink the specified permalink
* @return {@code true} if invalid, returns {@code false} otherwise * @return {@code true} if invalid, returns {@code false} otherwise
*/ */
public static boolean invalidPermalinkFormat(final String permalink) { public static boolean invalidPermalinkFormat(final String permalink) {
return invalidArticlePermalinkFormat(permalink) && invalidPagePermalinkFormat(permalink); return invalidArticlePermalinkFormat(permalink) && invalidPagePermalinkFormat(permalink);
} }
/** /**
* Checks whether the specified article permalink is invalid on format. * Checks whether the specified article permalink is invalid on format.
* *
* @param permalink the specified article permalink * @param permalink the specified article permalink
* @return {@code true} if invalid, returns {@code false} otherwise * @return {@code true} if invalid, returns {@code false} otherwise
*/ */
public static boolean invalidArticlePermalinkFormat(final String permalink) { public static boolean invalidArticlePermalinkFormat(final String permalink) {
if (Strings.isEmptyOrNull(permalink)) { if (Strings.isEmptyOrNull(permalink)) {
return true; return true;
} }
if (matchDefaultArticlePermalinkFormat(permalink)) { if (matchDefaultArticlePermalinkFormat(permalink)) {
return false; return false;
} }
return invalidUserDefinedPermalinkFormat(permalink); return invalidUserDefinedPermalinkFormat(permalink);
} }
/** /**
* Checks whether the specified page permalink is invalid on format. * Checks whether the specified page permalink is invalid on format.
* *
* @param permalink the specified page permalink * @param permalink the specified page permalink
* @return {@code true} if invalid, returns {@code false} otherwise * @return {@code true} if invalid, returns {@code false} otherwise
*/ */
public static boolean invalidPagePermalinkFormat(final String permalink) { public static boolean invalidPagePermalinkFormat(final String permalink) {
if (Strings.isEmptyOrNull(permalink)) { if (Strings.isEmptyOrNull(permalink)) {
return true; return true;
} }
if (matchDefaultPagePermalinkFormat(permalink)) { if (matchDefaultPagePermalinkFormat(permalink)) {
return false; return false;
} }
return invalidUserDefinedPermalinkFormat(permalink); return invalidUserDefinedPermalinkFormat(permalink);
} }
/** /**
* Checks whether the specified user-defined permalink is invalid on format. * Checks whether the specified user-defined permalink is invalid on format.
* *
* @param permalink the specified user-defined permalink * @param permalink the specified user-defined permalink
* @return {@code true} if invalid, returns {@code false} otherwise * @return {@code true} if invalid, returns {@code false} otherwise
*/ */
private static boolean invalidUserDefinedPermalinkFormat( private static boolean invalidUserDefinedPermalinkFormat(
final String permalink) { final String permalink) {
if (Strings.isEmptyOrNull(permalink)) { if (Strings.isEmptyOrNull(permalink)) {
return true; return true;
} }
if (isReservedLink(permalink)) { if (isReservedLink(permalink)) {
return true; return true;
} }
if (Strings.isNumeric(permalink.substring(1))) { if (Strings.isNumeric(permalink.substring(1))) {
// See issue 120 (http://code.google.com/p/b3log-solo/issues/detail?id=120#c4) // See issue 120 (http://code.google.com/p/b3log-solo/issues/detail?id=120#c4)
// for more details // for more details
return true; return true;
} }
int slashCnt = 0; int slashCnt = 0;
for (int i = 0; i < permalink.length(); i++) { for (int i = 0; i < permalink.length(); i++) {
if ('/' == permalink.charAt(i)) { if ('/' == permalink.charAt(i)) {
slashCnt++; slashCnt++;
} }
if (slashCnt > 1) { if (slashCnt > 1) {
return true; return true;
} }
} }
// FIXME: URL format check // FIXME: URL format check
return false; return false;
} }
/** /**
* Determines whether the specified request URI is a reserved link. * Determines whether the specified request URI is a reserved link.
* *
* <p> * <p>
* A URI starts with one of {@link Permalinks#RESERVED_LINKS reserved links} * A URI starts with one of {@link Permalinks#RESERVED_LINKS reserved links}
* will be treated as reserved link. * will be treated as reserved link.
* </p> * </p>
* *
* @param requestURI the specified request URI * @param requestURI the specified request URI
* @return {@code true} if it is a reserved link, returns {@code false} * @return {@code true} if it is a reserved link, returns {@code false}
* otherwise * otherwise
*/ */
private static boolean isReservedLink(final String requestURI) { private static boolean isReservedLink(final String requestURI) {
for (int i = 0; i < Permalinks.RESERVED_LINKS.length; i++) { for (int i = 0; i < Permalinks.RESERVED_LINKS.length; i++) {
final String reservedLink = Permalinks.RESERVED_LINKS[i]; final String reservedLink = Permalinks.RESERVED_LINKS[i];
if (reservedLink.startsWith(requestURI)) { if (reservedLink.startsWith(requestURI)) {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Determines whether the specified permalink exists. * Determines whether the specified permalink exists.
* *
* @param permalink the specified permalink * @param permalink the specified permalink
* @return {@code true} if exists, returns {@code false} otherwise * @return {@code true} if exists, returns {@code false} otherwise
*/ */
public boolean exist(final String permalink) { public boolean exist(final String permalink) {
try { try {
return isReservedLink(permalink) || null != articleRepository.getByPermalink(permalink) return isReservedLink(permalink) || null != articleRepository.getByPermalink(permalink)
|| null != pageRepository.getByPermalink(permalink) || permalink.endsWith(".ftl"); || null != pageRepository.getByPermalink(permalink) || permalink.endsWith(".ftl");
} catch (final RepositoryException e) { } catch (final RepositoryException e) {
LOGGER.log(Level.SEVERE, "Determines whether the permalink[" + permalink + "] exists failed, returns true", e); LOGGER.log(Level.SEVERE, "Determines whether the permalink[" + permalink + "] exists failed, returns true", e);
return true; return true;
} }
} }
/** /**
* Gets the {@link Permalinks} singleton. * Gets the {@link Permalinks} singleton.
* *
* @return the singleton * @return the singleton
*/ */
public static Permalinks getInstance() { public static Permalinks getInstance() {
return SingletonHolder.SINGLETON; return SingletonHolder.SINGLETON;
} }
/** /**
* Private default constructor. * Private default constructor.
*/ */
private Permalinks() {} private Permalinks() {}
/** /**
* Singleton holder. * Singleton holder.
* *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.0, Jan 12, 2011 * @version 1.0.0.0, Jan 12, 2011
*/ */
private static final class SingletonHolder { private static final class SingletonHolder {
/** /**
* Singleton. * Singleton.
*/ */
private static final Permalinks SINGLETON = new Permalinks(); private static final Permalinks SINGLETON = new Permalinks();
/** /**
* Private default constructor. * Private default constructor.
*/ */
private SingletonHolder() {} private SingletonHolder() {}
} }
} }
...@@ -13,14 +13,13 @@ ...@@ -13,14 +13,13 @@
* 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.
*/ */
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.b3log.solo.util; package org.b3log.solo.util;
import java.util.Random; import java.util.Random;
/** /**
* Generate random stuff, <p> currently only support random alpha and digital * Generate random stuff, <p> currently only support random alpha and digital
* string, whose length is also random between 8 and 16. * string, whose length is also random between 8 and 16.
...@@ -34,27 +33,32 @@ public class Randoms { ...@@ -34,27 +33,32 @@ public class Randoms {
* String's length should be positive. * String's length should be positive.
*/ */
private static final int LEN_LIM = 1; private static final int LEN_LIM = 1;
/** /**
* String's length maximum limit. * String's length maximum limit.
*/ */
private static final int MAX_LEN = 16; private static final int MAX_LEN = 16;
/** /**
* String's length minimum limit. * String's length minimum limit.
*/ */
private static final int MIN_LEN = 8; private static final int MIN_LEN = 8;
/** /**
* String's random length. * String's random length.
*/ */
private static final int RANDOM_LEN = new Random() private static final int RANDOM_LEN = new Random().nextInt(MAX_LEN - MIN_LEN + LEN_LIM) + MIN_LEN;
.nextInt(MAX_LEN - MIN_LEN + LEN_LIM) + MIN_LEN;
/** /**
* Characters set table, can be extended. * Characters set table, can be extended.
*/ */
private final char[] table; private final char[] table;
/** /**
* String's random seed. * String's random seed.
*/ */
private final Random random = new Random(); private final Random random = new Random();
/** /**
* String's random characters buffer. * String's random characters buffer.
*/ */
...@@ -76,8 +80,7 @@ public class Randoms { ...@@ -76,8 +80,7 @@ public class Randoms {
if (length < LEN_LIM) { if (length < LEN_LIM) {
throw new IllegalArgumentException("length < 1: " + length); throw new IllegalArgumentException("length < 1: " + length);
} }
table = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" table = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
.toCharArray();
buf = new char[length]; buf = new char[length];
} }
......
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