Example usage for org.apache.commons.lang.time DateFormatUtils format

List of usage examples for org.apache.commons.lang.time DateFormatUtils format

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateFormatUtils format.

Prototype

public static String format(Date date, String pattern) 

Source Link

Document

Formats a date/time into a specific pattern.

Usage

From source file:org.b3log.symphony.event.CommentNotifier.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, CommentNotifier.class.getName() });

    try {/*from  w ww .j ava2s.  co m*/
        final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
        final JSONObject originalComment = data.getJSONObject(Comment.COMMENT);
        final String commentContent = originalComment.optString(Comment.COMMENT_CONTENT);
        final JSONObject commenter = userQueryService
                .getUser(originalComment.optString(Comment.COMMENT_AUTHOR_ID));
        final String commenterName = commenter.optString(User.USER_NAME);

        // 0. Data channel (WebSocket)
        final JSONObject chData = new JSONObject();
        chData.put(Article.ARTICLE_T_ID, originalArticle.optString(Keys.OBJECT_ID));
        chData.put(Comment.COMMENT_T_ID, originalComment.optString(Keys.OBJECT_ID));
        chData.put(Comment.COMMENT_T_AUTHOR_NAME, commenterName);

        final String userEmail = commenter.optString(User.USER_EMAIL);
        chData.put(Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL, avatarQueryService.getAvatarURL(userEmail));
        chData.put(Common.THUMBNAIL_UPDATE_TIME, commenter.optLong(UserExt.USER_UPDATE_TIME));

        chData.put(Comment.COMMENT_CREATE_TIME, DateFormatUtils
                .format(new Date(originalComment.optLong(Comment.COMMENT_CREATE_TIME)), "yyyy-MM-dd HH:mm"));
        chData.put(Common.TIME_AGO, langPropsService.get("justNowLabel"));
        chData.put("thankLabel", langPropsService.get("thankLabel"));
        chData.put("thankedLabel", langPropsService.get("thankedLabel"));
        String thankTemplate = langPropsService.get("thankConfirmLabel");
        thankTemplate = thankTemplate.replace("{point}", String.valueOf(Symphonys.getInt("pointThankComment")))
                .replace("{user}", commenterName);
        chData.put(Comment.COMMENT_T_THANK_LABEL, thankTemplate);
        String cc = shortLinkQueryService.linkArticle(commentContent);
        cc = shortLinkQueryService.linkTag(cc);
        cc = Emotions.convert(cc);
        cc = Markdowns.toHTML(cc);
        cc = Markdowns.clean(cc, "");
        try {
            final Set<String> userNames = userQueryService.getUserNames(commentContent);
            for (final String userName : userNames) {
                cc = cc.replace('@' + userName, "@<a href='" + Latkes.getServePath() + "/member/" + userName
                        + "'>" + userName + "</a>");
            }
        } catch (final ServiceException e) {
            LOGGER.log(Level.ERROR, "Generates @username home URL for comment content failed", e);
        }
        chData.put(Comment.COMMENT_CONTENT, cc);

        ArticleChannel.notifyComment(chData);

        // + Article Heat
        final JSONObject articleHeat = new JSONObject();
        articleHeat.put(Article.ARTICLE_T_ID, originalArticle.optString(Keys.OBJECT_ID));
        articleHeat.put(Common.OPERATION, "+");

        ArticleListChannel.notifyHeat(articleHeat);
        ArticleChannel.notifyHeat(articleHeat);

        final boolean isDiscussion = originalArticle
                .optInt(Article.ARTICLE_TYPE) == Article.ARTICLE_TYPE_C_DISCUSSION;

        // Timeline
        if (!isDiscussion) {
            String articleTitle = Jsoup.parse(originalArticle.optString(Article.ARTICLE_TITLE)).text();
            articleTitle = Emotions.convert(articleTitle);
            final String articlePermalink = Latkes.getServePath()
                    + originalArticle.optString(Article.ARTICLE_PERMALINK);

            final JSONObject timeline = new JSONObject();
            timeline.put(Common.TYPE, Comment.COMMENT);
            String content = langPropsService.get("timelineCommentLabel");
            content = content
                    .replace("{user}",
                            "<a target='_blank' rel='nofollow' href='" + Latkes.getServePath() + "/member/"
                                    + commenterName + "'>" + commenterName + "</a>")
                    .replace("{article}",
                            "<a target='_blank' rel='nofollow' href='" + articlePermalink + "'>" + articleTitle
                                    + "</a>")
                    .replace("{comment}", cc.replaceAll("<p>", "").replaceAll("</p>", ""));
            timeline.put(Common.CONTENT, content);

            timelineMgmtService.addTimeline(timeline);
        }

        // 1. 'Commented' Notification
        final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID);
        final Set<String> atUserNames = userQueryService.getUserNames(commentContent);
        final boolean commenterIsArticleAuthor = articleAuthorId
                .equals(originalComment.optString(Comment.COMMENT_AUTHOR_ID));
        if (commenterIsArticleAuthor && atUserNames.isEmpty()) {
            return;
        }

        atUserNames.remove(commenterName); // Do not notify commenter itself

        if (!commenterIsArticleAuthor) {
            final JSONObject requestJSONObject = new JSONObject();
            requestJSONObject.put(Notification.NOTIFICATION_USER_ID, articleAuthorId);
            requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, originalComment.optString(Keys.OBJECT_ID));

            notificationMgmtService.addCommentedNotification(requestJSONObject);
        }

        final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT);
        final Set<String> articleContentAtUserNames = userQueryService.getUserNames(articleContent);

        // 2. 'At' Notification
        for (final String userName : atUserNames) {
            if (isDiscussion && !articleContentAtUserNames.contains(userName)) {
                continue;
            }

            final JSONObject user = userQueryService.getUserByName(userName);

            if (null == user) {
                LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName);

                continue;
            }

            if (user.optString(Keys.OBJECT_ID).equals(articleAuthorId)) {
                continue; // Has added in step 1
            }

            final JSONObject requestJSONObject = new JSONObject();
            requestJSONObject.put(Notification.NOTIFICATION_USER_ID, user.optString(Keys.OBJECT_ID));
            requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, originalComment.optString(Keys.OBJECT_ID));

            notificationMgmtService.addAtNotification(requestJSONObject);
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Sends the comment notification failed", e);
    }
}

