proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/UserCheckMidware.java
UserCheckMidware
handle
class UserCheckMidware { /** * User query service. */ @Inject private UserQueryService userQueryService; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final String userName = context.pathVar("userName"); if (UserExt.NULL_USER_NAME.equals(userName)) { context.sendError(404); context.abort(); } final JSONObject user = userQueryService.getUserByName(userName); if (null == user) { context.sendError(404); context.abort(); return; } if (UserExt.USER_STATUS_C_NOT_VERIFIED == user.optInt(UserExt.USER_STATUS)) { context.sendError(404); context.abort(); return; } if (UserExt.USER_STATUS_C_INVALID == user.optInt(UserExt.USER_STATUS)) { context.sendError(404); context.abort(); return; } context.attr(User.USER, user); context.handle();
64
244
308
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/Activity1A0001CollectValidationMidware.java
Activity1A0001CollectValidationMidware
handle
class Activity1A0001CollectValidationMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Activity query service. */ @Inject private ActivityQueryService activityQueryService; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
if (Symphonys.ACTIVITY_1A0001_CLOSED) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activityClosedLabel"))); context.abort(); return; } final Calendar calendar = Calendar.getInstance(); final int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activity1A0001CloseLabel"))); context.abort(); return; } final int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour < 16) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activityCollectNotOpenLabel"))); context.abort(); return; } final JSONObject currentUser = Sessions.getUser(); if (UserExt.USER_STATUS_C_VALID != currentUser.optInt(UserExt.USER_STATUS)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("userStatusInvalidLabel"))); context.abort(); return; } if (!activityQueryService.is1A0001Today(currentUser.optString(Keys.OBJECT_ID))) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activityNotParticipatedLabel"))); context.abort(); return; } context.handle();
99
432
531
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/Activity1A0001ValidationMidware.java
Activity1A0001ValidationMidware
handle
class Activity1A0001ValidationMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Activity query service. */ @Inject private ActivityQueryService activityQueryService; /** * Liveness query service. */ @Inject private LivenessQueryService livenessQueryService; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final JSONObject currentUser = Sessions.getUser(); final String userId = currentUser.optString(Keys.OBJECT_ID); final int currentLiveness = livenessQueryService.getCurrentLivenessPoint(userId); final int livenessMax = Symphonys.ACTIVITY_YESTERDAY_REWARD_MAX; final float liveness = (float) currentLiveness / livenessMax * 100; final float livenessThreshold = Symphonys.ACTIVITY_1A0001_LIVENESS_THRESHOLD; if (liveness < livenessThreshold) { String msg = langPropsService.get("activityNeedLivenessLabel"); msg = msg.replace("${liveness}", livenessThreshold + "%"); msg = msg.replace("${current}", String.format("%.2f", liveness) + "%"); context.renderJSON(new JSONObject().put(Keys.MSG, msg)); context.abort(); return; } if (Symphonys.ACTIVITY_1A0001_CLOSED) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activityClosedLabel"))); context.abort(); return; } final Calendar calendar = Calendar.getInstance(); final int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activity1A0001CloseLabel"))); context.abort(); return; } final int hour = calendar.get(Calendar.HOUR_OF_DAY); final int minute = calendar.get(Calendar.MINUTE); if (hour > 14 || (hour == 14 && minute > 55)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activityEndLabel"))); context.abort(); return; } final JSONObject requestJSONObject = context.requestJSON(); final int amount = requestJSONObject.optInt(Common.AMOUNT); if (200 != amount && 300 != amount && 400 != amount && 500 != amount) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activityBetFailLabel"))); context.abort(); return; } final int smallOrLarge = requestJSONObject.optInt(Common.SMALL_OR_LARGE); if (0 != smallOrLarge && 1 != smallOrLarge) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activityBetFailLabel"))); context.abort(); return; } if (UserExt.USER_STATUS_C_VALID != currentUser.optInt(UserExt.USER_STATUS)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("userStatusInvalidLabel"))); context.abort(); return; } if (activityQueryService.is1A0001Today(userId)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("activityParticipatedLabel"))); } final int balance = currentUser.optInt(UserExt.USER_POINT); if (balance - amount < 0) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("insufficientBalanceLabel"))); context.abort(); return; } context.handle();
130
959
1,089
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/ChatMsgAddValidationMidware.java
ChatMsgAddValidationMidware
handle
class ChatMsgAddValidationMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final Request request = context.getRequest(); final JSONObject requestJSONObject = context.requestJSON(); request.setAttribute(Keys.REQUEST, requestJSONObject); final JSONObject currentUser = Sessions.getUser(); if (System.currentTimeMillis() - currentUser.optLong(UserExt.USER_LATEST_CMT_TIME) < Symphonys.MIN_STEP_CHAT_TIME && !Role.ROLE_ID_C_ADMIN.equals(currentUser.optString(User.USER_ROLE))) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("tooFrequentCmtLabel"))); context.abort(); return; } String content = requestJSONObject.optString(Common.CONTENT); content = StringUtils.trim(content); if (StringUtils.isBlank(content) || content.length() > 4096) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("commentErrorLabel"))); context.abort(); return; } if (optionQueryService.containReservedWord(content)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("contentContainReservedWordLabel"))); context.abort(); return; } requestJSONObject.put(Common.CONTENT, content); context.handle();
123
366
489
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/CommentAddValidationMidware.java
CommentAddValidationMidware
handle
class CommentAddValidationMidware { public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final Request request = context.getRequest(); final JSONObject requestJSONObject = context.requestJSON(); request.setAttribute(Keys.REQUEST, requestJSONObject); final BeanManager beanManager = BeanManager.getInstance(); final LangPropsService langPropsService = beanManager.getReference(LangPropsService.class); final OptionQueryService optionQueryService = beanManager.getReference(OptionQueryService.class); final ArticleQueryService articleQueryService = beanManager.getReference(ArticleQueryService.class); final CommentQueryService commentQueryService = beanManager.getReference(CommentQueryService.class); final JSONObject exception = new JSONObject(); exception.put(Keys.CODE, StatusCodes.ERR); final String commentContent = StringUtils.trim(requestJSONObject.optString(Comment.COMMENT_CONTENT)); if (StringUtils.isBlank(commentContent) || commentContent.length() > Comment.MAX_COMMENT_CONTENT_LENGTH) { context.renderJSON(exception.put(Keys.MSG, langPropsService.get("commentErrorLabel"))); context.abort(); return; } if (optionQueryService.containReservedWord(commentContent)) { context.renderJSON(exception.put(Keys.MSG, langPropsService.get("contentContainReservedWordLabel"))); context.abort(); return; } final String articleId = requestJSONObject.optString(Article.ARTICLE_T_ID); if (StringUtils.isBlank(articleId)) { context.renderJSON(exception.put(Keys.MSG, langPropsService.get("commentArticleErrorLabel"))); context.abort(); return; } final JSONObject article = articleQueryService.getArticleById(articleId); if (null == article) { context.renderJSON(exception.put(Keys.MSG, langPropsService.get("commentArticleErrorLabel"))); context.abort(); return; } if (!article.optBoolean(Article.ARTICLE_COMMENTABLE)) { context.renderJSON(exception.put(Keys.MSG, langPropsService.get("notAllowCmtLabel"))); context.abort(); return; } final String originalCommentId = requestJSONObject.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID); if (StringUtils.isNotBlank(originalCommentId)) { final JSONObject originalCmt = commentQueryService.getComment(originalCommentId); if (null == originalCmt) { context.renderJSON(exception.put(Keys.MSG, langPropsService.get("commentArticleErrorLabel"))); context.abort(); return; } } context.handle();
36
696
732
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/CommentUpdateValidationMidware.java
CommentUpdateValidationMidware
handle
class CommentUpdateValidationMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Comment query service. */ @Inject private CommentQueryService commentQueryService; /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final Request request = context.getRequest(); final JSONObject requestJSONObject = context.requestJSON(); request.setAttribute(Keys.REQUEST, requestJSONObject); final BeanManager beanManager = BeanManager.getInstance(); final LangPropsService langPropsService = beanManager.getReference(LangPropsService.class); final OptionQueryService optionQueryService = beanManager.getReference(OptionQueryService.class); final JSONObject exception = new JSONObject(); exception.put(Keys.CODE, StatusCodes.ERR); final String commentContent = StringUtils.trim(requestJSONObject.optString(Comment.COMMENT_CONTENT)); if (StringUtils.isBlank(commentContent) || commentContent.length() > Comment.MAX_COMMENT_CONTENT_LENGTH) { context.renderJSON(exception.put(Keys.MSG, langPropsService.get("commentErrorLabel"))); context.abort(); return; } if (optionQueryService.containReservedWord(commentContent)) { context.renderJSON(exception.put(Keys.MSG, langPropsService.get("contentContainReservedWordLabel"))); context.abort(); return; } context.handle();
151
305
456
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/PointTransferValidationMidware.java
PointTransferValidationMidware
handle
class PointTransferValidationMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; /** * User query service. */ @Inject private UserQueryService userQueryService; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final Request request = context.getRequest(); final JSONObject requestJSONObject = context.requestJSON(); final String userName = requestJSONObject.optString(User.USER_NAME); if (StringUtils.isBlank(userName) || UserExt.COM_BOT_NAME.equals(userName)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("notFoundUserLabel"))); context.abort(); return; } final int amount = requestJSONObject.optInt(Common.AMOUNT); if (amount < 1 || amount > 5000) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("amountInvalidLabel"))); context.abort(); return; } JSONObject toUser = userQueryService.getUserByName(userName); if (null == toUser) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("notFoundUserLabel"))); context.abort(); return; } if (UserExt.USER_STATUS_C_VALID != toUser.optInt(UserExt.USER_STATUS)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("userStatusInvalidLabel"))); context.abort(); return; } request.setAttribute(Common.TO_USER, toUser); final JSONObject currentUser = Sessions.getUser(); if (UserExt.USER_STATUS_C_VALID != currentUser.optInt(UserExt.USER_STATUS)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("userStatusInvalidLabel"))); context.abort(); return; } if (currentUser.optString(User.USER_NAME).equals(toUser.optString(User.USER_NAME))) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("cannotTransferSelfLabel"))); context.abort(); return; } final int balanceMinLimit = Symphonys.POINT_TRANSER_MIN; final int balance = currentUser.optInt(UserExt.USER_POINT); if (balance - amount < balanceMinLimit) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("insufficientBalanceLabel"))); context.abort(); return; } String memo = StringUtils.trim(requestJSONObject.optString(Pointtransfer.MEMO)); if (128 < StringUtils.length(memo)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("memoTooLargeLabel"))); context.abort(); return; } memo = Jsoup.clean(memo, Safelist.none()); request.setAttribute(Pointtransfer.MEMO, memo); context.handle();
94
770
864
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/UpdatePasswordValidationMidware.java
UpdatePasswordValidationMidware
handle
class UpdatePasswordValidationMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final JSONObject requestJSONObject = context.requestJSON(); final String oldPwd = requestJSONObject.optString(User.USER_PASSWORD); if (StringUtils.isBlank(oldPwd)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("emptyOldPwdLabel"))); context.abort(); return; } final String pwd = requestJSONObject.optString(User.USER_PASSWORD); if (UserRegister2ValidationMidware.invalidUserPassword(pwd)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("invalidPasswordLabel"))); context.abort(); return; } context.handle();
64
192
256
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/UpdateProfilesValidationMidware.java
UpdateProfilesValidationMidware
handle
class UpdateProfilesValidationMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Max user nickname length. */ public static final int MAX_USER_NICKNAME_LENGTH = 20; /** * Max user URL length. */ public static final int MAX_USER_URL_LENGTH = 100; /** * Max user QQ length. */ public static final int MAX_USER_QQ_LENGTH = 12; /** * Max user intro length. */ public static final int MAX_USER_INTRO_LENGTH = 255; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} /** * Checks whether the specified user URL is invalid. * * @param userURL the specified user URL * @return {@code true} if it is invalid, returns {@code false} otherwise */ private boolean invalidUserURL(final String userURL) { if (!Strings.isURL(userURL)) { return true; } return userURL.length() > MAX_USER_URL_LENGTH; } }
final JSONObject requestJSONObject = context.requestJSON(); final String userURL = requestJSONObject.optString(User.USER_URL); if (StringUtils.isNotBlank(userURL) && invalidUserURL(userURL)) { context.renderJSON(new JSONObject().put(Keys.MSG, "URL" + langPropsService.get("colonLabel") + langPropsService.get("invalidUserURLLabel"))); context.abort(); return; } final String userQQ = requestJSONObject.optString(UserExt.USER_QQ); if (StringUtils.isNotBlank(userQQ) && (!Strings.isNumeric(userQQ) || userQQ.length() > MAX_USER_QQ_LENGTH)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("invalidUserQQLabel"))); context.abort(); return; } final String userNickname = requestJSONObject.optString(UserExt.USER_NICKNAME); if (StringUtils.isNotBlank(userNickname) && userNickname.length() > MAX_USER_NICKNAME_LENGTH) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("invalidUserNicknameLabel"))); context.abort(); return; } final String userIntro = requestJSONObject.optString(UserExt.USER_INTRO); if (StringUtils.isNotBlank(userIntro) && userIntro.length() > MAX_USER_INTRO_LENGTH) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("invalidUserIntroLabel"))); context.abort(); return; } final int userCommentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE); if (userCommentViewMode != UserExt.USER_COMMENT_VIEW_MODE_C_REALTIME && userCommentViewMode != UserExt.USER_COMMENT_VIEW_MODE_C_TRADITIONAL) { requestJSONObject.put(UserExt.USER_COMMENT_VIEW_MODE, UserExt.USER_COMMENT_VIEW_MODE_C_TRADITIONAL); } final String tagErrMsg = langPropsService.get("selfTagLabel") + langPropsService.get("colonLabel") + langPropsService.get("tagsErrorLabel"); String userTags = requestJSONObject.optString(UserExt.USER_TAGS); if (StringUtils.isNotBlank(userTags)) { userTags = Tag.formatTags(userTags); String[] tagTitles = userTags.split(","); if (null == tagTitles || 0 == tagTitles.length) { context.renderJSON(new JSONObject().put(Keys.MSG, tagErrMsg)); context.abort(); return; } tagTitles = new LinkedHashSet<>(Arrays.asList(tagTitles)).toArray(new String[0]); final StringBuilder tagBuilder = new StringBuilder(); for (int i = 0; i < tagTitles.length; i++) { final String tagTitle = tagTitles[i].trim(); if (StringUtils.isBlank(tagTitle)) { context.renderJSON(new JSONObject().put(Keys.MSG, tagErrMsg)); context.abort(); return; } if (Tag.containsWhiteListTags(tagTitle)) { tagBuilder.append(tagTitle).append(","); continue; } if (!Tag.TAG_TITLE_PATTERN.matcher(tagTitle).matches()) { context.renderJSON(new JSONObject().put(Keys.MSG, tagErrMsg)); context.abort(); return; } if (tagTitle.length() > Tag.MAX_TAG_TITLE_LENGTH) { context.renderJSON(new JSONObject().put(Keys.MSG, tagErrMsg)); context.abort(); return; } final JSONObject currentUser = Sessions.getUser(); if (!Role.ROLE_ID_C_ADMIN.equals(currentUser.optString(User.USER_ROLE)) && ArrayUtils.contains(Symphonys.RESERVED_TAGS, tagTitle)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("selfTagLabel") + langPropsService.get("colonLabel") + langPropsService.get("articleTagReservedLabel") + " [" + tagTitle + "]")); context.abort(); return; } tagBuilder.append(tagTitle).append(","); } if (tagBuilder.length() > 0) { tagBuilder.deleteCharAt(tagBuilder.length() - 1); } requestJSONObject.put(UserExt.USER_TAGS, tagBuilder.toString()); } context.handle();
317
1,277
1,594
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/UserForgetPwdValidationMidware.java
UserForgetPwdValidationMidware
handle
class UserForgetPwdValidationMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final JSONObject requestJSONObject = context.requestJSON(); final String email = requestJSONObject.optString(User.USER_EMAIL); final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA); if (CaptchaProcessor.invalidCaptcha(captcha)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("submitFailedLabel") + " - " + langPropsService.get("captchaErrorLabel"))); context.abort(); return; } if (!Strings.isEmail(email)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("submitFailedLabel") + " - " + langPropsService.get("invalidEmailLabel"))); context.abort(); return; } context.handle();
67
219
286
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/validate/UserRegister2ValidationMidware.java
UserRegister2ValidationMidware
handle
class UserRegister2ValidationMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * Max password length. * * <p> * MD5 32 * </p> */ private static final int MAX_PWD_LENGTH = 32; /** * Min password length. */ private static final int MIN_PWD_LENGTH = 1; public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} /** * Checks password, length [1, 16]. * * @param password the specific password * @return {@code true} if it is invalid, returns {@code false} otherwise */ public static boolean invalidUserPassword(final String password) { return password.length() < MIN_PWD_LENGTH || password.length() > MAX_PWD_LENGTH; } }
final JSONObject requestJSONObject = context.requestJSON(); // check if admin allow to register final JSONObject option = optionQueryService.getOption(Option.ID_C_MISC_ALLOW_REGISTER); if ("1".equals(option.optString(Option.OPTION_VALUE))) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("notAllowRegisterLabel"))); context.abort(); return; } final int appRole = requestJSONObject.optInt(UserExt.USER_APP_ROLE); final String password = requestJSONObject.optString(User.USER_PASSWORD); if (UserExt.USER_APP_ROLE_C_HACKER != appRole && UserExt.USER_APP_ROLE_C_PAINTER != appRole) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("registerFailLabel") + " - " + langPropsService.get("invalidAppRoleLabel"))); context.abort(); return; } if (invalidUserPassword(password)) { context.renderJSON(new JSONObject().put(Keys.MSG, langPropsService.get("registerFailLabel") + " - " + langPropsService.get("invalidPasswordLabel"))); context.abort(); return; } context.handle();
280
349
629
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/ArticleRepository.java
ArticleRepository
getRandomly
class ArticleRepository extends AbstractRepository { /** * Article cache. */ @Inject private ArticleCache articleCache; /** * Public constructor. */ public ArticleRepository() { super(Article.ARTICLE); } @Override public void remove(final String id) throws RepositoryException { super.remove(id); articleCache.removeArticle(id); } @Override public JSONObject get(final String id) throws RepositoryException { JSONObject ret = articleCache.getArticle(id); if (null != ret) { return ret; } ret = super.get(id); if (null == ret) { return null; } articleCache.putArticle(ret); return ret; } @Override public void update(final String id, final JSONObject article, final String... propertyNames) throws RepositoryException { super.update(id, article, propertyNames); article.put(Keys.OBJECT_ID, id); articleCache.putArticle(article); } @Override public List<JSONObject> getRandomly(final int fetchSize) throws RepositoryException {<FILL_FUNCTION_BODY>} /** * Gets an article by the specified article title. * * @param articleTitle the specified article title * @return an article, {@code null} if not found * @throws RepositoryException repository exception */ public JSONObject getByTitle(final String articleTitle) throws RepositoryException { final Query query = new Query().setFilter(new PropertyFilter(Article.ARTICLE_TITLE, FilterOperator.EQUAL, articleTitle)).setPageCount(1); return getFirst(query); } }
final List<JSONObject> ret = new ArrayList<>(); final double mid = Math.random(); Query query = new Query(). setFilter(CompositeFilterOperator.and(new PropertyFilter(Article.ARTICLE_RANDOM_DOUBLE, FilterOperator.GREATER_THAN_OR_EQUAL, mid), new PropertyFilter(Article.ARTICLE_RANDOM_DOUBLE, FilterOperator.LESS_THAN_OR_EQUAL, mid), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.NOT_EQUAL, Article.ARTICLE_STATUS_C_INVALID), new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION), new PropertyFilter(Article.ARTICLE_SHOW_IN_LIST, FilterOperator.NOT_EQUAL, Article.ARTICLE_SHOW_IN_LIST_C_NOT))). select(Article.ARTICLE_TITLE, Article.ARTICLE_PERMALINK, Article.ARTICLE_AUTHOR_ID). setPage(1, fetchSize).setPageCount(1); final List<JSONObject> list1 = getList(query); ret.addAll(list1); final int reminingSize = fetchSize - list1.size(); if (0 != reminingSize) { // Query for remains query = new Query(). setFilter(CompositeFilterOperator.and(new PropertyFilter(Article.ARTICLE_RANDOM_DOUBLE, FilterOperator.GREATER_THAN_OR_EQUAL, 0D), new PropertyFilter(Article.ARTICLE_RANDOM_DOUBLE, FilterOperator.LESS_THAN_OR_EQUAL, mid), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.NOT_EQUAL, Article.ARTICLE_STATUS_C_INVALID), new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.NOT_EQUAL, Article.ARTICLE_TYPE_C_DISCUSSION), new PropertyFilter(Article.ARTICLE_SHOW_IN_LIST, FilterOperator.NOT_EQUAL, Article.ARTICLE_SHOW_IN_LIST_C_NOT))). select(Article.ARTICLE_TITLE, Article.ARTICLE_PERMALINK, Article.ARTICLE_AUTHOR_ID). setPage(1, reminingSize).setPageCount(1); final List<JSONObject> list2 = getList(query); ret.addAll(list2); } return ret;
462
673
1,135
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/CommentRepository.java
CommentRepository
removeComment
class CommentRepository extends AbstractRepository { /** * Comment cache. */ @Inject private CommentCache commentCache; /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Revision repository. */ @Inject private RevisionRepository revisionRepository; /** * Option repository. */ @Inject private OptionRepository optionRepository; /** * Notification repository. */ @Inject private NotificationRepository notificationRepository; /** * Public constructor. */ public CommentRepository() { super(Comment.COMMENT); } /** * Removes a comment specified with the given comment id. Calls this method will remove all existed data related * with the specified comment forcibly. * * @param commentId the given comment id * @throws RepositoryException repository exception */ public void removeComment(final String commentId) throws RepositoryException {<FILL_FUNCTION_BODY>} @Override public void remove(final String id) throws RepositoryException { super.remove(id); commentCache.removeComment(id); } @Override public JSONObject get(final String id) throws RepositoryException { JSONObject ret = commentCache.getComment(id); if (null != ret) { return ret; } ret = super.get(id); if (null == ret) { return null; } commentCache.putComment(ret); return ret; } @Override public void update(final String id, final JSONObject comment, final String... propertyNames) throws RepositoryException { super.update(id, comment, propertyNames); comment.put(Keys.OBJECT_ID, id); commentCache.putComment(comment); } }
final JSONObject comment = get(commentId); if (null == comment) { return; } remove(comment.optString(Keys.OBJECT_ID)); final String commentAuthorId = comment.optString(Comment.COMMENT_AUTHOR_ID); final JSONObject commenter = userRepository.get(commentAuthorId); int commentCount = commenter.optInt(UserExt.USER_COMMENT_COUNT) - 1; if (0 > commentCount) { commentCount = 0; } commenter.put(UserExt.USER_COMMENT_COUNT, commentCount); userRepository.update(commentAuthorId, commenter); final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID); final JSONObject article = articleRepository.get(articleId); article.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT) - 1); if (0 < article.optInt(Article.ARTICLE_COMMENT_CNT)) { final Query latestCmtQuery = new Query(). setFilter(new PropertyFilter(Comment.COMMENT_ON_ARTICLE_ID, FilterOperator.EQUAL, articleId)). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING). setPage(1, 1); final JSONObject latestCmt = getFirst(latestCmtQuery); article.put(Article.ARTICLE_LATEST_CMT_TIME, latestCmt.optLong(Keys.OBJECT_ID)); final JSONObject latestCmtAuthor = userRepository.get(latestCmt.optString(Comment.COMMENT_AUTHOR_ID)); article.put(Article.ARTICLE_LATEST_CMTER_NAME, latestCmtAuthor.optString(User.USER_NAME)); } else { article.put(Article.ARTICLE_LATEST_CMT_TIME, articleId); article.put(Article.ARTICLE_LATEST_CMTER_NAME, ""); } articleRepository.update(articleId, article); final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Revision.REVISION_DATA_ID, FilterOperator.EQUAL, commentId), new PropertyFilter(Revision.REVISION_DATA_TYPE, FilterOperator.EQUAL, Revision.DATA_TYPE_C_COMMENT))); final List<JSONObject> commentRevisions = revisionRepository.getList(query); for (final JSONObject articleRevision : commentRevisions) { revisionRepository.remove(articleRevision.optString(Keys.OBJECT_ID)); } final JSONObject commentCntOption = optionRepository.get(Option.ID_C_STATISTIC_CMT_COUNT); commentCntOption.put(Option.OPTION_VALUE, commentCntOption.optInt(Option.OPTION_VALUE) - 1); optionRepository.update(Option.ID_C_STATISTIC_CMT_COUNT, commentCntOption); final String originalCommentId = comment.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID); if (StringUtils.isNotBlank(originalCommentId)) { final JSONObject originalComment = get(originalCommentId); if (null != originalComment) { originalComment.put(Comment.COMMENT_REPLY_CNT, originalComment.optInt(Comment.COMMENT_REPLY_CNT) - 1); update(originalCommentId, originalComment); } } notificationRepository.removeByDataId(commentId);
513
924
1,437
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/DomainTagRepository.java
DomainTagRepository
getByTagId
class DomainTagRepository extends AbstractRepository { /** * Public constructor. */ public DomainTagRepository() { super(Domain.DOMAIN + "_" + Tag.TAG); } /** * Gets domain-tag relations by the specified domain id. * * @param domainId the specified domain id * @param currentPageNum the specified current page number, MUST greater then {@code 0} * @param pageSize the specified page size(count of a page contains objects), MUST greater then {@code 0} * @return for example <pre> * { * "pagination": { * "paginationPageCount": 88250 * }, * "rslts": [{ * "oId": "", * "domain_oId": domainId, * "tag_oId": "" * }, ....] * } * </pre> * @throws RepositoryException repository exception */ public JSONObject getByDomainId(final String domainId, final int currentPageNum, final int pageSize) throws RepositoryException { final Query query = new Query(). setFilter(new PropertyFilter(Domain.DOMAIN + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, domainId)). setPage(currentPageNum, pageSize).setPageCount(1); return get(query); } /** * Removes domain-tag relations by the specified domain id. * * @param domainId the specified domain id * @throws RepositoryException repository exception */ public void removeByDomainId(final String domainId) throws RepositoryException { final Query query = new Query().setFilter(new PropertyFilter(Domain.DOMAIN + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, domainId)); remove(query); } /** * Gets domain-tag relations by the specified tag id. * * @param tagId the specified tag id * @param currentPageNum the specified current page number, MUST greater then {@code 0} * @param pageSize the specified page size(count of a page contains objects), MUST greater then {@code 0} * @return for example <pre> * { * "pagination": { * "paginationPageCount": 88250 * }, * "rslts": [{ * "oId": "", * "domain_oId": "", * "tag_oId": tagId * }, ....] * } * </pre> * @throws RepositoryException repository exception */ public JSONObject getByTagId(final String tagId, final int currentPageNum, final int pageSize) throws RepositoryException {<FILL_FUNCTION_BODY>} }
final Query query = new Query(). setFilter(new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tagId)). setPage(currentPageNum, pageSize).setPageCount(1); return get(query);
727
72
799
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/EmotionRepository.java
EmotionRepository
getUserEmojis
class EmotionRepository extends AbstractRepository { /** * Public constructor. */ public EmotionRepository() { super(Emotion.EMOTION); } /** * Gets a user's emotion (emoji with type=0). * * @param userId the specified user id * @return emoji string join with {@code ","}, returns {@code null} if not found * @throws RepositoryException repository exception */ public String getUserEmojis(final String userId) throws RepositoryException {<FILL_FUNCTION_BODY>} /** * Remove emotions by the specified user id. * * @param userId the specified user id * @throws RepositoryException repository exception */ public void removeByUserId(final String userId) throws RepositoryException { remove(new Query().setFilter(new PropertyFilter(Emotion.EMOTION_USER_ID, FilterOperator.EQUAL, userId))); } }
final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Emotion.EMOTION_USER_ID, FilterOperator.EQUAL, userId), new PropertyFilter(Emotion.EMOTION_TYPE, FilterOperator.EQUAL, Emotion.EMOTION_TYPE_C_EMOJI))). addSort(Emotion.EMOTION_SORT, SortDirection.ASCENDING); final List<JSONObject> result = getList(query); if (result.isEmpty()) { return null; } final StringBuilder retBuilder = new StringBuilder(); for (int i = 0; i < result.size(); i++) { retBuilder.append(result.get(i).optString(Emotion.EMOTION_CONTENT)); if (i != result.size() - 1) { retBuilder.append(","); } } return retBuilder.toString();
251
240
491
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/FollowRepository.java
FollowRepository
removeByFollowerIdAndFollowingId
class FollowRepository extends AbstractRepository { /** * Public constructor. */ public FollowRepository() { super(Follow.FOLLOW); } /** * Removes a follow relationship by the specified follower id and the specified following entity id. * * @param followerId the specified follower id * @param followingId the specified following entity id * @param followingType the specified following type * @throws RepositoryException repository exception */ public void removeByFollowerIdAndFollowingId(final String followerId, final String followingId, final int followingType) throws RepositoryException {<FILL_FUNCTION_BODY>} /** * Gets a follow relationship by the specified follower id and the specified following entity id. * * @param followerId the specified follower id * @param followingId the specified following entity id * @param followingType the specified following type * @return follow relationship, returns {@code null} if not found * @throws RepositoryException repository exception */ public JSONObject getByFollowerIdAndFollowingId(final String followerId, final String followingId, final int followingType) throws RepositoryException { final List<Filter> filters = new ArrayList<Filter>(); filters.add(new PropertyFilter(Follow.FOLLOWER_ID, FilterOperator.EQUAL, followerId)); filters.add(new PropertyFilter(Follow.FOLLOWING_ID, FilterOperator.EQUAL, followingId)); filters.add(new PropertyFilter(Follow.FOLLOWING_TYPE, FilterOperator.EQUAL, followingType)); final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); return getFirst(query); } /** * Determines whether exists a follow relationship for the specified follower and the specified following entity. * * @param followerId the specified follower id * @param followingId the specified following entity id * @param followingType the specified following type * @return {@code true} if exists, returns {@code false} otherwise * @throws RepositoryException repository exception */ public boolean exists(final String followerId, final String followingId, final int followingType) throws RepositoryException { return null != getByFollowerIdAndFollowingId(followerId, followingId, followingType); } /** * Get follows by the specified following id and type. * * @param followingId the specified following id * @param type the specified type * @param currentPageNum the specified current page number, MUST greater then {@code 0} * @param pageSize the specified page size(count of a page contains objects), MUST greater then {@code 0} * @return for example <pre> * { * "pagination": { * "paginationPageCount": 88250 * }, * "rslts": [{ * Follow * }, ....] * } * </pre> * @throws RepositoryException repository exception */ public JSONObject getByFollowingId(final String followingId, final int type, final int currentPageNum, final int pageSize) throws RepositoryException { final Query query = new Query(). setFilter(CompositeFilterOperator.and( new PropertyFilter(Follow.FOLLOWING_ID, FilterOperator.EQUAL, followingId), new PropertyFilter(Follow.FOLLOWING_TYPE, FilterOperator.EQUAL, type))). setPage(currentPageNum, pageSize).setPageCount(1); return get(query); } }
final JSONObject toRemove = getByFollowerIdAndFollowingId(followerId, followingId, followingType); if (null == toRemove) { return; } remove(toRemove.optString(Keys.OBJECT_ID));
908
64
972
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/LinkRepository.java
LinkRepository
getLink
class LinkRepository extends AbstractRepository { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(LinkRepository.class); /** * Gets a link with the specified address. * * @param addr the specified address * @return a link, returns {@code null} if not found */ public JSONObject getLink(final String addr) {<FILL_FUNCTION_BODY>} /** * Public constructor. */ public LinkRepository() { super(Link.LINK); } }
final String hash = DigestUtils.sha1Hex(addr); final Query query = new Query().setFilter(new PropertyFilter(Link.LINK_ADDR_HASH, FilterOperator.EQUAL, hash)). setPageCount(1).setPage(1, 1); try { return getFirst(query); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets link by address [addr=" + addr + ", hash=" + hash + "] failed", e); return null; }
147
139
286
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/LivenessRepository.java
LivenessRepository
getByUserAndDate
class LivenessRepository extends AbstractRepository { /** * Public constructor. */ public LivenessRepository() { super(Liveness.LIVENESS); } /** * Remove liveness by the specified user id. * * @param userId the specified user id * @throws RepositoryException repository exception */ public void removeByUserId(final String userId) throws RepositoryException { remove(new Query().setFilter(new PropertyFilter(Liveness.LIVENESS_USER_ID, FilterOperator.EQUAL, userId))); } /** * Gets a liveness by the specified user id and date. * * @param userId the specified user id * @param date the specified date * @return a liveness, {@code null} if not found * @throws RepositoryException repository exception */ public JSONObject getByUserAndDate(final String userId, final String date) throws RepositoryException {<FILL_FUNCTION_BODY>} }
final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Liveness.LIVENESS_USER_ID, FilterOperator.EQUAL, userId), new PropertyFilter(Liveness.LIVENESS_DATE, FilterOperator.EQUAL, date))).setPageCount(1); return getFirst(query);
259
92
351
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/NotificationRepository.java
NotificationRepository
hasSentByDataIdAndType
class NotificationRepository extends AbstractRepository { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(NotificationRepository.class); /** * Public constructor. */ public NotificationRepository() { super(Notification.NOTIFICATION); } /** * Removes notifications by the specified data id. * * @param dataId the specified data id * @throws RepositoryException repository exception */ public void removeByDataId(final String dataId) throws RepositoryException { remove(new Query().setFilter(new PropertyFilter(Notification.NOTIFICATION_DATA_ID, FilterOperator.EQUAL, dataId))); } /** * Checks whether has sent a notification to a user specified by the given user id with the specified data id and data type. * * @param userId the given user id * @param dataId the specified the specified data id * @param notificationDataType the specified notification data type * @return {@code true} if sent, returns {@code false} otherwise */ public boolean hasSentByDataIdAndType(final String userId, final String dataId, final int notificationDataType) {<FILL_FUNCTION_BODY>} /** * Remove notifications by the specified user id. * * @param userId the specified user id * @throws RepositoryException repository exception */ public void removeByUserId(final String userId) throws RepositoryException { remove(new Query().setFilter(new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId))); } }
try { return 0 < count(new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Notification.NOTIFICATION_USER_ID, FilterOperator.EQUAL, userId), new PropertyFilter(Notification.NOTIFICATION_DATA_ID, FilterOperator.EQUAL, dataId), new PropertyFilter(Notification.NOTIFICATION_DATA_TYPE, FilterOperator.EQUAL, notificationDataType)))); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Checks [" + notificationDataType + "] notification sent failed [userId=" + userId + ", dataId=" + dataId + "]", e); return false; }
412
177
589
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/OptionRepository.java
OptionRepository
get
class OptionRepository extends AbstractRepository { /** * Option cache. */ @Inject private OptionCache optionCache; /** * Public constructor. */ public OptionRepository() { super(Option.OPTION); } @Override public void remove(final String id) throws RepositoryException { super.remove(id); optionCache.removeOption(id); } @Override public JSONObject get(final String id) throws RepositoryException {<FILL_FUNCTION_BODY>} @Override public void update(final String id, final JSONObject option, final String... propertyNames) throws RepositoryException { super.update(id, option, propertyNames); option.put(Keys.OBJECT_ID, id); optionCache.putOption(option); } }
JSONObject ret = optionCache.getOption(id); if (null != ret) { return ret; } ret = super.get(id); if (null == ret) { return null; } optionCache.putOption(ret); return ret;
216
80
296
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/PointtransferRepository.java
PointtransferRepository
getActivityEatingSnakeAvg
class PointtransferRepository extends AbstractRepository { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(PointtransferRepository.class); /** * Gets average point of activity eating snake of a user specified by the given user id. * * @param userId the given user id * @return average point, if the point small than {@code 1}, returns {@code pointActivityEatingSnake} which * configured in sym.properties */ public int getActivityEatingSnakeAvg(final String userId) {<FILL_FUNCTION_BODY>} /** * Public constructor. */ public PointtransferRepository() { super(Pointtransfer.POINTTRANSFER); } }
int ret = Pointtransfer.TRANSFER_SUM_C_ACTIVITY_EATINGSNAKE; try { final List<JSONObject> result = select("SELECT\n" + " AVG(sum) AS point\n" + "FROM\n" + " `" + getName() + "`\n" + "WHERE\n" + " type = 27\n" + "AND toId = ?\n" + "", userId); if (!result.isEmpty()) { ret = result.get(0).optInt(Common.POINT, ret); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Calc avg point failed", e); } if (ret < 1) { ret = Pointtransfer.TRANSFER_SUM_C_ACTIVITY_EATINGSNAKE; } return ret;
197
243
440
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/ReferralRepository.java
ReferralRepository
getByDataIdAndIP
class ReferralRepository extends AbstractRepository { /** * Gets a referral by the specified data id and IP. * * @param dataId the specified data id * @param ip the specified IP * @return referral, returns {@code null} if not found * @throws RepositoryException repository exception */ public JSONObject getByDataIdAndIP(final String dataId, final String ip) throws RepositoryException {<FILL_FUNCTION_BODY>} /** * Public constructor. */ public ReferralRepository() { super(Referral.REFERRAL); } }
final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Referral.REFERRAL_DATA_ID, FilterOperator.EQUAL, dataId), new PropertyFilter(Referral.REFERRAL_IP, FilterOperator.EQUAL, ip))).setPageCount(1).setPage(1, 1); return getFirst(query);
161
98
259
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/TagArticleRepository.java
TagArticleRepository
getByTagId
class TagArticleRepository extends AbstractRepository { /** * Public constructor. */ public TagArticleRepository() { super(Tag.TAG + "_" + Article.ARTICLE); } /** * Removes tag-articles relations by the specified article id. * * @param articleId the specified article id * @throws RepositoryException repository exception */ public void removeByArticleId(final String articleId) throws RepositoryException { final List<JSONObject> relations = getByArticleId(articleId); for (final JSONObject relation : relations) { remove(relation.optString(Keys.OBJECT_ID)); } } /** * Gets tag-article relations by the specified article id. * * @param articleId the specified article id * @return for example <pre> * [{ * "oId": "", * "tag_oId": "", * "article_oId": articleId * }, ....], returns an empty list if not found * </pre> * @throws RepositoryException repository exception */ public List<JSONObject> getByArticleId(final String articleId) throws RepositoryException { final Query query = new Query().setFilter( new PropertyFilter(Article.ARTICLE + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, articleId)). setPageCount(1); return getList(query); } /** * Gets tag-article relations by the specified tag id. * * @param tagId the specified tag id * @param currentPageNum the specified current page number, MUST greater then {@code 0} * @param pageSize the specified page size(count of a page contains objects), MUST greater then {@code 0} * @return for example <pre> * { * "pagination": { * "paginationPageCount": 88250 * }, * "rslts": [{ * "oId": "", * "tag_oId": tagId, * "article_oId": "" * }, ....] * } * </pre> * @throws RepositoryException repository exception */ public JSONObject getByTagId(final String tagId, final int currentPageNum, final int pageSize) throws RepositoryException {<FILL_FUNCTION_BODY>} }
final Query query = new Query(). setFilter(new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tagId)). addSort(Article.ARTICLE + "_" + Keys.OBJECT_ID, SortDirection.DESCENDING). setPage(currentPageNum, pageSize).setPageCount(1); return get(query);
625
103
728
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/TagTagRepository.java
TagTagRepository
getByTag2Id
class TagTagRepository extends AbstractRepository { /** * Public constructor. */ public TagTagRepository() { super(Tag.TAG + "_" + Tag.TAG); } /** * Gets tag-tag relations by the specified tag1 id. * * @param tag1Id the specified tag1 id * @param currentPageNum the specified current page number, MUST greater then {@code 0} * @param pageSize the specified page size(count of a page contains objects), MUST greater then {@code 0} * @return for example <pre> * { * "pagination": { * "paginationPageCount": 88250 * }, * "rslts": [{ * "oId": "", * "tag1_oId": tag1Id, * "tag2_oId": "", * "weight": int * }, ....] * } * </pre> * @throws RepositoryException repository exception */ public JSONObject getByTag1Id(final String tag1Id, final int currentPageNum, final int pageSize) throws RepositoryException { final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Tag.TAG + "1_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tag1Id)); filters.add(new PropertyFilter(Common.WEIGHT, FilterOperator.GREATER_THAN_OR_EQUAL, Symphonys.TAG_RELATED_WEIGHT)); final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)). setPage(currentPageNum, pageSize).setPageCount(1). addSort(Common.WEIGHT, SortDirection.DESCENDING); return get(query); } /** * Gets tag-tag relations by the specified tag2 id. * * @param tag2Id the specified tag2 id * @param currentPageNum the specified current page number, MUST greater then {@code 0} * @param pageSize the specified page size(count of a page contains objects), MUST greater then {@code 0} * @return for example <pre> * { * "pagination": { * "paginationPageCount": 88250 * }, * "rslts": [{ * "oId": "", * "tag1_oId": "", * "tag2_oId": tag2Id, * "weight": int * }, ....] * } * </pre> * @throws RepositoryException repository exception */ public JSONObject getByTag2Id(final String tag2Id, final int currentPageNum, final int pageSize) throws RepositoryException {<FILL_FUNCTION_BODY>} /** * Gets a tag-tag relation by the specified tag1 id and tag2 id. * * @param tag1Id the specified tag1 id * @param tag2Id the specified tag2 id * @return for example <pre> * { * "oId": "", * "tag1_oId": tag1Id, * "tag2_oId": tag2Id, * "weight": int * }, returns {@code null} if not found * </pre> * @throws RepositoryException repository exception */ public JSONObject getByTag1IdAndTag2Id(final String tag1Id, final String tag2Id) throws RepositoryException { final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Tag.TAG + "1_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tag1Id)); filters.add(new PropertyFilter(Tag.TAG + "2_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tag2Id)); final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); return getFirst(query); } }
final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Tag.TAG + "2_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tag2Id)); filters.add(new PropertyFilter(Common.WEIGHT, FilterOperator.GREATER_THAN_OR_EQUAL, Symphonys.TAG_RELATED_WEIGHT)); final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)). setPage(currentPageNum, pageSize).setPageCount(1). addSort(Common.WEIGHT, SortDirection.DESCENDING); return get(query);
1,040
170
1,210
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/UserRepository.java
UserRepository
get
class UserRepository extends AbstractRepository { /** * User cache. */ @Inject private UserCache userCache; /** * Public constructor. */ public UserRepository() { super(User.USER); } @Override public JSONObject get(final String id) throws RepositoryException {<FILL_FUNCTION_BODY>} @Override public void update(final String id, final JSONObject user, final String... propertyNames) throws RepositoryException { final JSONObject old = get(id); if (null == old) { return; } userCache.removeUser(old); super.update(id, user, propertyNames); user.put(Keys.OBJECT_ID, id); userCache.putUser(user); } /** * Gets a user by the specified name. * * @param name the specified name * @return user, returns {@code null} if not found * @throws RepositoryException repository exception */ public JSONObject getByName(final String name) throws RepositoryException { JSONObject ret = userCache.getUserByName(name); if (null != ret) { return ret; } final Query query = new Query().setPageCount(1).setFilter(new PropertyFilter(User.USER_NAME, FilterOperator.EQUAL, name)); ret = getFirst(query); if (null == ret) { return null; } userCache.putUser(ret); return ret; } /** * Gets a user by the specified email. * * @param email the specified email * @return user, returns {@code null} if not found * @throws RepositoryException repository exception */ public JSONObject getByEmail(final String email) throws RepositoryException { final Query query = new Query().setPageCount(1).setFilter(new PropertyFilter(User.USER_EMAIL, FilterOperator.EQUAL, email.toLowerCase().trim())); return getFirst(query); } /** * Gets the administrators. * * @return administrators, returns an empty list if not found or error * @throws RepositoryException repository exception */ public List<JSONObject> getAdmins() throws RepositoryException { List<JSONObject> ret = userCache.getAdmins(); if (ret.isEmpty()) { final Query query = new Query().setFilter( new PropertyFilter(User.USER_ROLE, FilterOperator.EQUAL, Role.ROLE_ID_C_ADMIN)).setPageCount(1) .addSort(Keys.OBJECT_ID, SortDirection.ASCENDING); ret = getList(query); userCache.putAdmins(ret); } return ret; } /** * Gets the anonymous user. * * @return anonymous user * @throws RepositoryException repository exception */ public JSONObject getAnonymousUser() throws RepositoryException { return getByName(UserExt.ANONYMOUS_USER_NAME); } }
JSONObject ret = userCache.getUser(id); if (null != ret) { return ret; } ret = super.get(id); if (null == ret) { return null; } userCache.putUser(ret); return ret;
795
81
876
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/UserTagRepository.java
UserTagRepository
getByUserId
class UserTagRepository extends AbstractRepository { /** * Public constructor. */ public UserTagRepository() { super(User.USER + "_" + Tag.TAG); } /** * Removes user-tag relations by the specified user id and tag id. * * @param userId the specified user id * @param tagId the specified tag id * @param type the specified type * @throws RepositoryException repository exception */ public void removeByUserIdAndTagId(final String userId, final String tagId, final int type) throws RepositoryException { final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(User.USER + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, userId), new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tagId), new PropertyFilter(Common.TYPE, FilterOperator.EQUAL, type))).setPage(1, Integer.MAX_VALUE).setPageCount(1); remove(query); } /** * Gets user-tag relations by the specified user id. * * @param userId the specified user id * @param currentPageNum the specified current page number, MUST greater then {@code 0} * @param pageSize the specified page size(count of a page contains objects), MUST greater then {@code 0} * @return for example <pre> * { * "pagination": { * "paginationPageCount": 88250 * }, * "rslts": [{ * "oId": "", * "tag_oId": "", * "user_oId": userId, * "type": "" // "creator"/"article"/"comment", a tag 'creator' is also an 'article' quoter * }, ....] * } * </pre> * @throws RepositoryException repository exception */ public JSONObject getByUserId(final String userId, final int currentPageNum, final int pageSize) throws RepositoryException {<FILL_FUNCTION_BODY>} /** * Gets user-tag relations by the specified tag id. * * @param tagId the specified tag id * @param currentPageNum the specified current page number, MUST greater then {@code 0} * @param pageSize the specified page size(count of a page contains objects), MUST greater then {@code 0} * @return for example <pre> * { * "pagination": { * "paginationPageCount": 88250 * }, * "rslts": [{ * "oId": "", * "tag_oId": "", * "user_oId": userId, * "type": "" // "creator"/"article"/"comment", a tag 'creator' is also an 'article' quoter * }, ....] * } * </pre> * @throws RepositoryException repository exception */ public JSONObject getByTagId(final String tagId, final int currentPageNum, final int pageSize) throws RepositoryException { final Query query = new Query().setFilter(new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tagId)). setPage(currentPageNum, pageSize).setPageCount(1); return get(query); } }
final Query query = new Query().setFilter(new PropertyFilter(User.USER + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, userId)). setPage(currentPageNum, pageSize).setPageCount(1); return get(query);
897
70
967
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/repository/VoteRepository.java
VoteRepository
removeIfExists
class VoteRepository extends AbstractRepository { /** * Removes votes by the specified data id. * * @param dataId the specified data id * @throws RepositoryException repository exception */ public void removeByDataId(final String dataId) throws RepositoryException { remove(new Query().setFilter(new PropertyFilter(Vote.DATA_ID, FilterOperator.EQUAL, dataId)). setPageCount(1)); } /** * Removes vote if it exists. * * @param userId the specified user id * @param dataId the specified data entity id * @param dataType the specified data type * @return the removed vote type, returns {@code -1} if removed nothing * @throws RepositoryException repository exception */ public int removeIfExists(final String userId, final String dataId, final int dataType) throws RepositoryException {<FILL_FUNCTION_BODY>} /** * Public constructor. */ public VoteRepository() { super(Vote.VOTE); } }
final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Vote.USER_ID, FilterOperator.EQUAL, userId)); filters.add(new PropertyFilter(Vote.DATA_ID, FilterOperator.EQUAL, dataId)); filters.add(new PropertyFilter(Vote.DATA_TYPE, FilterOperator.EQUAL, dataType)); final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); final JSONObject voteToRemove = getFirst(query); if (null == voteToRemove) { return -1; } remove(voteToRemove.optString(Keys.OBJECT_ID)); return voteToRemove.optInt(Vote.TYPE);
275
191
466
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/AvatarQueryService.java
AvatarQueryService
getAvatarURLByUser
class AvatarQueryService { /** * Default avatar URL. */ public static final String DEFAULT_AVATAR_URL = Latkes.getStaticServePath() + "/images/user-thumbnail.png"; /** * Fills the specified user thumbnail URL. * * @param user the specified user */ public void fillUserAvatarURL(final JSONObject user) { user.put(UserExt.USER_AVATAR_URL + "210", getAvatarURLByUser(user, "210")); user.put(UserExt.USER_AVATAR_URL + "48", getAvatarURLByUser(user, "48")); user.put(UserExt.USER_AVATAR_URL + "20", getAvatarURLByUser(user, "20")); } /** * Gets the default avatar URL with the specified size. * * @param size the specified size * @return the default avatar URL */ public String getDefaultAvatarURL(final String size) { if (!Symphonys.QN_ENABLED) { return DEFAULT_AVATAR_URL; } return DEFAULT_AVATAR_URL + "?imageView2/1/w/" + size + "/h/" + size + "/interlace/0/q/100"; } /** * Gets the avatar URL for the specified user with the specified size. * * @param user the specified user * @param size the specified size * @return the avatar URL */ public String getAvatarURLByUser(final JSONObject user, final String size) {<FILL_FUNCTION_BODY>} /** * Creates a avatar image with the specified hash string and size. * <p> * Refers to: https://github.com/superhj1987/awesome-identicon * </p> * * @param hash the specified hash string * @param size the specified size * @return buffered image */ public BufferedImage createAvatar(final String hash, final int size) { final boolean[][] array = new boolean[6][5]; for (int i = 0; i < 6; i++) { for (int j = 0; j < 5; j++) { array[i][j] = false; } } for (int i = 0; i < hash.length(); i += 2) { final int s = i / 2; final boolean v = Math.random() > 0.5; if (s % 3 == 0) { array[s / 3][0] = v; array[s / 3][4] = v; } else if (s % 3 == 1) { array[s / 3][1] = v; array[s / 3][3] = v; } else { array[s / 3][2] = v; } } final int ratio = Math.round(size / 5); final BufferedImage ret = new BufferedImage(ratio * 5, ratio * 5, BufferedImage.TYPE_3BYTE_BGR); final Graphics graphics = ret.getGraphics(); graphics.setColor(new Color(Integer.parseInt(String.valueOf(hash.charAt(0)), 16) * 16, Integer.parseInt(String.valueOf(hash.charAt(1)), 16) * 16, Integer.parseInt(String.valueOf(hash.charAt(2)), 16) * 16)); graphics.fillRect(0, 0, ret.getWidth(), ret.getHeight()); graphics.setColor(new Color(Integer.parseInt(String.valueOf(hash.charAt(hash.length() - 1)), 16) * 16, Integer.parseInt(String.valueOf(hash.charAt(hash.length() - 2)), 16) * 16, Integer.parseInt(String.valueOf(hash.charAt(hash.length() - 3)), 16) * 16)); for (int i = 0; i < 6; i++) { for (int j = 0; j < 5; j++) { if (array[i][j]) { graphics.fillRect(j * ratio, i * ratio, ratio, ratio); } } } return ret; } }
if (null == user) { return getDefaultAvatarURL(size); } final int viewMode = Sessions.getAvatarViewMode(); String originalURL = user.optString(UserExt.USER_AVATAR_URL); if (StringUtils.isBlank(originalURL)) { originalURL = DEFAULT_AVATAR_URL; } if (StringUtils.isBlank(originalURL) || Strings.contains(originalURL, new String[]{"<", ">", "\"", "'"})) { originalURL = DEFAULT_AVATAR_URL; } String avatarURL = StringUtils.substringBeforeLast(originalURL, "?"); final boolean qiniuEnabled = Symphonys.QN_ENABLED; if (UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL == viewMode) { if (qiniuEnabled) { final String qiniuDomain = Symphonys.UPLOAD_QINIU_DOMAIN; if (!StringUtils.startsWith(avatarURL, qiniuDomain)) { return DEFAULT_AVATAR_URL + "?imageView2/1/w/" + size + "/h/" + size + "/interlace/0/q/100"; } else { return avatarURL + "?imageView2/1/w/" + size + "/h/" + size + "/interlace/0/q/100"; } } else { return avatarURL; } } else if (qiniuEnabled) { final String qiniuDomain = Symphonys.UPLOAD_QINIU_DOMAIN; if (!StringUtils.startsWith(avatarURL, qiniuDomain)) { return DEFAULT_AVATAR_URL + "?imageView2/1/w/" + size + "/h/" + size + "/format/jpg/interlace/0/q/100"; } else { return avatarURL + "?imageView2/1/w/" + size + "/h/" + size + "/format/jpg/interlace/0/q/100"; } } else { return avatarURL; }
1,139
553
1,692
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/BreezemoonMgmtService.java
BreezemoonMgmtService
updateBreezemoon
class BreezemoonMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(BreezemoonMgmtService.class); /** * Breezemoon repository. */ @Inject private BreezemoonRepository breezemoonRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Adds a breezemoon with the specified request json object. * * @param requestJSONObject the specified request json object, for example, * "breezemoonContent": "", * "breezemoonAuthorId": "", * "breezemoonIP": "", * "breezemoonUA": "", * "breezemoonCity": "" * @throws ServiceException service exception */ @Transactional public void addBreezemoon(final JSONObject requestJSONObject) throws ServiceException { final String content = requestJSONObject.optString(Breezemoon.BREEZEMOON_CONTENT); if (optionQueryService.containReservedWord(content)) { throw new ServiceException(langPropsService.get("contentContainReservedWordLabel")); } final JSONObject bm = new JSONObject(); bm.put(Breezemoon.BREEZEMOON_CONTENT, content); bm.put(Breezemoon.BREEZEMOON_AUTHOR_ID, requestJSONObject.optString(Breezemoon.BREEZEMOON_AUTHOR_ID)); bm.put(Breezemoon.BREEZEMOON_IP, requestJSONObject.optString(Breezemoon.BREEZEMOON_IP)); String ua = requestJSONObject.optString(Breezemoon.BREEZEMOON_UA); if (StringUtils.length(ua) > Common.MAX_LENGTH_UA) { ua = StringUtils.substring(ua, 0, Common.MAX_LENGTH_UA); } bm.put(Breezemoon.BREEZEMOON_UA, ua); final long now = System.currentTimeMillis(); bm.put(Breezemoon.BREEZEMOON_CREATED, now); bm.put(Breezemoon.BREEZEMOON_UPDATED, now); bm.put(Breezemoon.BREEZEMOON_STATUS, Breezemoon.BREEZEMOON_STATUS_C_VALID); bm.put(Breezemoon.BREEZEMOON_CITY, requestJSONObject.optString(Breezemoon.BREEZEMOON_CITY)); try { breezemoonRepository.add(bm); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Adds a breezemoon failed", e); throw new ServiceException(langPropsService.get("systemErrLabel")); } } /** * Updates a breezemoon with the specified request json object. * * @param requestJSONObject the specified request json object, for example, * "oId": "", * "breezemoonContent": "", * "breezemoonAuthorId": "", * "breezemoonIP": "", * "breezemoonUA": "", * "breezemoonStatus": "" // optional, 0 as default * @throws ServiceException service exception */ @Transactional public void updateBreezemoon(final JSONObject requestJSONObject) throws ServiceException {<FILL_FUNCTION_BODY>} /** * Removes a breezemoon with the specified id. * * @param id the specified id * @throws ServiceException service exception */ @Transactional public void removeBreezemoon(final String id) throws ServiceException { try { breezemoonRepository.remove(id); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Removes a breezemoon [id=" + id + "] failed", e); throw new ServiceException(langPropsService.get("systemErrLabel")); } } }
final String content = requestJSONObject.optString(Breezemoon.BREEZEMOON_CONTENT); if (optionQueryService.containReservedWord(content)) { throw new ServiceException(langPropsService.get("contentContainReservedWordLabel")); } final String id = requestJSONObject.optString(Keys.OBJECT_ID); JSONObject old; try { old = breezemoonRepository.get(id); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets a breezemoon [id=" + id + "] failed", e); throw new ServiceException(langPropsService.get("systemErrLabel")); } if (null == old) { throw new ServiceException(langPropsService.get("queryFailedLabel")); } old.put(Breezemoon.BREEZEMOON_CONTENT, content); old.put(Breezemoon.BREEZEMOON_AUTHOR_ID, requestJSONObject.optString(Breezemoon.BREEZEMOON_AUTHOR_ID, old.optString(Breezemoon.BREEZEMOON_AUTHOR_ID))); old.put(Breezemoon.BREEZEMOON_IP, requestJSONObject.optString(Breezemoon.BREEZEMOON_IP)); String ua = requestJSONObject.optString(Breezemoon.BREEZEMOON_UA); if (StringUtils.length(ua) > Common.MAX_LENGTH_UA) { ua = StringUtils.substring(ua, 0, Common.MAX_LENGTH_UA); } old.put(Breezemoon.BREEZEMOON_UA, ua); old.put(Breezemoon.BREEZEMOON_STATUS, requestJSONObject.optInt(Breezemoon.BREEZEMOON_STATUS, Breezemoon.BREEZEMOON_STATUS_C_VALID)); final long now = System.currentTimeMillis(); old.put(Breezemoon.BREEZEMOON_UPDATED, now); try { breezemoonRepository.update(id, old); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Updates a breezemoon failed", e); throw new ServiceException(langPropsService.get("systemErrLabel")); }
1,174
628
1,802
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/CacheMgmtService.java
CacheMgmtService
statusReport
class CacheMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(CacheMgmtService.class); /** * Global locks */ private static final Cache LOCKS = CacheFactory.getCache("locks"); /** * Tag cache. */ @Inject private TagCache tagCache; /** * Domain cache. */ @Inject private DomainCache domainCache; /** * Article cache. */ @Inject private ArticleCache articleCache; /** * User management service. */ @Inject private UserMgmtService userMgmtService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * Refreshes all caches. */ public void refreshCache() { final String lockName = "refreshCaches"; if (!lock(lockName)) { return; } try { LOGGER.info("Refreshing cache"); domainCache.loadDomains(); articleCache.loadPerfectArticles(); articleCache.loadSideHotArticles(); articleCache.loadSideRandomArticles(); tagCache.loadTags(); final StatisticProcessor statisticProcessor = BeanManager.getInstance().getReference(StatisticProcessor.class); statisticProcessor.loadStatData(); userQueryService.loadUserNames(); statusReport(); LOGGER.info("Refreshed cache"); } finally { unlock(lockName); } } private void statusReport() {<FILL_FUNCTION_BODY>} /** * Lock. * * @param lockName the specified lock name * @return {@code true} if lock successfully, returns {@code false} otherwise */ public synchronized static boolean lock(final String lockName) { JSONObject lock = LOCKS.get(lockName); if (null == lock) { lock = new JSONObject(); } if (lock.optBoolean(Common.LOCK)) { return false; } lock.put(Common.LOCK, true); LOCKS.put(lockName, lock); return true; } /** * Unlock. * * @param lockName the specified lock name */ public synchronized static void unlock(final String lockName) { JSONObject lock = LOCKS.get(lockName); if (null == lock) { lock = new JSONObject(); } lock.put(Common.LOCK, false); LOCKS.put(lockName, lock); } }
final JSONObject ret = new JSONObject(); ret.put(Common.ONLINE_VISITOR_CNT, optionQueryService.getOnlineVisitorCount()); ret.put(Common.ONLINE_MEMBER_CNT, optionQueryService.getOnlineMemberCount()); ret.put(Common.ONLINE_CHAT_CNT, ChatroomChannel.SESSIONS.size()); ret.put(Common.ARTICLE_CHANNEL_CNT, ArticleChannel.SESSIONS.size()); ret.put(Common.ARTICLE_LIST_CHANNEL_CNT, ArticleListChannel.SESSIONS.size()); ret.put(Common.THREAD_CNT, Symphonys.getActiveThreadCount() + "/" + Symphonys.getMaxThreadCount()); ret.put(Common.DB_CONN_CNT, Connections.getActiveConnectionCount() + "/" + Connections.getTotalConnectionCount() + "/" + Connections.getMaxConnectionCount()); ret.put(Keys.Runtime.RUNTIME_CACHE, Latkes.getRuntimeCache().name()); ret.put(Keys.Runtime.RUNTIME_DATABASE, Latkes.getRuntimeDatabase().name()); ret.put(Keys.Runtime.RUNTIME_MODE, Latkes.getRuntimeMode().name()); final JSONObject memory = new JSONObject(); ret.put("memory", memory); final int mb = 1024 * 1024; final Runtime runtime = Runtime.getRuntime(); memory.put("total", runtime.totalMemory() / mb); memory.put("free", runtime.freeMemory() / mb); memory.put("used", (runtime.totalMemory() - runtime.freeMemory()) / mb); memory.put("max", runtime.maxMemory() / mb); LOGGER.info(ret.toString(4));
729
458
1,187
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/CharacterQueryService.java
CharacterQueryService
getWrittenCharacterCount
class CharacterQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(CharacterQueryService.class); /** * Character repository. */ @Inject private CharacterRepository characterRepository; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Gets total character count. * * @return total character count */ public int getTotalCharacterCount() { return langPropsService.get("characters").length(); } /** * Gets all written character count. * * @return all written character count */ public int getWrittenCharacterCount() {<FILL_FUNCTION_BODY>} /** * Gets all written characters. * * <p> * <b>Note</b>: Just for testing. * </p> * * @return all written characters */ public Set<JSONObject> getWrittenCharacters() { try { return new HashSet<>(characterRepository.getList(new Query())); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets characters failed", e); return Collections.emptySet(); } } /** * Gets written character count of a user specified by the given user id. * * @param userId the given user id * @return user written character count */ public int getWrittenCharacterCount(final String userId) { final Query query = new Query().setFilter(new PropertyFilter( org.b3log.symphony.model.Character.CHARACTER_USER_ID, FilterOperator.EQUAL, userId)); try { return (int) characterRepository.count(query); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Counts user written characters failed", e); return 0; } } /** * Gets an unwritten character. * * @param userId the specified user id * @return character */ public String getUnwrittenCharacter(final String userId) { final String ret = getUnwrittenCharacterRandom(userId); if (StringUtils.isNotBlank(ret)) { return ret; } return getUnwrittenCharacterOneByOne(userId); } /** * Gets an unwritten character (strategy: One By One). * * @param userId the specified user id * @return character */ private String getUnwrittenCharacterOneByOne(final String userId) { final String characters = langPropsService.get("characters"); int index = 0; while (true) { if (index > characters.length()) { return null; // All done } final String ret = StringUtils.trim(characters.substring(index, index + 1)); index++; final Query query = new Query(); query.setFilter(CompositeFilterOperator.and( new PropertyFilter(org.b3log.symphony.model.Character.CHARACTER_USER_ID, FilterOperator.EQUAL, userId), new PropertyFilter(org.b3log.symphony.model.Character.CHARACTER_CONTENT, FilterOperator.EQUAL, ret) )); try { if (characterRepository.count(query) > 0) { continue; } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an unwritten character for user [id=" + userId + "] failed", e); } } } /** * Gets an unwritten character (strategy: Random). * * @param userId the specified user id * @return character */ private String getUnwrittenCharacterRandom(final String userId) { final String characters = langPropsService.get("characters"); final int maxRetries = 7; int retries = 0; while (retries < maxRetries) { retries++; final int index = RandomUtils.nextInt(0, characters.length()); final String ret = StringUtils.trim(characters.substring(index, index + 1)); final Query query = new Query(); query.setFilter(CompositeFilterOperator.and( new PropertyFilter(org.b3log.symphony.model.Character.CHARACTER_USER_ID, FilterOperator.EQUAL, userId), new PropertyFilter(org.b3log.symphony.model.Character.CHARACTER_CONTENT, FilterOperator.EQUAL, ret) )); try { if (characterRepository.count(query) > 0) { continue; } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an unwritten character failed", e); } } return null; } /** * Gets an unwritten character. * * @return character */ public String getUnwrittenCharacter() { final String ret = getUnwrittenCharacterRandom(); if (StringUtils.isNotBlank(ret)) { return ret; } return getUnwrittenCharacterOneByOne(); } /** * Gets an unwritten character (strategy: Random). * * @return character */ private String getUnwrittenCharacterRandom() { final String characters = langPropsService.get("characters"); final int maxRetries = 7; int retries = 0; while (retries < maxRetries) { retries++; final int index = RandomUtils.nextInt(0, characters.length()); final String ret = StringUtils.trim(characters.substring(index, index + 1)); final Query query = new Query().setFilter( new PropertyFilter(org.b3log.symphony.model.Character.CHARACTER_CONTENT, FilterOperator.EQUAL, ret)); try { if (characterRepository.count(query) > 0) { continue; } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an unwritten character failed", e); } } return null; } /** * Gets an unwritten character (strategy: One By One). * * @return character */ private String getUnwrittenCharacterOneByOne() { final String characters = langPropsService.get("characters"); int index = 0; while (true) { if (index > characters.length()) { return null; // All done } final String ret = StringUtils.trim(characters.substring(index, index + 1)); index++; final Query query = new Query().setFilter( new PropertyFilter(org.b3log.symphony.model.Character.CHARACTER_CONTENT, FilterOperator.EQUAL, ret)); try { if (characterRepository.count(query) > 0) { continue; } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an unwritten character failed", e); } } } }
try { final List<JSONObject> result = characterRepository.select("select count(DISTINCT characterContent) from " + characterRepository.getName()); if (null == result || result.isEmpty()) { return 0; } return result.get(0).optInt("count(DISTINCT characterContent)"); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Counts characters failed", e); return 0; }
1,887
127
2,014
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/CronMgmtService.java
CronMgmtService
start
class CronMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(CronMgmtService.class); /** * Article management service. */ @Inject private ArticleMgmtService articleMgmtService; /** * Verifycode management service. */ @Inject private VerifycodeMgmtService verifycodeMgmtService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Notification management service. */ @Inject private NotificationMgmtService notificationMgmtService; /** * Notification query service. */ @Inject private NotificationQueryService notificationQueryService; /** * Comment management service. */ @Inject private CommentMgmtService commentMgmtService; /** * Invitecode management service. */ @Inject private InvitecodeMgmtService invitecodeMgmtService; /** * Mail management service. */ @Inject private MailMgmtService mailMgmtService; /** * User management service. */ @Inject private UserMgmtService userMgmtService; /** * Cache management service. */ @Inject private CacheMgmtService cacheMgmtService; /** * Start all cron tasks. */ public void start() {<FILL_FUNCTION_BODY>} /** * Stop all cron tasks. */ public void stop() { Symphonys.SCHEDULED_EXECUTOR_SERVICE.shutdown(); } }
long delay = 10000; Symphonys.SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(() -> { try { articleMgmtService.expireStick(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Executes cron failed", e); } finally { Stopwatchs.release(); } }, delay, 60 * 1000, TimeUnit.MILLISECONDS); delay += 2000; Symphonys.SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(() -> { try { verifycodeMgmtService.sendEmailVerifycode(); verifycodeMgmtService.removeExpiredVerifycodes(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Executes cron failed", e); } finally { Stopwatchs.release(); } }, delay, 5 * 1000, TimeUnit.MILLISECONDS); delay += 2000; Symphonys.SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(() -> { try { cacheMgmtService.refreshCache(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Executes cron failed", e); } finally { Stopwatchs.release(); } }, delay, 30 * 60 * 1000, TimeUnit.MILLISECONDS); delay += 2000; Symphonys.SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(() -> { try { invitecodeMgmtService.expireInvitecodes(); mailMgmtService.sendWeeklyNewsletter(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Executes cron failed", e); } finally { Stopwatchs.release(); } }, delay, 5 * 60 * 1000, TimeUnit.MILLISECONDS); delay += 2000; Symphonys.SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(() -> { try { userMgmtService.resetUnverifiedUsers(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Executes cron failed", e); } finally { Stopwatchs.release(); } }, delay, 2 * 60 * 60 * 1000, TimeUnit.MILLISECONDS); delay += 2000;
468
691
1,159
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/DomainMgmtService.java
DomainMgmtService
addDomainTag
class DomainMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(DomainMgmtService.class); /** * Domain repository. */ @Inject private DomainRepository domainRepository; /** * Domain tag repository. */ @Inject private DomainTagRepository domainTagRepository; /** * Option repository. */ @Inject private OptionRepository optionRepository; /** * Domain cache. */ @Inject private DomainCache domainCache; /** * Removes a domain-tag relation. * * @param domainId the specified domain id * @param tagId the specified tag id */ @Transactional public void removeDomainTag(final String domainId, final String tagId) { try { final JSONObject domain = domainRepository.get(domainId); domain.put(Domain.DOMAIN_TAG_COUNT, domain.optInt(Domain.DOMAIN_TAG_COUNT) - 1); domainRepository.update(domainId, domain); final Query query = new Query().setFilter( CompositeFilterOperator.and( new PropertyFilter(Domain.DOMAIN + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, domainId), new PropertyFilter(Tag.TAG + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, tagId))); final List<JSONObject> relations = domainTagRepository.getList(query); if (relations.size() < 1) { return; } final JSONObject relation = relations.get(0); domainTagRepository.remove(relation.optString(Keys.OBJECT_ID)); // Refresh cache domainCache.loadDomains(); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Adds a domain-tag relation failed", e); } } /** * Adds a domain-tag relation. * * @param domainTag the specified domain-tag relation */ @Transactional public void addDomainTag(final JSONObject domainTag) {<FILL_FUNCTION_BODY>} /** * Adds a domain relation. * * @param domain the specified domain relation * @return domain id * @throws ServiceException service exception */ @Transactional public String addDomain(final JSONObject domain) throws ServiceException { try { final JSONObject record = new JSONObject(); record.put(Domain.DOMAIN_CSS, domain.optString(Domain.DOMAIN_CSS)); record.put(Domain.DOMAIN_DESCRIPTION, domain.optString(Domain.DOMAIN_DESCRIPTION)); record.put(Domain.DOMAIN_ICON_PATH, domain.optString(Domain.DOMAIN_ICON_PATH)); record.put(Domain.DOMAIN_SEO_DESC, domain.optString(Domain.DOMAIN_SEO_DESC)); record.put(Domain.DOMAIN_SEO_KEYWORDS, domain.optString(Domain.DOMAIN_SEO_KEYWORDS)); record.put(Domain.DOMAIN_SEO_TITLE, domain.optString(Domain.DOMAIN_SEO_TITLE)); record.put(Domain.DOMAIN_STATUS, domain.optInt(Domain.DOMAIN_STATUS)); record.put(Domain.DOMAIN_TITLE, domain.optString(Domain.DOMAIN_TITLE)); record.put(Domain.DOMAIN_URI, domain.optString(Domain.DOMAIN_URI)); record.put(Domain.DOMAIN_TAG_COUNT, 0); record.put(Domain.DOMAIN_TYPE, ""); record.put(Domain.DOMAIN_SORT, 10); record.put(Domain.DOMAIN_NAV, Domain.DOMAIN_NAV_C_ENABLED); final JSONObject domainCntOption = optionRepository.get(Option.ID_C_STATISTIC_DOMAIN_COUNT); final int domainCnt = domainCntOption.optInt(Option.OPTION_VALUE); domainCntOption.put(Option.OPTION_VALUE, domainCnt + 1); optionRepository.update(Option.ID_C_STATISTIC_DOMAIN_COUNT, domainCntOption); final String ret = domainRepository.add(record); // Refresh cache domainCache.loadDomains(); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Adds a domain failed", e); throw new ServiceException(e); } } /** * Updates the specified domain by the given domain id. * * @param domainId the given domain id * @param domain the specified domain */ @Transactional public void updateDomain(final String domainId, final JSONObject domain) { try { domainRepository.update(domainId, domain); // Refresh cache domainCache.loadDomains(); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Updates a domain [id=" + domainId + "] failed", e); } } /** * Removes the specified domain by the given domain id. * * @param domainId the given domain id */ @Transactional public void removeDomain(final String domainId) { try { domainTagRepository.removeByDomainId(domainId); domainRepository.remove(domainId); final JSONObject domainCntOption = optionRepository.get(Option.ID_C_STATISTIC_DOMAIN_COUNT); final int domainCnt = domainCntOption.optInt(Option.OPTION_VALUE); domainCntOption.put(Option.OPTION_VALUE, domainCnt - 1); optionRepository.update(Option.ID_C_STATISTIC_DOMAIN_COUNT, domainCntOption); // Refresh cache domainCache.loadDomains(); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Updates a domain [id=" + domainId + "] failed", e); } } }
try { final String domainId = domainTag.optString(Domain.DOMAIN + "_" + Keys.OBJECT_ID); final JSONObject domain = domainRepository.get(domainId); domain.put(Domain.DOMAIN_TAG_COUNT, domain.optInt(Domain.DOMAIN_TAG_COUNT) + 1); domainRepository.update(domainId, domain); domainTagRepository.add(domainTag); // Refresh cache domainCache.loadDomains(); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Adds a domain-tag relation failed", e); }
1,587
161
1,748
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/EmotionMgmtService.java
EmotionMgmtService
setEmotionList
class EmotionMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(EmotionMgmtService.class); /** * Emotion repository. */ @Inject private EmotionRepository emotionRepository; /** * Sets a user's emotions. * * @param userId the specified user id * @param emotionList the specified emotions * @throws ServiceException service exception */ public void setEmotionList(final String userId, final String emotionList) throws ServiceException {<FILL_FUNCTION_BODY>} }
final Transaction transaction = emotionRepository.beginTransaction(); try { // clears the user all emotions emotionRepository.removeByUserId(userId); final Set<String> emotionSet = new HashSet<>(); // for deduplication final String[] emotionArray = emotionList.split(","); for (int i = 0, sort = 0; i < emotionArray.length; i++) { final String content = emotionArray[i]; if (StringUtils.isBlank(content) || emotionSet.contains(content) || !Emotions.isEmoji(content)) { continue; } final JSONObject userEmotion = new JSONObject(); userEmotion.put(Emotion.EMOTION_USER_ID, userId); userEmotion.put(Emotion.EMOTION_CONTENT, content); userEmotion.put(Emotion.EMOTION_SORT, sort++); userEmotion.put(Emotion.EMOTION_TYPE, Emotion.EMOTION_TYPE_C_EMOJI); emotionRepository.add(userEmotion); emotionSet.add(content); } transaction.commit(); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Set user emotion list failed [id=" + userId + "]", e); if (null != transaction && transaction.isActive()) { transaction.rollback(); } throw new ServiceException(e); }
163
378
541
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/EmotionQueryService.java
EmotionQueryService
getEmojis
class EmotionQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(EmotionQueryService.class); /** * Common used emoji string. */ private static final String COMMON_USED = "smile,flushed,joy,sob,yum,trollface,tada,heart,+1,ok_hand,pray"; /** * Emotion repository. */ @Inject private EmotionRepository emotionRepository; /** * Gets a user's emotion (emoji with type=0). * * @param userId the specified user id * @return emoji string join with {@code ","}, returns a common used emoji string if not found */ public String getEmojis(final String userId) {<FILL_FUNCTION_BODY>} }
try { final String ret = emotionRepository.getUserEmojis(userId); if (StringUtils.isBlank(ret)) { return COMMON_USED; } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, e.getMessage()); return COMMON_USED; }
230
98
328
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/InvitecodeMgmtService.java
InvitecodeMgmtService
adminGenInvitecodes
class InvitecodeMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(InvitecodeMgmtService.class); /** * Invitecode repository. */ @Inject private InvitecodeRepository invitecodeRepository; /** * Expires invitecodes. */ @Transactional public void expireInvitecodes() { final long now = System.currentTimeMillis(); final long expired = now - Symphonys.INVITECODE_EXPIRED; final Query query = new Query().setPage(1, Integer.MAX_VALUE). setFilter(CompositeFilterOperator.and( new PropertyFilter(Invitecode.STATUS, FilterOperator.EQUAL, Invitecode.STATUS_C_UNUSED), new PropertyFilter(Invitecode.GENERATOR_ID, FilterOperator.NOT_EQUAL, Pointtransfer.ID_C_SYS), new PropertyFilter(Keys.OBJECT_ID, FilterOperator.LESS_THAN_OR_EQUAL, expired) )); JSONObject result; try { result = invitecodeRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets invitecodes failed", e); return; } final List<JSONObject> data = (List<JSONObject>) result.opt(Keys.RESULTS); try { for (final JSONObject invitecode : data) { final String invitecodeId = invitecode.optString(Keys.OBJECT_ID); invitecodeRepository.remove(invitecodeId); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Expires invitecodes failed", e); } } /** * User generates an invitecode. * * @param userId the specified user id * @param userName the specified user name * @return invitecode */ public String userGenInvitecode(final String userId, final String userName) { final Transaction transaction = invitecodeRepository.beginTransaction(); try { final String ret = RandomStringUtils.randomAlphanumeric(16); final JSONObject invitecode = new JSONObject(); invitecode.put(Invitecode.CODE, ret); invitecode.put(Invitecode.MEMO, "User [" + userName + "," + userId + "] generated"); invitecode.put(Invitecode.STATUS, Invitecode.STATUS_C_UNUSED); invitecode.put(Invitecode.GENERATOR_ID, userId); invitecode.put(Invitecode.USER_ID, ""); invitecode.put(Invitecode.USE_TIME, 0); invitecodeRepository.add(invitecode); transaction.commit(); return ret; } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Generates invitecode failed", e); return null; } } /** * Admin generates invitecodes with the specified quantity and memo. * * @param quantity the specified quantity * @param memo the specified memo */ public void adminGenInvitecodes(final int quantity, final String memo) {<FILL_FUNCTION_BODY>} /** * Updates the specified invitecode by the given invitecode id. * * @param invitecodeId the given invitecode id * @param invitecode the specified invitecode * @throws ServiceException service exception */ public void updateInvitecode(final String invitecodeId, final JSONObject invitecode) throws ServiceException { final Transaction transaction = invitecodeRepository.beginTransaction(); try { invitecodeRepository.update(invitecodeId, invitecode); transaction.commit(); } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Updates an invitecode[id=" + invitecodeId + "] failed", e); throw new ServiceException(e); } } }
final Transaction transaction = invitecodeRepository.beginTransaction(); try { for (int i = 0; i < quantity; i++) { final JSONObject invitecode = new JSONObject(); invitecode.put(Invitecode.CODE, RandomStringUtils.randomAlphanumeric(16)); invitecode.put(Invitecode.MEMO, memo); invitecode.put(Invitecode.STATUS, Invitecode.STATUS_C_UNUSED); invitecode.put(Invitecode.GENERATOR_ID, Pointtransfer.ID_C_SYS); invitecode.put(Invitecode.USER_ID, ""); invitecode.put(Invitecode.USE_TIME, 0); invitecodeRepository.add(invitecode); } transaction.commit(); } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Generates invitecodes failed", e); }
1,093
262
1,355
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/InvitecodeQueryService.java
InvitecodeQueryService
getInvitecodes
class InvitecodeQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(InvitecodeQueryService.class); /** * Invitecode repository. */ @Inject private InvitecodeRepository invitecodeRepository; /** * Gets valid invitecodes by the specified generator id. * * @param generatorId the specified generator id * @return for example, <pre> * { * "oId": "", * "code": "", * "memo": "", * .... * } * </pre>, returns an empty list if not found */ public List<JSONObject> getValidInvitecodes(final String generatorId) { final Query query = new Query().setFilter( CompositeFilterOperator.and( new PropertyFilter(Invitecode.GENERATOR_ID, FilterOperator.EQUAL, generatorId), new PropertyFilter(Invitecode.STATUS, FilterOperator.EQUAL, Invitecode.STATUS_C_UNUSED))); try { return invitecodeRepository.getList(query); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets valid invitecode failed", e); return Collections.emptyList(); } } /** * Gets an invitecode with the specified code. * * @param code the specified code * @return invitecode, returns {@code null} if not found */ public JSONObject getInvitecode(final String code) { final Query query = new Query().setFilter(new PropertyFilter(Invitecode.CODE, FilterOperator.EQUAL, code)); try { return invitecodeRepository.getFirst(query); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets invitecode failed", e); return null; } } /** * Gets invitecodes by the specified request json object. * * @param requestJSONObject the specified request json object, for example, * { * "paginationCurrentPageNum": 1, * "paginationPageSize": 20, * "paginationWindowSize": 10 * } * @return for example, <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "invitecodes": [{ * "oId": "", * "code": "", * "memo": "", * .... * }, ....] * } * </pre> * @see Pagination */ public JSONObject getInvitecodes(final JSONObject requestJSONObject) {<FILL_FUNCTION_BODY>} /** * Gets an invitecode by the specified invitecode id. * * @param invitecodeId the specified invitecode id * @return for example, <pre> * { * "oId": "", * "code": "", * "memo": "", * .... * } * </pre>, returns {@code null} if not found */ public JSONObject getInvitecodeById(final String invitecodeId) { try { return invitecodeRepository.get(invitecodeId); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an invitecode failed", e); return null; } } /** * Gets an invitecode by the specified user id. * * @param userId the specified user id * @return for example, <pre> * { * "oId": "", * "code": "", * "memo": "", * .... * } * </pre>, returns {@code null} if not found * @throws ServiceException service exception */ public JSONObject getInvitecodeByUserId(final String userId) throws ServiceException { final Query query = new Query().setFilter(new PropertyFilter(Invitecode.USER_ID, FilterOperator.EQUAL, userId)); try { return invitecodeRepository.getFirst(query); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets an invitecode failed", e); throw new ServiceException(e); } } }
final JSONObject ret = new JSONObject(); final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM); final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE); final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE); final Query query = new Query().setPage(currentPageNum, pageSize). addSort(Invitecode.STATUS, SortDirection.DESCENDING). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); JSONObject result; try { result = invitecodeRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets invitecodes failed", e); return null; } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); ret.put(Invitecode.INVITECODES, result.opt(Keys.RESULTS)); return ret;
1,162
410
1,572
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/LinkMgmtService.java
LinkMgmtService
addLink
class LinkMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(LinkMgmtService.class); /** * Link repository. */ @Inject private LinkRepository linkRepository; /** * Adds a link with the specified URL. * * @param url the specified URL */ public void addLink(final String url) { JSONObject link = linkRepository.getLink(url); final int clickCnt = null != link ? link.optInt(Link.LINK_CLICK_CNT) + 1 : 0; if (null != link) { link.put(Link.LINK_CLICK_CNT, clickCnt); final Transaction transaction = linkRepository.beginTransaction(); try { linkRepository.update(link.optString(Keys.OBJECT_ID), link); transaction.commit(); } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Updates link clicks [addr=" + url + "] failed", e); } } if (null != link && 1000 * 60 * 5 > System.currentTimeMillis() - link.optLong(Link.LINK_PING_TIME)) { return; } JSONObject lnk = Links.getLink(url); if (null == lnk) { lnk = new JSONObject(); lnk.put(Link.LINK_ADDR, url); lnk.put(Link.LINK_TITLE, ""); } link = new JSONObject(); final String addr = lnk.optString(Link.LINK_ADDR); link.put(Link.LINK_ADDR_HASH, DigestUtils.sha1Hex(addr)); link.put(Link.LINK_ADDR, addr); link.put(Link.LINK_BAD_CNT, 0); link.put(Link.LINK_BAIDU_REF_CNT, 0); link.put(Link.LINK_CLICK_CNT, clickCnt); link.put(Link.LINK_GOOD_CNT, 0); link.put(Link.LINK_SCORE, 0); link.put(Link.LINK_SUBMIT_CNT, 0); link.put(Link.LINK_TITLE, lnk.optString(Link.LINK_TITLE)); link.put(Link.LINK_PING_CNT, 0); link.put(Link.LINK_PING_ERR_CNT, 0); link.put(Link.LINK_PING_TIME, 0); link.put(Link.LINK_CARD_HTML, ""); addLink(link); } /** * Adds the specified link. * * @param link the specified link */ private void addLink(final JSONObject link) {<FILL_FUNCTION_BODY>} /** * Pings the specified link with the specified count down latch. * * @param link the specified link * @param countDownLatch the specified count down latch */ public void pingLink(final JSONObject link, CountDownLatch countDownLatch) { Symphonys.EXECUTOR_SERVICE.submit(new CheckTask(link, countDownLatch)); } /** * Link accessibility check task. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 2.0.0.0, Jan 1, 2018 * @since 2.2.0 */ private class CheckTask implements Runnable { /** * Link to check. */ private final JSONObject link; /** * Count down latch. */ private final CountDownLatch countDownLatch; /** * Constructs a check task with the specified link. * * @param link the specified link * @param countDownLatch the specified count down latch */ public CheckTask(final JSONObject link, final CountDownLatch countDownLatch) { this.link = link; this.countDownLatch = countDownLatch; } @Override public void run() { final String linkAddr = link.optString(Link.LINK_ADDR); final long start = System.currentTimeMillis(); int responseCode = 0; try { final int TIMEOUT = 5000; final HttpResponse response = HttpRequest.get(linkAddr).timeout(TIMEOUT).followRedirects(true).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT).send(); responseCode = response.statusCode(); } catch (final Exception e) { LOGGER.trace("Link [url=" + linkAddr + "] accessibility check failed [msg=" + e.getMessage() + "]"); } finally { countDownLatch.countDown(); final long elapsed = System.currentTimeMillis() - start; LOGGER.log(Level.TRACE, "Accesses link [url=" + linkAddr + "] response [code=" + responseCode + "], " + "elapsed [" + elapsed + "]"); link.put(Link.LINK_PING_CNT, link.optInt(Link.LINK_PING_CNT) + 1); if (200 != responseCode) { link.put(Link.LINK_PING_ERR_CNT, link.optInt(Link.LINK_PING_ERR_CNT) + 1); } link.put(Link.LINK_PING_TIME, System.currentTimeMillis()); final Transaction transaction = linkRepository.beginTransaction(); try { linkRepository.update(link.optString(Keys.OBJECT_ID), link); transaction.commit(); } catch (final RepositoryException e) { if (null != transaction && transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Updates link failed", e); } } } } private void singlePing(final JSONObject link) { try { final CountDownLatch countDownLatch = new CountDownLatch(1); pingLink(link, countDownLatch); countDownLatch.await(10, TimeUnit.SECONDS); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Pings link [addr=" + link.optString(Link.LINK_ADDR) + "] failed", e); } } }
final String linkAddr = link.optString(Link.LINK_ADDR); final JSONObject old = linkRepository.getLink(linkAddr); if (null != old) { old.put(Link.LINK_CLICK_CNT, link.optInt(Link.LINK_CLICK_CNT)); singlePing(old); return; } final Transaction transaction = linkRepository.beginTransaction(); try { linkRepository.add(link); transaction.commit(); } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Adds link [addr=" + linkAddr + "] failed", e); } singlePing(link);
1,775
202
1,977
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/LinkQueryService.java
LinkQueryService
getTopLink
class LinkQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(LinkQueryService.class); /** * Link repository. */ @Inject private LinkRepository linkRepository; /** * Tag cache. */ @Inject private TagCache tagCache; /** * Get top links with the specified size. * * @param size the specified size * @return links, returns an empty list if not found */ public List<JSONObject> getTopLink(final int size) {<FILL_FUNCTION_BODY>} }
final List<JSONObject> ret = new ArrayList<>(); try { final List<JSONObject> links = linkRepository.select("SELECT\n" + "\t*\n" + "FROM\n" + "\t`symphony_link`\n" + "WHERE\n" + "\tlinkPingErrCnt / linkPingCnt < 0.1\n" + "AND linkTitle != \"\"\n" + "AND linkAddr NOT LIKE \"%baidu.com%\" \n" + "AND linkAddr NOT LIKE \"%weiyun.com%\"\n" + "ORDER BY\n" + "\tlinkClickCnt DESC\n" + "LIMIT ?", size); ret.addAll(links); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Get top links failed", e); } return ret;
168
239
407
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/LivenessMgmtService.java
LivenessMgmtService
incLiveness
class LivenessMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(LivenessMgmtService.class); /** * Liveness repository. */ @Inject private LivenessRepository livenessRepository; /** * Increments a field of the specified liveness. * * @param userId the specified user id * @param field the specified field */ @Transactional public void incLiveness(final String userId, final String field) {<FILL_FUNCTION_BODY>} }
Stopwatchs.start("Inc liveness"); final String date = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd"); try { JSONObject liveness = livenessRepository.getByUserAndDate(userId, date); if (null == liveness) { liveness = new JSONObject(); liveness.put(Liveness.LIVENESS_USER_ID, userId); liveness.put(Liveness.LIVENESS_DATE, date); liveness.put(Liveness.LIVENESS_POINT, 0); liveness.put(Liveness.LIVENESS_ACTIVITY, 0); liveness.put(Liveness.LIVENESS_ARTICLE, 0); liveness.put(Liveness.LIVENESS_COMMENT, 0); liveness.put(Liveness.LIVENESS_PV, 0); liveness.put(Liveness.LIVENESS_REWARD, 0); liveness.put(Liveness.LIVENESS_THANK, 0); liveness.put(Liveness.LIVENESS_VOTE, 0); liveness.put(Liveness.LIVENESS_VOTE, 0); liveness.put(Liveness.LIVENESS_ACCEPT_ANSWER, 0); livenessRepository.add(liveness); } liveness.put(field, liveness.optInt(field) + 1); livenessRepository.update(liveness.optString(Keys.OBJECT_ID), liveness); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Updates a liveness [" + date + "] field [" + field + "] failed", e); } finally { Stopwatchs.end(); }
157
484
641
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/LivenessQueryService.java
LivenessQueryService
getCurrentLivenessPoint
class LivenessQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(LivenessQueryService.class); /** * Liveness repository. */ @Inject private LivenessRepository livenessRepository; /** * Gets point of current liveness. * * @param userId the specified user id * @return point */ public int getCurrentLivenessPoint(final String userId) {<FILL_FUNCTION_BODY>} /** * Gets the yesterday's liveness. * * @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; } } }
Stopwatchs.start("Gets liveness"); try { final String date = DateFormatUtils.format(new Date(), "yyyyMMdd"); try { final JSONObject liveness = livenessRepository.getByUserAndDate(userId, date); if (null == liveness) { return 0; } return Liveness.calcPoint(liveness); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets current liveness point failed", e); return 0; } } finally { Stopwatchs.end(); }
317
162
479
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/MailMgmtService.java
MailMgmtService
sendWeeklyNewsletter
class MailMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(MailMgmtService.class); /** * User repository. */ @Inject private UserRepository userRepository; /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * Option repository. */ @Inject private OptionRepository optionRepository; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * Avatar query service. */ @Inject private AvatarQueryService avatarQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Weekly newsletter sending status. */ private boolean weeklyNewsletterSending; /** * Send weekly newsletter. */ public void sendWeeklyNewsletter() {<FILL_FUNCTION_BODY>} }
final Calendar calendar = Calendar.getInstance(); final int hour = calendar.get(Calendar.HOUR_OF_DAY); final int minute = calendar.get(Calendar.MINUTE); if (13 != hour || 55 > minute) { return; } if (weeklyNewsletterSending) { return; } weeklyNewsletterSending = true; LOGGER.info("Sending weekly newsletter...."); final long now = System.currentTimeMillis(); final long sevenDaysAgo = now - 1000 * 60 * 60 * 24 * 7; try { final int memberCount = optionRepository.get(Option.ID_C_STATISTIC_MEMBER_COUNT).optInt(Option.OPTION_VALUE); final int userSize = memberCount / 7; // select receivers final Query toUserQuery = new Query(); toUserQuery.setPage(1, userSize).setPageCount(1). setFilter(CompositeFilterOperator.and( new PropertyFilter(UserExt.USER_SUB_MAIL_SEND_TIME, FilterOperator.LESS_THAN_OR_EQUAL, sevenDaysAgo), new PropertyFilter(UserExt.USER_LATEST_LOGIN_TIME, FilterOperator.LESS_THAN_OR_EQUAL, sevenDaysAgo), new PropertyFilter(UserExt.USER_SUB_MAIL_STATUS, FilterOperator.EQUAL, UserExt.USER_SUB_MAIL_STATUS_ENABLED), new PropertyFilter(UserExt.USER_STATUS, FilterOperator.EQUAL, UserExt.USER_STATUS_C_VALID), new PropertyFilter(User.USER_EMAIL, FilterOperator.NOT_LIKE, "%" + UserExt.USER_BUILTIN_EMAIL_SUFFIX))). addSort(Keys.OBJECT_ID, SortDirection.ASCENDING); final List<JSONObject> receivers = userRepository.getList(toUserQuery); if (receivers.isEmpty()) { LOGGER.info("No user need send newsletter"); return; } final Set<String> toMails = new HashSet<>(); final Transaction transaction = userRepository.beginTransaction(); for (final JSONObject user : receivers) { final String email = user.optString(User.USER_EMAIL); if (Strings.isEmail(email)) { toMails.add(email); user.put(UserExt.USER_SUB_MAIL_SEND_TIME, now); userRepository.update(user.optString(Keys.OBJECT_ID), user, UserExt.USER_SUB_MAIL_SEND_TIME); } } transaction.commit(); // send to admins by default final List<JSONObject> admins = userRepository.getAdmins(); for (final JSONObject admin : admins) { toMails.add(admin.optString(User.USER_EMAIL)); } final Map<String, Object> dataModel = new HashMap<>(); // select nice articles final Query articleQuery = new Query(); articleQuery.setPage(1, Symphonys.MAIL_BATCH_ARTICLE_SIZE).setPageCount(1). setFilter(CompositeFilterOperator.and( new PropertyFilter(Article.ARTICLE_CREATE_TIME, FilterOperator.GREATER_THAN_OR_EQUAL, sevenDaysAgo), new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.EQUAL, Article.ARTICLE_TYPE_C_NORMAL), new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.NOT_EQUAL, Article.ARTICLE_STATUS_C_INVALID), new PropertyFilter(Article.ARTICLE_TAGS, FilterOperator.NOT_LIKE, Tag.TAG_TITLE_C_SANDBOX + "%"))). addSort(Article.ARTICLE_PUSH_ORDER, SortDirection.DESCENDING). addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING). addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING); final List<JSONObject> articles = articleRepository.getList(articleQuery); if (articles.isEmpty()) { LOGGER.info("No article as newsletter to send"); return; } articleQueryService.organizeArticles(articles); String mailSubject = ""; int goodCnt = 0; for (final JSONObject article : articles) { article.put(Article.ARTICLE_CONTENT, articleQueryService.getArticleMetaDesc(article)); final int gc = article.optInt(Article.ARTICLE_GOOD_CNT); if (gc >= goodCnt) { mailSubject = article.optString(Article.ARTICLE_TITLE); goodCnt = gc; } } dataModel.put(Article.ARTICLES, articles); // select nice users final List<JSONObject> users = userQueryService.getNiceUsers(6); dataModel.put(User.USERS, users); final String fromName = langPropsService.get("symphonyEnLabel") + " " + langPropsService.get("weeklyEmailFromNameLabel", Latkes.getLocale()); Mails.batchSendHTML(fromName, mailSubject, new ArrayList<>(toMails), Mails.TEMPLATE_NAME_WEEKLY, dataModel); LOGGER.info("Sent weekly newsletter [" + toMails.size() + "]"); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends weekly newsletter failed", e); } finally { weeklyNewsletterSending = false; }
306
1,486
1,792
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/OperationMgmtService.java
OperationMgmtService
addOperation
class OperationMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(OperationMgmtService.class); /** * Operation repository. */ @Inject private OperationRepository operationRepository; /** * Adds the specified operation. * * @param operation the specified operation */ @Transactional public void addOperation(final JSONObject operation) {<FILL_FUNCTION_BODY>} }
try { operationRepository.add(operation); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Adds an operation failed", e); }
131
49
180
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/OperationQueryService.java
OperationQueryService
getAuditlogs
class OperationQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(OperationQueryService.class); /** * Operation repository. */ @Inject private OperationRepository operationRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Get audit logs by the specified request json object. * * @param requestJSONObject the specified request json object, for example, * { * "paginationCurrentPageNum": 1, * "paginationPageSize": 20, * "paginationWindowSize": 10 * }, see {@link Pagination} for more details * @return for example, <pre> * { * "pagination": { * "paginationPageCount": 100, * "paginationPageNums": [1, 2, 3, 4, 5] * }, * "operations": [{ * "oId": "", * "operationUserName": "", * "operationContent": "", * "operationTime": "", * "operationIP": "", * "operationUA": "" * }, ....] * } * </pre> * @see Pagination */ public JSONObject getAuditlogs(final JSONObject requestJSONObject) {<FILL_FUNCTION_BODY>} }
final JSONObject ret = new JSONObject(); final int currentPageNum = requestJSONObject.optInt(Pagination.PAGINATION_CURRENT_PAGE_NUM); final int pageSize = requestJSONObject.optInt(Pagination.PAGINATION_PAGE_SIZE); final int windowSize = requestJSONObject.optInt(Pagination.PAGINATION_WINDOW_SIZE); final Query query = new Query().setPage(currentPageNum, pageSize).addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); JSONObject result; try { result = operationRepository.get(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Get operations failed", e); return null; } final int pageCount = result.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_PAGE_COUNT); final JSONObject pagination = new JSONObject(); ret.put(Pagination.PAGINATION, pagination); final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize); pagination.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); pagination.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); final List<JSONObject> records = (List<JSONObject>) result.opt((Keys.RESULTS)); final List<JSONObject> auditlogs = new ArrayList<>(); for (final JSONObject record : records) { final JSONObject auditlog = new JSONObject(); auditlog.put(Keys.OBJECT_ID, record.optString(Keys.OBJECT_ID)); try { final String operationUserId = record.optString(Operation.OPERATION_USER_ID); final JSONObject operationUser = userRepository.get(operationUserId); auditlog.put(Operation.OPERATION_T_USER_NAME, UserExt.getUserLink(operationUser)); auditlog.put(Operation.OPERATION_T_TIME, DateFormatUtils.format(record.optLong(Keys.OBJECT_ID), "yyyy-MM-dd HH:mm:ss")); auditlog.put(Operation.OPERATION_IP, record.optString(Operation.OPERATION_IP)); auditlog.put(Operation.OPERATION_UA, record.optString(Operation.OPERATION_UA)); final int operationCode = record.optInt(Operation.OPERATION_CODE); final String operationContent = langPropsService.get("auditlog" + operationCode + "Label"); auditlog.put(Operation.OPERATION_T_CONTENT, operationContent); auditlogs.add(auditlog); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Builds audit log failed", e); } } ret.put(Operation.OPERATIONS, (Object) auditlogs); return ret;
417
762
1,179
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/OptionMgmtService.java
OptionMgmtService
updateOption
class OptionMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(OptionMgmtService.class); /** * Option repository. */ @Inject private OptionRepository optionRepository; /** * Removes an option. * * @param id the specified option id */ public void removeOption(final String id) { final Transaction transaction = optionRepository.beginTransaction(); try { optionRepository.remove(id); transaction.commit(); } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Removes an option failed", e); } } /** * Adds the specified option. * * @param option the specified option */ public void addOption(final JSONObject option) { final Transaction transaction = optionRepository.beginTransaction(); try { optionRepository.add(option); transaction.commit(); } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Adds an option failed", e); } } /** * Updates the specified option by the given option id. * * @param optionId the given option id * @param option the specified option */ public void updateOption(final String optionId, final JSONObject option) {<FILL_FUNCTION_BODY>} }
final Transaction transaction = optionRepository.beginTransaction(); try { optionRepository.update(optionId, option); transaction.commit(); } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Updates an option[id=" + optionId + "] failed", e); }
415
106
521
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/OptionQueryService.java
OptionQueryService
getMisc
class OptionQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(OptionQueryService.class); /** * Option repository. */ @Inject private OptionRepository optionRepository; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Gets the online member count. * * @return online member count */ public int getOnlineMemberCount() { int ret = 0; for (final Set<WebSocketSession> value : UserChannel.SESSIONS.values()) { ret += value.size(); } return ret; } /** * Gets the online visitor count. * * @return online visitor count */ public int getOnlineVisitorCount() { final int ret = ArticleChannel.SESSIONS.size() + ArticleListChannel.SESSIONS.size() + ChatroomChannel.SESSIONS.size() + getOnlineMemberCount(); try { final JSONObject maxOnlineMemberCntRecord = optionRepository.get(Option.ID_C_STATISTIC_MAX_ONLINE_VISITOR_COUNT); final int maxOnlineVisitorCnt = maxOnlineMemberCntRecord.optInt(Option.OPTION_VALUE); if (maxOnlineVisitorCnt < ret) { // Updates the max online visitor count final Transaction transaction = optionRepository.beginTransaction(); try { maxOnlineMemberCntRecord.put(Option.OPTION_VALUE, String.valueOf(ret)); optionRepository.update(maxOnlineMemberCntRecord.optString(Keys.OBJECT_ID), maxOnlineMemberCntRecord); transaction.commit(); } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Updates the max online visitor count failed", e); } } } catch (final RepositoryException ex) { LOGGER.log(Level.ERROR, "Gets online visitor count failed", ex); } return ret; } /** * Gets the statistic. * * @return statistic */ public JSONObject getStatistic() { final JSONObject ret = new JSONObject(); final Query query = new Query(). setFilter(new PropertyFilter(Option.OPTION_CATEGORY, FilterOperator.EQUAL, Option.CATEGORY_C_STATISTIC)). setPageCount(1); try { final List<JSONObject> options = optionRepository.getList(query); for (final JSONObject option : options) { ret.put(option.optString(Keys.OBJECT_ID), option.optInt(Option.OPTION_VALUE)); } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets statistic failed", e); return null; } } /** * Checks whether the specified content contains reserved words. * * @param content the specified content * @return {@code true} if it contains reserved words, returns {@code false} otherwise */ public boolean containReservedWord(final String content) { if (StringUtils.isBlank(content)) { return false; } try { final List<JSONObject> reservedWords = getReservedWords(); for (final JSONObject reservedWord : reservedWords) { if (content.contains(reservedWord.optString(Option.OPTION_VALUE))) { return true; } } return false; } catch (final Exception e) { return true; } } /** * Gets the reserved words. * * @return reserved words */ public List<JSONObject> getReservedWords() { final Query query = new Query().setFilter(new PropertyFilter(Option.OPTION_CATEGORY, FilterOperator.EQUAL, Option.CATEGORY_C_RESERVED_WORDS)); try { return optionRepository.getList(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets reserved words failed", e); return Collections.emptyList(); } } /** * Checks whether the specified word is a reserved word. * * @param word the specified word * @return {@code true} if it is a reserved word, returns {@code false} otherwise */ public boolean isReservedWord(final String word) { final Query query = new Query(). setFilter(CompositeFilterOperator.and( new PropertyFilter(Option.OPTION_VALUE, FilterOperator.EQUAL, word), new PropertyFilter(Option.OPTION_CATEGORY, FilterOperator.EQUAL, Option.CATEGORY_C_RESERVED_WORDS) )); try { return optionRepository.count(query) > 0; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Checks reserved word failed", e); return true; } } /** * Gets allow register option value. * * @return allow register option value, return {@code null} if not found */ public String getAllowRegister() { try { final JSONObject result = optionRepository.get(Option.ID_C_MISC_ALLOW_REGISTER); return result.optString(Option.OPTION_VALUE); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets option [allow register] value failed", e); return null; } } /** * Gets the miscellaneous. * * @return misc */ public List<JSONObject> getMisc() {<FILL_FUNCTION_BODY>} /** * Gets an option by the specified id. * * @param optionId the specified id * @return option, return {@code null} if not found */ public JSONObject getOption(final String optionId) { try { final JSONObject ret = optionRepository.get(optionId); return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets an option [optionId=" + optionId + "] failed", e); return null; } } }
final Query query = new Query().setFilter(new PropertyFilter(Option.OPTION_CATEGORY, FilterOperator.EQUAL, Option.CATEGORY_C_MISC)); try { final List<JSONObject> ret = optionRepository.getList(query); for (final JSONObject option : ret) { option.put("label", langPropsService.get(option.optString(Keys.OBJECT_ID) + "Label")); } return ret; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Gets misc failed", e); return null; }
1,657
161
1,818
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/PointtransferMgmtService.java
PointtransferMgmtService
transfer
class PointtransferMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(PointtransferMgmtService.class); /** * Pointtransfer repository. */ @Inject private PointtransferRepository pointtransferRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Transfers point from the specified from id to the specified to id with type, sum, data id and time. * * @param fromId the specified from id, may be system "sys" * @param toId the specified to id, may be system "sys" * @param type the specified type * @param sum the specified sum * @param dataId the specified data id * @param time the specified time * @param memo the specified memo * @return transfer record id, returns {@code null} if transfer failed */ public synchronized String transfer(final String fromId, final String toId, final int type, final int sum, final String dataId, final long time, final String memo) {<FILL_FUNCTION_BODY>} }
if (StringUtils.equals(fromId, toId)) { LOGGER.log(Level.WARN, "The from id is equal to the to id [" + fromId + "]"); return null; } final Transaction transaction = pointtransferRepository.beginTransaction(); try { int fromBalance = 0; if (!Pointtransfer.ID_C_SYS.equals(fromId)) { final JSONObject fromUser = userRepository.get(fromId); fromBalance = fromUser.optInt(UserExt.USER_POINT) - sum; if (fromBalance < 0) { throw new Exception("Insufficient balance"); } fromUser.put(UserExt.USER_POINT, fromBalance); fromUser.put(UserExt.USER_USED_POINT, fromUser.optInt(UserExt.USER_USED_POINT) + sum); userRepository.update(fromId, fromUser, UserExt.USER_POINT, UserExt.USER_USED_POINT); } int toBalance = 0; if (!Pointtransfer.ID_C_SYS.equals(toId)) { final JSONObject toUser = userRepository.get(toId); toBalance = toUser.optInt(UserExt.USER_POINT) + sum; toUser.put(UserExt.USER_POINT, toBalance); userRepository.update(toId, toUser, UserExt.USER_POINT); } final JSONObject pointtransfer = new JSONObject(); pointtransfer.put(Pointtransfer.FROM_ID, fromId); pointtransfer.put(Pointtransfer.TO_ID, toId); pointtransfer.put(Pointtransfer.SUM, sum); pointtransfer.put(Pointtransfer.FROM_BALANCE, fromBalance); pointtransfer.put(Pointtransfer.TO_BALANCE, toBalance); pointtransfer.put(Pointtransfer.TIME, time); pointtransfer.put(Pointtransfer.TYPE, type); pointtransfer.put(Pointtransfer.DATA_ID, dataId); pointtransfer.put(Pointtransfer.MEMO, memo); final String ret = pointtransferRepository.add(pointtransfer); transaction.commit(); return ret; } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Transfer [fromId=" + fromId + ", toId=" + toId + ", sum=" + sum + ", type=" + type + ", dataId=" + dataId + ", memo=" + memo + "] failed", e); return null; }
308
702
1,010
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/PostExportService.java
PostExportService
exportPosts
class PostExportService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(PostExportService.class); /** * User repository. */ @Inject private UserRepository userRepository; /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * Comment repository. */ @Inject private CommentRepository commentRepository; /** * Pointtransfer management service. */ @Inject private PointtransferMgmtService pointtransferMgmtService; /** * Exports all posts of a user's specified with the given user id. * * @param userId the given user id * @return download URL, returns {@code "-1"} if in sufficient balance, returns {@code null} if other exceptions */ public String exportPosts(final String userId) {<FILL_FUNCTION_BODY>} }
final int pointDataExport = Symphonys.POINT_DATA_EXPORT; try { final JSONObject user = userRepository.get(userId); final int balance = user.optInt(UserExt.USER_POINT); if (balance - pointDataExport < 0) { return "-1"; } } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Checks user failed", e); return null; } final JSONArray posts = new JSONArray(); Query query = new Query().setFilter( new PropertyFilter(Article.ARTICLE_AUTHOR_ID, FilterOperator.EQUAL, userId)). select(Keys.OBJECT_ID, Article.ARTICLE_TITLE, Article.ARTICLE_TAGS, Article.ARTICLE_CONTENT, Article.ARTICLE_CREATE_TIME); try { final List<JSONObject> articles = articleRepository.getList(query); for (final JSONObject article : articles) { final JSONObject post = new JSONObject(); post.put("id", article.optString(Keys.OBJECT_ID)); final JSONObject content = new JSONObject(); content.put("title", article.optString(Article.ARTICLE_TITLE)); content.put("tags", article.optString(Article.ARTICLE_TAGS)); content.put("body", article.optString(Article.ARTICLE_CONTENT)); post.put("content", content.toString()); post.put("created", Article.ARTICLE_CREATE_TIME); post.put("type", "article"); posts.put(post); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Export articles failed", e); return null; } query = new Query().setFilter(new PropertyFilter(Comment.COMMENT_AUTHOR_ID, FilterOperator.EQUAL, userId)). select(Keys.OBJECT_ID, Comment.COMMENT_CONTENT, Comment.COMMENT_CREATE_TIME); try { final List<JSONObject> comments = commentRepository.getList(query); for (final JSONObject comment : comments) { final JSONObject post = new JSONObject(); post.put("id", comment.optString(Keys.OBJECT_ID)); final JSONObject content = new JSONObject(); content.put("title", ""); content.put("tags", ""); content.put("body", comment.optString(Comment.COMMENT_CONTENT)); post.put("content", content.toString()); post.put("created", Comment.COMMENT_CREATE_TIME); post.put("type", "comment"); posts.put(post); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Export comments failed", e); return null; } LOGGER.info("Exporting posts [size=" + posts.length() + "]"); final boolean succ = null != pointtransferMgmtService.transfer(userId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_DATA_EXPORT, Pointtransfer.TRANSFER_SUM_C_DATA_EXPORT, String.valueOf(posts.length()), System.currentTimeMillis(), ""); if (!succ) { return null; } final String uuid = UUID.randomUUID().toString().replaceAll("-", ""); String fileKey = "export-" + userId + "-" + uuid + ".zip"; final String tmpDir = System.getProperty("java.io.tmpdir"); String localFilePath = tmpDir + "/" + uuid + ".json"; LOGGER.info(localFilePath); final File localFile = new File(localFilePath); try { final byte[] data = posts.toString(2).getBytes(StandardCharsets.UTF_8); try (final OutputStream output = new FileOutputStream(localFile)) { IOUtils.write(data, output); } final File zipFile = ZipUtil.zip(localFile); final FileInputStream inputStream = new FileInputStream(zipFile); final byte[] zipData = IOUtils.toByteArray(inputStream); if (Symphonys.QN_ENABLED) { final Auth auth = Auth.create(Symphonys.UPLOAD_QINIU_AK, Symphonys.UPLOAD_QINIU_SK); final UploadManager uploadManager = new UploadManager(new Configuration()); uploadManager.put(zipData, fileKey, auth.uploadToken(Symphonys.UPLOAD_QINIU_BUCKET), null, "application/zip", false); return Symphonys.UPLOAD_QINIU_DOMAIN + "/" + fileKey; } else { fileKey = FileUploadProcessor.genFilePath(fileKey); final String filePath = Symphonys.UPLOAD_LOCAL_DIR + fileKey; FileUtils.copyFile(zipFile, new File(filePath)); return Latkes.getServePath() + "/upload/" + fileKey; } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Uploading exprted data failed", e); return null; }
253
1,362
1,615
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/ReferralMgmtService.java
ReferralMgmtService
updateReferral
class ReferralMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ReferralMgmtService.class); /** * Referral repository. */ @Inject private ReferralRepository referralRepository; /** * Adds or updates a referral. * * @param referral the specified referral */ @Transactional public void updateReferral(final JSONObject referral) {<FILL_FUNCTION_BODY>} }
final String dataId = referral.optString(Referral.REFERRAL_DATA_ID); final String ip = referral.optString(Referral.REFERRAL_IP); try { JSONObject record = referralRepository.getByDataIdAndIP(dataId, ip); if (null == record) { record = new JSONObject(); record.put(Referral.REFERRAL_AUTHOR_HAS_POINT, false); record.put(Referral.REFERRAL_CLICK, 1); record.put(Referral.REFERRAL_DATA_ID, dataId); record.put(Referral.REFERRAL_IP, ip); record.put(Referral.REFERRAL_TYPE, referral.optInt(Referral.REFERRAL_TYPE)); record.put(Referral.REFERRAL_USER, referral.optString(Referral.REFERRAL_USER)); record.put(Referral.REFERRAL_USER_HAS_POINT, false); referralRepository.add(record); } else { final String currentReferralUser = referral.optString(Referral.REFERRAL_USER); final String firstReferralUser = record.optString(Referral.REFERRAL_USER); if (!currentReferralUser.equals(firstReferralUser)) { return; } record.put(Referral.REFERRAL_CLICK, record.optInt(Referral.REFERRAL_CLICK) + 1); referralRepository.update(record.optString(Keys.OBJECT_ID), record); } } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Updates a referral failed", e); }
152
468
620
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/ReportMgmtService.java
ReportMgmtService
makeReportHandled
class ReportMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ReportMgmtService.class); /** * Report repository. */ @Inject private ReportRepository reportRepository; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Pointtransfer management service. */ @Inject private PointtransferMgmtService pointtransferMgmtService; /** * Notification management service. */ @Inject private NotificationMgmtService notificationMgmtService; /** * Makes the specified report as ignored. * * @param reportId the specified report id */ @Transactional public void makeReportIgnored(final String reportId) { try { final JSONObject report = reportRepository.get(reportId); report.put(Report.REPORT_HANDLED, Report.REPORT_HANDLED_C_IGNORED); reportRepository.update(reportId, report); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Makes report [id=" + reportId + "] as ignored failed", e); } } /** * Makes the specified report as handled. * * @param reportId the specified report id */ public void makeReportHandled(final String reportId) {<FILL_FUNCTION_BODY>} /** * Adds a report. * * @param report the specified report, for example, * { * "reportUserId": "", * "reportDataId": "", * "reportDataType": int, * "reportType": int, * "reportMemo": "" * } * @throws ServiceException service exception */ @Transactional public void addReport(final JSONObject report) throws ServiceException { report.put(Report.REPORT_HANDLED, Report.REPORT_HANDLED_C_NOT); try { reportRepository.add(report); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Adds a report failed", e); throw new ServiceException(langPropsService.get("systemErrLabel")); } } }
final Transaction transaction = reportRepository.beginTransaction(); try { final JSONObject report = reportRepository.get(reportId); report.put(Report.REPORT_HANDLED, Report.REPORT_HANDLED_C_YES); reportRepository.update(reportId, report); transaction.commit(); final String reporterId = report.optString(Report.REPORT_USER_ID); final String transferId = pointtransferMgmtService.transfer(Pointtransfer.ID_C_SYS, reporterId, Pointtransfer.TRANSFER_TYPE_C_REPORT_HANDLED, Pointtransfer.TRANSFER_SUM_C_REPORT_HANDLED, reportId, System.currentTimeMillis(), ""); final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, reporterId); notification.put(Notification.NOTIFICATION_DATA_ID, transferId); notificationMgmtService.addReportHandledNotification(notification); } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Makes report [id=" + reportId + "] as handled failed", e); }
613
322
935
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/RewardMgmtService.java
RewardMgmtService
addReward
class RewardMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(RewardMgmtService.class); /** * Reward repository. */ @Inject private RewardRepository rewardRepository; /** * Adds a reward with the specified request json object. * * @param requestJSONObject the specified request json object, for example, * { * "senderId"; "", * "dataId": "", * "type": int * } * @return reward id * @throws ServiceException service exception */ @Transactional public String addReward(final JSONObject requestJSONObject) throws ServiceException {<FILL_FUNCTION_BODY>} }
try { return rewardRepository.add(requestJSONObject); } catch (final RepositoryException e) { final String msg = "Adds reward failed"; LOGGER.log(Level.ERROR, msg, e); throw new ServiceException(msg); }
207
71
278
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/RewardQueryService.java
RewardQueryService
rewardedCount
class RewardQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(RewardQueryService.class); /** * Reward repository. */ @Inject private RewardRepository rewardRepository; /** * Gets rewarded count. * * @param dataId the specified data id * @param type the specified type * @return rewarded count */ public long rewardedCount(final String dataId, final int type) {<FILL_FUNCTION_BODY>} /** * Determines the user specified by the given user id has rewarded the data (article/comment/user) or not. * * @param userId the specified user id * @param dataId the specified data id * @param type the specified type * @return {@code true} if has rewared */ public boolean isRewarded(final String userId, final String dataId, final int type) { final Query query = new Query(); final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Reward.SENDER_ID, FilterOperator.EQUAL, userId)); filters.add(new PropertyFilter(Reward.DATA_ID, FilterOperator.EQUAL, dataId)); filters.add(new PropertyFilter(Reward.TYPE, FilterOperator.EQUAL, type)); query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); try { return 0 != rewardRepository.count(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Determines reward failed", e); return false; } } }
final Query query = new Query(); final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Reward.DATA_ID, FilterOperator.EQUAL, dataId)); filters.add(new PropertyFilter(Reward.TYPE, FilterOperator.EQUAL, type)); query.setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); try { return rewardRepository.count(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Rewarded count failed", e); return 0; }
445
155
600
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/RoleMgmtService.java
RoleMgmtService
addRole
class RoleMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(RoleMgmtService.class); /** * Role repository. */ @Inject private RoleRepository roleRepository; /** * Role-Permission repository. */ @Inject private RolePermissionRepository rolePermissionRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Removes the specified role. * * @param roleId the specified role id */ @Transactional public void removeRole(final String roleId) { try { final Query userCountQuery = new Query().setFilter(new PropertyFilter(User.USER_ROLE, FilterOperator.EQUAL, roleId)); final int count = (int) userRepository.count(userCountQuery); if (0 < count) { return; } rolePermissionRepository.removeByRoleId(roleId); roleRepository.remove(roleId); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Removes a role [id=" + roleId + "] failed", e); } } /** * Adds the specified role. * * @param role the specified role */ @Transactional public void addRole(final JSONObject role) {<FILL_FUNCTION_BODY>} /** * Updates role permissions. * * @param roleId the specified role id */ @Transactional public void updateRolePermissions(final String roleId, final Set<String> permissionIds) { try { rolePermissionRepository.removeByRoleId(roleId); for (final String permissionId : permissionIds) { final JSONObject rel = new JSONObject(); rel.put(Role.ROLE_ID, roleId); rel.put(Permission.PERMISSION_ID, permissionId); rolePermissionRepository.add(rel); } } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Updates role permissions failed", e); } } }
try { final String roleName = role.optString(Role.ROLE_NAME); final Query query = new Query(). setFilter(new PropertyFilter(Role.ROLE_NAME, FilterOperator.EQUAL, roleName)); if (roleRepository.count(query) > 0) { return; } roleRepository.add(role); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Adds role failed", e); }
569
128
697
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/SearchQueryService.java
SearchQueryService
searchElasticsearch
class SearchQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(SearchQueryService.class); /** * Searches by Elasticsearch. * * @param type the specified document type * @param keyword the specified keyword * @param currentPage the specified current page number * @param pageSize the specified page size * @return search result, returns {@code null} if not found */ public JSONObject searchElasticsearch(final String type, final String keyword, final int currentPage, final int pageSize) {<FILL_FUNCTION_BODY>} /** * Searches by Algolia. * * @param keyword the specified keyword * @param currentPage the specified current page number * @param pageSize the specified page size * @return search result, returns {@code null} if not found */ public JSONObject searchAlgolia(final String keyword, final int currentPage, final int pageSize) { final int maxRetries = 3; int retries = 1; final String appId = Symphonys.ALGOLIA_APP_ID; final String index = Symphonys.ALGOLIA_INDEX; final String key = Symphonys.ALGOLIA_ADMIN_KEY; while (retries <= maxRetries) { String host = appId + "-" + retries + ".algolianet.com"; try { final JSONObject params = new JSONObject(); params.put("params", "query=" + URLs.encode(keyword) + "&getRankingInfo=1&facets=*&attributesToRetrieve=*&highlightPreTag=%3Cem%3E" + "&highlightPostTag=%3C%2Fem%3E" + "&facetFilters=%5B%5D&maxValuesPerFacet=100" + "&hitsPerPage=" + pageSize + "&page=" + (currentPage - 1)); final HttpResponse response = HttpRequest.post("https://" + host + "/1/indexes/" + index + "/query"). header("X-Algolia-API-Key", key). header("X-Algolia-Application-Id", appId).bodyText(params.toString()).contentTypeJson(). connectionTimeout(5000).timeout(5000).send(); response.charset("UTF-8"); final JSONObject ret = new JSONObject(response.bodyText()); if (200 != response.statusCode()) { LOGGER.warn(ret.toString(4)); return null; } return ret; } catch (final Exception e) { LOGGER.log(Level.WARN, "Queries failed", e); retries++; if (retries > maxRetries) { LOGGER.log(Level.ERROR, "Queries failed", e); } } } return null; } }
try { final JSONObject reqData = new JSONObject(); final JSONObject q = new JSONObject(); final JSONObject and = new JSONObject(); q.put("and", and); final JSONArray query = new JSONArray(); and.put("query", query); final JSONObject or = new JSONObject(); query.put(or); final JSONArray orClause = new JSONArray(); or.put("or", orClause); final JSONObject content = new JSONObject(); content.put(Article.ARTICLE_CONTENT, keyword); final JSONObject matchContent = new JSONObject(); matchContent.put("match", content); orClause.put(matchContent); final JSONObject title = new JSONObject(); title.put(Article.ARTICLE_TITLE, keyword); final JSONObject matchTitle = new JSONObject(); matchTitle.put("match", title); orClause.put(matchTitle); reqData.put("query", q); reqData.put("from", currentPage); reqData.put("size", pageSize); final JSONArray sort = new JSONArray(); final JSONObject sortField = new JSONObject(); sort.put(sortField); sortField.put(Article.ARTICLE_CREATE_TIME, "desc"); sort.put("_score"); reqData.put("sort", sort); final JSONObject highlight = new JSONObject(); reqData.put("highlight", highlight); highlight.put("number_of_fragments", 3); highlight.put("fragment_size", 150); final JSONObject fields = new JSONObject(); highlight.put("fields", fields); final JSONObject contentField = new JSONObject(); fields.put(Article.ARTICLE_CONTENT, contentField); final JSONArray filter = new JSONArray(); and.put("filter", filter); final JSONObject term = new JSONObject(); filter.put(term); final JSONObject field = new JSONObject(); term.put("term", field); field.put(Article.ARTICLE_STATUS, Article.ARTICLE_STATUS_C_VALID); LOGGER.debug(reqData.toString(4)); final HttpResponse response = HttpRequest.post(Symphonys.ES_SERVER + "/" + SearchMgmtService.ES_INDEX_NAME + "/" + type + "/_search").bodyText(reqData.toString()).contentTypeJson().timeout(5000).send(); response.charset("UTF-8"); return new JSONObject(response.bodyText()); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Queries failed", e); return null; }
771
693
1,464
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/ShortLinkQueryService.java
ShortLinkQueryService
linkArticle
class ShortLinkQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ShortLinkQueryService.class); /** * Article pattern - full. */ private static final Pattern ARTICLE_PATTERN_FULL = Pattern.compile(Latkes.getServePath() + "/article/\\d{13,15}[?\\w&-_=#%:]*(\\b|$)"); /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * Processes article short link (article id). * * @param content the specified content * @return processed content */ public String linkArticle(final String content) {<FILL_FUNCTION_BODY>} }
Stopwatchs.start("Link article"); StringBuffer contentBuilder = new StringBuffer(); try { Matcher matcher = ARTICLE_PATTERN_FULL.matcher(content); final String[] codeBlocks = StringUtils.substringsBetween(content, "```", "```"); String codes = ""; if (null != codeBlocks) { codes = String.join("", codeBlocks); } try { while (matcher.find()) { final String url = StringUtils.trim(matcher.group()); if (0 < matcher.start()) { final char c = content.charAt(matcher.start() - 1); // look back one char if ('(' == c || ']' == c || '\'' == c || '"' == c || '`' == c) { continue; } } if (StringUtils.containsIgnoreCase(codes, url)) { continue; } String linkId; String queryStr = null; String anchor = null; if (StringUtils.contains(url, "?")) { linkId = StringUtils.substringBetween(url, "/article/", "?"); queryStr = StringUtils.substringAfter(url, "?"); } else { linkId = StringUtils.substringAfter(url, "/article/"); } if (StringUtils.contains(url, "#")) { linkId = StringUtils.substringBefore(linkId, "#"); anchor = StringUtils.substringAfter(url, "#"); } final Query query = new Query().select(Article.ARTICLE_TITLE).setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.EQUAL, linkId)); final List<JSONObject> results = articleRepository.getList(query); if (results.isEmpty()) { continue; } final JSONObject linkArticle = results.get(0); final String linkTitle = linkArticle.optString(Article.ARTICLE_TITLE); String link = " [" + linkTitle + "](" + Latkes.getServePath() + "/article/" + linkId; if (StringUtils.isNotBlank(queryStr)) { link += "?" + queryStr; } if (StringUtils.isNotBlank(anchor)) { link += "#" + anchor; } link += ") "; matcher.appendReplacement(contentBuilder, link); } matcher.appendTail(contentBuilder); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Generates article link failed", e); } return contentBuilder.toString(); } finally { Stopwatchs.end(); }
210
702
912
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/SitemapQueryService.java
SitemapQueryService
genDomains
class SitemapQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(SitemapQueryService.class); /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * Domain cache. */ @Inject private DomainCache domainCache; /** * Generates index for the specified sitemap. * * @param sitemap the specified sitemap */ public void genIndex(final Sitemap sitemap) { final Sitemap.URL url = new Sitemap.URL(); url.setLoc(Latkes.getServePath()); url.setChangeFreq("always"); url.setPriority("1.0"); sitemap.addURL(url); } /** * Generates domains for the specified sitemap. * * @param sitemap the specified sitemap */ public void genDomains(final Sitemap sitemap) {<FILL_FUNCTION_BODY>} /** * Generates articles for the specified sitemap. * * @param sitemap the specified sitemap */ public void genArticles(final Sitemap sitemap) { final Query query = new Query().setPage(1, Integer.MAX_VALUE).setPageCount(Integer.MAX_VALUE). select(Keys.OBJECT_ID, Article.ARTICLE_UPDATE_TIME). setFilter(new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.NOT_EQUAL, Article.ARTICLE_STATUS_C_INVALID)). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); try { final List<JSONObject> articles = articleRepository.getList(query); for (final JSONObject article : articles) { final long id = article.getLong(Keys.OBJECT_ID); final String permalink = Latkes.getServePath() + "/article/" + id; final Sitemap.URL url = new Sitemap.URL(); url.setLoc(permalink); final Date updateDate = new Date(id); final String lastMod = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(updateDate); url.setLastMod(lastMod); sitemap.addURL(url); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets sitemap articles failed", e); } } }
final List<JSONObject> domains = domainCache.getDomains(Integer.MAX_VALUE); for (final JSONObject domain : domains) { final String permalink = Latkes.getServePath() + "/domain/" + domain.optString(Domain.DOMAIN_URI); final Sitemap.URL url = new Sitemap.URL(); url.setLoc(permalink); url.setChangeFreq("always"); url.setPriority("0.9"); sitemap.addURL(url); }
659
138
797
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/VerifycodeMgmtService.java
VerifycodeMgmtService
sendEmailVerifycode
class VerifycodeMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(VerifycodeMgmtService.class); /** * Verifycode repository. */ @Inject private VerifycodeRepository verifycodeRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Removes a verifycode with the specified code. * * @param code the specified code */ @Transactional public void removeByCode(final String code) { final Query query = new Query().setFilter(new PropertyFilter(Verifycode.CODE, FilterOperator.EQUAL, code)); try { verifycodeRepository.remove(query); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Removes by code [" + code + "] failed", e); } } /** * Adds a verifycode with the specified request json object. * * @param requestJSONObject the specified request json object, for example, * { * "userId"; "", * "type": int, * "bizType": int, * "receiver": "", * "code": "", * "status": int, * "expired": long * } * @return verifycode id * @throws ServiceException service exception */ @Transactional public String addVerifycode(final JSONObject requestJSONObject) throws ServiceException { try { return verifycodeRepository.add(requestJSONObject); } catch (final RepositoryException e) { final String msg = "Adds verifycode failed"; LOGGER.log(Level.ERROR, msg, e); throw new ServiceException(msg); } } /** * Removes expired verifycodes. */ @Transactional public void removeExpiredVerifycodes() { final Query query = new Query().setFilter(new PropertyFilter(Verifycode.EXPIRED, FilterOperator.LESS_THAN, new Date().getTime())); try { verifycodeRepository.remove(query); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Expires verifycodes failed", e); } } /** * Sends email verifycode. */ @Transactional public void sendEmailVerifycode() {<FILL_FUNCTION_BODY>} }
final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Verifycode.TYPE, FilterOperator.EQUAL, Verifycode.TYPE_C_EMAIL)); filters.add(new PropertyFilter(Verifycode.STATUS, FilterOperator.EQUAL, Verifycode.STATUS_C_UNSENT)); final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); try { final List<JSONObject> verifycodes = verifycodeRepository.getList(query); for (final JSONObject verifycode : verifycodes) { final String userId = verifycode.optString(Verifycode.USER_ID); final JSONObject user = userRepository.get(userId); if (null == user) { continue; } final Map<String, Object> dataModel = new HashMap<>(); final String userName = user.optString(User.USER_NAME); dataModel.put(User.USER_NAME, userName); final String toMail = verifycode.optString(Verifycode.RECEIVER); final String code = verifycode.optString(Verifycode.CODE); String subject; final int bizType = verifycode.optInt(Verifycode.BIZ_TYPE); switch (bizType) { case Verifycode.BIZ_TYPE_C_REGISTER: dataModel.put(Common.URL, Latkes.getServePath() + "/register?code=" + code); subject = langPropsService.get("registerEmailSubjectLabel", Latkes.getLocale()); break; case Verifycode.BIZ_TYPE_C_RESET_PWD: dataModel.put(Common.URL, Latkes.getServePath() + "/reset-pwd?code=" + code); subject = langPropsService.get("forgetEmailSubjectLabel", Latkes.getLocale()); break; case Verifycode.BIZ_TYPE_C_BIND_EMAIL: dataModel.put(Keys.CODE, code); subject = langPropsService.get("bindEmailSubjectLabel", Latkes.getLocale()); break; default: LOGGER.warn("Send email verify code failed with wrong biz type [" + bizType + "]"); continue; } verifycode.put(Verifycode.STATUS, Verifycode.STATUS_C_SENT); verifycodeRepository.update(verifycode.optString(Keys.OBJECT_ID), verifycode); final String fromName = langPropsService.get("symphonyEnLabel") + " " + langPropsService.get("verifycodeEmailFromNameLabel", Latkes.getLocale()); Mails.sendHTML(fromName, subject, toMail, Mails.TEMPLATE_NAME_VERIFYCODE, dataModel); } } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Sends verifycode failed", e); }
672
745
1,417
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/VerifycodeQueryService.java
VerifycodeQueryService
getVerifycodeByUserId
class VerifycodeQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(VerifycodeQueryService.class); /** * Verifycode repository. */ @Inject private VerifycodeRepository verifycodeRepository; /** * Gets a verifycode with the specified type, biz type and user id. * * @param type the specified type * @param bizType the specified biz type * @param userId the specified user id * @return verifycode, returns {@code null} if not found */ public JSONObject getVerifycodeByUserId(final int type, final int bizType, final String userId) {<FILL_FUNCTION_BODY>} /** * Gets a verifycode with the specified code. * * @param code the specified code * @return verifycode, returns {@code null} if not found */ public JSONObject getVerifycode(final String code) { final Query query = new Query().setFilter(new PropertyFilter(Verifycode.CODE, FilterOperator.EQUAL, code)); try { return verifycodeRepository.getFirst(query); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets verifycode failed", e); return null; } } }
final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Verifycode.TYPE, FilterOperator.EQUAL, type), new PropertyFilter(Verifycode.BIZ_TYPE, FilterOperator.EQUAL, bizType), new PropertyFilter(Verifycode.USER_ID, FilterOperator.EQUAL, userId))). addSort(Keys.OBJECT_ID, SortDirection.DESCENDING); try { return verifycodeRepository.getFirst(query); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets verifycode failed", e); return null; }
345
165
510
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/VisitMgmtService.java
VisitMgmtService
expire
class VisitMgmtService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(VisitMgmtService.class); /** * Visit repository. */ @Inject private VisitRepository visitRepository; /** * Adds the specified visit. * * @param visit the specified visit * @return {@code true} if visited before, returns {@code false} otherwise */ @Transactional public boolean add(final JSONObject visit) { try { final String url = visit.optString(Visit.VISIT_URL); final String ip = visit.optString(Visit.VISIT_IP); final Query query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Visit.VISIT_URL, FilterOperator.EQUAL, url), new PropertyFilter(Visit.VISIT_IP, FilterOperator.EQUAL, ip))).setPageCount(1); final long count = visitRepository.count(query); if (0 < count) { return true; } String ua = visit.optString(Visit.VISIT_UA); if (StringUtils.length(ua) > Common.MAX_LENGTH_UA) { ua = StringUtils.substring(ua, 0, Common.MAX_LENGTH_UA); } visit.put(Visit.VISIT_UA, ua); String referer = visit.optString(Visit.VISIT_REFERER_URL); if (StringUtils.length(referer) > Common.MAX_LENGTH_URL) { referer = StringUtils.substring(referer, 0, Common.MAX_LENGTH_URL); } visit.put(Visit.VISIT_REFERER_URL, referer); visitRepository.add(visit); return false; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Adds a visit failed", e); return true; } } /** * Expires visits. */ @Transactional public void expire() {<FILL_FUNCTION_BODY>} }
try { final Query query = new Query().setFilter(new PropertyFilter(Visit.VISIT_EXPIRED, FilterOperator.LESS_THAN_OR_EQUAL, System.currentTimeMillis())) .setPageCount(1); visitRepository.remove(query); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Expires visits failed", e); }
564
105
669
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/service/VoteQueryService.java
VoteQueryService
isOwn
class VoteQueryService { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(VoteQueryService.class); /** * Vote repository. */ @Inject private VoteRepository voteRepository; /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * Comment repository. */ @Inject private CommentRepository commentRepository; /** * Determines whether the specified user dose vote the specified entity. * * @param userId the specified user id * @param dataId the specified entity id * @return voted type, returns {@code -1} if has not voted yet */ public int isVoted(final String userId, final String dataId) { try { final List<Filter> filters = new ArrayList<>(); filters.add(new PropertyFilter(Vote.USER_ID, FilterOperator.EQUAL, userId)); filters.add(new PropertyFilter(Vote.DATA_ID, FilterOperator.EQUAL, dataId)); final Query query = new Query().setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters)); final JSONObject vote = voteRepository.getFirst(query); if (null == vote) { return -1; } return vote.optInt(Vote.TYPE); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, e.getMessage()); return -1; } } /** * Determines whether the specified data dose belong to the specified user. * * @param userId the specified user id * @param dataId the specified data id * @param dataType the specified data type * @return {@code true} if it belongs to the user, otherwise returns {@code false} */ public boolean isOwn(final String userId, final String dataId, final int dataType) {<FILL_FUNCTION_BODY>} }
try { if (Vote.DATA_TYPE_C_ARTICLE == dataType) { final JSONObject article = articleRepository.get(dataId); if (null == article) { LOGGER.log(Level.ERROR, "Not found article [id={}]", dataId); return false; } return article.optString(Article.ARTICLE_AUTHOR_ID).equals(userId); } else if (Vote.DATA_TYPE_C_COMMENT == dataType) { final JSONObject comment = commentRepository.get(dataId); if (null == comment) { LOGGER.log(Level.ERROR, "Not found comment [id={}]", dataId); return false; } return comment.optString(Comment.COMMENT_AUTHOR_ID).equals(userId); } return false; } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, e.getMessage()); return false; }
511
261
772
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Escapes.java
Escapes
escapeHTML
class Escapes { /** * Sanitizes the specified file name. * * @param unsanitized the specified file name * @return sanitized file name */ public static String sanitizeFilename(final String unsanitized) { return unsanitized. replaceAll("[\\?\\\\/:|<>\\*\\[\\]]", "-"). // ? \ / : | < > * [ ] to - replaceAll("\\s+", "-"); // white space to - } /** * Escapes the specified string. * * @param str the specified string */ public static String escapeHTML(final String str) { return Encode.forHtml(str); } /** * Escapes string property in the specified JSON object. * * @param jsonObject the specified JSON object */ public static void escapeHTML(final JSONObject jsonObject) {<FILL_FUNCTION_BODY>} /** * Private constructor. */ private Escapes() { } }
final Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { final String key = keys.next(); if (jsonObject.opt(key) instanceof String) { jsonObject.put(key, Encode.forHtml(jsonObject.optString(key))); } }
273
82
355
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Geos.java
Geos
getAddress
class Geos { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(Geos.class); /** * Private constructor. */ private Geos() { } /** * Gets country, province and city of the specified IP. * * @param ip the specified IP * @return address info, for example <pre> * { * "country": "", * "province": "", * "city": "" * } * </pre>, returns {@code null} if not found */ public static JSONObject getAddress(final String ip) {<FILL_FUNCTION_BODY>} /** * Gets province, city of the specified IP by Taobao API. * * @param ip the specified IP * @return address info, for example <pre> * { * "province": "", * "city": "" * } * </pre>, returns {@code null} if not found */ private static JSONObject getAddressTaobao(final String ip) { HttpURLConnection conn = null; try { final URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); final JSONObject data = new JSONObject(IOUtils.toString(conn.getInputStream(), StandardCharsets.UTF_8)); if (0 != data.optInt("code")) { return null; } final String country = data.optString("country"); final String province = data.optString("region"); String city = data.optString("city"); city = StringUtils.replace(city, "市", ""); final JSONObject ret = new JSONObject(); ret.put(Common.COUNTRY, country); ret.put(Common.PROVINCE, province); ret.put(Common.CITY, city); return ret; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Can't get location from Taobao [ip=" + ip + "]", e); return null; } finally { if (null != conn) { try { conn.disconnect(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Close HTTP connection failed", e); } } } } }
final String ak = Symphonys.BAIDU_LBS_AK; if (StringUtils.isBlank(ak) || !Strings.isIPv4(ip)) { return null; } HttpURLConnection conn = null; try { final URL url = new URL("http://api.map.baidu.com/location/ip?ip=" + ip + "&ak=" + ak); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); final JSONObject data = new JSONObject(IOUtils.toString(conn.getInputStream(), StandardCharsets.UTF_8)); if (0 != data.optInt("status")) { return getAddressTaobao(ip); } final String content = data.optString("address"); final String country = content.split("\\|")[0]; if (!"CN".equals(country) && !"HK".equals(country) && !"TW".equals(country)) { LOGGER.log(Level.WARN, "Found other country via Baidu [" + country + ", " + ip + "]"); return null; } final String province = content.split("\\|")[1]; String city = content.split("\\|")[2]; if ("None".equals(province) || "None".equals(city)) { return getAddressTaobao(ip); } city = StringUtils.replace(city, "市", ""); final JSONObject ret = new JSONObject(); ret.put(Common.COUNTRY, "中国"); ret.put(Common.PROVINCE, province); ret.put(Common.CITY, city); return ret; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Can't get location from Baidu [ip=" + ip + "]", e); return getAddressTaobao(ip); } finally { if (null != conn) { try { conn.disconnect(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Close HTTP connection failed", e); } } }
663
579
1,242
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Gravatars.java
Gravatars
getRandomAvatarData
class Gravatars { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(Gravatars.class); /** * Styles. */ private static final String[] d = new String[]{"identicon", "monsterid", "wavatar", "retro", "robohash"}; /** * Gets random avatar image byte array data with the specified hash. * * @param hash the specified hash * @return avatar image byte array date, returns {@code null} if failed to get avatar */ public static byte[] getRandomAvatarData(final String hash) {<FILL_FUNCTION_BODY>} /** * Private constructor. */ private Gravatars() { } }
try { String h = hash; if (StringUtils.isBlank(h)) { h = RandomStringUtils.randomAlphanumeric(16); } final HttpResponse response = HttpRequest.get("http://www.gravatar.com/avatar/" + h + "?s=256&d=" + d[RandomUtils.nextInt(0, d.length)]). connectionTimeout(5000).timeout(5000).send(); if (200 != response.statusCode()) { LOGGER.log(Level.WARN, "Gets avatar data failed [sc=" + response.statusCode() + "]"); return null; } return response.bodyBytes(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets avatar data failed", e); return null; }
206
228
434
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Headers.java
Headers
getSuffix
class Headers { /** * Gets suffix (for example jpg) of the specified file. * * @param file the specified file * @return suffix */ public static String getSuffix(final FileUpload file) {<FILL_FUNCTION_BODY>} /** * Gets suffix (for example jpg) with the specified content type. * * @param contentType the specified content type * @return suffix */ public static String getSuffix(final String contentType) { String ret; final String[] exts = MimeTypes.findExtensionsByMimeTypes(contentType, false); if (null != exts && 0 < exts.length) { ret = exts[0]; } else { ret = StringUtils.substringAfter(contentType, "/"); ret = StringUtils.substringBefore(ret, ";"); } return ret; } /** * Gets a value of a header specified by the given header name from the specified request. * * @param request the specified request * @param name the given header name * @param defaultVal the specified default value * @return header value, returns {@code defaultVal} if not found this header */ public static String getHeader(final Request request, final String name, final String defaultVal) { String value = request.getHeader(name); if (StringUtils.isBlank(value)) { return defaultVal; } return Escapes.escapeHTML(value); } /** * Private constructor. */ private Headers() { } }
final String fileName = file.getFilename(); String ret = StringUtils.substringAfterLast(fileName, "."); if (StringUtils.isNotBlank(ret)) { return ret; } final String contentType = file.getContentType(); return getSuffix(contentType);
418
82
500
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Images.java
Images
qiniuImgProcessing
class Images { /** * Qiniu image processing. * * @param content the specified article content * @return processed content */ public static String qiniuImgProcessing(final String content) {<FILL_FUNCTION_BODY>} /** * Private constructor. */ private Images() { } }
String ret = content; if (!Symphonys.QN_ENABLED) { return ret; } final String qiniuDomain = Symphonys.UPLOAD_QINIU_DOMAIN; final String html = Markdowns.toHTML(content); final String[] imgSrcs = StringUtils.substringsBetween(html, "<img src=\"", "\""); if (null == imgSrcs) { return ret; } for (final String imgSrc : imgSrcs) { if (!StringUtils.startsWith(imgSrc, qiniuDomain) || StringUtils.contains(imgSrc, ".gif") || StringUtils.containsIgnoreCase(imgSrc, "?imageView2")) { continue; } ret = StringUtils.replace(ret, imgSrc, imgSrc + "?imageView2/2/w/768/format/webp/interlace/1"); } return ret;
94
258
352
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Links.java
Links
getLink
class Links { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(Links.class); /** * Gets link from the specified URL. * * @param url the specified URL * @return link like this: <pre> * { * "linkAddr": "https://ld246.com/article/1440573175609", * "linkTitle": "社区简介", * "linkKeywords": "", * "linkHTML": "page HTML", * "linkText": "page text", * "linkBaiduRefCnt": int * } * </pre> */ public static JSONObject getLink(final String url) {<FILL_FUNCTION_BODY>} private static boolean containsChinese(final String str) { if (StringUtils.isBlank(str)) { return false; } final Pattern p = Pattern.compile("[\u4e00-\u9fa5]"); final Matcher m = p.matcher(str); return m.find(); } static class Spider implements Callable<JSONObject> { private final String url; Spider(final String url) { this.url = url; } @Override public JSONObject call() { final int TIMEOUT = 5000; try { final JSONObject ret = new JSONObject(); // Get meta info of the URL final Connection.Response res = Jsoup.connect(url).timeout(TIMEOUT).followRedirects(true).execute(); if (200 != res.statusCode()) { return null; } String charset = res.charset(); if (StringUtils.isBlank(charset)) { charset = "UTF-8"; } final String html = new String(res.bodyAsBytes(), charset); String title = StringUtils.substringBetween(html, "<title>", "</title>"); title = StringUtils.trim(title); if (!containsChinese(title)) { return null; } title = Emotions.toAliases(title); final String keywords = StringUtils.substringBetween(html, "eywords\" content=\"", "\""); ret.put(Link.LINK_ADDR, url); ret.put(Link.LINK_TITLE, title); ret.put(Link.LINK_T_KEYWORDS, keywords); ret.put(Link.LINK_T_HTML, html); final Document doc = Jsoup.parse(html); doc.select("pre").remove(); ret.put(Link.LINK_T_TEXT, doc.text()); // Evaluate the URL URL baiduURL = new URL("https://www.baidu.com/s?pn=0&wd=" + URLs.encode(url)); HttpURLConnection conn = (HttpURLConnection) baiduURL.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.addRequestProperty(Common.USER_AGENT, Symphonys.USER_AGENT_BOT); String baiduRes; try (final InputStream inputStream = conn.getInputStream()) { baiduRes = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } conn.disconnect(); int baiduRefCnt = StringUtils.countMatches(baiduRes, "<em>" + url + "</em>"); if (1 > baiduRefCnt) { ret.put(Link.LINK_BAIDU_REF_CNT, baiduRefCnt); // LOGGER.debug(ret.optString(Link.LINK_ADDR)); return ret; } else { baiduURL = new URL("https://www.baidu.com/s?pn=10&wd=" + URLs.encode(url)); conn = (HttpURLConnection) baiduURL.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.addRequestProperty(Common.USER_AGENT, Symphonys.USER_AGENT_BOT); try (final InputStream inputStream = conn.getInputStream()) { baiduRes = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } conn.disconnect(); baiduRefCnt += StringUtils.countMatches(baiduRes, "<em>" + url + "</em>"); ret.put(Link.LINK_BAIDU_REF_CNT, baiduRefCnt); // LOGGER.debug(ret.optString(Link.LINK_ADDR)); return ret; } } catch (final SocketTimeoutException e) { return null; } catch (final Exception e) { LOGGER.log(Level.TRACE, "Parses URL [" + url + "] failed", e); return null; } } } }
try { return Symphonys.EXECUTOR_SERVICE.submit(new Spider(url)).get(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Parses URL [" + url + "] failed", e); return null; }
1,328
78
1,406
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/MediaPlayers.java
MediaPlayers
renderAudio
class MediaPlayers { /** * Video suffix. */ private static final String VIDEO_SUFFIX = "rm|rmvb|3gp|avi|mpeg|mp4|wmv|mkv|dat|asf|flv|mov|webm"; /** * Video URL regex. */ private static final String VIDEO_URL_REGEX = "<p>( )*<a href.*\\.(" + VIDEO_SUFFIX + ").*</a>( )*</p>"; /** * Video URL regex pattern. */ private static final Pattern VIDEO_PATTERN = Pattern.compile(VIDEO_URL_REGEX, Pattern.CASE_INSENSITIVE); /** * Audio suffix. */ private static final String AUDIO_SUFFIX = "mp3|flac"; /** * Audio (.mp3, .flac) URL regex. */ private static final String AUDIO_URL_REGEX = "<p>( )*<a href.*\\.(" + AUDIO_SUFFIX + ").*</a>( )*</p>"; /** * Audio URL regex pattern. */ private static final Pattern AUDIO_PATTERN = Pattern.compile(AUDIO_URL_REGEX, Pattern.CASE_INSENSITIVE); /** * Media suffix. */ public static final String MEDIA_SUFFIX = VIDEO_SUFFIX + "|" + AUDIO_SUFFIX; /** * Checks whether the specified src is a media resource. * * @param src the specified src * @return {@code true} if it is a media resource, returns {@code false} otherwise */ public static boolean isMedia(final String src) { final String[] suffixes = StringUtils.split(MEDIA_SUFFIX, "|"); for (final String suffix : suffixes) { if (StringUtils.endsWithIgnoreCase(src, "." + suffix)) { return true; } } return false; } /** * Checks whether the specified a tag could be rendered by Vditor. * * @param a the specified a tag * @return {@code true} if could be, returns {@code false} otherwise */ public static boolean isVditorRender(final String a) { return StringUtils.containsIgnoreCase(a, "v.qq.com") || StringUtils.containsIgnoreCase(a, "youtube.com") || StringUtils.containsIgnoreCase(a, "youtu.be") || StringUtils.containsIgnoreCase(a, "youku.com") || StringUtils.containsIgnoreCase(a, "coub.com") || StringUtils.containsIgnoreCase(a, "dailymotion.com") || StringUtils.containsIgnoreCase(a, "facebook.com/videos/"); } /** * Renders the specified content with audio player if need. * * @param content the specified content * @return rendered content */ public static String renderAudio(final String content) {<FILL_FUNCTION_BODY>} /** * Renders the specified content with video player if need. * * @param content the specified content * @return rendered content */ public static String renderVideo(final String content) { final BeanManager beanManager = BeanManager.getInstance(); final LangPropsService langPropsService = beanManager.getReference(LangPropsService.class); final StringBuffer contentBuilder = new StringBuffer(); final Matcher m = VIDEO_PATTERN.matcher(content); while (m.find()) { final String g = m.group(); if (isVditorRender(g)) { continue; } String videoURL = StringUtils.substringBetween(g, "href=\"", "\" rel="); if (StringUtils.isBlank(videoURL)) { videoURL = StringUtils.substringBetween(g, "href=\"", "\""); } if (StringUtils.containsIgnoreCase(videoURL, "/forward")) { // 站外链接不渲染视频 continue; } m.appendReplacement(contentBuilder, "<video width=\"100%\" src=\"" + videoURL + "\" controls=\"controls\">" + langPropsService.get("notSupportPlayLabel") + "</video>\n"); } m.appendTail(contentBuilder); return contentBuilder.toString(); } private MediaPlayers() { } }
final StringBuffer contentBuilder = new StringBuffer(); final Matcher m = AUDIO_PATTERN.matcher(content); while (m.find()) { final String g = m.group(); String audioName = StringUtils.substringBetween(g, "\">", "</a>"); audioName = StringUtils.substringBeforeLast(audioName, "."); String audioURL = StringUtils.substringBetween(g, "href=\"", "\" rel="); if (StringUtils.isBlank(audioURL)) { audioURL = StringUtils.substringBetween(g, "href=\"", "\""); } m.appendReplacement(contentBuilder, "<div class=\"aplayer content-audio\" data-title=\"" + audioName + "\" data-url=\"" + audioURL + "\" ></div>\n"); } m.appendTail(contentBuilder); return contentBuilder.toString();
1,195
246
1,441
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Networks.java
Networks
isInnerAddress
class Networks { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(Networks.class); /** * Checks the specified hostname is an inner address. * * @param host the specified hostname * @return {@code true} if it is, returns {@code false} otherwise */ public static boolean isInnerAddress(final String host) {<FILL_FUNCTION_BODY>} private static int ipToLong(final String ip) throws Exception { return ByteBuffer.wrap(InetAddress.getByName(ip).getAddress()).getInt(); } /** * Private constructor. */ private Networks() { } }
try { final int intAddress = ipToLong(host); return ipToLong("0.0.0.0") >> 24 == intAddress >> 24 || ipToLong("127.0.0.1") >> 24 == intAddress >> 24 || ipToLong("10.0.0.0") >> 24 == intAddress >> 24 || ipToLong("172.16.0.0") >> 20 == intAddress >> 20 || ipToLong("192.168.0.0") >> 16 == intAddress >> 16; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Checks inner address failed: " + e.getMessage()); return true; }
187
204
391
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Pangu.java
Pangu
spacingText
class Pangu { /** * You should use the constructor to create a {@code Pangu} object with default values. */ public Pangu() { } /* * Some capturing group patterns for convenience. * * CJK: Chinese, Japanese, Korean * ANS: Alphabet, Number, Symbol */ private static final Pattern CJK_ANS = Pattern.compile( "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])" + "([a-z0-9`~@\\$%\\^&\\*\\-_\\+=\\|\\\\/])", Pattern.CASE_INSENSITIVE ); private static final Pattern ANS_CJK = Pattern.compile( "([a-z0-9`~!\\$%\\^&\\*\\-_\\+=\\|\\\\;:,\\./\\?])" + "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])", Pattern.CASE_INSENSITIVE ); private static final Pattern CJK_QUOTE = Pattern.compile( "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])" + "([\"'])" ); private static final Pattern QUOTE_CJK = Pattern.compile( "([\"'])" + "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])" ); private static final Pattern FIX_QUOTE = Pattern.compile("([\"'])(\\s*)(.+?)(\\s*)([\"'])"); private static final Pattern CJK_BRACKET_CJK = Pattern.compile( "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])" + "([\\({\\[]+(.*?)[\\)}\\]]+)" + "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])" ); private static final Pattern CJK_BRACKET = Pattern.compile( "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])" + "([\\(\\){}\\[\\]<>])" ); private static final Pattern BRACKET_CJK = Pattern.compile( "([\\(\\){}\\[\\]<>])" + "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])" ); private static final Pattern FIX_BRACKET = Pattern.compile("([(\\({\\[)]+)(\\s*)(.+?)(\\s*)([\\)}\\]]+)"); private static final Pattern CJK_HASH = Pattern.compile( "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])" + "(#(\\S+))" ); private static final Pattern HASH_CJK = Pattern.compile( "((\\S+)#)" + "([\\p{InHiragana}\\p{InKatakana}\\p{InBopomofo}\\p{InCJKCompatibilityIdeographs}\\p{InCJKUnifiedIdeographs}])" ); /** * Performs a paranoid text spacing on {@code text}. * * @param text the string you want to process, must not be {@code null}. * @return a comfortable and readable version of {@code text} for paranoiac. */ public static String spacingText(String text) {<FILL_FUNCTION_BODY>} }
// CJK and quotes Matcher cqMatcher = CJK_QUOTE.matcher(text); text = cqMatcher.replaceAll("$1 $2"); Matcher qcMatcher = QUOTE_CJK.matcher(text); text = qcMatcher.replaceAll("$1 $2"); Matcher fixQuoteMatcher = FIX_QUOTE.matcher(text); text = fixQuoteMatcher.replaceAll("$1$3$5"); // CJK and brackets String oldText = text; Matcher cbcMatcher = CJK_BRACKET_CJK.matcher(text); String newText = cbcMatcher.replaceAll("$1 $2 $4"); text = newText; if (oldText.equals(newText)) { Matcher cbMatcher = CJK_BRACKET.matcher(text); text = cbMatcher.replaceAll("$1 $2"); Matcher bcMatcher = BRACKET_CJK.matcher(text); text = bcMatcher.replaceAll("$1 $2"); } Matcher fixBracketMatcher = FIX_BRACKET.matcher(text); text = fixBracketMatcher.replaceAll("$1$3$5"); // CJK and hash Matcher chMatcher = CJK_HASH.matcher(text); text = chMatcher.replaceAll("$1 $2"); Matcher hcMatcher = HASH_CJK.matcher(text); text = hcMatcher.replaceAll("$1 $3"); // CJK and ANS Matcher caMatcher = CJK_ANS.matcher(text); text = caMatcher.replaceAll("$1 $2"); Matcher acMatcher = ANS_CJK.matcher(text); text = acMatcher.replaceAll("$1 $2"); return text;
1,260
514
1,774
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Results.java
Results
newFail
class Results { /** * Constructs a successful result. * * @return result */ public static JSONObject newSucc() { return new JSONObject().put(Keys.CODE, StatusCodes.SUCC).put(Keys.MSG, ""); } /** * Constructs a failed result. * * @return result */ public static JSONObject newFail() {<FILL_FUNCTION_BODY>} /** * Private constructor. */ private Results() { } }
return new JSONObject().put(Keys.CODE, StatusCodes.ERR).put(Keys.MSG, "System is abnormal, please try again later");
143
40
183
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Runes.java
Runes
getChinesePercent
class Runes { private Runes() { } // public static void main(final String[] args) { // System.out.println(getChinesePercent("123abc这个中文cde123abc也要提取123ab")); // } /** * Removes control characters for the specified string. * * @param str the specified string * @return str removed control characters */ public static String removeControlChars(final String str) { final CharMatcher charsToPreserve = CharMatcher.anyOf("\r\n\t"); final CharMatcher allButPreserved = charsToPreserve.negate(); final CharMatcher controlCharactersToRemove = CharMatcher.javaIsoControl().and(allButPreserved); return controlCharactersToRemove.removeFrom(str); } /** * Gets chinese percentage of the specified string. * * @param str the specified string * @return percentage */ public static int getChinesePercent(final String str) {<FILL_FUNCTION_BODY>} }
if (StringUtils.isBlank(str)) { return 0; } final Pattern p = Pattern.compile("([\u4e00-\u9fa5]+)"); final Matcher m = p.matcher(str); final StringBuilder chineseBuilder = new StringBuilder(); while (m.find()) { chineseBuilder.append(m.group(0)); } return (int) Math.floor(StringUtils.length(chineseBuilder.toString()) / (double) StringUtils.length(str) * 100);
285
147
432
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/util/Tesseracts.java
Tesseracts
recognizeCharacter
class Tesseracts { /** * Recognizes a single character from the specified image file path. * * @param imagePath the specified image file path * @return the recognized character */ public static String recognizeCharacter(final String imagePath) {<FILL_FUNCTION_BODY>} /** * Private constructor. */ private Tesseracts() { } }
try { Execs.exec(new String[]{"sh", "-c", "tesseract " + imagePath + " " + imagePath + " -l chi_sim --psm 8"}, 1000 * 3); return StringUtils.trim(IOUtils.toString(new FileInputStream(imagePath + ".txt"), StandardCharsets.UTF_8)); } catch (final Exception e) { return ""; }
108
109
217
<no_super_class>
jtablesaw_tablesaw
tablesaw/beakerx/src/main/java/tech/tablesaw/beakerx/TablesawDisplayer.java
TablesawDisplayer
registerColumns
class TablesawDisplayer { private TablesawDisplayer() {} /** * Registers {@link Table} and {@link Column} for display in Jupyter. Call {@link * #registerTable()} or {@link #registerColumns()} instead if you'd like to only display one or * the other. */ public static void register() { registerTable(); registerColumns(); } /** Registers {@link Table} for display in Jupyter. */ public static void registerTable() { Displayers.register( Table.class, new Displayer<Table>() { @Override public Map<String, String> display(Table table) { new TableDisplay( table.rowCount(), table.columnCount(), table.columnNames(), (int columnIndex, int rowIndex) -> table.getUnformatted(rowIndex, columnIndex)) .display(); return OutputCell.DISPLAYER_HIDDEN; } }); } /** * Registers and {@link Column} for display in Jupyter. Call {@link #registerTable()} or {@link * #registerColumns()} instead if you'd like to only display one or the other. */ // TODO: remove rawtypes warnings suppression after PR below is merged // https://github.com/jupyter/jvm-repr/pull/22 @SuppressWarnings({"rawtypes", "unchecked"}) public static void registerColumns() {<FILL_FUNCTION_BODY>} }
Displayers.register( Column.class, new Displayer<Column>() { @Override public Map<String, String> display(Column column) { new TableDisplay( column.size(), 1, Lists.newArrayList(column.name()), (int columnIndex, int rowIndex) -> column.getUnformattedString(rowIndex)) .display(); return OutputCell.DISPLAYER_HIDDEN; } });
397
124
521
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/aggregate/NumericAggregateFunction.java
NumericAggregateFunction
isCompatibleColumn
class NumericAggregateFunction extends AggregateFunction<NumericColumn<?>, Double> { /** * Constructs a NumericAggregateFunction with the given name. The name may be used to name a * column in the output when this function is used by {@link Summarizer} */ public NumericAggregateFunction(String name) { super(name); } /** {@inheritDoc} */ @Override public boolean isCompatibleColumn(ColumnType type) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public ColumnType returnType() { return ColumnType.DOUBLE; } }
return type.equals(ColumnType.DOUBLE) || type.equals(ColumnType.FLOAT) || type.equals(ColumnType.INTEGER) || type.equals(ColumnType.SHORT) || type.equals(ColumnType.LONG);
174
71
245
<methods>public void <init>(java.lang.String) ,public java.lang.String functionName() ,public abstract boolean isCompatibleColumn(tech.tablesaw.api.ColumnType) ,public abstract tech.tablesaw.api.ColumnType returnType() ,public abstract java.lang.Double summarize(NumericColumn<?>) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String functionName
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/aggregate/PivotTable.java
PivotTable
pivot
class PivotTable { /** * Returns a table that is a rotation of the given table pivoted around the key columns, and * filling the output cells using the values calculated by the {@code aggregateFunction} when * applied to the {@code values column} grouping by the key columns * * @param table The table that provides the data to be pivoted * @param column1 A "key" categorical column from which the primary grouping is created. There * will be one on each row of the result * @param column2 A second categorical column for which a subtotal is created; this produces n * columns on each row of the result * @param values A numeric column that provides the values to be summarized * @param aggregateFunction function that defines what operation is performed on the values in the * subgroups * @return A new, pivoted table */ public static Table pivot( Table table, CategoricalColumn<?> column1, CategoricalColumn<?> column2, NumericColumn<?> values, AggregateFunction<?, ?> aggregateFunction) {<FILL_FUNCTION_BODY>} private static Map<String, Double> getValueMap( CategoricalColumn<?> column1, CategoricalColumn<?> column2, NumericColumn<?> values, int valueIndex, TableSlice slice, AggregateFunction<?, ?> function) { Table temp = slice.asTable(); Table summary = temp.summarize(values.name(), function).by(column1.name(), column2.name()); Map<String, Double> valueMap = new HashMap<>(); NumericColumn<?> nc = summary.numberColumn(summary.columnCount() - 1); for (int i = 0; i < summary.rowCount(); i++) { valueMap.put(String.valueOf(summary.get(i, 1)), nc.getDouble(i)); } return valueMap; } private static List<String> getValueColumnNames(Table table, CategoricalColumn<?> column2) { List<String> valueColumnNames = new ArrayList<>(); for (Object colName : table.column(column2.name()).unique()) { valueColumnNames.add(String.valueOf(colName)); } valueColumnNames.sort(String::compareTo); return valueColumnNames; } }
TableSliceGroup tsg = table.splitOn(column1); Table pivotTable = Table.create("Pivot: " + column1.name() + " x " + column2.name()); pivotTable.addColumns(column1.type().create(column1.name())); List<String> valueColumnNames = getValueColumnNames(table, column2); for (String colName : valueColumnNames) { pivotTable.addColumns(DoubleColumn.create(colName)); } int valueIndex = table.columnIndex(column2); int keyIndex = table.columnIndex(column1); String key; for (TableSlice slice : tsg.getSlices()) { key = String.valueOf(slice.get(0, keyIndex)); pivotTable.column(0).appendCell(key); Map<String, Double> valueMap = getValueMap(column1, column2, values, valueIndex, slice, aggregateFunction); for (String columnName : valueColumnNames) { Double aDouble = valueMap.get(columnName); NumericColumn<?> pivotValueColumn = pivotTable.numberColumn(columnName); if (aDouble == null) { pivotValueColumn.appendMissing(); } else { pivotValueColumn.appendObj(aDouble); } } } return pivotTable;
619
357
976
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/analytic/AnalyticQueryEngine.java
AnalyticQueryEngine
processNumberingFunctions
class AnalyticQueryEngine { private final AnalyticQuery query; private final Table destination; private final IntComparatorChain rowComparator; private AnalyticQueryEngine(AnalyticQuery query) { this.query = query; this.destination = Table.create("Analytic ~ " + query.getTable().name()); Optional<Sort> sort = query.getSort(); this.rowComparator = sort.isPresent() ? SortUtils.getChain(query.getTable(), sort.get()) : null; } /** Returns a new AnalyticQueryEngine to execute the given query */ public static AnalyticQueryEngine create(AnalyticQuery query) { return new AnalyticQueryEngine(query); } /** * Execute the given analytic Query. * * @return a table with the result of the query. Rows in the result table match the order of rows * in the source table. */ public Table execute() { addColumns(); partition().forEach(this::processSlice); return destination; } private void processSlice(TableSlice slice) { orderBy(slice); processAggregateFunctions(slice); processNumberingFunctions(slice); } /** * Execute all aggregate functions for the given slice setting values in the appropriate * destination column. */ private void processAggregateFunctions(TableSlice slice) { for (String toColumn : query.getArgumentList().getAggregateFunctions().keySet()) { FunctionCall<AggregateFunctions> functionCall = query.getArgumentList().getAggregateFunctions().get(toColumn); AggregateFunctions aggregateFunction = functionCall.getFunction(); Column<?> sourceColumn = query.getTable().column(functionCall.getSourceColumnName()); validateColumn(aggregateFunction, sourceColumn); Column<?> destinationColumn = destination.column(functionCall.getDestinationColumnName()); new WindowSlider( query.getWindowFrame(), aggregateFunction, slice, sourceColumn, destinationColumn) .execute(); } } /** * Execute all numbering functions for the given slice setting values in the appropriate * destination column. */ @SuppressWarnings({"unchecked", "rawtypes"}) private void processNumberingFunctions(TableSlice slice) {<FILL_FUNCTION_BODY>} /** * Checks to make sure the given aggregate function is compatible with the type of the source * column. */ private void validateColumn(FunctionMetaData function, Column<?> sourceColumn) { if (!function.isCompatibleColumn(sourceColumn.type())) { throw new IllegalArgumentException( "Function: " + function.functionName() + " Is not compatible with column type: " + sourceColumn.type()); } } /** * Creates empty columns that will be filled in when the analytic aggregate or numbering functions * are executed. */ private void addColumns() { this.destination.addColumns( query .getArgumentList() .createEmptyDestinationColumns(query.getTable().rowCount()) .toArray(new Column<?>[0])); } /** * Partition the source table into a series of table slices. Does not modify the underlying table. */ private Iterable<TableSlice> partition() { if (query.getPartitionColumns().isEmpty()) { return ImmutableList.of(new TableSlice(query.getTable())); } return query.getTable().splitOn(query.getPartitionColumns().toArray(new String[0])); } /** Order the tableSlice in place. Does not modify the underlying table. */ private void orderBy(TableSlice tableSlice) { query.getSort().ifPresent(tableSlice::sortOn); } }
for (String toColumn : query.getArgumentList().getNumberingFunctions().keySet()) { if (rowComparator == null) { throw new IllegalArgumentException("Cannot use Numbering Function without OrderBy"); } FunctionCall<NumberingFunctions> functionCall = query.getArgumentList().getNumberingFunctions().get(toColumn); NumberingFunctions numberingFunctions = functionCall.getFunction(); NumberingFunction function = numberingFunctions.getImplementation(); Column<Integer> destinationColumn = (Column<Integer>) destination.column(functionCall.getDestinationColumnName()); int prevRowNumber = -1; // Slice has already been ordered. for (Row row : slice) { if (row.getRowNumber() == 0) { function.addNextRow(); } else { // Consecutive rows are equal. if (rowComparator.compare( slice.mappedRowNumber(prevRowNumber), slice.mappedRowNumber(row.getRowNumber())) == 0) { function.addEqualRow(); } else { // Consecutive rows are not equal. function.addNextRow(); } } prevRowNumber = row.getRowNumber(); // Set the row number in the destination that corresponds to the row in the view. destinationColumn.set(slice.mappedRowNumber(row.getRowNumber()), function.getValue()); } }
978
364
1,342
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/analytic/ArgumentList.java
ArgumentList
toSqlString
class ArgumentList { // Throws if a column with the same name is registered private final Map<String, FunctionCall<AggregateFunctions>> aggregateFunctions; private final Map<String, FunctionCall<NumberingFunctions>> numberingFunctions; // Used to determine the order in which to add new columns. private final Set<String> newColumnNames; private ArgumentList( Map<String, FunctionCall<AggregateFunctions>> aggregateFunctions, Map<String, FunctionCall<NumberingFunctions>> numberingFunctions, Set<String> newColumnNames) { this.aggregateFunctions = aggregateFunctions; this.numberingFunctions = numberingFunctions; this.newColumnNames = newColumnNames; } static Builder builder() { return new Builder(); } public Map<String, FunctionCall<AggregateFunctions>> getAggregateFunctions() { return aggregateFunctions; } public Map<String, FunctionCall<NumberingFunctions>> getNumberingFunctions() { return numberingFunctions; } public List<String> getNewColumnNames() { return ImmutableList.copyOf(newColumnNames); } public String toSqlString(String windowName) {<FILL_FUNCTION_BODY>} /** @return an ordered list of new columns this analytic query will generate. */ List<Column<?>> createEmptyDestinationColumns(int rowCount) { List<Column<?>> newColumns = new ArrayList<>(); for (String toColumn : newColumnNames) { FunctionCall<? extends FunctionMetaData> functionCall = Stream.of(aggregateFunctions.get(toColumn), numberingFunctions.get(toColumn)) .filter(java.util.Objects::nonNull) .findFirst() .get(); ColumnType type = functionCall.function.returnType(); Column<?> resultColumn = type.create(toColumn); newColumns.add(resultColumn); for (int i = 0; i < rowCount; i++) { resultColumn.appendMissing(); } } return newColumns; } @Override public String toString() { return toSqlString("?"); } static class FunctionCall<T extends FunctionMetaData> { private final String sourceColumnName; private final String destinationColumnName; private final T function; public String getSourceColumnName() { return sourceColumnName; } public String getDestinationColumnName() { return destinationColumnName; } public T getFunction() { return function; } public FunctionCall(String sourceColumnName, String destinationColumnName, T function) { this.sourceColumnName = sourceColumnName; this.destinationColumnName = destinationColumnName; this.function = function; } @Override public String toString() { return toSqlString(""); } public String toSqlString(String windowName) { String over = ""; if (!windowName.isEmpty()) { over = " OVER " + windowName; } return function.toString() + '(' + sourceColumnName + ")" + over + " AS " + destinationColumnName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FunctionCall<?> that = (FunctionCall<?>) o; return Objects.equal(sourceColumnName, that.sourceColumnName) && Objects.equal(destinationColumnName, that.destinationColumnName) && Objects.equal(function, that.function); } @Override public int hashCode() { return Objects.hashCode(sourceColumnName, destinationColumnName, function); } } static class Builder { // Maps the destination column name to aggregate function. private final Map<String, FunctionCall<AggregateFunctions>> aggregateFunctions = new HashMap<>(); // Maps the destination column name to aggregate function. private final Map<String, FunctionCall<NumberingFunctions>> numberingFunctions = new HashMap<>(); // Throws if a column with the same name is registered twice. private final Set<String> newColumnNames = new LinkedHashSet<>(); // Temporarily store analytic function data until the user calls 'as' to give the new column a // name // and save all the metadata. private String stagedFromColumn; private AggregateFunctions stagedAggregateFunction; private NumberingFunctions stagedNumberingFunction; private Builder() {} Builder stageFunction(String fromColumn, AggregateFunctions function) { checkNothingStaged(); Preconditions.checkNotNull(fromColumn); Preconditions.checkNotNull(function); this.stagedFromColumn = fromColumn; this.stagedAggregateFunction = function; return this; } Builder stageFunction(NumberingFunctions function) { checkNothingStaged(); Preconditions.checkNotNull(function); // Numbering functions do not have a from column. Use a placeholder instead. this.stagedFromColumn = "NUMBERING_FUNCTION_PLACEHOLDER"; this.stagedNumberingFunction = function; return this; } private void checkNothingStaged() { if (this.stagedFromColumn != null) { throw new IllegalArgumentException( "Cannot stage a column while another is staged. Must call unstage first"); } } private void checkForDuplicateAlias(String toColumn) { Preconditions.checkArgument( !newColumnNames.contains(toColumn), "Cannot add duplicate column name: " + toColumn); newColumnNames.add(toColumn); } Builder unStageFunction(String toColumn) { Preconditions.checkNotNull(stagedFromColumn); checkForDuplicateAlias(toColumn); if (stagedNumberingFunction != null) { Preconditions.checkNotNull(stagedNumberingFunction); this.numberingFunctions.put( toColumn, new FunctionCall<>("", toColumn, this.stagedNumberingFunction)); } else { Preconditions.checkNotNull(stagedAggregateFunction); this.aggregateFunctions.put( toColumn, new FunctionCall<>(this.stagedFromColumn, toColumn, this.stagedAggregateFunction)); } this.stagedNumberingFunction = null; this.stagedAggregateFunction = null; this.stagedFromColumn = null; return this; } ArgumentList build() { if (this.stagedFromColumn != null) { throw new IllegalStateException("Cannot build when a column is staged"); } return new ArgumentList(aggregateFunctions, numberingFunctions, newColumnNames); } } }
StringBuilder sb = new StringBuilder(); int colCount = 0; for (String newColName : newColumnNames) { String optionalNumberingCol = Optional.ofNullable(numberingFunctions.get(newColName)) .map(f -> f.toSqlString(windowName)) .orElse(""); String optionalAggregateCol = Optional.ofNullable(aggregateFunctions.get(newColName)) .map(f -> f.toSqlString(windowName)) .orElse(""); sb.append(optionalNumberingCol); sb.append(optionalAggregateCol); colCount++; if (colCount < newColumnNames.size()) { sb.append(","); sb.append(System.lineSeparator()); } } return sb.toString();
1,774
213
1,987
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/analytic/WindowSlider.java
WindowSlider
slideRightStrategy
class WindowSlider { private final boolean mirrored; private final WindowGrowthType windowGrowthType; private final int initialLeftBound; private final int initialRightBound; @SuppressWarnings({"unchecked", "rawtypes"}) private final AggregateFunction function; private final TableSlice slice; private final Column<?> sourceColumn; @SuppressWarnings({"unchecked", "rawtypes"}) private final Column destinationColumn; WindowSlider( WindowFrame windowFrame, AggregateFunctions func, TableSlice slice, Column<?> sourceColumn, Column<?> destinationColumn) { this.slice = slice; this.destinationColumn = destinationColumn; this.sourceColumn = sourceColumn; this.function = func.getImplementation(windowFrame.windowGrowthType()); // Convert UNBOUNDED FOLLOWING to an equivalent UNBOUNDED PRECEDING window. if (windowFrame.windowGrowthType() == WindowGrowthType.FIXED_RIGHT) { this.windowGrowthType = WindowGrowthType.FIXED_LEFT; this.mirrored = true; this.initialLeftBound = windowFrame.getInitialRightBound() * -1; this.initialRightBound = windowFrame.getInitialLeftBound() * -1; } else { this.mirrored = false; this.initialLeftBound = windowFrame.getInitialLeftBound(); this.initialRightBound = windowFrame.getInitialRightBound(); this.windowGrowthType = windowFrame.windowGrowthType(); } } /** Slide the window over the slice calculating an aggregate value for every row in the slice. */ @SuppressWarnings({"unchecked", "rawtypes"}) void execute() { initWindow(); // Initial window bounds can be outside the current slice. This allows for windows like 20 // PRECEDING 10 PRECEDING // to slide into the slice. Rows outside the slide will be ignored. int leftBound = getInitialLeftBound() - 1; int rightBound = getInitialRightBound(); for (int i = 0; i < slice.rowCount(); i++) { this.set(i, function.getValue()); // Slide the left side of the window if applicable for the window definition. int newLeftBound = slideLeftStrategy().apply(leftBound); if (newLeftBound > leftBound && isRowNumberInSlice(newLeftBound)) { // If the left side of the window changed remove the left most value from the aggregate // function. function.removeLeftMost(); } leftBound = newLeftBound; // Slide the right side of the window if applicable for the window definition. int newRightBound = slideRightStrategy().apply(rightBound); if (newRightBound > rightBound && isRowNumberInSlice(newRightBound)) { // If the right side of the window changed add the next value to the aggregate function. if (isMissing(newRightBound)) { function.addRightMostMissing(); } else { function.addRightMost(get(newRightBound)); } } rightBound = newRightBound; } } /** * Returns the mirrored index about the center of the window. Used to convert UNBOUNDED FOLLOWING * windows to UNBOUNDED PRECEDING windows. */ int mirror(int rowNumber) { if (this.mirrored) { return slice.rowCount() - rowNumber - 1; } return rowNumber; } /** * Adds initial values to the aggregate function for the first window. E.G. ROWS BETWEEN CURRENT * ROW AND 3 FOLLOWING would add the first four rows in the slice to the function. */ @SuppressWarnings({"unchecked", "rawtypes"}) private void initWindow() { int leftBound = Math.max(getInitialLeftBound(), 0); int rightBound = Math.min(getInitialRightBound(), slice.rowCount() - 1); for (int i = leftBound; i <= rightBound; i++) { if (isMissing(i)) { function.addRightMostMissing(); } else { function.addRightMost(get(i)); } } } /** Set the value in the destination column that corresponds to the row in the view. */ @SuppressWarnings({"unchecked", "rawtypes"}) private void set(int rowNumberInSlice, Object value) { destinationColumn.set(slice.mappedRowNumber(mirror(rowNumberInSlice)), value); } /** Get a value from the source column that corresponds to the row in the view. */ private Object get(int rowNumberInSlice) { return sourceColumn.get(slice.mappedRowNumber(mirror(rowNumberInSlice))); } /** * Determine if the value in the source column that corresponds to the row in the view is missing. */ private boolean isMissing(int rowNumberInSlice) { return sourceColumn.isMissing(slice.mappedRowNumber(mirror(rowNumberInSlice))); } /** Returns true of the rowNumber exists in the slice. */ private boolean isRowNumberInSlice(int rowNumber) { return rowNumber >= 0 && rowNumber < slice.rowCount(); } private Function<Integer, Integer> slideLeftStrategy() { switch (this.windowGrowthType) { case FIXED: case FIXED_LEFT: return i -> i; case SLIDING: return i -> i + 1; } throw new IllegalArgumentException("Unexpected growthType: " + this.windowGrowthType); } private Function<Integer, Integer> slideRightStrategy() {<FILL_FUNCTION_BODY>} private int getInitialLeftBound() { // is zero for FIXED and FIXED_LEFT windows. return this.initialLeftBound; } private int getInitialRightBound() { switch (this.windowGrowthType) { case FIXED: return slice.rowCount() - 1; case FIXED_LEFT: case SLIDING: return this.initialRightBound; } throw new IllegalArgumentException("Unexpected growthType: " + this.windowGrowthType); } }
switch (this.windowGrowthType) { case FIXED: return i -> i; case FIXED_LEFT: case SLIDING: return i -> i + 1; } throw new IllegalArgumentException("Unexpected growthType: " + this.windowGrowthType);
1,657
84
1,741
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/analytic/WindowSpecification.java
WindowSpecification
formatOrdering
class WindowSpecification { private final String windowName; private final Set<String> partitionColumns; private final Sort sort; private WindowSpecification(String windowName, Set<String> partitionColumns, Sort sort) { this.windowName = windowName; this.partitionColumns = partitionColumns; this.sort = sort; } static Builder builder() { return new Builder(); } public String toSqlString() { StringBuilder sb = new StringBuilder(); if (!partitionColumns.isEmpty()) { sb.append("PARTITION BY "); sb.append(String.join(", ", partitionColumns)); sb.append(System.lineSeparator()); } if (!sort.isEmpty()) { sb.append("ORDER BY "); sb.append( Streams.stream(sort.iterator()) .map(this::formatOrdering) .collect(Collectors.joining(", "))); } return sb.toString(); } public boolean isEmpty() { return partitionColumns.isEmpty() && sort == null; } @Override public String toString() { return this.toSqlString(); } public String getWindowName() { return windowName; } public Set<String> getPartitionColumns() { return partitionColumns; } public Optional<Sort> getSort() { return Optional.ofNullable(this.sort); } private String formatOrdering(Map.Entry<String, Sort.Order> sortEntry) {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WindowSpecification that = (WindowSpecification) o; return Objects.equal(windowName, that.windowName) && Objects.equal(partitionColumns, that.partitionColumns) && Objects.equal(sort, that.sort); } @Override public int hashCode() { return Objects.hashCode(windowName, partitionColumns, sort); } static class Builder { private String windowName = "w1"; private LinkedHashSet<String> partitioning = new LinkedHashSet<>(); private Sort sort = null; private Builder() {} Builder setWindowName(String windowName) { this.windowName = windowName; return this; } Builder setPartitionColumns(List<String> columns) { this.partitioning.clear(); this.partitioning.addAll(columns); Preconditions.checkArgument( partitioning.size() == columns.size(), "Partition by Columns cannot contain duplicate columns"); return this; } Builder setSort(Sort sort) { this.sort = sort; return this; } WindowSpecification build() { return new WindowSpecification(windowName, partitioning, sort); } } }
String formattedOrder = "ASC"; if (sortEntry.getValue() == Sort.Order.DESCEND) { formattedOrder = "DESC"; } return sortEntry.getKey() + " " + formattedOrder;
761
60
821
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/api/NumberColumn.java
NumberColumn
set
class NumberColumn<C extends NumberColumn<C, T>, T extends Number> extends AbstractColumn<C, T> implements NumericColumn<T> { private NumberColumnFormatter printFormatter = new NumberColumnFormatter(); protected Locale locale; protected final IntComparator comparator = (r1, r2) -> { final double f1 = getDouble(r1); final double f2 = getDouble(r2); return Double.compare(f1, f2); }; protected NumberColumn(final ColumnType type, final String name, AbstractColumnParser<T> parser) { super(type, name, parser); } protected abstract C createCol(final String name, int size); protected abstract C createCol(final String name); /** * Updates this column where values matching the selection are replaced with the corresponding * value from the given column */ public NumberColumn<C, T> set(DoublePredicate condition, NumberColumn<C, T> other) {<FILL_FUNCTION_BODY>} /** * Sets the value of all elements in this column matching condition to be equal to newValue and * returns this column */ public NumberColumn<C, T> set(DoublePredicate condition, T newValue) { for (int row = 0; row < size(); row++) { if (condition.test(getDouble(row))) { set(row, newValue); } } return this; } /** {@inheritDoc} */ @Override public void setPrintFormatter(NumberFormat format, String missingValueIndicator) { setPrintFormatter(new NumberColumnFormatter(format, missingValueIndicator)); } /** {@inheritDoc} */ @Override public void setPrintFormatter(final NumberColumnFormatter formatter) { this.printFormatter = formatter; formatter.setColumnType(type()); } /** Returns the NumbetPrintFormatter for this column, or null */ protected NumberColumnFormatter getPrintFormatter() { return printFormatter; } /** * Returns the largest ("top") n values in the column TODO(lwhite): Consider whether this should * exclude missing * * @param n The maximum number of records to return. The actual number will be smaller if n is * greater than the number of observations in the column * @return A list, possibly empty, of the largest observations */ public abstract NumericColumn<T> top(final int n); /** * Returns the smallest ("bottom") n values in the column TODO(lwhite): Consider whether this * should exclude missing * * @param n The maximum number of records to return. The actual number will be smaller if n is * greater than the number of observations in the column * @return A list, possibly empty, of the smallest n observations */ public abstract NumericColumn<T> bottom(final int n); /** {@inheritDoc} */ @Override public String getString(final int row) { final double value = getDouble(row); if (DoubleColumnType.valueIsMissing(value)) { return ""; } return String.valueOf(printFormatter.format(value)); } /** {@inheritDoc} */ @Override public C emptyCopy() { final C column = createCol(name()); column.setPrintFormatter(printFormatter); column.locale = locale; return column; } /** {@inheritDoc} */ @Override public C emptyCopy(final int rowSize) { final C column = createCol(name(), rowSize); column.setPrintFormatter(printFormatter); column.locale = locale; return column; } /** * Compares the given ints, which refer to the indexes of the doubles in this column, according to * the values of the doubles themselves */ @Override public IntComparator rowComparator() { return comparator; } /** {@inheritDoc} */ @Override public int byteSize() { return type().byteSize(); } /** Returns the count of missing values in this column */ @Override public int countMissing() { int count = 0; for (int i = 0; i < size(); i++) { if (isMissing(i)) { count++; } } return count; } }
for (int row = 0; row < size(); row++) { if (condition.test(getDouble(row))) { set(row, other.get(row)); } } return this;
1,135
57
1,192
<methods>public void <init>(tech.tablesaw.api.ColumnType, java.lang.String, AbstractColumnParser<T>) ,public tech.tablesaw.api.StringColumn asStringColumn() ,public abstract Column<T> emptyCopy() ,public C filter(Predicate<? super T>) ,public C first(int) ,public C inRange(int, int) ,public int indexOf(java.lang.Object) ,public C last(int) ,public int lastIndexOf(java.lang.Object) ,public C map(Function<? super T,? extends T>) ,public C max(Column<T>) ,public C min(Column<T>) ,public java.lang.String name() ,public AbstractColumnParser<T> parser() ,public C sampleN(int) ,public C sampleX(double) ,public C set(tech.tablesaw.selection.Selection, Column<T>) ,public C set(tech.tablesaw.selection.Selection, T) ,public C setName(java.lang.String) ,public C setParser(AbstractColumnParser<T>) ,public C sorted(Comparator<? super T>) ,public C subset(int[]) ,public java.lang.String toString() ,public tech.tablesaw.api.ColumnType type() <variables>public static final int DEFAULT_ARRAY_SIZE,private java.lang.String name,private AbstractColumnParser<T> parser,private final non-sealed tech.tablesaw.api.ColumnType type
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/AbstractColumn.java
AbstractColumn
lastIndexOf
class AbstractColumn<C extends Column<T>, T> implements Column<T> { public static final int DEFAULT_ARRAY_SIZE = 128; private String name; private final ColumnType type; private AbstractColumnParser<T> parser; /** * Constructs a column with the given {@link ColumnType}, name, and {@link AbstractColumnParser} */ public AbstractColumn(ColumnType type, final String name, final AbstractColumnParser<T> parser) { this.type = type; setParser(parser); setName(name); } /** {@inheritDoc} */ @Override public String name() { return name; } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C setName(final String name) { this.name = name.trim(); return (C) this; } /** {@inheritDoc} */ @Override public AbstractColumnParser<T> parser() { return parser; } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C setParser(final AbstractColumnParser<T> parser) { Preconditions.checkNotNull(parser); this.parser = parser; return (C) this; } /** {@inheritDoc} */ @Override public ColumnType type() { return type; } /** {@inheritDoc} */ @Override public abstract Column<T> emptyCopy(); /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C filter(Predicate<? super T> test) { return (C) Column.super.filter(test); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C sorted(Comparator<? super T> comp) { return (C) Column.super.sorted(comp); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C map(Function<? super T, ? extends T> fun) { return (C) Column.super.map(fun); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C min(Column<T> other) { return (C) Column.super.min(other); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C max(Column<T> other) { return (C) Column.super.max(other); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C set(Selection condition, Column<T> other) { return (C) Column.super.set(condition, other); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C set(Selection rowSelection, T newValue) { return (C) Column.super.set(rowSelection, newValue); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C first(int numRows) { return (C) Column.super.first(numRows); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C last(int numRows) { return (C) Column.super.last(numRows); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C sampleN(int n) { return (C) Column.super.sampleN(n); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C sampleX(double proportion) { return (C) Column.super.sampleX(proportion); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C subset(int[] rows) { return (C) Column.super.subset(rows); } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked", "rawtypes"}) public C inRange(int start, int end) { return (C) Column.super.inRange(start, end); } /** {@inheritDoc} */ @Override public String toString() { return type().getPrinterFriendlyName() + " column: " + name(); } /** {@inheritDoc} */ @Override public StringColumn asStringColumn() { StringColumn sc = StringColumn.create(name() + " strings"); for (int i = 0; i < size(); i++) { sc.append(getUnformattedString(i)); } return sc; } /** {@inheritDoc} */ @Override public int indexOf(final Object o) { return IntStream.range(0, size()).filter(i -> get(i).equals(o)).findFirst().orElse(-1); } /** {@inheritDoc} */ @Override public int lastIndexOf(Object o) {<FILL_FUNCTION_BODY>} }
return IntStream.iterate(size() - 1, i -> (i >= 0), i -> i - 1).filter(i -> get(i).equals(o)) .findFirst().orElse(-1);
1,445
59
1,504
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/AbstractColumnParser.java
AbstractColumnParser
remove
class AbstractColumnParser<T> { private final ColumnType columnType; protected List<String> missingValueStrings = TypeUtils.MISSING_INDICATORS; public AbstractColumnParser(ColumnType columnType) { this.columnType = columnType; } public abstract boolean canParse(String s); public abstract T parse(String s); public ColumnType columnType() { return columnType; } public boolean isMissing(String s) { if (s == null) { return true; } return s.isEmpty() || missingValueStrings.contains(s); } public byte parseByte(String s) { throw new UnsupportedOperationException( this.getClass().getSimpleName() + " doesn't support parsing to booleans"); } public int parseInt(String s) { throw new UnsupportedOperationException( this.getClass().getSimpleName() + " doesn't support parsing to ints"); } public short parseShort(String s) { throw new UnsupportedOperationException( this.getClass().getSimpleName() + " doesn't support parsing to shorts"); } public long parseLong(String s) { throw new UnsupportedOperationException( this.getClass().getSimpleName() + " doesn't support parsing to longs"); } public double parseDouble(String s) { throw new UnsupportedOperationException( this.getClass().getSimpleName() + " doesn't support parsing to doubles"); } public float parseFloat(String s) { throw new UnsupportedOperationException( this.getClass().getSimpleName() + " doesn't support parsing to floats"); } protected static String remove(final String str, final char remove) {<FILL_FUNCTION_BODY>} public void setMissingValueStrings(List<String> missingValueStrings) { this.missingValueStrings = missingValueStrings; } }
if (str == null || str.indexOf(remove) == -1) { return str; } final char[] chars = str.toCharArray(); int pos = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] != remove) { chars[pos++] = chars[i]; } } return new String(chars, 0, pos);
515
119
634
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/AbstractColumnType.java
AbstractColumnType
equals
class AbstractColumnType implements ColumnType { private final int byteSize; private final String name; private final String printerFriendlyName; protected AbstractColumnType(int byteSize, String name, String printerFriendlyName) { this.byteSize = byteSize; this.name = name; this.printerFriendlyName = printerFriendlyName; ColumnType.register(this); } /** {@inheritDoc} */ @Override public String toString() { return name; } /** {@inheritDoc} */ @Override public String name() { return name; } /** {@inheritDoc} */ public int byteSize() { return byteSize; } /** {@inheritDoc} */ @Override public String getPrinterFriendlyName() { return printerFriendlyName; } /** {@inheritDoc} */ @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hashCode(byteSize, name, printerFriendlyName); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractColumnType that = (AbstractColumnType) o; return byteSize == that.byteSize && Objects.equal(name, that.name) && Objects.equal(printerFriendlyName, that.printerFriendlyName);
303
95
398
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/SkipColumnType.java
SkipColumnType
create
class SkipColumnType extends AbstractColumnType { private static SkipColumnType INSTANCE; private SkipColumnType(int byteSize, String name, String printerFriendlyName) { super(byteSize, name, printerFriendlyName); } /** Returns the singleton instance of this class */ public static SkipColumnType instance() { if (INSTANCE == null) { INSTANCE = new SkipColumnType(0, "SKIP", "Skipped"); } return INSTANCE; } /** {@inheritDoc} */ @Override public Column<Void> create(String name) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public AbstractColumnParser<?> customParser(ReadOptions options) { throw new UnsupportedOperationException("Column type " + name() + " doesn't support parsing"); } /** This method is not supported. It will always throw {@link UnsupportedOperationException} */ public static Object missingValueIndicator() throws UnsupportedOperationException { throw new UnsupportedOperationException( "Column type " + SKIP + " doesn't support missing values"); } }
throw new UnsupportedOperationException( "Column type " + name() + " doesn't support column creation");
300
30
330
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/booleans/BooleanColumnType.java
BooleanColumnType
instance
class BooleanColumnType extends AbstractColumnType { public static final BooleanParser DEFAULT_PARSER = new BooleanParser(ColumnType.BOOLEAN); public static final byte MISSING_VALUE = (Byte) missingValueIndicator(); public static final byte BYTE_TRUE = 1; public static final byte BYTE_FALSE = 0; private static final byte BYTE_SIZE = 1; private static BooleanColumnType INSTANCE; private BooleanColumnType(int byteSize, String name, String printerFriendlyName) { super(byteSize, name, printerFriendlyName); } public static BooleanColumnType instance() {<FILL_FUNCTION_BODY>} @Override public BooleanColumn create(String name) { return BooleanColumn.create(name); } @Override public BooleanParser customParser(ReadOptions readOptions) { return new BooleanParser(this, readOptions); } public static byte missingValueIndicator() { return Byte.MIN_VALUE; } public static boolean valueIsMissing(byte value) { return value == missingValueIndicator(); } }
if (INSTANCE == null) { INSTANCE = new BooleanColumnType(BYTE_SIZE, "BOOLEAN", "Boolean"); } return INSTANCE;
290
48
338
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/booleans/BooleanFormatter.java
BooleanFormatter
format
class BooleanFormatter extends ColumnFormatter { private String trueString = "true"; private String falseString = "false"; public BooleanFormatter(String trueString, String falseString, String missingString) { super(missingString); this.trueString = trueString; this.falseString = falseString; } public BooleanFormatter(String trueString, String falseString) { super(""); this.trueString = trueString; this.falseString = falseString; } public BooleanFormatter(String missingString) { super(missingString); } public String format(Boolean value) { if (value == null) { return getMissingString(); } if (value) { return trueString; } return falseString; } public String format(byte value) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "BooleanFormatter{" + "trueString='" + trueString + '\'' + ", falseString='" + falseString + '\'' + ", missingString='" + getMissingString() + '\'' + '}'; } }
if (value == BooleanColumnType.MISSING_VALUE) { return getMissingString(); } if (value == (byte) 1) { return trueString; } return falseString;
317
58
375
<methods>public java.lang.String getMissingString() <variables>private final non-sealed java.lang.String missingString
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/booleans/BooleanParser.java
BooleanParser
parse
class BooleanParser extends AbstractColumnParser<Boolean> { // A more restricted set of 'false' strings that is used for column type detection private static final List<String> FALSE_STRINGS_FOR_DETECTION = Arrays.asList("F", "f", "N", "n", "FALSE", "false", "False"); // A more restricted set of 'true' strings that is used for column type detection private static final List<String> TRUE_STRINGS_FOR_DETECTION = Arrays.asList("T", "t", "Y", "y", "TRUE", "true", "True"); // These Strings will convert to true booleans private static final List<String> TRUE_STRINGS = Arrays.asList("T", "t", "Y", "y", "TRUE", "true", "True", "1"); // These Strings will convert to false booleans private static final List<String> FALSE_STRINGS = Arrays.asList("F", "f", "N", "n", "FALSE", "false", "False", "0"); public BooleanParser(ColumnType columnType) { super(columnType); } public BooleanParser(BooleanColumnType booleanColumnType, ReadOptions readOptions) { super(booleanColumnType); if (readOptions.missingValueIndicators().length > 0) { missingValueStrings = Lists.newArrayList(readOptions.missingValueIndicators()); } } @Override public boolean canParse(String s) { if (isMissing(s)) { return true; } return TRUE_STRINGS_FOR_DETECTION.contains(s) || FALSE_STRINGS_FOR_DETECTION.contains(s); } @Override public Boolean parse(String s) {<FILL_FUNCTION_BODY>} @Override public byte parseByte(String s) { if (isMissing(s)) { return MISSING_VALUE; } else if (TRUE_STRINGS.contains(s)) { return BYTE_TRUE; } else if (FALSE_STRINGS.contains(s)) { return BYTE_FALSE; } else { throw new IllegalArgumentException( "Attempting to convert non-boolean value " + s + " to Boolean"); } } }
if (isMissing(s)) { return null; } else if (TRUE_STRINGS.contains(s)) { return true; } else if (FALSE_STRINGS.contains(s)) { return false; } else { throw new IllegalArgumentException( "Attempting to convert non-boolean value " + s + " to Boolean"); }
590
95
685
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.lang.Boolean parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/booleans/fillers/BooleanIterable.java
BooleanIterable
iterator
class BooleanIterable implements it.unimi.dsi.fastutil.booleans.BooleanIterable { private final long bits; private final int length; private BooleanIterable(final long bits, final int length) { this.bits = bits; this.length = length; } public static BooleanIterable bits(final long bits, final int length) { return new BooleanIterable(bits, length); } @Override public BooleanIterator iterator() {<FILL_FUNCTION_BODY>} }
return new BooleanIterator() { int num = 0; boolean next = bit(num); private boolean bit(final int num) { return ((bits >> (length - num - 1)) & 1) == 1; } @Override public boolean hasNext() { return (num < length); } @Override public boolean nextBoolean() { final boolean current = next; num++; next = bit(num); return current; } };
139
134
273
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/dates/DateColumnFormatter.java
DateColumnFormatter
format
class DateColumnFormatter extends TemporalColumnFormatter { public DateColumnFormatter(DateTimeFormatter format) { super(format); } public DateColumnFormatter() { super(); } public DateColumnFormatter(DateTimeFormatter format, String missingValueString) { super(format, missingValueString); } public String format(int value) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "DateColumnFormatter{" + "format=" + getFormat() + ", missingString='" + getMissingString() + '\'' + '}'; } }
if (value == DateColumnType.missingValueIndicator()) { return getMissingString(); } if (getFormat() == null) { return toDateString(value); } LocalDate date = asLocalDate(value); if (date == null) { return ""; } return getFormat().format(date);
177
92
269
<methods>public java.time.format.DateTimeFormatter getFormat() <variables>private final non-sealed java.time.format.DateTimeFormatter format
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/dates/DateColumnType.java
DateColumnType
instance
class DateColumnType extends AbstractColumnType { public static final int BYTE_SIZE = 4; public static final DateParser DEFAULT_PARSER = new DateParser(ColumnType.LOCAL_DATE); private static DateColumnType INSTANCE; private DateColumnType(int byteSize, String name, String printerFriendlyName) { super(byteSize, name, printerFriendlyName); } public static DateColumnType instance() {<FILL_FUNCTION_BODY>} @Override public DateColumn create(String name) { return DateColumn.create(name); } @Override public AbstractColumnParser<LocalDate> customParser(ReadOptions options) { return new DateParser(this, options); } public static int missingValueIndicator() { return Integer.MIN_VALUE; } public static boolean valueIsMissing(int i) { return i == missingValueIndicator(); } }
if (INSTANCE == null) { INSTANCE = new DateColumnType(BYTE_SIZE, "LOCAL_DATE", "Date"); } return INSTANCE;
243
48
291
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/dates/DateParser.java
DateParser
parse
class DateParser extends AbstractColumnParser<LocalDate> { // Formats that we accept in parsing dates from strings private static final DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyyMMdd"); private static final DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MM/dd/yyyy"); private static final DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("MM-dd-yyyy"); private static final DateTimeFormatter dtf4 = DateTimeFormatter.ofPattern("MM.dd.yyyy"); private static final DateTimeFormatter dtf5 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final DateTimeFormatter dtf6 = DateTimeFormatter.ofPattern("yyyy/MM/dd"); private static final DateTimeFormatter dtf7 = DateTimeParser.caseInsensitiveFormatter("dd/MMM/yyyy"); private static final DateTimeFormatter dtf8 = DateTimeParser.caseInsensitiveFormatter("dd-MMM-yyyy"); private static final DateTimeFormatter dtf9 = DateTimeFormatter.ofPattern("M/d/yyyy"); private static final DateTimeFormatter dtf10 = DateTimeFormatter.ofPattern("M/d/yy"); private static final DateTimeFormatter dtf11 = DateTimeParser.caseInsensitiveFormatter("MMM/dd/yyyy"); private static final DateTimeFormatter dtf12 = DateTimeParser.caseInsensitiveFormatter("MMM-dd-yyyy"); private static final DateTimeFormatter dtf13 = DateTimeParser.caseInsensitiveFormatter("MMM/dd/yy"); private static final DateTimeFormatter dtf14 = DateTimeParser.caseInsensitiveFormatter("MMM-dd-yy"); private static final DateTimeFormatter dtf15 = DateTimeParser.caseInsensitiveFormatter("MMM/dd/yyyy"); private static final DateTimeFormatter dtf16 = DateTimeParser.caseInsensitiveFormatter("MMM/d/yyyy"); private static final DateTimeFormatter dtf17 = DateTimeParser.caseInsensitiveFormatter("MMM-dd-yy"); private static final DateTimeFormatter dtf18 = DateTimeParser.caseInsensitiveFormatter("MMM dd, yyyy"); private static final DateTimeFormatter dtf19 = DateTimeParser.caseInsensitiveFormatter("MMM d, yyyy"); // A formatter that handles all the date formats defined above public static final DateTimeFormatter DEFAULT_FORMATTER = new DateTimeFormatterBuilder() .appendOptional(dtf1) .appendOptional(dtf2) .appendOptional(dtf3) .appendOptional(dtf4) .appendOptional(dtf5) .appendOptional(dtf6) .appendOptional(dtf7) .appendOptional(dtf8) .appendOptional(dtf9) .appendOptional(dtf10) .appendOptional(dtf11) .appendOptional(dtf12) .appendOptional(dtf13) .appendOptional(dtf14) .appendOptional(dtf15) .appendOptional(dtf16) .appendOptional(dtf17) .appendOptional(dtf18) .appendOptional(dtf19) .toFormatter(); private Locale locale = Locale.getDefault(); private DateTimeFormatter formatter = DEFAULT_FORMATTER; public DateParser(ColumnType type, ReadOptions readOptions) { super(type); DateTimeFormatter readCsvFormatter = readOptions.dateFormatter(); if (readCsvFormatter != null) { formatter = readCsvFormatter; } if (readOptions.locale() != null) { locale = readOptions.locale(); } if (readOptions.missingValueIndicators().length > 0) { missingValueStrings = Lists.newArrayList(readOptions.missingValueIndicators()); } } public DateParser(ColumnType type) { super(type); } @Override public boolean canParse(String s) { if (isMissing(s)) { return true; } try { LocalDate.parse(s, formatter.withLocale(locale)); return true; } catch (DateTimeParseException e) { // it's all part of the plan return false; } } public void setCustomFormatter(DateTimeFormatter f) { formatter = f; } public void setLocale(Locale locale) { this.locale = locale; } @Override public LocalDate parse(String s) {<FILL_FUNCTION_BODY>} }
if (isMissing(s)) { return null; } return LocalDate.parse(s, formatter);
1,170
34
1,204
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.time.LocalDate parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/datetimes/DateTimeColumnFormatter.java
DateTimeColumnFormatter
format
class DateTimeColumnFormatter { private final DateTimeFormatter format; private String missingValueString = ""; public DateTimeColumnFormatter() { this.format = null; } public DateTimeColumnFormatter(DateTimeFormatter format) { this.format = format; } public DateTimeColumnFormatter(DateTimeFormatter format, String missingValueString) { this.format = format; this.missingValueString = missingValueString; } public String format(long value) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "DateTimeColumnFormatter{" + "format=" + format + ", missingValueString='" + missingValueString + '\'' + '}'; } }
if (value == DateTimeColumnType.missingValueIndicator()) { return missingValueString; } if (format == null) { return PackedLocalDateTime.toString(value); } LocalDateTime time = asLocalDateTime(value); if (time == null) { return ""; } return format.format(time);
204
92
296
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/datetimes/DateTimeColumnType.java
DateTimeColumnType
instance
class DateTimeColumnType extends AbstractColumnType { public static final int BYTE_SIZE = 8; public static final DateTimeParser DEFAULT_PARSER = new DateTimeParser(ColumnType.LOCAL_DATE_TIME); private static DateTimeColumnType INSTANCE = new DateTimeColumnType(BYTE_SIZE, "LOCAL_DATE_TIME", "DateTime"); private DateTimeColumnType(int byteSize, String name, String printerFriendlyName) { super(byteSize, name, printerFriendlyName); } public static DateTimeColumnType instance() {<FILL_FUNCTION_BODY>} @Override public DateTimeColumn create(String name) { return DateTimeColumn.create(name); } @Override public DateTimeParser customParser(ReadOptions options) { return new DateTimeParser(this, options); } public static long missingValueIndicator() { return Long.MIN_VALUE; } public static boolean valueIsMissing(long value) { return value == missingValueIndicator(); } }
if (INSTANCE == null) { INSTANCE = new DateTimeColumnType(BYTE_SIZE, "LOCAL_DATE_TIME", "DateTime"); } return INSTANCE;
266
50
316
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/datetimes/DateTimeParser.java
DateTimeParser
canParse
class DateTimeParser extends AbstractColumnParser<LocalDateTime> { private static final DateTimeFormatter dtTimef0 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 2014-07-09 13:03:44 private static final DateTimeFormatter dtTimef2 = DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss.S"); // 2014-07-09 13:03:44.7 (as above, but without leading 0 in // millis) private static final DateTimeFormatter dtTimef4 = caseInsensitiveFormatter("dd-MMM-yyyy HH:mm"); // 09-Jul-2014 13:03 private static final DateTimeFormatter dtTimef5 = DateTimeFormatter.ISO_LOCAL_DATE_TIME; private static final DateTimeFormatter dtTimef6; // ISO, with millis appended private static final DateTimeFormatter dtTimef7 = // 7/9/14 9:04 DateTimeFormatter.ofPattern("M/d/yy H:mm"); private static final DateTimeFormatter dtTimef8 = caseInsensitiveFormatter("M/d/yyyy h:mm:ss a"); // 7/9/2014 9:04:55 PM /** * Creates a Case-insensitive formatter using the specified pattern. * This method will create a formatter based on a simple pattern of letters and symbols as described in the class documentation. * For example, d MMM yyyy will format 2011-12-03 as '3 Dec 2011'. The formatter will use the default FORMAT locale. * This function can handle cases like am/AM, pm/PM, Jan/JAN, Feb/FEB etc * * @param pattern the pattern to use, not null * @return the formatter based on the pattern, not null * @throws IllegalArgumentException if the pattern is invalid */ public static DateTimeFormatter caseInsensitiveFormatter(String pattern) { return new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern(pattern).toFormatter(); } static { dtTimef6 = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME) .appendLiteral('.') .appendPattern("SSS") .toFormatter(); } // A formatter that handles date time formats defined above public static final DateTimeFormatter DEFAULT_FORMATTER = new DateTimeFormatterBuilder() .appendOptional(dtTimef7) .appendOptional(dtTimef8) .appendOptional(dtTimef2) .appendOptional(dtTimef4) .appendOptional(dtTimef0) .appendOptional(dtTimef5) .appendOptional(dtTimef6) .toFormatter(); private Locale locale = Locale.getDefault(); private DateTimeFormatter formatter = DEFAULT_FORMATTER; public DateTimeParser(ColumnType columnType) { super(columnType); } public DateTimeParser(DateTimeColumnType dateTimeColumnType, ReadOptions readOptions) { super(dateTimeColumnType); DateTimeFormatter readCsvFormatter = readOptions.dateTimeFormatter(); if (readCsvFormatter != null) { formatter = readCsvFormatter; } if (readOptions.locale() != null) { locale = readOptions.locale(); } if (readOptions.missingValueIndicators().length > 0) { missingValueStrings = Lists.newArrayList(readOptions.missingValueIndicators()); } } @Override public boolean canParse(String s) {<FILL_FUNCTION_BODY>} @Override public LocalDateTime parse(String value) { if (isMissing(value)) { return null; } String paddedValue = Strings.padStart(value, 4, '0'); return LocalDateTime.parse(paddedValue, formatter); } }
if (isMissing(s)) { return true; } try { LocalDateTime.parse(s, formatter.withLocale(locale)); return true; } catch (DateTimeParseException e) { // it's all part of the plan return false; }
1,045
78
1,123
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.time.LocalDateTime parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/instant/InstantColumnFormatter.java
InstantColumnFormatter
format
class InstantColumnFormatter extends TemporalColumnFormatter { private final ZoneId zoneId; public InstantColumnFormatter() { super(null); this.zoneId = ZoneOffset.UTC; } public InstantColumnFormatter(ZoneId zoneId) { super(null); this.zoneId = zoneId; } public InstantColumnFormatter(DateTimeFormatter format) { super(format); this.zoneId = ZoneOffset.UTC; } public InstantColumnFormatter(DateTimeFormatter format, ZoneId zoneId) { super(format); this.zoneId = zoneId; } public InstantColumnFormatter(DateTimeFormatter format, String missingValueString) { super(format, missingValueString); this.zoneId = ZoneOffset.UTC; } public InstantColumnFormatter( DateTimeFormatter format, ZoneId zoneId, String missingValueString) { super(format, missingValueString); this.zoneId = zoneId; } public String format(long value) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "InstantColumnFormatter{" + "format=" + getFormat() + ", missingValueString='" + getMissingString() + '\'' + '}'; } }
if (value == InstantColumnType.missingValueIndicator()) { return getMissingString(); } if (getFormat() == null) { return PackedInstant.toString(value); } Instant instant = PackedInstant.asInstant(value); if (instant == null) { return ""; } ZonedDateTime time = instant.atZone(zoneId); return getFormat().format(time);
360
117
477
<methods>public java.time.format.DateTimeFormatter getFormat() <variables>private final non-sealed java.time.format.DateTimeFormatter format
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/instant/InstantColumnType.java
InstantColumnType
instance
class InstantColumnType extends AbstractColumnType { public static final int BYTE_SIZE = 8; public static final InstantParser DEFAULT_PARSER = new InstantParser(ColumnType.INSTANT); private static InstantColumnType INSTANCE = new InstantColumnType(BYTE_SIZE, "INSTANT", "Instant"); private InstantColumnType(int byteSize, String name, String printerFriendlyName) { super(byteSize, name, printerFriendlyName); } public static InstantColumnType instance() {<FILL_FUNCTION_BODY>} public static boolean valueIsMissing(long value) { return value == missingValueIndicator(); } @Override public InstantColumn create(String name) { return InstantColumn.create(name); } @Override public InstantParser customParser(ReadOptions options) { return new InstantParser(this); } public static long missingValueIndicator() { return Long.MIN_VALUE; } }
if (INSTANCE == null) { INSTANCE = new InstantColumnType(BYTE_SIZE, "INSTANT", "Instant"); } return INSTANCE;
266
48
314
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/instant/InstantParser.java
InstantParser
canParse
class InstantParser extends AbstractColumnParser<Instant> { public InstantParser(ColumnType columnType) { super(columnType); } @Override public boolean canParse(String s) {<FILL_FUNCTION_BODY>} @Override public Instant parse(String value) { return Instant.parse(value); } }
if (isMissing(s)) { return true; } try { parse(s); return true; } catch (RuntimeException e) { return false; }
97
54
151
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.time.Instant parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/instant/PackedInstant.java
PackedInstant
asInstant
class PackedInstant { protected PackedInstant() {} public static Instant asInstant(long dateTime) {<FILL_FUNCTION_BODY>} protected static long pack(LocalDate date, LocalTime time) { if (date == null || time == null) { return missingValueIndicator(); } int d = PackedLocalDate.pack(date); int t = PackedLocalTime.pack(time); return (((long) d) << 32) | (t & 0xffffffffL); } public static long pack(Instant instant) { if (instant == null) { return missingValueIndicator(); } LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC); LocalDate date = dateTime.toLocalDate(); LocalTime time = dateTime.toLocalTime(); return (pack(date, time)); } public static int date(long packedDateTIme) { return (int) (packedDateTIme >> 32); } public static int time(long packedDateTIme) { return (int) packedDateTIme; } public static String toString(long dateTime) { if (dateTime == Long.MIN_VALUE) { return ""; } int date = date(dateTime); int time = time(dateTime); return "" + PackedLocalDate.getYear(date) + "-" + Strings.padStart(Byte.toString(PackedLocalDate.getMonthValue(date)), 2, '0') + "-" + Strings.padStart(Byte.toString(PackedLocalDate.getDayOfMonth(date)), 2, '0') + "T" + Strings.padStart(Byte.toString(PackedLocalTime.getHour(time)), 2, '0') + ":" + Strings.padStart(Byte.toString(PackedLocalTime.getMinute(time)), 2, '0') + ":" + Strings.padStart(Byte.toString(PackedLocalTime.getSecond(time)), 2, '0') + "." + Strings.padStart(String.valueOf(PackedLocalTime.getMilliseconds(time)), 3, '0') + "Z"; } /** * Returns the given packedDateTime with amtToAdd of temporal units added * * <p>TODO(lwhite): Replace with a native implementation that doesn't convert everything to * Instant */ public static long plus(long packedDateTime, long amountToAdd, TemporalUnit unit) { Instant dateTime = asInstant(packedDateTime); if (dateTime == null) { throw new IllegalArgumentException("Cannot do addition on missing value"); } return pack(dateTime.plus(amountToAdd, unit)); } public static boolean isAfter(long packedDateTime, long value) { return (packedDateTime != missingValueIndicator()) && packedDateTime > value; } public static boolean isBefore(long packedDateTime, long value) { return (packedDateTime != missingValueIndicator()) && packedDateTime < value; } public static long create(int date, int time) { return (((long) date) << 32) | (time & 0xffffffffL); } // TODO: packed support for minutesUntil and hoursUnit. These implementations are inefficient public static long minutesUntil(long packedDateTimeEnd, long packedDateTimeStart) { return ChronoUnit.MINUTES.between(asInstant(packedDateTimeStart), asInstant(packedDateTimeEnd)); } public static long hoursUntil(long packedDateTimeEnd, long packedDateTimeStart) { return ChronoUnit.HOURS.between(asInstant(packedDateTimeStart), asInstant(packedDateTimeEnd)); } public static int daysUntil(long packedDateTimeEnd, long packedDateTimeStart) { return (int) (PackedLocalDate.toEpochDay(date(packedDateTimeEnd)) - PackedLocalDate.toEpochDay(date(packedDateTimeStart))); } public static int weeksUntil(long packedDateTimeEnd, long packedDateStart) { return daysUntil(packedDateTimeEnd, packedDateStart) / 7; } public static boolean isEqualTo(long packedDateTime, long value) { return DateTimePredicates.isEqualTo.test(packedDateTime, value); } public static boolean isOnOrAfter(long valueToTest, long valueToTestAgainst) { return valueToTest >= valueToTestAgainst; } public static boolean isOnOrBefore(long valueToTest, long valueToTestAgainst) { return isBefore(valueToTest, valueToTestAgainst) || isEqualTo(valueToTest, valueToTestAgainst); } }
if (dateTime == missingValueIndicator()) { return null; } int date = date(dateTime); int time = time(dateTime); LocalDate d = PackedLocalDate.asLocalDate(date); LocalTime t = PackedLocalTime.asLocalTime(time); if (d == null || t == null) { return null; } return LocalDateTime.of(d, t).toInstant(ZoneOffset.UTC);
1,243
122
1,365
<no_super_class>
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/DoubleColumnType.java
DoubleColumnType
instance
class DoubleColumnType extends AbstractColumnType { private static final int BYTE_SIZE = 8; /** Returns the default parser for DoubleColumn */ public static final DoubleParser DEFAULT_PARSER = new DoubleParser(ColumnType.DOUBLE); private static DoubleColumnType INSTANCE = new DoubleColumnType(BYTE_SIZE, "DOUBLE", "Double"); /** Returns the singleton instance of DoubleColumnType */ public static DoubleColumnType instance() {<FILL_FUNCTION_BODY>} private DoubleColumnType(int byteSize, String name, String printerFriendlyName) { super(byteSize, name, printerFriendlyName); } /** {@inheritDoc} */ @Override public DoubleColumn create(String name) { return DoubleColumn.create(name); } /** {@inheritDoc} */ @Override public DoubleParser customParser(ReadOptions options) { return new DoubleParser(this, options); } /** Returns true if the given value is the missing value indicator for this column type */ public static boolean valueIsMissing(double value) { return Double.isNaN(value); } /** * Returns the missing value indicator for this column type NOTE: Clients should use {@link * DoubleColumnType#valueIsMissing(double)} to test for missing value indicators */ public static double missingValueIndicator() { return Double.NaN; } }
if (INSTANCE == null) { INSTANCE = new DoubleColumnType(BYTE_SIZE, "DOUBLE", "Double"); } return INSTANCE;
362
47
409
<methods>public int byteSize() ,public boolean equals(java.lang.Object) ,public java.lang.String getPrinterFriendlyName() ,public int hashCode() ,public java.lang.String name() ,public java.lang.String toString() <variables>private final non-sealed int byteSize,private final non-sealed java.lang.String name,private final non-sealed java.lang.String printerFriendlyName
jtablesaw_tablesaw
tablesaw/core/src/main/java/tech/tablesaw/columns/numbers/DoubleParser.java
DoubleParser
isPercent
class DoubleParser extends AbstractColumnParser<Double> { public DoubleParser(ColumnType columnType) { super(columnType); } public DoubleParser(DoubleColumnType doubleColumnType, ReadOptions readOptions) { super(doubleColumnType); if (readOptions.missingValueIndicators().length > 0) { missingValueStrings = Lists.newArrayList(readOptions.missingValueIndicators()); } } @Override public boolean canParse(String s) { if (isMissing(s)) { return true; } try { if (isPercent(AbstractColumnParser.remove(s, ','))) { s = AbstractColumnParser.remove(s, ','); Number number = NumberFormat.getPercentInstance().parse(s); } else { Double.parseDouble(AbstractColumnParser.remove(s, ',')); } return true; } catch (NumberFormatException | ParseException | IndexOutOfBoundsException e) { // it's all part of the plan return false; } } @Override public Double parse(String s) { return parseDouble(s); } @Override public double parseDouble(String s) { if (isMissing(s)) { return DoubleColumnType.missingValueIndicator(); } if (isPercent(AbstractColumnParser.remove(s, ','))) { s = AbstractColumnParser.remove(s, ',').substring(0, s.length() - 1); return Double.parseDouble(s) / 100.0; } return Double.parseDouble(AbstractColumnParser.remove(s, ',')); } /** * A number is percent when it ends with % * - We can trim off the last occurrence of '%' * - The remaining string should then be parsable as a number(double) * * @param s Value * @return Flag returning whether the input is a percent or not */ private boolean isPercent(String s) {<FILL_FUNCTION_BODY>} }
boolean containsPercentSymbol = s.charAt(s.length() - 1) == '%'; if (containsPercentSymbol) { String percentageValue = s.substring(0, s.length() - 1); try { double value = Double.parseDouble(percentageValue); return !Double.isNaN(value); } catch (NumberFormatException e) { // it's all part of the plan return false; } } return false;
536
126
662
<methods>public void <init>(tech.tablesaw.api.ColumnType) ,public abstract boolean canParse(java.lang.String) ,public tech.tablesaw.api.ColumnType columnType() ,public boolean isMissing(java.lang.String) ,public abstract java.lang.Double parse(java.lang.String) ,public byte parseByte(java.lang.String) ,public double parseDouble(java.lang.String) ,public float parseFloat(java.lang.String) ,public int parseInt(java.lang.String) ,public long parseLong(java.lang.String) ,public short parseShort(java.lang.String) ,public void setMissingValueStrings(List<java.lang.String>) <variables>private final non-sealed tech.tablesaw.api.ColumnType columnType,protected List<java.lang.String> missingValueStrings