Commit d6037937 authored by Liang Ding's avatar Liang Ding

[GET] /register.html 改为 /register

parent 7839d204
/* /*
* 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.processor; package org.b3log.solo.processor;
import freemarker.template.Template; import freemarker.template.Template;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.Map; import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys; import org.b3log.latke.Keys;
import org.b3log.latke.Latkes; import org.b3log.latke.Latkes;
import org.b3log.latke.cache.PageCaches; import org.b3log.latke.cache.PageCaches;
import org.b3log.latke.model.Pagination; import org.b3log.latke.model.Pagination;
import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException; import org.b3log.latke.service.ServiceException;
import org.b3log.latke.servlet.HTTPRequestContext; import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod; import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.URIPatternMode; import org.b3log.latke.servlet.URIPatternMode;
import org.b3log.latke.servlet.annotation.RequestProcessing; import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor; import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer; import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer;
import org.b3log.latke.util.Locales; import org.b3log.latke.util.Locales;
import org.b3log.latke.util.Requests; import org.b3log.latke.util.Requests;
import org.b3log.solo.model.Common; import org.b3log.solo.model.Common;
import org.b3log.solo.model.PageTypes; import org.b3log.solo.model.PageTypes;
import org.b3log.solo.model.Preference; import org.b3log.solo.model.Preference;
import org.b3log.solo.processor.renderer.ConsoleRenderer; import org.b3log.solo.processor.renderer.ConsoleRenderer;
import org.b3log.solo.processor.renderer.FrontRenderer; import org.b3log.solo.processor.renderer.FrontRenderer;
import org.b3log.solo.processor.util.Filler; import org.b3log.solo.processor.util.Filler;
import org.b3log.solo.service.PreferenceQueryService; import org.b3log.solo.service.PreferenceQueryService;
import org.b3log.solo.util.Skins; import org.b3log.solo.util.Skins;
import org.json.JSONObject; import org.json.JSONObject;
/** /**
* Index processor. * Index processor.
* *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @author <a href="mailto:385321165@qq.com">DASHU</a> * @author <a href="mailto:385321165@qq.com">DASHU</a>
* @version 1.1.1.1, Mar 30, 2013 * @version 1.1.1.2, Apr 1, 2013
* @since 0.3.1 * @since 0.3.1
*/ */
@RequestProcessor @RequestProcessor
public final class IndexProcessor { public final class IndexProcessor {
/** /**
* Logger. * Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(IndexProcessor.class.getName()); private static final Logger LOGGER = Logger.getLogger(IndexProcessor.class.getName());
/** /**
* Filler. * Filler.
*/ */
private Filler filler = Filler.getInstance(); private Filler filler = Filler.getInstance();
/** /**
* Preference query service. * Preference query service.
*/ */
private PreferenceQueryService preferenceQueryService = PreferenceQueryService.getInstance(); private PreferenceQueryService preferenceQueryService = PreferenceQueryService.getInstance();
/** /**
* Language service. * Language service.
*/ */
private LangPropsService langPropsService = LangPropsService.getInstance(); private LangPropsService langPropsService = LangPropsService.getInstance();
/** /**
* Shows index with the specified context. * Shows index with the specified context.
* *
* @param context the specified context * @param context the specified context
* @param request the specified HTTP servlet request * @param request the specified HTTP servlet request
* @param response the specified HTTP servlet response * @param response the specified HTTP servlet response
*/ */
@RequestProcessing(value = { "/\\d*", ""}, uriPatternsMode = URIPatternMode.REGEX, method = HTTPRequestMethod.GET) @RequestProcessing(value = { "/\\d*", ""}, uriPatternsMode = URIPatternMode.REGEX, method = HTTPRequestMethod.GET)
public void showIndex(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) { public void showIndex(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) {
final AbstractFreeMarkerRenderer renderer = new FrontRenderer(); final AbstractFreeMarkerRenderer renderer = new FrontRenderer();
context.setRenderer(renderer); context.setRenderer(renderer);
renderer.setTemplateName("index.ftl"); renderer.setTemplateName("index.ftl");
final Map<String, Object> dataModel = renderer.getDataModel(); final Map<String, Object> dataModel = renderer.getDataModel();
final String requestURI = request.getRequestURI(); final String requestURI = request.getRequestURI();
try { try {
final int currentPageNum = getCurrentPageNum(requestURI); final int currentPageNum = getCurrentPageNum(requestURI);
final JSONObject preference = preferenceQueryService.getPreference(); final JSONObject preference = preferenceQueryService.getPreference();
Skins.fillSkinLangs(preference.optString(Preference.LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), Skins.fillSkinLangs(preference.optString(Preference.LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME),
dataModel); dataModel);
final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale()); final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale());
request.setAttribute(PageCaches.CACHED_OID, "No id"); request.setAttribute(PageCaches.CACHED_OID, "No id");
request.setAttribute(PageCaches.CACHED_TITLE, request.setAttribute(PageCaches.CACHED_TITLE,
langs.get(PageTypes.INDEX.getLangeLabel()) + " [" + langs.get("pageNumLabel") + "=" + currentPageNum + "]"); langs.get(PageTypes.INDEX.getLangeLabel()) + " [" + langs.get("pageNumLabel") + "=" + currentPageNum + "]");
request.setAttribute(PageCaches.CACHED_TYPE, langs.get(PageTypes.INDEX.getLangeLabel())); request.setAttribute(PageCaches.CACHED_TYPE, langs.get(PageTypes.INDEX.getLangeLabel()));
request.setAttribute(PageCaches.CACHED_LINK, requestURI); request.setAttribute(PageCaches.CACHED_LINK, requestURI);
filler.fillIndexArticles(request, dataModel, currentPageNum, preference); filler.fillIndexArticles(request, dataModel, currentPageNum, preference);
dataModel.put(Keys.PAGE_TYPE, PageTypes.INDEX); dataModel.put(Keys.PAGE_TYPE, PageTypes.INDEX);
filler.fillSide(request, dataModel, preference); filler.fillSide(request, dataModel, preference);
filler.fillBlogHeader(request, dataModel, preference); filler.fillBlogHeader(request, dataModel, preference);
filler.fillBlogFooter(dataModel, preference); filler.fillBlogFooter(dataModel, preference);
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, currentPageNum); dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, currentPageNum);
final String previousPageNum = Integer.toString(currentPageNum > 1 ? currentPageNum - 1 : 0); final String previousPageNum = Integer.toString(currentPageNum > 1 ? currentPageNum - 1 : 0);
dataModel.put(Pagination.PAGINATION_PREVIOUS_PAGE_NUM, "0".equals(previousPageNum) ? "" : previousPageNum); dataModel.put(Pagination.PAGINATION_PREVIOUS_PAGE_NUM, "0".equals(previousPageNum) ? "" : previousPageNum);
final Integer pageCount = (Integer) dataModel.get(Pagination.PAGINATION_PAGE_COUNT); final Integer pageCount = (Integer) dataModel.get(Pagination.PAGINATION_PAGE_COUNT);
if (pageCount == currentPageNum + 1) { // The next page is the last page if (pageCount == currentPageNum + 1) { // The next page is the last page
dataModel.put(Pagination.PAGINATION_NEXT_PAGE_NUM, ""); dataModel.put(Pagination.PAGINATION_NEXT_PAGE_NUM, "");
} else { } else {
dataModel.put(Pagination.PAGINATION_NEXT_PAGE_NUM, currentPageNum + 1); dataModel.put(Pagination.PAGINATION_NEXT_PAGE_NUM, currentPageNum + 1);
} }
dataModel.put(Common.PATH, ""); dataModel.put(Common.PATH, "");
} catch (final ServiceException e) { } catch (final ServiceException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e); LOGGER.log(Level.SEVERE, e.getMessage(), e);
try { try {
response.sendError(HttpServletResponse.SC_NOT_FOUND); response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (final IOException ex) { } catch (final IOException ex) {
LOGGER.severe(ex.getMessage()); LOGGER.severe(ex.getMessage());
} }
} }
} }
/** /**
* Shows kill browser page with the specified context. * Shows kill browser page with the specified context.
* *
* @param context the specified context * @param context the specified context
* @param request the specified HTTP servlet request * @param request the specified HTTP servlet request
* @param response the specified HTTP servlet response * @param response the specified HTTP servlet response
*/ */
@RequestProcessing(value = "/kill-browser.html", method = HTTPRequestMethod.GET) @RequestProcessing(value = "/kill-browser.html", method = HTTPRequestMethod.GET)
public void showKillBrowser(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) { public void showKillBrowser(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) {
final AbstractFreeMarkerRenderer renderer = new KillBrowserRenderer(); final AbstractFreeMarkerRenderer renderer = new KillBrowserRenderer();
context.setRenderer(renderer); context.setRenderer(renderer);
final Map<String, Object> dataModel = renderer.getDataModel(); final Map<String, Object> dataModel = renderer.getDataModel();
try { try {
final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request)); final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));
dataModel.putAll(langs); dataModel.putAll(langs);
final JSONObject preference = preferenceQueryService.getPreference(); final JSONObject preference = preferenceQueryService.getPreference();
filler.fillBlogFooter(dataModel, preference); filler.fillBlogFooter(dataModel, preference);
Keys.fillServer(dataModel); Keys.fillServer(dataModel);
Keys.fillRuntime(dataModel); Keys.fillRuntime(dataModel);
filler.fillMinified(dataModel); filler.fillMinified(dataModel);
dataModel.put(Keys.PAGE_TYPE, PageTypes.KILL_BROWSER); dataModel.put(Keys.PAGE_TYPE, PageTypes.KILL_BROWSER);
request.setAttribute(PageCaches.CACHED_OID, "No id"); request.setAttribute(PageCaches.CACHED_OID, "No id");
request.setAttribute(PageCaches.CACHED_TITLE, "Kill Browser Page"); request.setAttribute(PageCaches.CACHED_TITLE, "Kill Browser Page");
request.setAttribute(PageCaches.CACHED_TYPE, langs.get(PageTypes.KILL_BROWSER.getLangeLabel())); request.setAttribute(PageCaches.CACHED_TYPE, langs.get(PageTypes.KILL_BROWSER.getLangeLabel()));
request.setAttribute(PageCaches.CACHED_LINK, request.getRequestURI()); request.setAttribute(PageCaches.CACHED_LINK, request.getRequestURI());
} catch (final ServiceException e) { } catch (final ServiceException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e); LOGGER.log(Level.SEVERE, e.getMessage(), e);
try { try {
response.sendError(HttpServletResponse.SC_NOT_FOUND); response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (final IOException ex) { } catch (final IOException ex) {
LOGGER.severe(ex.getMessage()); LOGGER.severe(ex.getMessage());
} }
} }
} }
/** /**
* Show register page. * Show register page.
* *
* @param context the specified context * @param context the specified context
* @param request the specified HTTP servlet request * @param request the specified HTTP servlet request
* @param response the specified HTTP servlet response * @param response the specified HTTP servlet response
*/ */
@RequestProcessing(value = "/register.html", method = HTTPRequestMethod.GET) @RequestProcessing(value = "/register", method = HTTPRequestMethod.GET)
public void register(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) { public void register(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) {
final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer(); final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();
context.setRenderer(renderer); context.setRenderer(renderer);
renderer.setTemplateName("register.ftl"); renderer.setTemplateName("register.ftl");
final Map<String, Object> dataModel = renderer.getDataModel(); final Map<String, Object> dataModel = renderer.getDataModel();
try { try {
final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request)); final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));
dataModel.putAll(langs); dataModel.putAll(langs);
final JSONObject preference = preferenceQueryService.getPreference(); final JSONObject preference = preferenceQueryService.getPreference();
filler.fillBlogFooter(dataModel, preference); filler.fillBlogFooter(dataModel, preference);
filler.fillMinified(dataModel); filler.fillMinified(dataModel);
Keys.fillServer(dataModel); Keys.fillServer(dataModel);
} catch (final ServiceException e) { } catch (final ServiceException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e); LOGGER.log(Level.SEVERE, e.getMessage(), e);
try { try {
response.sendError(HttpServletResponse.SC_NOT_FOUND); response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (final IOException ex) { } catch (final IOException ex) {
LOGGER.severe(ex.getMessage()); LOGGER.severe(ex.getMessage());
} }
} }
} }
/** /**
* Gets the request page number from the specified request URI. * Gets the request page number from the specified request URI.
* *
* @param requestURI the specified request URI * @param requestURI the specified request URI
* @return page number, returns {@code -1} if the specified request URI * @return page number, returns {@code -1} if the specified request URI
* can not convert to an number * can not convert to an number
*/ */
private static int getCurrentPageNum(final String requestURI) { private static int getCurrentPageNum(final String requestURI) {
final String pageNumString = StringUtils.substringAfter(requestURI, "/"); final String pageNumString = StringUtils.substringAfter(requestURI, "/");
return Requests.getCurrentPageNum(pageNumString); return Requests.getCurrentPageNum(pageNumString);
} }
/** /**
* Kill browser (kill-browser.ftl) HTTP response renderer. * Kill browser (kill-browser.ftl) HTTP response renderer.
* *
* @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, Sep 18, 2011 * @version 1.0.0.0, Sep 18, 2011
* @see 0.3.1 * @see 0.3.1
*/ */
private static final class KillBrowserRenderer extends AbstractFreeMarkerRenderer { private static final class KillBrowserRenderer extends AbstractFreeMarkerRenderer {
/** /**
* Logger. * Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(KillBrowserRenderer.class.getName()); private static final Logger LOGGER = Logger.getLogger(KillBrowserRenderer.class.getName());
@Override @Override
public void render(final HTTPRequestContext context) { public void render(final HTTPRequestContext context) {
final HttpServletResponse response = context.getResponse(); final HttpServletResponse response = context.getResponse();
response.setContentType("text/html"); response.setContentType("text/html");
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
try { try {
final Template template = ConsoleRenderer.TEMPLATE_CFG.getTemplate("kill-browser.ftl"); final Template template = ConsoleRenderer.TEMPLATE_CFG.getTemplate("kill-browser.ftl");
final PrintWriter writer = response.getWriter(); final PrintWriter writer = response.getWriter();
final StringWriter stringWriter = new StringWriter(); final StringWriter stringWriter = new StringWriter();
template.setOutputEncoding("UTF-8"); template.setOutputEncoding("UTF-8");
template.process(getDataModel(), stringWriter); template.process(getDataModel(), stringWriter);
final String pageContent = stringWriter.toString(); final String pageContent = stringWriter.toString();
context.getRequest().setAttribute(PageCaches.CACHED_CONTENT, pageContent); context.getRequest().setAttribute(PageCaches.CACHED_CONTENT, pageContent);
writer.write(pageContent); writer.write(pageContent);
writer.flush(); writer.flush();
writer.close(); writer.close();
} catch (final Exception e) { } catch (final Exception e) {
try { try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (final IOException ex) { } catch (final IOException ex) {
LOGGER.log(Level.SEVERE, "Can not sned error 500!", ex); LOGGER.log(Level.SEVERE, "Can not sned error 500!", ex);
} }
} }
} }
@Override @Override
protected void afterRender(final HTTPRequestContext context) throws Exception { protected void afterRender(final HTTPRequestContext context) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); throw new UnsupportedOperationException("Not supported yet.");
} }
@Override @Override
protected void beforeRender(final HTTPRequestContext context) throws Exception { protected void beforeRender(final HTTPRequestContext context) throws Exception {
throw new UnsupportedOperationException("Not supported yet."); throw new UnsupportedOperationException("Not supported yet.");
} }
} }
} }
/* /*
* 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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.b3log.latke.Keys; import org.b3log.latke.Keys;
import org.b3log.latke.model.Role; import org.b3log.latke.model.Role;
import org.b3log.latke.model.User; import org.b3log.latke.model.User;
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.user.GeneralUser; import org.b3log.latke.user.GeneralUser;
import org.b3log.latke.user.UserService; import org.b3log.latke.user.UserService;
import org.b3log.latke.user.UserServiceFactory; import org.b3log.latke.user.UserServiceFactory;
import org.b3log.latke.util.Strings; import org.b3log.latke.util.Strings;
import org.b3log.solo.model.Article; import org.b3log.solo.model.Article;
import org.b3log.solo.processor.LoginProcessor; import org.b3log.solo.processor.LoginProcessor;
import org.b3log.solo.repository.ArticleRepository; import org.b3log.solo.repository.ArticleRepository;
import org.b3log.solo.repository.UserRepository; import org.b3log.solo.repository.UserRepository;
import org.b3log.solo.repository.impl.ArticleRepositoryImpl; import org.b3log.solo.repository.impl.ArticleRepositoryImpl;
import org.b3log.solo.repository.impl.UserRepositoryImpl; import org.b3log.solo.repository.impl.UserRepositoryImpl;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/** /**
* User utilities. * User utilities.
* *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @author <a href="mailto:385321165@qq.com">DASHU</a> * @author <a href="mailto:385321165@qq.com">DASHU</a>
* @version 1.0.1.4, Mar 30, 2013 * @version 1.0.1.5, Apr 1, 2013
* @since 0.3.1 * @since 0.3.1
*/ */
public final class Users { public final class Users {
/** /**
* Logger. * Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(Users.class.getName()); private static final Logger LOGGER = Logger.getLogger(Users.class.getName());
/** /**
* User repository. * User repository.
*/ */
private UserRepository userRepository = UserRepositoryImpl.getInstance(); private UserRepository userRepository = UserRepositoryImpl.getInstance();
/** /**
* User service. * User service.
*/ */
private UserService userService = UserServiceFactory.getUserService(); private UserService userService = UserServiceFactory.getUserService();
/** /**
* Article repository. * Article repository.
*/ */
private ArticleRepository articleRepository = ArticleRepositoryImpl.getInstance(); private ArticleRepository articleRepository = ArticleRepositoryImpl.getInstance();
/** /**
* Determines whether if exists multiple users in current Solo. * Determines whether if exists multiple users in current Solo.
* *
* @return {@code true} if exists, {@code false} otherwise * @return {@code true} if exists, {@code false} otherwise
* @throws ServiceException service exception * @throws ServiceException service exception
*/ */
public boolean hasMultipleUsers() throws ServiceException { public boolean hasMultipleUsers() throws ServiceException {
final Query query = new Query().setPageCount(1); final Query query = new Query().setPageCount(1);
try { try {
final JSONArray users = userRepository.get(query).getJSONArray(Keys.RESULTS); final JSONArray users = userRepository.get(query).getJSONArray(Keys.RESULTS);
return 1 != users.length(); return 1 != users.length();
} catch (final RepositoryException e) { } catch (final RepositoryException e) {
LOGGER.log(Level.SEVERE, "Determines multiple users failed", e); LOGGER.log(Level.SEVERE, "Determines multiple users failed", e);
throw new ServiceException(e); throw new ServiceException(e);
} catch (final JSONException e) { } catch (final JSONException e) {
LOGGER.log(Level.SEVERE, "Determines multiple users failed", e); LOGGER.log(Level.SEVERE, "Determines multiple users failed", e);
throw new ServiceException(e); throw new ServiceException(e);
} }
} }
/** /**
* Can the current user access an article specified by the given article id? * Can the current user access an article specified by the given article id?
* *
* @param articleId the given article id * @param articleId the given article id
* @param request the specified request * @param request the specified request
* @return {@code true} if the current user can access the article, * @return {@code true} if the current user can access the article,
* {@code false} otherwise * {@code false} otherwise
* @throws Exception exception * @throws Exception exception
*/ */
public boolean canAccessArticle(final String articleId, final HttpServletRequest request) public boolean canAccessArticle(final String articleId, final HttpServletRequest request)
throws Exception { throws Exception {
if (Strings.isEmptyOrNull(articleId)) { if (Strings.isEmptyOrNull(articleId)) {
return false; return false;
} }
if (isAdminLoggedIn(request)) { if (isAdminLoggedIn(request)) {
return true; return true;
} }
final JSONObject article = articleRepository.get(articleId); final JSONObject article = articleRepository.get(articleId);
final String currentUserEmail = getCurrentUser(request).getString(User.USER_EMAIL); final String currentUserEmail = getCurrentUser(request).getString(User.USER_EMAIL);
if (!article.getString(Article.ARTICLE_AUTHOR_EMAIL).equals(currentUserEmail)) { if (!article.getString(Article.ARTICLE_AUTHOR_EMAIL).equals(currentUserEmail)) {
return false; return false;
} }
return true; return true;
} }
/** /**
* Checks whether the current request is made by a logged in user * Checks whether the current request is made by a logged in user
* (including default user and administrator lists in <i>users</i>). * (including default user and administrator lists in <i>users</i>).
* *
* <p> * <p>
* Invokes this method will try to login with cookie first. * Invokes this method will try to login with cookie first.
* </p> * </p>
* *
* @param request the specified request * @param request the specified request
* @param response the specified response * @param response the specified response
* @return {@code true} if the current request is made by logged in user, * @return {@code true} if the current request is made by logged in user,
* returns {@code false} otherwise * returns {@code false} otherwise
*/ */
public boolean isLoggedIn(final HttpServletRequest request, final HttpServletResponse response) { public boolean isLoggedIn(final HttpServletRequest request, final HttpServletResponse response) {
LoginProcessor.tryLogInWithCookie(request, response); LoginProcessor.tryLogInWithCookie(request, response);
final GeneralUser currentUser = userService.getCurrentUser(request); final GeneralUser currentUser = userService.getCurrentUser(request);
if (null == currentUser) { if (null == currentUser) {
return false; return false;
} }
return isSoloUser(currentUser.getEmail()) || userService.isUserAdmin(request); return isSoloUser(currentUser.getEmail()) || userService.isUserAdmin(request);
} }
/** /**
* Checks whether the current request is made by logged in administrator. * Checks whether the current request is made by logged in administrator.
* *
* @param request the specified request * @param request the specified request
* @return {@code true} if the current request is made by logged in * @return {@code true} if the current request is made by logged in
* administrator, returns {@code false} otherwise * administrator, returns {@code false} otherwise
*/ */
public boolean isAdminLoggedIn(final HttpServletRequest request) { public boolean isAdminLoggedIn(final HttpServletRequest request) {
return userService.isUserLoggedIn(request) && userService.isUserAdmin(request); return userService.isUserLoggedIn(request) && userService.isUserAdmin(request);
} }
/** /**
* Gets the current user. * Gets the current user.
* *
* @param request the specified request * @param request the specified request
* @return the current user, {@code null} if not found * @return the current user, {@code null} if not found
*/ */
public JSONObject getCurrentUser(final HttpServletRequest request) { public JSONObject getCurrentUser(final HttpServletRequest request) {
final GeneralUser currentUser = userService.getCurrentUser(request); final GeneralUser currentUser = userService.getCurrentUser(request);
if (null == currentUser) { if (null == currentUser) {
return null; return null;
} }
final String email = currentUser.getEmail(); final String email = currentUser.getEmail();
try { try {
return userRepository.getByEmail(email); return userRepository.getByEmail(email);
} catch (final RepositoryException e) { } catch (final RepositoryException e) {
LOGGER.log(Level.SEVERE, "Gets current user by request failed, returns null", e); LOGGER.log(Level.SEVERE, "Gets current user by request failed, returns null", e);
return null; return null;
} }
} }
/** /**
* Determines whether the specified email is a user's email of this Solo * Determines whether the specified email is a user's email of this Solo
* application. * application.
* *
* @param email the specified email * @param email the specified email
* @return {@code true} if it is, {@code false} otherwise * @return {@code true} if it is, {@code false} otherwise
*/ */
public boolean isSoloUser(final String email) { public boolean isSoloUser(final String email) {
try { try {
final Query query = new Query().setPageCount(1); final Query query = new Query().setPageCount(1);
final JSONObject result = userRepository.get(query); final JSONObject result = userRepository.get(query);
final JSONArray users = result.getJSONArray(Keys.RESULTS); final JSONArray users = result.getJSONArray(Keys.RESULTS);
return existEmail(email, users); return existEmail(email, users);
} catch (final Exception e) { } catch (final Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e); LOGGER.log(Level.SEVERE, e.getMessage(), e);
return false; return false;
} }
} }
/** /**
* Determines whether the specified email exits in the specified users. * Determines whether the specified email exits in the specified users.
* *
* @param email the specified email * <p>
* @param users the specified user * If the email is a visitor's, returns {@code false}.
* @return {@code true} if exists, {@code false} otherwise * </p>
* @throws JSONException json exception *
*/ * @param email the specified email
private boolean existEmail(final String email, final JSONArray users) throws JSONException { * @param users the specified user
for (int i = 0; i < users.length(); i++) { * @return {@code true} if exists, {@code false} otherwise
final JSONObject user = users.getJSONObject(i); * @throws JSONException json exception
*/
if (isVisitor(user)) { private boolean existEmail(final String email, final JSONArray users) throws JSONException {
return false; for (int i = 0; i < users.length(); i++) {
} final JSONObject user = users.getJSONObject(i);
if (user.getString(User.USER_EMAIL).equalsIgnoreCase(email)) { if (isVisitor(user)) {
return true; return false;
} }
}
if (user.getString(User.USER_EMAIL).equalsIgnoreCase(email)) {
return false; return true;
} }
}
/**
* Check the user is visitor or not. return false;
* }
* @param user the specified user
* @return {@code true} if is visitor, {@code false} otherwise /**
* @throws JSONException json exception * Check the user is visitor or not.
*/ *
private boolean isVisitor(final JSONObject user) throws JSONException { * @param user the specified user
if (user.getString(User.USER_ROLE).equals(Role.VISITOR_ROLE)) { * @return {@code true} if is visitor, {@code false} otherwise
return true; * @throws JSONException json exception
} */
return false; private boolean isVisitor(final JSONObject user) throws JSONException {
} if (user.getString(User.USER_ROLE).equals(Role.VISITOR_ROLE)) {
return true;
/** }
* Gets the {@link Users} singleton. return false;
* }
* @return the singleton
*/ /**
public static Users getInstance() { * Gets the {@link Users} singleton.
return SingletonHolder.SINGLETON; *
} * @return the singleton
*/
/** public static Users getInstance() {
* Private default constructor. return SingletonHolder.SINGLETON;
*/ }
private Users() {}
/**
/** * Private default constructor.
* Singleton holder. */
* private Users() {}
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.0, Jan 12, 2011 /**
*/ * Singleton holder.
private static final class SingletonHolder { *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
/** * @version 1.0.0.0, Jan 12, 2011
* Singleton. */
*/ private static final class SingletonHolder {
private static final Users SINGLETON = new Users();
/**
/** * Singleton.
* Private default constructor. */
*/ private static final Users SINGLETON = new Users();
private SingletonHolder() {}
} /**
} * Private default constructor.
*/
private SingletonHolder() {}
}
}
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