From source file:org.b3log.symphony.processor.AdminProcessor.java

/**
 * Shows admin orders./*from  w  w w  .j av  a 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 = "/admin/orders", method = HTTPRequestMethod.GET)
@Before(adviceClass = { StopwatchStartAdvice.class, MallAdminCheck.class })
@After(adviceClass = { CSRFToken.class, StopwatchEndAdvice.class })
public void showOrders(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("admin/orders.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();

    String pageNumStr = request.getParameter("p");
    if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
        pageNumStr = "1";
    }

    final int pageNum = Integer.valueOf(pageNumStr);
    final int pageSize = Symphonys.PAGE_SIZE;
    final int windowSize = Symphonys.WINDOW_SIZE;

    final JSONObject requestJSONObject = new JSONObject();
    requestJSONObject.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
    requestJSONObject.put(Pagination.PAGINATION_PAGE_SIZE, pageSize);
    requestJSONObject.put(Pagination.PAGINATION_WINDOW_SIZE, windowSize);

    final String category = request.getParameter(Common.CATEGORY);
    if (!Strings.isEmptyOrNull(category)) {
        requestJSONObject.put(Order.ORDER_PRODUCT_CATEGORY, category);
        dataModel.put(Common.CATEGORY, category);
    } else {
        dataModel.put(Common.CATEGORY, "");
    }

    final String status = request.getParameter(Common.STATUS);
    if (!Strings.isEmptyOrNull(status)) {
        requestJSONObject.put(Order.ORDER_STATUS, status);
        dataModel.put(Common.STATUS, status);
    } else {
        requestJSONObject.put(Order.ORDER_STATUS, Order.ORDER_STATUS_C_INIT);
        dataModel.put(Common.STATUS, String.valueOf(Order.ORDER_STATUS_C_INIT));
    }

    final String from = request.getParameter(Common.FROM);
    if (!Strings.isEmptyOrNull(from)) {
        final Date date = DateUtils.parseDate(from, new String[] { "yyyy-MM-dd" });
        requestJSONObject.put(Common.FROM, date.getTime());
        dataModel.put(Common.FROM, DateFormatUtils.format(date, "yyyy-MM-dd"));
    } else {
        final Date date = DateUtils.addMonths(new Date(), -1);
        requestJSONObject.put(Common.FROM, date.getTime());
        dataModel.put(Common.FROM, DateFormatUtils.format(date, "yyyy-MM-dd"));
    }

    final String to = request.getParameter(Common.TO);
    if (!Strings.isEmptyOrNull(to)) {
        final Date date = DateUtils.parseDate(to, new String[] { "yyyy-MM-dd" });
        requestJSONObject.put(Common.TO, Times.getDayEndTime(date.getTime()));
        dataModel.put(Common.TO, DateFormatUtils.format(date, "yyyy-MM-dd"));
    } else {
        requestJSONObject.put(Common.TO, Times.getDayEndTime(System.currentTimeMillis()));
        dataModel.put(Common.TO, DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
    }

    final Map<String, Class<?>> fields = new HashMap<String, Class<?>>();
    fields.put(Keys.OBJECT_ID, String.class);
    fields.put(Order.ORDER_CONFIRM_TIME, Long.class);
    fields.put(Order.ORDER_CREATE_TIME, Long.class);
    fields.put(Order.ORDER_HANDLER_ID, String.class);
    fields.put(Order.ORDER_POINT, Integer.class);
    fields.put(Order.ORDER_PRICE, Double.class);
    fields.put(Order.ORDER_PRODUCT_NAME, String.class);
    fields.put(Order.ORDER_STATUS, Integer.class);
    fields.put(Order.ORDER_BUYER_ID, String.class);

    final JSONObject result = orderQueryService.getOrders(requestJSONObject, fields);
    dataModel.put(Order.ORDERS, CollectionUtils.jsonArrayToList(result.optJSONArray(Order.ORDERS)));

    final JSONObject pagination = result.optJSONObject(Pagination.PAGINATION);
    final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT);
    final JSONArray pageNums = pagination.optJSONArray(Pagination.PAGINATION_PAGE_NUMS);
    dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.opt(0));
    dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.opt(pageNums.length() - 1));
    dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
    dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
    dataModel.put(Pagination.PAGINATION_PAGE_NUMS, CollectionUtils.jsonArrayToList(pageNums));

    filler.fillHeaderAndFooter(request, response, dataModel);
}

From source file:org.b3log.symphony.processor.ArticleProcessor.java

/**
 * Shows add article./*from   w w  w.j  a  v  a2 s .  c om*/
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = "/post", method = HTTPRequestMethod.GET)
@Before(adviceClass = { StopwatchStartAdvice.class, LoginCheck.class })
@After(adviceClass = { CSRFToken.class, StopwatchEndAdvice.class })
public void showAddArticle(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
    context.setRenderer(renderer);

    renderer.setTemplateName("/home/post.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();

    // Qiniu file upload authenticate
    final Auth auth = Auth.create(Symphonys.get("qiniu.accessKey"), Symphonys.get("qiniu.secretKey"));
    final String uploadToken = auth.uploadToken(Symphonys.get("qiniu.bucket"));
    dataModel.put("qiniuUploadToken", uploadToken);
    dataModel.put("qiniuDomain", Symphonys.get("qiniu.domain"));

    if (!Symphonys.getBoolean("qiniu.enabled")) {
        dataModel.put("qiniuUploadToken", "");
    }

    final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);

    String tags = request.getParameter(Tag.TAGS);
    if (StringUtils.isBlank(tags)) {
        tags = "";

        dataModel.put(Tag.TAGS, tags);
    } else {
        tags = articleMgmtService.formatArticleTags(tags);
        final String[] tagTitles = tags.split(",");

        final StringBuilder tagBuilder = new StringBuilder();
        for (final String title : tagTitles) {
            final String tagTitle = title.trim();

            if (Strings.isEmptyOrNull(tagTitle)) {
                continue;
            }

            if (!Tag.TAG_TITLE_PATTERN.matcher(tagTitle).matches()) {
                continue;
            }

            if (Strings.isEmptyOrNull(tagTitle) || tagTitle.length() > Tag.MAX_TAG_TITLE_LENGTH
                    || tagTitle.length() < 1) {
                continue;
            }

            if (!Role.ADMIN_ROLE.equals(currentUser.optString(User.USER_ROLE))
                    && ArrayUtils.contains(Symphonys.RESERVED_TAGS, tagTitle)) {
                continue;
            }

            tagBuilder.append(tagTitle).append(",");
        }
        if (tagBuilder.length() > 0) {
            tagBuilder.deleteCharAt(tagBuilder.length() - 1);
        }

        dataModel.put(Tag.TAGS, tagBuilder.toString());
    }

    final String type = request.getParameter(Common.TYPE);
    if (StringUtils.isBlank(type)) {
        dataModel.put(Article.ARTICLE_TYPE, Article.ARTICLE_TYPE_C_NORMAL);
    } else {
        int articleType = Article.ARTICLE_TYPE_C_NORMAL;

        try {
            articleType = Integer.valueOf(type);
        } catch (final Exception e) {
            LOGGER.log(Level.WARN, "Gets article type error [" + type + "]", e);
        }

        if (Article.isInvalidArticleType(articleType)) {
            articleType = Article.ARTICLE_TYPE_C_NORMAL;
        }

        dataModel.put(Article.ARTICLE_TYPE, articleType);
    }

    // Default title for journal
    if (Article.ARTICLE_TYPE_C_JOURNAL_PARAGRAPH == (Integer) dataModel.get(Article.ARTICLE_TYPE)) {
        dataModel.put(Article.ARTICLE_TITLE, currentUser.optString(UserExt.USER_REAL_NAME) + " "
                + DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd"));
    }

    final String at = request.getParameter(Common.AT);
    if (StringUtils.isNotBlank(at)) {
        dataModel.put(Common.AT, at);
    }

    filler.fillHeaderAndFooter(request, response, dataModel);
}

From source file:org.b3log.symphony.processor.StatisticProcessor.java

/**
 * Loads statistic data./*from   w w  w.  j a  v  a 2s. c o  m*/
 *
 * @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.repository.ArchiveRepository.java

/**
 * Gets the latest week archive (Sunday) with the specified time.
 *
 * @param time the specified time//from   ww  w.  j a  va2  s. co m
 * @return archive, returns {@code null} if not found
 * @throws RepositoryException repository exception
 */
public JSONObject getWeekArchive(final long time) throws RepositoryException {
    final long weekEndTime = Times.getWeekEndTime(time);
    final String startDate = DateFormatUtils.format(time, "yyyyMMdd");
    final String endDate = DateFormatUtils.format(weekEndTime, "yyyyMMdd");

    final Query query = new Query().setCurrentPageNum(1).setPageCount(1)
            .addSort(Archive.ARCHIVE_DATE, SortDirection.DESCENDING)
            .setFilter(CompositeFilterOperator.and(
                    new PropertyFilter(Archive.ARCHIVE_DATE, FilterOperator.GREATER_THAN_OR_EQUAL, startDate),
                    new PropertyFilter(Archive.ARCHIVE_DATE, FilterOperator.LESS_THAN_OR_EQUAL, endDate)));
    final JSONObject result = get(query);
    final JSONArray data = result.optJSONArray(Keys.RESULTS);

    if (data.length() < 1) {
        return null;
    }

    return data.optJSONObject(0);
}

From source file:org.b3log.symphony.repository.ArchiveRepository.java

/**
 * Gets an archive with the specified time.
 *
 * @param time the specified time//w w  w.  jav  a2  s  .  co m
 * @return archive, returns {@code null} if not found
 * @throws RepositoryException repository exception
 */
public JSONObject getArchive(final long time) throws RepositoryException {
    final String archiveDate = DateFormatUtils.format(time, "yyyyMMdd");

    final Query query = new Query().setCurrentPageNum(1).setPageCount(1)
            .setFilter(new PropertyFilter(Archive.ARCHIVE_DATE, FilterOperator.EQUAL, archiveDate));
    final JSONObject result = get(query);
    final JSONArray data = result.optJSONArray(Keys.RESULTS);

    if (data.length() < 1) {
        return null;
    }

    return data.optJSONObject(0);
}

From source file:org.b3log.symphony.service.ActivityMgmtService.java

/**
 * Daily checkin./*from   w w w.  j av  a 2  s.  c om*/
 *
 * @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.ActivityMgmtService.java

/**
 * Bets 1A0001./*from   w  w  w .  j a v a  2s  . com*/
 *
 * @param userId the specified user id
 * @param amount the specified amount
 * @param smallOrLarge the specified small or large
 * @return result
 */
public synchronized JSONObject bet1A0001(final String userId, final int amount, final int smallOrLarge) {
    final JSONObject ret = Results.falseResult();

    if (activityQueryService.is1A0001Today(userId)) {
        ret.put(Keys.MSG, langPropsService.get("activityParticipatedLabel"));

        return ret;
    }

    final String date = DateFormatUtils.format(new Date(), "yyyyMMdd");

    final boolean succ = null != pointtransferMgmtService.transfer(userId, Pointtransfer.ID_C_SYS,
            Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_1A0001, amount, date + "-" + smallOrLarge);

    ret.put(Keys.STATUS_CODE, succ);

    final String msg = succ ? langPropsService.get("activityBetSuccLabel")
            : langPropsService.get("activityBetFailLabel");
    ret.put(Keys.MSG, msg);

    try {
        final JSONObject user = userQueryService.getUser(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("timelineActivity1A0001Label");
        content = content.replace("{user}", "<a target='_blank' rel='nofollow' href='" + Latkes.getServePath()
                + "/member/" + userName + "'>" + userName + "</a>");
        timeline.put(Common.CONTENT, content);

        timelineMgmtService.addTimeline(timeline);
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, "Timeline error", e);
    }

    return ret;
}

From source file:org.b3log.symphony.service.ActivityMgmtService.java

/**
 * Collects 1A0001.//w  ww. j  av  a  2 s.  c  om
 *
 * @param userId the specified user id
 * @return result
 */
public synchronized JSONObject collect1A0001(final String userId) {
    final JSONObject ret = Results.falseResult();

    if (!activityQueryService.is1A0001Today(userId)) {
        ret.put(Keys.MSG, langPropsService.get("activityNotParticipatedLabel"));

        return ret;
    }

    if (activityQueryService.isCollected1A0001Today(userId)) {
        ret.put(Keys.MSG, langPropsService.get("activityParticipatedLabel"));

        return ret;
    }

    final List<JSONObject> records = pointtransferQueryService.getLatestPointtransfers(userId,
            Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_1A0001, 1);
    final JSONObject pointtransfer = records.get(0);
    final String data = pointtransfer.optString(Pointtransfer.DATA_ID);
    final String smallOrLarge = data.split("-")[1];
    final int sum = pointtransfer.optInt(Pointtransfer.SUM);

    String smallOrLargeResult = null;
    try {
        final Document doc = Jsoup.parse(new URL("http://stockpage.10jqka.com.cn/1A0001/quote/header/"), 5000);
        final JSONObject result = new JSONObject(doc.text());
        final String price = result.optJSONObject("data").optJSONObject("1A0001").optString("10");

        if (!price.contains(".")) {
            smallOrLargeResult = "0";
        } else {
            int endInt = 0;
            if (price.split("\\.")[1].length() > 1) {
                final String end = price.substring(price.length() - 1);
                endInt = Integer.valueOf(end);
            }

            if (0 <= endInt && endInt <= 4) {
                smallOrLargeResult = "0";
            } else if (5 <= endInt && endInt <= 9) {
                smallOrLargeResult = "1";
            } else {
                LOGGER.error("Activity 1A0001 collect result [" + endInt + "]");
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Collect 1A0001 failed", e);

        ret.put(Keys.MSG, langPropsService.get("activity1A0001CollectFailLabel"));

        return ret;
    }

    if (Strings.isEmptyOrNull(smallOrLarge)) {
        ret.put(Keys.MSG, langPropsService.get("activity1A0001CollectFailLabel"));

        return ret;
    }

    ret.put(Keys.STATUS_CODE, true);
    if (StringUtils.equals(smallOrLarge, smallOrLargeResult)) {
        final int amount = sum * 2;

        final boolean succ = null != pointtransferMgmtService.transfer(Pointtransfer.ID_C_SYS, userId,
                Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_1A0001_COLLECT, amount,
                DateFormatUtils.format(new Date(), "yyyyMMdd") + "-" + smallOrLargeResult);

        if (succ) {
            String msg = langPropsService.get("activity1A0001CollectSucc1Label");
            msg = msg.replace("{point}", String.valueOf(amount));

            ret.put(Keys.MSG, msg);
        } else {
            ret.put(Keys.MSG, langPropsService.get("activity1A0001CollectFailLabel"));
        }
    } else {
        ret.put(Keys.MSG, langPropsService.get("activity1A0001CollectSucc0Label"));
    }

    return ret;
}

From source file:org.b3log.symphony.service.ArchiveMgmtService.java

/**
 * Refreshes the teams in an archive specified by the given time.
 *
 * @param time the given time/*  w w w  . j a  v a2 s.c  o  m*/
 * @throws ServiceException service exception
 */
@Transactional
public void refreshTeams(final long time) throws ServiceException {
    try {
        boolean toAdd = false;
        JSONObject archive = archiveRepository.getArchive(time);
        if (null == archive) {
            archive = new JSONObject();
            archive.put(Archive.ARCHIVE_DATE, DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd"));

            toAdd = true;
        }

        final JSONArray teams = new JSONArray();
        final String[] teamStrs = Symphonys.get("teams").split(",");
        for (final String teamStr : teamStrs) {
            final JSONObject team = new JSONObject();
            teams.put(team);
            team.put(Common.TEAM_NAME, teamStr);
            final JSONArray members = new JSONArray();
            team.put(User.USERS, members);

            final List<JSONObject> teamMembers = getTeamMembers(teamStr);
            for (final JSONObject teamMember : teamMembers) {
                final String memberId = teamMember.optString(Keys.OBJECT_ID);

                members.put(memberId);
            }
        }

        archive.put(Archive.ARCHIVE_TEAMS, teams.toString());

        if (toAdd) {
            archiveRepository.add(archive);
        } else {
            archiveRepository.update(archive.optString(Keys.OBJECT_ID), archive);
        }
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Refreshes archive failed", e);

        throw new ServiceException(e);
    }
}