use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.
the class InitProcessor method initSolo.
/**
* Initializes Solo.
*
* @param context the specified http request context
* @param request the specified http servlet request, for example, <pre>
* {
* "userName": "",
* "userEmail": "",
* "userPassword": ""
* }
* </pre>
*
* @param response the specified http servlet response
* @throws Exception exception
*/
@RequestProcessing(value = "/init", method = HTTPRequestMethod.POST)
public void initSolo(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
if (initService.isInited()) {
response.sendRedirect("/");
return;
}
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
final JSONObject ret = QueryResults.defaultResult();
renderer.setJSONObject(ret);
try {
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
final String userName = requestJSONObject.optString(User.USER_NAME);
final String userEmail = requestJSONObject.optString(User.USER_EMAIL);
final String userPassword = requestJSONObject.optString(User.USER_PASSWORD);
if (Strings.isEmptyOrNull(userName) || Strings.isEmptyOrNull(userEmail) || Strings.isEmptyOrNull(userPassword) || !Strings.isEmail(userEmail)) {
ret.put(Keys.MSG, "Init failed, please check your input");
return;
}
if (invalidUserName(userName)) {
ret.put(Keys.MSG, "Init failed, please check your username (length [1, 20], content {a-z, A-Z, 0-9}, do not contain 'admin' for security reason]");
return;
}
final Locale locale = Locales.getLocale(request);
requestJSONObject.put(Keys.LOCALE, locale.toString());
initService.init(requestJSONObject);
// If initialized, login the admin
final JSONObject admin = new JSONObject();
admin.put(User.USER_NAME, userName);
admin.put(User.USER_EMAIL, userEmail);
admin.put(User.USER_ROLE, Role.ADMIN_ROLE);
admin.put(User.USER_PASSWORD, userPassword);
admin.put(UserExt.USER_AVATAR, Thumbnails.getGravatarURL(userEmail, "128"));
Sessions.login(request, response, admin);
ret.put(Keys.STATUS_CODE, true);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, e.getMessage(), e);
ret.put(Keys.MSG, e.getMessage());
}
}
use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.
the class ChanceProcessor method hasChance.
/**
* Dose the client has a broadcast chance.
*
* <p>
* If the request come from a user not administrator, consider it is no broadcast chance.
* </p>
*
* <p>
* Renders the response with a json object, for example,
* <pre>
* {
* "sc": boolean, // if has a chance, the value will be true
* "broadcastChanceExpirationTime": long, // if has a chance, the value will larger then 0L
* }
* </pre>
* </p>
*
* @param context the specified http request context
* @param request the specified http servlet request
* @param response the specified http servlet response
* @throws Exception
*/
@RequestProcessing(value = "/console/plugins/b3log-broadcast/chance", method = HTTPRequestMethod.GET)
public void hasChance(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
if (!userQueryService.isLoggedIn(request, response)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
final JSONObject ret = new JSONObject();
renderer.setJSONObject(ret);
if (!userQueryService.isAdminLoggedIn(request)) {
ret.put(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME, 0L);
ret.put(Keys.STATUS_CODE, false);
return;
}
try {
final JSONObject option = optionQueryService.getOptionById(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME);
if (null == option) {
ret.put(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME, 0L);
ret.put(Keys.STATUS_CODE, false);
return;
}
ret.put(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME, option.getLong(Option.OPTION_VALUE));
ret.put(Keys.STATUS_CODE, true);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Broadcast plugin exception", e);
final JSONObject jsonObject = QueryResults.defaultResult();
renderer.setJSONObject(jsonObject);
}
}
use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.
the class ChanceProcessor method submitBroadcast.
/**
* Submits a broadcast.
*
* <p>
* Renders the response with a json object, for example,
* <pre>
* {
* "sc": boolean,
* "msg": "" // optional
* }
* </pre>
* </p>
*
* @param context the specified http request context
* @param request the specified http servlet request, for example,
* <pre>
* {
* "broadcast": {
* "title": "",
* "content": "",
* "link": "" // optional
* }
* }
* </pre>
* @param response the specified http servlet response
* @throws Exception
*/
@RequestProcessing(value = "/console/plugins/b3log-broadcast", method = HTTPRequestMethod.POST)
public void submitBroadcast(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
if (!userQueryService.isAdminLoggedIn(request)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
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 broadcast = requestJSONObject.getJSONObject("broadcast");
final JSONObject preference = preferenceQueryService.getPreference();
final String b3logKey = preference.getString(Option.ID_C_KEY_OF_SOLO);
final String email = preference.getString(Option.ID_C_ADMIN_EMAIL);
final String clientName = "B3log Solo";
final String clientVersion = SoloServletListener.VERSION;
final String clientTitle = preference.getString(Option.ID_C_BLOG_TITLE);
final String clientRuntimeEnv = Latkes.getRuntimeEnv().name();
final JSONObject broadcastRequest = new JSONObject();
broadcastRequest.put("b3logKey", b3logKey);
broadcastRequest.put("email", email);
broadcastRequest.put("broadcast", broadcast);
broadcastRequest.put("clientRuntimeEnv", clientRuntimeEnv);
broadcastRequest.put("clientTitle", clientTitle);
broadcastRequest.put("clientVersion", clientVersion);
broadcastRequest.put("clientName", clientName);
broadcastRequest.put("clientHost", Latkes.getServePath());
final HTTPRequest httpRequest = new HTTPRequest();
httpRequest.setURL(ADD_BROADCAST_URL);
httpRequest.setRequestMethod(HTTPRequestMethod.POST);
httpRequest.setPayload(broadcastRequest.toString().getBytes("UTF-8"));
@SuppressWarnings("unchecked") final Future<HTTPResponse> future = (Future<HTTPResponse>) urlFetchService.fetchAsync(httpRequest);
final HTTPResponse result = future.get();
if (HttpServletResponse.SC_OK == result.getResponseCode()) {
ret.put(Keys.STATUS_CODE, true);
optionMgmtService.removeOption(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME);
LOGGER.info("Submits broadcast successfully");
return;
}
ret.put(Keys.STATUS_CODE, false);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Submits broadcast failed", e);
final JSONObject jsonObject = QueryResults.defaultResult();
renderer.setJSONObject(jsonObject);
jsonObject.put(Keys.MSG, e.getMessage());
}
}
use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.
the class ChanceProcessor method addChance.
/**
* Adds a broadcast chance to option repository.
*
* <p>
* Renders the response with a json object, for example,
* <pre>
* {
* "sc": boolean,
* "msg": "" // optional
* }
* </pre>
* </p>
*
* @param context the specified http request context
* @param request the specified http servlet request
* @param response the specified http servlet response
* @throws Exception
*/
@RequestProcessing(value = "/console/plugins/b3log-broadcast/chance", method = HTTPRequestMethod.POST)
public void addChance(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
final JSONObject ret = new JSONObject();
renderer.setJSONObject(ret);
try {
// TODO: verify b3 key
final String time = request.getParameter("time");
if (Strings.isEmptyOrNull(time)) {
ret.put(Keys.STATUS_CODE, false);
return;
}
final long expirationTime = Long.valueOf(time);
final JSONObject option = new JSONObject();
option.put(Keys.OBJECT_ID, Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME);
option.put(Option.OPTION_VALUE, expirationTime);
option.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_BROADCAST);
optionMgmtService.addOrUpdateOption(option);
ret.put(Keys.STATUS_CODE, true);
} catch (final Exception e) {
final String msg = "Broadcast plugin exception";
LOGGER.log(Level.ERROR, msg, e);
final JSONObject jsonObject = QueryResults.defaultResult();
renderer.setJSONObject(jsonObject);
jsonObject.put(Keys.MSG, msg);
}
}
use of org.b3log.latke.servlet.renderer.JSONRenderer in project solo by b3log.
the class ArticleProcessor method getArchivesArticlesByPage.
/**
* Gets tag articles paged with the specified context.
*
* @param context the specified context
* @param request the specified request
*/
@RequestProcessing(value = "/articles/archives/.+/\\d+", uriPatternsMode = URIPatternMode.REGEX, method = HTTPRequestMethod.GET)
public void getArchivesArticlesByPage(final HTTPRequestContext context, final HttpServletRequest request) {
final JSONObject jsonObject = new JSONObject();
final String archiveDateString = getArchivesArticlesPagedArchive(request.getRequestURI());
final int currentPageNum = getArchivesArticlesPagedCurrentPageNum(request.getRequestURI());
Stopwatchs.start("Get Archive-Articles Paged[archive=" + archiveDateString + ", pageNum=" + currentPageNum + ']');
try {
jsonObject.put(Keys.STATUS_CODE, true);
final JSONObject preference = preferenceQueryService.getPreference();
final int pageSize = preference.getInt(Option.ID_C_ARTICLE_LIST_DISPLAY_COUNT);
final JSONObject archiveQueryResult = archiveDateQueryService.getByArchiveDateString(archiveDateString);
if (null == archiveQueryResult) {
throw new Exception("Can not found archive[archiveDate=" + archiveDateString + "]");
}
final JSONObject archiveDate = archiveQueryResult.getJSONObject(ArchiveDate.ARCHIVE_DATE);
final String archiveDateId = archiveDate.getString(Keys.OBJECT_ID);
final int articleCount = archiveDate.getInt(ArchiveDate.ARCHIVE_DATE_PUBLISHED_ARTICLE_COUNT);
final int pageCount = (int) Math.ceil((double) articleCount / (double) pageSize);
final List<JSONObject> articles = articleQueryService.getArticlesByArchiveDate(archiveDateId, currentPageNum, pageSize);
final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
if (hasMultipleUsers) {
filler.setArticlesExProperties(request, articles, preference);
} else if (!articles.isEmpty()) {
final JSONObject author = articleQueryService.getAuthor(articles.get(0));
filler.setArticlesExProperties(request, articles, author, preference);
}
Collections.sort(articles, Comparators.ARTICLE_CREATE_DATE_COMPARATOR);
final JSONObject result = new JSONObject();
final JSONObject pagination = new JSONObject();
pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
result.put(Pagination.PAGINATION, pagination);
result.put(Article.ARTICLES, articles);
jsonObject.put(Keys.RESULTS, result);
} catch (final Exception e) {
jsonObject.put(Keys.STATUS_CODE, false);
LOGGER.log(Level.ERROR, "Gets article paged failed", e);
} finally {
Stopwatchs.end();
}
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
renderer.setJSONObject(jsonObject);
}
Aggregations