use of org.b3log.latke.repository.Transaction in project solo by b3log.
the class StatisticMgmtService method updateStatistic.
/**
* Updates the statistic with the specified statistic.
*
* @param statistic the specified statistic
* @throws ServiceException service exception
*/
public void updateStatistic(final JSONObject statistic) throws ServiceException {
final Transaction transaction = statisticRepository.beginTransaction();
try {
statisticRepository.update(Statistic.STATISTIC, statistic);
transaction.commit();
} catch (final RepositoryException e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Updates statistic failed", e);
}
LOGGER.log(Level.DEBUG, "Updates statistic successfully");
}
use of org.b3log.latke.repository.Transaction in project solo by b3log.
the class CommentReceiver method addComment.
/**
* Adds an article with the specified request.
*
* <p>
* Renders the response with a json object, for example,
* <pre>
* {
* "sc": true
* }
* </pre>
* </p>
*
* @param request the specified http servlet request, for example, <pre>
* {
* "comment": {
* "userB3Key": "",
* "oId": "",
* "commentSymphonyArticleId": "",
* "commentOnArticleId": "",
* "commentAuthorName": "",
* "commentAuthorEmail": "",
* "commentAuthorURL": "",
* "commentContent": "",
* "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
* }
* }
* </pre>
*
* @param response the specified http servlet response
* @param context the specified http request context
* @throws Exception exception
*/
@RequestProcessing(value = "/apis/symphony/comment", method = HTTPRequestMethod.PUT)
public void addComment(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);
final Transaction transaction = commentRepository.beginTransaction();
try {
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
final JSONObject symphonyCmt = requestJSONObject.optJSONObject(Comment.COMMENT);
final JSONObject preference = preferenceQueryService.getPreference();
final String keyOfSolo = preference.optString(Option.ID_C_KEY_OF_SOLO);
final String key = symphonyCmt.optString("userB3Key");
if (Strings.isEmptyOrNull(keyOfSolo) || !keyOfSolo.equals(key)) {
ret.put(Keys.STATUS_CODE, HttpServletResponse.SC_FORBIDDEN);
ret.put(Keys.MSG, "Wrong key");
return;
}
final String articleId = symphonyCmt.getString("commentOnArticleId");
final JSONObject article = articleRepository.get(articleId);
if (null == article) {
ret.put(Keys.STATUS_CODE, HttpServletResponse.SC_NOT_FOUND);
ret.put(Keys.MSG, "Not found the specified article[id=" + articleId + "]");
return;
}
final String commentName = symphonyCmt.getString("commentAuthorName");
final String commentEmail = symphonyCmt.getString("commentAuthorEmail").trim().toLowerCase();
String commentURL = symphonyCmt.optString("commentAuthorURL");
if (!commentURL.contains("://")) {
commentURL = "http://" + commentURL;
}
try {
new URL(commentURL);
} catch (final MalformedURLException e) {
LOGGER.log(Level.WARN, "The comment URL is invalid [{0}]", commentURL);
commentURL = "";
}
final String commentId = symphonyCmt.optString(Keys.OBJECT_ID);
String commentContent = symphonyCmt.getString(Comment.COMMENT_CONTENT);
// commentContent += "<p class='cmtFromSym'><i>该评论同步自 <a href='" + SoloServletListener.B3LOG_SYMPHONY_SERVE_PATH
// + "/article/" + symphonyCmt.optString("commentSymphonyArticleId") + "#" + commentId
// + "' target='_blank'>黑客派</a></i></p>";
final String originalCommentId = symphonyCmt.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID);
// Step 1: Add comment
final JSONObject comment = new JSONObject();
JSONObject originalComment = null;
comment.put(Keys.OBJECT_ID, commentId);
comment.put(Comment.COMMENT_NAME, commentName);
comment.put(Comment.COMMENT_EMAIL, commentEmail);
comment.put(Comment.COMMENT_URL, commentURL);
comment.put(Comment.COMMENT_CONTENT, commentContent);
final Date date = new Date();
comment.put(Comment.COMMENT_DATE, date);
ret.put(Comment.COMMENT_DATE, DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
if (!Strings.isEmptyOrNull(originalCommentId)) {
originalComment = commentRepository.get(originalCommentId);
if (null != originalComment) {
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, originalCommentId);
final String originalCommentName = originalComment.getString(Comment.COMMENT_NAME);
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
ret.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
} else {
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, "");
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
LOGGER.log(Level.WARN, "Not found orginal comment[id={0}] of reply[name={1}, content={2}]", new String[] { originalCommentId, commentName, commentContent });
}
} else {
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, "");
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
}
commentMgmtService.setCommentThumbnailURL(comment);
ret.put(Comment.COMMENT_THUMBNAIL_URL, comment.getString(Comment.COMMENT_THUMBNAIL_URL));
// Sets comment on article....
comment.put(Comment.COMMENT_ON_ID, articleId);
comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE);
final String commentSharpURL = Comments.getCommentSharpURLForArticle(article, commentId);
comment.put(Comment.COMMENT_SHARP_URL, commentSharpURL);
commentRepository.add(comment);
// Step 2: Update article comment count
articleMgmtService.incArticleCommentCount(articleId);
// Step 3: Update blog statistic comment count
statisticMgmtService.incBlogCommentCount();
statisticMgmtService.incPublishedBlogCommentCount();
// Step 4: Send an email to admin
try {
commentMgmtService.sendNotificationMail(article, comment, originalComment, preference);
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Send mail failed", e);
}
// Step 5: Fire add comment event
final JSONObject eventData = new JSONObject();
eventData.put(Comment.COMMENT, comment);
eventData.put(Article.ARTICLE, article);
eventManager.fireEventSynchronously(new Event<JSONObject>(EventTypes.ADD_COMMENT_TO_ARTICLE_FROM_SYMPHONY, eventData));
transaction.commit();
ret.put(Keys.STATUS_CODE, true);
ret.put(Keys.OBJECT_ID, commentId);
ret.put(Keys.OBJECT_ID, articleId);
ret.put(Keys.MSG, "add a comment to an article from symphony succ");
ret.put(Keys.STATUS_CODE, true);
renderer.setJSONObject(ret);
} catch (final ServiceException e) {
LOGGER.log(Level.ERROR, e.getMessage(), e);
final JSONObject jsonObject = QueryResults.defaultResult();
renderer.setJSONObject(jsonObject);
jsonObject.put(Keys.MSG, e.getMessage());
}
}
use of org.b3log.latke.repository.Transaction in project solo by b3log.
the class PluginRefresher method action.
@Override
public void action(final Event<List<AbstractPlugin>> event) throws EventException {
final List<AbstractPlugin> plugins = event.getData();
LOGGER.log(Level.DEBUG, "Processing an event[type={0}, data={1}] in listener[className={2}]", new Object[] { event.getType(), plugins, PluginRefresher.class.getName() });
final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
final PluginRepository pluginRepository = beanManager.getReference(PluginRepositoryImpl.class);
final Transaction transaction = pluginRepository.beginTransaction();
try {
final PluginMgmtService pluginMgmtService = beanManager.getReference(PluginMgmtService.class);
pluginMgmtService.refresh(plugins);
transaction.commit();
} catch (final Exception e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Processing plugin loaded event error", e);
throw new EventException(e);
}
}
use of org.b3log.latke.repository.Transaction in project solo by b3log.
the class LoginProcessor method sendResetUrl.
/**
* Sends the password resetting URL with a random token.
*
* @param userEmail the given email
* @param jsonObject return code and message object
* @throws JSONException the JSONException
* @throws ServiceException the ServiceException
* @throws IOException the IOException
* @throws RepositoryException the RepositoryException
*/
private void sendResetUrl(final String userEmail, final JSONObject jsonObject) throws JSONException, ServiceException, IOException, RepositoryException {
final JSONObject preference = preferenceQueryService.getPreference();
final String token = new Randoms().nextStringWithMD5();
final String adminEmail = preference.getString(Option.ID_C_ADMIN_EMAIL);
final String mailSubject = langPropsService.get("resetPwdMailSubject");
final String mailBody = langPropsService.get("resetPwdMailBody") + " " + Latkes.getServePath() + "/forgot?token=" + token + "&login=" + userEmail;
final MailService.Message message = new MailService.Message();
final JSONObject option = new JSONObject();
option.put(Keys.OBJECT_ID, token);
option.put(Option.OPTION_CATEGORY, "passwordReset");
option.put(Option.OPTION_VALUE, System.currentTimeMillis());
final Transaction transaction = optionRepository.beginTransaction();
optionRepository.add(option);
transaction.commit();
message.setFrom(adminEmail);
message.addRecipient(userEmail);
message.setSubject(mailSubject);
message.setHtmlBody(mailBody);
mailService.send(message);
jsonObject.put("succeed", true);
jsonObject.put("to", Latkes.getServePath() + "/login?from=forgot");
jsonObject.put(Keys.MSG, langPropsService.get("resetPwdSuccessSend"));
LOGGER.log(Level.DEBUG, "Sent a mail[mailSubject={0}, mailBody=[{1}] to [{2}]", new Object[] { mailSubject, mailBody, userEmail });
}
use of org.b3log.latke.repository.Transaction in project solo by b3log.
the class InitService method init.
/**
* Initializes Solo.
*
* <p>
* Initializes the followings in sequence:
* <ol>
* <li>Statistic</li>
* <li>Preference</li>
* <li>Administrator</li>
* </ol>
* </p>
*
* <p>
* We will try to initialize Solo 3 times at most.
* </p>
*
* <p>
* Posts "Hello World!" article and its comment while Solo initialized.
* </p>
*
* @param requestJSONObject the specified request json object, for example, <pre>
* {
* "userName": "",
* "userEmail": "",
* "userPassword": "", // Unhashed
* }
* </pre>
*
* @throws ServiceException service exception
*/
public void init(final JSONObject requestJSONObject) throws ServiceException {
if (isInited()) {
return;
}
final RuntimeEnv runtimeEnv = Latkes.getRuntimeEnv();
if (RuntimeEnv.LOCAL == runtimeEnv) {
LOGGER.log(Level.INFO, "Solo is running on [" + runtimeEnv + "] environment, database [{0}], creates " + "all tables", Latkes.getRuntimeDatabase());
if (RuntimeDatabase.H2 == Latkes.getRuntimeDatabase()) {
String dataDir = Latkes.getLocalProperty("jdbc.URL");
dataDir = dataDir.replace("~", System.getProperty("user.home"));
LOGGER.log(Level.INFO, "YOUR DATA will be stored in directory [" + dataDir + "], " + "please pay more attention to it~");
}
final List<CreateTableResult> createTableResults = JdbcRepositories.initAllTables();
for (final CreateTableResult createTableResult : createTableResults) {
LOGGER.log(Level.DEBUG, "Create table result[tableName={0}, isSuccess={1}]", new Object[] { createTableResult.getName(), createTableResult.isSuccess() });
}
}
int retries = MAX_RETRIES_CNT;
while (true) {
final Transaction transaction = userRepository.beginTransaction();
try {
final JSONObject statistic = statisticRepository.get(Statistic.STATISTIC);
if (null == statistic) {
initStatistic();
initPreference(requestJSONObject);
initReplyNotificationTemplate();
initAdmin(requestJSONObject);
initLink();
}
transaction.commit();
break;
} catch (final Exception e) {
if (0 == retries) {
LOGGER.log(Level.ERROR, "Initialize Solo error", e);
throw new ServiceException("Initailize Solo error: " + e.getMessage());
}
// Allow retry to occur
--retries;
LOGGER.log(Level.WARN, "Retrying to init Solo[retries={0}]", retries);
} finally {
if (transaction.isActive()) {
transaction.rollback();
}
}
}
final Transaction transaction = userRepository.beginTransaction();
try {
helloWorld();
transaction.commit();
} catch (final Exception e) {
if (transaction.isActive()) {
transaction.rollback();
}
LOGGER.log(Level.ERROR, "Hello World error?!", e);
}
try {
final URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
final HTTPRequest req = new HTTPRequest();
req.setURL(new URL(Latkes.getServePath() + "/blog/symphony/user"));
urlFetchService.fetch(req);
} catch (final Exception e) {
LOGGER.log(Level.TRACE, "Sync account failed");
}
pluginManager.load();
}
Aggregations