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
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/BookComment.java
BookComment
toString
class BookComment implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 评论小说ID */ private Long bookId; /** * 评论用户ID */ private Long userId; /** * 评价内容 */ private String commentContent; /** * 回复数量 */ private Integer replyCount; /** * 审核状态;0-待审核 1-审核通过 2-审核不通过 */ private Integer auditStatus; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getBookId() { return bookId; } public void setBookId(Long bookId) { this.bookId = bookId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getCommentContent() { return commentContent; } public void setCommentContent(String commentContent) { this.commentContent = commentContent; } public Integer getReplyCount() { return replyCount; } public void setReplyCount(Integer replyCount) { this.replyCount = replyCount; } public Integer getAuditStatus() { return auditStatus; } public void setAuditStatus(Integer auditStatus) { this.auditStatus = auditStatus; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BookComment{" + "id=" + id + ", bookId=" + bookId + ", userId=" + userId + ", commentContent=" + commentContent + ", replyCount=" + replyCount + ", auditStatus=" + auditStatus + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
627
102
729
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/BookCommentCopy1.java
BookCommentCopy1
toString
class BookCommentCopy1 implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 评论小说ID */ private Long bookId; /** * 评论用户ID */ private Long userId; /** * 评价内容 */ private String commentContent; /** * 回复数量 */ private Integer replyCount; /** * 审核状态;0-待审核 1-审核通过 2-审核不通过 */ private Integer auditStatus; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getBookId() { return bookId; } public void setBookId(Long bookId) { this.bookId = bookId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getCommentContent() { return commentContent; } public void setCommentContent(String commentContent) { this.commentContent = commentContent; } public Integer getReplyCount() { return replyCount; } public void setReplyCount(Integer replyCount) { this.replyCount = replyCount; } public Integer getAuditStatus() { return auditStatus; } public void setAuditStatus(Integer auditStatus) { this.auditStatus = auditStatus; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BookCommentCopy1{" + "id=" + id + ", bookId=" + bookId + ", userId=" + userId + ", commentContent=" + commentContent + ", replyCount=" + replyCount + ", auditStatus=" + auditStatus + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
629
104
733
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/BookCommentReply.java
BookCommentReply
toString
class BookCommentReply implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ private Long id; /** * 评论ID */ private Long commentId; /** * 回复用户ID */ private Long userId; /** * 回复内容 */ private String replyContent; /** * 审核状态;0-待审核 1-审核通过 2-审核不通过 */ private Integer auditStatus; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCommentId() { return commentId; } public void setCommentId(Long commentId) { this.commentId = commentId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getReplyContent() { return replyContent; } public void setReplyContent(String replyContent) { this.replyContent = replyContent; } public Integer getAuditStatus() { return auditStatus; } public void setAuditStatus(Integer auditStatus) { this.auditStatus = auditStatus; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BookCommentReply{" + "id=" + id + ", commentId=" + commentId + ", userId=" + userId + ", replyContent=" + replyContent + ", auditStatus=" + auditStatus + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
544
93
637
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/BookContent.java
BookContent
toString
class BookContent implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 章节ID */ private Long chapterId; /** * 小说章节内容 */ private String content; private LocalDateTime createTime; private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getChapterId() { return chapterId; } public void setChapterId(Long chapterId) { this.chapterId = chapterId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BookContent{" + "id=" + id + ", chapterId=" + chapterId + ", content=" + content + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
371
67
438
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/BookInfo.java
BookInfo
toString
class BookInfo implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 作品方向;0-男频 1-女频 */ private Integer workDirection; /** * 类别ID */ private Long categoryId; /** * 类别名 */ private String categoryName; /** * 小说封面地址 */ private String picUrl; /** * 小说名 */ private String bookName; /** * 作家id */ private Long authorId; /** * 作家名 */ private String authorName; /** * 书籍描述 */ private String bookDesc; /** * 评分;总分:10 ,真实评分 = score/10 */ private Integer score; /** * 书籍状态;0-连载中 1-已完结 */ private Integer bookStatus; /** * 点击量 */ private Long visitCount; /** * 总字数 */ private Integer wordCount; /** * 评论数 */ private Integer commentCount; /** * 最新章节ID */ private Long lastChapterId; /** * 最新章节名 */ private String lastChapterName; /** * 最新章节更新时间 */ private LocalDateTime lastChapterUpdateTime; /** * 是否收费;1-收费 0-免费 */ private Integer isVip; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getWorkDirection() { return workDirection; } public void setWorkDirection(Integer workDirection) { this.workDirection = workDirection; } public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public Long getAuthorId() { return authorId; } public void setAuthorId(Long authorId) { this.authorId = authorId; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getBookDesc() { return bookDesc; } public void setBookDesc(String bookDesc) { this.bookDesc = bookDesc; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public Integer getBookStatus() { return bookStatus; } public void setBookStatus(Integer bookStatus) { this.bookStatus = bookStatus; } public Long getVisitCount() { return visitCount; } public void setVisitCount(Long visitCount) { this.visitCount = visitCount; } public Integer getWordCount() { return wordCount; } public void setWordCount(Integer wordCount) { this.wordCount = wordCount; } public Integer getCommentCount() { return commentCount; } public void setCommentCount(Integer commentCount) { this.commentCount = commentCount; } public Long getLastChapterId() { return lastChapterId; } public void setLastChapterId(Long lastChapterId) { this.lastChapterId = lastChapterId; } public String getLastChapterName() { return lastChapterName; } public void setLastChapterName(String lastChapterName) { this.lastChapterName = lastChapterName; } public LocalDateTime getLastChapterUpdateTime() { return lastChapterUpdateTime; } public void setLastChapterUpdateTime(LocalDateTime lastChapterUpdateTime) { this.lastChapterUpdateTime = lastChapterUpdateTime; } public Integer getIsVip() { return isVip; } public void setIsVip(Integer isVip) { this.isVip = isVip; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "BookInfo{" + "id=" + id + ", workDirection=" + workDirection + ", categoryId=" + categoryId + ", categoryName=" + categoryName + ", picUrl=" + picUrl + ", bookName=" + bookName + ", authorId=" + authorId + ", authorName=" + authorName + ", bookDesc=" + bookDesc + ", score=" + score + ", bookStatus=" + bookStatus + ", visitCount=" + visitCount + ", wordCount=" + wordCount + ", commentCount=" + commentCount + ", lastChapterId=" + lastChapterId + ", lastChapterName=" + lastChapterName + ", lastChapterUpdateTime=" + lastChapterUpdateTime + ", isVip=" + isVip + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
1,485
242
1,727
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/HomeBook.java
HomeBook
toString
class HomeBook implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 推荐类型;0-轮播图 1-顶部栏 2-本周强推 3-热门推荐 4-精品推荐 */ private Integer type; /** * 推荐排序 */ private Integer sort; /** * 推荐小说ID */ private Long bookId; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Long getBookId() { return bookId; } public void setBookId(Long bookId) { this.bookId = bookId; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "HomeBook{" + "id=" + id + ", type=" + type + ", sort=" + sort + ", bookId=" + bookId + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
471
76
547
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/HomeFriendLink.java
HomeFriendLink
toString
class HomeFriendLink implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 链接名 */ private String linkName; /** * 链接url */ private String linkUrl; /** * 排序号 */ private Integer sort; /** * 是否开启;0-不开启 1-开启 */ private Integer isOpen; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLinkName() { return linkName; } public void setLinkName(String linkName) { this.linkName = linkName; } public String getLinkUrl() { return linkUrl; } public void setLinkUrl(String linkUrl) { this.linkUrl = linkUrl; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Integer getIsOpen() { return isOpen; } public void setIsOpen(Integer isOpen) { this.isOpen = isOpen; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "HomeFriendLink{" + "id=" + id + ", linkName=" + linkName + ", linkUrl=" + linkUrl + ", sort=" + sort + ", isOpen=" + isOpen + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
524
90
614
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/NewsCategory.java
NewsCategory
toString
class NewsCategory implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 类别名 */ private String name; /** * 排序 */ private Integer sort; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "NewsCategory{" + "id=" + id + ", name=" + name + ", sort=" + sort + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
373
65
438
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/NewsContent.java
NewsContent
toString
class NewsContent implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 新闻ID */ private Long newsId; /** * 新闻内容 */ private String content; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getNewsId() { return newsId; } public void setNewsId(Long newsId) { this.newsId = newsId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "NewsContent{" + "id=" + id + ", newsId=" + newsId + ", content=" + content + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
391
67
458
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/NewsInfo.java
NewsInfo
toString
class NewsInfo implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 类别ID */ private Long categoryId; /** * 类别名 */ private String categoryName; /** * 新闻来源 */ private String sourceName; /** * 新闻标题 */ private String title; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getSourceName() { return sourceName; } public void setSourceName(String sourceName) { this.sourceName = sourceName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "NewsInfo{" + "id=" + id + ", categoryId=" + categoryId + ", categoryName=" + categoryName + ", sourceName=" + sourceName + ", title=" + title + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
526
89
615
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/PayAlipay.java
PayAlipay
toString
class PayAlipay implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 商户订单号 */ private String outTradeNo; /** * 支付宝交易号 */ private String tradeNo; /** * 买家支付宝账号 ID */ private String buyerId; /** * 交易状态;TRADE_SUCCESS-交易成功 */ private String tradeStatus; /** * 订单金额;单位:分 */ private Integer totalAmount; /** * 实收金额;单位:分 */ private Integer receiptAmount; /** * 开票金额 */ private Integer invoiceAmount; /** * 交易创建时间 */ private LocalDateTime gmtCreate; /** * 交易付款时间 */ private LocalDateTime gmtPayment; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getOutTradeNo() { return outTradeNo; } public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getTradeNo() { return tradeNo; } public void setTradeNo(String tradeNo) { this.tradeNo = tradeNo; } public String getBuyerId() { return buyerId; } public void setBuyerId(String buyerId) { this.buyerId = buyerId; } public String getTradeStatus() { return tradeStatus; } public void setTradeStatus(String tradeStatus) { this.tradeStatus = tradeStatus; } public Integer getTotalAmount() { return totalAmount; } public void setTotalAmount(Integer totalAmount) { this.totalAmount = totalAmount; } public Integer getReceiptAmount() { return receiptAmount; } public void setReceiptAmount(Integer receiptAmount) { this.receiptAmount = receiptAmount; } public Integer getInvoiceAmount() { return invoiceAmount; } public void setInvoiceAmount(Integer invoiceAmount) { this.invoiceAmount = invoiceAmount; } public LocalDateTime getGmtCreate() { return gmtCreate; } public void setGmtCreate(LocalDateTime gmtCreate) { this.gmtCreate = gmtCreate; } public LocalDateTime getGmtPayment() { return gmtPayment; } public void setGmtPayment(LocalDateTime gmtPayment) { this.gmtPayment = gmtPayment; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "PayAlipay{" + "id=" + id + ", outTradeNo=" + outTradeNo + ", tradeNo=" + tradeNo + ", buyerId=" + buyerId + ", tradeStatus=" + tradeStatus + ", totalAmount=" + totalAmount + ", receiptAmount=" + receiptAmount + ", invoiceAmount=" + invoiceAmount + ", gmtCreate=" + gmtCreate + ", gmtPayment=" + gmtPayment + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
962
160
1,122
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/PayWechat.java
PayWechat
toString
class PayWechat implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 商户订单号 */ private String outTradeNo; /** * 微信支付订单号 */ private String transactionId; /** * 交易类型;JSAPI-公众号支付 NATIVE-扫码支付 APP-APP支付 MICROPAY-付款码支付 MWEB-H5支付 FACEPAY-刷脸支付 */ private String tradeType; /** * 交易状态;SUCCESS-支付成功 REFUND-转入退款 NOTPAY-未支付 CLOSED-已关闭 REVOKED-已撤销(付款码支付) USERPAYING-用户支付中(付款码支付) PAYERROR-支付失败(其他原因,如银行返回失败) */ private String tradeState; /** * 交易状态描述 */ private String tradeStateDesc; /** * 订单总金额;单位:分 */ private Integer amount; /** * 用户支付金额;单位:分 */ private Integer payerTotal; /** * 支付完成时间 */ private LocalDateTime successTime; /** * 支付者用户标识;用户在直连商户appid下的唯一标识 */ private String payerOpenid; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getOutTradeNo() { return outTradeNo; } public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public String getTradeType() { return tradeType; } public void setTradeType(String tradeType) { this.tradeType = tradeType; } public String getTradeState() { return tradeState; } public void setTradeState(String tradeState) { this.tradeState = tradeState; } public String getTradeStateDesc() { return tradeStateDesc; } public void setTradeStateDesc(String tradeStateDesc) { this.tradeStateDesc = tradeStateDesc; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public Integer getPayerTotal() { return payerTotal; } public void setPayerTotal(Integer payerTotal) { this.payerTotal = payerTotal; } public LocalDateTime getSuccessTime() { return successTime; } public void setSuccessTime(LocalDateTime successTime) { this.successTime = successTime; } public String getPayerOpenid() { return payerOpenid; } public void setPayerOpenid(String payerOpenid) { this.payerOpenid = payerOpenid; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "PayWechat{" + "id=" + id + ", outTradeNo=" + outTradeNo + ", transactionId=" + transactionId + ", tradeType=" + tradeType + ", tradeState=" + tradeState + ", tradeStateDesc=" + tradeStateDesc + ", amount=" + amount + ", payerTotal=" + payerTotal + ", successTime=" + successTime + ", payerOpenid=" + payerOpenid + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
1,067
157
1,224
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/SysLog.java
SysLog
toString
class SysLog implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 用户id */ private Long userId; /** * 用户名 */ private String username; /** * 用户操作 */ private String operation; /** * 响应时间 */ private Integer time; /** * 请求方法 */ private String method; /** * 请求参数 */ private String params; /** * IP地址 */ private String ip; /** * 创建时间 */ private LocalDateTime createTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; } public Integer getTime() { return time; } public void setTime(Integer time) { this.time = time; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getParams() { return params; } public void setParams(String params) { this.params = params; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SysLog{" + "id=" + id + ", userId=" + userId + ", username=" + username + ", operation=" + operation + ", time=" + time + ", method=" + method + ", params=" + params + ", ip=" + ip + ", createTime=" + createTime + "}";
610
102
712
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/SysMenu.java
SysMenu
toString
class SysMenu implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 父菜单ID;一级菜单为0 */ private Long parentId; /** * 菜单名称 */ private String name; /** * 菜单URL */ private String url; /** * 类型;0-目录 1-菜单 */ private Integer type; /** * 菜单图标 */ private String icon; /** * 排序 */ private Integer sort; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SysMenu{" + "id=" + id + ", parentId=" + parentId + ", name=" + name + ", url=" + url + ", type=" + type + ", icon=" + icon + ", sort=" + sort + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
639
104
743
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/SysRole.java
SysRole
toString
class SysRole implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 角色名称 */ private String roleName; /** * 角色标识 */ private String roleSign; /** * 备注 */ private String remark; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleSign() { return roleSign; } public void setRoleSign(String roleSign) { this.roleSign = roleSign; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SysRole{" + "id=" + id + ", roleName=" + roleName + ", roleSign=" + roleSign + ", remark=" + remark + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
450
79
529
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/SysRoleMenu.java
SysRoleMenu
toString
class SysRoleMenu implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 角色ID */ private Long roleId; /** * 菜单ID */ private Long menuId; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } public Long getMenuId() { return menuId; } public void setMenuId(Long menuId) { this.menuId = menuId; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SysRoleMenu{" + "id=" + id + ", roleId=" + roleId + ", menuId=" + menuId + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
389
71
460
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/SysUser.java
SysUser
toString
class SysUser implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 用户名 */ private String username; /** * 密码 */ private String password; /** * 真实姓名 */ private String name; /** * 性别;0-男 1-女 */ private Integer sex; /** * 出身日期 */ private LocalDateTime birth; /** * 邮箱 */ private String email; /** * 手机号 */ private String mobile; /** * 状态;0-禁用 1-正常 */ private Integer status; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public LocalDateTime getBirth() { return birth; } public void setBirth(LocalDateTime birth) { this.birth = birth; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SysUser{" + "id=" + id + ", username=" + username + ", password=" + password + ", name=" + name + ", sex=" + sex + ", birth=" + birth + ", email=" + email + ", mobile=" + mobile + ", status=" + status + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
756
120
876
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/SysUserRole.java
SysUserRole
toString
class SysUserRole implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 用户ID */ private Long userId; /** * 角色ID */ private Long roleId; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SysUserRole{" + "id=" + id + ", userId=" + userId + ", roleId=" + roleId + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
388
71
459
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/UserBookshelf.java
UserBookshelf
toString
class UserBookshelf implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 用户ID */ private Long userId; /** * 小说ID */ private Long bookId; /** * 上一次阅读的章节内容表ID */ private Long preContentId; /** * 创建时间; */ private LocalDateTime createTime; /** * 更新时间; */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getBookId() { return bookId; } public void setBookId(Long bookId) { this.bookId = bookId; } public Long getPreContentId() { return preContentId; } public void setPreContentId(Long preContentId) { this.preContentId = preContentId; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserBookshelf{" + "id=" + id + ", userId=" + userId + ", bookId=" + bookId + ", preContentId=" + preContentId + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
483
85
568
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/UserComment.java
UserComment
toString
class UserComment implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 评论用户ID */ private Long userId; /** * 评论小说ID */ private Long bookId; /** * 评价内容 */ private String commentContent; /** * 回复数量 */ private Integer replyCount; /** * 审核状态;0-待审核 1-审核通过 2-审核不通过 */ private Integer auditStatus; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getBookId() { return bookId; } public void setBookId(Long bookId) { this.bookId = bookId; } public String getCommentContent() { return commentContent; } public void setCommentContent(String commentContent) { this.commentContent = commentContent; } public Integer getReplyCount() { return replyCount; } public void setReplyCount(Integer replyCount) { this.replyCount = replyCount; } public Integer getAuditStatus() { return auditStatus; } public void setAuditStatus(Integer auditStatus) { this.auditStatus = auditStatus; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserComment{" + "id=" + id + ", userId=" + userId + ", bookId=" + bookId + ", commentContent=" + commentContent + ", replyCount=" + replyCount + ", auditStatus=" + auditStatus + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
627
102
729
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/UserCommentReply.java
UserCommentReply
toString
class UserCommentReply implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ private Long id; /** * 评论ID */ private Long commentId; /** * 回复用户ID */ private Long userId; /** * 回复内容 */ private String replyContent; /** * 审核状态;0-待审核 1-审核通过 2-审核不通过 */ private Integer auditStatus; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCommentId() { return commentId; } public void setCommentId(Long commentId) { this.commentId = commentId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getReplyContent() { return replyContent; } public void setReplyContent(String replyContent) { this.replyContent = replyContent; } public Integer getAuditStatus() { return auditStatus; } public void setAuditStatus(Integer auditStatus) { this.auditStatus = auditStatus; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserCommentReply{" + "id=" + id + ", commentId=" + commentId + ", userId=" + userId + ", replyContent=" + replyContent + ", auditStatus=" + auditStatus + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
544
93
637
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/UserConsumeLog.java
UserConsumeLog
toString
class UserConsumeLog implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 消费用户ID */ private Long userId; /** * 消费使用的金额;单位:屋币 */ private Integer amount; /** * 消费商品类型;0-小说VIP章节 */ private Integer productType; /** * 消费的的商品ID;例如:章节ID */ private Long productId; /** * 消费的的商品名;例如:章节名 */ private String producName; /** * 消费的的商品值;例如:1 */ private Integer producValue; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public Integer getProductType() { return productType; } public void setProductType(Integer productType) { this.productType = productType; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getProducName() { return producName; } public void setProducName(String producName) { this.producName = producName; } public Integer getProducValue() { return producValue; } public void setProducValue(Integer producValue) { this.producValue = producValue; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserConsumeLog{" + "id=" + id + ", userId=" + userId + ", amount=" + amount + ", productType=" + productType + ", productId=" + productId + ", producName=" + producName + ", producValue=" + producValue + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
717
117
834
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/UserFeedback.java
UserFeedback
toString
class UserFeedback implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 反馈用户id */ private Long userId; /** * 反馈内容 */ private String content; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserFeedback{" + "id=" + id + ", userId=" + userId + ", content=" + content + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
383
68
451
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/UserInfo.java
UserInfo
toString
class UserInfo implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 登录名 */ private String username; /** * 登录密码-加密 */ private String password; /** * 加密盐值 */ private String salt; /** * 昵称 */ private String nickName; /** * 用户头像 */ private String userPhoto; /** * 用户性别;0-男 1-女 */ private Integer userSex; /** * 账户余额 */ private Long accountBalance; /** * 用户状态;0-正常 */ private Integer status; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getUserPhoto() { return userPhoto; } public void setUserPhoto(String userPhoto) { this.userPhoto = userPhoto; } public Integer getUserSex() { return userSex; } public void setUserSex(Integer userSex) { this.userSex = userSex; } public Long getAccountBalance() { return accountBalance; } public void setAccountBalance(Long accountBalance) { this.accountBalance = accountBalance; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserInfo{" + "id=" + id + ", username=" + username + ", password=" + password + ", salt=" + salt + ", nickName=" + nickName + ", userPhoto=" + userPhoto + ", userSex=" + userSex + ", accountBalance=" + accountBalance + ", status=" + status + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
800
131
931
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/UserPayLog.java
UserPayLog
toString
class UserPayLog implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 充值用户ID */ private Long userId; /** * 充值方式;0-支付宝 1-微信 */ private Integer payChannel; /** * 商户订单号 */ private String outTradeNo; /** * 充值金额;单位:分 */ private Integer amount; /** * 充值商品类型;0-屋币 1-包年VIP */ private Integer productType; /** * 充值商品ID */ private Long productId; /** * 充值商品名;示例值:屋币 */ private String productName; /** * 充值商品值;示例值:255 */ private Integer productValue; /** * 充值时间 */ private LocalDateTime payTime; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Integer getPayChannel() { return payChannel; } public void setPayChannel(Integer payChannel) { this.payChannel = payChannel; } public String getOutTradeNo() { return outTradeNo; } public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public Integer getProductType() { return productType; } public void setProductType(Integer productType) { this.productType = productType; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Integer getProductValue() { return productValue; } public void setProductValue(Integer productValue) { this.productValue = productValue; } public LocalDateTime getPayTime() { return payTime; } public void setPayTime(LocalDateTime payTime) { this.payTime = payTime; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserPayLog{" + "id=" + id + ", userId=" + userId + ", payChannel=" + payChannel + ", outTradeNo=" + outTradeNo + ", amount=" + amount + ", productType=" + productType + ", productId=" + productId + ", productName=" + productName + ", productValue=" + productValue + ", payTime=" + payTime + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
918
149
1,067
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dao/entity/UserReadHistory.java
UserReadHistory
toString
class UserReadHistory implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 用户ID */ private Long userId; /** * 小说ID */ private Long bookId; /** * 上一次阅读的章节内容表ID */ private Long preContentId; /** * 创建时间; */ private LocalDateTime createTime; /** * 更新时间; */ private LocalDateTime updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getBookId() { return bookId; } public void setBookId(Long bookId) { this.bookId = bookId; } public Long getPreContentId() { return preContentId; } public void setPreContentId(Long preContentId) { this.preContentId = preContentId; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "UserReadHistory{" + "id=" + id + ", userId=" + userId + ", bookId=" + bookId + ", preContentId=" + preContentId + ", createTime=" + createTime + ", updateTime=" + updateTime + "}";
481
83
564
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/dto/es/EsBookDto.java
EsBookDto
build
class EsBookDto { /** * id */ private Long id; /** * 作品方向;0-男频 1-女频 */ private Integer workDirection; /** * 类别ID */ private Long categoryId; /** * 类别名 */ private String categoryName; /** * 小说名 */ private String bookName; /** * 作家id */ private Long authorId; /** * 作家名 */ private String authorName; /** * 书籍描述 */ private String bookDesc; /** * 评分;总分:10 ,真实评分 = score/10 */ private Integer score; /** * 书籍状态;0-连载中 1-已完结 */ private Integer bookStatus; /** * 点击量 */ private Long visitCount; /** * 总字数 */ private Integer wordCount; /** * 评论数 */ private Integer commentCount; /** * 最新章节ID */ private Long lastChapterId; /** * 最新章节名 */ private String lastChapterName; /** * 最新章节更新时间 */ private Long lastChapterUpdateTime; /** * 是否收费;1-收费 0-免费 */ private Integer isVip; public static EsBookDto build(BookInfo bookInfo){<FILL_FUNCTION_BODY>} }
return EsBookDto.builder() .id(bookInfo.getId()) .categoryId(bookInfo.getCategoryId()) .categoryName(bookInfo.getCategoryName()) .bookDesc(bookInfo.getBookDesc()) .bookName(bookInfo.getBookName()) .authorId(bookInfo.getAuthorId()) .authorName(bookInfo.getAuthorName()) .bookStatus(bookInfo.getBookStatus()) .commentCount(bookInfo.getCommentCount()) .isVip(bookInfo.getIsVip()) .score(bookInfo.getScore()) .visitCount(bookInfo.getVisitCount()) .wordCount(bookInfo.getWordCount()) .workDirection(bookInfo.getWorkDirection()) .lastChapterId(bookInfo.getLastChapterId()) .lastChapterName(bookInfo.getLastChapterName()) .lastChapterUpdateTime(bookInfo.getLastChapterUpdateTime() .toInstant(ZoneOffset.ofHours(8)).toEpochMilli()) .build();
440
267
707
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/AuthorInfoCacheManager.java
AuthorInfoCacheManager
getAuthor
class AuthorInfoCacheManager { private final AuthorInfoMapper authorInfoMapper; /** * 查询作家信息,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.REDIS_CACHE_MANAGER, value = CacheConsts.AUTHOR_INFO_CACHE_NAME, unless = "#result == null") public AuthorInfoDto getAuthor(Long userId) {<FILL_FUNCTION_BODY>} @CacheEvict(cacheManager = CacheConsts.REDIS_CACHE_MANAGER, value = CacheConsts.AUTHOR_INFO_CACHE_NAME) public void evictAuthorCache() { // 调用此方法自动清除作家信息的缓存 } }
QueryWrapper<AuthorInfo> queryWrapper = new QueryWrapper<>(); queryWrapper .eq(DatabaseConsts.AuthorInfoTable.COLUMN_USER_ID, userId) .last(DatabaseConsts.SqlEnum.LIMIT_1.getSql()); AuthorInfo authorInfo = authorInfoMapper.selectOne(queryWrapper); if (Objects.isNull(authorInfo)) { return null; } return AuthorInfoDto.builder() .id(authorInfo.getId()) .penName(authorInfo.getPenName()) .status(authorInfo.getStatus()).build();
198
152
350
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/BookCategoryCacheManager.java
BookCategoryCacheManager
listCategory
class BookCategoryCacheManager { private final BookCategoryMapper bookCategoryMapper; /** * 根据作品方向查询小说分类列表,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.BOOK_CATEGORY_LIST_CACHE_NAME) public List<BookCategoryRespDto> listCategory(Integer workDirection) {<FILL_FUNCTION_BODY>} }
QueryWrapper<BookCategory> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(DatabaseConsts.BookCategoryTable.COLUMN_WORK_DIRECTION, workDirection); return bookCategoryMapper.selectList(queryWrapper).stream().map(v -> BookCategoryRespDto.builder() .id(v.getId()) .name(v.getName()) .build()).toList();
130
105
235
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/BookChapterCacheManager.java
BookChapterCacheManager
getChapter
class BookChapterCacheManager { private final BookChapterMapper bookChapterMapper; /** * 查询小说章节信息,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.BOOK_CHAPTER_CACHE_NAME) public BookChapterRespDto getChapter(Long chapterId) {<FILL_FUNCTION_BODY>} @CacheEvict(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.BOOK_CHAPTER_CACHE_NAME) public void evictBookChapterCache(Long chapterId) { // 调用此方法自动清除小说章节信息的缓存 } }
BookChapter bookChapter = bookChapterMapper.selectById(chapterId); return BookChapterRespDto.builder() .id(chapterId) .bookId(bookChapter.getBookId()) .chapterNum(bookChapter.getChapterNum()) .chapterName(bookChapter.getChapterName()) .chapterWordCount(bookChapter.getWordCount()) .chapterUpdateTime(bookChapter.getUpdateTime()) .isVip(bookChapter.getIsVip()) .build();
202
133
335
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/BookContentCacheManager.java
BookContentCacheManager
getBookContent
class BookContentCacheManager { private final BookContentMapper bookContentMapper; /** * 查询小说内容,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.REDIS_CACHE_MANAGER, value = CacheConsts.BOOK_CONTENT_CACHE_NAME) public String getBookContent(Long chapterId) {<FILL_FUNCTION_BODY>} @CacheEvict(cacheManager = CacheConsts.REDIS_CACHE_MANAGER, value = CacheConsts.BOOK_CONTENT_CACHE_NAME) public void evictBookContentCache(Long chapterId) { // 调用此方法自动清除小说内容信息的缓存 } }
QueryWrapper<BookContent> contentQueryWrapper = new QueryWrapper<>(); contentQueryWrapper.eq(DatabaseConsts.BookContentTable.COLUMN_CHAPTER_ID, chapterId) .last(DatabaseConsts.SqlEnum.LIMIT_1.getSql()); BookContent bookContent = bookContentMapper.selectOne(contentQueryWrapper); return bookContent.getContent();
194
94
288
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/BookInfoCacheManager.java
BookInfoCacheManager
getLastUpdateIdList
class BookInfoCacheManager { private final BookInfoMapper bookInfoMapper; private final BookChapterMapper bookChapterMapper; /** * 从缓存中查询小说信息(先判断缓存中是否已存在,存在则直接从缓存中取,否则执行方法体中的逻辑后缓存结果) */ @Cacheable(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.BOOK_INFO_CACHE_NAME) public BookInfoRespDto getBookInfo(Long id) { return cachePutBookInfo(id); } /** * 缓存小说信息(不管缓存中是否存在都执行方法体中的逻辑,然后缓存起来) */ @CachePut(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.BOOK_INFO_CACHE_NAME) public BookInfoRespDto cachePutBookInfo(Long id) { // 查询基础信息 BookInfo bookInfo = bookInfoMapper.selectById(id); // 查询首章ID QueryWrapper<BookChapter> queryWrapper = new QueryWrapper<>(); queryWrapper .eq(DatabaseConsts.BookChapterTable.COLUMN_BOOK_ID, id) .orderByAsc(DatabaseConsts.BookChapterTable.COLUMN_CHAPTER_NUM) .last(DatabaseConsts.SqlEnum.LIMIT_1.getSql()); BookChapter firstBookChapter = bookChapterMapper.selectOne(queryWrapper); // 组装响应对象 return BookInfoRespDto.builder() .id(bookInfo.getId()) .bookName(bookInfo.getBookName()) .bookDesc(bookInfo.getBookDesc()) .bookStatus(bookInfo.getBookStatus()) .authorId(bookInfo.getAuthorId()) .authorName(bookInfo.getAuthorName()) .categoryId(bookInfo.getCategoryId()) .categoryName(bookInfo.getCategoryName()) .commentCount(bookInfo.getCommentCount()) .firstChapterId(firstBookChapter.getId()) .lastChapterId(bookInfo.getLastChapterId()) .picUrl(bookInfo.getPicUrl()) .visitCount(bookInfo.getVisitCount()) .wordCount(bookInfo.getWordCount()) .build(); } @CacheEvict(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.BOOK_INFO_CACHE_NAME) public void evictBookInfoCache(Long bookId) { // 调用此方法自动清除小说信息的缓存 } /** * 查询每个类别下最新更新的 500 个小说ID列表,并放入缓存中 1 个小时 */ @Cacheable(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.LAST_UPDATE_BOOK_ID_LIST_CACHE_NAME) public List<Long> getLastUpdateIdList(Long categoryId) {<FILL_FUNCTION_BODY>} }
QueryWrapper<BookInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(DatabaseConsts.BookTable.COLUMN_CATEGORY_ID, categoryId) .gt(DatabaseConsts.BookTable.COLUMN_WORD_COUNT, 0) .orderByDesc(DatabaseConsts.BookTable.COLUMN_LAST_CHAPTER_UPDATE_TIME) .last(DatabaseConsts.SqlEnum.LIMIT_500.getSql()); return bookInfoMapper.selectList(queryWrapper).stream().map(BookInfo::getId).toList();
814
144
958
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/BookRankCacheManager.java
BookRankCacheManager
listRankBooks
class BookRankCacheManager { private final BookInfoMapper bookInfoMapper; /** * 查询小说点击榜列表,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.REDIS_CACHE_MANAGER, value = CacheConsts.BOOK_VISIT_RANK_CACHE_NAME) public List<BookRankRespDto> listVisitRankBooks() { QueryWrapper<BookInfo> bookInfoQueryWrapper = new QueryWrapper<>(); bookInfoQueryWrapper.orderByDesc(DatabaseConsts.BookTable.COLUMN_VISIT_COUNT); return listRankBooks(bookInfoQueryWrapper); } /** * 查询小说新书榜列表,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.BOOK_NEWEST_RANK_CACHE_NAME) public List<BookRankRespDto> listNewestRankBooks() { QueryWrapper<BookInfo> bookInfoQueryWrapper = new QueryWrapper<>(); bookInfoQueryWrapper .gt(DatabaseConsts.BookTable.COLUMN_WORD_COUNT, 0) .orderByDesc(DatabaseConsts.CommonColumnEnum.CREATE_TIME.getName()); return listRankBooks(bookInfoQueryWrapper); } /** * 查询小说更新榜列表,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.BOOK_UPDATE_RANK_CACHE_NAME) public List<BookRankRespDto> listUpdateRankBooks() { QueryWrapper<BookInfo> bookInfoQueryWrapper = new QueryWrapper<>(); bookInfoQueryWrapper .gt(DatabaseConsts.BookTable.COLUMN_WORD_COUNT, 0) .orderByDesc(DatabaseConsts.CommonColumnEnum.UPDATE_TIME.getName()); return listRankBooks(bookInfoQueryWrapper); } private List<BookRankRespDto> listRankBooks(QueryWrapper<BookInfo> bookInfoQueryWrapper) {<FILL_FUNCTION_BODY>} }
bookInfoQueryWrapper .gt(DatabaseConsts.BookTable.COLUMN_WORD_COUNT, 0) .last(DatabaseConsts.SqlEnum.LIMIT_30.getSql()); return bookInfoMapper.selectList(bookInfoQueryWrapper).stream().map(v -> { BookRankRespDto respDto = new BookRankRespDto(); respDto.setId(v.getId()); respDto.setCategoryId(v.getCategoryId()); respDto.setCategoryName(v.getCategoryName()); respDto.setBookName(v.getBookName()); respDto.setAuthorName(v.getAuthorName()); respDto.setPicUrl(v.getPicUrl()); respDto.setBookDesc(v.getBookDesc()); respDto.setLastChapterName(v.getLastChapterName()); respDto.setLastChapterUpdateTime(v.getLastChapterUpdateTime()); respDto.setWordCount(v.getWordCount()); return respDto; }).toList();
586
277
863
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/FriendLinkCacheManager.java
FriendLinkCacheManager
listFriendLinks
class FriendLinkCacheManager { private final HomeFriendLinkMapper friendLinkMapper; /** * 友情链接列表查询,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.REDIS_CACHE_MANAGER, value = CacheConsts.HOME_FRIEND_LINK_CACHE_NAME) public List<HomeFriendLinkRespDto> listFriendLinks() {<FILL_FUNCTION_BODY>} }
// 从友情链接表中查询出友情链接列表 QueryWrapper<HomeFriendLink> queryWrapper = new QueryWrapper<>(); queryWrapper.orderByAsc(DatabaseConsts.CommonColumnEnum.SORT.getName()); return friendLinkMapper.selectList(queryWrapper).stream().map(v -> { HomeFriendLinkRespDto respDto = new HomeFriendLinkRespDto(); respDto.setLinkName(v.getLinkName()); respDto.setLinkUrl(v.getLinkUrl()); return respDto; }).toList();
126
152
278
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/HomeBookCacheManager.java
HomeBookCacheManager
listHomeBooks
class HomeBookCacheManager { private final HomeBookMapper homeBookMapper; private final BookInfoMapper bookInfoMapper; /** * 查询首页小说推荐,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.HOME_BOOK_CACHE_NAME) public List<HomeBookRespDto> listHomeBooks() {<FILL_FUNCTION_BODY>} }
// 从首页小说推荐表中查询出需要推荐的小说 QueryWrapper<HomeBook> queryWrapper = new QueryWrapper<>(); queryWrapper.orderByAsc(DatabaseConsts.CommonColumnEnum.SORT.getName()); List<HomeBook> homeBooks = homeBookMapper.selectList(queryWrapper); // 获取推荐小说ID列表 if (!CollectionUtils.isEmpty(homeBooks)) { List<Long> bookIds = homeBooks.stream() .map(HomeBook::getBookId) .toList(); // 根据小说ID列表查询相关的小说信息列表 QueryWrapper<BookInfo> bookInfoQueryWrapper = new QueryWrapper<>(); bookInfoQueryWrapper.in(DatabaseConsts.CommonColumnEnum.ID.getName(), bookIds); List<BookInfo> bookInfos = bookInfoMapper.selectList(bookInfoQueryWrapper); // 组装 HomeBookRespDto 列表数据并返回 if (!CollectionUtils.isEmpty(bookInfos)) { Map<Long, BookInfo> bookInfoMap = bookInfos.stream() .collect(Collectors.toMap(BookInfo::getId, Function.identity())); return homeBooks.stream().map(v -> { BookInfo bookInfo = bookInfoMap.get(v.getBookId()); HomeBookRespDto bookRespDto = new HomeBookRespDto(); bookRespDto.setType(v.getType()); bookRespDto.setBookId(v.getBookId()); bookRespDto.setBookName(bookInfo.getBookName()); bookRespDto.setPicUrl(bookInfo.getPicUrl()); bookRespDto.setAuthorName(bookInfo.getAuthorName()); bookRespDto.setBookDesc(bookInfo.getBookDesc()); return bookRespDto; }).toList(); } } return Collections.emptyList();
132
497
629
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/NewsCacheManager.java
NewsCacheManager
listLatestNews
class NewsCacheManager { private final NewsInfoMapper newsInfoMapper; /** * 最新新闻列表查询,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.CAFFEINE_CACHE_MANAGER, value = CacheConsts.LATEST_NEWS_CACHE_NAME) public List<NewsInfoRespDto> listLatestNews() {<FILL_FUNCTION_BODY>} }
// 从新闻信息表中查询出最新发布的两条新闻 QueryWrapper<NewsInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.orderByDesc(DatabaseConsts.CommonColumnEnum.CREATE_TIME.getName()) .last(DatabaseConsts.SqlEnum.LIMIT_2.getSql()); return newsInfoMapper.selectList(queryWrapper).stream().map(v -> NewsInfoRespDto.builder() .id(v.getId()) .categoryId(v.getCategoryId()) .categoryName(v.getCategoryName()) .title(v.getTitle()) .sourceName(v.getSourceName()) .updateTime(v.getUpdateTime()) .build()).toList();
121
184
305
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/cache/UserInfoCacheManager.java
UserInfoCacheManager
getUser
class UserInfoCacheManager { private final UserInfoMapper userInfoMapper; /** * 查询用户信息,并放入缓存中 */ @Cacheable(cacheManager = CacheConsts.REDIS_CACHE_MANAGER, value = CacheConsts.USER_INFO_CACHE_NAME) public UserInfoDto getUser(Long userId) {<FILL_FUNCTION_BODY>} }
UserInfo userInfo = userInfoMapper.selectById(userId); if (Objects.isNull(userInfo)) { return null; } return UserInfoDto.builder() .id(userInfo.getId()) .status(userInfo.getStatus()).build();
113
74
187
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/dao/UserDaoManager.java
UserDaoManager
listUsers
class UserDaoManager { private final UserInfoMapper userInfoMapper; /** * 根据用户ID集合批量查询用户信息列表 * * @param userIds 需要查询的用户ID集合 * @return 满足条件的用户信息列表 */ public List<UserInfo> listUsers(List<Long> userIds) {<FILL_FUNCTION_BODY>} }
QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.in(DatabaseConsts.CommonColumnEnum.ID.getName(), userIds); return userInfoMapper.selectList(queryWrapper);
109
54
163
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/message/AbstractMailSender.java
AbstractMailSender
sendMessage
class AbstractMailSender extends AbstractMessageSender { private final MailProperties mailProperties; private final JavaMailSender mailSender; @Override protected void sendMessage(Long toUserId, String messageTitle, String messageContent) {<FILL_FUNCTION_BODY>} }
// TODO 根据消息接收方的用户ID查询出消息接收方的邮件地址 String toEmail = "xxyopen@foxmail.com"; // 开始发送邮件 log.info("发送 HTML 邮件开始:{},{},{}", toEmail, messageTitle, messageContent); // 使用 MimeMessage,MIME 协议 MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper; // MimeMessageHelper 帮助我们设置更丰富的内容 try { helper = new MimeMessageHelper(message, true); helper.setFrom(new InternetAddress(mailProperties.username(), mailProperties.nickname(), "UTF-8")); helper.setTo(toEmail); helper.setSubject(messageTitle); // 第二个参数 true 代表支持 html helper.setText(messageContent, true); mailSender.send(message); log.info("发送 HTML 邮件 to {} 成功", toEmail); } catch (Exception e) { // 邮件发送失败不会重试 log.error("发送 HTML 邮件 to {} 失败", toEmail, e); }
76
297
373
<methods>public non-sealed void <init>() ,public final transient void sendMessage(java.lang.Long, java.lang.Object[]) <variables>private static final java.lang.String PLACEHOLDER
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/message/AbstractMessageSender.java
AbstractMessageSender
sendMessage
class AbstractMessageSender implements MessageSender { private static final String PLACEHOLDER = "{}"; /** * 定义消息发送的模版,子类不能修改此模版 */ @Override public final void sendMessage(Long toUserId, Object... args) {<FILL_FUNCTION_BODY>} /** * 发送消息,具体发送到哪里由子类决定 * * @param toUserId 消息接收方的用户ID * @param messageTitle 消息标题 * @param messageContent 消息内容 */ protected abstract void sendMessage(Long toUserId, String messageTitle, String messageContent); /** * 获取消息标题的模版,具体如何制定模版由子类决定 * * @return 消息标题 */ protected abstract String getTitleTemplate(); /** * 获取消息内容的模版,具体如何制定模版由子类决定 * * @return 消息内容 */ protected abstract String getContentTemplate(); /** * 通过给定的参数列表解析消息标题模版,默认固定标题,不需要解析,可以由子类来拓展它的功能 * * @param titleTemplate 消息标题模版 * @param arguments 用来解析的参数列表 * @return 解析后的消息标题 */ protected String resolveTitle(String titleTemplate, Object... arguments) { return titleTemplate; } /** * 通过给定的参数列表解析消息内容模版,默认实现是使用参数列表来替换消息内容模版中的占位符,可以由子类来拓展它的功能 * <p> * 子类可以根据第一个/前几个参数去数据库中查询动态内容,然后重组参数列表 * * @param contentTemplate 消息内容模版 * @param args 用来解析的参数列表 * @return 解析后的消息内容 */ protected String resolveContent(String contentTemplate, Object... args) { if (args.length > 0) { StringBuilder formattedContent = new StringBuilder(contentTemplate); for (Object arg : args) { int start = formattedContent.indexOf(PLACEHOLDER); formattedContent.replace(start, start + PLACEHOLDER.length(), String.valueOf(arg)); } return formattedContent.toString(); } return contentTemplate; } }
// 1.获取消息标题模版 String titleTemplate = getTitleTemplate(); // 2.获取消息内容模版 String contentTemplate = getContentTemplate(); // 3.解析消息模版,得到最终需要发送的消息标题 String title = resolveTitle(titleTemplate, args); // 4.解析消息内容,得到最终需要发送的消息内容 String content = resolveContent(contentTemplate, args); // 5.发送消息 sendMessage(toUserId, title, content);
632
134
766
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/message/AbstractSysNoticeSender.java
AbstractSysNoticeSender
sendMessage
class AbstractSysNoticeSender extends AbstractMessageSender { @Override protected void sendMessage(Long toUserId, String messageTitle, String messageContent) {<FILL_FUNCTION_BODY>} }
// 生成消息的发送时间 LocalDateTime messageDateTime = LocalDateTime.now(); // TODO 在数据库系统通知表中插入一条记录 log.info("系统通知发送成功,{},{},{},{}", toUserId, messageDateTime.format(DateTimeFormatter.ISO_DATE_TIME), messageTitle, messageContent);
55
88
143
<methods>public non-sealed void <init>() ,public final transient void sendMessage(java.lang.Long, java.lang.Object[]) <variables>private static final java.lang.String PLACEHOLDER
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/message/RegisterMailSender.java
RegisterMailSender
getContentTemplate
class RegisterMailSender extends AbstractMailSender { public RegisterMailSender(MailProperties mailProperties, JavaMailSender mailSender) { super(mailProperties, mailSender); } @Override protected String getTitleTemplate() { return "欢迎来到小说精品屋"; } @Override protected String getContentTemplate() {<FILL_FUNCTION_BODY>} @Override protected String resolveContent(String content, Object... args) { // TODO 去数据库/配置文件中查询网站配置 String websiteLink = "https://www.xxyopen.com"; String websiteEmail = "xxyopen@foxmail.com"; return super.resolveContent(content, Stream.of(args, new Object[]{websiteLink, websiteEmail}).flatMap(Arrays::stream).toArray()); } }
return """ <div> 感谢你注册小说精品屋!你的账户现在处于活动状态。 </div> <ul> <li> 你的账户电子邮件:{} <li> 你的账户用户名:{} </ul> <div style="padding: 10px 0 50px 0; text-align: center;"> <a style="background: #0274be; color: #fff; padding: 12px 30px; text-decoration: none; border-radius: 3px; letter-spacing: 0.3px;" href="{}" target="_blank" rel="noopener"> 登录我们的网站 </a> </div> 如果你有任何问题,请通过 {} 与我们联系。 """;
218
209
427
<methods>public non-sealed void <init>() <variables>private final non-sealed MailProperties mailProperties,private final non-sealed JavaMailSender mailSender
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/mq/AmqpMsgManager.java
AmqpMsgManager
sendAmqpMessage
class AmqpMsgManager { private final AmqpTemplate amqpTemplate; @Value("${spring.amqp.enabled:false}") private boolean amqpEnabled; /** * 发送小说信息改变消息 */ public void sendBookChangeMsg(Long bookId) { if (amqpEnabled) { sendAmqpMessage(amqpTemplate, AmqpConsts.BookChangeMq.EXCHANGE_NAME, null, bookId); } } private void sendAmqpMessage(AmqpTemplate amqpTemplate, String exchange, String routingKey, Object message) {<FILL_FUNCTION_BODY>} }
// 如果在事务中则在事务执行完成后再发送,否则可以直接发送 if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronization() { @Override public void afterCommit() { amqpTemplate.convertAndSend(exchange, routingKey, message); } }); return; } amqpTemplate.convertAndSend(exchange, routingKey, message);
180
132
312
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/manager/redis/VerifyCodeManager.java
VerifyCodeManager
genImgVerifyCode
class VerifyCodeManager { private final StringRedisTemplate stringRedisTemplate; /** * 生成图形验证码,并放入 Redis 中 */ public String genImgVerifyCode(String sessionId) throws IOException {<FILL_FUNCTION_BODY>} /** * 校验图形验证码 */ public boolean imgVerifyCodeOk(String sessionId, String verifyCode) { return Objects.equals(stringRedisTemplate.opsForValue() .get(CacheConsts.IMG_VERIFY_CODE_CACHE_KEY + sessionId), verifyCode); } /** * 从 Redis 中删除验证码 */ public void removeImgVerifyCode(String sessionId) { stringRedisTemplate.delete(CacheConsts.IMG_VERIFY_CODE_CACHE_KEY + sessionId); } }
String verifyCode = ImgVerifyCodeUtils.getRandomVerifyCode(4); String img = ImgVerifyCodeUtils.genVerifyCodeImg(verifyCode); stringRedisTemplate.opsForValue().set(CacheConsts.IMG_VERIFY_CODE_CACHE_KEY + sessionId, verifyCode, Duration.ofMinutes(5)); return img;
234
97
331
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/service/impl/AuthorServiceImpl.java
AuthorServiceImpl
register
class AuthorServiceImpl implements AuthorService { private final AuthorInfoCacheManager authorInfoCacheManager; private final AuthorInfoMapper authorInfoMapper; @Override public RestResp<Void> register(AuthorRegisterReqDto dto) {<FILL_FUNCTION_BODY>} @Override public RestResp<Integer> getStatus(Long userId) { AuthorInfoDto author = authorInfoCacheManager.getAuthor(userId); return Objects.isNull(author) ? RestResp.ok(null) : RestResp.ok(author.getStatus()); } }
// 校验该用户是否已注册为作家 AuthorInfoDto author = authorInfoCacheManager.getAuthor(dto.getUserId()); if (Objects.nonNull(author)) { // 该用户已经是作家,直接返回 return RestResp.ok(); } // 保存作家注册信息 AuthorInfo authorInfo = new AuthorInfo(); authorInfo.setUserId(dto.getUserId()); authorInfo.setChatAccount(dto.getChatAccount()); authorInfo.setEmail(dto.getEmail()); authorInfo.setInviteCode("0"); authorInfo.setTelPhone(dto.getTelPhone()); authorInfo.setPenName(dto.getPenName()); authorInfo.setWorkDirection(dto.getWorkDirection()); authorInfo.setCreateTime(LocalDateTime.now()); authorInfo.setUpdateTime(LocalDateTime.now()); authorInfoMapper.insert(authorInfo); // 清除作家缓存 authorInfoCacheManager.evictAuthorCache(); return RestResp.ok();
153
279
432
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/service/impl/DbSearchServiceImpl.java
DbSearchServiceImpl
searchBooks
class DbSearchServiceImpl implements SearchService { private final BookInfoMapper bookInfoMapper; @Override public RestResp<PageRespDto<BookInfoRespDto>> searchBooks(BookSearchReqDto condition) {<FILL_FUNCTION_BODY>} }
Page<BookInfoRespDto> page = new Page<>(); page.setCurrent(condition.getPageNum()); page.setSize(condition.getPageSize()); List<BookInfo> bookInfos = bookInfoMapper.searchBooks(page, condition); return RestResp.ok( PageRespDto.of(condition.getPageNum(), condition.getPageSize(), page.getTotal(), bookInfos.stream().map(v -> BookInfoRespDto.builder() .id(v.getId()) .bookName(v.getBookName()) .categoryId(v.getCategoryId()) .categoryName(v.getCategoryName()) .authorId(v.getAuthorId()) .authorName(v.getAuthorName()) .wordCount(v.getWordCount()) .lastChapterName(v.getLastChapterName()) .build()).toList()));
76
230
306
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/service/impl/EsSearchServiceImpl.java
EsSearchServiceImpl
buildSearchCondition
class EsSearchServiceImpl implements SearchService { private final ElasticsearchClient esClient; @SneakyThrows @Override public RestResp<PageRespDto<BookInfoRespDto>> searchBooks(BookSearchReqDto condition) { SearchResponse<EsBookDto> response = esClient.search(s -> { SearchRequest.Builder searchBuilder = s.index(EsConsts.BookIndex.INDEX_NAME); // 构建检索条件 buildSearchCondition(condition, searchBuilder); // 排序 if (!StringUtils.isBlank(condition.getSort())) { searchBuilder.sort(o -> o.field(f -> f .field(StringUtils.underlineToCamel(condition.getSort().split(" ")[0])) .order(SortOrder.Desc)) ); } // 分页 searchBuilder.from((condition.getPageNum() - 1) * condition.getPageSize()) .size(condition.getPageSize()); // 设置高亮显示 searchBuilder.highlight(h -> h.fields(EsConsts.BookIndex.FIELD_BOOK_NAME, t -> t.preTags("<em style='color:red'>").postTags("</em>")) .fields(EsConsts.BookIndex.FIELD_AUTHOR_NAME, t -> t.preTags("<em style='color:red'>").postTags("</em>"))); return searchBuilder; }, EsBookDto.class ); TotalHits total = response.hits().total(); List<BookInfoRespDto> list = new ArrayList<>(); List<Hit<EsBookDto>> hits = response.hits().hits(); // 类型推断 var 非常适合 for 循环,JDK 10 引入,JDK 11 改进 for (var hit : hits) { EsBookDto book = hit.source(); assert book != null; if (!CollectionUtils.isEmpty(hit.highlight().get(EsConsts.BookIndex.FIELD_BOOK_NAME))) { book.setBookName(hit.highlight().get(EsConsts.BookIndex.FIELD_BOOK_NAME).get(0)); } if (!CollectionUtils.isEmpty( hit.highlight().get(EsConsts.BookIndex.FIELD_AUTHOR_NAME))) { book.setAuthorName( hit.highlight().get(EsConsts.BookIndex.FIELD_AUTHOR_NAME).get(0)); } list.add(BookInfoRespDto.builder() .id(book.getId()) .bookName(book.getBookName()) .categoryId(book.getCategoryId()) .categoryName(book.getCategoryName()) .authorId(book.getAuthorId()) .authorName(book.getAuthorName()) .wordCount(book.getWordCount()) .lastChapterName(book.getLastChapterName()) .build()); } assert total != null; return RestResp.ok( PageRespDto.of(condition.getPageNum(), condition.getPageSize(), total.value(), list)); } /** * 构建检索条件 */ private void buildSearchCondition(BookSearchReqDto condition, SearchRequest.Builder searchBuilder) {<FILL_FUNCTION_BODY>} }
BoolQuery boolQuery = BoolQuery.of(b -> { // 只查有字数的小说 b.must(RangeQuery.of(m -> m .field(EsConsts.BookIndex.FIELD_WORD_COUNT) .gt(JsonData.of(0)) )._toQuery()); if (!StringUtils.isBlank(condition.getKeyword())) { // 关键词匹配 b.must((q -> q.multiMatch(t -> t .fields(EsConsts.BookIndex.FIELD_BOOK_NAME + "^2", EsConsts.BookIndex.FIELD_AUTHOR_NAME + "^1.8", EsConsts.BookIndex.FIELD_BOOK_DESC + "^0.1") .query(condition.getKeyword()) ) )); } // 精确查询 if (Objects.nonNull(condition.getWorkDirection())) { b.must(TermQuery.of(m -> m .field(EsConsts.BookIndex.FIELD_WORK_DIRECTION) .value(condition.getWorkDirection()) )._toQuery()); } if (Objects.nonNull(condition.getCategoryId())) { b.must(TermQuery.of(m -> m .field(EsConsts.BookIndex.FIELD_CATEGORY_ID) .value(condition.getCategoryId()) )._toQuery()); } // 范围查询 if (Objects.nonNull(condition.getWordCountMin())) { b.must(RangeQuery.of(m -> m .field(EsConsts.BookIndex.FIELD_WORD_COUNT) .gte(JsonData.of(condition.getWordCountMin())) )._toQuery()); } if (Objects.nonNull(condition.getWordCountMax())) { b.must(RangeQuery.of(m -> m .field(EsConsts.BookIndex.FIELD_WORD_COUNT) .lt(JsonData.of(condition.getWordCountMax())) )._toQuery()); } if (Objects.nonNull(condition.getUpdateTimeMin())) { b.must(RangeQuery.of(m -> m .field(EsConsts.BookIndex.FIELD_LAST_CHAPTER_UPDATE_TIME) .gte(JsonData.of(condition.getUpdateTimeMin().getTime())) )._toQuery()); } return b; }); searchBuilder.query(q -> q.bool(boolQuery));
868
657
1,525
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/service/impl/NewsServiceImpl.java
NewsServiceImpl
getNews
class NewsServiceImpl implements NewsService { private final NewsCacheManager newsCacheManager; private final NewsInfoMapper newsInfoMapper; private final NewsContentMapper newsContentMapper; @Override public RestResp<List<NewsInfoRespDto>> listLatestNews() { return RestResp.ok(newsCacheManager.listLatestNews()); } @Override public RestResp<NewsInfoRespDto> getNews(Long id) {<FILL_FUNCTION_BODY>} }
NewsInfo newsInfo = newsInfoMapper.selectById(id); QueryWrapper<NewsContent> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(DatabaseConsts.NewsContentTable.COLUMN_NEWS_ID, id) .last(DatabaseConsts.SqlEnum.LIMIT_1.getSql()); NewsContent newsContent = newsContentMapper.selectOne(queryWrapper); return RestResp.ok(NewsInfoRespDto.builder() .title(newsInfo.getTitle()) .sourceName(newsInfo.getSourceName()) .updateTime(newsInfo.getUpdateTime()) .content(newsContent.getContent()) .build());
133
169
302
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/service/impl/ResourceServiceImpl.java
ResourceServiceImpl
uploadImage
class ResourceServiceImpl implements ResourceService { private final VerifyCodeManager verifyCodeManager; @Value("${novel.file.upload.path}") private String fileUploadPath; @Override public RestResp<ImgVerifyCodeRespDto> getImgVerifyCode() throws IOException { String sessionId = IdWorker.get32UUID(); return RestResp.ok(ImgVerifyCodeRespDto.builder() .sessionId(sessionId) .img(verifyCodeManager.genImgVerifyCode(sessionId)) .build()); } @SneakyThrows @Override public RestResp<String> uploadImage(MultipartFile file) {<FILL_FUNCTION_BODY>} }
LocalDateTime now = LocalDateTime.now(); String savePath = SystemConfigConsts.IMAGE_UPLOAD_DIRECTORY + now.format(DateTimeFormatter.ofPattern("yyyy")) + File.separator + now.format(DateTimeFormatter.ofPattern("MM")) + File.separator + now.format(DateTimeFormatter.ofPattern("dd")); String oriName = file.getOriginalFilename(); assert oriName != null; String saveFileName = IdWorker.get32UUID() + oriName.substring(oriName.lastIndexOf(".")); File saveFile = new File(fileUploadPath + savePath, saveFileName); if (!saveFile.getParentFile().exists()) { boolean isSuccess = saveFile.getParentFile().mkdirs(); if (!isSuccess) { throw new BusinessException(ErrorCodeEnum.USER_UPLOAD_FILE_ERROR); } } file.transferTo(saveFile); if (Objects.isNull(ImageIO.read(saveFile))) { // 上传的文件不是图片 Files.delete(saveFile.toPath()); throw new BusinessException(ErrorCodeEnum.USER_UPLOAD_FILE_TYPE_NOT_MATCH); } return RestResp.ok(savePath + File.separator + saveFileName);
195
334
529
<no_super_class>
201206030_novel
novel/src/main/java/io/github/xxyopen/novel/service/impl/UserServiceImpl.java
UserServiceImpl
register
class UserServiceImpl implements UserService { private final UserInfoMapper userInfoMapper; private final VerifyCodeManager verifyCodeManager; private final UserFeedbackMapper userFeedbackMapper; private final UserBookshelfMapper userBookshelfMapper; private final JwtUtils jwtUtils; @Override public RestResp<UserRegisterRespDto> register(UserRegisterReqDto dto) {<FILL_FUNCTION_BODY>} @Override public RestResp<UserLoginRespDto> login(UserLoginReqDto dto) { // 查询用户信息 QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(DatabaseConsts.UserInfoTable.COLUMN_USERNAME, dto.getUsername()) .last(DatabaseConsts.SqlEnum.LIMIT_1.getSql()); UserInfo userInfo = userInfoMapper.selectOne(queryWrapper); if (Objects.isNull(userInfo)) { // 用户不存在 throw new BusinessException(ErrorCodeEnum.USER_ACCOUNT_NOT_EXIST); } // 判断密码是否正确 if (!Objects.equals(userInfo.getPassword() , DigestUtils.md5DigestAsHex(dto.getPassword().getBytes(StandardCharsets.UTF_8)))) { // 密码错误 throw new BusinessException(ErrorCodeEnum.USER_PASSWORD_ERROR); } // 登录成功,生成JWT并返回 return RestResp.ok(UserLoginRespDto.builder() .token(jwtUtils.generateToken(userInfo.getId(), SystemConfigConsts.NOVEL_FRONT_KEY)) .uid(userInfo.getId()) .nickName(userInfo.getNickName()).build()); } @Override public RestResp<Void> saveFeedback(Long userId, String content) { UserFeedback userFeedback = new UserFeedback(); userFeedback.setUserId(userId); userFeedback.setContent(content); userFeedback.setCreateTime(LocalDateTime.now()); userFeedback.setUpdateTime(LocalDateTime.now()); userFeedbackMapper.insert(userFeedback); return RestResp.ok(); } @Override public RestResp<Void> updateUserInfo(UserInfoUptReqDto dto) { UserInfo userInfo = new UserInfo(); userInfo.setId(dto.getUserId()); userInfo.setNickName(dto.getNickName()); userInfo.setUserPhoto(dto.getUserPhoto()); userInfo.setUserSex(dto.getUserSex()); userInfoMapper.updateById(userInfo); return RestResp.ok(); } @Override public RestResp<Void> deleteFeedback(Long userId, Long id) { QueryWrapper<UserFeedback> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(DatabaseConsts.CommonColumnEnum.ID.getName(), id) .eq(DatabaseConsts.UserFeedBackTable.COLUMN_USER_ID, userId); userFeedbackMapper.delete(queryWrapper); return RestResp.ok(); } @Override public RestResp<Integer> getBookshelfStatus(Long userId, String bookId) { QueryWrapper<UserBookshelf> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(DatabaseConsts.UserBookshelfTable.COLUMN_USER_ID, userId) .eq(DatabaseConsts.UserBookshelfTable.COLUMN_BOOK_ID, bookId); return RestResp.ok( userBookshelfMapper.selectCount(queryWrapper) > 0 ? CommonConsts.YES : CommonConsts.NO ); } @Override public RestResp<UserInfoRespDto> getUserInfo(Long userId) { UserInfo userInfo = userInfoMapper.selectById(userId); return RestResp.ok(UserInfoRespDto.builder() .nickName(userInfo.getNickName()) .userSex(userInfo.getUserSex()) .userPhoto(userInfo.getUserPhoto()) .build()); } }
// 校验图形验证码是否正确 if (!verifyCodeManager.imgVerifyCodeOk(dto.getSessionId(), dto.getVelCode())) { // 图形验证码校验失败 throw new BusinessException(ErrorCodeEnum.USER_VERIFY_CODE_ERROR); } // 校验手机号是否已注册 QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq(DatabaseConsts.UserInfoTable.COLUMN_USERNAME, dto.getUsername()) .last(DatabaseConsts.SqlEnum.LIMIT_1.getSql()); if (userInfoMapper.selectCount(queryWrapper) > 0) { // 手机号已注册 throw new BusinessException(ErrorCodeEnum.USER_NAME_EXIST); } // 注册成功,保存用户信息 UserInfo userInfo = new UserInfo(); userInfo.setPassword( DigestUtils.md5DigestAsHex(dto.getPassword().getBytes(StandardCharsets.UTF_8))); userInfo.setUsername(dto.getUsername()); userInfo.setNickName(dto.getUsername()); userInfo.setCreateTime(LocalDateTime.now()); userInfo.setUpdateTime(LocalDateTime.now()); userInfo.setSalt("0"); userInfoMapper.insert(userInfo); // 删除验证码 verifyCodeManager.removeImgVerifyCode(dto.getSessionId()); // 生成JWT 并返回 return RestResp.ok( UserRegisterRespDto.builder() .token(jwtUtils.generateToken(userInfo.getId(), SystemConfigConsts.NOVEL_FRONT_KEY)) .uid(userInfo.getId()) .build() );
1,105
463
1,568
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/Metrics.java
Metrics
updateSubFiles
class Metrics { private static final Logger LOGGER = LoggerFactory.getLogger(Metrics.class); private static final StatsdConfig statsdConfig = new StatsdConfig() { @Override public String get(String k) { return null; } @Override public StatsdFlavor flavor() { return RuntimeEnvironment.getInstance().getStatsdConfig().getFlavor(); } @Override public int port() { return RuntimeEnvironment.getInstance().getStatsdConfig().getPort(); } @Override public String host() { return RuntimeEnvironment.getInstance().getStatsdConfig().getHost(); } @Override public boolean buffered() { return true; } }; private static PrometheusMeterRegistry prometheusRegistry; private static StatsdMeterRegistry statsdRegistry; static { MeterRegistry registry = null; if (RuntimeEnvironment.getInstance().getStatsdConfig().isEnabled()) { LOGGER.log(Level.INFO, "configuring StatsdRegistry"); statsdRegistry = new StatsdMeterRegistry(statsdConfig, Clock.SYSTEM); registry = statsdRegistry; } else if (!RuntimeEnvironment.getInstance().isIndexer()) { LOGGER.log(Level.INFO, "configuring PrometheusRegistry"); prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); registry = prometheusRegistry; } if (registry != null) { new ClassLoaderMetrics().bindTo(registry); new JvmMemoryMetrics().bindTo(registry); new JvmGcMetrics().bindTo(registry); new ProcessorMetrics().bindTo(registry); new JvmThreadMetrics().bindTo(registry); } } private Metrics() { } public static void updateSubFiles(List<String> subFiles) {<FILL_FUNCTION_BODY>} public static PrometheusMeterRegistry getPrometheusRegistry() { return prometheusRegistry; } private static StatsdMeterRegistry getStatsdRegistry() { return statsdRegistry; } /** * Get registry based on running context. * @return MeterRegistry instance */ public static MeterRegistry getRegistry() { if (RuntimeEnvironment.getInstance().isIndexer()) { return getStatsdRegistry(); } else { return getPrometheusRegistry(); } } }
// Add tag for per-project reindex. if (statsdRegistry != null && !subFiles.isEmpty()) { String projects = subFiles.stream(). map(s -> s.startsWith(Indexer.PATH_SEPARATOR_STRING) ? s.substring(1) : s). collect(Collectors.joining(",")); Tag commonTag = Tag.of("projects", projects); LOGGER.log(Level.FINE, "updating statsdRegistry with common tag: {}", commonTag); statsdRegistry.config().commonTags(Collections.singleton(commonTag)); }
640
155
795
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/AbstractAnalyzer.java
AbstractAnalyzer
get
class AbstractAnalyzer extends Analyzer { public static final Reader DUMMY_READER = new StringReader(""); protected AnalyzerFactory factory; protected Supplier<JFlexTokenizer> symbolTokenizerFactory; protected Project project; protected Ctags ctags; protected NumLinesLOCAggregator countsAggregator; protected boolean scopesEnabled; protected boolean foldingEnabled; protected AbstractAnalyzer(ReuseStrategy reuseStrategy) { super(reuseStrategy); } /** * Subclasses should override to return the case-insensitive name aligning * with either a built-in Universal Ctags language name or an OpenGrok * custom language name. * @return a defined instance or {@code null} if the analyzer has no aligned * Universal Ctags language */ public abstract String getCtagsLang(); public abstract long getVersionNo(); /** * Subclasses should override to produce a value relevant for the evolution * of their analysis in each release. * * @return 0 since {@link AbstractAnalyzer} is not specialized */ protected int getSpecializedVersionNo() { return 0; } public void setCtags(Ctags ctags) { this.ctags = ctags; } public void setCountsAggregator(NumLinesLOCAggregator countsAggregator) { this.countsAggregator = countsAggregator; } public void setProject(Project project) { this.project = project; } public void setScopesEnabled(boolean scopesEnabled) { this.scopesEnabled = supportsScopes() && scopesEnabled; } public void setFoldingEnabled(boolean foldingEnabled) { this.foldingEnabled = supportsScopes() && foldingEnabled; } protected abstract boolean supportsScopes(); /** * Get the factory which created this analyzer. * * @return the {@code FileAnalyzerFactory} which created this analyzer */ public final AnalyzerFactory getFactory() { return factory; } public AbstractAnalyzer.Genre getGenre() { return factory.getGenre(); } public abstract String getFileTypeName(); public abstract void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException, InterruptedException; public abstract Xrefer writeXref(WriteXrefArgs args) throws IOException; @Override protected abstract TokenStreamComponents createComponents(String fieldName); @Override protected abstract TokenStream normalize(String fieldName, TokenStream in); /** * Subclasses must override to incorporate a determined number of lines and * lines-of-code (LOC). * @param doc Document instance * @param counts NumLinesLOC instance */ protected abstract void addNumLinesLOC(Document doc, NumLinesLOC counts); /** * What kind of file is this? */ public enum Genre { /** * xrefed - line numbered context. */ PLAIN("p"), /** * xrefed - summarizer context. */ XREFABLE("x"), /** * not xrefed - no context - used by diff/list. */ IMAGE("i"), /** * not xrefed - no context. */ DATA("d"), /** * not xrefed - summarizer context from original file. */ HTML("h"); private final String typeName; Genre(String typename) { this.typeName = typename; } /** * Get the type name value used to tag lucene documents. * * @return a none-null string. */ public String typeName() { return typeName; } /** * Get the Genre for the given type name. * * @param typeName name to check * @return {@code null} if it doesn't match any genre, the genre * otherwise. * @see #typeName() */ public static Genre get(String typeName) {<FILL_FUNCTION_BODY>} } }
if (typeName == null) { return null; } for (Genre g : values()) { if (g.typeName.equals(typeName)) { return g; } } return null;
1,070
63
1,133
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/AnalyzerGuruHelp.java
AnalyzerGuruHelp
reportable
class AnalyzerGuruHelp { private AnalyzerGuruHelp() { } /** * Gets a reportable hunk of text that details * {@link AnalyzerGuru#getPrefixesMap()}, * {@link AnalyzerGuru#getExtensionsMap()}, * {@link AnalyzerGuru#getMagicsMap()}, and * {@link AnalyzerGuru#getAnalyzerFactoryMatchers()}. * @return a defined, multi-line String */ public static String getUsage() { StringBuilder b = new StringBuilder(); b.append("List of analyzers:" + System.lineSeparator()); b.append("The names of the analyzers (left column) can be used for the -A indexer option:" + System.lineSeparator() + System.lineSeparator()); byFactory(AnalyzerGuru.getAnalyzerFactories().stream(). collect(Collectors.toMap(f -> f.getClass().getSimpleName(), f -> f))). forEach(factory -> b.append(String.format("%-10s : %s%n", factory.fac.getClass().getSimpleName().replace("AnalyzerFactory", ""), factory.fac.getName() != null ? factory.fac.getName() : "N/A")) ); b.append(System.lineSeparator() + "AnalyzerGuru prefixes:" + System.lineSeparator()); byKey(AnalyzerGuru.getPrefixesMap()).forEach(kv -> b.append(String.format("%-10s : %s%n", reportable(kv.key + '*'), reportable(kv.fac))) ); b.append(System.lineSeparator() + "AnalyzerGuru extensions:" + System.lineSeparator()); byKey(AnalyzerGuru.getExtensionsMap()).forEach(kv -> b.append(String.format("*.%-7s : %s%n", reportable(kv.key.toLowerCase(Locale.ROOT)), reportable(kv.fac))) ); b.append(System.lineSeparator() + "AnalyzerGuru magic strings:" + System.lineSeparator()); byFactory(AnalyzerGuru.getMagicsMap()).forEach(kv -> b.append(String.format("%-23s : %s%n", reportable(kv.key), reportable(kv.fac))) ); b.append(System.lineSeparator() + "AnalyzerGuru magic matchers:" + System.lineSeparator()); AnalyzerGuru.getAnalyzerFactoryMatchers().forEach(m -> { if (m.isPreciseMagic()) { b.append(reportable(m)); } }); AnalyzerGuru.getAnalyzerFactoryMatchers().forEach(m -> { if (!m.isPreciseMagic()) { b.append(reportable(m)); } }); return b.toString(); } private static String reportable(AnalyzerFactory fac) { String nm = fac.getName(); return nm == null ? fac.getClass().getSimpleName() : nm; } private static String reportable(String value) {<FILL_FUNCTION_BODY>} private static String reportable(FileAnalyzerFactory.Matcher m) { final String MATCHER_FMT = "%-11s %-1s %s%n"; StringBuilder b = new StringBuilder(); String[] lines = splitLines(m.description(), 66); for (int i = 0; i < lines.length; ++i) { if (i < 1) { b.append(String.format(MATCHER_FMT, reportable(m.forFactory()), ":", lines[i])); } else { b.append(String.format(MATCHER_FMT, "", "", lines[i])); } } return b.toString(); } private static String[] splitLines(String str, int width) { List<String> res = new ArrayList<>(); StringBuilder b = new StringBuilder(); int llen = 0; int i = 0; while (i < str.length()) { int wlen = StringUtils.whitespaceOrControlLength(str, i, false); if (wlen > 0) { String word = str.substring(i, i + wlen); if (llen < 1) { b.append(word); llen = word.length(); } else if (llen + 1 + wlen <= width) { b.append(" "); b.append(word); llen += word.length() + 1; } else { res.add(b.toString()); b.setLength(0); b.append(word); llen = word.length(); } i += wlen; } int slen = StringUtils.whitespaceOrControlLength(str, i, true); i += slen; } if (b.length() > 0) { res.add(b.toString()); b.setLength(0); } return res.toArray(String[]::new); } private static List<MappedFactory> byKey(Map<String, AnalyzerFactory> mapped) { return mapped.entrySet().stream() .map(t -> new MappedFactory(t.getKey(), t.getValue())) .sorted(Comparator.comparing(mf -> mf.key.toLowerCase(Locale.ROOT))) .collect(Collectors.toList()); } private static List<MappedFactory> byFactory(Map<String, AnalyzerFactory> mapped) { return mapped.entrySet().stream() .map(t -> new MappedFactory(t.getKey(), t.getValue())) .sorted((mf1, mf2) -> { String r1 = reportable(mf1.fac); String r2 = reportable(mf2.fac); int cmp = r1.toLowerCase(Locale.ROOT).compareTo( r2.toLowerCase(Locale.ROOT)); if (cmp != 0) { return cmp; } return mf1.key.toLowerCase(Locale.ROOT).compareTo( mf2.key.toLowerCase(Locale.ROOT)); }) .collect(Collectors.toList()); } private static class MappedFactory { public final String key; public final AnalyzerFactory fac; MappedFactory(String key, AnalyzerFactory fac) { this.key = key; this.fac = fac; } } }
if (value.startsWith("#!")) { return value; } boolean allAsciiPrintable = true; for (int i = 0; i < value.length(); ++i) { char c = value.charAt(i); if (c < ' ' || c > '~') { allAsciiPrintable = false; break; } } if (allAsciiPrintable) { return value; } StringBuilder b = new StringBuilder(); int i = 0; while (i < value.length()) { int cp = Character.codePointAt(value, i); i += Character.charCount(cp); if (Character.isAlphabetic(cp)) { b.appendCodePoint(cp); } else { b.append("\\{"); b.append(String.format("%x", cp)); b.append("}"); } } return b.toString();
1,714
253
1,967
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/CompatibleAnalyser.java
CompatibleAnalyser
createComponents
class CompatibleAnalyser extends Analyzer { public CompatibleAnalyser() { super(Analyzer.PER_FIELD_REUSE_STRATEGY); } @Override protected TokenStreamComponents createComponents(String fieldName) {<FILL_FUNCTION_BODY>} private JFlexTokenizer createPlainSymbolTokenizer() { return new JFlexTokenizer(new PlainSymbolTokenizer( AbstractAnalyzer.DUMMY_READER)); } private JFlexTokenizer createPlainFullTokenizer() { return new JFlexTokenizer(new PlainFullTokenizer( AbstractAnalyzer.DUMMY_READER)); } @Override protected TokenStream normalize(String fieldName, TokenStream in) { switch (fieldName) { case QueryBuilder.DEFS: case QueryBuilder.REFS: return in; default: return new LowerCaseFilter(in); } } }
switch (fieldName) { case QueryBuilder.FULL: return new TokenStreamComponents(createPlainFullTokenizer()); case QueryBuilder.REFS: return new TokenStreamComponents(createPlainSymbolTokenizer()); case QueryBuilder.DEFS: return new TokenStreamComponents(createPlainSymbolTokenizer()); case QueryBuilder.PATH: case QueryBuilder.PROJECT: return new TokenStreamComponents(new PathTokenizer()); case QueryBuilder.HIST: try (HistoryAnalyzer historyAnalyzer = new HistoryAnalyzer()) { return historyAnalyzer.createComponents(fieldName); } default: return new TokenStreamComponents(createPlainFullTokenizer()); }
259
187
446
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/Definitions.java
LineTagMap
occurrences
class LineTagMap implements Serializable { private static final long serialVersionUID = 1191703801007779481L; @SuppressWarnings("java:S116") private final Map<String, Set<Tag>> sym_tags; //NOPMD protected LineTagMap() { this.sym_tags = new HashMap<>(); } } // line number -> tag map @SuppressWarnings("java:S116") private final Map<Integer, LineTagMap> line_maps; /** * Map from symbol to the line numbers on which the symbol is defined. */ private final Map<String, Set<Integer>> symbols; /** * List of all the tags. */ private final List<Tag> tags; public Definitions() { symbols = new HashMap<>(); line_maps = new HashMap<>(); tags = new ArrayList<>(); } /** * Reset all {@link Tag#used} values to {@code false}. */ public void resetUnused() { for (Tag tag : tags) { tag.used = false; } } /** * Get all symbols used in definitions. * * @return a set containing all the symbols */ public Set<String> getSymbols() { return symbols.keySet(); } /** * Check if there is a tag for a symbol. * * @param symbol the symbol to check * @return {@code true} if there is a tag for {@code symbol} */ public boolean hasSymbol(String symbol) { return symbols.containsKey(symbol); } /** * Check whether the specified symbol is defined on the given line. * * @param symbol the symbol to look for * @param lineNumber the line to check * @param strs type of definition(to be passed back to caller) * @return {@code true} if {@code symbol} is defined on the specified line */ public boolean hasDefinitionAt(String symbol, int lineNumber, String[] strs) { if (strs.length > 0) { strs[0] = "none"; } // Get tag info boolean isDefinitionPresent = Optional.ofNullable(symbols.get(symbol)) .filter(lines -> lines.contains(lineNumber)) .isPresent(); if (isDefinitionPresent) { LineTagMap lineMap = line_maps.get(lineNumber); if (lineMap != null) { for (Tag tag : lineMap.sym_tags.get(symbol)) { if (tag.used) { continue; } if (strs.length > 0) { //NOPMD strs[0] = tag.type; } tag.used = true; // Assume the first one return true; } } } return false; } /** * Return the number of occurrences of definitions with the specified * symbol. * * @param symbol the symbol to count the occurrences of * @return the number of times the specified symbol is defined */ public int occurrences(String symbol) {<FILL_FUNCTION_BODY>
Set<Integer> lines = symbols.get(symbol); return lines == null ? 0 : lines.size();
839
31
870
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/ExpandTabsReader.java
ExpandTabsReader
read
class ExpandTabsReader extends FilterReader { /** The size of tabs. */ private final int tabSize; /** * The position on the current line. Used to decide how many spaces to * insert to fill up to the next tab stop. */ private int pos; /** * Number of spaces to insert (as replacement for a tab) before reading * more from the underlying stream. */ private int spacesToInsert; /** * Create a new ExpandTabsReader to expand tabs to spaces. * * @param in the original input source * @param tabSize the size of tabs */ ExpandTabsReader(Reader in, int tabSize) { super(in); this.tabSize = tabSize; } /** * Wrap a reader in an ExpandTabsReader if the project has custom tab * size settings. * * @param in the reader to wrap * @param p the project * @return {@code in} if the project doesn't have custom tab settings; * otherwise, an {@code ExpandTabsReader} that wraps {@code in} and expands * tabs as defined by the project's settings */ public static Reader wrap(Reader in, Project p) { if (p != null && p.hasTabSizeSetting()) { return new ExpandTabsReader(in, p.getTabSize()); } else { return in; } } /** * Wrap a reader in an {@link ExpandTabsReader} if the {@code tabSize} is * positive. * @param in the reader to wrap * @param tabSize a value effective only if greater than zero * @return {@code in} if the {@code tabSize} is not positive; * otherwise, an {@code ExpandTabsReader} that wraps {@code in} and expands * tabs */ public static Reader wrap(Reader in, int tabSize) { return tabSize < 1 ? in : new ExpandTabsReader(in, tabSize); } /** * Translates a specified {@code line} {@code column} offset (0-based) to an * offset computed when translating for the specified tab size in accordance * with {@link ExpandTabsReader} read handling. * @param line a defined instance * @param column a value greater than or equal to zero and less than or * equal to {@code line} length * @param tabSize a value effective only if greater than zero * @return a translated offset * @throws IllegalArgumentException if {@code column} is invalid for * {@code line} */ public static int translate(String line, int column, int tabSize) { if (column < 0) { throw new IllegalArgumentException("`column' is negative"); } if (column > line.length()) { throw new IllegalArgumentException("`column' is out of bounds"); } if (tabSize < 1) { return column; } int newColumn = 0; for (int i = 0; i < column; ++i) { char c = line.charAt(i); if (c == '\t') { // Fill up with spaces up to the next tab stop newColumn += tabSize - (newColumn % tabSize); } else { // \r or \n are not expected so do not handle specially. ++newColumn; } } return newColumn; } @Override public int read() throws IOException { if (spacesToInsert > 0) { pos++; spacesToInsert--; return ' '; } int c = super.read(); if (c == '\t') { // Fill up with spaces up to the next tab stop int spaces = tabSize - (pos % tabSize); pos++; spacesToInsert = spaces - 1; return ' '; } if (c == '\n' || c == '\r') { // Reset position on new line pos = 0; } else { pos++; } return c; } @Override public int read(char[] cbuf, int off, int len) throws IOException {<FILL_FUNCTION_BODY>} @Override public long skip(long n) throws IOException { if (n < 0L) { throw new IllegalArgumentException("n is negative"); } long skipped = 0; for (long l = 0; l < n; l++) { int c = read(); if (c == -1) { break; } skipped++; } return skipped; } @Override public boolean markSupported() { // Support for mark/reset has not been implemented. return false; } }
for (int i = 0; i < len; i++) { int c = read(); if (c == -1) { return (i > 0 ? i : -1); } cbuf[off + i] = (char) c; } return len;
1,234
76
1,310
<methods>public void close() throws java.io.IOException,public void mark(int) throws java.io.IOException,public boolean markSupported() ,public int read() throws java.io.IOException,public int read(char[], int, int) throws java.io.IOException,public boolean ready() throws java.io.IOException,public void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException<variables>protected java.io.Reader in
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/FileAnalyzerFactory.java
FileAnalyzerFactory
getAnalyzer
class FileAnalyzerFactory extends AnalyzerFactory { /** The user-friendly name of this analyzer. */ private final String name; /** * Create an instance of {@code FileAnalyzerFactory}. */ FileAnalyzerFactory() { this(null, null, null, null, null, null, null, null, false); } /** * Construct an instance of {@code FileAnalyzerFactory}. This constructor * should be used by subclasses to override default values. * * @param names list of file names to recognize (possibly {@code null}) * @param prefixes list of prefixes to recognize (possibly {@code null}) * @param suffixes list of suffixes to recognize (possibly {@code null}) * @param magics list of magic strings to recognize (possibly {@code null}) * @param matcher a matcher for this analyzer (possibly {@code null}) * @param contentType content type for this analyzer (possibly {@code null}) * @param genre the genre for this analyzer (if {@code null}, {@code * Genre.DATA} is used) * @param name user-friendly name of this analyzer (or null if it shouldn't be listed) * @param hasAnnotations whether the files processed by the analyzers produced by this factory can be annotated */ protected FileAnalyzerFactory( String[] names, String[] prefixes, String[] suffixes, String[] magics, Matcher matcher, String contentType, AbstractAnalyzer.Genre genre, String name, boolean hasAnnotations) { super(matcher, contentType); this.names = asList(names); this.prefixes = asList(prefixes); this.suffixes = asList(suffixes); this.magics = asList(magics); this.genre = (genre == null) ? AbstractAnalyzer.Genre.DATA : genre; this.name = name; this.hasAnnotations = hasAnnotations; } /** * Helper method which wraps an array in a list. * * @param a the array to wrap ({@code null} means an empty array) * @return a list which wraps the array */ private static <T> List<T> asList(T[] a) { if (a == null) { return Collections.emptyList(); } return List.of(a); } @Override public String getName() { return name; } /** * Get an analyzer. If the same thread calls this method multiple times on * the same factory object, the exact same analyzer object will be returned * each time. Subclasses should not override this method, but instead * override the {@code newAnalyzer()} method. * * @return a {@code FileAnalyzer} instance * @see #newAnalyzer() */ @Override public final AbstractAnalyzer getAnalyzer() {<FILL_FUNCTION_BODY>} /** * Free thread-local data. */ @Override public void returnAnalyzer() { cachedAnalyzer.remove(); } /** * Create a new analyzer. * @return an analyzer */ @Override protected AbstractAnalyzer newAnalyzer() { return new FileAnalyzer(this); } /** * Interface for matchers which map file contents to analyzer factories. */ public interface Matcher { /** * Get a value indicating if the magic is byte-precise. * @return true if precise */ default boolean isPreciseMagic() { return false; } /** * Gets a default, reportable description of the matcher. * <p> * Subclasses can override to report a more informative description, * with line length up to 50 characters before starting a new line with * {@code \n}. * @return a defined, reportable String */ default String description() { return isPreciseMagic() ? "precise matcher" : "heuristic matcher"; } /** * Try to match the file contents with an analyzer factory. * If the method reads from the input stream, it must reset the * stream before returning. * * @param contents the first few bytes of a file * @param in the input stream from which the full file can be read * @return an analyzer factory if the contents match, or {@code null} * if they don't match any factory known by this matcher * @throws java.io.IOException in case of any read error */ AnalyzerFactory isMagic(byte[] contents, InputStream in) throws IOException; /** * Gets the instance which the matcher produces if * {@link #isMagic(byte[], java.io.InputStream)} matches a file. * @return a defined instance */ AnalyzerFactory forFactory(); } }
AbstractAnalyzer fa = cachedAnalyzer.get(); if (fa == null) { fa = newAnalyzer(); cachedAnalyzer.set(fa); } return fa;
1,254
51
1,305
<methods>public abstract org.opengrok.indexer.analysis.AbstractAnalyzer getAnalyzer() ,public final org.opengrok.indexer.analysis.AbstractAnalyzer.Genre getGenre() ,public abstract java.lang.String getName() ,public boolean hasAnnotations() ,public abstract void returnAnalyzer() <variables>protected final non-sealed ThreadLocal<org.opengrok.indexer.analysis.AbstractAnalyzer> cachedAnalyzer,protected final non-sealed java.lang.String contentType,protected org.opengrok.indexer.analysis.AbstractAnalyzer.Genre genre,protected boolean hasAnnotations,protected List<java.lang.String> magics,protected final non-sealed List<org.opengrok.indexer.analysis.FileAnalyzerFactory.Matcher> matchers,protected List<java.lang.String> names,protected List<java.lang.String> prefixes,protected List<java.lang.String> suffixes
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/HistoryAnalyzer.java
HistoryAnalyzer
createComponents
class HistoryAnalyzer extends Analyzer { private final CharArraySet stopWords; /** * An array containing some common English words that are not usually useful * for searching. */ private static final String[] ENGLISH_STOP_WORDS = { "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "no", "not", "of", "on", "or", "s", "such", "t", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with", "/", "\\", ":", ".", "0.0", "1.0" }; /** * Builds an analyzer which removes words in ENGLISH_STOP_WORDS. */ public HistoryAnalyzer() { super(Analyzer.PER_FIELD_REUSE_STRATEGY); stopWords = StopFilter.makeStopSet(ENGLISH_STOP_WORDS); } /** * Creates components using a new {@link PlainFullTokenizer}, filtered using * a default set of English stop-words. * @param fieldName name of field for which to create components * @return components for this analyzer (NB safe to use even if this * analyzer were to be garbage-collected) */ @Override protected TokenStreamComponents createComponents(String fieldName) {<FILL_FUNCTION_BODY>} @Override protected TokenStream normalize(String fieldName, TokenStream in) { return new LowerCaseFilter(in); } }
JFlexTokenizer plainfull = new JFlexTokenizer(new PlainFullTokenizer( AbstractAnalyzer.DUMMY_READER)); //we are counting position increments, this might affect the queries //later and need to be in sync, especially for highlighting of results return new TokenStreamComponents(plainfull, new StopFilter(plainfull, stopWords));
445
98
543
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/IteratorReader.java
IteratorReader
read
class IteratorReader extends Reader { private Iterator<String> iterator; private StringReader current; public IteratorReader(Iterable<String> iterable) { if (iterable == null) { throw new IllegalArgumentException("`iterable' is null"); } Iterator<String> iter = iterable.iterator(); if (iter == null) { throw new IllegalArgumentException("`iterable' did not produce iterator"); } this.iterator = iter; } public IteratorReader(Iterator<String> iterator) { if (iterator == null) { throw new IllegalArgumentException("`iterator' is null"); } this.iterator = iterator; } @Override public int read(char[] cbuf, int off, int len) throws IOException {<FILL_FUNCTION_BODY>} @Override public void close() { iterator = null; current = null; } }
if (current != null) { int ret = current.read(cbuf, off, len); if (ret > 0 || len == 0) { // If some data was read, or if no data was requested, // we're OK. Return the number of characters read. return ret; } } // No more data was found in the current element. Read data from // the next element, or return -1 if there are no more elements. if (iterator.hasNext()) { current = new StringReader(iterator.next() + '\n'); return current.read(cbuf, off, len); } else { return -1; }
244
173
417
<methods>public abstract void close() throws java.io.IOException,public void mark(int) throws java.io.IOException,public boolean markSupported() ,public static java.io.Reader nullReader() ,public int read() throws java.io.IOException,public int read(java.nio.CharBuffer) throws java.io.IOException,public int read(char[]) throws java.io.IOException,public abstract int read(char[], int, int) throws java.io.IOException,public boolean ready() throws java.io.IOException,public void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public long transferTo(java.io.Writer) throws java.io.IOException<variables>private static final int TRANSFER_BUFFER_SIZE,protected java.lang.Object lock,private static final int maxSkipBufferSize,private char[] skipBuffer
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/JFlexTokenizer.java
JFlexTokenizer
setAttribs
class JFlexTokenizer extends Tokenizer implements SymbolMatchedListener { private static final int LUCENE_MAX_TOKEN_LENGTH = 32766; private final ScanningSymbolMatcher matcher; private boolean didSetAttribsValues; /** * Initialize an instance, passing a {@link ScanningSymbolMatcher} which * will be owned by the {@link JFlexTokenizer}. * @param matcher a defined instance */ public JFlexTokenizer(ScanningSymbolMatcher matcher) { if (matcher == null) { throw new IllegalArgumentException("`matcher' is null"); } this.matcher = matcher; matcher.setSymbolMatchedListener(this); // The tokenizer will own the matcher, so we won't have to unsubscribe. } /** * Resets the instance and the instance's {@link ScanningSymbolMatcher}. * If necessary, users should have first called this instance's * {@link #setReader(java.io.Reader)} since the matcher will be * reset to the current reader. * @throws java.io.IOException in case of I/O error */ @Override public void reset() throws IOException { super.reset(); matcher.yyreset(input); matcher.reset(); clearAttributesEtc(); } /** * Closes the instance and the instance's {@link ScanningSymbolMatcher}. * @throws IOException if any error occurs while closing */ @Override public final void close() throws IOException { super.close(); matcher.yyclose(); } private final CharTermAttribute termAtt = addAttribute( CharTermAttribute.class); private final OffsetAttribute offsetAtt = addAttribute( OffsetAttribute.class); private final PositionIncrementAttribute posIncrAtt = addAttribute( PositionIncrementAttribute.class); /** * Attempts to advance the stream to the next acceptable token, and updates * the appropriate {@link AttributeImpl}s. * * @return {@code true} if an acceptable token was produced; {@code false} * otherwise to indicate end of stream * @throws IOException in case of I/O error */ @Override public final boolean incrementToken() throws IOException { boolean notAtEOF; do { clearAttributesEtc(); notAtEOF = matcher.yylex() != matcher.getYYEOF(); } while (!didSetAttribsValues && notAtEOF); return notAtEOF; } /** * Calls {@link #setAttribs(String, long, long)} on the publishing * of a {@link SymbolMatchedEvent}. * @param evt the event raised */ @Override public void symbolMatched(SymbolMatchedEvent evt) { setAttribs(evt.getStr(), evt.getStart(), evt.getEnd()); } /** * Does nothing. * @param evt ignored */ @Override public void sourceCodeSeen(SourceCodeSeenEvent evt) { } /** * Clears, and then resets the instances attributes per the specified * arguments. If {@code start} or {@code end} is past * {@link Integer#MAX_VALUE}, then only the clearing occurs. * @param str the matched symbol * @param start the match start position * @param end the match end position */ protected void setAttribs(String str, long start, long end) {<FILL_FUNCTION_BODY>} /** * Calls {@link #clearAttributes()}, and also resets some additional tracked * state. */ protected void clearAttributesEtc() { clearAttributes(); didSetAttribsValues = false; } }
clearAttributesEtc(); if (start < Integer.MAX_VALUE && end < Integer.MAX_VALUE) { if (str.length() > LUCENE_MAX_TOKEN_LENGTH) { str = str.substring(0, LUCENE_MAX_TOKEN_LENGTH); /* * Leave `end` unadjusted. The truncated string will represent * the full source text, similar to how a Lucene synonym is an * alternative representation of full source text. */ } /* * FIXME increasing below by one(default) might be tricky, need more * analysis after lucene upgrade to 3.5 below is most probably not * even needed. */ this.posIncrAtt.setPositionIncrement(1); this.termAtt.setEmpty(); this.termAtt.append(str); this.offsetAtt.setOffset((int) start, (int) end); this.didSetAttribsValues = true; }
984
259
1,243
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/PathTokenizer.java
PathTokenizer
incrementToken
class PathTokenizer extends Tokenizer { // below should be '/' since we try to convert even windows file separators // to unix ones public static final char DEFAULT_DELIMITER = '/'; private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class); private int startPosition = 0; private final char delimiter; private int charsRead = 0; private boolean dot = false; private static final char cdot = '.'; public PathTokenizer() { this.delimiter = DEFAULT_DELIMITER; } @Override public final boolean incrementToken() throws IOException {<FILL_FUNCTION_BODY>} @Override public final void end() throws IOException { super.end(); // set final offset int finalOffset = correctOffset(charsRead); offsetAtt.setOffset(finalOffset, finalOffset); } @Override public void reset() throws IOException { super.reset(); dot = false; charsRead = 0; startPosition = 0; } }
clearAttributes(); if (dot) { dot = false; termAtt.setEmpty(); termAtt.append(cdot); termAtt.setLength(1); offsetAtt.setOffset(correctOffset(startPosition), correctOffset(startPosition + 1)); startPosition++; return true; } char[] buf = new char[64]; int c; int i = 0; do { c = input.read(); charsRead++; if (c == -1) { return false; } } while (c == delimiter); do { if (i >= buf.length) { buf = Arrays.copyOf(buf, buf.length * 2); } /* "In general, String.toLowerCase(Locale) should be used to map characters to lowercase. String case mapping methods have several benefits over Character case mapping methods. String case mapping methods can perform locale-sensitive mappings, context-sensitive mappings, and 1:M character mappings, whereas the Character case mapping methods cannot." See below. */ buf[i++] = (char) c; c = input.read(); charsRead++; } while (c != delimiter && c != cdot && !Character.isWhitespace(c) && c != -1); if (c == cdot) { dot = true; } String bufLcase = String.valueOf(buf, 0, i).toLowerCase(Locale.ROOT); i = bufLcase.length(); termAtt.append(bufLcase); termAtt.setLength(i); offsetAtt.setOffset(correctOffset(startPosition), correctOffset(startPosition + i)); startPosition = startPosition + i + 1; return true;
294
470
764
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/PendingToken.java
PendingToken
equals
class PendingToken { public final String str; public final int start; public final int end; /** * Initializes an instance with immutable fields for the specified * arguments. * @param str string value * @param start start offset * @param end end offset */ public PendingToken(String str, int start, int end) { this.str = str; this.start = start; this.end = end; } /** * Compares this instance's immutable fields to the other. * @param o object * @return {@code true} if the objects are equal */ @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} /** * Calculates a hash code from the instance's immutable fields. * @return a hash value */ @Override public int hashCode() { return Objects.hash(str, start, end); } /** * Gets a readable representation for debugging. * @return a defined instance */ @Override public String toString() { return "PendingToken{" + str + "<<< start=" + start + ",end=" + end + '}'; } }
if (o == this) { return true; } if (!(o instanceof PendingToken)) { return false; } PendingToken other = (PendingToken) o; return start == other.start && end == other.end && str.equals(other.str);
327
79
406
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/PendingTokenOffsetsComparator.java
PendingTokenOffsetsComparator
compare
class PendingTokenOffsetsComparator implements Comparator<PendingToken> { /** * Singleton instance. */ public static final PendingTokenOffsetsComparator INSTANCE = new PendingTokenOffsetsComparator(); @Override public int compare(PendingToken o1, PendingToken o2) {<FILL_FUNCTION_BODY>} /** Private to enforce singleton. */ private PendingTokenOffsetsComparator() { } }
// ASC by starting offset. int cmp = Integer.compare(o1.start, o2.start); if (cmp != 0) { return cmp; } // ASC by ending offset cmp = Integer.compare(o1.end, o2.end); return cmp;
128
83
211
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/Scopes.java
Scope
deserialize
class Scope implements Serializable, Comparable<Scope> { private static final long serialVersionUID = 1191703801007779489L; private int lineFrom; private int lineTo; private String name; private String namespace; private String signature; public Scope(int lineFrom, int lineTo, String name, String namespace) { this(lineFrom, lineTo, name, namespace, ""); } public Scope(int lineFrom, int lineTo, String name, String namespace, String signature) { this.lineFrom = lineFrom; this.lineTo = lineTo; this.name = name; this.namespace = namespace; this.signature = signature; } public Scope(int lineFrom) { this.lineFrom = lineFrom; } public boolean matches(int line) { return line >= lineFrom && line <= lineTo; } @Override public int compareTo(Scope o) { return Integer.compare(lineFrom, o.lineFrom); } public int getLineFrom() { return lineFrom; } public void setLineFrom(int lineFrom) { this.lineFrom = lineFrom; } public int getLineTo() { return lineTo; } public void setLineTo(int lineTo) { this.lineTo = lineTo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } } // default global scope public static final Scope GLOBAL_SCOPE = new Scope(0, 0, "global", null, null); // tree of scopes sorted by starting line private final TreeSet<Scope> scopes = new TreeSet<>(); public Scopes() { // nothing to do here } public int size() { return scopes.size(); } public void addScope(Scope scope) { scopes.add(scope); } public Scope getScope(int line) { // find closest scope that starts before or on given line Scope s = scopes.floor(new Scope(line)); return (s != null && s.matches(line)) ? s : GLOBAL_SCOPE; } /** * Create a binary representation of this object. * * @return a byte array representing this object * @throws IOException if an error happens when writing to the array */ public byte[] serialize() throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); new ObjectOutputStream(bytes).writeObject(this); return bytes.toByteArray(); } /** * De-serialize a binary representation of a {@code Definitions} object. * * @param bytes a byte array containing the {@code Definitions} object * @return a {@code Definitions} object * @throws IOException if an I/O error happens when reading the array * @throws ClassNotFoundException if the class definition for an object * stored in the byte array cannot be found * @throws ClassCastException if the array contains an object of another * type than {@code Definitions} */ public static Scopes deserialize(byte[] bytes) throws IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { in.setObjectInputFilter(serialFilter); return (Scopes) in.readObject(); }
953
50
1,003
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/StreamSource.java
StreamSource
fromString
class StreamSource { /** * Get a stream that reads data from the input source. Every call should * return a new instance so that multiple readers can read from the source * without interfering with each other. * * @return an {@code InputStream} * @throws IOException if an error occurs when opening the stream */ public abstract InputStream getStream() throws IOException; /** * Helper method that creates a {@code StreamSource} instance that * reads data from a file. * * @param file the data file * @return a stream source that reads from {@code file} */ public static StreamSource fromFile(final File file) { return new StreamSource() { @Override public InputStream getStream() throws IOException { return new BufferedInputStream(new FileInputStream(file)); } }; } /** * Helper method that creates a {@code StreamSource} instance that * reads data from a String. * @param str the source string * @return a stream source that reads from {@code str} */ public static StreamSource fromString(final String str) {<FILL_FUNCTION_BODY>} }
return new StreamSource() { private final byte[] sbuf = str.getBytes(StandardCharsets.UTF_8); @Override public InputStream getStream() throws IOException { return new ByteArrayInputStream(sbuf); } };
297
66
363
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/TextAnalyzer.java
TextAnalyzer
writeXref
class TextAnalyzer extends FileAnalyzer { /** * Creates a new instance of {@link TextAnalyzer}. * @param factory defined instance for the analyzer */ protected TextAnalyzer(AnalyzerFactory factory) { super(factory); } /** * Creates a new instance of {@link TextAnalyzer}. * @param factory defined instance for the analyzer * @param symbolTokenizerFactory defined instance for the analyzer */ protected TextAnalyzer(AnalyzerFactory factory, Supplier<JFlexTokenizer> symbolTokenizerFactory) { super(factory, symbolTokenizerFactory); } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20171223_00 */ @Override protected int getSpecializedVersionNo() { return 20171223_00; // Edit comment above too! } /** * Write a cross referenced HTML file reads the source from in. * @param args a defined instance * @return the instance used to write the cross-referencing * @throws IOException if an I/O error occurs */ @Override public Xrefer writeXref(WriteXrefArgs args) throws IOException {<FILL_FUNCTION_BODY>} /** * Derived classes should implement to create an xref for the language * supported by this analyzer. * @param reader the data to produce xref for * @return an xref instance */ protected abstract Xrefer newXref(Reader reader); /** * Gets a BOM-stripped {@link Reader} (default UTF-8 charset) of the * specified {@code stream}, wrapped in a {@link ZeroReader}. * @param stream input stream * @return Reader instance */ protected Reader getReader(InputStream stream) throws IOException { // sourceRoot is read with UTF-8 as a default. return new ZeroReader(IOUtils.createBOMStrippedReader(stream, StandardCharsets.UTF_8.name())); } }
if (args == null) { throw new IllegalArgumentException("`args' is null"); } Xrefer xref = newXref(args.getIn()); xref.setDefs(args.getDefs()); xref.setScopesEnabled(scopesEnabled); xref.setFoldingEnabled(foldingEnabled); xref.setAnnotation(args.getAnnotation()); xref.setProject(args.getProject()); xref.write(args.getOut()); return xref;
558
133
691
<methods>public void <init>(org.opengrok.indexer.analysis.AnalyzerFactory) ,public void analyze(Document, org.opengrok.indexer.analysis.StreamSource, java.io.Writer) throws java.io.IOException, java.lang.InterruptedException,public java.lang.String getCtagsLang() ,public java.lang.String getFileTypeName() ,public final long getVersionNo() ,public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>private static final java.util.logging.Logger LOGGER
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/XrefStyle.java
XrefStyle
getStyle
class XrefStyle { /** * Name of the style definition as given by CTags. */ final String name; /** * Class name used by the style sheets when rendering the xref. */ final String ssClass; /** * The title of the section to which this type belongs, or {@code null} * if this type should not be listed in the navigation panel. */ final String title; XrefStyle(String name, String ssClass, String title) { this.name = name; this.ssClass = ssClass; this.title = title; } /** * Description of styles to use for different types of definitions. */ protected static final XrefStyle[] DEFINITION_STYLES = { new XrefStyle("macro", "xm", "Macro"), new XrefStyle("argument", "xa", null), new XrefStyle("local", "xl", null), new XrefStyle("variable", "xv", "Variable"), new XrefStyle("class", "xc", "Class"), new XrefStyle("package", "xp", "Package"), new XrefStyle("interface", "xi", "Interface"), new XrefStyle("namespace", "xn", "Namespace"), new XrefStyle("enumerator", "xer", null), new XrefStyle("enum", "xe", "Enum"), new XrefStyle("struct", "xs", "Struct"), new XrefStyle("typedefs", "xts", null), new XrefStyle("typedef", "xt", "Typedef"), new XrefStyle("union", "xu", null), new XrefStyle("field", "xfld", null), new XrefStyle("member", "xmb", null), new XrefStyle("function", "xf", "Function"), new XrefStyle("method", "xmt", "Method"), new XrefStyle("subroutine", "xsr", "Subroutine"), new XrefStyle("label", "xlbl", "Label"), new XrefStyle("procedure", "xf", "Procedure") }; /** * Get the style description for a definition type. * @param type the definition type * @return the style of a definition type, or {@code null} if no style is * defined for the type * @see #DEFINITION_STYLES */ public static XrefStyle getStyle(String type) {<FILL_FUNCTION_BODY>} }
for (XrefStyle style : DEFINITION_STYLES) { if (type.startsWith(style.name)) { return style; } } return null;
630
53
683
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/XrefWork.java
XrefWork
getXrefer
class XrefWork { private Xrefer xrefer; private Exception exception; private final WriteXrefArgs args; private final AbstractAnalyzer analyzer; public XrefWork(WriteXrefArgs args, AbstractAnalyzer analyzer) { this.args = args; this.analyzer = analyzer; } public Xrefer getXrefer() throws ExecutionException, InterruptedException {<FILL_FUNCTION_BODY>} }
RuntimeEnvironment env = RuntimeEnvironment.getInstance(); CompletableFuture<XrefWork> future = CompletableFuture.supplyAsync(() -> { try { xrefer = this.analyzer.writeXref(args); } catch (IOException e) { exception = e; } return this; }, env.getIndexerParallelizer().getXrefWatcherExecutor()). orTimeout(env.getXrefTimeout(), TimeUnit.SECONDS); XrefWork xrefWork = future.get(); // Will throw ExecutionException wrapping TimeoutException on timeout. if (xrefWork.xrefer != null) { return xrefer; } else { // Re-throw the exception from writeXref(). throw new ExecutionException(xrefWork.exception); }
119
207
326
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/ZeroReader.java
ZeroReader
read
class ZeroReader extends Reader { /** The underlying Reader that is being wrapped. */ private final Reader reader; /** * Initializes to wrap a {@link Reader} that might not always block * appropriately in {@link #read(char[], int, int)}. */ public ZeroReader(Reader reader) { this.reader = reader; } /** * Read {@code len} characters from the underlying {@link Reader} into the * buffer {@code cbuf} at offset {@code off}, blocking until input is * available or end-of-stream is reached. * * <p>Relies on the method {@link #read()} of the underlying {@link Reader} * to block until at least one character is available or end-of-stream is * reached. * * @param cbuf the buffer to write into * @param off the offset at which to write * @param len the maximum number of characters to write * @return -1 for end of stream; number of characters read otherwise. * Returns 0 if and only if len is equal to 0. * @exception IOException If an I/O error occurs * @exception IndexOutOfBoundsException * If {@code off} is negative, or {@code len} is negative, * or {@code len} is greater than {@code cbuf.length - off} */ @Override public int read(char[] cbuf, int off, int len) throws IOException {<FILL_FUNCTION_BODY>} /** * Closes the underlying {@link Reader}. * * @throws IOException if thrown by the underlying {@link Reader} */ @Override public void close() throws IOException { reader.close(); } /** * For testing only: gets the encoding of the underlying {@link Reader} if * it is an instanceof {@link InputStreamReader}. * @return a defined instance or {@code null} */ String getUnderlyingEncoding() { if (reader instanceof InputStreamReader) { return ((InputStreamReader) reader).getEncoding(); } return null; } }
int n = reader.read(cbuf, off, len); if (n != 0 || len == 0) { return n; } if (len < 0) { throw new IndexOutOfBoundsException("len is negative"); } if (off >= cbuf.length || off < 0) { throw new IndexOutOfBoundsException("off is out of cbuf bounds"); } // Returns the character read, as an integer in the range 0 to 65535 // (0x00-0xffff), or -1 if the end of the stream has been reached int c = reader.read(); if (c == -1) { return -1; } cbuf[off] = (char) c; return 1;
528
200
728
<methods>public abstract void close() throws java.io.IOException,public void mark(int) throws java.io.IOException,public boolean markSupported() ,public static java.io.Reader nullReader() ,public int read() throws java.io.IOException,public int read(java.nio.CharBuffer) throws java.io.IOException,public int read(char[]) throws java.io.IOException,public abstract int read(char[], int, int) throws java.io.IOException,public boolean ready() throws java.io.IOException,public void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public long transferTo(java.io.Writer) throws java.io.IOException<variables>private static final int TRANSFER_BUFFER_SIZE,protected java.lang.Object lock,private static final int maxSkipBufferSize,private char[] skipBuffer
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/ada/AdaLexer.java
AdaLexer
takeLiteral
class AdaLexer extends JFlexSymbolMatcher implements JFlexJointLexer, Resettable { /** * Writes {@code value} to output -- if it contains any EOLs then the * {@link JFlexJointLexer#startNewLine()} is called in lieu of outputting * EOL. */ public void takeLiteral(String value, String className) throws IOException {<FILL_FUNCTION_BODY>} /** * Calls {@link #phLOC()} if the yystate is not SCOMMENT. */ public void chkLOC() { if (yystate() != SCOMMENT()) { phLOC(); } } /** * Subclasses must override to get the constant value created by JFlex to * represent SCOMMENT. */ @SuppressWarnings("java:S100") abstract int SCOMMENT(); }
disjointSpan(className); int off = 0; do { int w = 1; int i; int ri = value.indexOf("\r", off); int ni = value.indexOf("\n", off); if (ri == -1 && ni == -1) { String sub = value.substring(off); offer(sub); break; } if (ri != -1 && ni != -1) { if (ri < ni) { i = ri; if (value.charAt(ri) == '\r' && value.charAt(ni) == '\n') { w = 2; } } else { i = ni; } } else if (ri != -1) { i = ri; } else { i = ni; } String sub = value.substring(off, i); offer(sub); disjointSpan(null); startNewLine(); disjointSpan(className); off = i + w; } while (off < value.length()); disjointSpan(null);
245
285
530
<methods>public non-sealed void <init>() ,public void clearNonSymbolMatchedListener() ,public void clearSymbolMatchedListener() ,public void setNonSymbolMatchedListener(org.opengrok.indexer.analysis.NonSymbolMatchedListener) ,public void setSymbolMatchedListener(org.opengrok.indexer.analysis.SymbolMatchedListener) <variables>private java.lang.String disjointSpanClassName,private org.opengrok.indexer.analysis.NonSymbolMatchedListener nonSymbolListener,private org.opengrok.indexer.analysis.SymbolMatchedListener symbolListener
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/archive/BZip2Analyzer.java
BZip2Analyzer
analyze
class BZip2Analyzer extends FileAnalyzer { private Genre g; @Override public Genre getGenre() { if (g != null) { return g; } return super.getGenre(); } protected BZip2Analyzer(AnalyzerFactory factory) { super(factory); } /** * @return {@code null} as there is no aligned language */ @Override public String getCtagsLang() { return null; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20180111_00 */ @Override protected int getSpecializedVersionNo() { return 20180111_00; // Edit comment above too! } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>} /** * Wrap the raw stream source in one that returns the uncompressed stream. */ private static StreamSource wrap(final StreamSource src) { return new StreamSource() { @Override public InputStream getStream() throws IOException { InputStream raw = src.getStream(); // A BZip2 file starts with "BZ", but CBZip2InputStream // expects the magic bytes to be stripped off first. if (raw.read() == 'B' && raw.read() == 'Z') { return new BufferedInputStream(new CBZip2InputStream(raw)); } else { throw new IOException("Not BZIP2 format"); } } }; } }
var optionalNewName = Optional.ofNullable(doc.get(QueryBuilder.PATH)) .filter(path -> path.toUpperCase().endsWith(".BZ2") || path.endsWith(".bz")) .map(path -> path.substring(0, path.lastIndexOf('.'))); if (optionalNewName.isPresent()) { StreamSource bzSrc = wrap(src); AbstractAnalyzer fa; try (InputStream in = bzSrc.getStream()) { fa = AnalyzerGuru.getAnalyzer(in, optionalNewName.get()); } if (!(fa instanceof BZip2Analyzer)) { this.g = Optional.ofNullable(fa.getGenre()) .filter( genre -> genre == Genre.PLAIN || genre == Genre.XREFABLE) .map(genre -> Genre.XREFABLE) .orElse(Genre.DATA); fa.analyze(doc, bzSrc, xrefOut); if (doc.get(QueryBuilder.T) != null) { doc.removeField(QueryBuilder.T); if (g == Genre.XREFABLE) { doc.add(new Field(QueryBuilder.T, g.typeName(), AnalyzerGuru.string_ft_stored_nanalyzed_norms)); } } } }
471
351
822
<methods>public void <init>(org.opengrok.indexer.analysis.AnalyzerFactory) ,public void analyze(Document, org.opengrok.indexer.analysis.StreamSource, java.io.Writer) throws java.io.IOException, java.lang.InterruptedException,public java.lang.String getCtagsLang() ,public java.lang.String getFileTypeName() ,public final long getVersionNo() ,public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>private static final java.util.logging.Logger LOGGER
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/archive/GZIPAnalyzer.java
GZIPAnalyzer
analyze
class GZIPAnalyzer extends FileAnalyzer { private static final Logger LOGGER = LoggerFactory.getLogger(GZIPAnalyzer.class); private Genre g; @Override public Genre getGenre() { if (g != null) { return g; } return super.getGenre(); } protected GZIPAnalyzer(AnalyzerFactory factory) { super(factory); } /** * @return {@code null} as there is no aligned language */ @Override public String getCtagsLang() { return null; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20180111_00 */ @Override protected int getSpecializedVersionNo() { return 20180111_00; // Edit comment above too! } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>} /** * Wrap the raw stream source in one that returns the uncompressed stream. */ private static StreamSource wrap(final StreamSource src) { return new StreamSource() { @Override public InputStream getStream() throws IOException { return new BufferedInputStream( new GZIPInputStream(src.getStream())); } }; } }
AbstractAnalyzer fa; StreamSource gzSrc = wrap(src); String path = doc.get(QueryBuilder.PATH); if (path != null && path.toLowerCase(Locale.ROOT).endsWith(".gz")) { String newname = path.substring(0, path.length() - 3); try (InputStream gzis = gzSrc.getStream()) { fa = AnalyzerGuru.getAnalyzer(gzis, newname); } if (fa == null) { this.g = Genre.DATA; LOGGER.log(Level.WARNING, "Did not analyze {0}, detected as data.", newname); //TODO we could probably wrap tar analyzer here, need to do research on reader coming from gzis ... } else { // cant recurse! //simple file gziped case captured here if (fa.getGenre() == Genre.PLAIN || fa.getGenre() == Genre.XREFABLE) { this.g = Genre.XREFABLE; } else { this.g = Genre.DATA; } fa.analyze(doc, gzSrc, xrefOut); if (doc.get(QueryBuilder.T) != null) { doc.removeField(QueryBuilder.T); if (g == Genre.XREFABLE) { doc.add(new Field(QueryBuilder.T, g.typeName(), AnalyzerGuru.string_ft_stored_nanalyzed_norms)); } } } }
408
398
806
<methods>public void <init>(org.opengrok.indexer.analysis.AnalyzerFactory) ,public void analyze(Document, org.opengrok.indexer.analysis.StreamSource, java.io.Writer) throws java.io.IOException, java.lang.InterruptedException,public java.lang.String getCtagsLang() ,public java.lang.String getFileTypeName() ,public final long getVersionNo() ,public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>private static final java.util.logging.Logger LOGGER
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/archive/TarAnalyzer.java
TarAnalyzer
analyze
class TarAnalyzer extends FileAnalyzer { protected TarAnalyzer(AnalyzerFactory factory) { super(factory); } /** * @return {@code null} as there is no aligned language */ @Override public String getCtagsLang() { return null; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20180112_00 */ @Override protected int getSpecializedVersionNo() { return 20180112_00; // Edit comment above too! } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException {<FILL_FUNCTION_BODY>} }
ArrayList<String> names = new ArrayList<>(); try (TarInputStream zis = new TarInputStream(src.getStream())) { TarEntry entry; while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); names.add(name); if (xrefOut != null) { Util.htmlize(name, xrefOut); xrefOut.append("<br/>"); } } } doc.add(new OGKTextField(QueryBuilder.FULL, new IteratorReader(names)));
226
151
377
<methods>public void <init>(org.opengrok.indexer.analysis.AnalyzerFactory) ,public void analyze(Document, org.opengrok.indexer.analysis.StreamSource, java.io.Writer) throws java.io.IOException, java.lang.InterruptedException,public java.lang.String getCtagsLang() ,public java.lang.String getFileTypeName() ,public final long getVersionNo() ,public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>private static final java.util.logging.Logger LOGGER
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/archive/ZipAnalyzer.java
ZipAnalyzer
analyze
class ZipAnalyzer extends FileAnalyzer { protected ZipAnalyzer(AnalyzerFactory factory) { super(factory); } /** * @return {@code null} as there is no aligned language */ @Override public String getCtagsLang() { return null; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20180112_00 */ @Override protected int getSpecializedVersionNo() { return 20180112_00; // Edit comment above too! } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException {<FILL_FUNCTION_BODY>} }
ArrayList<String> names = new ArrayList<>(); try (ZipInputStream zis = new ZipInputStream(src.getStream())) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); names.add(name); if (xrefOut != null) { Util.htmlize(name, xrefOut); xrefOut.append("<br/>"); } } } doc.add(new OGKTextField(QueryBuilder.FULL, new IteratorReader(names)));
228
153
381
<methods>public void <init>(org.opengrok.indexer.analysis.AnalyzerFactory) ,public void analyze(Document, org.opengrok.indexer.analysis.StreamSource, java.io.Writer) throws java.io.IOException, java.lang.InterruptedException,public java.lang.String getCtagsLang() ,public java.lang.String getFileTypeName() ,public final long getVersionNo() ,public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>private static final java.util.logging.Logger LOGGER
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/archive/ZipMatcherBase.java
ZipMatcherBase
isMagic
class ZipMatcherBase implements FileAnalyzerFactory.Matcher { private static final byte[] MAGIC = {'P', 'K', 3, 4}; private static final int LOCHDRSIZ = 30; private static final int XFHSIZ = 4; @Override public boolean isPreciseMagic() { return true; } @Override public AnalyzerFactory isMagic(byte[] contents, InputStream in) throws IOException {<FILL_FUNCTION_BODY>} /** * Derived classes must implement to get a value indicating if the ZIP * "Extra field ID" should be checked to match the value returne by * {@link #strictExtraFieldID()}. * @return {@code true} if "Extra field ID" should be checked */ protected abstract boolean doesCheckExtraFieldID(); /** * Derived classes that override {@link #doesCheckExtraFieldID()} to return * {@code true} must override this method to return the value that must * equal an "Extra field ID" in the ZIP file in order for * {@link #isMagic(byte[], java.io.InputStream)} to match and return a * defined instance. * @return {@code null} */ protected Integer strictExtraFieldID() { return null; } private int CH(byte[] b, int n) { return b[n] & 0xff; } private int SH(byte[] b, int n) { return CH(b, n) | (CH(b, n + 1) << 8); } private int LOCNAM(byte[] b) { return SH(b, 26); } private int LOCEXT(byte[] b) { return SH(b, 28); } }
assert in.markSupported(); if (contents.length < MAGIC.length) { return null; } for (int i = 0; i < MAGIC.length; i++) { if (contents[i] != MAGIC[i]) { return null; } } if (!doesCheckExtraFieldID()) { return forFactory(); } else { byte[] buf = new byte[1024]; in.mark(buf.length); int len = in.read(buf); in.reset(); int xoff = LOCHDRSIZ + LOCNAM(buf); int xoffEnd = Math.min(len, xoff + LOCEXT(buf)); while ((xoff < xoffEnd) && (len - xoff >= XFHSIZ)) { int xfhid = SH(buf, xoff); if (xfhid == strictExtraFieldID()) { return forFactory(); } int xfdatasiz = SH(buf, xoff + 2); xoff += XFHSIZ + xfdatasiz; } return null; }
464
296
760
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/data/IgnorantAnalyzerFactory.java
IgnorantAnalyzerFactory
newAnalyzer
class IgnorantAnalyzerFactory extends FileAnalyzerFactory { private static final String[] SUFFIXES = { "BDF", "XPM", "PS", "AFM", "PDF", "LIB", "PDB" }; private static final String[] MAGICS = { "%!PS-", // post script files "# PaCkAg", "%PDF", "Microsoft C/C++ MSF ", // PDB files: https://msdn.microsoft.com/en-us/library/yd4f8bd1(vs.71).aspx "!<arch>", // LIB files: https://msdn.microsoft.com/en-us/library/ba1z7822.aspx }; public IgnorantAnalyzerFactory() { super(null, null, SUFFIXES, MAGICS, null, null, null, null, false); } @Override protected AbstractAnalyzer newAnalyzer() {<FILL_FUNCTION_BODY>} }
// just use a FileAnalyzer since it won't analyze or xref the file return new FileAnalyzer(this);
254
33
287
<methods>public final org.opengrok.indexer.analysis.AbstractAnalyzer getAnalyzer() ,public java.lang.String getName() ,public void returnAnalyzer() <variables>private final non-sealed java.lang.String name
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/data/ImageAnalyzerFactory.java
ImageAnalyzerFactory
newAnalyzer
class ImageAnalyzerFactory extends FileAnalyzerFactory { private static final String NAME = "Image file"; private static final String[] SUFFIXES = { "PNG", "GIF", "JPEG", "JPG", "TIFF", "BMP" }; public ImageAnalyzerFactory() { super(null, null, SUFFIXES, null, null, null, AbstractAnalyzer.Genre.IMAGE, NAME, false); } @Override protected AbstractAnalyzer newAnalyzer() {<FILL_FUNCTION_BODY>} }
// just use a FileAnalyzer since it won't analyze or xref the file return new FileAnalyzer(this);
145
33
178
<methods>public final org.opengrok.indexer.analysis.AbstractAnalyzer getAnalyzer() ,public java.lang.String getName() ,public void returnAnalyzer() <variables>private final non-sealed java.lang.String name
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/document/DocumentMatcher.java
DocumentMatcher
isMagic
class DocumentMatcher implements Matcher { /** * Set to 512K {@code int}, but {@code NUMCHARS_FIRST_LOOK} and * {@code LINE_LIMIT} should apply beforehand. This value is "effectively * unbounded" without being literally 2_147_483_647 -- as the other limits * will apply first, and the {@link java.io.BufferedInputStream} will * manage a reasonably-sized buffer. */ private static final int MARK_READ_LIMIT = 1024 * 512; private static final int LINE_LIMIT = 100; private static final int FIRST_LOOK_WIDTH = 300; private final AnalyzerFactory factory; private final String[] lineStarters; /** * Initializes an instance for the required parameters. * @param factory required factory to return when matched * @param lineStarters required list of line starters that indicate a match * @throws IllegalArgumentException thrown if any parameter is null */ public DocumentMatcher(AnalyzerFactory factory, String[] lineStarters) { if (factory == null) { throw new IllegalArgumentException("`factory' is null"); } if (lineStarters == null) { throw new IllegalArgumentException("`lineStarters' is null"); } if (lineStarters.length < 1) { throw new IllegalArgumentException("`lineStarters' is empty"); } String[] copyOf = Arrays.copyOf(lineStarters, lineStarters.length); for (String elem : copyOf) { if (elem == null) { throw new IllegalArgumentException( "`lineStarters' has null element"); } } this.factory = factory; this.lineStarters = copyOf; } /** * Try to match the file contents by looking for {@code lineStarters} in * the first 100 lines while also affirming that the document starts * with "." or "'" after a limited amount of whitespace. * <p> * The stream is reset before returning. * * @param contents the first few bytes of a file * @param in the input stream from which the full file can be read * @return an analyzer factory if the contents match, or {@code null} * otherwise * @throws IOException in case of any read error */ @Override public AnalyzerFactory isMagic(byte[] contents, InputStream in) throws IOException {<FILL_FUNCTION_BODY>} @Override public AnalyzerFactory forFactory() { return factory; } /** * Determines if the {@code in} stream has a line feed character within the * first {@code FIRST_LOOK_WIDTH} characters. * @param in the input stream has any BOM (not {@code reset} after use) * @param encoding the input stream charset * @return true if a line feed '\n' was found * @throws IOException thrown on any error in reading */ private boolean hasLineFeed(InputStream in, String encoding) throws IOException { byte[] buf; int nextra; int noff; switch (encoding) { case "UTF-16LE": buf = new byte[FIRST_LOOK_WIDTH * 2]; nextra = 1; noff = 0; break; case "UTF-16BE": buf = new byte[FIRST_LOOK_WIDTH * 2]; nextra = 1; noff = 1; break; default: buf = new byte[FIRST_LOOK_WIDTH]; nextra = 0; noff = 0; break; } int nread = in.read(buf); for (int i = 0; i + nextra < nread; i += 1 + nextra) { if (nextra > 0) { if (buf[i + noff] == '\n' && buf[i + 1 - noff] == '\0') { return true; } } else { if (buf[i] == '\n') { return true; } } } return false; } }
if (!in.markSupported()) { return null; } in.mark(MARK_READ_LIMIT); // read encoding, and skip past any BOM int bomLength = 0; String encoding = IOUtils.findBOMEncoding(contents); if (encoding == null) { encoding = StandardCharsets.UTF_8.name(); } else { bomLength = IOUtils.skipForBOM(contents); if (in.skip(bomLength) != bomLength) { in.reset(); return null; } } // affirm that a LF exists in a first block boolean foundLF = hasLineFeed(in, encoding); in.reset(); if (!foundLF) { return null; } if (bomLength > 0 && in.skip(bomLength) != bomLength) { in.reset(); return null; } // read line-by-line for a first few lines BufferedReader rdr = new BufferedReader(new InputStreamReader( in, encoding)); boolean foundContent = false; int numFirstChars = 0; int numLines = 0; String line; while ((line = rdr.readLine()) != null) { for (String lineStarter : lineStarters) { if (line.startsWith(lineStarter)) { in.reset(); return factory; } } if (++numLines >= LINE_LIMIT) { in.reset(); return null; } // If not yet `foundContent', then only a limited allowance is // given until a sentinel '.' or '\'' must be seen after nothing // else but whitespace. if (!foundContent) { for (int i = 0; i < line.length() && numFirstChars < FIRST_LOOK_WIDTH; ++i, ++numFirstChars) { char c = line.charAt(i); if (c == '.' || c == '\'') { foundContent = true; break; } else if (!Character.isWhitespace(c)) { in.reset(); return null; } } if (!foundContent && numFirstChars >= FIRST_LOOK_WIDTH) { in.reset(); return null; } } } in.reset(); return null;
1,083
624
1,707
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/document/MandocAnalyzer.java
MandocAnalyzer
analyze
class MandocAnalyzer extends TextAnalyzer { /** * Creates a new instance of MandocAnalyzer. * @param factory defined instance for the analyzer */ protected MandocAnalyzer(AnalyzerFactory factory) { super(factory, () -> new JFlexTokenizer(new TroffFullTokenizer( AbstractAnalyzer.DUMMY_READER))); } /** * @return {@code null} as there is no aligned language (nevermind ctags * supporting "Man" which is not useful for OpenGrok) */ @Override public String getCtagsLang() { return null; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20171218_00 */ @Override protected int getSpecializedVersionNo() { return 20171218_00; // Edit comment above too! } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>} /** * Creates a wrapped {@link MandocXref} instance. * @param reader the data to produce xref for * @return an xref instance */ @Override protected Xrefer newXref(Reader reader) { return new MandocXref(reader); } }
// this is to explicitly use appropriate analyzers tokenstream to // workaround #1376 symbols search works like full text search JFlexTokenizer symbolTokenizer = symbolTokenizerFactory.get(); symbolTokenizer.setReader(getReader(src.getStream())); OGKTextField full = new OGKTextField(QueryBuilder.FULL, symbolTokenizer); doc.add(full); if (xrefOut != null) { try (Reader in = getReader(src.getStream())) { WriteXrefArgs args = new WriteXrefArgs(in, xrefOut); args.setProject(project); XrefWork xrefWork = new XrefWork(args, this); try { Xrefer xref = xrefWork.getXrefer(); String path = doc.get(QueryBuilder.PATH); addNumLinesLOC(doc, new NumLinesLOC(path, xref.getLineNumber(), xref.getLOC())); } catch (ExecutionException e) { throw new InterruptedException("failed to generate xref :" + e); } } }
393
284
677
<methods>public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/document/MandocAnalyzerFactory.java
MandocAnalyzerFactory
isMagic
class MandocAnalyzerFactory extends FileAnalyzerFactory { private static final String NAME = "Manual pages"; public static final Matcher MATCHER = new Matcher() { @Override public AnalyzerFactory isMagic(byte[] contents, InputStream in) throws IOException {<FILL_FUNCTION_BODY>} @Override public AnalyzerFactory forFactory() { return getTrueMenMatcher().forFactory(); } }; public static final MandocAnalyzerFactory DEFAULT_INSTANCE = new MandocAnalyzerFactory(); protected MandocAnalyzerFactory() { super(null, null, null, null, MATCHER, "text/plain", AbstractAnalyzer.Genre.PLAIN, NAME, true); } @Override protected AbstractAnalyzer newAnalyzer() { return new MandocAnalyzer(this); } // Because DEFAULT_INSTANCE during its initialization uses the MATCHER, // while at the same time the DocumentMatcher in its initialization takes // a FileAnalyzerFactory, and because we want the instances to be the same // instance, then defer initialization of the DocumentMatcher using the // "16.6 Lazy initialization holder class idiom," written by Brian Goetz // and Tim Peierls with assistance from members of JCP JSR-166 Expert Group // and released to the public domain, as explained at // http://creativecommons.org/licenses/publicdomain . private static class TrueMatcherHolder { /** * The prologue, which consists of the Dd, Dt, and Os macros in that * order, is required for every document. * * As {@link TroffXref} does not present mdoc(5) documents well, even * if no mandoc binary is configured, then we want a * {@link MandocAnalyzer} that presents a plain-text cross-referencing. */ public static final DocumentMatcher MDOCMATCHER = new DocumentMatcher( DEFAULT_INSTANCE, new String[] {".Dd", ".Dt", ".Os"}); /** * As with {@code MDOCMATCHER} except that when a mandoc binary is * configured, then man(5) documents with a .TH also will use the * {@link MandocAnalyzer}. */ public static final DocumentMatcher MENMATCHER = new DocumentMatcher( DEFAULT_INSTANCE, new String[] {".Dd", ".Dt", ".Os", ".TH"}); } /** Gets a matcher that is mdoc(5)-specific. */ private static DocumentMatcher getTrueMdocMatcher() { return TrueMatcherHolder.MDOCMATCHER; } /** Gets a matcher that matches mdoc(5) and man(5). */ private static DocumentMatcher getTrueMenMatcher() { return TrueMatcherHolder.MENMATCHER; } }
return RuntimeEnvironment.getInstance().getMandoc() != null ? getTrueMenMatcher().isMagic(contents, in) : getTrueMdocMatcher().isMagic(contents, in);
730
54
784
<methods>public final org.opengrok.indexer.analysis.AbstractAnalyzer getAnalyzer() ,public java.lang.String getName() ,public void returnAnalyzer() <variables>private final non-sealed java.lang.String name
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/document/MandocRunner.java
MandocRunner
write
class MandocRunner { private static final Logger LOGGER = LoggerFactory.getLogger( MandocRunner.class); private Process mandoc; private OutputStreamWriter mandocIn; private BufferedReader mandocOut; private Thread errThread; private String osOverride = "GENERIC SYSTEM"; /** * Gets the value used for mandoc's setting to "Override the default * operating system name". Default is {@code "GENERIC SYSTEM"}. * @return a defined value or {@code null} */ public String getOSOverride() { return osOverride; } /** * Sets the value used for mandoc's setting to "Override the default * operating system name". * @param value a defined value or {@code null} to disable the override */ public void setOSOverride( String value ) { osOverride = value; } /** * Starts a run of the mandoc binary to receive input from {@link #write}. * @throws IOException thrown if a read or write to the mandoc process * fails. * @throws MandocException if no mandoc binary is defined */ public void start() throws IOException, MandocException { destroy(); RuntimeEnvironment env = RuntimeEnvironment.getInstance(); String binary = env.getMandoc(); if (binary == null) { throw new MandocException("no mandoc binary is defined"); } List<String> command = new ArrayList<>(); command.add(binary); command.add("-c"); // do not use `more` command.add("-Kutf-8"); // explicitly set the output encoding command.add("-Thtml"); // Produce HTML5, CSS1, and MathML output command.add("-Ofragment"); // HTML fragment only // Override the default operating system name String oo = osOverride; if (oo != null) { command.add("-I"); command.add("os=" + oo); } if (LOGGER.isLoggable(Level.FINER)) { StringBuilder sb = new StringBuilder(); command.forEach(s -> sb.append(s).append(" ")); String cmd = sb.toString(); LOGGER.log(Level.FINER, "Executing mandoc command [{0}]", cmd); } ProcessBuilder processBuilder = new ProcessBuilder(command); Process starting = processBuilder.start(); OutputStreamWriter inn = new OutputStreamWriter( starting.getOutputStream(), StandardCharsets.UTF_8); BufferedReader rdr = new BufferedReader(new InputStreamReader( starting.getInputStream(), StandardCharsets.UTF_8)); InputStream errorStream = starting.getErrorStream(); mandocIn = inn; mandocOut = rdr; mandoc = starting; errThread = new Thread(() -> { // implicitly capture `errorStream' for the InputStreamReader try (BufferedReader error = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8))) { String s; while ((s = error.readLine()) != null) { LOGGER.log(Level.WARNING, "Error from mandoc: {0}", s); } } catch (IOException ex) { // ignore } }); errThread.setDaemon(true); errThread.start(); } /** * Finishes a run of mandoc for its output. * @return the stdout output of the run. * @throws IOException thrown if closing the mandoc process fails. * @throws MandocException thrown if mandoc exits non-zero. */ public String finish() throws IOException, MandocException { if (mandoc == null) { return ""; } StringBuilder output = new StringBuilder(); int rc; try { String line; mandocIn.close(); while ((line = mandocOut.readLine()) != null) { output.append(line); output.append('\n'); } mandoc.waitFor(10, TimeUnit.SECONDS); rc = mandoc.exitValue(); } catch (InterruptedException e) { return ""; } finally { destroy(); } if (rc != 0) { throw new MandocException("exit code " + rc); } return output.toString(); } /** * Writes a character to the input of the run of mandoc. * @param s the string to write. * @throws IllegalStateException thrown if the runner was not successfully * {@link #start}ed. * @throws IOException thrown if a write to the mandoc process fails. */ public void write(String s) throws IOException {<FILL_FUNCTION_BODY>} /** * Kills the mandoc process if it is running. */ public void destroy() { // terminate straightaway any existing run if (errThread != null) { errThread.interrupt(); errThread = null; } if (mandoc != null) { Process destroying = mandoc; mandoc = null; if (mandocIn != null) { IOUtils.close(mandocIn); mandocIn = null; } if (mandocOut != null) { IOUtils.close(mandocOut); mandocOut = null; } destroying.destroyForcibly(); } } }
if (mandocIn == null) { throw new IllegalStateException("start() must succeed first"); } mandocIn.write(s);
1,415
42
1,457
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/document/TroffAnalyzer.java
TroffAnalyzer
analyze
class TroffAnalyzer extends TextAnalyzer { /** * Creates a new instance of TroffAnalyzer. * @param factory defined instance for the analyzer */ protected TroffAnalyzer(AnalyzerFactory factory) { super(factory, () -> new JFlexTokenizer(new TroffFullTokenizer( AbstractAnalyzer.DUMMY_READER))); } /** * @return {@code null} as there is no aligned language */ @Override public String getCtagsLang() { return null; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20180112_00 */ @Override protected int getSpecializedVersionNo() { return 20180112_00; // Edit comment above too! } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>} /** * Creates a wrapped {@link TroffXref} instance. * @param reader the data to produce xref for * @return xref instance */ @Override protected Xrefer newXref(Reader reader) { return new TroffXref(reader); } }
//this is to explicitly use appropriate analyzers tokenstream to workaround #1376 symbols search works like full text search JFlexTokenizer symbolTokenizer = symbolTokenizerFactory.get(); symbolTokenizer.setReader(getReader(src.getStream())); OGKTextField full = new OGKTextField(QueryBuilder.FULL, symbolTokenizer); doc.add(full); if (xrefOut != null) { try (Reader in = getReader(src.getStream())) { WriteXrefArgs args = new WriteXrefArgs(in, xrefOut); args.setProject(project); XrefWork xrefWork = new XrefWork(args, this); try { Xrefer xref = xrefWork.getXrefer(); String path = doc.get(QueryBuilder.PATH); addNumLinesLOC(doc, new NumLinesLOC(path, xref.getLineNumber(), xref.getLOC())); } catch (ExecutionException e) { throw new InterruptedException("failed to generate xref :" + e); } } }
370
280
650
<methods>public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/eiffel/EiffelLexer.java
EiffelLexer
maybeEndVerbatim
class EiffelLexer extends JFlexSymbolMatcher implements JFlexJointLexer, Resettable { /** * When matching a Verbatim_string, the expected closer is stored here. */ private String vstring_closer; /** * Resets the instance to an initial state. */ @Override public void reset() { super.reset(); vstring_closer = null; } /** * Begin a "Verbatim_string" according to the specified for the specified * "Verbatim_string_opener", {@code opener}, determining the matching * "Verbatim_string_closer" to be used with * {@link #maybeEndVerbatim(java.lang.String)}. * <p> * Everything between the first and last character of {@code opener} is the * verbatim string α, and the last character's opposite becomes the initial * character of the closer. * @param opener a defined opener following Eiffel "8.29.10 Syntax: * Manifest strings" */ public void vop(String opener) throws IOException { int lastoff = opener.length() - 1; String alpha = opener.substring(1, lastoff); String close0; switch (opener.charAt(lastoff)) { case '{': close0 = "}"; break; case '[': close0 = "]"; break; default: throw new IllegalArgumentException("Bad opener: " + opener); } vstring_closer = close0 + alpha + "\""; yypush(VSTRING()); disjointSpan(HtmlConsts.STRING_CLASS); offer(opener); } /** * Determine if the specified {@code capture} starts with the expected * "Verbatim_string_closer" from * {@link #vop(java.lang.String) }, and if so, pop the state, write the * closer, and push back any excess; otherwise, write the first character * of {@code capture}, and push back the rest. * @param capture a defined, possible ender * @throws IOException if output fails */ public void maybeEndVerbatim(String capture) throws IOException {<FILL_FUNCTION_BODY>} /** * Calls {@link #phLOC()} if the yystate is not SCOMMENT. */ public void chkLOC() { if (yystate() != SCOMMENT()) { phLOC(); } } /** * Subclasses must override to get the constant value created by JFlex to * represent SCOMMENT. */ abstract int SCOMMENT(); /** * Subclasses must override to get the constant value created by JFlex to * represent VSTRING. */ abstract int VSTRING(); }
int npushback; if (!capture.startsWith(vstring_closer)) { // Nope--so just write the double quote, and push back the rest. offer(capture.substring(0, 1)); npushback = capture.length() - 1; } else { offer(vstring_closer); disjointSpan(null); yypop(); npushback = capture.length() - vstring_closer.length(); vstring_closer = null; } if (npushback > 0) { yypushback(npushback); }
745
161
906
<methods>public non-sealed void <init>() ,public void clearNonSymbolMatchedListener() ,public void clearSymbolMatchedListener() ,public void setNonSymbolMatchedListener(org.opengrok.indexer.analysis.NonSymbolMatchedListener) ,public void setSymbolMatchedListener(org.opengrok.indexer.analysis.SymbolMatchedListener) <variables>private java.lang.String disjointSpanClassName,private org.opengrok.indexer.analysis.NonSymbolMatchedListener nonSymbolListener,private org.opengrok.indexer.analysis.SymbolMatchedListener symbolListener
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/executables/JFieldBuilder.java
JFieldBuilder
write
class JFieldBuilder { private final Map<String, StringWriter> fieldBuilders = new HashMap<>(); boolean hasField(String fieldName) { return fieldBuilders.containsKey(fieldName); } StringWriter write(String fieldName) {<FILL_FUNCTION_BODY>} }
StringWriter res = fieldBuilders.getOrDefault(fieldName, null); if (res != null) { return res; } res = new StringWriter(); fieldBuilders.put(fieldName, res); return res;
80
66
146
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/executables/JarAnalyzer.java
JarAnalyzer
analyze
class JarAnalyzer extends FileAnalyzer { private static final String[] UNSTORED_FIELD_NAMES = new String[] {QueryBuilder.FULL, QueryBuilder.REFS}; protected JarAnalyzer(AnalyzerFactory factory) { super(factory); } /** * @return {@code null} as there is no aligned language */ @Override public String getCtagsLang() { return null; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20180612_00 */ @Override protected int getSpecializedVersionNo() { return 20180612_00; // Edit comment above too! } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException {<FILL_FUNCTION_BODY>} }
JFieldBuilder jfbuilder = new JFieldBuilder(); try (ZipInputStream zis = new ZipInputStream(src.getStream())) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String ename = entry.getName(); if (xrefOut != null) { xrefOut.append("<br/><b>"); Util.htmlize(ename, xrefOut); xrefOut.append("</b>"); } StringWriter fout = jfbuilder.write(QueryBuilder.FULL); fout.write(ename); fout.write("\n"); AnalyzerFactory fac = AnalyzerGuru.find(ename); if (fac instanceof JavaClassAnalyzerFactory) { if (xrefOut != null) { xrefOut.append("<br/>"); } JavaClassAnalyzer jca = (JavaClassAnalyzer) fac.getAnalyzer(); jca.analyze(doc, new BufferedInputStream(zis), xrefOut, jfbuilder); } } } for (String name : UNSTORED_FIELD_NAMES) { if (jfbuilder.hasField(name)) { String fstr = jfbuilder.write(name).toString(); doc.add(new OGKTextField(name, fstr, Store.NO)); } } String name = QueryBuilder.DEFS; if (jfbuilder.hasField(name)) { String fstr = jfbuilder.write(name).toString(); doc.add(new OGKTextVecField(name, fstr, Store.NO)); }
262
431
693
<methods>public void <init>(org.opengrok.indexer.analysis.AnalyzerFactory) ,public void analyze(Document, org.opengrok.indexer.analysis.StreamSource, java.io.Writer) throws java.io.IOException, java.lang.InterruptedException,public java.lang.String getCtagsLang() ,public java.lang.String getFileTypeName() ,public final long getVersionNo() ,public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>private static final java.util.logging.Logger LOGGER
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/executables/JarAnalyzerFactory.java
JarAnalyzerFactory
description
class JarAnalyzerFactory extends FileAnalyzerFactory { private static final String NAME = "Jar"; private static final String[] SUFFIXES = { "JAR", "WAR", "EAR" }; private static final Matcher MATCHER = new ZipMatcherBase() { @Override public String description() {<FILL_FUNCTION_BODY>} @Override public AnalyzerFactory forFactory() { return JarAnalyzerFactory.DEFAULT_INSTANCE; } @Override protected boolean doesCheckExtraFieldID() { return true; } @Override protected Integer strictExtraFieldID() { return 0xCAFE; } }; public static final JarAnalyzerFactory DEFAULT_INSTANCE = new JarAnalyzerFactory(); private JarAnalyzerFactory() { super(null, null, SUFFIXES, null, MATCHER, null, AbstractAnalyzer.Genre.XREFABLE, NAME, false); } @Override protected AbstractAnalyzer newAnalyzer() { return new JarAnalyzer(this); } }
return "PK\\{3}\\{4} magic signature with 0xCAFE Extra Field ID";
290
27
317
<methods>public final org.opengrok.indexer.analysis.AbstractAnalyzer getAnalyzer() ,public java.lang.String getName() ,public void returnAnalyzer() <variables>private final non-sealed java.lang.String name
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/executables/JavaClassAnalyzerFactory.java
JavaClassAnalyzerFactory
isMagic
class JavaClassAnalyzerFactory extends FileAnalyzerFactory { private static final String NAME = "Java class"; private static final String[] SUFFIXES = { "CLASS" }; private static final byte[] CAFEBABE = new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE}; private static final int MAJOR_VER_HIGHBYTE = 6; private static final int MAJOR_VER_LOWBYTE = 7; private static final int JDK1_1_MAJOR_VER = 0x2D; private static final int JAVA_SE_9_MAJOR_VER = 0x35; private static final Matcher MATCHER = new Matcher() { @Override public boolean isPreciseMagic() { return true; } @Override public String description() { return "0xCAFEBABE magic with major_version from JDK 1.1 to Java" + " SE 9"; } @Override public AnalyzerFactory isMagic(byte[] content, InputStream in) {<FILL_FUNCTION_BODY>} @Override public AnalyzerFactory forFactory() { return JavaClassAnalyzerFactory.DEFAULT_INSTANCE; } }; public static final JavaClassAnalyzerFactory DEFAULT_INSTANCE = new JavaClassAnalyzerFactory(); private JavaClassAnalyzerFactory() { super(null, null, SUFFIXES, null, MATCHER, null, AbstractAnalyzer.Genre.XREFABLE, NAME, false); } /** * Creates a new {@link JavaClassAnalyzer} instance. * @return a defined instance */ @Override protected AbstractAnalyzer newAnalyzer() { return new JavaClassAnalyzer(this); } }
if (content.length < 8) { return null; } // Require CAFEBABE or indicate no match. for (int i = 0; i < CAFEBABE.length; ++i) { if (content[i] != CAFEBABE[i]) { return null; } } // Require known major_version number. int majorVersion = ((content[MAJOR_VER_HIGHBYTE] & 0xff) << 1) | (content[MAJOR_VER_LOWBYTE] & 0xff); if (majorVersion >= JDK1_1_MAJOR_VER && majorVersion <= JAVA_SE_9_MAJOR_VER) { return JavaClassAnalyzerFactory.DEFAULT_INSTANCE; } return null;
484
214
698
<methods>public final org.opengrok.indexer.analysis.AbstractAnalyzer getAnalyzer() ,public java.lang.String getName() ,public void returnAnalyzer() <variables>private final non-sealed java.lang.String name
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/hcl/HCLLexer.java
HCLLexer
hereOp
class HCLLexer extends JFlexSymbolMatcher implements JFlexJointLexer, Resettable { // Defined to be the equivalent of {Identifier} from HCL.lexh private static final Pattern HERE_TERMINATOR_MATCH = Pattern.compile( "^\\p{javaUnicodeIdentifierStart}(\\p{javaUnicodeIdentifierPart}|-)*"); private HCLLexerData dataHead; private Stack<HCLLexerData> data; protected HCLLexer() { dataHead = new HCLLexerData(); } /** * Resets the instance to an initial state. */ @Override public void reset() { super.reset(); dataHead = new HCLLexerData(); if (data != null) { data.clear(); } } /** * Parses a Here-document declaration, and takes the {@code capture} using * {@link HCLLexer#offer(String)}. If the declaration is valid, * {@code hereSettings} will have been appended. */ public void hereOp(String capture) throws IOException {<FILL_FUNCTION_BODY>} /** * Pushes the first Here-document state if any declarations were parsed, or * else does nothing. * @return true if a Here state was pushed */ public boolean maybeHereStart() throws IOException { if (dataHead.hereSettings != null && !dataHead.hereSettings.isEmpty()) { HereDocSettings settings = dataHead.hereSettings.peek(); yypush(settings.state); disjointSpan(HtmlConsts.STRING_CLASS); return true; } return false; } /** * Process the {@code capture}, possibly ending the Here-document state * just beforehand. * @return true if the Here state ended */ public boolean maybeHereEnd(String capture) throws IOException { String trimmed = capture.stripLeading(); HereDocSettings settings = dataHead.hereSettings.peek(); assert settings != null; boolean didZspan = false; if (trimmed.equals(settings.terminator)) { disjointSpan(null); didZspan = true; dataHead.hereSettings.remove(); } offer(capture); if (!dataHead.hereSettings.isEmpty()) { settings = dataHead.hereSettings.peek(); yybegin(settings.state); if (didZspan) { disjointSpan(HtmlConsts.STRING_CLASS); } return false; } yypop(); return true; } /** * Resets the interpolation counter to 1. */ public void interpOp() { dataHead.numEndBrace = 1; } /** * Determine if the interpolation should end based on the first character * of {@code capture}, recognizing tokens that increase the nesting level * instead. * <p> * Calling this method has side effects to possibly modify * {@code numEndBrace}. * @return true if the interpolation state ended */ public boolean maybeInterpolationEnd(String capture) throws IOException { if (dataHead.numEndBrace <= 0) { return false; } if (capture.startsWith("}")) { if (--dataHead.numEndBrace <= 0) { int rem = capture.length() - 1; String opener = capture.substring(0, 1); popData(); yypop(); disjointSpan(HtmlConsts.STRING_CLASS); offer(opener); if (rem > 0) { yypushback(rem); } return true; } } else if (capture.startsWith("{")) { ++dataHead.numEndBrace; } return false; } /** * Calls {@link #phLOC()} if the yystate is not COMMENT or SCOMMENT. */ public void chkLOC() { int yystate = yystate(); if (yystate != COMMENT() && yystate != SCOMMENT()) { phLOC(); } } /** * Push the lexer state data on the stack, and initialize a new state. */ public void pushData() { if (data == null) { data = new Stack<>(); } data.push(dataHead); dataHead = new HCLLexerData(); } /** * Discard the current lexer state, and pop state off the stack. */ public void popData() { dataHead = data.pop(); } /** * Subclasses must override to get the constant value created by JFlex to * represent COMMENT. */ public abstract int COMMENT(); /** * Subclasses must override to get the constant value created by JFlex to * represent SCOMMENT. */ public abstract int SCOMMENT(); /** * Subclasses must override to get the constant value created by JFlex to * represent HERE. */ public abstract int HERE(); /** * Subclasses must override to get the constant value created by JFlex to * represent HEREin. */ public abstract int HEREin(); private static class HereDocSettings { private final String terminator; private final int state; HereDocSettings(String terminator, int state) { this.terminator = terminator; this.state = state; } } private static class HCLLexerData { private Queue<HereDocSettings> hereSettings; /** * When interpolating inside a quoting construct, the number of * remaining '}' is stored. It starts at 1, and any nesting increases * the value. */ private int numEndBrace; } }
if (!capture.startsWith("<<")) { throw new IllegalArgumentException("bad HERE: " + capture); } offer(capture); if (dataHead.hereSettings == null) { dataHead.hereSettings = new LinkedList<>(); } String remaining = capture; boolean indented = false; int i = 0; HereDocSettings settings; String terminator; String opener = remaining.substring(0, i + "<<".length()); remaining = remaining.substring(opener.length()); if (remaining.startsWith("-")) { indented = true; remaining = remaining.substring(1); } // Trim any whitespace, which is allowed by HCL after the HERE op. remaining = remaining.stripLeading(); Matcher m = HERE_TERMINATOR_MATCH.matcher(remaining); if (!m.find()) { return; } terminator = m.group(0); int state = indented ? HEREin() : HERE(); settings = new HereDocSettings(terminator, state); dataHead.hereSettings.add(settings);
1,532
298
1,830
<methods>public non-sealed void <init>() ,public void clearNonSymbolMatchedListener() ,public void clearSymbolMatchedListener() ,public void setNonSymbolMatchedListener(org.opengrok.indexer.analysis.NonSymbolMatchedListener) ,public void setSymbolMatchedListener(org.opengrok.indexer.analysis.SymbolMatchedListener) <variables>private java.lang.String disjointSpanClassName,private org.opengrok.indexer.analysis.NonSymbolMatchedListener nonSymbolListener,private org.opengrok.indexer.analysis.SymbolMatchedListener symbolListener
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/javascript/JavaScriptLexer.java
JavaScriptLexer
notInTemplateOrSubstitutionDoesNotEnd
class JavaScriptLexer extends JFlexSymbolMatcher implements JFlexJointLexer, Resettable { private ECMAScriptLexerData data; /** * Represents the stack of data if substitution is nested. */ private Stack<ECMAScriptLexerData> dataStack; public JavaScriptLexer() { data = new ECMAScriptLexerData(); // dataStack is null to begin. } /** * Resets the instance to an initial state. */ @Override public void reset() { super.reset(); data = new ECMAScriptLexerData(); if (dataStack != null) { dataStack.clear(); } } /** * Calls {@link #phLOC()} if the yystate is not COMMENT or SCOMMENT. */ public void chkLOC() { if (yystate() != COMMENT() && yystate() != SCOMMENT()) { phLOC(); } } /** * Resets the substitution brace counter to 1. */ protected void substitutionOp() { data.nEndBrace = 1; } /** * Determine if template substitution should end based on the first * character of {@code capture}, and also recognizing tokens that increase * the nesting level alternatively. * <p> * Calling this method has side effects to possibly modify * {@code nEndBrace}. * @return {@code true} if the substitution state does not end */ protected boolean notInTemplateOrSubstitutionDoesNotEnd(String capture) throws IOException {<FILL_FUNCTION_BODY>} protected void pushData() { if (dataStack == null) { dataStack = new Stack<>(); } dataStack.push(data); data = new ECMAScriptLexerData(); } private void popData() { data = dataStack.pop(); } /** * Subclasses must override to get the constant value created by JFlex to * represent COMMENT. */ protected abstract int COMMENT(); /** * Subclasses must override to get the constant value created by JFlex to * represent SCOMMENT. */ protected abstract int SCOMMENT(); private static class ECMAScriptLexerData { /** * When interpolating inside `` with ${, the number of remaining '}' * characters is stored. It starts at 1, and any nesting increases the * value. */ int nEndBrace; } }
if (data.nEndBrace <= 0) { return true; } if (capture.startsWith("}")) { if (--data.nEndBrace <= 0) { int nRemaining = capture.length() - 1; String opener = capture.substring(0, 1); popData(); yypop(); disjointSpan(HtmlConsts.STRING_CLASS); offer(opener); if (nRemaining > 0) { yypushback(nRemaining); } return false; } } if (capture.startsWith("{")) { ++data.nEndBrace; } return true;
678
184
862
<methods>public non-sealed void <init>() ,public void clearNonSymbolMatchedListener() ,public void clearSymbolMatchedListener() ,public void setNonSymbolMatchedListener(org.opengrok.indexer.analysis.NonSymbolMatchedListener) ,public void setSymbolMatchedListener(org.opengrok.indexer.analysis.SymbolMatchedListener) <variables>private java.lang.String disjointSpanClassName,private org.opengrok.indexer.analysis.NonSymbolMatchedListener nonSymbolListener,private org.opengrok.indexer.analysis.SymbolMatchedListener symbolListener
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/lua/LuaUtils.java
LuaUtils
isClosingLongBracket
class LuaUtils { /** * Private to enforce singleton. */ private LuaUtils() { } /** * Counts the level of a Lua opening long bracket specified in * {@code capture}. * @param capture the opening long bracket * @return the bracket level */ public static int countOpeningLongBracket(String capture) { if (!capture.startsWith("[") || !capture.endsWith("[")) { throw new IllegalArgumentException( "Invalid opening long bracket: " + capture); } int n = 0; for (int i = 1; i + 1 < capture.length(); ++i) { if (capture.charAt(i) != '=') { throw new IllegalArgumentException( "Invalid opening long bracket: " + capture); } ++n; } return n; } /** * Determines if the specified {@code capture} is a closing long bracket of * the specified {@code level}. * @param capture the possible Lua closing long bracket * @param level the required level of closing long bracket * @return true if the {@code capture} is determined to be the required * closing long bracket or false otherwise. */ public static boolean isClosingLongBracket(String capture, int level) {<FILL_FUNCTION_BODY>} }
if (!capture.startsWith("]") || !capture.endsWith("]")) { throw new IllegalArgumentException( "Invalid opening long bracket: " + capture); } int n = 0; for (int i = 1; i + 1 < capture.length(); ++i) { if (capture.charAt(i) != '=') { throw new IllegalArgumentException( "Invalid opening long bracket: " + capture); } ++n; } return n == level;
359
135
494
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/plain/DefinitionsTokenStream.java
DefinitionsTokenStream
initialize
class DefinitionsTokenStream extends TokenStream { /** * Defines the ultimate queue of tokens to be produced by * {@link #incrementToken()}. */ private final List<PendingToken> events = new ArrayList<>(); private final CharTermAttribute termAtt = addAttribute( CharTermAttribute.class); private final OffsetAttribute offsetAtt = addAttribute( OffsetAttribute.class); private final PositionIncrementAttribute posIncrAtt = addAttribute( PositionIncrementAttribute.class); private int offset; /** * Initializes the stream by merging {@code defs} with cross-referenced * line offsets read from {@code src}. * @param defs a defined instance * @param src a defined instance * @param wrapper an optional instance * @throws IOException if I/O error occurs */ public void initialize(Definitions defs, StreamSource src, ReaderWrapper wrapper) throws IOException {<FILL_FUNCTION_BODY>} /** * Publishes the next, pending token from * {@link #initialize(org.opengrok.indexer.analysis.Definitions, org.opengrok.indexer.analysis.StreamSource, * org.opengrok.indexer.util.ReaderWrapper)}, * if one is available. * @return false if no more tokens; otherwise true * @throws IOException in case of I/O error */ @Override public final boolean incrementToken() throws IOException { if (offset < events.size()) { PendingToken tok = events.get(offset++); setAttribs(tok); return true; } clearAttributes(); return false; } private void setAttribs(PendingToken tok) { clearAttributes(); this.posIncrAtt.setPositionIncrement(1); this.termAtt.setEmpty(); this.termAtt.append(tok.str); this.offsetAtt.setOffset(tok.start, tok.end); } private void createTokens(Definitions defs, LineBreaker brk) { for (Definitions.Tag tag : defs.getTags()) { // Shift from ctags's convention. int lineno = tag.line - 1; if (lineno >= 0 && lineno < brk.count() && tag.symbol != null && tag.text != null) { int lineoff = brk.getOffset(lineno); if (tag.lineStart >= 0) { PendingToken tok = new PendingToken(tag.symbol, lineoff + tag.lineStart, lineoff + tag.lineEnd); events.add(tok); } } } events.sort(PendingTokenOffsetsComparator.INSTANCE); } }
if (defs == null) { throw new IllegalArgumentException("`defs' is null"); } if (src == null) { throw new IllegalArgumentException("`src' is null"); } events.clear(); offset = 0; LineBreaker brk = new LineBreaker(); brk.reset(src, wrapper); createTokens(defs, brk);
722
105
827
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/plain/PlainAnalyzer.java
PlainAnalyzer
analyze
class PlainAnalyzer extends TextAnalyzer { /** * Creates a new instance of PlainAnalyzer. * @param factory defined instance for the analyzer */ protected PlainAnalyzer(AnalyzerFactory factory) { super(factory); } /** * Creates a new instance of {@link PlainAnalyzer}. * @param factory defined instance for the analyzer * @param symbolTokenizerFactory defined instance for the analyzer */ protected PlainAnalyzer(AnalyzerFactory factory, Supplier<JFlexTokenizer> symbolTokenizerFactory) { super(factory, symbolTokenizerFactory); } /** * @return {@code null} as there is no aligned language */ @Override public String getCtagsLang() { return null; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20180208_00 */ @Override protected int getSpecializedVersionNo() { return 20180208_00; // Edit comment above too! } /** * Creates a wrapped {@link PlainXref} instance. * @param reader the data to produce xref for * @return an xref instance */ @Override protected Xrefer newXref(Reader reader) { return new JFlexXref(new PlainXref(reader)); } @Override protected Reader getReader(InputStream stream) throws IOException { return ExpandTabsReader.wrap(super.getReader(stream), project); } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>} // DefinitionsTokenStream should not be used in try-with-resources @SuppressWarnings("java:S2095") private void tryAddingDefs(Document doc, Definitions defs, StreamSource src) throws IOException { DefinitionsTokenStream defstream = new DefinitionsTokenStream(); defstream.initialize(defs, src, this::wrapReader); /* * Testing showed that UnifiedHighlighter will fall back to * ANALYSIS in the presence of multi-term queries (MTQs) such as * prefixes and wildcards even for fields that are analyzed with * POSTINGS -- i.e. with DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS. * This is despite UnifiedHighlighter seeming to indicate that * postings should be sufficient in the comment for * shouldHandleMultiTermQuery(String): "MTQ highlighting can be * expensive, particularly when using offsets in postings." * DEFS re-analysis will not be correct, however, as the * PlainAnalyzer which UnifiedHighlighter will use on-the-fly will * not correctly integrate ctags Definitions. * Storing term vectors, however, allows UnifiedHighlighter to * avoid re-analysis at the cost of a larger index. As DEFS are a * small subset of source text, it seems worth the cost to get * accurate highlighting for DEFS MTQs. */ doc.add(new OGKTextVecField(QueryBuilder.DEFS, defstream)); } /** * Identical to {@link #getReader(java.io.InputStream)} but overlaying an * existing stream. * @see #getReader(java.io.InputStream) */ private Reader wrapReader(Reader reader) { return ExpandTabsReader.wrap(reader, project); } }
Definitions defs = null; NullWriter nullWriter = null; doc.add(new OGKTextField(QueryBuilder.FULL, getReader(src.getStream()))); String fullPath = doc.get(QueryBuilder.FULLPATH); if (fullPath != null && ctags != null) { defs = ctags.doCtags(fullPath); if (defs != null && defs.numberOfSymbols() > 0) { tryAddingDefs(doc, defs, src); byte[] tags = defs.serialize(); doc.add(new StoredField(QueryBuilder.TAGS, tags)); } } /* * This is to explicitly use appropriate analyzer's token stream to * work around #1376: symbols search works like full text search. */ JFlexTokenizer symbolTokenizer = symbolTokenizerFactory.get(); OGKTextField ref = new OGKTextField(QueryBuilder.REFS, symbolTokenizer); symbolTokenizer.setReader(getReader(src.getStream())); doc.add(ref); if (scopesEnabled && xrefOut == null) { /* * Scopes are generated during xref generation. If xrefs are * turned off we still need to run writeXref() to produce scopes, * we use a dummy writer that will throw away any xref output. */ nullWriter = new NullWriter(); xrefOut = nullWriter; } if (xrefOut != null) { try (Reader in = getReader(src.getStream())) { WriteXrefArgs args = new WriteXrefArgs(in, xrefOut); args.setDefs(defs); args.setProject(project); XrefWork xrefWork = new XrefWork(args, this); Xrefer xref = xrefWork.getXrefer(); if (xref != null) { Scopes scopes = xref.getScopes(); if (scopes.size() > 0) { byte[] scopesSerialized = scopes.serialize(); doc.add(new StoredField(QueryBuilder.SCOPES, scopesSerialized)); } String path = doc.get(QueryBuilder.PATH); addNumLinesLOC(doc, new NumLinesLOC(path, xref.getLineNumber(), xref.getLOC())); } } catch (ExecutionException e) { throw new InterruptedException("failed to generate xref :" + e); } finally { if (nullWriter != null) { nullWriter.close(); } } }
961
676
1,637
<methods>public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/plain/PlainAnalyzerFactory.java
PlainAnalyzerFactory
readSomePlainCharactersUTF8noBOMwithoutError
class PlainAnalyzerFactory extends FileAnalyzerFactory { private static final String NAME = "Plain Text"; private static final int MIN_CHARS_WHILE_REMAINING = 20; // Up to 4 octets per UTF-8 character private static final int TRY_UTF8_BYTES = MIN_CHARS_WHILE_REMAINING * 4; /** * The reentrant {@link Matcher} implementation for plain-text files. */ public static final Matcher MATCHER = new Matcher() { @Override public String description() { return "UTF-8, UTF-16BE, or UTF-16LE Byte Order Mark is present; or initial " + "bytes are all UTF-8-encoded graphic characters or whitespace"; } @Override public AnalyzerFactory isMagic(byte[] content, InputStream in) throws IOException { int lengthBOM = IOUtils.skipForBOM(content); if (lengthBOM > 0) { return DEFAULT_INSTANCE; } if (readSomePlainCharactersUTF8noBOMwithoutError(in)) { return DEFAULT_INSTANCE; } return null; } @Override public AnalyzerFactory forFactory() { return DEFAULT_INSTANCE; } }; /** * Gets the singleton, factory instance that associates * {@link PlainAnalyzer} with files whose initial bytes are the UTF-8, * UTF-16BE, or UTF-16LE Byte Order Mark; or whose initial bytes are all * UTF-8-encoded graphic characters or whitespace. */ public static final PlainAnalyzerFactory DEFAULT_INSTANCE = new PlainAnalyzerFactory(); private PlainAnalyzerFactory() { super(null, null, null, null, MATCHER, "text/plain", AbstractAnalyzer.Genre.PLAIN, NAME, true); } @Override protected AbstractAnalyzer newAnalyzer() { return new PlainAnalyzer(this); } private static boolean readSomePlainCharactersUTF8noBOMwithoutError(InputStream in) throws IOException {<FILL_FUNCTION_BODY>} }
boolean isEOF = false; byte[] bytes = new byte[TRY_UTF8_BYTES]; in.mark(TRY_UTF8_BYTES); int len = in.read(bytes); in.reset(); if (len < 1) { return false; } if (len != TRY_UTF8_BYTES) { bytes = Arrays.copyOf(bytes, len); isEOF = true; } /* * Decode one character at a time until either a decoding error occurs * (failure) or the minimum number of required, valid characters is * reached (success). * * "Decode bytes to chars one at a time" * answered by https://stackoverflow.com/users/1831293/evgeniy-dorofeev * https://stackoverflow.com/questions/17227331/decode-bytes-to-chars-one-at-a-time * asked by https://stackoverflow.com/users/244360/kong * * Used under CC 4 with modifications noted as follows as required by * license: * * 2021-08-15 -- cfraire@me.com, revised to check for errors. */ CharsetDecoder cd = StandardCharsets.UTF_8.newDecoder(). onMalformedInput(CodingErrorAction.REPORT). onUnmappableCharacter(CodingErrorAction.REPORT); ByteBuffer bin = ByteBuffer.wrap(bytes); CharBuffer out = CharBuffer.allocate(MIN_CHARS_WHILE_REMAINING); int numCharacters = 0; CoderResult decodeResult = cd.decode(bin, out, isEOF); if (decodeResult.isError()) { return false; } int numChars = out.position(); out.position(0); for (int i = 0; i < numChars; ++i) { char c = out.charAt(i); if (Character.isISOControl(c) && !Character.isWhitespace(c)) { return false; } if (++numCharacters >= MIN_CHARS_WHILE_REMAINING) { return true; } } /* * At this point, as no error has occurred, then if any character was * read, consider the input as plain text. */ return (numCharacters > 0);
568
636
1,204
<methods>public final org.opengrok.indexer.analysis.AbstractAnalyzer getAnalyzer() ,public java.lang.String getName() ,public void returnAnalyzer() <variables>private final non-sealed java.lang.String name
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/plain/XMLAnalyzer.java
XMLAnalyzer
analyze
class XMLAnalyzer extends TextAnalyzer { /** * Creates a new instance of XMLAnalyzer. * @param factory factory to be used */ protected XMLAnalyzer(AnalyzerFactory factory) { super(factory); } /** * @return {@code "XML"} */ @Override public String getCtagsLang() { return "XML"; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20180112_00 */ @Override protected int getSpecializedVersionNo() { return 20180112_00; // Edit comment above too! } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>} /** * Creates a wrapped {@link XMLXref} instance. * @param reader the data to produce xref for * @return xref instance */ @Override protected JFlexXref newXref(Reader reader) { return new JFlexXref(new XMLXref(reader)); } }
doc.add(new OGKTextField(QueryBuilder.FULL, getReader(src.getStream()))); if (xrefOut != null) { try (Reader in = getReader(src.getStream())) { WriteXrefArgs args = new WriteXrefArgs(in, xrefOut); args.setProject(project); XrefWork xrefWork = new XrefWork(args, this); Xrefer xref = xrefWork.getXrefer(); if (xref != null) { String path = doc.get(QueryBuilder.PATH); addNumLinesLOC(doc, new NumLinesLOC(path, xref.getLineNumber(), xref.getLOC())); } } catch (ExecutionException e) { throw new InterruptedException("failed to generate xref :" + e); } }
338
218
556
<methods>public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/r/RLexer.java
RLexer
chkLOC
class RLexer extends JFlexSymbolMatcher implements JFlexJointLexer, Resettable { /** * Calls {@link #phLOC()} if the yystate is not SCOMMENT. */ public void chkLOC() {<FILL_FUNCTION_BODY>} /** * Subclasses must override to get the constant value created by JFlex to * represent SCOMMENT. */ public abstract int SCOMMENT(); }
int yystate = yystate(); if (yystate != SCOMMENT()) { phLOC(); }
122
36
158
<methods>public non-sealed void <init>() ,public void clearNonSymbolMatchedListener() ,public void clearSymbolMatchedListener() ,public void setNonSymbolMatchedListener(org.opengrok.indexer.analysis.NonSymbolMatchedListener) ,public void setSymbolMatchedListener(org.opengrok.indexer.analysis.SymbolMatchedListener) <variables>private java.lang.String disjointSpanClassName,private org.opengrok.indexer.analysis.NonSymbolMatchedListener nonSymbolListener,private org.opengrok.indexer.analysis.SymbolMatchedListener symbolListener
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/rust/RustUtils.java
RustUtils
countRawHashes
class RustUtils { /** * Private to enforce singleton. */ private RustUtils() { } /** * Counts the number of hashes ('#') before a terminating quote ('"') in * {@code capture}. * @param capture the Rust raw- or raw-byte-string initiator (e.g., * {@code "r##\""}) * @return the number of hashes counted */ public static int countRawHashes(String capture) {<FILL_FUNCTION_BODY>} /** * Determines if the specified {@code capture} starts with a quote ('"') * and is followed by the specified number of hashes (plus possibly an * excess number of hashes), indicating the end of a raw- or raw-byte- * string. * @param capture the possible Rust raw- or raw-byte-string ender (e.g., * {@code "\"####"}) * @param rawHashCount the number of required hashes in order to be * considered "raw-ending" * @return true if the {@code capture} is determined to be "raw-ending" or * false otherwise (N.b., there may have been too many hashes captured, so * any excess of {@code yylength()} minus one minus {@code rawHashCount} * should be pushed back. */ public static boolean isRawEnding(String capture, int rawHashCount) { if (!capture.startsWith("\"")) { throw new IllegalArgumentException( "`capture' does not start with \""); } int n = 0; for (int i = 1; i < capture.length(); ++i) { if (capture.charAt(i) != '#') { break; } ++n; if (n >= rawHashCount) { break; } } return n >= rawHashCount; } }
if (!capture.endsWith("\"")) { throw new IllegalArgumentException("`capture' does not end in \""); } int n = 0; for (int i = capture.length() - 2; i >= 0; --i) { if (capture.charAt(i) != '#') { break; } ++n; } return n;
493
104
597
<no_super_class>
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/sql/JointSQLLexer.java
JointSQLLexer
chkLOC
class JointSQLLexer extends JFlexSymbolMatcher implements JFlexJointLexer, Resettable { protected int commentLevel; @Override public void reset() { super.reset(); commentLevel = 0; } @Override public void yypop() throws IOException { onDisjointSpanChanged(null, getYYCHAR()); super.yypop(); } /** * Calls {@link #phLOC()} if the yystate is not BRACKETED_COMMENT or * SINGLE_LINE_COMMENT. */ public void chkLOC() {<FILL_FUNCTION_BODY>} /** * Subclasses must override to get the dialect's keywords set. */ abstract Set<String> getDialectKeywords(); /** * Subclasses must override to get the constant value created by JFlex to * represent BRACKETED_COMMENT. */ abstract int BRACKETED_COMMENT(); /** * Subclasses must override to get the constant value created by JFlex to * represent SINGLE_LINE_COMMENT. */ abstract int SINGLE_LINE_COMMENT(); }
if (yystate() != BRACKETED_COMMENT() && yystate() != SINGLE_LINE_COMMENT()) { phLOC(); }
313
46
359
<methods>public non-sealed void <init>() ,public void clearNonSymbolMatchedListener() ,public void clearSymbolMatchedListener() ,public void setNonSymbolMatchedListener(org.opengrok.indexer.analysis.NonSymbolMatchedListener) ,public void setSymbolMatchedListener(org.opengrok.indexer.analysis.SymbolMatchedListener) <variables>private java.lang.String disjointSpanClassName,private org.opengrok.indexer.analysis.NonSymbolMatchedListener nonSymbolListener,private org.opengrok.indexer.analysis.SymbolMatchedListener symbolListener
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/sql/JointSQLSymbolTokenizer.java
JointSQLSymbolTokenizer
offerSymbol
class JointSQLSymbolTokenizer extends JointSQLLexer { private String lastSymbol; /** * Resets the SQL tracked state. {@inheritDoc} */ @Override public void reset() { super.reset(); lastSymbol = null; } /** noop. */ @Override public void offer(String value) { } @Override public boolean offerSymbol(String value, int captureOffset, boolean ignoreKwd) {<FILL_FUNCTION_BODY>} @Override public void skipSymbol() { lastSymbol = null; } @Override public void offerKeyword(String value) { lastSymbol = null; } /** noop. */ @Override public void startNewLine() { } /** noop. */ @Override public void disjointSpan(String className) { } /** noop. */ @Override public void phLOC() { } /** Gets the value {@code false}. */ protected boolean takeAllContent() { return false; } /** Gets the value indicating if {@link #lastSymbol} is defined. */ protected boolean returnOnSymbol() { return lastSymbol != null; } }
if (ignoreKwd || !getDialectKeywords().contains(value.toLowerCase(Locale.ROOT))) { lastSymbol = value; onSymbolMatched(value, getYYCHAR() + captureOffset); return true; } else { lastSymbol = null; } return false;
330
83
413
<methods>public void chkLOC() ,public void reset() ,public void yypop() throws java.io.IOException<variables>protected int commentLevel
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/sql/JointSQLXref.java
JointSQLXref
offerSymbol
class JointSQLXref extends JointSQLLexer { @Override public void offer(String value) { onNonSymbolMatched(value, getYYCHAR()); } @Override public boolean offerSymbol(String value, int captureOffset, boolean ignoreKwd) {<FILL_FUNCTION_BODY>} /** noop. */ @Override public void skipSymbol() { } @Override public void offerKeyword(String value) { onKeywordMatched(value, getYYCHAR()); } @Override public void startNewLine() { onEndOfLineMatched("\n", getYYCHAR()); } @Override public void disjointSpan(String className) { onDisjointSpanChanged(className, getYYCHAR()); } /** Gets the value {@code true}. */ protected boolean takeAllContent() { return true; } /** Gets the value {@code false}. */ protected boolean returnOnSymbol() { return false; } }
Set<String> keywords = ignoreKwd ? null : getDialectKeywords(); return onFilteredSymbolMatched(value, getYYCHAR(), keywords, false);
267
44
311
<methods>public void chkLOC() ,public void reset() ,public void yypop() throws java.io.IOException<variables>protected int commentLevel
oracle_opengrok
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/uue/UuencodeAnalyzer.java
UuencodeAnalyzer
analyze
class UuencodeAnalyzer extends TextAnalyzer { /** * Creates a new instance of UuencodeAnalyzer. * @param factory defined instance for the analyzer */ protected UuencodeAnalyzer(AnalyzerFactory factory) { super(factory, () -> new JFlexTokenizer(new UuencodeFullTokenizer( AbstractAnalyzer.DUMMY_READER))); } /** * @return {@code null} as there is no aligned language */ @Override public String getCtagsLang() { return null; } /** * Gets a version number to be used to tag processed documents so that * re-analysis can be re-done later if a stored version number is different * from the current implementation. * @return 20180112_00 */ @Override protected int getSpecializedVersionNo() { return 20180112_00; // Edit comment above too! } @Override public void analyze(Document doc, StreamSource src, Writer xrefOut) throws IOException, InterruptedException {<FILL_FUNCTION_BODY>} /** * Creates a wrapped {@link UuencodeXref} instance. * @param reader the data to produce xref for * @return an xref instance */ @Override protected JFlexXref newXref(Reader reader) { return new JFlexXref(new UuencodeXref(reader)); } }
//this is to explicitly use appropriate analyzers tokenstream to workaround #1376 symbols search works like full text search JFlexTokenizer symbolTokenizer = symbolTokenizerFactory.get(); OGKTextField full = new OGKTextField(QueryBuilder.FULL, symbolTokenizer); symbolTokenizer.setReader(getReader(src.getStream())); doc.add(full); if (xrefOut != null) { try (Reader in = getReader(src.getStream())) { WriteXrefArgs args = new WriteXrefArgs(in, xrefOut); args.setProject(project); XrefWork xrefWork = new XrefWork(args, this); try { xrefWork.getXrefer(); } catch (ExecutionException e) { throw new InterruptedException("failed to generate xref :" + e); } } }
386
228
614
<methods>public org.opengrok.indexer.analysis.Xrefer writeXref(org.opengrok.indexer.analysis.WriteXrefArgs) throws java.io.IOException<variables>