List of usage examples for org.apache.commons.lang.time DateUtils addDays
public static Date addDays(Date date, int amount)
From source file:org.apache.oozie.command.coord.TestAbandonedCoordChecker.java
public void testStartTime() throws Exception { Date start = DateUtils.addDays(new Date(), 1); Date end = DateUtils.addDays(new Date(), 6); Date createdTime = new Date(); CoordinatorJobBean job1 = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, start, end, createdTime, true, false, 6);//from www.j a v a2s . c o m addRecordToCoordActionTable(job1.getId(), 6, CoordinatorAction.Status.FAILED); start = DateUtils.addDays(new Date(), -3); createdTime = DateUtils.addDays(new Date(), -4); CoordinatorJobBean job2 = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, start, end, createdTime, true, false, 4); addRecordToCoordActionTable(job2.getId(), 10, CoordinatorAction.Status.FAILED); new AbandonedCoordCheckerRunnable(5, true).run(); // job1 should be RUNNING as starttime > 2 days buffer assertEquals(CoordJobQueryExecutor.getInstance().get(CoordJobQuery.GET_COORD_JOB, job1.getId()).getStatus(), CoordinatorJob.Status.RUNNING); assertEquals(CoordJobQueryExecutor.getInstance().get(CoordJobQuery.GET_COORD_JOB, job2.getId()).getStatus(), CoordinatorJob.Status.KILLED); }
From source file:org.apache.oozie.command.coord.TestAbandonedCoordChecker.java
public void testCatchupJob() throws Exception { Date start = DateUtils.addMonths(new Date(), -1); Date end = DateUtils.addHours(new Date(), 4); // 4 hrs Date createdTime = DateUtils.addDays(new Date(), -1); CoordinatorJobBean job1 = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, start, end, createdTime, true, false, 6);/*from w w w .j a va 2 s .c o m*/ addRecordToCoordActionTable(job1.getId(), 6, CoordinatorAction.Status.FAILED); createdTime = DateUtils.addDays(new Date(), -3); CoordinatorJobBean job2 = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, start, end, createdTime, true, false, 4); addRecordToCoordActionTable(job2.getId(), 10, CoordinatorAction.Status.FAILED); new AbandonedCoordCheckerRunnable(5, true).run(); // Only one job should be running. assertEquals(CoordJobQueryExecutor.getInstance().get(CoordJobQuery.GET_COORD_JOB, job1.getId()).getStatus(), CoordinatorJob.Status.RUNNING); assertEquals(CoordJobQueryExecutor.getInstance().get(CoordJobQuery.GET_COORD_JOB, job2.getId()).getStatus(), CoordinatorJob.Status.KILLED); }
From source file:org.b3log.symphony.event.ArticleAddNotifier.java
@Override public void action(final Event<JSONObject> event) throws EventException { final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event [type={0}, data={1}]", event.getType(), data); try {// www . j a v a 2s . co m final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE); final String articleId = originalArticle.optString(Keys.OBJECT_ID); final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId); final String articleAuthorName = articleAuthor.optString(User.USER_NAME); final Set<String> requisiteAtUserPermissions = new HashSet<>(); requisiteAtUserPermissions.add(Permission.PERMISSION_ID_C_COMMON_AT_USER); final boolean hasAtUserPerm = roleQueryService.userHasPermissions(articleAuthorId, requisiteAtUserPermissions); final Set<String> atedUserIds = new HashSet<>(); if (hasAtUserPerm) { // 'At' Notification final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT); final Set<String> atUserNames = userQueryService.getUserNames(articleContent); atUserNames.remove(articleAuthorName); // Do not notify the author itself for (final String userName : atUserNames) { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName); continue; } final JSONObject requestJSONObject = new JSONObject(); final String atedUserId = user.optString(Keys.OBJECT_ID); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, atedUserId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addAtNotification(requestJSONObject); atedUserIds.add(atedUserId); } } final String tags = originalArticle.optString(Article.ARTICLE_TAGS); // 'following - user' Notification if (Article.ARTICLE_TYPE_C_DISCUSSION != originalArticle.optInt(Article.ARTICLE_TYPE) && Article.ARTICLE_ANONYMOUS_C_PUBLIC == originalArticle.optInt(Article.ARTICLE_ANONYMOUS) && !Tag.TAG_TITLE_C_SANDBOX.equals(tags) && !StringUtils.containsIgnoreCase(tags, Symphonys.get("systemAnnounce"))) { final JSONObject followerUsersResult = followQueryService.getFollowerUsers( UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL, articleAuthorId, 1, Integer.MAX_VALUE); final List<JSONObject> followerUsers = (List<JSONObject>) followerUsersResult.opt(Keys.RESULTS); for (final JSONObject followerUser : followerUsers) { final JSONObject requestJSONObject = new JSONObject(); final String followerUserId = followerUser.optString(Keys.OBJECT_ID); if (atedUserIds.contains(followerUserId)) { continue; } requestJSONObject.put(Notification.NOTIFICATION_USER_ID, followerUserId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addFollowingUserNotification(requestJSONObject); } } // Timeline final String articleTitle = Escapes.escapeHTML(originalArticle.optString(Article.ARTICLE_TITLE)); final String articlePermalink = Latkes.getServePath() + originalArticle.optString(Article.ARTICLE_PERMALINK); final JSONObject timeline = new JSONObject(); timeline.put(Common.USER_ID, articleAuthorId); timeline.put(Common.TYPE, Article.ARTICLE); String content = langPropsService.get("timelineArticleAddLabel"); if (Article.ARTICLE_ANONYMOUS_C_PUBLIC == originalArticle.optInt(Article.ARTICLE_ANONYMOUS)) { content = content.replace("{user}", "<a target='_blank' rel='nofollow' href='" + Latkes.getServePath() + "/member/" + articleAuthorName + "'>" + articleAuthorName + "</a>"); } else { content = content.replace("{user}", UserExt.ANONYMOUS_USER_NAME); } content = content.replace("{article}", "<a target='_blank' rel='nofollow' href='" + articlePermalink + "'>" + articleTitle + "</a>"); content = Emotions.convert(content); timeline.put(Common.CONTENT, content); timelineMgmtService.addTimeline(timeline); // 'Broadcast' / 'Book' Notification if (Article.ARTICLE_TYPE_C_CITY_BROADCAST == originalArticle.optInt(Article.ARTICLE_TYPE) || (Article.ARTICLE_TYPE_C_BOOK == originalArticle.optInt(Article.ARTICLE_TYPE) && !articleAuthorName.equals("book_share"))) { final String city = originalArticle.optString(Article.ARTICLE_CITY); if (StringUtils.isNotBlank(city)) { final JSONObject requestJSONObject = new JSONObject(); requestJSONObject.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, 1); requestJSONObject.put(Pagination.PAGINATION_PAGE_SIZE, Integer.MAX_VALUE); requestJSONObject.put(Pagination.PAGINATION_WINDOW_SIZE, Integer.MAX_VALUE); final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime(); requestJSONObject.put(UserExt.USER_LATEST_LOGIN_TIME, latestLoginTime); requestJSONObject.put(UserExt.USER_CITY, city); final JSONObject result = userQueryService.getUsersByCity(requestJSONObject); final JSONArray users = result.optJSONArray(User.USERS); for (int i = 0; i < users.length(); i++) { final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID); if (userId.equals(articleAuthorId)) { continue; } final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, userId); notification.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addBroadcastNotification(notification); } LOGGER.info("City [" + city + "] broadcast [users=" + users.length() + "]"); } } // 'Sys Announce' Notification if (StringUtils.containsIgnoreCase(tags, Symphonys.get("systemAnnounce"))) { final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime(); final JSONObject result = userQueryService.getLatestLoggedInUsers(latestLoginTime, 1, Integer.MAX_VALUE, Integer.MAX_VALUE); final JSONArray users = result.optJSONArray(User.USERS); for (int i = 0; i < users.length(); i++) { final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID); final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, userId); notification.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addSysAnnounceArticleNotification(notification); } LOGGER.info("System announcement [" + articleTitle + "] broadcast [users=" + users.length() + "]"); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends the article add notification failed", e); } }
From source file:org.b3log.symphony.event.ArticleNotifier.java
@Override public void action(final Event<JSONObject> event) throws EventException { final JSONObject data = event.getData(); LOGGER.log(Level.DEBUG, "Processing an event[type={0}, data={1}] in listener[className={2}]", new Object[] { event.getType(), data, ArticleNotifier.class.getName() }); try {/*from w ww .j ava 2s .c o m*/ final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE); final String articleId = originalArticle.optString(Keys.OBJECT_ID); final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId); final String articleAuthorName = articleAuthor.optString(User.USER_NAME); final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT); final Set<String> atUserNames = userQueryService.getUserNames(articleContent); atUserNames.remove(articleAuthorName); // Do not notify the author itself final Set<String> atedUserIds = new HashSet<String>(); // 'At' Notification for (final String userName : atUserNames) { final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName); continue; } final JSONObject requestJSONObject = new JSONObject(); final String atedUserId = user.optString(Keys.OBJECT_ID); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, atedUserId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addAtNotification(requestJSONObject); atedUserIds.add(atedUserId); } // 'FollowingUser' Notification if (Article.ARTICLE_TYPE_C_DISCUSSION != originalArticle.optInt(Article.ARTICLE_TYPE)) { final JSONObject followerUsersResult = followQueryService.getFollowerUsers(articleAuthorId, 1, Integer.MAX_VALUE); @SuppressWarnings("unchecked") final List<JSONObject> followerUsers = (List) followerUsersResult.opt(Keys.RESULTS); for (final JSONObject followerUser : followerUsers) { final JSONObject requestJSONObject = new JSONObject(); final String followerUserId = followerUser.optString(Keys.OBJECT_ID); if (atedUserIds.contains(followerUserId)) { continue; } requestJSONObject.put(Notification.NOTIFICATION_USER_ID, followerUserId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addFollowingUserNotification(requestJSONObject); } } // Timeline final String articleTitle = Jsoup.parse(originalArticle.optString(Article.ARTICLE_TITLE)).text(); final String articlePermalink = Latkes.getServePath() + originalArticle.optString(Article.ARTICLE_PERMALINK); final JSONObject timeline = new JSONObject(); timeline.put(Common.TYPE, Article.ARTICLE); String content = langPropsService.get("timelineArticleLabel"); content = content .replace("{user}", "<a target='_blank' rel='nofollow' href='" + Latkes.getServePath() + "/member/" + articleAuthorName + "'>" + articleAuthorName + "</a>") .replace("{article}", "<a target='_blank' rel='nofollow' href='" + articlePermalink + "'>" + articleTitle + "</a>"); content = Emotions.convert(content); timeline.put(Common.CONTENT, content); timelineMgmtService.addTimeline(timeline); // 'Broadcast' Notification if (Article.ARTICLE_TYPE_C_CITY_BROADCAST == originalArticle.optInt(Article.ARTICLE_TYPE)) { final String city = originalArticle.optString(Article.ARTICLE_CITY); if (StringUtils.isNotBlank(city)) { final JSONObject requestJSONObject = new JSONObject(); requestJSONObject.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, 1); requestJSONObject.put(Pagination.PAGINATION_PAGE_SIZE, Integer.MAX_VALUE); requestJSONObject.put(Pagination.PAGINATION_WINDOW_SIZE, Integer.MAX_VALUE); final long latestLoginTime = DateUtils.addDays(new Date(), -15).getTime(); requestJSONObject.put(UserExt.USER_LATEST_LOGIN_TIME, latestLoginTime); requestJSONObject.put(UserExt.USER_CITY, city); final JSONObject result = userQueryService.getUsersByCity(requestJSONObject); final JSONArray users = result.optJSONArray(User.USERS); for (int i = 0; i < users.length(); i++) { final String userId = users.optJSONObject(i).optString(Keys.OBJECT_ID); if (userId.equals(articleAuthorId)) { continue; } final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, userId); notification.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addBroadcastNotification(notification); } LOGGER.info("City broadcast [" + users.length() + "]"); } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends the article notification failed", e); } }
From source file:org.b3log.symphony.processor.LoginProcessor.java
/** * Forget password.// w ww. j a va 2 s . c o m * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/forget-pwd", method = HTTPRequestMethod.POST) @Before(adviceClass = UserForgetPwdValidation.class) public void forgetPwd(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { context.renderJSON(); final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST); final String email = requestJSONObject.optString(User.USER_EMAIL); try { final JSONObject user = userQueryService.getUserByEmail(email); if (null == user) { context.renderFalseResult().renderMsg(langPropsService.get("notFoundUserLabel")); return; } final String userId = user.optString(Keys.OBJECT_ID); final JSONObject verifycode = new JSONObject(); verifycode.put(Verifycode.BIZ_TYPE, Verifycode.BIZ_TYPE_C_RESET_PWD); final String code = RandomStringUtils.randomAlphanumeric(6); verifycode.put(Verifycode.CODE, code); verifycode.put(Verifycode.EXPIRED, DateUtils.addDays(new Date(), 1).getTime()); verifycode.put(Verifycode.RECEIVER, email); verifycode.put(Verifycode.STATUS, Verifycode.STATUS_C_UNSENT); verifycode.put(Verifycode.TYPE, Verifycode.TYPE_C_EMAIL); verifycode.put(Verifycode.USER_ID, userId); verifycodeMgmtService.addVerifycode(verifycode); context.renderTrueResult().renderMsg(langPropsService.get("verifycodeSentLabel")); } catch (final ServiceException e) { final String msg = langPropsService.get("resetPwdLabel") + " - " + e.getMessage(); LOGGER.log(Level.ERROR, msg + "[name={0}, email={1}]", email); context.renderMsg(msg); } }
From source file:org.b3log.symphony.processor.LoginProcessor.java
/** * Register Step 1./*from w w w . j a v a 2s . c o m*/ * * @param context the specified context * @param request the specified request * @param response the specified response * @throws ServletException servlet exception * @throws IOException io exception */ @RequestProcessing(value = "/register", method = HTTPRequestMethod.POST) @Before(adviceClass = UserRegisterValidation.class) public void register(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { context.renderJSON(); JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST); final String name = requestJSONObject.optString(User.USER_NAME); final String email = requestJSONObject.optString(User.USER_EMAIL); final String realName = requestJSONObject.optString(UserExt.USER_REAL_NAME); final String team = requestJSONObject.optString(UserExt.USER_TEAM); final String referral = requestJSONObject.optString(Common.REFERRAL); final JSONObject user = new JSONObject(); user.put(User.USER_NAME, name); user.put(User.USER_EMAIL, email); user.put(UserExt.USER_REAL_NAME, realName); user.put(UserExt.USER_TEAM, team); user.put(User.USER_PASSWORD, ""); try { final String newUserId = userMgmtService.addUser(user); final JSONObject verifycode = new JSONObject(); verifycode.put(Verifycode.BIZ_TYPE, Verifycode.BIZ_TYPE_C_REGISTER); String code = RandomStringUtils.randomAlphanumeric(6); if (!Strings.isEmptyOrNull(referral)) { code += "r=" + referral; } verifycode.put(Verifycode.CODE, code); verifycode.put(Verifycode.EXPIRED, DateUtils.addDays(new Date(), 1).getTime()); verifycode.put(Verifycode.RECEIVER, email); verifycode.put(Verifycode.STATUS, Verifycode.STATUS_C_UNSENT); verifycode.put(Verifycode.TYPE, Verifycode.TYPE_C_EMAIL); verifycode.put(Verifycode.USER_ID, newUserId); verifycodeMgmtService.addVerifycode(verifycode); context.renderTrueResult().renderMsg(langPropsService.get("verifycodeSentLabel")); } catch (final ServiceException e) { final String msg = langPropsService.get("registerFailLabel") + " - " + e.getMessage(); LOGGER.log(Level.ERROR, msg + "[name={0}, email={1}]", name, email); context.renderMsg(msg); } }
From source file:org.b3log.symphony.processor.StatisticProcessor.java
/** * Loads statistic data.//from w w w. j ava 2 s . c om * * @param request the specified HTTP servlet request * @param response the specified HTTP servlet response * @param context the specified HTTP request context * @throws Exception exception */ @RequestProcessing(value = "/cron/stat", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = StopwatchEndAdvice.class) public void loadStatData(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception { final Date end = new Date(); final Date dayStart = DateUtils.addDays(end, -30); monthDays.clear(); userCnts.clear(); articleCnts.clear(); commentCnts.clear(); months.clear(); historyArticleCnts.clear(); historyCommentCnts.clear(); historyUserCnts.clear(); for (int i = 0; i < 31; i++) { final Date day = DateUtils.addDays(dayStart, i); monthDays.add(DateFormatUtils.format(day, "yyyy-MM-dd")); final int userCnt = userQueryService.getUserCntInDay(day); userCnts.add(userCnt); final int articleCnt = articleQueryService.getArticleCntInDay(day); articleCnts.add(articleCnt); final int commentCnt = commentQueryService.getCommentCntInDay(day); commentCnts.add(commentCnt); } final JSONObject firstAdmin = userQueryService.getAdmins().get(0); final long monthStartTime = Times.getMonthStartTime(firstAdmin.optLong(Keys.OBJECT_ID)); final Date monthStart = new Date(monthStartTime); int i = 1; while (true) { final Date month = DateUtils.addMonths(monthStart, i); if (month.after(end)) { break; } i++; months.add(DateFormatUtils.format(month, "yyyy-MM")); final int userCnt = userQueryService.getUserCntInMonth(month); historyUserCnts.add(userCnt); final int articleCnt = articleQueryService.getArticleCntInMonth(month); historyArticleCnts.add(articleCnt); final int commentCnt = commentQueryService.getCommentCntInMonth(month); historyCommentCnts.add(commentCnt); } }
From source file:org.b3log.symphony.service.ActivityMgmtService.java
/** * Daily checkin.//from w w w . jav a2s. co m * * @param userId the specified user id * @return {@code Random int} if checkin succeeded, returns {@code Integer.MIN_VALUE} otherwise */ public synchronized int dailyCheckin(final String userId) { if (activityQueryService.isCheckedinToday(userId)) { return Integer.MIN_VALUE; } final Random random = new Random(); final int sum = random.nextInt(Pointtransfer.TRANSFER_SUM_C_ACTIVITY_CHECKIN_MAX) % (Pointtransfer.TRANSFER_SUM_C_ACTIVITY_CHECKIN_MAX - Pointtransfer.TRANSFER_SUM_C_ACTIVITY_CHECKIN_MIN + 1) + Pointtransfer.TRANSFER_SUM_C_ACTIVITY_CHECKIN_MIN; final boolean succ = null != pointtransferMgmtService.transfer(Pointtransfer.ID_C_SYS, userId, Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_CHECKIN, sum, userId); if (!succ) { return Integer.MIN_VALUE; } try { final JSONObject user = userQueryService.getUser(userId); int currentStreakStart = user.optInt(UserExt.USER_CURRENT_CHECKIN_STREAK_START); int currentStreakEnd = user.optInt(UserExt.USER_CURRENT_CHECKIN_STREAK_END); final Date today = new Date(); final String todayStr = DateFormatUtils.format(today, "yyyyMMdd"); final int todayInt = Integer.valueOf(todayStr); if (0 == currentStreakStart) { user.put(UserExt.USER_CURRENT_CHECKIN_STREAK_START, todayInt); user.put(UserExt.USER_CURRENT_CHECKIN_STREAK_END, todayInt); user.put(UserExt.USER_LONGEST_CHECKIN_STREAK_START, todayInt); user.put(UserExt.USER_LONGEST_CHECKIN_STREAK_END, todayInt); userMgmtService.updateUser(userId, user); return sum; } final Date endDate = DateUtils.parseDate(String.valueOf(currentStreakEnd), new String[] { "yyyyMMdd" }); final Date nextDate = DateUtils.addDays(endDate, 1); if (DateUtils.isSameDay(nextDate, today)) { user.put(UserExt.USER_CURRENT_CHECKIN_STREAK_END, todayInt); } else { user.put(UserExt.USER_CURRENT_CHECKIN_STREAK_START, todayInt); user.put(UserExt.USER_CURRENT_CHECKIN_STREAK_END, todayInt); } currentStreakStart = user.optInt(UserExt.USER_CURRENT_CHECKIN_STREAK_START); currentStreakEnd = user.optInt(UserExt.USER_CURRENT_CHECKIN_STREAK_END); final int longestStreakStart = user.optInt(UserExt.USER_LONGEST_CHECKIN_STREAK_START); final int longestStreakEnd = user.optInt(UserExt.USER_LONGEST_CHECKIN_STREAK_END); final Date currentStreakStartDate = DateUtils.parseDate(String.valueOf(currentStreakStart), new String[] { "yyyyMMdd" }); final Date currentStreakEndDate = DateUtils.parseDate(String.valueOf(currentStreakEnd), new String[] { "yyyyMMdd" }); final Date longestStreakStartDate = DateUtils.parseDate(String.valueOf(longestStreakStart), new String[] { "yyyyMMdd" }); final Date longestStreakEndDate = DateUtils.parseDate(String.valueOf(longestStreakEnd), new String[] { "yyyyMMdd" }); final int currentStreakDays = (int) ((currentStreakEndDate.getTime() - currentStreakStartDate.getTime()) / 86400000) + 1; final int longestStreakDays = (int) ((longestStreakEndDate.getTime() - longestStreakStartDate.getTime()) / 86400000) + 1; user.put(UserExt.USER_CURRENT_CHECKIN_STREAK, currentStreakDays); user.put(UserExt.USER_LONGEST_CHECKIN_STREAK, longestStreakDays); if (longestStreakDays < currentStreakDays) { user.put(UserExt.USER_LONGEST_CHECKIN_STREAK_START, currentStreakStart); user.put(UserExt.USER_LONGEST_CHECKIN_STREAK_END, currentStreakEnd); user.put(UserExt.USER_LONGEST_CHECKIN_STREAK, currentStreakDays); } userMgmtService.updateUser(userId, user); if (currentStreakDays > 0 && 0 == currentStreakDays % 10) { // Additional Point pointtransferMgmtService.transfer(Pointtransfer.ID_C_SYS, userId, Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_CHECKIN_STREAK, Pointtransfer.TRANSFER_SUM_C_ACTIVITY_CHECKINT_STREAK, userId); } final String userName = user.optString(User.USER_NAME); // Timeline final JSONObject timeline = new JSONObject(); timeline.put(Common.TYPE, Common.ACTIVITY); String content = langPropsService.get("timelineActivityCheckinLabel"); content = content.replace("{user}", "<a target='_blank' rel='nofollow' href='" + Latkes.getServePath() + "/member/" + userName + "'>" + userName + "</a>"); timeline.put(Common.CONTENT, content); timelineMgmtService.addTimeline(timeline); return sum; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Checkin streak error", e); return Integer.MIN_VALUE; } }
From source file:org.b3log.symphony.service.ArticleQueryService.java
/** * Gets hot articles with the specified fetch size. * * @param fetchSize the specified fetch size * @return recent articles, returns an empty list if not found * @throws ServiceException service exception *///from w ww. j a v a 2 s . co m public List<JSONObject> getHotArticles(final int fetchSize) throws ServiceException { final String id = String.valueOf(DateUtils.addDays(new Date(), -7).getTime()); try { final Query query = new Query().addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING) .addSort(Keys.OBJECT_ID, SortDirection.ASCENDING).setCurrentPageNum(1).setPageSize(fetchSize); final List<Filter> filters = new ArrayList<Filter>(); filters.add(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.GREATER_THAN_OR_EQUAL, id)); filters.add(new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION)); query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); final JSONObject result = articleRepository.get(query); final List<JSONObject> ret = CollectionUtils .<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS)); organizeArticles(ret); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets hot articles failed", e); throw new ServiceException(e); } }
From source file:org.b3log.symphony.service.LivenessQueryService.java
/** * Gets the yesterday's liveness.//from w ww .j a va 2s. c o m * * @param userId the specified user id * @return yesterday's liveness, returns {@code null} if not found */ public JSONObject getYesterdayLiveness(final String userId) { final Date yesterday = DateUtils.addDays(new Date(), -1); final String date = DateFormatUtils.format(yesterday, "yyyyMMdd"); try { return livenessRepository.getByUserAndDate(userId, date); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets yesterday's liveness failed", e); return null; } }