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
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/InputModifyGroupInfo.java
InputModifyGroupInfo
toProtoGroupRequest
class InputModifyGroupInfo extends InputGroupBase { private String group_id; //ModifyGroupInfoType private int type; private String value; public boolean isValide() { if (StringUtil.isNullOrEmpty(group_id) || StringUtil.isNullOrEmpty(operator)) return false; return true; } public String getGroup_id() { return group_id; } public void setGroup_id(String group_id) { this.group_id = group_id; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public WFCMessage.ModifyGroupInfoRequest toProtoGroupRequest() {<FILL_FUNCTION_BODY>} }
if(notify_message != null && notify_message.getType() > 0) { return WFCMessage.ModifyGroupInfoRequest.newBuilder() .setGroupId(group_id) .setType(type) .setValue(value == null ? "" : value) .addAllToLine(to_lines == null || to_lines.isEmpty() ? Arrays.asList(0) : to_lines) .setNotifyContent(notify_message.toProtoMessageContent()) .build(); } else { return WFCMessage.ModifyGroupInfoRequest.newBuilder() .setGroupId(group_id) .setType(type) .setValue(value == null ? "" : value) .addAllToLine(to_lines == null || to_lines.isEmpty() ? Arrays.asList(0) : to_lines) .build(); }
254
226
480
<methods>public non-sealed void <init>() ,public cn.wildfirechat.pojos.MessagePayload getNotify_message() ,public java.lang.String getOperator() ,public List<java.lang.Integer> getTo_lines() ,public void setNotify_message(cn.wildfirechat.pojos.MessagePayload) ,public void setOperator(java.lang.String) ,public void setTo_lines(List<java.lang.Integer>) <variables>public cn.wildfirechat.pojos.MessagePayload notify_message,public java.lang.String operator,public List<java.lang.Integer> to_lines
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/InputMuteGroupMember.java
InputMuteGroupMember
toProtoGroupRequest
class InputMuteGroupMember extends InputGroupBase { private String group_id; private List<String> members; private boolean is_manager; public String getGroup_id() { return group_id; } public void setGroup_id(String group_id) { this.group_id = group_id; } public List<String> getMembers() { return members; } public void setMembers(List<String> members) { this.members = members; } public boolean isIs_manager() { return is_manager; } public void setIs_manager(boolean is_manager) { this.is_manager = is_manager; } public boolean isValide() { if (StringUtil.isNullOrEmpty(operator) || StringUtil.isNullOrEmpty(group_id) || members == null || members.isEmpty()) { return false; } return true; } public WFCMessage.SetGroupManagerRequest toProtoGroupRequest() {<FILL_FUNCTION_BODY>} }
WFCMessage.SetGroupManagerRequest.Builder addGroupBuilder = WFCMessage.SetGroupManagerRequest.newBuilder(); addGroupBuilder.setGroupId(group_id); addGroupBuilder.addAllUserId(members); addGroupBuilder.setType(is_manager ? 1 : 0); if (to_lines != null) { for (Integer line : to_lines ) { addGroupBuilder.addToLine(line); } } if (notify_message != null) { addGroupBuilder.setNotifyContent(notify_message.toProtoMessageContent()); } return addGroupBuilder.build();
283
167
450
<methods>public non-sealed void <init>() ,public cn.wildfirechat.pojos.MessagePayload getNotify_message() ,public java.lang.String getOperator() ,public List<java.lang.Integer> getTo_lines() ,public void setNotify_message(cn.wildfirechat.pojos.MessagePayload) ,public void setOperator(java.lang.String) ,public void setTo_lines(List<java.lang.Integer>) <variables>public cn.wildfirechat.pojos.MessagePayload notify_message,public java.lang.String operator,public List<java.lang.Integer> to_lines
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/InputOutputUserInfo.java
InputOutputUserInfo
toUser
class InputOutputUserInfo { private String userId; private String name; private String password; private String displayName; private String portrait; private int gender; private String mobile; private String email; private String address; private String company; private String social; private String extra; private int type; private long updateDt; public static InputOutputUserInfo fromPbUser(WFCMessage.User pbUser) { InputOutputUserInfo inputCreateUser = new InputOutputUserInfo(); inputCreateUser.userId = pbUser.getUid(); inputCreateUser.name = pbUser.getName(); inputCreateUser.displayName = pbUser.getDisplayName(); inputCreateUser.portrait = pbUser.getPortrait(); inputCreateUser.gender = pbUser.getGender(); inputCreateUser.mobile = pbUser.getMobile(); inputCreateUser.email = pbUser.getEmail(); inputCreateUser.address = pbUser.getAddress(); inputCreateUser.company = pbUser.getCompany(); inputCreateUser.social = pbUser.getSocial(); inputCreateUser.extra = pbUser.getExtra(); inputCreateUser.type = pbUser.getType(); inputCreateUser.updateDt = pbUser.getUpdateDt(); return inputCreateUser; } public String getSocial() { return social; } public void setSocial(String social) { this.social = social; } public WFCMessage.User toUser() {<FILL_FUNCTION_BODY>} public long getUpdateDt() { return updateDt; } public void setUpdateDt(long updateDt) { this.updateDt = updateDt; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getPortrait() { return portrait; } public void setPortrait(String portrait) { this.portrait = portrait; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
WFCMessage.User.Builder newUserBuilder = WFCMessage.User.newBuilder() .setUid(userId); if (name != null) newUserBuilder.setName(name); if (displayName != null) newUserBuilder.setDisplayName(displayName); if (getPortrait() != null) newUserBuilder.setPortrait(getPortrait()); if (getEmail() != null) newUserBuilder.setEmail(getEmail()); if (getAddress() != null) newUserBuilder.setAddress(getAddress()); if (getCompany() != null) newUserBuilder.setCompany(getCompany()); if (getSocial() != null) newUserBuilder.setSocial(getSocial()); if (getMobile() != null) newUserBuilder.setMobile(getMobile()); if (getExtra() != null) newUserBuilder.setExtra(getExtra()); newUserBuilder.setGender(gender); newUserBuilder.setType(type); newUserBuilder.setUpdateDt(System.currentTimeMillis()); return newUserBuilder.build();
968
295
1,263
<no_super_class>
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/InputQuitGroup.java
InputQuitGroup
toProtoGroupRequest
class InputQuitGroup extends InputGroupBase { private String group_id; public String getGroup_id() { return group_id; } public void setGroup_id(String group_id) { this.group_id = group_id; } public boolean isValide() { if (StringUtil.isNullOrEmpty(group_id) || StringUtil.isNullOrEmpty(operator)) return false; return true; } public WFCMessage.QuitGroupRequest toProtoGroupRequest() {<FILL_FUNCTION_BODY>} }
WFCMessage.QuitGroupRequest.Builder removedGroupBuilder = WFCMessage.QuitGroupRequest.newBuilder(); removedGroupBuilder.setGroupId(group_id); if (to_lines != null) { for (Integer line : to_lines ) { removedGroupBuilder.addToLine(line); } } if (notify_message != null) { removedGroupBuilder.setNotifyContent(notify_message.toProtoMessageContent()); } return removedGroupBuilder.build();
154
135
289
<methods>public non-sealed void <init>() ,public cn.wildfirechat.pojos.MessagePayload getNotify_message() ,public java.lang.String getOperator() ,public List<java.lang.Integer> getTo_lines() ,public void setNotify_message(cn.wildfirechat.pojos.MessagePayload) ,public void setOperator(java.lang.String) ,public void setTo_lines(List<java.lang.Integer>) <variables>public cn.wildfirechat.pojos.MessagePayload notify_message,public java.lang.String operator,public List<java.lang.Integer> to_lines
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/InputSetGroupManager.java
InputSetGroupManager
isValide
class InputSetGroupManager extends InputGroupBase { private String group_id; private List<String> members; private boolean is_manager; public String getGroup_id() { return group_id; } public void setGroup_id(String group_id) { this.group_id = group_id; } public List<String> getMembers() { return members; } public void setMembers(List<String> members) { this.members = members; } public boolean isIs_manager() { return is_manager; } public void setIs_manager(boolean is_manager) { this.is_manager = is_manager; } public boolean isValide() {<FILL_FUNCTION_BODY>} public WFCMessage.SetGroupManagerRequest toProtoGroupRequest() { WFCMessage.SetGroupManagerRequest.Builder addGroupBuilder = WFCMessage.SetGroupManagerRequest.newBuilder(); addGroupBuilder.setGroupId(group_id); addGroupBuilder.addAllUserId(members); addGroupBuilder.setType(is_manager ? 1 : 0); if (to_lines != null) { for (Integer line : to_lines ) { addGroupBuilder.addToLine(line); } } if (notify_message != null) { addGroupBuilder.setNotifyContent(notify_message.toProtoMessageContent()); } return addGroupBuilder.build(); } }
if (StringUtil.isNullOrEmpty(operator) || StringUtil.isNullOrEmpty(group_id) || members == null || members.isEmpty()) { return false; } return true;
396
53
449
<methods>public non-sealed void <init>() ,public cn.wildfirechat.pojos.MessagePayload getNotify_message() ,public java.lang.String getOperator() ,public List<java.lang.Integer> getTo_lines() ,public void setNotify_message(cn.wildfirechat.pojos.MessagePayload) ,public void setOperator(java.lang.String) ,public void setTo_lines(List<java.lang.Integer>) <variables>public cn.wildfirechat.pojos.MessagePayload notify_message,public java.lang.String operator,public List<java.lang.Integer> to_lines
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/InputSetGroupMemberAlias.java
InputSetGroupMemberAlias
toProtoGroupRequest
class InputSetGroupMemberAlias extends InputGroupBase { private String group_id; private String memberId; private String alias; public String getGroup_id() { return group_id; } public void setGroup_id(String group_id) { this.group_id = group_id; } public boolean isValide() { return true; } public WFCMessage.ModifyGroupMemberAlias toProtoGroupRequest() {<FILL_FUNCTION_BODY>} public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } }
WFCMessage.ModifyGroupMemberAlias.Builder modifyAliasBuilder = WFCMessage.ModifyGroupMemberAlias.newBuilder(); modifyAliasBuilder.setGroupId(group_id); modifyAliasBuilder.setAlias(StringUtil.isNullOrEmpty(alias)?"":alias); modifyAliasBuilder.setMemberId(memberId); if (to_lines != null) { for (Integer line : to_lines) { modifyAliasBuilder.addToLine(line); } } if (notify_message != null) { modifyAliasBuilder.setNotifyContent(notify_message.toProtoMessageContent()); } return modifyAliasBuilder.build();
226
181
407
<methods>public non-sealed void <init>() ,public cn.wildfirechat.pojos.MessagePayload getNotify_message() ,public java.lang.String getOperator() ,public List<java.lang.Integer> getTo_lines() ,public void setNotify_message(cn.wildfirechat.pojos.MessagePayload) ,public void setOperator(java.lang.String) ,public void setTo_lines(List<java.lang.Integer>) <variables>public cn.wildfirechat.pojos.MessagePayload notify_message,public java.lang.String operator,public List<java.lang.Integer> to_lines
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/InputSetGroupMemberExtra.java
InputSetGroupMemberExtra
toProtoGroupRequest
class InputSetGroupMemberExtra extends InputGroupBase { private String group_id; private String memberId; private String extra; public String getGroup_id() { return group_id; } public void setGroup_id(String group_id) { this.group_id = group_id; } public boolean isValide() { return true; } public WFCMessage.ModifyGroupMemberExtra toProtoGroupRequest() {<FILL_FUNCTION_BODY>} public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } }
WFCMessage.ModifyGroupMemberExtra.Builder modifyAliasBuilder = WFCMessage.ModifyGroupMemberExtra.newBuilder(); modifyAliasBuilder.setGroupId(group_id); modifyAliasBuilder.setMemberId(memberId); modifyAliasBuilder.setExtra(StringUtil.isNullOrEmpty(extra)?"": extra); if (to_lines != null) { for (Integer line : to_lines) { modifyAliasBuilder.addToLine(line); } } if (notify_message != null) { modifyAliasBuilder.setNotifyContent(notify_message.toProtoMessageContent()); } return modifyAliasBuilder.build();
222
178
400
<methods>public non-sealed void <init>() ,public cn.wildfirechat.pojos.MessagePayload getNotify_message() ,public java.lang.String getOperator() ,public List<java.lang.Integer> getTo_lines() ,public void setNotify_message(cn.wildfirechat.pojos.MessagePayload) ,public void setOperator(java.lang.String) ,public void setTo_lines(List<java.lang.Integer>) <variables>public cn.wildfirechat.pojos.MessagePayload notify_message,public java.lang.String operator,public List<java.lang.Integer> to_lines
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/InputTransferGroup.java
InputTransferGroup
toProtoGroupRequest
class InputTransferGroup extends InputGroupBase { private String group_id; private String new_owner; public boolean isValide() { if (StringUtil.isNullOrEmpty(group_id) || StringUtil.isNullOrEmpty(operator) || StringUtil.isNullOrEmpty(new_owner)) return false; return true; } public WFCMessage.TransferGroupRequest toProtoGroupRequest() {<FILL_FUNCTION_BODY>} public String getGroup_id() { return group_id; } public void setGroup_id(String group_id) { this.group_id = group_id; } public String getNew_owner() { return new_owner; } public void setNew_owner(String new_owner) { this.new_owner = new_owner; } }
WFCMessage.TransferGroupRequest.Builder groupBuilder = WFCMessage.TransferGroupRequest.newBuilder(); groupBuilder.setGroupId(group_id); groupBuilder.setNewOwner(new_owner); if (to_lines != null) { for (Integer line : to_lines ) { groupBuilder.addToLine(line); } } if (notify_message != null) { groupBuilder.setNotifyContent(notify_message.toProtoMessageContent()); } return groupBuilder.build();
227
143
370
<methods>public non-sealed void <init>() ,public cn.wildfirechat.pojos.MessagePayload getNotify_message() ,public java.lang.String getOperator() ,public List<java.lang.Integer> getTo_lines() ,public void setNotify_message(cn.wildfirechat.pojos.MessagePayload) ,public void setOperator(java.lang.String) ,public void setTo_lines(List<java.lang.Integer>) <variables>public cn.wildfirechat.pojos.MessagePayload notify_message,public java.lang.String operator,public List<java.lang.Integer> to_lines
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/MessagePayload.java
MessagePayload
fromProtoMessageContent
class MessagePayload { private int type; private String searchableContent; private String pushContent; private String pushData; private String content; private String base64edData; private int mediaType; private String remoteMediaUrl; private int persistFlag; private int expireDuration; private int mentionedType; private List<String> mentionedTarget; private String extra; public int getType() { return type; } public void setType(int type) { this.type = type; } public String getSearchableContent() { return searchableContent; } public void setSearchableContent(String searchableContent) { this.searchableContent = searchableContent; } public String getPushContent() { return pushContent; } public void setPushContent(String pushContent) { this.pushContent = pushContent; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getBase64edData() { return base64edData; } public void setBase64edData(String base64edData) { this.base64edData = base64edData; } public int getMediaType() { return mediaType; } public void setMediaType(int mediaType) { this.mediaType = mediaType; } public String getRemoteMediaUrl() { return remoteMediaUrl; } public void setRemoteMediaUrl(String remoteMediaUrl) { this.remoteMediaUrl = remoteMediaUrl; } public int getPersistFlag() { return persistFlag; } public void setPersistFlag(int persistFlag) { this.persistFlag = persistFlag; } public int getExpireDuration() { return expireDuration; } public void setExpireDuration(int expireDuration) { this.expireDuration = expireDuration; } public int getMentionedType() { return mentionedType; } public void setMentionedType(int mentionedType) { this.mentionedType = mentionedType; } public List<String> getMentionedTarget() { return mentionedTarget; } public void setMentionedTarget(List<String> mentionedTarget) { this.mentionedTarget = mentionedTarget; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } public String getPushData() { return pushData; } public void setPushData(String pushData) { this.pushData = pushData; } public WFCMessage.MessageContent toProtoMessageContent() { WFCMessage.MessageContent.Builder builder = WFCMessage.MessageContent.newBuilder() .setType(type) .setMediaType(mediaType) .setPersistFlag(persistFlag) .setExpireDuration(expireDuration) .setMentionedType(mentionedType); if (!StringUtil.isNullOrEmpty(searchableContent)) builder.setSearchableContent(searchableContent); if (!StringUtil.isNullOrEmpty(pushContent)) builder.setPushContent(pushContent); if (!StringUtil.isNullOrEmpty(content)) builder.setContent(content); if (!StringUtil.isNullOrEmpty(base64edData)) builder.setData(ByteString.copyFrom(Base64.getDecoder().decode(base64edData))); if (!StringUtil.isNullOrEmpty(remoteMediaUrl)) builder.setRemoteMediaUrl(remoteMediaUrl); if (mentionedTarget != null && mentionedTarget.size() > 0) builder.addAllMentionedTarget(mentionedTarget); if (!StringUtil.isNullOrEmpty(extra)) builder.setExtra(extra); if (!StringUtil.isNullOrEmpty(pushData)) builder.setPushData(pushData); return builder.build(); } public static MessagePayload fromProtoMessageContent(WFCMessage.MessageContent protoContent) {<FILL_FUNCTION_BODY>} }
if (protoContent == null) return null; MessagePayload payload = new MessagePayload(); payload.type = protoContent.getType(); payload.searchableContent = protoContent.getSearchableContent(); payload.pushContent = protoContent.getPushContent(); payload.content = protoContent.getContent(); if (protoContent.getData() != null && protoContent.getData().size() > 0) payload.base64edData = Base64.getEncoder().encodeToString(protoContent.getData().toByteArray()); payload.mediaType = protoContent.getMediaType(); payload.remoteMediaUrl = protoContent.getRemoteMediaUrl(); payload.persistFlag = protoContent.getPersistFlag(); payload.expireDuration = protoContent.getExpireDuration(); payload.mentionedType = protoContent.getMentionedType(); payload.mentionedTarget = new ArrayList<>(); payload.mentionedTarget.addAll(protoContent.getMentionedTargetList()); payload.extra = protoContent.getExtra(); payload.pushData = protoContent.getPushData(); return payload;
1,119
282
1,401
<no_super_class>
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/MulticastMessageData.java
MulticastMessageData
isValide
class MulticastMessageData { private String sender; private int line; private MessagePayload payload; private List<String> targets; public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public int getLine() { return line; } public void setLine(int line) { this.line = line; } public MessagePayload getPayload() { return payload; } public void setPayload(MessagePayload payload) { this.payload = payload; } public static boolean isValide(MulticastMessageData sendMessageData) {<FILL_FUNCTION_BODY>} public WFCMessage.MultiCastMessage toProtoMessage() { return WFCMessage.MultiCastMessage.newBuilder().setFromUser(sender) .setLine(line) .setContent(payload.toProtoMessageContent()) .addAllTo(targets) .build(); } public List<String> getTargets() { return targets; } public void setTargets(List<String> targets) { this.targets = targets; } }
if(sendMessageData == null || StringUtil.isNullOrEmpty(sendMessageData.getSender()) || sendMessageData.getPayload() == null) { return false; } return true;
327
59
386
<no_super_class>
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/OutputCheckUserOnline.java
Session
addSession
class Session { public String clientId; public String userId; public int platform; public int status; //0 online, 1 have session offline public long lastSeen; public String packageName; public Session() { } public Session(String clientId, String userId, int platform, int status, long lastSeen, String packageName) { this.clientId = clientId; this.userId = userId; this.platform = platform; this.status = status; this.lastSeen = lastSeen; this.packageName = packageName; } } public void addSession(String userId, String clientId, int platform, int status, long lastSeen, String packageName) {<FILL_FUNCTION_BODY>
Session session = new Session(clientId, userId, platform, status, lastSeen, packageName); sessions.add(session);
201
36
237
<no_super_class>
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/OutputGetChannelInfo.java
OutputMenu
fromPbInfo
class OutputMenu { public String menuId; public String type; public String name; public String key; public String url; public String mediaId; public String articleId; public String appId; public String appPage; public String extra; public List<OutputMenu> subMenus; public static OutputMenu fromPbInfo(WFCMessage.ChannelMenu channelMenuMenu) {<FILL_FUNCTION_BODY>} public WFCMessage.ChannelMenu.Builder toPbInfo() { WFCMessage.ChannelMenu.Builder builder = WFCMessage.ChannelMenu.newBuilder(); builder.setType(type); builder.setName(name); if (!StringUtil.isNullOrEmpty(menuId)) builder.setMenuId(menuId); if (!StringUtil.isNullOrEmpty(key)) builder.setKey(key); if (!StringUtil.isNullOrEmpty(url)) builder.setUrl(url); if (!StringUtil.isNullOrEmpty(mediaId)) builder.setMediaId(mediaId); if (!StringUtil.isNullOrEmpty(articleId)) builder.setArticleId(articleId); if (!StringUtil.isNullOrEmpty(appId)) builder.setAppId(appId); if (!StringUtil.isNullOrEmpty(appPage)) builder.setAppPage(appPage); if (!StringUtil.isNullOrEmpty(extra)) builder.setExtra(extra); if (subMenus != null && !subMenus.isEmpty()) { subMenus.forEach(menuMenu -> builder.addSubMenu(menuMenu.toPbInfo())); } return builder; } }
OutputMenu out = new OutputMenu(); out.menuId = channelMenuMenu.getMenuId(); out.type = channelMenuMenu.getType(); out.name = channelMenuMenu.getName(); out.key = channelMenuMenu.getKey(); out.url = channelMenuMenu.getUrl(); out.mediaId = channelMenuMenu.getMediaId(); out.articleId = channelMenuMenu.getArticleId(); out.appId = channelMenuMenu.getAppId(); out.appPage = channelMenuMenu.getAppPage(); out.extra = channelMenuMenu.getExtra(); if (channelMenuMenu.getSubMenuCount() > 0) { out.subMenus = new ArrayList<>(); for (WFCMessage.ChannelMenu menuMenu : channelMenuMenu.getSubMenuList()) { out.subMenus.add(fromPbInfo(menuMenu)); } } return out;
418
234
652
<no_super_class>
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/OutputMessageData.java
OutputMessageData
fromProtoMessage
class OutputMessageData { private long messageId; private String sender; private Conversation conv; private MessagePayload payload; private List<String> toUsers; private long timestamp; private OutputClient client; public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public Conversation getConv() { return conv; } public void setConv(Conversation conv) { this.conv = conv; } public MessagePayload getPayload() { return payload; } public void setPayload(MessagePayload payload) { this.payload = payload; } public List<String> getToUsers() { return toUsers; } public void setToUsers(List<String> toUsers) { this.toUsers = toUsers; } public long getMessageId() { return messageId; } public void setMessageId(long messageId) { this.messageId = messageId; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public OutputClient getClient() { return client; } public void setClient(OutputClient client) { this.client = client; } public static OutputMessageData fromProtoMessage(WFCMessage.Message protoMessage) { return fromProtoMessage(protoMessage, null); } public static OutputMessageData fromProtoMessage(WFCMessage.Message protoMessage, OutputClient fromClient) {<FILL_FUNCTION_BODY>} }
OutputMessageData data = new OutputMessageData(); data.messageId = protoMessage.getMessageId(); data.sender = protoMessage.getFromUser(); data.conv = new Conversation(); data.conv.setTarget(protoMessage.getConversation().getTarget()); data.conv.setType(protoMessage.getConversation().getType()); data.conv.setLine(protoMessage.getConversation().getLine()); data.payload = MessagePayload.fromProtoMessageContent(protoMessage.getContent()); data.timestamp = protoMessage.getServerTimestamp(); data.toUsers = protoMessage.getToList(); data.client = fromClient; return data;
447
172
619
<no_super_class>
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/OutputRobot.java
OutputRobot
fromUser
class OutputRobot { private String userId; private String name; private String password; private String displayName; private String portrait; private int gender; private String mobile; private String email; private String address; private String company; private String social; private String extra; private long updateDt; private String owner; private String secret; private String callback; private String robotExtra; public String getSocial() { return social; } public void setSocial(String social) { this.social = social; } public long getUpdateDt() { return updateDt; } public void setUpdateDt(long updateDt) { this.updateDt = updateDt; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getPortrait() { return portrait; } public void setPortrait(String portrait) { this.portrait = portrait; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public String getCallback() { return callback; } public void setCallback(String callback) { this.callback = callback; } public String getRobotExtra() { return robotExtra; } public void setRobotExtra(String robotExtra) { this.robotExtra = robotExtra; } public void fromUser(WFCMessage.User user) {<FILL_FUNCTION_BODY>} public void fromRobot(WFCMessage.Robot robot, boolean withSecret) { setOwner(robot.getOwner()); if(withSecret) { setSecret(robot.getSecret()); } setCallback(robot.getCallback()); setRobotExtra(robot.getExtra()); } }
userId = user.getUid(); name = user.getName(); displayName = user.getDisplayName(); portrait = user.getPortrait(); gender = user.getGender(); mobile = user.getMobile(); email = user.getEmail(); address = user.getAddress(); company = user.getCompany(); social = user.getSocial(); extra = user.getExtra(); updateDt = user.getUpdateDt();
944
120
1,064
<no_super_class>
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/SendChannelMessageData.java
SendChannelMessageData
toProtoMessage
class SendChannelMessageData { private List<String> targets; private int line; private MessagePayload payload; public List<String> getTargets() { return targets; } public void setTargets(List<String> targets) { this.targets = targets; } public int getLine() { return line; } public void setLine(int line) { this.line = line; } public MessagePayload getPayload() { return payload; } public void setPayload(MessagePayload payload) { this.payload = payload; } public static boolean isValide(SendChannelMessageData sendMessageData) { if(sendMessageData == null || sendMessageData.getPayload() == null) { return false; } return true; } public WFCMessage.Message toProtoMessage(String channelId, String channelOwner) {<FILL_FUNCTION_BODY>} }
if (targets == null) { targets = new ArrayList<>(); } return WFCMessage.Message.newBuilder().setFromUser(channelOwner) .setConversation(WFCMessage.Conversation.newBuilder().setType(ProtoConstants.ConversationType.ConversationType_Channel).setTarget(channelId).setLine(line)) .addAllTo(targets) .setContent(payload.toProtoMessageContent()) .build();
261
117
378
<no_super_class>
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/SendMessageData.java
SendMessageData
fromProtoMessage
class SendMessageData { private String sender; private Conversation conv; private MessagePayload payload; private List<String> toUsers; public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public Conversation getConv() { return conv; } public void setConv(Conversation conv) { this.conv = conv; } public MessagePayload getPayload() { return payload; } public void setPayload(MessagePayload payload) { this.payload = payload; } public List<String> getToUsers() { return toUsers; } public void setToUsers(List<String> toUsers) { this.toUsers = toUsers; } public static boolean isValide(SendMessageData sendMessageData) { if(sendMessageData == null || sendMessageData.getConv() == null || sendMessageData.getConv().getType() < 0 || sendMessageData.getConv().getType() > 6 || StringUtil.isNullOrEmpty(sendMessageData.getConv().getTarget()) || StringUtil.isNullOrEmpty(sendMessageData.getSender()) || sendMessageData.getPayload() == null) { return false; } return true; } public WFCMessage.Message toProtoMessage() { if (toUsers != null && toUsers.size() > 0) { return WFCMessage.Message.newBuilder().setFromUser(sender) .setConversation(WFCMessage.Conversation.newBuilder().setType(conv.getType()).setTarget(conv.getTarget()).setLine(conv.getLine())) .setContent(payload.toProtoMessageContent()) .addAllTo(toUsers) .build(); } else { return WFCMessage.Message.newBuilder().setFromUser(sender) .setConversation(WFCMessage.Conversation.newBuilder().setType(conv.getType()).setTarget(conv.getTarget()).setLine(conv.getLine())) .setContent(payload.toProtoMessageContent()) .build(); } } public static SendMessageData fromProtoMessage(WFCMessage.Message protoMessage) {<FILL_FUNCTION_BODY>} }
SendMessageData data = new SendMessageData(); data.sender = protoMessage.getFromUser(); data.conv = new Conversation(); data.conv.setTarget(protoMessage.getConversation().getTarget()); data.conv.setType(protoMessage.getConversation().getType()); data.conv.setLine(protoMessage.getConversation().getLine()); data.payload = MessagePayload.fromProtoMessageContent(protoMessage.getContent()); return data;
614
124
738
<no_super_class>
wildfirechat_im-server
im-server/common/src/main/java/cn/wildfirechat/pojos/UserSettingPojo.java
UserSettingPojo
toProtoRequest
class UserSettingPojo { private String userId; private int scope; private String key; private String value; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public int getScope() { return scope; } public void setScope(int scope) { this.scope = scope; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public WFCMessage.ModifyUserSettingReq toProtoRequest() {<FILL_FUNCTION_BODY>} }
WFCMessage.ModifyUserSettingReq.Builder builder = WFCMessage.ModifyUserSettingReq.newBuilder(); builder.setScope(scope); if (!StringUtil.isNullOrEmpty(key)) builder.setKey(key); if(!StringUtil.isNullOrEmpty(value)) builder.setValue(value); return builder.build();
230
96
326
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/ChannelServiceApi.java
ChannelServiceApi
getUserInfo
class ChannelServiceApi { private final ChannelHttpUtils channelHttpUtils; public ChannelServiceApi(String imurl, String channelId, String secret) { channelHttpUtils = new ChannelHttpUtils(imurl, channelId, secret); } public IMResult<InputOutputUserInfo> getUserInfo(String userId) throws Exception {<FILL_FUNCTION_BODY>} public IMResult<InputOutputUserInfo> getUserInfoByName(String userName) throws Exception { String path = APIPath.Channel_User_Info; InputGetUserInfo getUserInfo = new InputGetUserInfo(null, userName, null); return channelHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class); } public IMResult<InputOutputUserInfo> getUserInfoByMobile(String mobile) throws Exception { String path = APIPath.Channel_User_Info; InputGetUserInfo getUserInfo = new InputGetUserInfo(null, null, mobile); return channelHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class); } public IMResult<Void> modifyChannelInfo(/*ProtoConstants.ModifyChannelInfoType*/int type, String value) throws Exception { String path = APIPath.Channel_Update_Profile; InputModifyChannelInfo modifyChannelInfo = new InputModifyChannelInfo(); modifyChannelInfo.setType(type); modifyChannelInfo.setValue(value); return channelHttpUtils.httpJsonPost(path, modifyChannelInfo, Void.class); } public IMResult<OutputGetChannelInfo> getChannelInfo() throws Exception { String path = APIPath.Channel_Get_Profile; return channelHttpUtils.httpJsonPost(path, null, OutputGetChannelInfo.class); } public IMResult<Void> modifyChannelMenu(List<OutputGetChannelInfo.OutputMenu> menus) throws Exception { String menuStr = new Gson().toJson(menus); return modifyChannelInfo(ProtoConstants.ModifyChannelInfoType.Modify_Channel_Menu, menuStr); } public IMResult<SendMessageResult> sendMessage(int line, List<String> targets, MessagePayload payload) throws Exception { String path = APIPath.Channel_Message_Send; SendChannelMessageData messageData = new SendChannelMessageData(); messageData.setLine(0); messageData.setTargets(targets); messageData.setPayload(payload); return channelHttpUtils.httpJsonPost(path, messageData, SendMessageResult.class); } public IMResult<Void> subscribe(String userId) throws Exception { String path = APIPath.Channel_Subscribe; InputChannelSubscribe input = new InputChannelSubscribe(); input.setTarget(userId); input.setSubscribe(1); return channelHttpUtils.httpJsonPost(path, input, Void.class); } public IMResult<Void> unsubscribe(String userId) throws Exception { String path = APIPath.Channel_Subscribe; InputChannelSubscribe input = new InputChannelSubscribe(); input.setTarget(userId); input.setSubscribe(0); return channelHttpUtils.httpJsonPost(path, input, Void.class); } public IMResult<OutputStringList> getSubscriberList() throws Exception { String path = APIPath.Channel_Subscriber_List; return channelHttpUtils.httpJsonPost(path, null, OutputStringList.class); } public IMResult<Boolean> isSubscriber(String userId) throws Exception { String path = APIPath.Channel_Is_Subscriber; InputUserId input = new InputUserId(userId); return channelHttpUtils.httpJsonPost(path, input, Boolean.class); } public IMResult<OutputApplicationUserInfo> applicationGetUserInfo(String authCode) throws Exception { String path = APIPath.Channel_Application_Get_UserInfo; InputApplicationGetUserInfo input = new InputApplicationGetUserInfo(); input.setAuthCode(authCode); return channelHttpUtils.httpJsonPost(path, input, OutputApplicationUserInfo.class); } public OutputApplicationConfigData getApplicationSignature() { int nonce = (int)(Math.random() * 100000 + 3); long timestamp = System.currentTimeMillis()/1000; String str = nonce + "|" + channelHttpUtils.getChannelId() + "|" + timestamp + "|" + channelHttpUtils.getChannelSecret(); String sign = DigestUtils.sha1Hex(str); OutputApplicationConfigData configData = new OutputApplicationConfigData(); configData.setAppId(channelHttpUtils.getChannelId()); configData.setAppType(ApplicationType_Channel); configData.setTimestamp(timestamp); configData.setNonceStr(nonce+""); configData.setSignature(sign); return configData; } }
String path = APIPath.Channel_User_Info; InputGetUserInfo getUserInfo = new InputGetUserInfo(userId, null, null); return channelHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
1,253
65
1,318
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/ChatroomAdmin.java
ChatroomAdmin
getChatroomBlacklist
class ChatroomAdmin { public static IMResult<OutputCreateChatroom> createChatroom(String chatroomId, String title, String desc ,String portrait, String extra, Integer state) throws Exception { String path = APIPath.Create_Chatroom; InputCreateChatroom input = new InputCreateChatroom(); input.setChatroomId(chatroomId); input.setTitle(title); input.setDesc(desc); input.setPortrait(portrait); input.setExtra(extra); input.setState(state); return AdminHttpUtils.httpJsonPost(path, input, OutputCreateChatroom.class); } public static IMResult<Void> destroyChatroom(String chatroomId) throws Exception { String path = APIPath.Chatroom_Destroy; InputDestoryChatroom input = new InputDestoryChatroom(); input.setChatroomId(chatroomId); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<OutputGetChatroomInfo> getChatroomInfo(String chatroomId) throws Exception { String path = APIPath.Chatroom_Info; InputGetChatroomInfo input = new InputGetChatroomInfo(chatroomId); return AdminHttpUtils.httpJsonPost(path, input, OutputGetChatroomInfo.class); } public static IMResult<OutputStringList> getChatroomMembers(String chatroomId) throws Exception { String path = APIPath.Chatroom_GetMembers; InputGetChatroomInfo input = new InputGetChatroomInfo(chatroomId); return AdminHttpUtils.httpJsonPost(path, input, OutputStringList.class); } public static IMResult<OutputUserChatroom> getUserChatroom(String userId) throws Exception { String path = APIPath.Chatroom_GetUserChatroom; InputUserId input = new InputUserId(userId); return AdminHttpUtils.httpJsonPost(path, input, OutputUserChatroom.class); } //仅专业版支持 //status:0,正常;1,禁言;2,禁止加入 public static IMResult<Void> setChatroomBlacklist(String chatroomId, String userId, int status) throws Exception { String path = APIPath.Chatroom_SetBlacklist; InputSetChatroomBlacklist input = new InputSetChatroomBlacklist(chatroomId, userId, status, 0); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<OutputChatroomBlackInfos> getChatroomBlacklist(String chatroomId) throws Exception {<FILL_FUNCTION_BODY>} //status: 1 set; 0 unset public static IMResult<Void> setChatroomManager(String chatroomId, String userId, int status) throws Exception { String path = APIPath.Chatroom_SetManager; InputSetChatroomManager input = new InputSetChatroomManager(chatroomId, userId, status); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<OutputStringList> getChatroomManagerList(String chatroomId) throws Exception { String path = APIPath.Chatroom_GetManagerList; InputChatroomId input = new InputChatroomId(chatroomId); return AdminHttpUtils.httpJsonPost(path, input, OutputStringList.class); } public static IMResult<Void> setChatroomMute(String chatroomId, boolean mute) throws Exception { String path = APIPath.Chatroom_MuteAll; InputChatroomMute input = new InputChatroomMute(chatroomId, mute ? 1 : 0); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } }
String path = APIPath.Chatroom_GetBlacklist; InputChatroomId input = new InputChatroomId(chatroomId); return AdminHttpUtils.httpJsonPost(path, input, OutputChatroomBlackInfos.class);
969
62
1,031
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/ConferenceAdmin.java
ConferenceAdmin
rtpForward
class ConferenceAdmin { public static IMResult<PojoConferenceInfoList> listConferences() throws Exception { String path = APIPath.Conference_List; return AdminHttpUtils.httpJsonPost(path, null, PojoConferenceInfoList.class); } public static IMResult<Boolean> existsConferences(String conferenceId) throws Exception { String path = APIPath.Conference_Exist; PojoConferenceRoomId data = new PojoConferenceRoomId(conferenceId, false); return AdminHttpUtils.httpJsonPost(path, data, Boolean.class); } public static IMResult<PojoConferenceParticipantList> listParticipants(String roomId, boolean advance) throws Exception { String path = APIPath.Conference_List_Participant; PojoConferenceRoomId data = new PojoConferenceRoomId(roomId, advance); return AdminHttpUtils.httpJsonPost(path, data, PojoConferenceParticipantList.class); } public static IMResult<Void> createRoom(String roomId, String description, String pin, int maxPublisher, boolean advance, int bitrate, boolean recording, boolean permanent) throws Exception { String path = APIPath.Conference_Create; PojoConferenceCreate create = new PojoConferenceCreate(); create.roomId = roomId; create.description = description; create.pin = pin; create.max_publishers = maxPublisher; create.advance = advance; create.bitrate = bitrate; create.recording = recording; create.permanent = permanent; return AdminHttpUtils.httpJsonPost(path, create, Void.class); } public static IMResult<Void> enableRecording(String roomId, boolean advance, boolean recording) throws Exception { String path = APIPath.Conference_Recording; PojoConferenceRecording create = new PojoConferenceRecording(); create.roomId = roomId; create.recording = recording; create.advance = advance; return AdminHttpUtils.httpJsonPost(path, create, Void.class); } public static IMResult<Void> destroy(String roomId, boolean advance) throws Exception { String path = APIPath.Conference_Destroy; PojoConferenceRoomId conferenceRoomId = new PojoConferenceRoomId(roomId, advance); return AdminHttpUtils.httpJsonPost(path, conferenceRoomId, Void.class); } public static IMResult<Void> rtpForward(String roomId, String userId, String rtpHost, int audioPort, int audioPt, long audioSSRC, int videoPort, int videoPt, long videoSSRC) throws Exception {<FILL_FUNCTION_BODY>} public static IMResult<Void> stopRtpForward(String roomId, String userId, long streamId) throws Exception { String path = APIPath.Conference_Stop_Rtp_Forward; PojoConferenceStopRtpForwardReq req = new PojoConferenceStopRtpForwardReq(roomId, userId, streamId); return AdminHttpUtils.httpJsonPost(path, req, Void.class); } public static IMResult<PojoConferenceRtpForwarders> listRtpForwarders(String roomId) throws Exception { String path = APIPath.Conference_List_Rtp_Forward; PojoConferenceRoomId req = new PojoConferenceRoomId(); req.roomId = roomId; return AdminHttpUtils.httpJsonPost(path, req, PojoConferenceRtpForwarders.class); } }
String path = APIPath.Conference_Rtp_Forward; PojoConferenceRtpForwardReq req = new PojoConferenceRtpForwardReq(roomId, userId, rtpHost, audioPort, audioPt, audioSSRC, videoPort, videoPt, videoSSRC); return AdminHttpUtils.httpJsonPost(path, req, Void.class);
937
100
1,037
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/GeneralAdmin.java
GeneralAdmin
getConversationTop
class GeneralAdmin { public static IMResult<SystemSettingPojo> getSystemSetting(int id) throws Exception { String path = APIPath.Get_System_Setting; SystemSettingPojo input = new SystemSettingPojo(); input.id = id; return AdminHttpUtils.httpJsonPost(path, input, SystemSettingPojo.class); } public static IMResult<Void> setSystemSetting(int id, String value, String desc) throws Exception { String path = APIPath.Put_System_Setting; SystemSettingPojo input = new SystemSettingPojo(); input.id = id; input.value = value; input.desc = desc; return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<OutputCreateChannel> createChannel(InputCreateChannel inputCreateChannel) throws Exception { String path = APIPath.Create_Channel; return AdminHttpUtils.httpJsonPost(path, inputCreateChannel, OutputCreateChannel.class); } public static IMResult<Void> destroyChannel(String channelId) throws Exception { String path = APIPath.Destroy_Channel; InputChannelId inputChannelId = new InputChannelId(channelId); return AdminHttpUtils.httpJsonPost(path, inputChannelId, Void.class); } public static IMResult<OutputGetChannelInfo> getChannelInfo(String channelId) throws Exception { String path = APIPath.Get_Channel_Info; InputChannelId inputChannelId = new InputChannelId(channelId); return AdminHttpUtils.httpJsonPost(path, inputChannelId, OutputGetChannelInfo.class); } public static IMResult<Void> subscribeChannel(String channelId, String userId) throws Exception { String path = APIPath.Subscribe_Channel; InputSubscribeChannel input = new InputSubscribeChannel(channelId, userId, 1); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<Void> unsubscribeChannel(String channelId, String userId) throws Exception { String path = APIPath.Subscribe_Channel; InputSubscribeChannel input = new InputSubscribeChannel(channelId, userId, 0); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<OutputBooleanValue> isUserSubscribedChannel(String userId, String channelId) throws Exception { String path = APIPath.Check_User_Subscribe_Channel; InputSubscribeChannel input = new InputSubscribeChannel(channelId, userId, 0); return AdminHttpUtils.httpJsonPost(path, input, OutputBooleanValue.class); } //以下仅专业版支持 public static IMResult<Void> setConversationTop(String userId, int conversationType, String target, int line, boolean isTop) throws Exception { String key = conversationType + "-" + line + "-" + target; String value = isTop?"1":"0"; return setUserSetting(userId, 3, key, value); } public static IMResult<Boolean> getConversationTop(String userId, int conversationType, String target, int line) throws Exception {<FILL_FUNCTION_BODY>} public static IMResult<UserSettingPojo> getUserSetting(String userId, int scope, String key) throws Exception { String path = APIPath.User_Get_Setting; UserSettingPojo pojo = new UserSettingPojo(); pojo.setUserId(userId); pojo.setScope(scope); pojo.setKey(key); return AdminHttpUtils.httpJsonPost(path, pojo, UserSettingPojo.class); } public static IMResult<Void> setUserSetting(String userId, int scope, String key, String value) throws Exception { String path = APIPath.User_Put_Setting; UserSettingPojo pojo = new UserSettingPojo(); pojo.setUserId(userId); pojo.setScope(scope); pojo.setKey(key); pojo.setValue(value); return AdminHttpUtils.httpJsonPost(path, pojo, Void.class); } public static IMResult<HealthCheckResult> healthCheck() throws Exception { return AdminHttpUtils.httpGet(APIPath.Health, HealthCheckResult.class); } public static IMResult<String> getCustomer() throws Exception { return AdminHttpUtils.httpJsonPost(APIPath.GET_CUSTOMER, null, String.class); } }
String key = conversationType + "-" + line + "-" + target; IMResult<UserSettingPojo> result = getUserSetting(userId, 3, key); IMResult<Boolean> out = new IMResult<Boolean>(); out.code = result.code; out.msg = result.msg; out.result = result.result != null && "1".equals(result.result.getValue()); return out;
1,171
110
1,281
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/MessageAdmin.java
MessageAdmin
clearConversation
class MessageAdmin { public static IMResult<SendMessageResult> sendMessage(String sender, Conversation conversation, MessagePayload payload) throws Exception { return sendMessage(sender, conversation, payload, null); } //toUsers为发送给会话中部分用户用的,正常为null,仅当需要指定群/频道/聊天室中部分接收用户时使用 public static IMResult<SendMessageResult> sendMessage(String sender, Conversation conversation, MessagePayload payload, List<String> toUsers) throws Exception { String path = APIPath.Msg_Send; SendMessageData messageData = new SendMessageData(); messageData.setSender(sender); messageData.setConv(conversation); messageData.setPayload(payload); messageData.setToUsers(toUsers); if (payload.getType() == 1 && (payload.getSearchableContent() == null || payload.getSearchableContent().isEmpty())) { System.out.println("Payload错误,Payload格式应该跟客户端消息encode出来的Payload对齐,这样客户端才能正确识别。比如文本消息,文本需要放到searchableContent属性。请与客户端同事确认Payload的格式,或则去 https://gitee.com/wfchat/android-chat/tree/master/client/src/main/java/cn/wildfirechat/message 找到消息encode的实现方法!"); } return AdminHttpUtils.httpJsonPost(path, messageData, SendMessageResult.class); } public static IMResult<String> recallMessage(String operator, long messageUid) throws Exception { String path = APIPath.Msg_Recall; RecallMessageData messageData = new RecallMessageData(); messageData.setOperator(operator); messageData.setMessageUid(messageUid); return AdminHttpUtils.httpJsonPost(path, messageData, String.class); } //仅专业版支持 public static IMResult<Void> deleteMessage(long messageUid) throws Exception { String path = APIPath.Msg_Delete; DeleteMessageData deleteMessageData = new DeleteMessageData(); deleteMessageData.setMessageUid(messageUid); return AdminHttpUtils.httpJsonPost(path, deleteMessageData, Void.class); } //仅专业版支持 public static IMResult<Void> clearUserMessages(String userId, Conversation conversation, long fromTime, long toTime) throws Exception { String path = APIPath.Msg_Clear_By_User; InputClearUserMessages clearUserMessages = new InputClearUserMessages(userId, conversation, fromTime, toTime); return AdminHttpUtils.httpJsonPost(path, clearUserMessages, Void.class); } //仅专业版支持 public static IMResult<Void> updateMessageContent(String operator, long messageUid, MessagePayload payload, boolean distribute) throws Exception { String path = APIPath.Msg_Update; UpdateMessageContentData updateMessageContentData = new UpdateMessageContentData(); updateMessageContentData.setOperator(operator); updateMessageContentData.setMessageUid(messageUid); updateMessageContentData.setPayload(payload); updateMessageContentData.setDistribute(distribute?1:0); updateMessageContentData.setUpdateTimestamp(0); return AdminHttpUtils.httpJsonPost(path, updateMessageContentData, Void.class); } //仅专业版支持 public static IMResult<Void> clearConversation(String userId, Conversation conversation) throws Exception {<FILL_FUNCTION_BODY>} /** * 获取单条消息。如果想要更多消息的读取,可以直接读取IM服务的数据库。 * @param messageUid * @return * @throws Exception */ public static IMResult<OutputMessageData> getMessage(long messageUid) throws Exception { String path = APIPath.Msg_GetOne; InputMessageUid inputMessageUid = new InputMessageUid(messageUid); return AdminHttpUtils.httpJsonPost(path, inputMessageUid, OutputMessageData.class); } /** * 撤回群发或者广播的消息 * @param operator 操作者 * @param messageUid 消息唯一ID * @return * @throws Exception */ public static IMResult<Void> recallBroadCastMessage(String operator, long messageUid) throws Exception { String path = APIPath.Msg_RecallBroadCast; RecallMessageData messageData = new RecallMessageData(); messageData.setOperator(operator); messageData.setMessageUid(messageUid); return AdminHttpUtils.httpJsonPost(path, messageData, Void.class); } public static IMResult<Void> recallMultiCastMessage(String operator, long messageUid, List<String> receivers) throws Exception { String path = APIPath.Msg_RecallMultiCast; RecallMultiCastMessageData messageData = new RecallMultiCastMessageData(); messageData.operator = operator; messageData.messageUid = messageUid; messageData.receivers = receivers; return AdminHttpUtils.httpJsonPost(path, messageData, Void.class); } public static IMResult<BroadMessageResult> broadcastMessage(String sender, int line, MessagePayload payload) throws Exception { String path = APIPath.Msg_Broadcast; BroadMessageData messageData = new BroadMessageData(); messageData.setSender(sender); messageData.setLine(line); messageData.setPayload(payload); return AdminHttpUtils.httpJsonPost(path, messageData, BroadMessageResult.class); } public static IMResult<MultiMessageResult> multicastMessage(String sender, List<String> receivers, int line, MessagePayload payload) throws Exception { String path = APIPath.Msg_Multicast; MulticastMessageData messageData = new MulticastMessageData(); messageData.setSender(sender); messageData.setTargets(receivers); messageData.setLine(line); messageData.setPayload(payload); return AdminHttpUtils.httpJsonPost(path, messageData, MultiMessageResult.class); } public static IMResult<OutputTimestamp> getConversationReadTimestamp(String userId, Conversation conversation) throws Exception { String path = APIPath.Msg_ConvRead; InputGetConvReadTime input = new InputGetConvReadTime(userId, conversation.getType(), conversation.getTarget(), conversation.getLine()); return AdminHttpUtils.httpJsonPost(path, input, OutputTimestamp.class); } public static IMResult<OutputTimestamp> getMessageDelivery(String userId) throws Exception { String path = APIPath.Msg_Delivery; InputUserId input = new InputUserId(userId); return AdminHttpUtils.httpJsonPost(path, input, OutputTimestamp.class); } }
String path = APIPath.Conversation_Delete; InputUserConversation input = new InputUserConversation(); input.userId = userId; input.conversation = conversation; return AdminHttpUtils.httpJsonPost(path, input, Void.class);
1,767
71
1,838
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/RelationAdmin.java
RelationAdmin
setUserFriend
class RelationAdmin { public static IMResult<Void> setUserFriend(String userId, String targetId, boolean isFriend, String extra) throws Exception {<FILL_FUNCTION_BODY>} public static IMResult<OutputStringList> getFriendList(String userId) throws Exception { String path = APIPath.Friend_Get_List; InputUserId input = new InputUserId(); input.setUserId(userId); return AdminHttpUtils.httpJsonPost(path, input, OutputStringList.class); } public static IMResult<Void> setUserBlacklist(String userId, String targetId, boolean isBlacklist) throws Exception { String path = APIPath.Blacklist_Update_Status; InputBlacklistRequest input = new InputBlacklistRequest(); input.setUserId(userId); input.setTargetUid(targetId); input.setStatus(isBlacklist ? 2 : 1); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<OutputStringList> getUserBlacklist(String userId) throws Exception { String path = APIPath.Blacklist_Get_List; InputUserId input = new InputUserId(); input.setUserId(userId); return AdminHttpUtils.httpJsonPost(path, input, OutputStringList.class); } public static IMResult<Void> updateFriendAlias(String operator, String targetId, String alias) throws Exception { String path = APIPath.Friend_Set_Alias; InputUpdateAlias input = new InputUpdateAlias(); input.setOperator(operator); input.setTargetId(targetId); input.setAlias(alias); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<OutputGetAlias> getFriendAlias(String operator, String targetId) throws Exception { String path = APIPath.Friend_Get_Alias; InputGetAlias input = new InputGetAlias(); input.setOperator(operator); input.setTargetId(targetId); return AdminHttpUtils.httpJsonPost(path, input, OutputGetAlias.class); } public static IMResult<Void> updateFriendExtra(String operator, String targetId, String extra) throws Exception { String path = APIPath.Friend_Set_Extra; InputUpdateFriendExtra input = new InputUpdateFriendExtra(); input.setOperator(operator); input.setTargetId(targetId); input.setExtra(extra); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<Void> sendFriendRequest(String userId, String targetId, String reason, boolean force) throws Exception { String path = APIPath.Friend_Send_Request; InputAddFriendRequest input = new InputAddFriendRequest(); input.setUserId(userId); input.setFriendUid(targetId); input.setReason(reason); input.setForce(force); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<RelationPojo> getRelation(String userId, String targetId) throws Exception { String path = APIPath.Relation_Get; StringPairPojo input = new StringPairPojo(userId, targetId); return AdminHttpUtils.httpJsonPost(path, input, RelationPojo.class); } }
String path = APIPath.Friend_Update_Status; InputUpdateFriendStatusRequest input = new InputUpdateFriendStatusRequest(); input.setUserId(userId); input.setFriendUid(targetId); input.setStatus(isFriend ? 0 : 1); //历史遗留问题,在IM数据库中0是好友,1是好友被删除。 input.setExtra(extra); return AdminHttpUtils.httpJsonPost(path, input, Void.class);
892
127
1,019
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/SensitiveAdmin.java
SensitiveAdmin
addSensitives
class SensitiveAdmin { public static IMResult<Void> addSensitives(List<String> sensitives) throws Exception {<FILL_FUNCTION_BODY>} public static IMResult<Void> removeSensitives(List<String> sensitives) throws Exception { String path = APIPath.Sensitive_Del; InputOutputSensitiveWords input = new InputOutputSensitiveWords(); input.setWords(sensitives); return AdminHttpUtils.httpJsonPost(path, input, Void.class); } public static IMResult<InputOutputSensitiveWords> getSensitives() throws Exception { String path = APIPath.Sensitive_Query; return AdminHttpUtils.httpJsonPost(path, null, InputOutputSensitiveWords.class); } }
String path = APIPath.Sensitive_Add; InputOutputSensitiveWords input = new InputOutputSensitiveWords(); input.setWords(sensitives); return AdminHttpUtils.httpJsonPost(path, input, Void.class);
204
67
271
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/utilities/AdminHttpUtils.java
AdminHttpUtils
httpGet
class AdminHttpUtils extends JsonUtils { private static final Logger LOG = LoggerFactory.getLogger(AdminHttpUtils.class); public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); private static String adminUrl; private static String adminSecret; private static CloseableHttpClient httpClient; public static void init(String url, String secret) { adminUrl = url; adminSecret = secret; PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setValidateAfterInactivity(1000); httpClient = HttpClients.custom() .setConnectionManager(cm) .evictExpiredConnections() .evictIdleConnections(60L, TimeUnit.SECONDS) .setRetryHandler(DefaultHttpRequestRetryHandler.INSTANCE) .setMaxConnTotal(100) .setMaxConnPerRoute(50) .build(); } public static <T> IMResult<T> httpGet(String path, Class<T> clazz) throws Exception {<FILL_FUNCTION_BODY>} public static <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception { if (isNullOrEmpty(adminUrl) || isNullOrEmpty(adminSecret)) { LOG.error("野火IM Server SDK必须先初始化才能使用,是不是忘记初始化了!!!!"); throw new Exception("SDK没有初始化"); } if (isNullOrEmpty(path)) { throw new Exception("路径缺失"); } String url = adminUrl + path; HttpPost post = null; try { int nonce = (int)(Math.random() * 100000 + 3); long timestamp = System.currentTimeMillis(); String str = nonce + "|" + adminSecret + "|" + timestamp; String sign = DigestUtils.sha1Hex(str); post = new HttpPost(url); post.setHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Connection", "Keep-Alive"); post.setHeader("nonce", nonce + ""); post.setHeader("timestamp", "" + timestamp); post.setHeader("sign", sign); String jsonStr = ""; if (object != null) { jsonStr = gson.toJson(object); } LOG.info("http request:{} content: {}", url, jsonStr); StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = httpClient.execute(post); int statusCode = response.getStatusLine().getStatusCode(); String content = null; if (response.getEntity().getContentLength() > 0) { BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8")); StringBuilder sb = new StringBuilder(); String line; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line).append(NL); } in.close(); content = sb.toString(); LOG.info("http request response content: {}", content); } if(statusCode != HttpStatus.SC_OK){ LOG.info("Request error: " + statusCode + " error msg:" + content); throw new Exception("Http request error with code:" + statusCode); } else { return fromJsonObject(content, clazz); } } catch (Exception e) { e.printStackTrace(); throw e; } finally { if(post != null) { post.releaseConnection(); } } } }
if (isNullOrEmpty(adminUrl) || isNullOrEmpty(adminSecret)) { LOG.error("野火IM Server SDK必须先初始化才能使用,是不是忘记初始化了!!!!"); throw new Exception("SDK没有初始化"); } if (isNullOrEmpty(path)) { throw new Exception("路径缺失"); } HttpGet get = null; try { get = new HttpGet(adminUrl + path); HttpResponse response = httpClient.execute(get); int statusCode = response.getStatusLine().getStatusCode(); String content = null; if (response.getEntity().getContentLength() > 0) { BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8")); StringBuilder sb = new StringBuilder(); String line; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line).append(NL); } in.close(); content = sb.toString(); LOG.info("http request response content: {}", content); } if(statusCode != HttpStatus.SC_OK){ LOG.info("Request error: " + statusCode + " error msg:" + content); throw new Exception("Http request error with code:" + statusCode); } else { return fromJsonObject(content, clazz); } } catch (Exception e) { e.printStackTrace(); throw e; } finally { if(get != null) { get.releaseConnection(); } }
1,021
427
1,448
<methods>public non-sealed void <init>() ,public static IMResult<T> fromJsonObject(java.lang.String, Class<T>) ,public static boolean isNullOrEmpty(java.lang.String) <variables>public static final com.google.gson.Gson gson
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/utilities/ChannelHttpUtils.java
ChannelHttpUtils
httpJsonPost
class ChannelHttpUtils extends JsonUtils { private static final Logger LOG = LoggerFactory.getLogger(ChannelHttpUtils.class); public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); private String imurl; private String channelId; private String channelSecret; private final CloseableHttpClient httpClient; public ChannelHttpUtils(String imurl, String channelId, String secret) { this.imurl = imurl; this.channelId = channelId; this.channelSecret = secret; PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setValidateAfterInactivity(1000); httpClient = HttpClients.custom() .setConnectionManager(cm) .evictExpiredConnections() .evictIdleConnections(60L, TimeUnit.SECONDS) .setRetryHandler(DefaultHttpRequestRetryHandler.INSTANCE) .setMaxConnTotal(100) .setMaxConnPerRoute(50) .build(); } public <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception{<FILL_FUNCTION_BODY>} public String getChannelId() { return channelId; } public String getChannelSecret() { return channelSecret; } }
if (isNullOrEmpty(imurl) || isNullOrEmpty(path)) { LOG.error("Not init IM SDK correctly. Do you forget init it?"); throw new Exception("SDK url or secret lack!"); } String url = imurl + path; HttpPost post = null; try { int nonce = (int)(Math.random() * 100000 + 3); long timestamp = System.currentTimeMillis(); String str = nonce + "|" + channelSecret + "|" + timestamp; String sign = DigestUtils.sha1Hex(str); post = new HttpPost(url); post.setHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Connection", "Keep-Alive"); post.setHeader("nonce", nonce + ""); post.setHeader("timestamp", "" + timestamp); post.setHeader("cid", channelId); post.setHeader("sign", sign); String jsonStr = ""; if (object != null) { jsonStr = gson.toJson(object); } LOG.info("http request:{} content: {}", url, jsonStr); StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = httpClient.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode != HttpStatus.SC_OK){ LOG.info("Request error: "+statusCode); throw new Exception("Http request error with code:" + statusCode); }else{ BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent(),"utf-8")); StringBuffer sb = new StringBuffer(); String line; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String content = sb.toString(); LOG.info("http request response content: {}", content); return fromJsonObject(content, clazz); } } catch (Exception e) { e.printStackTrace(); throw e; }finally{ if(post != null){ post.releaseConnection(); } }
357
640
997
<methods>public non-sealed void <init>() ,public static IMResult<T> fromJsonObject(java.lang.String, Class<T>) ,public static boolean isNullOrEmpty(java.lang.String) <variables>public static final com.google.gson.Gson gson
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/utilities/JsonUtils.java
JsonUtils
fromJsonObject
class JsonUtils { public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); public static <T> IMResult<T> fromJsonObject(String content, Class<T> clazz) {<FILL_FUNCTION_BODY>} public static boolean isNullOrEmpty(String str) { return str == null || str.isEmpty(); } }
TypeBuilder builder = TypeBuilder.newInstance(IMResult.class); if (!clazz.equals(Void.class)) { builder.addTypeParam(clazz); } return gson.fromJson(content, builder.build());
97
64
161
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/cn/wildfirechat/sdk/utilities/RobotHttpUtils.java
RobotHttpUtils
httpJsonPost
class RobotHttpUtils extends JsonUtils { private static final Logger LOG = LoggerFactory.getLogger(RobotHttpUtils.class); public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); private final String url; private final String robotId; private final String robotSecret; private final CloseableHttpClient httpClient; public RobotHttpUtils(String url, String robotId, String robotSecret) { this.url = url; this.robotId = robotId; this.robotSecret = robotSecret; PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setValidateAfterInactivity(1000); httpClient = HttpClients.custom() .setConnectionManager(cm) .evictExpiredConnections() .evictIdleConnections(60L, TimeUnit.SECONDS) .setRetryHandler(DefaultHttpRequestRetryHandler.INSTANCE) .setMaxConnTotal(100) .setMaxConnPerRoute(50) .build(); } public <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception{<FILL_FUNCTION_BODY>} public String getRobotId() { return robotId; } public String getRobotSecret() { return robotSecret; } }
if (isNullOrEmpty(url) || isNullOrEmpty(path)) { LOG.error("Not init IM SDK correctly. Do you forget init it?"); throw new Exception("SDK url or secret lack!"); } String url = this.url + path; HttpPost post = null; try { int nonce = (int)(Math.random() * 100000 + 3); long timestamp = System.currentTimeMillis(); String str = nonce + "|" + robotSecret + "|" + timestamp; String sign = DigestUtils.sha1Hex(str); post = new HttpPost(url); post.setHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Connection", "Keep-Alive"); post.setHeader("nonce", nonce + ""); post.setHeader("timestamp", "" + timestamp); post.setHeader("rid", robotId); post.setHeader("sign", sign); String jsonStr = null; if (object != null) { jsonStr = gson.toJson(object); } LOG.info("http request:{} content: {}", url, jsonStr); if(!StringUtil.isNullOrEmpty(jsonStr)) { StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); } HttpResponse response = httpClient.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode != HttpStatus.SC_OK){ LOG.info("Request error: "+statusCode); throw new Exception("Http request error with code:" + statusCode); }else{ BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent(),"utf-8")); StringBuffer sb = new StringBuffer(); String line; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String content = sb.toString(); LOG.info("http request response content: {}", content); return fromJsonObject(content, clazz); } } catch (Exception e) { e.printStackTrace(); throw e; }finally{ if(post != null){ post.releaseConnection(); } }
366
659
1,025
<methods>public non-sealed void <init>() ,public static IMResult<T> fromJsonObject(java.lang.String, Class<T>) ,public static boolean isNullOrEmpty(java.lang.String) <variables>public static final com.google.gson.Gson gson
wildfirechat_im-server
im-server/sdk/src/main/java/ikidou/reflect/TypeBuilder.java
TypeBuilder
addTypeParam
class TypeBuilder { private final TypeBuilder parent; private final Class raw; private final List<Type> args = new ArrayList<>(); private TypeBuilder(Class raw, TypeBuilder parent) { assert raw != null; this.raw = raw; this.parent = parent; } public static TypeBuilder newInstance(Class raw) { return new TypeBuilder(raw, null); } private static TypeBuilder newInstance(Class raw, TypeBuilder parent) { return new TypeBuilder(raw, parent); } public TypeBuilder beginSubType(Class raw) { return newInstance(raw, this); } public TypeBuilder endSubType() { if (parent == null) { throw new TypeException("expect beginSubType() before endSubType()"); } parent.addTypeParam(getType()); return parent; } public TypeBuilder addTypeParam(Class clazz) { return addTypeParam((Type) clazz); } public TypeBuilder addTypeParamExtends(Class... classes) { if (classes == null) { throw new NullPointerException("addTypeParamExtends() expect not null Class"); } WildcardTypeImpl wildcardType = new WildcardTypeImpl(null, classes); return addTypeParam(wildcardType); } public TypeBuilder addTypeParamSuper(Class... classes) { if (classes == null) { throw new NullPointerException("addTypeParamSuper() expect not null Class"); } WildcardTypeImpl wildcardType = new WildcardTypeImpl(classes, null); return addTypeParam(wildcardType); } public TypeBuilder addTypeParam(Type type) {<FILL_FUNCTION_BODY>} public Type build() { if (parent != null) { throw new TypeException("expect endSubType() before build()"); } return getType(); } private Type getType() { if (args.isEmpty()) { return raw; } return new ParameterizedTypeImpl(raw, args.toArray(new Type[args.size()]), null); } }
if (type == null) { throw new NullPointerException("addTypeParam expect not null Type"); } args.add(type); return this;
555
46
601
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/ikidou/reflect/typeimpl/ParameterizedTypeImpl.java
ParameterizedTypeImpl
toString
class ParameterizedTypeImpl implements ParameterizedType { private final Class raw; private final Type[] args; private final Type owner; public ParameterizedTypeImpl(Class raw, Type[] args, Type owner) { this.raw = raw; this.args = args != null ? args : new Type[0]; this.owner = owner; checkArgs(); } private void checkArgs() { if (raw == null) { throw new TypeException("raw class can't be null"); } TypeVariable[] typeParameters = raw.getTypeParameters(); if (args.length != 0 && typeParameters.length != args.length) { throw new TypeException(raw.getName() + " expect " + typeParameters.length + " arg(s), got " + args.length); } } @Override public Type[] getActualTypeArguments() { return args; } @Override public Type getRawType() { return raw; } @Override public Type getOwnerType() { return owner; } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ParameterizedTypeImpl that = (ParameterizedTypeImpl) o; if (!raw.equals(that.raw)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(args, that.args)) return false; return owner != null ? owner.equals(that.owner) : that.owner == null; } @Override public int hashCode() { int result = raw.hashCode(); result = 31 * result + Arrays.hashCode(args); result = 31 * result + (owner != null ? owner.hashCode() : 0); return result; } }
StringBuilder sb = new StringBuilder(); sb.append(raw.getName()); if (args.length != 0) { sb.append('<'); for (int i = 0; i < args.length; i++) { if (i != 0) { sb.append(", "); } Type type = args[i]; if (type instanceof Class) { Class clazz = (Class) type; if (clazz.isArray()) { int count = 0; do { count++; clazz = clazz.getComponentType(); } while (clazz.isArray()); sb.append(clazz.getName()); for (int j = count; j > 0; j--) { sb.append("[]"); } } else { sb.append(clazz.getName()); } } else { sb.append(args[i].toString()); } } sb.append('>'); } return sb.toString();
517
264
781
<no_super_class>
wildfirechat_im-server
im-server/sdk/src/main/java/ikidou/reflect/typeimpl/WildcardTypeImpl.java
WildcardTypeImpl
getTypeString
class WildcardTypeImpl implements WildcardType { private final Class[] upper; private final Class[] lower; public WildcardTypeImpl(Class[] lower, Class[] upper) { this.lower = lower != null ? lower : new Class[0]; this.upper = upper != null ? upper : new Class[0]; checkArgs(); } private void checkArgs() { if (lower.length == 0 && upper.length == 0) { throw new IllegalArgumentException("lower or upper can't be null"); } checkArgs(lower); checkArgs(upper); } private void checkArgs(Class[] args) { for (int i = 1; i < args.length; i++) { Class clazz = args[i]; if (!clazz.isInterface()) { throw new IllegalArgumentException(clazz.getName() + " not a interface!"); } } } @Override public Type[] getUpperBounds() { return upper; } @Override public Type[] getLowerBounds() { return lower; } @Override public String toString() { if (upper.length > 0) { if (upper[0] == Object.class) { return "?"; } return getTypeString("? extends ", upper); } else { return getTypeString("? super ", lower); } } private String getTypeString(String prefix, Class[] type) {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WildcardTypeImpl that = (WildcardTypeImpl) o; return Arrays.equals(upper, that.upper) && Arrays.equals(lower, that.lower); } @Override public int hashCode() { int result = Arrays.hashCode(upper); result = 31 * result + Arrays.hashCode(lower); return result; } }
StringBuilder sb = new StringBuilder(); sb.append(prefix); for (int i = 0; i < type.length; i++) { if (i != 0) { sb.append(" & "); } sb.append(type[i].getName()); } return sb.toString();
541
86
627
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-client/src/main/java/org/apache/hugegraph/pd/client/Channels.java
Channels
getChannel
class Channels { private static final ConcurrentHashMap<String, ManagedChannel> chs = new ConcurrentHashMap<>(); public static ManagedChannel getChannel(String target) {<FILL_FUNCTION_BODY>} }
ManagedChannel channel; if ((channel = chs.get(target)) == null || channel.isShutdown() || channel.isTerminated()) { synchronized (chs) { if ((channel = chs.get(target)) == null || channel.isShutdown() || channel.isTerminated()) { channel = ManagedChannelBuilder.forTarget(target).usePlaintext().build(); chs.put(target, channel); } } } return channel;
61
129
190
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-client/src/main/java/org/apache/hugegraph/pd/client/DiscoveryClient.java
DiscoveryClient
resetChannel
class DiscoveryClient implements Closeable, Discoverable { private final Timer timer = new Timer("serverHeartbeat", true); private final AtomicBoolean requireResetStub = new AtomicBoolean(false); protected int period; //心跳周期 LinkedList<String> pdAddresses = new LinkedList<>(); ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private volatile int currentIndex; // 当前在用pd地址位置 private int maxTime = 6; private ManagedChannel channel = null; private DiscoveryServiceGrpc.DiscoveryServiceBlockingStub registerStub; private DiscoveryServiceGrpc.DiscoveryServiceBlockingStub blockingStub; public DiscoveryClient(String centerAddress, int delay) { String[] addresses = centerAddress.split(","); for (int i = 0; i < addresses.length; i++) { String singleAddress = addresses[i]; if (singleAddress == null || singleAddress.length() <= 0) { continue; } pdAddresses.add(addresses[i]); } this.period = delay; if (maxTime < addresses.length) { maxTime = addresses.length; } } private <V, R> R tryWithTimes(Function<V, R> function, V v) { R r; Exception ex = null; for (int i = 0; i < maxTime; i++) { try { r = function.apply(v); return r; } catch (Exception e) { requireResetStub.set(true); resetStub(); ex = e; } } if (ex != null) { log.error("Try discovery method with error: {}", ex.getMessage()); } return null; } /*** * 按照pd列表重置stub */ private void resetStub() { String errLog = null; for (int i = currentIndex + 1; i <= pdAddresses.size() + currentIndex; i++) { currentIndex = i % pdAddresses.size(); String singleAddress = pdAddresses.get(currentIndex); try { if (requireResetStub.get()) { resetChannel(singleAddress); } errLog = null; break; } catch (Exception e) { requireResetStub.set(true); if (errLog == null) { errLog = e.getMessage(); } continue; } } if (errLog != null) { log.error(errLog); } } /*** * 按照某个pd的地址重置channel和stub * @param singleAddress * @throws PDException */ private void resetChannel(String singleAddress) throws PDException {<FILL_FUNCTION_BODY>} /*** * 获取注册节点信息 * @param query * @return */ @Override public NodeInfos getNodeInfos(Query query) { return tryWithTimes((q) -> { this.readWriteLock.readLock().lock(); NodeInfos nodes; try { nodes = this.blockingStub.getNodes(q); } catch (Exception e) { throw e; } finally { this.readWriteLock.readLock().unlock(); } return nodes; }, query); } /*** * 启动心跳任务 */ @Override public void scheduleTask() { timer.schedule(new TimerTask() { @Override public void run() { NodeInfo nodeInfo = getRegisterNode(); tryWithTimes((t) -> { RegisterInfo register; readWriteLock.readLock().lock(); try { register = registerStub.register(t); log.debug("Discovery Client work done."); Consumer<RegisterInfo> consumer = getRegisterConsumer(); if (consumer != null) { consumer.accept(register); } } catch (Exception e) { throw e; } finally { readWriteLock.readLock().unlock(); } return register; }, nodeInfo); } }, 0, period); } abstract NodeInfo getRegisterNode(); abstract Consumer<RegisterInfo> getRegisterConsumer(); @Override public void cancelTask() { this.timer.cancel(); } @Override public void close() { this.timer.cancel(); readWriteLock.writeLock().lock(); try { while (channel != null && !channel.shutdownNow().awaitTermination( 100, TimeUnit.MILLISECONDS)) { continue; } } catch (Exception e) { log.info("Close channel with error : {}.", e); } finally { readWriteLock.writeLock().unlock(); } } }
readWriteLock.writeLock().lock(); try { if (requireResetStub.get()) { while (channel != null && !channel.shutdownNow().awaitTermination( 100, TimeUnit.MILLISECONDS)) { continue; } channel = ManagedChannelBuilder.forTarget( singleAddress).usePlaintext().build(); this.registerStub = DiscoveryServiceGrpc.newBlockingStub( channel); this.blockingStub = DiscoveryServiceGrpc.newBlockingStub( channel); requireResetStub.set(false); } } catch (Exception e) { throw new PDException(-1, String.format( "Reset channel with error : %s.", e.getMessage())); } finally { readWriteLock.writeLock().unlock(); }
1,275
219
1,494
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-client/src/main/java/org/apache/hugegraph/pd/client/LicenseClient.java
LicenseClient
putLicense
class LicenseClient extends AbstractClient { public LicenseClient(PDConfig config) { super(config); } @Override protected AbstractStub createStub() { return PDGrpc.newStub(channel); } @Override protected AbstractBlockingStub createBlockingStub() { return PDGrpc.newBlockingStub(channel); } public Pdpb.PutLicenseResponse putLicense(byte[] content) {<FILL_FUNCTION_BODY>} }
Pdpb.PutLicenseRequest request = Pdpb.PutLicenseRequest.newBuilder() .setContent( ByteString.copyFrom(content)) .build(); try { KVPair<Boolean, Pdpb.PutLicenseResponse> pair = concurrentBlockingUnaryCall( PDGrpc.getPutLicenseMethod(), request, (rs) -> rs.getHeader().getError().getType().equals(Pdpb.ErrorType.OK)); if (pair.getKey()) { Pdpb.PutLicenseResponse.Builder builder = Pdpb.PutLicenseResponse.newBuilder(); builder.setHeader(okHeader); return builder.build(); } else { return pair.getValue(); } } catch (Exception e) { e.printStackTrace(); log.debug("put license with error:{} ", e); Pdpb.ResponseHeader rh = newErrorHeader(Pdpb.ErrorType.LICENSE_ERROR_VALUE, e.getMessage()); return Pdpb.PutLicenseResponse.newBuilder().setHeader(rh).build(); }
134
279
413
<methods>public void close() ,public static org.apache.hugegraph.pd.grpc.Pdpb.ResponseHeader newErrorHeader(int, java.lang.String) <variables>protected ManagedChannel channel,private static final ConcurrentHashMap<java.lang.String,ManagedChannel> chs,protected final non-sealed org.apache.hugegraph.pd.client.PDConfig config,protected final non-sealed org.apache.hugegraph.pd.grpc.Pdpb.RequestHeader header,public static org.apache.hugegraph.pd.grpc.Pdpb.ResponseHeader okHeader,protected final non-sealed org.apache.hugegraph.pd.client.AbstractClientStubProxy stubProxy,protected volatile ConcurrentMap<java.lang.String,AbstractBlockingStub> stubs
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-client/src/main/java/org/apache/hugegraph/pd/client/PDConfig.java
PDConfig
toString
class PDConfig { //TODO multi-server private String serverHost = "localhost:9000"; private long grpcTimeOut = 60000; // grpc调用超时时间 10秒 // 是否接收PD异步通知 private boolean enablePDNotify = false; private boolean enableCache = false; private PDConfig() { } public static PDConfig of() { return new PDConfig(); } public static PDConfig of(String serverHost) { PDConfig config = new PDConfig(); config.serverHost = serverHost; return config; } public static PDConfig of(String serverHost, long timeOut) { PDConfig config = new PDConfig(); config.serverHost = serverHost; config.grpcTimeOut = timeOut; return config; } public String getServerHost() { return serverHost; } public long getGrpcTimeOut() { return grpcTimeOut; } @Deprecated public PDConfig setEnablePDNotify(boolean enablePDNotify) { this.enablePDNotify = enablePDNotify; // TODO 临时代码,hugegraph修改完后删除 this.enableCache = enablePDNotify; return this; } public boolean isEnableCache() { return enableCache; } public PDConfig setEnableCache(boolean enableCache) { this.enableCache = enableCache; return this; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "PDConfig{" + "serverHost='" + serverHost + '\'' + '}';
431
30
461
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-client/src/main/java/org/apache/hugegraph/pd/client/PDPulseImpl.java
AbstractConnector
ackNotice
class AbstractConnector<N, L> implements Notifier<N>, StreamObserver<PulseResponse> { Listener<L> listener; StreamObserver<PulseRequest> reqStream; PulseType pulseType; PulseRequest.Builder reqBuilder = PulseRequest.newBuilder(); PulseAckRequest.Builder ackBuilder = PulseAckRequest.newBuilder(); private AbstractConnector(Listener<L> listener, PulseType pulseType) { this.listener = listener; this.pulseType = pulseType; this.init(); } void init() { PulseCreateRequest.Builder builder = PulseCreateRequest.newBuilder() .setPulseType(this.pulseType); this.reqStream = PDPulseImpl.this.stub.pulse(this); this.reqStream.onNext(reqBuilder.clear().setCreateRequest(builder).build()); } /*** notifier ***/ @Override public void close() { this.reqStream.onCompleted(); } @Override public abstract void notifyServer(N t); @Override public void crash(String error) { this.reqStream.onError(new Throwable(error)); } /*** listener ***/ @Override public abstract void onNext(PulseResponse pulseResponse); @Override public void onError(Throwable throwable) { this.listener.onError(throwable); } @Override public void onCompleted() { this.listener.onCompleted(); } protected void ackNotice(long noticeId, long observerId) {<FILL_FUNCTION_BODY>} }
threadPool.execute(() -> { // log.info("send ack: {}, ts: {}", noticeId, System.currentTimeMillis()); this.reqStream.onNext(reqBuilder.clear() .setAckRequest( this.ackBuilder.clear() .setNoticeId(noticeId) .setObserverId(observerId) .build() ).build() ); });
443
113
556
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-client/src/main/java/org/apache/hugegraph/pd/client/PDWatchImpl.java
PartitionWatcher
onNext
class PartitionWatcher extends AbstractWatcher<PartitionEvent> { private PartitionWatcher(Listener listener) { super(listener, () -> WatchCreateRequest .newBuilder() .setWatchType(WatchType.WATCH_TYPE_PARTITION_CHANGE) .build() ); } @Override public void onNext(WatchResponse watchResponse) {<FILL_FUNCTION_BODY>} }
WatchPartitionResponse res = watchResponse.getPartitionResponse(); PartitionEvent event = new PartitionEvent(res.getGraph(), res.getPartitionId(), PartitionEvent.ChangeType.grpcTypeOf( res.getChangeType())); this.listener.onNext(event);
117
76
193
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-client/src/main/java/org/apache/hugegraph/pd/watch/NodeEvent.java
NodeEvent
equals
class NodeEvent { private final String graph; private final long nodeId; private final EventType eventType; public NodeEvent(String graph, long nodeId, EventType eventType) { this.graph = graph; this.nodeId = nodeId; this.eventType = eventType; } public String getGraph() { return graph; } public long getNodeId() { return nodeId; } public EventType getEventType() { return eventType; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(graph, nodeId, eventType); } @Override public String toString() { return "NodeEvent{" + "graph='" + graph + '\'' + ", nodeId=" + nodeId + ", eventType=" + eventType + '}'; } public enum EventType { UNKNOWN, NODE_ONLINE, NODE_OFFLINE, NODE_RAFT_CHANGE, NODE_PD_LEADER_CHANGE; public static EventType grpcTypeOf(NodeEventType grpcType) { switch (grpcType) { case NODE_EVENT_TYPE_NODE_ONLINE: return NODE_ONLINE; case NODE_EVENT_TYPE_NODE_OFFLINE: return NODE_OFFLINE; case NODE_EVENT_TYPE_NODE_RAFT_CHANGE: return NODE_RAFT_CHANGE; case NODE_EVENT_TYPE_PD_LEADER_CHANGE: return NODE_PD_LEADER_CHANGE; default: return UNKNOWN; } } } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NodeEvent nodeEvent = (NodeEvent) o; return nodeId == nodeEvent.nodeId && Objects.equals(graph, nodeEvent.graph) && eventType == nodeEvent.eventType;
481
99
580
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-client/src/main/java/org/apache/hugegraph/pd/watch/PartitionEvent.java
PartitionEvent
grpcTypeOf
class PartitionEvent { private final String graph; private final int partitionId; private final ChangeType changeType; public PartitionEvent(String graph, int partitionId, ChangeType changeType) { this.graph = graph; this.partitionId = partitionId; this.changeType = changeType; } public String getGraph() { return this.graph; } public int getPartitionId() { return this.partitionId; } public ChangeType getChangeType() { return this.changeType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PartitionEvent that = (PartitionEvent) o; return partitionId == that.partitionId && Objects.equals(graph, that.graph) && changeType == that.changeType; } @Override public int hashCode() { return Objects.hash(graph, partitionId, changeType); } @Override public String toString() { return "PartitionEvent{" + "graph='" + graph + '\'' + ", partitionId=" + partitionId + ", changeType=" + changeType + '}'; } public enum ChangeType { UNKNOWN, ADD, ALTER, DEL; public static ChangeType grpcTypeOf(WatchChangeType grpcType) {<FILL_FUNCTION_BODY>} } }
switch (grpcType) { case WATCH_CHANGE_TYPE_ADD: return ADD; case WATCH_CHANGE_TYPE_ALTER: return ALTER; case WATCH_CHANGE_TYPE_DEL: return DEL; default: return UNKNOWN; }
414
84
498
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-common/src/main/java/org/apache/hugegraph/pd/common/HgAssert.java
HgAssert
isContains
class HgAssert { public static void isTrue(boolean expression, String message) { if (message == null) { throw new IllegalArgumentException("message is null"); } if (!expression) { throw new IllegalArgumentException(message); } } public static void isFalse(boolean expression, String message) { isTrue(!expression, message); } public static void isArgumentValid(byte[] bytes, String parameter) { isFalse(isInvalid(bytes), "The argument is invalid: " + parameter); } public static void isArgumentValid(String str, String parameter) { isFalse(isInvalid(str), "The argument is invalid: " + parameter); } public static void isArgumentNotNull(Object obj, String parameter) { isTrue(obj != null, "The argument is null: " + parameter); } public static void istValid(byte[] bytes, String msg) { isFalse(isInvalid(bytes), msg); } public static void isValid(String str, String msg) { isFalse(isInvalid(str), msg); } public static void isNotNull(Object obj, String msg) { isTrue(obj != null, msg); } public static boolean isContains(Object[] objs, Object obj) { if (objs == null || objs.length == 0 || obj == null) { return false; } for (Object item : objs) { if (obj.equals(item)) { return true; } } return false; } public static boolean isInvalid(String... strs) { if (strs == null || strs.length == 0) { return true; } for (String item : strs) { if (item == null || "".equals(item.trim())) { return true; } } return false; } public static boolean isInvalid(byte[] bytes) { return bytes == null || bytes.length == 0; } public static boolean isInvalid(Map<?, ?> map) { return map == null || map.isEmpty(); } public static boolean isInvalid(Collection<?> list) { return list == null || list.isEmpty(); } public static <T> boolean isContains(Collection<T> list, T item) {<FILL_FUNCTION_BODY>} public static boolean isNull(Object... objs) { if (objs == null) { return true; } for (Object item : objs) { if (item == null) { return true; } } return false; } }
if (list == null || item == null) { return false; } return list.contains(item);
686
33
719
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-common/src/main/java/org/apache/hugegraph/pd/common/KVPair.java
KVPair
hashCode
class KVPair<K, V> implements Serializable { /** * Key of this <code>Pair</code>. */ private K key; /** * Value of this this <code>Pair</code>. */ private V value; /** * Creates a new pair * * @param key The key for this pair * @param value The value to use for this pair */ public KVPair(K key, V value) { this.key = key; this.value = value; } /** * Gets the key for this pair. * * @return key for this pair */ public K getKey() { return key; } public void setKey(K key) { this.key = key; } /** * Gets the value for this pair. * * @return value for this pair */ public V getValue() { return value; } public void setValue(V value) { this.value = value; } /** * <p><code>String</code> representation of this * <code>Pair</code>.</p> * * <p>The default name/value delimiter '=' is always used.</p> * * @return <code>String</code> representation of this <code>Pair</code> */ @Override public String toString() { return key + "=" + value; } /** * <p>Generate a hash code for this <code>Pair</code>.</p> * * <p>The hash code is calculated using both the name and * the value of the <code>Pair</code>.</p> * * @return hash code for this <code>Pair</code> */ @Override public int hashCode() {<FILL_FUNCTION_BODY>} /** * <p>Test this <code>Pair</code> for equality with another * <code>Object</code>.</p> * * <p>If the <code>Object</code> to be tested is not a * <code>Pair</code> or is <code>null</code>, then this method * returns <code>false</code>.</p> * * <p>Two <code>Pair</code>s are considered equal if and only if * both the names and values are equal.</p> * * @param o the <code>Object</code> to test for * equality with this <code>Pair</code> * @return <code>true</code> if the given <code>Object</code> is * equal to this <code>Pair</code> else <code>false</code> */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof KVPair) { KVPair pair = (KVPair) o; if (!Objects.equals(key, pair.key)) { return false; } return Objects.equals(value, pair.value); } return false; } }
// name's hashCode is multiplied by an arbitrary prime number (13) // in order to make sure there is a difference in the hashCode between // these two parameters: // name: a value: aa // name: aa value: a return key.hashCode() * 13 + (value == null ? 0 : value.hashCode());
859
96
955
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-common/src/main/java/org/apache/hugegraph/pd/common/PartitionUtils.java
PartitionUtils
calcHashcode
class PartitionUtils { public static final int MAX_VALUE = 0xffff; /** * 计算key的hashcode * * @param key * @return hashcode */ public static int calcHashcode(byte[] key) {<FILL_FUNCTION_BODY>} }
final int p = 16777619; int hash = (int) 2166136261L; for (byte element : key) { hash = (hash ^ element) * p; } hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; hash = hash & PartitionUtils.MAX_VALUE; if (hash == PartitionUtils.MAX_VALUE) { hash = PartitionUtils.MAX_VALUE - 1; } return hash;
81
162
243
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/ConfigService.java
ConfigService
loadConfig
class ConfigService implements RaftStateListener { private final ConfigMetaStore meta; private PDConfig pdConfig; public ConfigService(PDConfig config) { this.pdConfig = config; config.setConfigService(this); meta = MetadataFactory.newConfigMeta(config); } public Metapb.PDConfig getPDConfig(long version) throws PDException { return this.meta.getPdConfig(version); } public Metapb.PDConfig getPDConfig() throws PDException { return this.meta.getPdConfig(0); } public Metapb.PDConfig setPDConfig(Metapb.PDConfig mConfig) throws PDException { Metapb.PDConfig oldCfg = getPDConfig(); Metapb.PDConfig.Builder builder = oldCfg.toBuilder().mergeFrom(mConfig) .setVersion(oldCfg.getVersion() + 1) .setTimestamp(System.currentTimeMillis()); mConfig = this.meta.setPdConfig(builder.build()); log.info("PDConfig has been modified, new PDConfig is {}", mConfig); updatePDConfig(mConfig); return mConfig; } public List<Metapb.GraphSpace> getGraphSpace(String graphSpaceName) throws PDException { return this.meta.getGraphSpace(graphSpaceName); } public Metapb.GraphSpace setGraphSpace(Metapb.GraphSpace graphSpace) throws PDException { return this.meta.setGraphSpace(graphSpace.toBuilder() .setTimestamp(System.currentTimeMillis()) .build()); } /** * 从存储中读取配置项,并覆盖全局的PDConfig对象 * * @return */ public PDConfig loadConfig() {<FILL_FUNCTION_BODY>} public synchronized PDConfig updatePDConfig(Metapb.PDConfig mConfig) { log.info("update pd config: mConfig:{}", mConfig); pdConfig.getPartition().setShardCount(mConfig.getShardCount()); pdConfig.getPartition().setTotalCount(mConfig.getPartitionCount()); pdConfig.getPartition().setMaxShardsPerStore(mConfig.getMaxShardsPerStore()); return pdConfig; } public synchronized PDConfig setPartitionCount(int count) { Metapb.PDConfig mConfig = null; try { mConfig = getPDConfig(); mConfig = mConfig.toBuilder().setPartitionCount(count).build(); setPDConfig(mConfig); } catch (PDException e) { log.error("ConfigService exception {}", e); e.printStackTrace(); } return pdConfig; } /** * meta store中的数量 * 由于可能会受分区分裂/合并的影响,原始的partition count不推荐使用 * * @return partition count of cluster * @throws PDException when io error */ public int getPartitionCount() throws PDException { return getPDConfig().getPartitionCount(); } @Override public void onRaftLeaderChanged() { loadConfig(); } }
try { Metapb.PDConfig mConfig = this.meta.getPdConfig(0); if (mConfig == null) { mConfig = Metapb.PDConfig.newBuilder() .setPartitionCount(pdConfig.getInitialPartitionCount()) .setShardCount(pdConfig.getPartition().getShardCount()) .setVersion(1) .setTimestamp(System.currentTimeMillis()) .setMaxShardsPerStore( pdConfig.getPartition().getMaxShardsPerStore()) .build(); } if (RaftEngine.getInstance().isLeader()) { this.meta.setPdConfig(mConfig); } pdConfig = updatePDConfig(mConfig); } catch (Exception e) { log.error("ConfigService loadConfig exception {}", e); } return pdConfig;
830
223
1,053
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/LogService.java
LogService
insertLog
class LogService { public static final String GRPC = "GRPC"; public static final String REST = "REST"; public static final String TASK = "TASK"; public static final String NODE_CHANGE = "NODE_CHANGE"; public static final String PARTITION_CHANGE = "PARTITION_CHANGE"; private final LogMeta logMeta; public LogService(PDConfig pdConfig) { logMeta = MetadataFactory.newLogMeta(pdConfig); } public List<Metapb.LogRecord> getLog(String action, Long start, Long end) throws PDException { return logMeta.getLog(action, start, end); } public void insertLog(String action, String message, GeneratedMessageV3 target) {<FILL_FUNCTION_BODY>} }
try { Metapb.LogRecord logRecord = Metapb.LogRecord.newBuilder() .setAction(action) .setMessage(message) .setTimestamp(System.currentTimeMillis()) .setObject(Any.pack(target)) .build(); logMeta.insertLog(logRecord); } catch (PDException e) { log.debug("Insert log with error:{}", e); }
208
119
327
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/config/PDConfig.java
PDConfig
getInitialStoreMap
class PDConfig { @Value("${pd.cluster_id:1}") private long clusterId; // 集群ID @Value("${pd.patrol-interval:300}") private long patrolInterval = 300; //巡查任务时间间隔 @Value("${pd.data-path}") private String dataPath; @Value("${pd.initial-store-count:3}") private int minStoreCount; // 初始store列表,该列表内的store自动激活 @Value("${pd.initial-store-list: ''}") private String initialStoreList; @Value("${grpc.host}") private String host; @Value("${license.verify-path}") private String verifyPath; @Value("${license.license-path}") private String licensePath; @Autowired private ThreadPoolGrpc threadPoolGrpc; @Autowired private Raft raft; @Autowired private Store store; @Autowired private Partition partition; @Autowired private Discovery discovery; private Map<String, String> initialStoreMap = null; private ConfigService configService; private IdService idService; public Map<String, String> getInitialStoreMap() {<FILL_FUNCTION_BODY>} /** * 初始分区数量 * Store数量 * 每Store最大副本数 /每分区副本数 * * @return */ public int getInitialPartitionCount() { return getInitialStoreMap().size() * partition.getMaxShardsPerStore() / partition.getShardCount(); } public ConfigService getConfigService() { return configService; } public void setConfigService(ConfigService configService) { this.configService = configService; } public IdService getIdService() { return idService; } public void setIdService(IdService idService) { this.idService = idService; } @Data @Configuration public class ThreadPoolGrpc { @Value("${thread.pool.grpc.core:600}") private int core; @Value("${thread.pool.grpc.max:1000}") private int max; @Value("${thread.pool.grpc.queue:" + Integer.MAX_VALUE + "}") private int queue; } @Data @Configuration public class Raft { @Value("${raft.enable:true }") private boolean enable; @Value("${raft.address}") private String address; @Value("${pd.data-path}") private String dataPath; @Value("${raft.peers-list}") private String peersList; @Value("${raft.snapshotInterval: 300}") private int snapshotInterval; @Value("${raft.rpc-timeout:10000}") private int rpcTimeout; @Value("${grpc.host}") private String host; @Value("${server.port}") private int port; @Value("${pd.cluster_id:1}") private long clusterId; // 集群ID @Value("${grpc.port}") private int grpcPort; public String getGrpcAddress() { return host + ":" + grpcPort; } } @Data @Configuration public class Store { // store 心跳超时时间 @Value("${store.keepAlive-timeout:300}") private long keepAliveTimeout = 300; @Value("${store.max-down-time:1800}") private long maxDownTime = 1800; @Value("${store.monitor_data_enabled:true}") private boolean monitorDataEnabled = true; @Value("${store.monitor_data_interval: 1 minute}") private String monitorDataInterval = "1 minute"; @Value("${store.monitor_data_retention: 1 day}") private String monitorDataRetention = "1 day"; /** * interval -> seconds. * minimum value is 1 seconds. * * @return the seconds of the interval */ public Long getMonitorInterval() { return parseTimeExpression(this.monitorDataInterval); } /** * the monitor data that saved in rocksdb, will be deleted * out of period * * @return the period of the monitor data should keep */ public Long getRetentionPeriod() { return parseTimeExpression(this.monitorDataRetention); } /** * parse time expression , support pattern: * [1-9][ ](second, minute, hour, day, month, year) * unit could not be null, the number part is 1 by default. * * @param exp * @return seconds value of the expression. 1 will return by illegal expression */ private Long parseTimeExpression(String exp) { if (exp != null) { Pattern pattern = Pattern.compile( "(?<n>(\\d+)*)(\\s)*(?<unit>(second|minute|hour|day|month|year)$)"); Matcher matcher = pattern.matcher(exp.trim()); if (matcher.find()) { String n = matcher.group("n"); String unit = matcher.group("unit"); if (null == n || n.length() == 0) { n = "1"; } Long interval; switch (unit) { case "minute": interval = 60L; break; case "hour": interval = 3600L; break; case "day": interval = 86400L; break; case "month": interval = 86400L * 30; break; case "year": interval = 86400L * 365; break; case "second": default: interval = 1L; } // avoid n == '0' return Math.max(1L, interval * Integer.parseInt(n)); } } return 1L; } } @Data @Configuration public class Partition { private int totalCount = 0; // 每个Store最大副本数 @Value("${partition.store-max-shard-count:24}") private int maxShardsPerStore = 24; // 默认分副本数量 @Value("${partition.default-shard-count:3}") private int shardCount = 3; public int getTotalCount() { if (totalCount == 0) { totalCount = getInitialPartitionCount(); } return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } } @Data @Configuration public class Discovery { // 客户端注册后,无心跳最长次数,超过后,之前的注册信息会被删除 @Value("${discovery.heartbeat-try-count:3}") private int heartbeatOutTimes = 3; } }
if (initialStoreMap == null) { initialStoreMap = new HashMap<>(); Arrays.asList(initialStoreList.split(",")).forEach(s -> { initialStoreMap.put(s, s); }); } return initialStoreMap;
1,936
73
2,009
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/meta/ConfigMetaStore.java
ConfigMetaStore
setPdConfig
class ConfigMetaStore extends MetadataRocksDBStore { private final long clusterId; public ConfigMetaStore(PDConfig pdConfig) { super(pdConfig); this.clusterId = pdConfig.getClusterId(); } /** * 更新图空间存储状态信息 * * @param */ public Metapb.GraphSpace setGraphSpace(Metapb.GraphSpace graphSpace) throws PDException { byte[] graphSpaceKey = MetadataKeyHelper.getGraphSpaceKey(graphSpace.getName()); graphSpace = graphSpace.toBuilder().setTimestamp(System.currentTimeMillis()).build(); put(graphSpaceKey, graphSpace.toByteArray()); return graphSpace; } public List<Metapb.GraphSpace> getGraphSpace(String graphSpace) throws PDException { byte[] graphSpaceKey = MetadataKeyHelper.getGraphSpaceKey(graphSpace); return scanPrefix(Metapb.GraphSpace.parser(), graphSpaceKey); } public Metapb.PDConfig setPdConfig(Metapb.PDConfig pdConfig) throws PDException {<FILL_FUNCTION_BODY>} public Metapb.PDConfig getPdConfig(long version) throws PDException { byte[] graphSpaceKey = MetadataKeyHelper.getPdConfigKey(version <= 0 ? null : String.valueOf(version)); Optional<Metapb.PDConfig> max = scanPrefix( Metapb.PDConfig.parser(), graphSpaceKey).stream().max( (o1, o2) -> (o1.getVersion() > o2.getVersion()) ? 1 : -1); return max.isPresent() ? max.get() : null; } }
byte[] graphSpaceKey = MetadataKeyHelper.getPdConfigKey(String.valueOf(pdConfig.getVersion())); Metapb.PDConfig config = Metapb.PDConfig.newBuilder( pdConfig).setTimestamp(System.currentTimeMillis()).build(); put(graphSpaceKey, config.toByteArray()); return config;
443
92
535
<methods>public void <init>(org.apache.hugegraph.pd.config.PDConfig) ,public void clearAllCache() throws org.apache.hugegraph.pd.common.PDException,public void close() ,public boolean containsKey(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List#RAW getListWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public byte[] getOne(byte[]) throws org.apache.hugegraph.pd.common.PDException,public E getOne(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public org.apache.hugegraph.pd.store.HgKVStore getStore() ,public byte[] getWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void put(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long, java.util.concurrent.TimeUnit) throws org.apache.hugegraph.pd.common.PDException,public long remove(byte[]) throws org.apache.hugegraph.pd.common.PDException,public long removeByPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void removeWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanPrefix(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanRange(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanRange(Parser<E>, byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException<variables>org.apache.hugegraph.pd.config.PDConfig pdConfig,org.apache.hugegraph.pd.store.HgKVStore store
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/meta/DiscoveryMetaStore.java
DiscoveryMetaStore
getNodes
class DiscoveryMetaStore extends MetadataRocksDBStore { /** * appName --> address --> registryInfo */ private static final String PREFIX = "REGIS-"; private static final String SPLITTER = "-"; public DiscoveryMetaStore(PDConfig pdConfig) { super(pdConfig); } public void register(NodeInfo nodeInfo, int outTimes) throws PDException { putWithTTL(toKey(nodeInfo.getAppName(), nodeInfo.getVersion(), nodeInfo.getAddress()), nodeInfo.toByteArray(), (nodeInfo.getInterval() / 1000) * outTimes); } byte[] toKey(String appName, String version, String address) { StringBuilder builder = getPrefixBuilder(appName, version); builder.append(SPLITTER); builder.append(address); return builder.toString().getBytes(); } private StringBuilder getPrefixBuilder(String appName, String version) { StringBuilder builder = new StringBuilder(); builder.append(PREFIX); if (!StringUtils.isEmpty(appName)) { builder.append(appName); builder.append(SPLITTER); } if (!StringUtils.isEmpty(version)) { builder.append(version); } return builder; } public NodeInfos getNodes(Query query) {<FILL_FUNCTION_BODY>} private boolean labelMatch(NodeInfo node, Query query) { Map<String, String> labelsMap = node.getLabelsMap(); for (Map.Entry<String, String> entry : query.getLabelsMap().entrySet()) { if (!entry.getValue().equals(labelsMap.get(entry.getKey()))) { return false; } } return true; } }
List<NodeInfo> nodeInfos = null; try { StringBuilder builder = getPrefixBuilder(query.getAppName(), query.getVersion()); nodeInfos = getInstanceListWithTTL( NodeInfo.parser(), builder.toString().getBytes()); builder.setLength(0); } catch (PDException e) { log.error("An error occurred getting data from the store,{}", e); } if (query.getLabelsMap() != null && !query.getLabelsMap().isEmpty()) { List result = new LinkedList<NodeInfo>(); for (NodeInfo node : nodeInfos) { if (labelMatch(node, query)) { result.add(node); } } return NodeInfos.newBuilder().addAllInfo(result).build(); } return NodeInfos.newBuilder().addAllInfo(nodeInfos).build();
465
234
699
<methods>public void <init>(org.apache.hugegraph.pd.config.PDConfig) ,public void clearAllCache() throws org.apache.hugegraph.pd.common.PDException,public void close() ,public boolean containsKey(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List#RAW getListWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public byte[] getOne(byte[]) throws org.apache.hugegraph.pd.common.PDException,public E getOne(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public org.apache.hugegraph.pd.store.HgKVStore getStore() ,public byte[] getWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void put(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long, java.util.concurrent.TimeUnit) throws org.apache.hugegraph.pd.common.PDException,public long remove(byte[]) throws org.apache.hugegraph.pd.common.PDException,public long removeByPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void removeWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanPrefix(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanRange(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanRange(Parser<E>, byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException<variables>org.apache.hugegraph.pd.config.PDConfig pdConfig,org.apache.hugegraph.pd.store.HgKVStore store
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/meta/LogMeta.java
LogMeta
getLog
class LogMeta extends MetadataRocksDBStore { private final PDConfig pdConfig; public LogMeta(PDConfig pdConfig) { super(pdConfig); this.pdConfig = pdConfig; } public void insertLog(Metapb.LogRecord record) throws PDException { byte[] storeLogKey = MetadataKeyHelper.getLogKey(record); put(storeLogKey, record.toByteArray()); } public List<Metapb.LogRecord> getLog(String action, Long start, Long end) throws PDException {<FILL_FUNCTION_BODY>} }
byte[] keyStart = MetadataKeyHelper.getLogKeyPrefix(action, start); byte[] keyEnd = MetadataKeyHelper.getLogKeyPrefix(action, end); List<Metapb.LogRecord> stores = this.scanRange(Metapb.LogRecord.parser(), keyStart, keyEnd); return stores;
161
86
247
<methods>public void <init>(org.apache.hugegraph.pd.config.PDConfig) ,public void clearAllCache() throws org.apache.hugegraph.pd.common.PDException,public void close() ,public boolean containsKey(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List#RAW getListWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public byte[] getOne(byte[]) throws org.apache.hugegraph.pd.common.PDException,public E getOne(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public org.apache.hugegraph.pd.store.HgKVStore getStore() ,public byte[] getWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void put(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long, java.util.concurrent.TimeUnit) throws org.apache.hugegraph.pd.common.PDException,public long remove(byte[]) throws org.apache.hugegraph.pd.common.PDException,public long removeByPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void removeWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanPrefix(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanRange(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanRange(Parser<E>, byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException<variables>org.apache.hugegraph.pd.config.PDConfig pdConfig,org.apache.hugegraph.pd.store.HgKVStore store
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/meta/MetadataFactory.java
MetadataFactory
getStore
class MetadataFactory { private static HgKVStore store = null; public static HgKVStore getStore(PDConfig pdConfig) {<FILL_FUNCTION_BODY>} public static void closeStore() { if (store != null) { store.close(); } } public static StoreInfoMeta newStoreInfoMeta(PDConfig pdConfig) { return new StoreInfoMeta(pdConfig); } public static PartitionMeta newPartitionMeta(PDConfig pdConfig) { return new PartitionMeta(pdConfig); } public static IdMetaStore newHugeServerMeta(PDConfig pdConfig) { return new IdMetaStore(pdConfig); } public static DiscoveryMetaStore newDiscoveryMeta(PDConfig pdConfig) { return new DiscoveryMetaStore(pdConfig); } public static ConfigMetaStore newConfigMeta(PDConfig pdConfig) { return new ConfigMetaStore(pdConfig); } public static TaskInfoMeta newTaskInfoMeta(PDConfig pdConfig) { return new TaskInfoMeta(pdConfig); } public static QueueStore newQueueStore(PDConfig pdConfig) { return new QueueStore(pdConfig); } public static LogMeta newLogMeta(PDConfig pdConfig) { return new LogMeta(pdConfig); } }
if (store == null) { synchronized (MetadataFactory.class) { if (store == null) { HgKVStore proto = new HgKVStoreImpl(); //proto.init(pdConfig); store = pdConfig.getRaft().isEnable() ? new RaftKVStore(RaftEngine.getInstance(), proto) : proto; store.init(pdConfig); } } } return store;
355
120
475
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/meta/MetadataRocksDBStore.java
MetadataRocksDBStore
remove
class MetadataRocksDBStore extends MetadataStoreBase { HgKVStore store; PDConfig pdConfig; public MetadataRocksDBStore(PDConfig pdConfig) { store = MetadataFactory.getStore(pdConfig); this.pdConfig = pdConfig; } public HgKVStore getStore() { if (store == null) { store = MetadataFactory.getStore(pdConfig); } return store; } @Override public byte[] getOne(byte[] key) throws PDException { try { byte[] bytes = store.get(key); return bytes; } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_READ_ERROR_VALUE, e); } } @Override public <E> E getOne(Parser<E> parser, byte[] key) throws PDException { try { byte[] bytes = store.get(key); if (ArrayUtils.isEmpty(bytes)) { return null; } return parser.parseFrom(bytes); } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_READ_ERROR_VALUE, e); } } @Override public void put(byte[] key, byte[] value) throws PDException { try { getStore().put(key, value); } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_WRITE_ERROR_VALUE, e); } } @Override public void putWithTTL(byte[] key, byte[] value, long ttl) throws PDException { this.store.putWithTTL(key, value, ttl); } @Override public void putWithTTL(byte[] key, byte[] value, long ttl, TimeUnit timeUnit) throws PDException { this.store.putWithTTL(key, value, ttl, timeUnit); } @Override public byte[] getWithTTL(byte[] key) throws PDException { return this.store.getWithTTL(key); } @Override public List getListWithTTL(byte[] key) throws PDException { return this.store.getListWithTTL(key); } @Override public void removeWithTTL(byte[] key) throws PDException { this.store.removeWithTTL(key); } @Override public List<KV> scanPrefix(byte[] prefix) throws PDException { //TODO 使用rocksdb 前缀查询 try { return this.store.scanPrefix(prefix); } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_READ_ERROR_VALUE, e); } } @Override public List<KV> scanRange(byte[] start, byte[] end) throws PDException { return this.store.scanRange(start, end); } @Override public <E> List<E> scanRange(Parser<E> parser, byte[] start, byte[] end) throws PDException { List<E> stores = new LinkedList<>(); try { List<KV> kvs = this.scanRange(start, end); for (KV keyValue : kvs) { stores.add(parser.parseFrom(keyValue.getValue())); } } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_READ_ERROR_VALUE, e); } return stores; } @Override public <E> List<E> scanPrefix(Parser<E> parser, byte[] prefix) throws PDException { List<E> stores = new LinkedList<>(); try { List<KV> kvs = this.scanPrefix(prefix); for (KV keyValue : kvs) { stores.add(parser.parseFrom(keyValue.getValue())); } } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_READ_ERROR_VALUE, e); } return stores; } @Override public boolean containsKey(byte[] key) throws PDException { return !ArrayUtils.isEmpty(store.get(key)); } @Override public long remove(byte[] key) throws PDException {<FILL_FUNCTION_BODY>} @Override public long removeByPrefix(byte[] prefix) throws PDException { try { return this.store.removeByPrefix(prefix); } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_WRITE_ERROR_VALUE, e); } } @Override public void clearAllCache() throws PDException { this.store.clear(); } @Override public void close() { } }
try { return this.store.remove(key); } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_WRITE_ERROR_VALUE, e); }
1,299
59
1,358
<methods>public non-sealed void <init>() ,public abstract void clearAllCache() throws org.apache.hugegraph.pd.common.PDException,public abstract void close() throws java.io.IOException,public abstract boolean containsKey(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<T> getInstanceListWithTTL(Parser<T>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public T getInstanceWithTTL(Parser<T>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract List#RAW getListWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract byte[] getOne(byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract E getOne(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract byte[] getWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract void put(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract void putWithTTL(byte[], byte[], long) throws org.apache.hugegraph.pd.common.PDException,public abstract void putWithTTL(byte[], byte[], long, java.util.concurrent.TimeUnit) throws org.apache.hugegraph.pd.common.PDException,public abstract long remove(byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract long removeByPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract void removeWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract List<org.apache.hugegraph.pd.store.KV> scanPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract List<E> scanPrefix(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract List<org.apache.hugegraph.pd.store.KV> scanRange(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public abstract List<E> scanRange(Parser<E>, byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException<variables>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/meta/MetadataStoreBase.java
MetadataStoreBase
getInstanceListWithTTL
class MetadataStoreBase { // public long timeout = 3; // 请求超时时间,默认三秒 public abstract byte[] getOne(byte[] key) throws PDException; public abstract <E> E getOne(Parser<E> parser, byte[] key) throws PDException; public abstract void put(byte[] key, byte[] value) throws PDException; /** * 带有过期时间的put */ public abstract void putWithTTL(byte[] key, byte[] value, long ttl) throws PDException; public abstract void putWithTTL(byte[] key, byte[] value, long ttl, TimeUnit timeUnit) throws PDException; public abstract byte[] getWithTTL(byte[] key) throws PDException; public abstract List getListWithTTL(byte[] key) throws PDException; public abstract void removeWithTTL(byte[] key) throws PDException; /** * 前缀查询 * * @param prefix * @return * @throws PDException */ public abstract List<KV> scanPrefix(byte[] prefix) throws PDException; /** * 前缀查询 * * @param prefix * @return * @throws PDException */ public abstract <E> List<E> scanPrefix(Parser<E> parser, byte[] prefix) throws PDException; public abstract List<KV> scanRange(byte[] start, byte[] end) throws PDException; public abstract <E> List<E> scanRange(Parser<E> parser, byte[] start, byte[] end) throws PDException; /** * 检查Key是否存在 * * @param key * @return * @throws PDException */ public abstract boolean containsKey(byte[] key) throws PDException; public abstract long remove(byte[] key) throws PDException; public abstract long removeByPrefix(byte[] prefix) throws PDException; public abstract void clearAllCache() throws PDException; public abstract void close() throws IOException; public <T> T getInstanceWithTTL(Parser<T> parser, byte[] key) throws PDException { try { byte[] withTTL = this.getWithTTL(key); return parser.parseFrom(withTTL); } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_READ_ERROR_VALUE, e); } } public <T> List<T> getInstanceListWithTTL(Parser<T> parser, byte[] key) throws PDException {<FILL_FUNCTION_BODY>} }
try { List withTTL = this.getListWithTTL(key); LinkedList<T> ts = new LinkedList<>(); for (int i = 0; i < withTTL.size(); i++) { ts.add(parser.parseFrom((byte[]) withTTL.get(i))); } return ts; } catch (Exception e) { throw new PDException(Pdpb.ErrorType.ROCKSDB_READ_ERROR_VALUE, e); }
706
129
835
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/meta/QueueStore.java
QueueStore
removeItem
class QueueStore extends MetadataRocksDBStore { QueueStore(PDConfig pdConfig) { super(pdConfig); } public void addItem(Metapb.QueueItem queueItem) throws PDException { HgAssert.isArgumentNotNull(queueItem, "queueItem"); byte[] key = MetadataKeyHelper.getQueueItemKey(queueItem.getItemId()); put(key, queueItem.toByteString().toByteArray()); } public void removeItem(String itemId) throws PDException {<FILL_FUNCTION_BODY>} public List<Metapb.QueueItem> getQueue() throws PDException { byte[] prefix = MetadataKeyHelper.getQueueItemPrefix(); return scanPrefix(Metapb.QueueItem.parser(), prefix); } }
if (RaftEngine.getInstance().isLeader()) { remove(MetadataKeyHelper.getQueueItemKey(itemId)); } else { var store = getStore(); // todo: delete record via client if (store instanceof RaftKVStore) { ((RaftKVStore) store).doRemove(MetadataKeyHelper.getQueueItemKey(itemId)); } }
207
101
308
<methods>public void <init>(org.apache.hugegraph.pd.config.PDConfig) ,public void clearAllCache() throws org.apache.hugegraph.pd.common.PDException,public void close() ,public boolean containsKey(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List#RAW getListWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public byte[] getOne(byte[]) throws org.apache.hugegraph.pd.common.PDException,public E getOne(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public org.apache.hugegraph.pd.store.HgKVStore getStore() ,public byte[] getWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void put(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long, java.util.concurrent.TimeUnit) throws org.apache.hugegraph.pd.common.PDException,public long remove(byte[]) throws org.apache.hugegraph.pd.common.PDException,public long removeByPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void removeWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanPrefix(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanRange(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanRange(Parser<E>, byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException<variables>org.apache.hugegraph.pd.config.PDConfig pdConfig,org.apache.hugegraph.pd.store.HgKVStore store
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/meta/StoreInfoMeta.java
StoreInfoMeta
getStoreStats
class StoreInfoMeta extends MetadataRocksDBStore { private final PDConfig pdConfig; public StoreInfoMeta(PDConfig pdConfig) { super(pdConfig); this.pdConfig = pdConfig; // this.timeout = pdConfig.getDiscovery().getHeartbeatOutTimes(); } public static boolean shardGroupEquals(List<Metapb.Shard> g1, List<Metapb.Shard> g2) { ListIterator<Metapb.Shard> e1 = g1.listIterator(); ListIterator<Metapb.Shard> e2 = g2.listIterator(); while (e1.hasNext() && e2.hasNext()) { Metapb.Shard o1 = e1.next(); Metapb.Shard o2 = e2.next(); if (!(o1 == null ? o2 == null : o1.getStoreId() == o2.getStoreId())) { return false; } } return !(e1.hasNext() || e2.hasNext()); } /** * 更新Store信息 * * @param store * @throws PDException */ public void updateStore(Metapb.Store store) throws PDException { byte[] storeInfoKey = MetadataKeyHelper.getStoreInfoKey(store.getId()); put(storeInfoKey, store.toByteArray()); } /** * 更新Store的存活状态 * * @param store */ public void keepStoreAlive(Metapb.Store store) throws PDException { byte[] activeStoreKey = MetadataKeyHelper.getActiveStoreKey(store.getId()); putWithTTL(activeStoreKey, store.toByteArray(), pdConfig.getStore().getKeepAliveTimeout()); } public void removeActiveStore(Metapb.Store store) throws PDException { byte[] activeStoreKey = MetadataKeyHelper.getActiveStoreKey(store.getId()); removeWithTTL(activeStoreKey); } public Metapb.Store getStore(Long storeId) throws PDException { byte[] storeInfoKey = MetadataKeyHelper.getStoreInfoKey(storeId); Metapb.Store store = getOne(Metapb.Store.parser(), storeInfoKey); return store; } /** * 获取所有的store * * @param graphName * @return * @throws PDException */ public List<Metapb.Store> getStores(String graphName) throws PDException { byte[] storePrefix = MetadataKeyHelper.getStorePrefix(); return scanPrefix(Metapb.Store.parser(), storePrefix); } /** * 获取活跃的Store * * @param graphName * @return * @throws PDException */ public List<Metapb.Store> getActiveStores(String graphName) throws PDException { byte[] activePrefix = MetadataKeyHelper.getActiveStorePrefix(); List listWithTTL = getInstanceListWithTTL(Metapb.Store.parser(), activePrefix); return listWithTTL; } public List<Metapb.Store> getActiveStores() throws PDException { byte[] activePrefix = MetadataKeyHelper.getActiveStorePrefix(); List listWithTTL = getInstanceListWithTTL(Metapb.Store.parser(), activePrefix); return listWithTTL; } /** * 检查storeid是否存在 * * @param storeId * @return */ public boolean storeExists(Long storeId) throws PDException { byte[] storeInfoKey = MetadataKeyHelper.getStoreInfoKey(storeId); return containsKey(storeInfoKey); } /** * 更新存储状态信息 * * @param storeStats */ public Metapb.StoreStats updateStoreStats(Metapb.StoreStats storeStats) throws PDException { byte[] storeStatusKey = MetadataKeyHelper.getStoreStatusKey(storeStats.getStoreId()); put(storeStatusKey, storeStats.toByteArray()); return storeStats; } public long removeStore(long storeId) throws PDException { byte[] storeInfoKey = MetadataKeyHelper.getStoreInfoKey(storeId); return remove(storeInfoKey); } public long removeAll() throws PDException { byte[] storePrefix = MetadataKeyHelper.getStorePrefix(); return this.removeByPrefix(storePrefix); } public void updateShardGroup(Metapb.ShardGroup group) throws PDException { byte[] shardGroupKey = MetadataKeyHelper.getShardGroupKey(group.getId()); put(shardGroupKey, group.toByteArray()); } public void deleteShardGroup(int groupId) throws PDException { byte[] shardGroupKey = MetadataKeyHelper.getShardGroupKey(groupId); remove(shardGroupKey); } public Metapb.ShardGroup getShardGroup(int groupId) throws PDException { byte[] shardGroupKey = MetadataKeyHelper.getShardGroupKey(groupId); return getOne(Metapb.ShardGroup.parser(), shardGroupKey); } public int getShardGroupCount() throws PDException { byte[] shardGroupPrefix = MetadataKeyHelper.getShardGroupPrefix(); return scanPrefix(Metapb.ShardGroup.parser(), shardGroupPrefix).size(); } public List<Metapb.ShardGroup> getShardGroups() throws PDException { byte[] shardGroupPrefix = MetadataKeyHelper.getShardGroupPrefix(); return scanPrefix(Metapb.ShardGroup.parser(), shardGroupPrefix); } public Metapb.StoreStats getStoreStats(long storeId) throws PDException {<FILL_FUNCTION_BODY>} /** * @return store及状态信息 * @throws PDException */ public List<Metapb.Store> getStoreStatus(boolean isActive) throws PDException { byte[] storePrefix = MetadataKeyHelper.getStorePrefix(); List<Metapb.Store> stores = isActive ? getActiveStores() : scanPrefix(Metapb.Store.parser(), storePrefix); LinkedList<Metapb.Store> list = new LinkedList<>(); for (int i = 0; i < stores.size(); i++) { Metapb.Store store = stores.get(i); Metapb.StoreStats stats = getStoreStats(store.getId()); if (stats != null) { store = Metapb.Store.newBuilder(store).setStats(getStoreStats(store.getId())) .build(); } list.add(store); } return list; } }
byte[] storeStatusKey = MetadataKeyHelper.getStoreStatusKey(storeId); Metapb.StoreStats stats = getOne(Metapb.StoreStats.parser(), storeStatusKey); return stats;
1,767
57
1,824
<methods>public void <init>(org.apache.hugegraph.pd.config.PDConfig) ,public void clearAllCache() throws org.apache.hugegraph.pd.common.PDException,public void close() ,public boolean containsKey(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List#RAW getListWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public byte[] getOne(byte[]) throws org.apache.hugegraph.pd.common.PDException,public E getOne(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public org.apache.hugegraph.pd.store.HgKVStore getStore() ,public byte[] getWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void put(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long, java.util.concurrent.TimeUnit) throws org.apache.hugegraph.pd.common.PDException,public long remove(byte[]) throws org.apache.hugegraph.pd.common.PDException,public long removeByPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void removeWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanPrefix(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanRange(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanRange(Parser<E>, byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException<variables>org.apache.hugegraph.pd.config.PDConfig pdConfig,org.apache.hugegraph.pd.store.HgKVStore store
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/meta/TaskInfoMeta.java
TaskInfoMeta
updateMovePartitionTask
class TaskInfoMeta extends MetadataRocksDBStore { public TaskInfoMeta(PDConfig pdConfig) { super(pdConfig); } /** * 添加分区分裂任务 */ public void addSplitTask(int groupID, Metapb.Partition partition, SplitPartition splitPartition) throws PDException { byte[] key = MetadataKeyHelper.getSplitTaskKey(partition.getGraphName(), groupID); MetaTask.Task task = MetaTask.Task.newBuilder() .setType(MetaTask.TaskType.Split_Partition) .setState(MetaTask.TaskState.Task_Doing) .setStartTimestamp(System.currentTimeMillis()) .setPartition(partition) .setSplitPartition(splitPartition) .build(); put(key, task.toByteString().toByteArray()); } public void updateSplitTask(MetaTask.Task task) throws PDException { var partition = task.getPartition(); byte[] key = MetadataKeyHelper.getSplitTaskKey(partition.getGraphName(), partition.getId()); put(key, task.toByteString().toByteArray()); } public MetaTask.Task getSplitTask(String graphName, int groupID) throws PDException { byte[] key = MetadataKeyHelper.getSplitTaskKey(graphName, groupID); return getOne(MetaTask.Task.parser(), key); } public List<MetaTask.Task> scanSplitTask(String graphName) throws PDException { byte[] prefix = MetadataKeyHelper.getSplitTaskPrefix(graphName); return scanPrefix(MetaTask.Task.parser(), prefix); } public void removeSplitTaskPrefix(String graphName) throws PDException { byte[] key = MetadataKeyHelper.getSplitTaskPrefix(graphName); removeByPrefix(key); } public boolean hasSplitTaskDoing() throws PDException { byte[] key = MetadataKeyHelper.getAllSplitTaskPrefix(); return scanPrefix(key).size() > 0; } public void addMovePartitionTask(Metapb.Partition partition, MovePartition movePartition) throws PDException { byte[] key = MetadataKeyHelper.getMoveTaskKey(partition.getGraphName(), movePartition.getTargetPartition().getId(), partition.getId()); MetaTask.Task task = MetaTask.Task.newBuilder() .setType(MetaTask.TaskType.Move_Partition) .setState(MetaTask.TaskState.Task_Doing) .setStartTimestamp(System.currentTimeMillis()) .setPartition(partition) .setMovePartition(movePartition) .build(); put(key, task.toByteArray()); } public void updateMovePartitionTask(MetaTask.Task task) throws PDException {<FILL_FUNCTION_BODY>} public MetaTask.Task getMovePartitionTask(String graphName, int targetId, int partId) throws PDException { byte[] key = MetadataKeyHelper.getMoveTaskKey(graphName, targetId, partId); return getOne(MetaTask.Task.parser(), key); } public List<MetaTask.Task> scanMoveTask(String graphName) throws PDException { byte[] prefix = MetadataKeyHelper.getMoveTaskPrefix(graphName); return scanPrefix(MetaTask.Task.parser(), prefix); } /** * 按照prefix删除迁移任务,一次分组的 * * @param graphName 图名称 * @throws PDException io error */ public void removeMoveTaskPrefix(String graphName) throws PDException { byte[] key = MetadataKeyHelper.getMoveTaskPrefix(graphName); removeByPrefix(key); } public boolean hasMoveTaskDoing() throws PDException { byte[] key = MetadataKeyHelper.getAllMoveTaskPrefix(); return scanPrefix(key).size() > 0; } }
byte[] key = MetadataKeyHelper.getMoveTaskKey(task.getPartition().getGraphName(), task.getMovePartition().getTargetPartition() .getId(), task.getPartition().getId()); put(key, task.toByteArray());
1,013
70
1,083
<methods>public void <init>(org.apache.hugegraph.pd.config.PDConfig) ,public void clearAllCache() throws org.apache.hugegraph.pd.common.PDException,public void close() ,public boolean containsKey(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List#RAW getListWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public byte[] getOne(byte[]) throws org.apache.hugegraph.pd.common.PDException,public E getOne(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public org.apache.hugegraph.pd.store.HgKVStore getStore() ,public byte[] getWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void put(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long) throws org.apache.hugegraph.pd.common.PDException,public void putWithTTL(byte[], byte[], long, java.util.concurrent.TimeUnit) throws org.apache.hugegraph.pd.common.PDException,public long remove(byte[]) throws org.apache.hugegraph.pd.common.PDException,public long removeByPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public void removeWithTTL(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanPrefix(byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanPrefix(Parser<E>, byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<org.apache.hugegraph.pd.store.KV> scanRange(byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException,public List<E> scanRange(Parser<E>, byte[], byte[]) throws org.apache.hugegraph.pd.common.PDException<variables>org.apache.hugegraph.pd.config.PDConfig pdConfig,org.apache.hugegraph.pd.store.HgKVStore store
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/KVOperation.java
KVOperation
createPutWithTTL
class KVOperation { /** * Put operation */ public static final byte PUT = 0x01; /** * Get operation */ public static final byte GET = 0x02; public static final byte DEL = 0x03; public static final byte REMOVE_BY_PREFIX = 0x04; public static final byte REMOVE = 0x05; public static final byte PUT_WITH_TTL = 0x06; public static final byte CLEAR = 0x07; public static final byte PUT_WITH_TTL_UNIT = 0x08; public static final byte REMOVE_WITH_TTL = 0x09; /** * Snapshot operation */ public static final byte SAVE_SNAPSHOT = 0x10; public static final byte LOAD_SNAPSHOT = 0x11; private byte[] key; private byte[] value; private Object attach; // 原始对象,用于本机处理,减少一次反序列化操作 private Object arg; private byte op; public KVOperation() { } public KVOperation(byte[] key, byte[] value, Object attach, byte op) { this.key = key; this.value = value; this.attach = attach; this.op = op; } public KVOperation(byte[] key, byte[] value, Object attach, byte op, Object arg) { this.key = key; this.value = value; this.attach = attach; this.op = op; this.arg = arg; } public static KVOperation fromByteArray(byte[] value) throws IOException { try (ByteArrayInputStream bis = new ByteArrayInputStream(value, 1, value.length - 1)) { Hessian2Input input = new Hessian2Input(bis); KVOperation op = new KVOperation(); op.op = value[0]; op.key = input.readBytes(); op.value = input.readBytes(); op.arg = input.readObject(); input.close(); return op; } } public static KVOperation createPut(final byte[] key, final byte[] value) { Requires.requireNonNull(key, "key"); Requires.requireNonNull(value, "value"); return new KVOperation(key, value, null, PUT); } public static KVOperation createGet(final byte[] key) { Requires.requireNonNull(key, "key"); return new KVOperation(key, BytesUtil.EMPTY_BYTES, null, GET); } public static KVOperation createPutWithTTL(byte[] key, byte[] value, long ttl) {<FILL_FUNCTION_BODY>} public static KVOperation createPutWithTTL(byte[] key, byte[] value, long ttl, TimeUnit timeUnit) { Requires.requireNonNull(key, "key"); Requires.requireNonNull(value, "value"); return new KVOperation(key, value, value, PUT_WITH_TTL_UNIT, new Object[]{ttl, timeUnit}); } public static KVOperation createRemoveWithTTL(byte[] key) { Requires.requireNonNull(key, "key"); return new KVOperation(key, key, null, REMOVE_WITH_TTL); } public static KVOperation createRemoveByPrefix(byte[] key) { Requires.requireNonNull(key, "key"); return new KVOperation(key, key, null, REMOVE_BY_PREFIX); } public static KVOperation createRemove(byte[] key) { Requires.requireNonNull(key, "key"); return new KVOperation(key, key, null, REMOVE); } public static KVOperation createClear() { return new KVOperation(null, null, null, CLEAR); } public static KVOperation createSaveSnapshot(String snapshotPath) { Requires.requireNonNull(snapshotPath, "snapshotPath"); return new KVOperation(null, null, snapshotPath, SAVE_SNAPSHOT); } public static KVOperation createLoadSnapshot(String snapshotPath) { Requires.requireNonNull(snapshotPath, "snapshotPath"); return new KVOperation(null, null, snapshotPath, LOAD_SNAPSHOT); } public byte[] toByteArray() throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { bos.write(op); Hessian2Output output = new Hessian2Output(bos); output.writeObject(key); output.writeObject(value); output.writeObject(arg); output.flush(); return bos.toByteArray(); } } }
Requires.requireNonNull(key, "key"); Requires.requireNonNull(value, "value"); return new KVOperation(key, value, value, PUT_WITH_TTL, ttl);
1,260
58
1,318
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftRpcClient.java
RaftRpcClient
getGrpcAddress
class RaftRpcClient { protected volatile RpcClient rpcClient; private RpcOptions rpcOptions; public synchronized boolean init(final RpcOptions rpcOptions) { this.rpcOptions = rpcOptions; final RaftRpcFactory factory = RpcFactoryHelper.rpcFactory(); this.rpcClient = factory.createRpcClient(factory.defaultJRaftClientConfigHelper(this.rpcOptions)); return this.rpcClient.init(null); } /** * 请求快照 */ public CompletableFuture<RaftRpcProcessor.GetMemberResponse> getGrpcAddress(final String address) {<FILL_FUNCTION_BODY>} private <V> void internalCallAsyncWithRpc(final Endpoint endpoint, final RaftRpcProcessor.BaseRequest request, final FutureClosureAdapter<V> closure) { final InvokeContext invokeCtx = new InvokeContext(); final InvokeCallback invokeCallback = new InvokeCallback() { @Override public void complete(final Object result, final Throwable err) { if (err == null) { final RaftRpcProcessor.BaseResponse response = (RaftRpcProcessor.BaseResponse) result; closure.setResponse((V) response); } else { closure.failure(err); closure.run(new Status(-1, err.getMessage())); } } }; try { this.rpcClient.invokeAsync(endpoint, request, invokeCtx, invokeCallback, this.rpcOptions.getRpcDefaultTimeout()); } catch (final Throwable t) { log.error("failed to call rpc to {}. {}", endpoint, t.getMessage()); closure.failure(t); closure.run(new Status(-1, t.getMessage())); } } }
RaftRpcProcessor.GetMemberRequest request = new RaftRpcProcessor.GetMemberRequest(); FutureClosureAdapter<RaftRpcProcessor.GetMemberResponse> response = new FutureClosureAdapter<>(); internalCallAsyncWithRpc(JRaftUtils.getEndPoint(address), request, response); return response.future;
477
88
565
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/RaftRpcProcessor.java
RaftRpcProcessor
getGrpcAddress
class RaftRpcProcessor<T extends RaftRpcProcessor.BaseRequest> implements RpcProcessor<T> { private final Class<?> requestClass; private final RaftEngine raftEngine; public RaftRpcProcessor(Class<?> requestClass, RaftEngine raftEngine) { this.requestClass = requestClass; this.raftEngine = raftEngine; } public static void registerProcessor(final RpcServer rpcServer, RaftEngine raftEngine) { rpcServer.registerProcessor(new RaftRpcProcessor<>(GetMemberRequest.class, raftEngine)); } @Override public void handleRequest(RpcContext rpcCtx, T request) { if (request.magic() == BaseRequest.GET_GRPC_ADDRESS) { rpcCtx.sendResponse(getGrpcAddress()); } } @Override public String interest() { return this.requestClass.getName(); } private GetMemberResponse getGrpcAddress() {<FILL_FUNCTION_BODY>} public enum Status implements Serializable { UNKNOWN(-1, "unknown"), OK(0, "ok"), COMPLETE(0, "Transmission completed"), INCOMPLETE(1, "Incomplete transmission"), NO_PARTITION(10, "Partition not found"), IO_ERROR(11, "io error"), EXCEPTION(12, "exception"), ABORT(100, "Transmission aborted"); private final int code; private String msg; Status(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return this.code; } public Status setMsg(String msg) { this.msg = msg; return this; } public boolean isOK() { return this.code == 0; } } public abstract static class BaseRequest implements Serializable { public static final byte GET_GRPC_ADDRESS = 0x01; public abstract byte magic(); } @Data public abstract static class BaseResponse implements Serializable { private Status status; } @Data public static class GetMemberRequest extends BaseRequest { @Override public byte magic() { return GET_GRPC_ADDRESS; } } @Data public static class GetMemberResponse extends BaseResponse { private long clusterId; private String raftAddress; private String grpcAddress; private String datePath; private String restAddress; } }
GetMemberResponse rep = new GetMemberResponse(); rep.setGrpcAddress(raftEngine.getConfig().getGrpcAddress()); rep.setClusterId(raftEngine.getConfig().getClusterId()); rep.setDatePath(raftEngine.getConfig().getDataPath()); rep.setRaftAddress(raftEngine.getConfig().getAddress()); rep.setRestAddress( raftEngine.getConfig().getHost() + ":" + raftEngine.getConfig().getPort()); rep.setStatus(Status.OK); return rep;
677
139
816
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-core/src/main/java/org/apache/hugegraph/pd/raft/ZipUtils.java
ZipUtils
compress
class ZipUtils { public static void compress(final String rootDir, final String sourceDir, final String outputFile, final Checksum checksum) throws IOException {<FILL_FUNCTION_BODY>} private static void compressDirectoryToZipFile(final String rootDir, final String sourceDir, final ZipOutputStream zos) throws IOException { final String dir = Paths.get(rootDir, sourceDir).toString(); final File[] files = new File(dir).listFiles(); for (final File file : files) { final String child = Paths.get(sourceDir, file.getName()).toString(); if (file.isDirectory()) { compressDirectoryToZipFile(rootDir, child, zos); } else { zos.putNextEntry(new ZipEntry(child)); try (final FileInputStream fis = new FileInputStream(file); final BufferedInputStream bis = new BufferedInputStream(fis)) { IOUtils.copy(bis, zos); } } } } public static void decompress(final String sourceFile, final File outputDir, final Checksum checksum) throws IOException { try (final FileInputStream fis = new FileInputStream(sourceFile); final CheckedInputStream cis = new CheckedInputStream(fis, checksum); final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(cis))) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { final String fileName = entry.getName(); final File entryFile = new File(outputDir, fileName); if (!entryFile.toPath().normalize().startsWith(outputDir.toPath())) { throw new IOException("Bad zip entry"); } FileUtils.forceMkdir(entryFile.getParentFile()); try (final FileOutputStream fos = new FileOutputStream(entryFile); final BufferedOutputStream bos = new BufferedOutputStream(fos)) { IOUtils.copy(zis, bos); bos.flush(); fos.getFD().sync(); } } IOUtils.copy(cis, NullOutputStream.NULL_OUTPUT_STREAM); } } }
try (final FileOutputStream fos = new FileOutputStream(outputFile); final CheckedOutputStream cos = new CheckedOutputStream(fos, checksum); final ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(cos))) { ZipUtils.compressDirectoryToZipFile(rootDir, sourceDir, zos); zos.flush(); fos.getFD().sync(); }
553
102
655
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-grpc/src/main/java/org/apache/hugegraph/pd/grpc/pulse/HgPdPulseGrpc.java
HgPdPulseMethodDescriptorSupplier
getServiceDescriptor
class HgPdPulseMethodDescriptorSupplier extends HgPdPulseBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; HgPdPulseMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() {<FILL_FUNCTION_BODY>
io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (HgPdPulseGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new HgPdPulseFileDescriptorSupplier()) .addMethod(getPulseMethod()) .build(); } } } return result;
175
131
306
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-pd/hg-pd-grpc/src/main/java/org/apache/hugegraph/pd/grpc/pulse/PulseCancelRequest.java
Builder
mergeFrom
class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:PulseCancelRequest) org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hugegraph.pd.grpc.pulse.HgPdPulseProto.internal_static_PulseCancelRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hugegraph.pd.grpc.pulse.HgPdPulseProto.internal_static_PulseCancelRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest.class, org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest.Builder.class); } // Construct using org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); observerId_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hugegraph.pd.grpc.pulse.HgPdPulseProto.internal_static_PulseCancelRequest_descriptor; } @java.lang.Override public org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest getDefaultInstanceForType() { return org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest.getDefaultInstance(); } @java.lang.Override public org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest build() { org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest buildPartial() { org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest result = new org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest(this); result.observerId_ = observerId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest) { return mergeFrom((org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest other) { if (other == org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest.getDefaultInstance()) return this; if (other.getObserverId() != 0L) { setObserverId(other.getObserverId()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {<FILL_FUNCTION_BODY>} private long observerId_ ; /** * <code>int64 observer_id = 1;</code> * @return The observerId. */ @java.lang.Override public long getObserverId() { return observerId_; } /** * <code>int64 observer_id = 1;</code> * @param value The observerId to set. * @return This builder for chaining. */ public Builder setObserverId(long value) { observerId_ = value; onChanged(); return this; } /** * <code>int64 observer_id = 1;</code> * @return This builder for chaining. */ public Builder clearObserverId() { observerId_ = 0L; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:PulseCancelRequest) }
org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hugegraph.pd.grpc.pulse.PulseCancelRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this;
1,765
150
1,915
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/API.java
API
parseProperties
class API { public static final String CHARSET = "UTF-8"; public static final String TEXT_PLAIN = MediaType.TEXT_PLAIN; public static final String APPLICATION_JSON = MediaType.APPLICATION_JSON; public static final String APPLICATION_JSON_WITH_CHARSET = APPLICATION_JSON + ";charset=" + CHARSET; public static final String APPLICATION_TEXT_WITH_CHARSET = MediaType.TEXT_PLAIN + ";charset=" + CHARSET; public static final String JSON = MediaType.APPLICATION_JSON_TYPE .getSubtype(); public static final String ACTION_APPEND = "append"; public static final String ACTION_ELIMINATE = "eliminate"; public static final String ACTION_CLEAR = "clear"; protected static final Logger LOG = Log.logger(API.class); private static final Meter SUCCEED_METER = MetricsUtil.registerMeter(API.class, "commit-succeed"); private static final Meter ILLEGAL_ARG_ERROR_METER = MetricsUtil.registerMeter(API.class, "illegal-arg"); private static final Meter EXPECTED_ERROR_METER = MetricsUtil.registerMeter(API.class, "expected-error"); private static final Meter UNKNOWN_ERROR_METER = MetricsUtil.registerMeter(API.class, "unknown-error"); public static HugeGraph graph(GraphManager manager, String graph) { HugeGraph g = manager.graph(graph); if (g == null) { throw new NotFoundException(String.format("Graph '%s' does not exist", graph)); } return g; } public static HugeGraph graph4admin(GraphManager manager, String graph) { return graph(manager, graph).hugegraph(); } public static <R> R commit(HugeGraph g, Callable<R> callable) { Consumer<Throwable> rollback = (error) -> { if (error != null) { LOG.error("Failed to commit", error); } try { g.tx().rollback(); } catch (Throwable e) { LOG.error("Failed to rollback", e); } }; try { R result = callable.call(); g.tx().commit(); SUCCEED_METER.mark(); return result; } catch (IllegalArgumentException | NotFoundException | ForbiddenException e) { ILLEGAL_ARG_ERROR_METER.mark(); rollback.accept(null); throw e; } catch (RuntimeException e) { EXPECTED_ERROR_METER.mark(); rollback.accept(e); throw e; } catch (Throwable e) { UNKNOWN_ERROR_METER.mark(); rollback.accept(e); // TODO: throw the origin exception 'e' throw new HugeException("Failed to commit", e); } } public static void commit(HugeGraph g, Runnable runnable) { commit(g, () -> { runnable.run(); return null; }); } public static Object[] properties(Map<String, Object> properties) { Object[] list = new Object[properties.size() * 2]; int i = 0; for (Map.Entry<String, Object> prop : properties.entrySet()) { list[i++] = prop.getKey(); list[i++] = prop.getValue(); } return list; } protected static void checkCreatingBody(Checkable body) { E.checkArgumentNotNull(body, "The request body can't be empty"); body.checkCreate(false); } protected static void checkUpdatingBody(Checkable body) { E.checkArgumentNotNull(body, "The request body can't be empty"); body.checkUpdate(); } protected static void checkCreatingBody(Collection<? extends Checkable> bodies) { E.checkArgumentNotNull(bodies, "The request body can't be empty"); for (Checkable body : bodies) { E.checkArgument(body != null, "The batch body can't contain null record"); body.checkCreate(true); } } protected static void checkUpdatingBody(Collection<? extends Checkable> bodies) { E.checkArgumentNotNull(bodies, "The request body can't be empty"); for (Checkable body : bodies) { E.checkArgumentNotNull(body, "The batch body can't contain null record"); body.checkUpdate(); } } @SuppressWarnings("unchecked") protected static Map<String, Object> parseProperties(String properties) {<FILL_FUNCTION_BODY>} public static boolean checkAndParseAction(String action) { E.checkArgumentNotNull(action, "The action param can't be empty"); if (action.equals(ACTION_APPEND)) { return true; } else if (action.equals(ACTION_ELIMINATE)) { return false; } else { throw new NotSupportedException(String.format("Not support action '%s'", action)); } } public static class ApiMeasurer { public static final String EDGE_ITER = "edge_iterations"; public static final String VERTICE_ITER = "vertice_iterations"; public static final String COST = "cost(ns)"; private final long timeStart; private final Map<String, Object> measures; public ApiMeasurer() { this.timeStart = System.nanoTime(); this.measures = InsertionOrderUtil.newMap(); } public Map<String, Object> measures() { measures.put(COST, System.nanoTime() - timeStart); return measures; } public void put(String key, String value) { this.measures.put(key, value); } public void put(String key, long value) { this.measures.put(key, value); } public void put(String key, int value) { this.measures.put(key, value); } protected void addCount(String key, long value) { Object current = measures.get(key); if (current == null) { measures.put(key, new MutableLong(value)); } else if (current instanceof MutableLong) { ((MutableLong) measures.computeIfAbsent(key, MutableLong::new)).add(value); } else if (current instanceof Long) { Long currentLong = (Long) current; measures.put(key, new MutableLong(currentLong + value)); } else { throw new NotSupportedException("addCount() method's 'value' datatype must be " + "Long or MutableLong"); } } public void addIterCount(long verticeIters, long edgeIters) { this.addCount(EDGE_ITER, edgeIters); this.addCount(VERTICE_ITER, verticeIters); } } }
if (properties == null || properties.isEmpty()) { return ImmutableMap.of(); } Map<String, Object> props = null; try { props = JsonUtil.fromJson(properties, Map.class); } catch (Exception ignored) { // ignore } // If properties is the string "null", props will be null E.checkArgument(props != null, "Invalid request with properties: %s", properties); return props;
1,865
123
1,988
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/arthas/ArthasAPI.java
ArthasAPI
startArthas
class ArthasAPI extends API { @Context private jakarta.inject.Provider<HugeConfig> configProvider; @PUT @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) @Operation(summary = "start arthas agent") public Object startArthas() {<FILL_FUNCTION_BODY>} }
HugeConfig config = this.configProvider.get(); HashMap<String, String> configMap = new HashMap<>(4); configMap.put("arthas.telnetPort", config.get(ServerOptions.ARTHAS_TELNET_PORT)); configMap.put("arthas.httpPort", config.get(ServerOptions.ARTHAS_HTTP_PORT)); configMap.put("arthas.ip", config.get(ServerOptions.ARTHAS_IP)); configMap.put("arthas.disabledCommands", config.get(ServerOptions.ARTHAS_DISABLED_COMMANDS)); ArthasAgent.attach(configMap); return JsonUtil.toJson(configMap);
99
181
280
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/auth/AccessAPI.java
AccessAPI
create
class AccessAPI extends API { private static final Logger LOG = Log.logger(AccessAPI.class); @POST @Timed @Status(Status.CREATED) @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String create(@Context GraphManager manager, @PathParam("graph") String graph, JsonAccess jsonAccess) {<FILL_FUNCTION_BODY>} @PUT @Timed @Path("{id}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String update(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id, JsonAccess jsonAccess) { LOG.debug("Graph [{}] update access: {}", graph, jsonAccess); checkUpdatingBody(jsonAccess); HugeGraph g = graph(manager, graph); HugeAccess access; try { access = manager.authManager().getAccess(UserAPI.parseId(id)); } catch (NotFoundException e) { throw new IllegalArgumentException("Invalid access id: " + id); } access = jsonAccess.build(access); manager.authManager().updateAccess(access); return manager.serializer(g).writeAuthElement(access); } @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String list(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("group") String group, @QueryParam("target") String target, @QueryParam("limit") @DefaultValue("100") long limit) { LOG.debug("Graph [{}] list belongs by group {} or target {}", graph, group, target); E.checkArgument(group == null || target == null, "Can't pass both group and target at the same time"); HugeGraph g = graph(manager, graph); List<HugeAccess> belongs; if (group != null) { Id id = UserAPI.parseId(group); belongs = manager.authManager().listAccessByGroup(id, limit); } else if (target != null) { Id id = UserAPI.parseId(target); belongs = manager.authManager().listAccessByTarget(id, limit); } else { belongs = manager.authManager().listAllAccess(limit); } return manager.serializer(g).writeAuthElements("accesses", belongs); } @GET @Timed @Path("{id}") @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id) { LOG.debug("Graph [{}] get access: {}", graph, id); HugeGraph g = graph(manager, graph); HugeAccess access = manager.authManager().getAccess(UserAPI.parseId(id)); return manager.serializer(g).writeAuthElement(access); } @DELETE @Timed @Path("{id}") @Consumes(APPLICATION_JSON) public void delete(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id) { LOG.debug("Graph [{}] delete access: {}", graph, id); @SuppressWarnings("unused") // just check if the graph exists HugeGraph g = graph(manager, graph); try { manager.authManager().deleteAccess(UserAPI.parseId(id)); } catch (NotFoundException e) { throw new IllegalArgumentException("Invalid access id: " + id); } } @JsonIgnoreProperties(value = {"id", "access_creator", "access_create", "access_update"}) private static class JsonAccess implements Checkable { @JsonProperty("group") private String group; @JsonProperty("target") private String target; @JsonProperty("access_permission") private HugePermission permission; @JsonProperty("access_description") private String description; public HugeAccess build(HugeAccess access) { E.checkArgument(this.group == null || access.source().equals(UserAPI.parseId(this.group)), "The group of access can't be updated"); E.checkArgument(this.target == null || access.target().equals(UserAPI.parseId(this.target)), "The target of access can't be updated"); E.checkArgument(this.permission == null || access.permission().equals(this.permission), "The permission of access can't be updated"); if (this.description != null) { access.description(this.description); } return access; } public HugeAccess build() { HugeAccess access = new HugeAccess(UserAPI.parseId(this.group), UserAPI.parseId(this.target)); access.permission(this.permission); access.description(this.description); return access; } @Override public void checkCreate(boolean isBatch) { E.checkArgumentNotNull(this.group, "The group of access can't be null"); E.checkArgumentNotNull(this.target, "The target of access can't be null"); E.checkArgumentNotNull(this.permission, "The permission of access can't be null"); } @Override public void checkUpdate() { E.checkArgumentNotNull(this.description, "The description of access can't be null"); } } }
LOG.debug("Graph [{}] create access: {}", graph, jsonAccess); checkCreatingBody(jsonAccess); HugeGraph g = graph(manager, graph); HugeAccess access = jsonAccess.build(); access.id(manager.authManager().createAccess(access)); return manager.serializer(g).writeAuthElement(access);
1,464
91
1,555
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/auth/BelongAPI.java
BelongAPI
list
class BelongAPI extends API { private static final Logger LOG = Log.logger(BelongAPI.class); @POST @Timed @Status(Status.CREATED) @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String create(@Context GraphManager manager, @PathParam("graph") String graph, JsonBelong jsonBelong) { LOG.debug("Graph [{}] create belong: {}", graph, jsonBelong); checkCreatingBody(jsonBelong); HugeGraph g = graph(manager, graph); HugeBelong belong = jsonBelong.build(); belong.id(manager.authManager().createBelong(belong)); return manager.serializer(g).writeAuthElement(belong); } @PUT @Timed @Path("{id}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String update(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id, JsonBelong jsonBelong) { LOG.debug("Graph [{}] update belong: {}", graph, jsonBelong); checkUpdatingBody(jsonBelong); HugeGraph g = graph(manager, graph); HugeBelong belong; try { belong = manager.authManager().getBelong(UserAPI.parseId(id)); } catch (NotFoundException e) { throw new IllegalArgumentException("Invalid belong id: " + id); } belong = jsonBelong.build(belong); manager.authManager().updateBelong(belong); return manager.serializer(g).writeAuthElement(belong); } @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String list(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("user") String user, @QueryParam("group") String group, @QueryParam("limit") @DefaultValue("100") long limit) {<FILL_FUNCTION_BODY>} @GET @Timed @Path("{id}") @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id) { LOG.debug("Graph [{}] get belong: {}", graph, id); HugeGraph g = graph(manager, graph); HugeBelong belong = manager.authManager().getBelong(UserAPI.parseId(id)); return manager.serializer(g).writeAuthElement(belong); } @DELETE @Timed @Path("{id}") @Consumes(APPLICATION_JSON) public void delete(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id) { LOG.debug("Graph [{}] delete belong: {}", graph, id); @SuppressWarnings("unused") // just check if the graph exists HugeGraph g = graph(manager, graph); try { manager.authManager().deleteBelong(UserAPI.parseId(id)); } catch (NotFoundException e) { throw new IllegalArgumentException("Invalid belong id: " + id); } } @JsonIgnoreProperties(value = {"id", "belong_creator", "belong_create", "belong_update"}) private static class JsonBelong implements Checkable { @JsonProperty("user") private String user; @JsonProperty("group") private String group; @JsonProperty("belong_description") private String description; public HugeBelong build(HugeBelong belong) { E.checkArgument(this.user == null || belong.source().equals(UserAPI.parseId(this.user)), "The user of belong can't be updated"); E.checkArgument(this.group == null || belong.target().equals(UserAPI.parseId(this.group)), "The group of belong can't be updated"); if (this.description != null) { belong.description(this.description); } return belong; } public HugeBelong build() { HugeBelong belong = new HugeBelong(UserAPI.parseId(this.user), UserAPI.parseId(this.group)); belong.description(this.description); return belong; } @Override public void checkCreate(boolean isBatch) { E.checkArgumentNotNull(this.user, "The user of belong can't be null"); E.checkArgumentNotNull(this.group, "The group of belong can't be null"); } @Override public void checkUpdate() { E.checkArgumentNotNull(this.description, "The description of belong can't be null"); } } }
LOG.debug("Graph [{}] list belongs by user {} or group {}", graph, user, group); E.checkArgument(user == null || group == null, "Can't pass both user and group at the same time"); HugeGraph g = graph(manager, graph); List<HugeBelong> belongs; if (user != null) { Id id = UserAPI.parseId(user); belongs = manager.authManager().listBelongByUser(id, limit); } else if (group != null) { Id id = UserAPI.parseId(group); belongs = manager.authManager().listBelongByGroup(id, limit); } else { belongs = manager.authManager().listAllBelong(limit); } return manager.serializer(g).writeAuthElements("belongs", belongs);
1,289
215
1,504
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/auth/GroupAPI.java
JsonGroup
build
class JsonGroup implements Checkable { @JsonProperty("group_name") private String name; @JsonProperty("group_description") private String description; public HugeGroup build(HugeGroup group) {<FILL_FUNCTION_BODY>} public HugeGroup build() { HugeGroup group = new HugeGroup(this.name); group.description(this.description); return group; } @Override public void checkCreate(boolean isBatch) { E.checkArgumentNotNull(this.name, "The name of group can't be null"); } @Override public void checkUpdate() { E.checkArgumentNotNull(this.description, "The description of group can't be null"); } }
E.checkArgument(this.name == null || group.name().equals(this.name), "The name of group can't be updated"); if (this.description != null) { group.description(this.description); } return group;
201
69
270
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/auth/LoginAPI.java
LoginAPI
login
class LoginAPI extends API { private static final Logger LOG = Log.logger(LoginAPI.class); @POST @Timed @Path("login") @Status(Status.OK) @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String login(@Context GraphManager manager, @PathParam("graph") String graph, JsonLogin jsonLogin) {<FILL_FUNCTION_BODY>} @DELETE @Timed @Path("logout") @Status(Status.OK) @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public void logout(@Context GraphManager manager, @PathParam("graph") String graph, @HeaderParam(HttpHeaders.AUTHORIZATION) String auth) { E.checkArgument(StringUtils.isNotEmpty(auth), "Request header Authorization must not be null"); LOG.debug("Graph [{}] user logout: {}", graph, auth); if (!auth.startsWith(AuthenticationFilter.BEARER_TOKEN_PREFIX)) { throw new BadRequestException("Only HTTP Bearer authentication is supported"); } String token = auth.substring(AuthenticationFilter.BEARER_TOKEN_PREFIX.length()); manager.authManager().logoutUser(token); } @GET @Timed @Path("verify") @Status(Status.OK) @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String verifyToken(@Context GraphManager manager, @PathParam("graph") String graph, @HeaderParam(HttpHeaders.AUTHORIZATION) String token) { E.checkArgument(StringUtils.isNotEmpty(token), "Request header Authorization must not be null"); LOG.debug("Graph [{}] get user: {}", graph, token); if (!token.startsWith(AuthenticationFilter.BEARER_TOKEN_PREFIX)) { throw new BadRequestException("Only HTTP Bearer authentication is supported"); } token = token.substring(AuthenticationFilter.BEARER_TOKEN_PREFIX.length()); UserWithRole userWithRole = manager.authManager().validateUser(token); HugeGraph g = graph(manager, graph); return manager.serializer(g) .writeMap(ImmutableMap.of(AuthConstant.TOKEN_USER_NAME, userWithRole.username(), AuthConstant.TOKEN_USER_ID, userWithRole.userId())); } private static class JsonLogin implements Checkable { @JsonProperty("user_name") private String name; @JsonProperty("user_password") private String password; @Override public void checkCreate(boolean isBatch) { E.checkArgument(!StringUtils.isEmpty(this.name), "The name of user can't be null"); E.checkArgument(!StringUtils.isEmpty(this.password), "The password of user can't be null"); } @Override public void checkUpdate() { // pass } } }
LOG.debug("Graph [{}] user login: {}", graph, jsonLogin); checkCreatingBody(jsonLogin); try { String token = manager.authManager().loginUser(jsonLogin.name, jsonLogin.password); HugeGraph g = graph(manager, graph); return manager.serializer(g).writeMap(ImmutableMap.of("token", token)); } catch (AuthenticationException e) { throw new NotAuthorizedException(e.getMessage(), e); }
813
125
938
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/auth/ProjectAPI.java
JsonProject
buildAddGraph
class JsonProject implements Checkable { @JsonProperty("project_name") private String name; @JsonProperty("project_graphs") private Set<String> graphs; @JsonProperty("project_description") private String description; public HugeProject build() { HugeProject project = new HugeProject(this.name, this.description); return project; } private HugeProject buildAddGraph(HugeProject project) {<FILL_FUNCTION_BODY>} private HugeProject buildRemoveGraph(HugeProject project) { E.checkArgument(this.name == null || this.name.equals(project.name()), "The name of project can't be updated"); E.checkArgument(!CollectionUtils.isEmpty(this.graphs), "The graphs of project can't be empty " + "when removing graphs"); E.checkArgument(StringUtils.isEmpty(this.description), "The description of project can't be updated " + "when removing graphs"); Set<String> sourceGraphs = new HashSet<>(project.graphs()); sourceGraphs.removeAll(this.graphs); project.graphs(sourceGraphs); return project; } private HugeProject buildUpdateDescription(HugeProject project) { E.checkArgument(this.name == null || this.name.equals(project.name()), "The name of project can't be updated"); E.checkArgumentNotNull(this.description, "The description of project " + "can't be null"); E.checkArgument(CollectionUtils.isEmpty(this.graphs), "The graphs of project can't be updated"); project.description(this.description); return project; } @Override public void checkCreate(boolean isBatch) { E.checkArgumentNotNull(this.name, "The name of project can't be null"); E.checkArgument(CollectionUtils.isEmpty(this.graphs), "The graphs '%s' of project can't be added when" + "creating the project '%s'", this.graphs, this.name); } @Override public void checkUpdate() { E.checkArgument(!CollectionUtils.isEmpty(this.graphs) || this.description != null, "Must specify 'graphs' or 'description' " + "field that need to be updated"); } }
E.checkArgument(this.name == null || this.name.equals(project.name()), "The name of project can't be updated"); E.checkArgument(!CollectionUtils.isEmpty(this.graphs), "The graphs of project can't be empty " + "when adding graphs"); E.checkArgument(StringUtils.isEmpty(this.description), "The description of project can't be updated " + "when adding graphs"); Set<String> sourceGraphs = new HashSet<>(project.graphs()); E.checkArgument(!sourceGraphs.containsAll(this.graphs), "There are graphs '%s' of project '%s' that " + "have been added in the graph collection", this.graphs, project.id()); sourceGraphs.addAll(this.graphs); project.graphs(sourceGraphs); return project;
617
224
841
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/auth/TargetAPI.java
JsonTarget
build
class JsonTarget implements Checkable { @JsonProperty("target_name") private String name; @JsonProperty("target_graph") private String graph; @JsonProperty("target_url") private String url; @JsonProperty("target_resources") // error when List<HugeResource> private List<Map<String, Object>> resources; public HugeTarget build(HugeTarget target) {<FILL_FUNCTION_BODY>} public HugeTarget build() { HugeTarget target = new HugeTarget(this.name, this.graph, this.url); if (this.resources != null) { target.resources(JsonUtil.toJson(this.resources)); } return target; } @Override public void checkCreate(boolean isBatch) { E.checkArgumentNotNull(this.name, "The name of target can't be null"); E.checkArgumentNotNull(this.graph, "The graph of target can't be null"); E.checkArgumentNotNull(this.url, "The url of target can't be null"); } @Override public void checkUpdate() { E.checkArgument(this.url != null || this.resources != null, "Expect one of target url/resources"); } }
E.checkArgument(this.name == null || target.name().equals(this.name), "The name of target can't be updated"); E.checkArgument(this.graph == null || target.graph().equals(this.graph), "The graph of target can't be updated"); if (this.url != null) { target.url(this.url); } if (this.resources != null) { target.resources(JsonUtil.toJson(this.resources)); } return target;
339
140
479
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/auth/UserAPI.java
UserAPI
role
class UserAPI extends API { private static final Logger LOG = Log.logger(UserAPI.class); @POST @Timed @Status(Status.CREATED) @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String create(@Context GraphManager manager, @PathParam("graph") String graph, JsonUser jsonUser) { LOG.debug("Graph [{}] create user: {}", graph, jsonUser); checkCreatingBody(jsonUser); HugeGraph g = graph(manager, graph); HugeUser user = jsonUser.build(); user.id(manager.authManager().createUser(user)); return manager.serializer(g).writeAuthElement(user); } @PUT @Timed @Path("{id}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public String update(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id, JsonUser jsonUser) { LOG.debug("Graph [{}] update user: {}", graph, jsonUser); checkUpdatingBody(jsonUser); HugeGraph g = graph(manager, graph); HugeUser user; try { user = manager.authManager().getUser(UserAPI.parseId(id)); } catch (NotFoundException e) { throw new IllegalArgumentException("Invalid user id: " + id); } user = jsonUser.build(user); manager.authManager().updateUser(user); return manager.serializer(g).writeAuthElement(user); } @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public String list(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("limit") @DefaultValue("100") long limit) { LOG.debug("Graph [{}] list users", graph); HugeGraph g = graph(manager, graph); List<HugeUser> users = manager.authManager().listAllUsers(limit); return manager.serializer(g).writeAuthElements("users", users); } @GET @Timed @Path("{id}") @Produces(APPLICATION_JSON_WITH_CHARSET) public String get(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id) { LOG.debug("Graph [{}] get user: {}", graph, id); HugeGraph g = graph(manager, graph); HugeUser user = manager.authManager().getUser(IdGenerator.of(id)); return manager.serializer(g).writeAuthElement(user); } @GET @Timed @Path("{id}/role") @Produces(APPLICATION_JSON_WITH_CHARSET) public String role(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id) {<FILL_FUNCTION_BODY>} @DELETE @Timed @Path("{id}") @Consumes(APPLICATION_JSON) public void delete(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") String id) { LOG.debug("Graph [{}] delete user: {}", graph, id); @SuppressWarnings("unused") // just check if the graph exists HugeGraph g = graph(manager, graph); try { manager.authManager().deleteUser(IdGenerator.of(id)); } catch (NotFoundException e) { throw new IllegalArgumentException("Invalid user id: " + id); } } protected static Id parseId(String id) { return IdGenerator.of(id); } @JsonIgnoreProperties(value = {"id", "user_creator", "user_create", "user_update"}) private static class JsonUser implements Checkable { @JsonProperty("user_name") private String name; @JsonProperty("user_password") private String password; @JsonProperty("user_phone") private String phone; @JsonProperty("user_email") private String email; @JsonProperty("user_avatar") private String avatar; @JsonProperty("user_description") private String description; public HugeUser build(HugeUser user) { E.checkArgument(this.name == null || user.name().equals(this.name), "The name of user can't be updated"); if (this.password != null) { user.password(StringEncoding.hashPassword(this.password)); } if (this.phone != null) { user.phone(this.phone); } if (this.email != null) { user.email(this.email); } if (this.avatar != null) { user.avatar(this.avatar); } if (this.description != null) { user.description(this.description); } return user; } public HugeUser build() { HugeUser user = new HugeUser(this.name); user.password(StringEncoding.hashPassword(this.password)); user.phone(this.phone); user.email(this.email); user.avatar(this.avatar); user.description(this.description); return user; } @Override public void checkCreate(boolean isBatch) { E.checkArgument(!StringUtils.isEmpty(this.name), "The name of user can't be null"); E.checkArgument(!StringUtils.isEmpty(this.password), "The password of user can't be null"); } @Override public void checkUpdate() { E.checkArgument(!StringUtils.isEmpty(this.password) || this.phone != null || this.email != null || this.avatar != null, "Expect one of user password/phone/email/avatar]"); } } }
LOG.debug("Graph [{}] get user role: {}", graph, id); @SuppressWarnings("unused") // just check if the graph exists HugeGraph g = graph(manager, graph); HugeUser user = manager.authManager().getUser(IdGenerator.of(id)); return manager.authManager().rolePermission(user).toJson();
1,583
94
1,677
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/cypher/CypherAPI.java
CypherAPI
client
class CypherAPI extends API { private static final Logger LOG = Log.logger(CypherAPI.class); private static final Charset UTF8 = StandardCharsets.UTF_8; private static final String CLIENT_CONF = "conf/remote-objects.yaml"; private final Base64.Decoder decoder = Base64.getUrlDecoder(); private final String basic = "Basic "; private final String bearer = "Bearer "; private CypherManager cypherManager; private CypherManager cypherManager() { if (this.cypherManager == null) { this.cypherManager = CypherManager.configOf(CLIENT_CONF); } return this.cypherManager; } @GET @Timed @CompressInterceptor.Compress(buffer = (1024 * 40)) @Produces(APPLICATION_JSON_WITH_CHARSET) public CypherModel query(@PathParam("graph") String graph, @Context HttpHeaders headers, @QueryParam("cypher") String cypher) { LOG.debug("Graph [{}] query by cypher: {}", graph, cypher); return this.queryByCypher(graph, headers, cypher); } @POST @Timed @CompressInterceptor.Compress @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public CypherModel post(@PathParam("graph") String graph, @Context HttpHeaders headers, String cypher) { LOG.debug("Graph [{}] query by cypher: {}", graph, cypher); return this.queryByCypher(graph, headers, cypher); } private CypherModel queryByCypher(String graph, HttpHeaders headers, String cypher) { E.checkArgument(graph != null && !graph.isEmpty(), "The graph parameter can't be null or empty"); E.checkArgument(cypher != null && !cypher.isEmpty(), "The cypher parameter can't be null or empty"); Map<String, String> aliases = new HashMap<>(1, 1); aliases.put("g", "__g_" + graph); return this.client(headers).submitQuery(cypher, aliases); } private CypherClient client(HttpHeaders headers) {<FILL_FUNCTION_BODY>} private CypherClient clientViaBasic(String auth) { Pair<String, String> userPass = this.toUserPass(auth); E.checkNotNull(userPass, "user-password-pair"); return this.cypherManager().getClient(userPass.getLeft(), userPass.getRight()); } private CypherClient clientViaToken(String auth) { return this.cypherManager().getClient(auth.substring(bearer.length())); } private Pair<String, String> toUserPass(String auth) { if (auth == null || auth.isEmpty()) { return null; } if (!auth.startsWith(basic)) { return null; } String[] split; try { String encoded = auth.substring(basic.length()); byte[] userPass = this.decoder.decode(encoded); String authorization = new String(userPass, UTF8); split = authorization.split(":"); } catch (Exception e) { LOG.error("Failed convert auth to credential.", e); return null; } if (split.length != 2) { return null; } return ImmutablePair.of(split[0], split[1]); } }
String auth = headers.getHeaderString(HttpHeaders.AUTHORIZATION); if (auth != null && !auth.isEmpty()) { auth = auth.split(",")[0]; } if (auth != null) { if (auth.startsWith(basic)) { return this.clientViaBasic(auth); } else if (auth.startsWith(bearer)) { return this.clientViaToken(auth); } } throw new NotAuthorizedException("The Cypher-API called without any authorization.");
972
147
1,119
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/cypher/CypherClient.java
CypherClient
equals
class CypherClient { private static final Logger LOG = Log.logger(CypherClient.class); private final Supplier<Configuration> configurationSupplier; private String userName; private String password; private String token; CypherClient(String userName, String password, Supplier<Configuration> configurationSupplier) { this.userName = userName; this.password = password; this.configurationSupplier = configurationSupplier; } CypherClient(String token, Supplier<Configuration> configurationSupplier) { this.token = token; this.configurationSupplier = configurationSupplier; } public CypherModel submitQuery(String cypherQuery, @Nullable Map<String, String> aliases) { E.checkArgument(cypherQuery != null && !cypherQuery.isEmpty(), "The cypher-query parameter can't be null or empty"); Cluster cluster = Cluster.open(getConfig()); Client client = cluster.connect(); if (aliases != null && !aliases.isEmpty()) { client = client.alias(aliases); } RequestMessage request = createRequest(cypherQuery); CypherModel res; try { List<Object> list = this.doQueryList(client, request); res = CypherModel.dataOf(request.getRequestId().toString(), list); } catch (Exception e) { LOG.error(String.format("Failed to submit cypher-query: [ %s ], caused by:", cypherQuery), e); res = CypherModel.failOf(request.getRequestId().toString(), e.getMessage()); } finally { client.close(); cluster.close(); } return res; } private RequestMessage createRequest(String cypherQuery) { return RequestMessage.build(Tokens.OPS_EVAL) .processor("cypher") .add(Tokens.ARGS_GREMLIN, cypherQuery) .create(); } private List<Object> doQueryList(Client client, RequestMessage request) throws ExecutionException, InterruptedException { ResultSet results = client.submitAsync(request).get(); Iterator<Result> iter = results.iterator(); List<Object> list = new LinkedList<>(); while (iter.hasNext()) { Result data = iter.next(); list.add(data.getObject()); } return list; } /** * As Sasl does not support a token, which is a coded string to indicate a legal user, * we had to use a trick to fix it. When the token is set, the password will be set to * an empty string, which is an uncommon value under normal conditions. * The token will then be transferred through the userName-property. * To see org.apache.hugegraph.auth.StandardAuthenticator.TokenSaslAuthenticator */ private Configuration getConfig() { Configuration conf = this.configurationSupplier.get(); conf.addProperty("username", this.token == null ? this.userName : this.token); conf.addProperty("password", this.token == null ? this.password : ""); return conf; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(userName, password, token); } @Override public String toString() { final StringBuilder builder = new StringBuilder("CypherClient{"); builder.append("userName='").append(userName).append('\'') .append(", token='").append(token).append('\'').append('}'); return builder.toString(); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CypherClient that = (CypherClient) o; return Objects.equals(userName, that.userName) && Objects.equals(password, that.password) && Objects.equals(token, that.token);
978
108
1,086
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/cypher/CypherManager.java
CypherManager
loadYaml
class CypherManager { private final String configurationFile; private YAMLConfiguration configuration; public static CypherManager configOf(String configurationFile) { E.checkArgument(configurationFile != null && !configurationFile.isEmpty(), "The configurationFile parameter can't be null or empty"); return new CypherManager(configurationFile); } private CypherManager(String configurationFile) { this.configurationFile = configurationFile; } public CypherClient getClient(String userName, String password) { E.checkArgument(userName != null && !userName.isEmpty(), "The userName parameter can't be null or empty"); E.checkArgument(password != null && !password.isEmpty(), "The password parameter can't be null or empty"); // TODO: Need to cache the client and make it hold the connection. return new CypherClient(userName, password, this::cloneConfig); } public CypherClient getClient(String token) { E.checkArgument(token != null && !token.isEmpty(), "The token parameter can't be null or empty"); // TODO: Need to cache the client and make it hold the connection. return new CypherClient(token, this::cloneConfig); } private Configuration cloneConfig() { if (this.configuration == null) { this.configuration = loadYaml(this.configurationFile); } return (Configuration) this.configuration.clone(); } private static YAMLConfiguration loadYaml(String configurationFile) {<FILL_FUNCTION_BODY>} private static File getConfigFile(String configurationFile) { File systemFile = new File(configurationFile); if (!systemFile.exists()) { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); URL resource = currentClassLoader.getResource(configurationFile); assert resource != null; File resourceFile = new File(resource.getFile()); if (!resourceFile.exists()) { throw new IllegalArgumentException(String.format("Configuration file at '%s' does" + " not exist", configurationFile)); } return resourceFile; } return systemFile; } }
File yamlFile = getConfigFile(configurationFile); YAMLConfiguration yaml; try { Reader reader = new FileReader(yamlFile); yaml = new YAMLConfiguration(); yaml.read(reader); } catch (Exception e) { throw new RuntimeException(String.format("Failed to load configuration file," + " the file at '%s'.", configurationFile), e); } return yaml;
562
115
677
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/cypher/CypherModel.java
CypherModel
dataOf
class CypherModel { public String requestId; public Status status = new Status(); public Result result = new Result(); public static CypherModel dataOf(String requestId, List<Object> data) {<FILL_FUNCTION_BODY>} public static CypherModel failOf(String requestId, String message) { CypherModel res = new CypherModel(); res.requestId = requestId; res.status.code = 400; res.status.message = message; return res; } private CypherModel() { } public static class Status { public String message = ""; public int code; public Map<String, Object> attributes = Collections.EMPTY_MAP; } private static class Result { public List<Object> data; public Map<String, Object> meta = Collections.EMPTY_MAP; } }
CypherModel res = new CypherModel(); res.requestId = requestId; res.status.code = 200; res.result.data = data; return res;
244
54
298
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/filter/AccessLogFilter.java
AccessLogFilter
filter
class AccessLogFilter implements ContainerResponseFilter { private static final Logger LOG = Log.logger(AccessLogFilter.class); private static final String DELIMITER = "/"; private static final String GRAPHS = "graphs"; private static final String GREMLIN = "gremlin"; private static final String CYPHER = "cypher"; @Context private jakarta.inject.Provider<HugeConfig> configProvider; @Context private jakarta.inject.Provider<GraphManager> managerProvider; public static boolean needRecordLog(ContainerRequestContext context) { // TODO: add test for 'path' result ('/gremlin' or 'gremlin') String path = context.getUriInfo().getPath(); // GraphsAPI/CypherAPI/Job GremlinAPI if (path.startsWith(GRAPHS)) { if (HttpMethod.GET.equals(context.getMethod()) || path.endsWith(CYPHER)) { return true; } } // Direct GremlinAPI return path.endsWith(GREMLIN); } private String join(String path1, String path2) { return String.join(DELIMITER, path1, path2); } /** * Use filter to log request info * * @param requestContext requestContext * @param responseContext responseContext */ @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {<FILL_FUNCTION_BODY>} private boolean statusOk(int status) { return status >= 200 && status < 300; } }
// Grab corresponding request / response info from context; URI uri = requestContext.getUriInfo().getRequestUri(); String path = uri.getRawPath(); String method = requestContext.getMethod(); String metricsName = join(path, method); MetricsUtil.registerCounter(join(metricsName, METRICS_PATH_TOTAL_COUNTER)).inc(); if (statusOk(responseContext.getStatus())) { MetricsUtil.registerCounter(join(metricsName, METRICS_PATH_SUCCESS_COUNTER)).inc(); } else { MetricsUtil.registerCounter(join(metricsName, METRICS_PATH_FAILED_COUNTER)).inc(); } Object requestTime = requestContext.getProperty(REQUEST_TIME); if (requestTime != null) { long now = System.currentTimeMillis(); long start = (Long) requestTime; long executeTime = now - start; MetricsUtil.registerHistogram(join(metricsName, METRICS_PATH_RESPONSE_TIME_HISTOGRAM)) .update(executeTime); HugeConfig config = configProvider.get(); long timeThreshold = config.get(ServerOptions.SLOW_QUERY_LOG_TIME_THRESHOLD); // Record slow query if meet needs, watch out the perf if (timeThreshold > 0 && executeTime > timeThreshold && needRecordLog(requestContext)) { // TODO: set RequestBody null, handle it later & should record "client IP" LOG.info("[Slow Query] execTime={}ms, body={}, method={}, path={}, query={}", executeTime, null, method, path, uri.getQuery()); } } // Unset the context in "HugeAuthenticator", need distinguish Graph/Auth server lifecycle GraphManager manager = managerProvider.get(); // TODO: transfer Authorizer if we need after. if (manager.requireAuthentication()) { manager.unauthorize(requestContext.getSecurityContext()); }
436
526
962
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/filter/CompressInterceptor.java
CompressInterceptor
compress
class CompressInterceptor implements WriterInterceptor { public static final String GZIP = "gzip"; private static final Logger LOG = Log.logger(CompressInterceptor.class); // Set compress output buffer size to 4KB (about 40~600 vertices) public static final int BUFFER_SIZE = 1024 * 4; @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { // If there is no annotation(like exception), we don't compress it if (context.getAnnotations().length > 0) { try { this.compress(context); } catch (Throwable e) { LOG.warn("Failed to compress response", e); /* * FIXME: This will cause java.lang.IllegalStateException: * Illegal attempt to call getOutputStream() after getWriter() */ throw e; } } context.proceed(); } private void compress(WriterInterceptorContext context) throws IOException {<FILL_FUNCTION_BODY>} private static Compress getCompressAnnotation(WriterInterceptorContext c) { for (Annotation annotation : c.getAnnotations()) { if (annotation.annotationType() == Compress.class) { return (Compress) annotation; } } throw new AssertionError("Unable find @Compress annotation"); } @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface Compress { String value() default GZIP; int buffer() default BUFFER_SIZE; } }
// Get compress info from the @Compress annotation final Compress compression = getCompressAnnotation(context); final String encoding = compression.value(); final int buffer = compression.buffer(); // Update header MultivaluedMap<String, Object> headers = context.getHeaders(); headers.remove("Content-Length"); headers.add("Content-Encoding", encoding); // Replace output stream with new compression stream OutputStream output = null; if (encoding.equalsIgnoreCase(GZIP)) { output = new GZIPOutputStream(context.getOutputStream(), buffer); } else { // NOTE: Currently we just support GZIP. throw new WebApplicationException("Can't support: " + encoding); } context.setOutputStream(output);
425
195
620
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/filter/DecompressInterceptor.java
DecompressInterceptor
aroundReadFrom
class DecompressInterceptor implements ReaderInterceptor { public static final String GZIP = "gzip"; @Override public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException {<FILL_FUNCTION_BODY>} @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface Decompress { String value() default GZIP; } }
// NOTE: Currently we just support GZIP String encoding = context.getHeaders().getFirst("Content-Encoding"); if (!GZIP.equalsIgnoreCase(encoding)) { return context.proceed(); } context.setInputStream(new GZIPInputStream(context.getInputStream())); return context.proceed();
111
85
196
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/filter/ExceptionFilter.java
UnknownExceptionMapper
formatGremlinException
class UnknownExceptionMapper extends TracedExceptionMapper implements ExceptionMapper<Throwable> { @Override public Response toResponse(Throwable exception) { if (exception instanceof MultiException && ((MultiException) exception).getErrors().size() == 1) { exception = ((MultiException) exception).getErrors().get(0); } return Response.status(INTERNAL_SERVER_ERROR) .type(MediaType.APPLICATION_JSON) .entity(formatException(exception, this.trace())) .build(); } } public static String formatException(Throwable exception, boolean trace) { String clazz = exception.getClass().toString(); String message = exception.getMessage() != null ? exception.getMessage() : ""; String cause = exception.getCause() != null ? exception.getCause().toString() : ""; JsonObjectBuilder json = Json.createObjectBuilder() .add("exception", clazz) .add("message", message) .add("cause", cause); if (trace) { JsonArrayBuilder traces = Json.createArrayBuilder(); for (StackTraceElement i : exception.getStackTrace()) { traces.add(i.toString()); } json.add("trace", traces); } return json.build().toString(); } public static String formatGremlinException(HugeGremlinException exception, boolean trace) {<FILL_FUNCTION_BODY>
Map<String, Object> map = exception.response(); String message = (String) map.get("message"); String exClassName = (String) map.get("Exception-Class"); @SuppressWarnings("unchecked") List<String> exceptions = (List<String>) map.get("exceptions"); String stackTrace = (String) map.get("stackTrace"); message = message != null ? message : ""; exClassName = exClassName != null ? exClassName : ""; String cause = exceptions != null ? exceptions.toString() : ""; JsonObjectBuilder json = Json.createObjectBuilder() .add("exception", exClassName) .add("message", message) .add("cause", cause); if (trace && stackTrace != null) { JsonArrayBuilder traces = Json.createArrayBuilder(); for (String part : StringUtils.split(stackTrace, '\n')) { traces.add(part); } json.add("trace", traces); } return json.build().toString();
372
268
640
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/filter/LoadDetectFilter.java
LoadDetectFilter
filter
class LoadDetectFilter implements ContainerRequestFilter { private static final Set<String> WHITE_API_LIST = ImmutableSet.of( "", "apis", "metrics", "versions" ); // Call gc every 30+ seconds if memory is low and request frequently private static final RateLimiter GC_RATE_LIMITER = RateLimiter.create(1.0 / 30); @Context private jakarta.inject.Provider<HugeConfig> configProvider; @Context private jakarta.inject.Provider<WorkLoad> loadProvider; @Override public void filter(ContainerRequestContext context) {<FILL_FUNCTION_BODY>} public static boolean isWhiteAPI(ContainerRequestContext context) { List<PathSegment> segments = context.getUriInfo().getPathSegments(); E.checkArgument(!segments.isEmpty(), "Invalid request uri '%s'", context.getUriInfo().getPath()); String rootPath = segments.get(0).getPath(); return WHITE_API_LIST.contains(rootPath); } private static void gcIfNeeded() { if (GC_RATE_LIMITER.tryAcquire(1)) { System.gc(); } } }
if (LoadDetectFilter.isWhiteAPI(context)) { return; } HugeConfig config = this.configProvider.get(); int maxWorkerThreads = config.get(ServerOptions.MAX_WORKER_THREADS); WorkLoad load = this.loadProvider.get(); // There will be a thread doesn't work, dedicated to statistics if (load.incrementAndGet() >= maxWorkerThreads) { throw new ServiceUnavailableException(String.format( "The server is too busy to process the request, " + "you can config %s to adjust it or try again later", ServerOptions.MAX_WORKER_THREADS.name())); } long minFreeMemory = config.get(ServerOptions.MIN_FREE_MEMORY); long allocatedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long presumableFreeMem = (Runtime.getRuntime().maxMemory() - allocatedMem) / Bytes.MB; if (presumableFreeMem < minFreeMemory) { gcIfNeeded(); throw new ServiceUnavailableException(String.format( "The server available memory %s(MB) is below than " + "threshold %s(MB) and can't process the request, " + "you can config %s to adjust it or try again later", presumableFreeMem, minFreeMemory, ServerOptions.MIN_FREE_MEMORY.name())); }
337
375
712
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/filter/LoadReleaseFilter.java
LoadReleaseFilter
filter
class LoadReleaseFilter implements ContainerResponseFilter { @Context private jakarta.inject.Provider<WorkLoad> loadProvider; @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {<FILL_FUNCTION_BODY>} }
if (LoadDetectFilter.isWhiteAPI(requestContext)) { return; } WorkLoad load = this.loadProvider.get(); load.decrementAndGet();
76
51
127
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/filter/PathFilter.java
PathFilter
filter
class PathFilter implements ContainerRequestFilter { public static final String REQUEST_TIME = "request_time"; public static final String REQUEST_PARAMS_JSON = "request_params_json"; @Override public void filter(ContainerRequestContext context) throws IOException {<FILL_FUNCTION_BODY>} }
context.setProperty(REQUEST_TIME, System.currentTimeMillis()); // TODO: temporarily comment it to fix loader bug, handle it later /*// record the request json String method = context.getMethod(); String requestParamsJson = ""; if (method.equals(HttpMethod.POST)) { requestParamsJson = IOUtils.toString(context.getEntityStream(), Charsets.toCharset(CHARSET)); // replace input stream because we have already read it InputStream in = IOUtils.toInputStream(requestParamsJson, Charsets.toCharset(CHARSET)); context.setEntityStream(in); } else if (method.equals(HttpMethod.GET)) { MultivaluedMap<String, String> pathParameters = context.getUriInfo() .getPathParameters(); requestParamsJson = pathParameters.toString(); } context.setProperty(REQUEST_PARAMS_JSON, requestParamsJson);*/
81
234
315
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/filter/RedirectFilter.java
RedirectFilter
forwardRequest
class RedirectFilter implements ContainerRequestFilter { private static final Logger LOG = Log.logger(RedirectFilter.class); private static final String X_HG_REDIRECT = "x-hg-redirect"; private static volatile Client client = null; @Context private IterableProvider<GraphManager> managerProvider; private static final Set<String> MUST_BE_NULL = new HashSet<>(); static { MUST_BE_NULL.add("DELETE"); MUST_BE_NULL.add("GET"); MUST_BE_NULL.add("HEAD"); MUST_BE_NULL.add("TRACE"); } @Override public void filter(ContainerRequestContext context) throws IOException { ServiceHandle<GraphManager> handle = this.managerProvider.getHandle(); E.checkState(handle != null, "Context GraphManager is absent"); GraphManager manager = handle.getService(); E.checkState(manager != null, "Context GraphManager is absent"); String redirectTag = context.getHeaderString(X_HG_REDIRECT); if (StringUtils.isNotEmpty(redirectTag)) { return; } GlobalMasterInfo globalNodeInfo = manager.globalNodeRoleInfo(); if (globalNodeInfo == null || !globalNodeInfo.supportElection()) { return; } GlobalMasterInfo.NodeInfo masterInfo = globalNodeInfo.masterInfo(); if (masterInfo == null || masterInfo.isMaster() || StringUtils.isEmpty(masterInfo.nodeUrl())) { return; } String url = masterInfo.nodeUrl(); URI redirectUri; try { URIBuilder redirectURIBuilder = new URIBuilder(context.getUriInfo().getRequestUri()); URI masterURI = URI.create(url); redirectURIBuilder.setHost(masterURI.getHost()); redirectURIBuilder.setPort(masterURI.getPort()); redirectURIBuilder.setScheme(masterURI.getScheme()); redirectUri = redirectURIBuilder.build(); } catch (URISyntaxException e) { LOG.error("Redirect request exception occurred", e); return; } this.initClientIfNeeded(); Response response = this.forwardRequest(context, redirectUri); context.abortWith(response); } private Response forwardRequest(ContainerRequestContext requestContext, URI redirectUri) {<FILL_FUNCTION_BODY>} private void initClientIfNeeded() { if (client != null) { return; } synchronized (RedirectFilter.class) { if (client != null) { return; } client = ClientBuilder.newClient(); } } @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface RedirectMasterRole { } }
MultivaluedMap<String, String> headers = requestContext.getHeaders(); MultivaluedMap<String, Object> newHeaders = HeaderUtils.createOutbound(); if (headers != null) { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { for (String value : entry.getValue()) { newHeaders.add(entry.getKey(), value); } } } newHeaders.add(X_HG_REDIRECT, new Date().getTime()); Invocation.Builder builder = client.target(redirectUri) .request() .headers(newHeaders); Response response; if (MUST_BE_NULL.contains(requestContext.getMethod())) { response = builder.method(requestContext.getMethod()); } else { response = builder.method(requestContext.getMethod(), Entity.json(requestContext.getEntityStream())); } return response;
727
244
971
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/filter/StatusFilter.java
StatusFilter
filter
class StatusFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {<FILL_FUNCTION_BODY>} @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface Status { int OK = 200; int CREATED = 201; int ACCEPTED = 202; int value(); } }
if (responseContext.getStatus() == 200) { for (Annotation i : responseContext.getEntityAnnotations()) { if (i instanceof Status) { responseContext.setStatus(((Status) i).value()); break; } } }
122
72
194
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/graph/BatchAPI.java
JsonElement
updateExistElement
class JsonElement implements Checkable { @JsonProperty("id") public Object id; @JsonProperty("label") public String label; @JsonProperty("properties") public Map<String, Object> properties; @JsonProperty("type") public String type; @Override public abstract void checkCreate(boolean isBatch); @Override public abstract void checkUpdate(); protected abstract Object[] properties(); } protected void updateExistElement(JsonElement oldElement, JsonElement newElement, Map<String, UpdateStrategy> strategies) {<FILL_FUNCTION_BODY>
if (oldElement == null) { return; } E.checkArgument(newElement != null, "The json element can't be null"); for (Map.Entry<String, UpdateStrategy> kv : strategies.entrySet()) { String key = kv.getKey(); UpdateStrategy updateStrategy = kv.getValue(); if (oldElement.properties.get(key) != null && newElement.properties.get(key) != null) { Object value = updateStrategy.checkAndUpdateProperty( oldElement.properties.get(key), newElement.properties.get(key)); newElement.properties.put(key, value); } else if (oldElement.properties.get(key) != null && newElement.properties.get(key) == null) { // If new property is null & old is present, use old property newElement.properties.put(key, oldElement.properties.get(key)); } }
155
246
401
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/gremlin/AbstractJerseyRestClient.java
AbstractJerseyRestClient
cleanThreadPoolExecutor
class AbstractJerseyRestClient { /** * Time unit: hour */ private static final long TTL = 24L; /** * Time unit: ms */ private static final long IDLE_TIME = 40L * 1000L; private static final String PROPERTY_MAX_TOTAL = "maxTotal"; private static final String PROPERTY_MAX_PER_ROUTE = "maxPerRoute"; private static final String PROPERTY_IDLE_TIME = "idleTime"; private static final String CONNECTION_MANAGER = ApacheClientProperties.CONNECTION_MANAGER; private final Client client; private final WebTarget webTarget; private final PoolingHttpClientConnectionManager pool; private ScheduledExecutorService cleanExecutor; public AbstractJerseyRestClient(String url, int timeout, int maxTotal, int maxPerRoute) { this(url, new ConfigBuilder().configTimeout(timeout) .configPool(maxTotal, maxPerRoute) .build()); } public AbstractJerseyRestClient(String url, ClientConfig config) { this.pool = configConnectionManager(config); this.client = JerseyClientBuilder.newClient(config); this.client.register(GZipEncoder.class); this.webTarget = this.client.target(url); cleanThreadPoolExecutor(config); } private static PoolingHttpClientConnectionManager configConnectionManager(ClientConfig conf) { /* * Using httpclient with connection pooling, and configuring the * jersey connector. But the jersey that has been released in the maven central * repository seems to have a bug: https://github.com/jersey/jersey/pull/3752 */ PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(TTL, TimeUnit.HOURS); Integer maxTotal = (Integer) conf.getProperty(PROPERTY_MAX_TOTAL); Integer maxPerRoute = (Integer) conf.getProperty(PROPERTY_MAX_PER_ROUTE); if (maxTotal != null) { pool.setMaxTotal(maxTotal); } if (maxPerRoute != null) { pool.setDefaultMaxPerRoute(maxPerRoute); } conf.property(CONNECTION_MANAGER, pool); conf.connectorProvider(new ApacheConnectorProvider()); return pool; } private void cleanThreadPoolExecutor(ClientConfig config) {<FILL_FUNCTION_BODY>} protected WebTarget getWebTarget() { return this.webTarget; } public void close() { try { if (this.pool != null) { this.pool.close(); this.cleanExecutor.shutdownNow(); } } finally { this.client.close(); } } private static class ConfigBuilder { private final ClientConfig config; ConfigBuilder() { this.config = new ClientConfig(); } public ConfigBuilder configTimeout(int timeout) { this.config.property(ClientProperties.CONNECT_TIMEOUT, timeout); this.config.property(ClientProperties.READ_TIMEOUT, timeout); return this; } public ConfigBuilder configPool(int maxTotal, int maxPerRoute) { this.config.property(PROPERTY_MAX_TOTAL, maxTotal); this.config.property(PROPERTY_MAX_PER_ROUTE, maxPerRoute); return this; } public ClientConfig build() { return this.config; } } }
this.cleanExecutor = ExecutorUtil.newScheduledThreadPool("conn-clean-worker-%d"); Number idleTimeProp = (Number) config.getProperty(PROPERTY_IDLE_TIME); final long idleTime = idleTimeProp == null ? IDLE_TIME : idleTimeProp.longValue(); final long checkPeriod = idleTime / 2L; this.cleanExecutor.scheduleWithFixedDelay(() -> { PoolStats stats = this.pool.getTotalStats(); int using = stats.getLeased() + stats.getPending(); if (using > 0) { // Do clean only when all connections are idle return; } // Release connections when all clients are inactive this.pool.closeIdleConnections(idleTime, TimeUnit.MILLISECONDS); this.pool.closeExpiredConnections(); }, checkPeriod, checkPeriod, TimeUnit.MILLISECONDS);
926
233
1,159
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/gremlin/GremlinAPI.java
GremlinAPI
post
class GremlinAPI extends GremlinQueryAPI { private static final Histogram GREMLIN_INPUT_HISTOGRAM = MetricsUtil.registerHistogram(GremlinAPI.class, "gremlin-input"); private static final Histogram GREMLIN_OUTPUT_HISTOGRAM = MetricsUtil.registerHistogram(GremlinAPI.class, "gremlin-output"); @POST @Timed @Compress @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) public Response post(@Context HugeConfig conf, @Context HttpHeaders headers, String request) {<FILL_FUNCTION_BODY>} @GET @Timed @Compress(buffer = (1024 * 40)) @Produces(APPLICATION_JSON_WITH_CHARSET) public Response get(@Context HugeConfig conf, @Context HttpHeaders headers, @Context UriInfo uriInfo) { String auth = headers.getHeaderString(HttpHeaders.AUTHORIZATION); String query = uriInfo.getRequestUri().getRawQuery(); E.checkArgumentNotNull(query, "The request query can't be empty"); MultivaluedMap<String, String> params = uriInfo.getQueryParameters(); Response response = this.client().doGetRequest(auth, params); GREMLIN_INPUT_HISTOGRAM.update(query.length()); GREMLIN_OUTPUT_HISTOGRAM.update(response.getLength()); return transformResponseIfNeeded(response); } }
/* The following code is reserved for forwarding request */ // context.getRequestDispatcher(location).forward(request, response); // return Response.seeOther(UriBuilder.fromUri(location).build()) // .build(); // Response.temporaryRedirect(UriBuilder.fromUri(location).build()) // .build(); String auth = headers.getHeaderString(HttpHeaders.AUTHORIZATION); Response response = this.client().doPostRequest(auth, request); GREMLIN_INPUT_HISTOGRAM.update(request.length()); GREMLIN_OUTPUT_HISTOGRAM.update(response.getLength()); return transformResponseIfNeeded(response);
414
176
590
<methods>public non-sealed void <init>() ,public org.apache.hugegraph.api.gremlin.GremlinClient client() <variables>private static final Set<java.lang.String> BAD_REQUEST_EXCEPTIONS,private static final Set<java.lang.String> FORBIDDEN_REQUEST_EXCEPTIONS,private org.apache.hugegraph.api.gremlin.GremlinClient client,private Provider<HugeConfig> configProvider
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/gremlin/GremlinClient.java
GremlinClient
doPostRequest
class GremlinClient extends AbstractJerseyRestClient { /** * Constructs a GremlinClient with the specified URL, timeout, maxTotal, and maxPerRoute. * * @param url The URL of the Gremlin server this client will interact with. * @param timeout The timeout for the client. * @param maxTotal The maximum total connections for the client. * @param maxPerRoute The maximum connections per route for the client. */ public GremlinClient(String url, int timeout, int maxTotal, int maxPerRoute) { super(url, timeout, maxTotal, maxPerRoute); } /** * Sends a POST request to the Gremlin server. * * @param auth The authorization token for the request. * @param req The body of the request. * @return The response from the server. */ public Response doPostRequest(String auth, String req) {<FILL_FUNCTION_BODY>} /** * Sends a GET request to the Gremlin server. * * @param auth The authorization token for the request. * @param params The query parameters for the request. * @return The response from the server. */ public Response doGetRequest(String auth, MultivaluedMap<String, String> params) { WebTarget target = this.getWebTarget(); for (Map.Entry<String, List<String>> entry : params.entrySet()) { E.checkArgument(entry.getValue().size() == 1, "Invalid query param '%s', can only accept one value, but got %s", entry.getKey(), entry.getValue()); target = target.queryParam(entry.getKey(), entry.getValue().get(0)); } return target.request() .header(HttpHeaders.AUTHORIZATION, auth) .accept(MediaType.APPLICATION_JSON) .acceptEncoding(CompressInterceptor.GZIP) .get(); } }
Entity<?> body = Entity.entity(req, MediaType.APPLICATION_JSON); return this.getWebTarget().request() .header(HttpHeaders.AUTHORIZATION, auth) .accept(MediaType.APPLICATION_JSON) .acceptEncoding(CompressInterceptor.GZIP) .post(body);
504
92
596
<methods>public void <init>(java.lang.String, int, int, int) ,public void <init>(java.lang.String, ClientConfig) ,public void close() <variables>private static final java.lang.String CONNECTION_MANAGER,private static final long IDLE_TIME,private static final java.lang.String PROPERTY_IDLE_TIME,private static final java.lang.String PROPERTY_MAX_PER_ROUTE,private static final java.lang.String PROPERTY_MAX_TOTAL,private static final long TTL,private java.util.concurrent.ScheduledExecutorService cleanExecutor,private final non-sealed Client client,private final non-sealed PoolingHttpClientConnectionManager pool,private final non-sealed WebTarget webTarget
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/gremlin/GremlinQueryAPI.java
GremlinQueryAPI
transformResponseIfNeeded
class GremlinQueryAPI extends API { private static final Set<String> FORBIDDEN_REQUEST_EXCEPTIONS = ImmutableSet.of("java.lang.SecurityException", "jakarta.ws.rs.ForbiddenException"); private static final Set<String> BAD_REQUEST_EXCEPTIONS = ImmutableSet.of( "java.lang.IllegalArgumentException", "java.util.concurrent.TimeoutException", "groovy.lang.", "org.codehaus.", "org.apache.hugegraph." ); @Context private Provider<HugeConfig> configProvider; private GremlinClient client; public GremlinClient client() { if (this.client != null) { return this.client; } HugeConfig config = this.configProvider.get(); String url = config.get(ServerOptions.GREMLIN_SERVER_URL); int timeout = config.get(ServerOptions.GREMLIN_SERVER_TIMEOUT) * 1000; int maxRoutes = config.get(ServerOptions.GREMLIN_SERVER_MAX_ROUTE); this.client = new GremlinClient(url, timeout, maxRoutes, maxRoutes); return this.client; } protected static Response transformResponseIfNeeded(Response response) {<FILL_FUNCTION_BODY>} private static boolean matchBadRequestException(String exClass) { if (exClass == null) { return false; } if (BAD_REQUEST_EXCEPTIONS.contains(exClass)) { return true; } return BAD_REQUEST_EXCEPTIONS.stream().anyMatch(exClass::startsWith); } }
MediaType mediaType = response.getMediaType(); if (mediaType != null) { // Append charset assert MediaType.APPLICATION_JSON_TYPE.equals(mediaType); response.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mediaType.withCharset(CHARSET)); } Response.StatusType status = response.getStatusInfo(); if (status.getStatusCode() < 400) { // No need to transform if normal response without error return response; } if (mediaType == null || !JSON.equals(mediaType.getSubtype())) { String message = response.readEntity(String.class); throw new HugeGremlinException(status.getStatusCode(), ImmutableMap.of("message", message)); } @SuppressWarnings("unchecked") Map<String, Object> map = response.readEntity(Map.class); String exClassName = (String) map.get("Exception-Class"); if (FORBIDDEN_REQUEST_EXCEPTIONS.contains(exClassName)) { status = Response.Status.FORBIDDEN; } else if (matchBadRequestException(exClassName)) { status = Response.Status.BAD_REQUEST; } throw new HugeGremlinException(status.getStatusCode(), map);
449
346
795
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/job/AlgorithmAPI.java
AlgorithmAPI
post
class AlgorithmAPI extends API { private static final Logger LOG = Log.logger(RestServer.class); @POST @Timed @Path("/{name}") @Status(Status.CREATED) @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) @RedirectFilter.RedirectMasterRole public Map<String, Id> post(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("name") String algorithm, Map<String, Object> parameters) {<FILL_FUNCTION_BODY>} }
LOG.debug("Graph [{}] schedule algorithm job: {}", graph, parameters); E.checkArgument(algorithm != null && !algorithm.isEmpty(), "The algorithm name can't be empty"); if (parameters == null) { parameters = ImmutableMap.of(); } if (!AlgorithmJob.check(algorithm, parameters)) { throw new NotFoundException("Not found algorithm: " + algorithm); } HugeGraph g = graph(manager, graph); Map<String, Object> input = ImmutableMap.of("algorithm", algorithm, "parameters", parameters); JobBuilder<Object> builder = JobBuilder.of(g); builder.name("algorithm:" + algorithm) .input(JsonUtil.toJson(input)) .job(new AlgorithmJob()); return ImmutableMap.of("task_id", builder.schedule().id());
158
219
377
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/job/ComputerAPI.java
ComputerAPI
post
class ComputerAPI extends API { private static final Logger LOG = Log.logger(ComputerAPI.class); @POST @Timed @Path("/{name}") @Status(Status.CREATED) @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) @RedirectFilter.RedirectMasterRole public Map<String, Id> post(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("name") String computer, Map<String, Object> parameters) {<FILL_FUNCTION_BODY>} }
LOG.debug("Graph [{}] schedule computer job: {}", graph, parameters); E.checkArgument(computer != null && !computer.isEmpty(), "The computer name can't be empty"); if (parameters == null) { parameters = ImmutableMap.of(); } if (!ComputerJob.check(computer, parameters)) { throw new NotFoundException("Not found computer: " + computer); } HugeGraph g = graph(manager, graph); Map<String, Object> input = ImmutableMap.of("computer", computer, "parameters", parameters); JobBuilder<Object> builder = JobBuilder.of(g); builder.name("computer:" + computer) .input(JsonUtil.toJson(input)) .job(new ComputerJob()); HugeTask<Object> task = builder.schedule(); return ImmutableMap.of("task_id", task.id());
159
236
395
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/job/GremlinAPI.java
GremlinRequest
name
class GremlinRequest implements Checkable { // See org.apache.tinkerpop.gremlin.server.channel.HttpChannelizer @JsonProperty private String gremlin; @JsonProperty private Map<String, Object> bindings = new HashMap<>(); @JsonProperty private String language = "gremlin-groovy"; @JsonProperty private Map<String, String> aliases = new HashMap<>(); public String gremlin() { return this.gremlin; } public void gremlin(String gremlin) { this.gremlin = gremlin; } public Map<String, Object> bindings() { return this.bindings; } public void bindings(Map<String, Object> bindings) { this.bindings = bindings; } public void binding(String name, Object value) { this.bindings.put(name, value); } public String language() { return this.language; } public void language(String language) { this.language = language; } public Map<String, String> aliases() { return this.aliases; } public void aliases(Map<String, String> aliases) { this.aliases = aliases; } public void aliase(String key, String value) { this.aliases.put(key, value); } public String name() {<FILL_FUNCTION_BODY>} @Override public void checkCreate(boolean isBatch) { E.checkArgumentNotNull(this.gremlin, "The gremlin parameter can't be null"); E.checkArgumentNotNull(this.language, "The language parameter can't be null"); E.checkArgument(this.aliases == null || this.aliases.isEmpty(), "There is no need to pass gremlin aliases"); } public String toJson() { Map<String, Object> map = new HashMap<>(); map.put("gremlin", this.gremlin); map.put("bindings", this.bindings); map.put("language", this.language); map.put("aliases", this.aliases); return JsonUtil.toJson(map); } public static GremlinRequest fromJson(String json) { @SuppressWarnings("unchecked") Map<String, Object> map = JsonUtil.fromJson(json, Map.class); String gremlin = (String) map.get("gremlin"); @SuppressWarnings("unchecked") Map<String, Object> bindings = (Map<String, Object>) map.get("bindings"); String language = (String) map.get("language"); @SuppressWarnings("unchecked") Map<String, String> aliases = (Map<String, String>) map.get("aliases"); GremlinRequest request = new GremlinRequest(); request.gremlin(gremlin); request.bindings(bindings); request.language(language); request.aliases(aliases); return request; } }
// Get the first line of script as the name String firstLine = this.gremlin.split("\r\n|\r|\n", 2)[0]; final Charset charset = Charset.forName(CHARSET); final byte[] bytes = firstLine.getBytes(charset); if (bytes.length <= MAX_NAME_LENGTH) { return firstLine; } CharsetDecoder decoder = charset.newDecoder(); decoder.onMalformedInput(CodingErrorAction.IGNORE); decoder.reset(); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, MAX_NAME_LENGTH); try { return decoder.decode(buffer).toString(); } catch (CharacterCodingException e) { throw new HugeException("Failed to decode truncated bytes of " + "gremlin first line", e); }
827
227
1,054
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/job/RebuildAPI.java
RebuildAPI
edgeLabelRebuild
class RebuildAPI extends API { private static final Logger LOG = Log.logger(RebuildAPI.class); @PUT @Timed @Path("vertexlabels/{name}") @Status(Status.ACCEPTED) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin", "$owner=$graph $action=index_write"}) @RedirectFilter.RedirectMasterRole public Map<String, Id> vertexLabelRebuild(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("name") String name) { LOG.debug("Graph [{}] rebuild vertex label: {}", graph, name); HugeGraph g = graph(manager, graph); return ImmutableMap.of("task_id", g.schema().vertexLabel(name).rebuildIndex()); } @PUT @Timed @Path("edgelabels/{name}") @Status(Status.ACCEPTED) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin", "$owner=$graph $action=index_write"}) @RedirectFilter.RedirectMasterRole public Map<String, Id> edgeLabelRebuild(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("name") String name) {<FILL_FUNCTION_BODY>} @PUT @Timed @Path("indexlabels/{name}") @Status(Status.ACCEPTED) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin", "$owner=$graph $action=index_write"}) @RedirectFilter.RedirectMasterRole public Map<String, Id> indexLabelRebuild(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("name") String name) { LOG.debug("Graph [{}] rebuild index label: {}", graph, name); HugeGraph g = graph(manager, graph); return ImmutableMap.of("task_id", g.schema().indexLabel(name).rebuild()); } }
LOG.debug("Graph [{}] rebuild edge label: {}", graph, name); HugeGraph g = graph(manager, graph); return ImmutableMap.of("task_id", g.schema().edgeLabel(name).rebuildIndex());
554
65
619
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/job/TaskAPI.java
TaskAPI
list
class TaskAPI extends API { private static final Logger LOG = Log.logger(TaskAPI.class); private static final long NO_LIMIT = -1L; public static final String ACTION_CANCEL = "cancel"; @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) public Map<String, Object> list(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("status") String status, @QueryParam("ids") List<Long> ids, @QueryParam("limit") @DefaultValue("100") long limit, @QueryParam("page") String page) {<FILL_FUNCTION_BODY>} @GET @Timed @Path("{id}") @Produces(APPLICATION_JSON_WITH_CHARSET) public Map<String, Object> get(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") long id) { LOG.debug("Graph [{}] get task: {}", graph, id); TaskScheduler scheduler = graph(manager, graph).taskScheduler(); return scheduler.task(IdGenerator.of(id)).asMap(); } @DELETE @Timed @Path("{id}") @RedirectFilter.RedirectMasterRole public void delete(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") long id) { LOG.debug("Graph [{}] delete task: {}", graph, id); TaskScheduler scheduler = graph(manager, graph).taskScheduler(); HugeTask<?> task = scheduler.delete(IdGenerator.of(id)); E.checkArgument(task != null, "There is no task with id '%s'", id); } @PUT @Timed @Path("{id}") @Status(Status.ACCEPTED) @Produces(APPLICATION_JSON_WITH_CHARSET) @RedirectFilter.RedirectMasterRole public Map<String, Object> update(@Context GraphManager manager, @PathParam("graph") String graph, @PathParam("id") long id, @QueryParam("action") String action) { LOG.debug("Graph [{}] cancel task: {}", graph, id); if (!ACTION_CANCEL.equals(action)) { throw new NotSupportedException(String.format( "Not support action '%s'", action)); } TaskScheduler scheduler = graph(manager, graph).taskScheduler(); HugeTask<?> task = scheduler.task(IdGenerator.of(id)); if (!task.completed() && !task.cancelling()) { scheduler.cancel(task); if (task.cancelling() || task.cancelled()) { return task.asMap(); } } assert task.completed() || task.cancelling(); throw new BadRequestException(String.format( "Can't cancel task '%s' which is completed or cancelling", id)); } private static TaskStatus parseStatus(String status) { try { return TaskStatus.valueOf(status.toUpperCase()); } catch (Exception e) { throw new IllegalArgumentException(String.format( "Status value must be in %s, but got '%s'", Arrays.asList(TaskStatus.values()), status)); } } }
LOG.debug("Graph [{}] list tasks with status {}, ids {}, " + "limit {}, page {}", graph, status, ids, limit, page); TaskScheduler scheduler = graph(manager, graph).taskScheduler(); Iterator<HugeTask<Object>> iter; if (!ids.isEmpty()) { E.checkArgument(status == null, "Not support status when query task by ids, " + "but got status='%s'", status); E.checkArgument(page == null, "Not support page when query task by ids, " + "but got page='%s'", page); // Set limit to NO_LIMIT to ignore limit when query task by ids limit = NO_LIMIT; List<Id> idList = ids.stream().map(IdGenerator::of) .collect(Collectors.toList()); iter = scheduler.tasks(idList); } else { if (status == null) { iter = scheduler.tasks(null, limit, page); } else { iter = scheduler.tasks(parseStatus(status), limit, page); } } List<Object> tasks = new ArrayList<>(); while (iter.hasNext()) { tasks.add(iter.next().asMap(false)); } if (limit != NO_LIMIT && tasks.size() > limit) { tasks = tasks.subList(0, (int) limit); } if (page == null) { return Maps.of("tasks", tasks); } else { return Maps.of("tasks", tasks, "page", PageInfo.pageInfo(iter)); }
889
433
1,322
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/profile/ProfileAPI.java
ProfileAPI
showAllAPIs
class ProfileAPI { private static final String SERVICE = "hugegraph"; private static final String DOC = "https://hugegraph.apache.org/docs/"; private static final String API_DOC = DOC + "clients/"; private static final String SWAGGER_UI = "/swagger-ui/index.html"; private static String SERVER_PROFILES = null; private static String API_PROFILES = null; @GET @Timed @Produces(MediaType.APPLICATION_JSON) public String getProfile(@Context HugeConfig conf, @Context Application application) { // May init multi times by multi threads, but no effect on the results if (SERVER_PROFILES != null) { return SERVER_PROFILES; } Map<String, Object> profiles = InsertionOrderUtil.newMap(); profiles.put("service", SERVICE); profiles.put("version", CoreVersion.VERSION.toString()); profiles.put("doc", DOC); profiles.put("api_doc", API_DOC); profiles.put("swagger_ui", conf.get(ServerOptions.REST_SERVER_URL) + SWAGGER_UI); Set<String> apis = new TreeSet<>(); for (Class<?> clazz : application.getClasses()) { if (!isAnnotatedPathClass(clazz)) { continue; } Resource resource = Resource.from(clazz); APICategory apiCategory = APICategory.parse(resource.getName()); apis.add(apiCategory.dir); } profiles.put("apis", apis); SERVER_PROFILES = JsonUtil.toJson(profiles); return SERVER_PROFILES; } @GET @Path("apis") @Timed @Produces(MediaType.APPLICATION_JSON) public String showAllAPIs(@Context Application application) {<FILL_FUNCTION_BODY>} private static boolean isAnnotatedPathClass(Class<?> clazz) { if (clazz.isAnnotationPresent(Path.class)) { return true; } for (Class<?> i : clazz.getInterfaces()) { if (i.isAnnotationPresent(Path.class)) { return true; } } return false; } private static class APIProfiles { @JsonProperty("apis") private final Map<String, Map<String, List<APIProfile>>> apis; public APIProfiles() { this.apis = new TreeMap<>(); } public void put(APICategory category, APIProfile profile) { Map<String, List<APIProfile>> categories; categories = this.apis.computeIfAbsent(category.dir, k -> new TreeMap<>()); List<APIProfile> profiles = categories.computeIfAbsent( category.category, k -> new ArrayList<>()); profiles.add(profile); } } private static class APIProfile { @JsonProperty("url") private final String url; @JsonProperty("method") private final String method; @JsonProperty("parameters") private final List<ParamInfo> parameters; public APIProfile(String url, String method, List<ParamInfo> parameters) { this.url = url; this.method = method; this.parameters = parameters; } public static APIProfile parse(String url, ResourceMethod resource) { String method = resource.getHttpMethod(); List<ParamInfo> params = new ArrayList<>(); for (Parameter param : resource.getInvocable().getParameters()) { if (param.getSource() == Source.QUERY) { String name = param.getSourceName(); String type = param.getType().getTypeName(); String defaultValue = param.getDefaultValue(); params.add(new ParamInfo(name, type, defaultValue)); } else if (param.getSource() == Source.ENTITY) { String type = param.getType().getTypeName(); params.add(new ParamInfo("body", type)); } } return new APIProfile(url, method, params); } private static class ParamInfo { @JsonProperty("name") private final String name; @JsonProperty("type") private final String type; @JsonProperty("default_value") private final String defaultValue; public ParamInfo(String name, String type) { this(name, type, null); } public ParamInfo(String name, String type, String defaultValue) { this.name = name; this.type = type; this.defaultValue = defaultValue; } } } private static class APICategory { private final String dir; private final String category; public APICategory(String dir, String category) { this.dir = dir; this.category = category; } public static APICategory parse(String fullName) { String[] parts = StringUtils.split(fullName, "."); E.checkState(parts.length >= 2, "Invalid api name"); String dir = parts[parts.length - 2]; String category = parts[parts.length - 1]; return new APICategory(dir, category); } } }
if (API_PROFILES != null) { return API_PROFILES; } APIProfiles apiProfiles = new APIProfiles(); for (Class<?> clazz : application.getClasses()) { if (!isAnnotatedPathClass(clazz)) { continue; } Resource resource = Resource.from(clazz); APICategory apiCategory = APICategory.parse(resource.getName()); String url = resource.getPath(); // List all methods of this resource for (ResourceMethod rm : resource.getResourceMethods()) { APIProfile profile = APIProfile.parse(url, rm); apiProfiles.put(apiCategory, profile); } // List all methods of this resource's child resources for (Resource childResource : resource.getChildResources()) { String childUrl = url + "/" + childResource.getPath(); for (ResourceMethod rm : childResource.getResourceMethods()) { APIProfile profile = APIProfile.parse(childUrl, rm); apiProfiles.put(apiCategory, profile); } } } API_PROFILES = JsonUtil.toJson(apiProfiles); return API_PROFILES;
1,369
306
1,675
<no_super_class>
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/profile/VersionAPI.java
VersionAPI
list
class VersionAPI extends API { @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) @PermitAll public Object list() {<FILL_FUNCTION_BODY>} }
Map<String, String> versions = ImmutableMap.of("version", "v1", "core", CoreVersion.VERSION.toString(), "gremlin", CoreVersion.GREMLIN_VERSION, "api", ApiVersion.VERSION.toString()); return ImmutableMap.of("versions", versions);
61
83
144
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/profile/WhiteIpListAPI.java
WhiteIpListAPI
updateWhiteIPs
class WhiteIpListAPI extends API { private static final Logger LOG = Log.logger(WhiteIpListAPI.class); @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed("admin") @Operation(summary = "list white ips") public Map<String, Object> list(@Context GraphManager manager) { LOG.debug("List white ips"); AuthManager authManager = manager.authManager(); Set<String> whiteIpList = authManager.listWhiteIPs(); return ImmutableMap.of("whiteIpList", whiteIpList); } @POST @Timed @StatusFilter.Status(StatusFilter.Status.ACCEPTED) @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed("admin") @Operation(summary = "update white ip list") public Map<String, Object> updateWhiteIPs(@Context GraphManager manager, Map<String, Object> actionMap) {<FILL_FUNCTION_BODY>} @PUT @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed("admin") @Operation(summary = "enable/disable the white ip list") public Map<String, Object> updateStatus(@Context GraphManager manager, @QueryParam("status") String status) { LOG.debug("Enable or disable white ip list"); E.checkArgument("true".equals(status) || "false".equals(status), "Invalid status, valid status is 'true' or 'false'"); boolean open = Boolean.parseBoolean(status); manager.authManager().enabledWhiteIpList(open); Map<String, Object> map = new HashMap<>(); map.put("WhiteIpListOpen", open); return map; } private boolean checkIp(String ipStr) { String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"; Pattern pattern = Pattern.compile(ip); Matcher matcher = pattern.matcher(ipStr); return matcher.matches(); } }
E.checkArgument(actionMap != null, "Missing argument: actionMap"); Set<String> whiteIpList = manager.authManager().listWhiteIPs(); Object ipListRaw = actionMap.get("ips"); E.checkArgument(ipListRaw instanceof List, "Invalid ips type '%s', must be list", ipListRaw.getClass()); List<String> ipList = (List<String>) ipListRaw; Object actionRaw = actionMap.get("action"); E.checkArgument(actionRaw != null, "Missing argument: action"); E.checkArgument(actionRaw instanceof String, "Invalid action type '%s', must be string", actionRaw.getClass()); String action = (String) actionRaw; E.checkArgument(StringUtils.isNotEmpty(action), "Missing argument: action"); Set<String> existedIPs = new HashSet<>(); Set<String> loadedIPs = new HashSet<>(); Set<String> illegalIPs = new HashSet<>(); Map<String, Object> result = new HashMap<>(); for (String ip : ipList) { if (whiteIpList.contains(ip)) { existedIPs.add(ip); continue; } if ("load".equals(action)) { boolean rightIp = checkIp(ip) ? loadedIPs.add(ip) : illegalIPs.add(ip); } } switch (action) { case "load": LOG.debug("Load to white ip list"); result.put("existed_ips", existedIPs); result.put("added_ips", loadedIPs); if (!illegalIPs.isEmpty()) { result.put("illegal_ips", illegalIPs); } whiteIpList.addAll(loadedIPs); break; case "remove": LOG.debug("Remove from white ip list"); result.put("removed_ips", existedIPs); result.put("non_existed_ips", loadedIPs); whiteIpList.removeAll(existedIPs); break; default: throw new AssertionError(String.format("Invalid action '%s', " + "supported action is " + "'load' or 'remove'", action)); } manager.authManager().setWhiteIPs(whiteIpList); return result;
730
609
1,339
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/raft/RaftAPI.java
RaftAPI
setLeader
class RaftAPI extends API { private static final Logger LOG = Log.logger(RaftAPI.class); @GET @Timed @Path("list_peers") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin"}) public Map<String, List<String>> listPeers(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("group") @DefaultValue("default") String group) { LOG.debug("Graph [{}] prepare to get leader", graph); HugeGraph g = graph(manager, graph); RaftGroupManager raftManager = raftGroupManager(g, group, "list_peers"); List<String> peers = raftManager.listPeers(); return ImmutableMap.of(raftManager.group(), peers); } @GET @Timed @Path("get_leader") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin"}) public Map<String, String> getLeader(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("group") @DefaultValue("default") String group) { LOG.debug("Graph [{}] prepare to get leader", graph); HugeGraph g = graph(manager, graph); RaftGroupManager raftManager = raftGroupManager(g, group, "get_leader"); String leaderId = raftManager.getLeader(); return ImmutableMap.of(raftManager.group(), leaderId); } @POST @Timed @Status(Status.OK) @Path("transfer_leader") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin"}) public Map<String, String> transferLeader(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("group") @DefaultValue("default") String group, @QueryParam("endpoint") String endpoint) { LOG.debug("Graph [{}] prepare to transfer leader to: {}", graph, endpoint); HugeGraph g = graph(manager, graph); RaftGroupManager raftManager = raftGroupManager(g, group, "transfer_leader"); String leaderId = raftManager.transferLeaderTo(endpoint); return ImmutableMap.of(raftManager.group(), leaderId); } @POST @Timed @Status(Status.OK) @Path("set_leader") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin"}) public Map<String, String> setLeader(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("group") @DefaultValue("default") String group, @QueryParam("endpoint") String endpoint) {<FILL_FUNCTION_BODY>} @POST @Timed @Status(Status.OK) @Path("add_peer") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin"}) @RedirectFilter.RedirectMasterRole public Map<String, Id> addPeer(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("group") @DefaultValue("default") String group, @QueryParam("endpoint") String endpoint) { LOG.debug("Graph [{}] prepare to add peer: {}", graph, endpoint); HugeGraph g = graph(manager, graph); RaftGroupManager raftManager = raftGroupManager(g, group, "add_peer"); JobBuilder<String> builder = JobBuilder.of(g); String name = String.format("raft-group-[%s]-add-peer-[%s]-at-[%s]", raftManager.group(), endpoint, DateUtil.now()); Map<String, String> inputs = new HashMap<>(); inputs.put("endpoint", endpoint); builder.name(name) .input(JsonUtil.toJson(inputs)) .job(new RaftAddPeerJob()); return ImmutableMap.of("task_id", builder.schedule().id()); } @POST @Timed @Status(Status.OK) @Path("remove_peer") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin"}) @RedirectFilter.RedirectMasterRole public Map<String, Id> removePeer(@Context GraphManager manager, @PathParam("graph") String graph, @QueryParam("group") @DefaultValue("default") String group, @QueryParam("endpoint") String endpoint) { LOG.debug("Graph [{}] prepare to remove peer: {}", graph, endpoint); HugeGraph g = graph(manager, graph); RaftGroupManager raftManager = raftGroupManager(g, group, "remove_peer"); JobBuilder<String> builder = JobBuilder.of(g); String name = String.format("raft-group-[%s]-remove-peer-[%s]-at-[%s]", raftManager.group(), endpoint, DateUtil.now()); Map<String, String> inputs = new HashMap<>(); inputs.put("endpoint", endpoint); builder.name(name) .input(JsonUtil.toJson(inputs)) .job(new RaftRemovePeerJob()); return ImmutableMap.of("task_id", builder.schedule().id()); } private static RaftGroupManager raftGroupManager(HugeGraph graph, String group, String operation) { RaftGroupManager raftManager = graph.raftGroupManager(); if (raftManager == null) { throw new HugeException("Allowed %s operation only when " + "working on raft mode", operation); } return raftManager; } }
LOG.debug("Graph [{}] prepare to set leader to: {}", graph, endpoint); HugeGraph g = graph(manager, graph); RaftGroupManager raftManager = raftGroupManager(g, group, "set_leader"); String leaderId = raftManager.setLeader(endpoint); return ImmutableMap.of(raftManager.group(), leaderId);
1,643
100
1,743
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/schema/EdgeLabelAPI.java
JsonEdgeLabel
convert2Builder
class JsonEdgeLabel implements Checkable { @JsonProperty("id") public long id; @JsonProperty("name") public String name; @JsonProperty("source_label") public String sourceLabel; @JsonProperty("target_label") public String targetLabel; @JsonProperty("frequency") public Frequency frequency; @JsonProperty("properties") public String[] properties; @JsonProperty("sort_keys") public String[] sortKeys; @JsonProperty("nullable_keys") public String[] nullableKeys; @JsonProperty("ttl") public long ttl; @JsonProperty("ttl_start_time") public String ttlStartTime; @JsonProperty("enable_label_index") public Boolean enableLabelIndex; @JsonProperty("user_data") public Userdata userdata; @JsonProperty("check_exist") public Boolean checkExist; @Override public void checkCreate(boolean isBatch) { E.checkArgumentNotNull(this.name, "The name of edge label can't be null"); } private EdgeLabel.Builder convert2Builder(HugeGraph g) {<FILL_FUNCTION_BODY>} @Override public String toString() { return String.format("JsonEdgeLabel{" + "name=%s, sourceLabel=%s, targetLabel=%s, frequency=%s, " + "sortKeys=%s, nullableKeys=%s, properties=%s, ttl=%s, " + "ttlStartTime=%s}", this.name, this.sourceLabel, this.targetLabel, this.frequency, Arrays.toString(this.sortKeys), Arrays.toString(this.nullableKeys), Arrays.toString(this.properties), this.ttl, this.ttlStartTime); } }
EdgeLabel.Builder builder = g.schema().edgeLabel(this.name); if (this.id != 0) { E.checkArgument(this.id > 0, "Only positive number can be assign as " + "edge label id"); E.checkArgument(g.mode() == GraphMode.RESTORING, "Only accept edge label id when graph in " + "RESTORING mode, but '%s' is in mode '%s'", g, g.mode()); builder.id(this.id); } if (this.sourceLabel != null) { builder.sourceLabel(this.sourceLabel); } if (this.targetLabel != null) { builder.targetLabel(this.targetLabel); } if (this.frequency != null) { builder.frequency(this.frequency); } if (this.properties != null) { builder.properties(this.properties); } if (this.sortKeys != null) { builder.sortKeys(this.sortKeys); } if (this.nullableKeys != null) { builder.nullableKeys(this.nullableKeys); } if (this.enableLabelIndex != null) { builder.enableLabelIndex(this.enableLabelIndex); } if (this.userdata != null) { builder.userdata(this.userdata); } if (this.checkExist != null) { builder.checkExist(this.checkExist); } if (this.ttl != 0) { builder.ttl(this.ttl); } if (this.ttlStartTime != null) { E.checkArgument(this.ttl > 0, "Only set ttlStartTime when ttl is " + "positive, but got ttl: %s", this.ttl); builder.ttlStartTime(this.ttlStartTime); } return builder;
475
510
985
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/schema/IndexLabelAPI.java
JsonIndexLabel
checkCreate
class JsonIndexLabel implements Checkable { @JsonProperty("id") public long id; @JsonProperty("name") public String name; @JsonProperty("base_type") public HugeType baseType; @JsonProperty("base_value") public String baseValue; @JsonProperty("index_type") public IndexType indexType; @JsonProperty("fields") public String[] fields; @JsonProperty("user_data") public Userdata userdata; @JsonProperty("check_exist") public Boolean checkExist; @JsonProperty("rebuild") public Boolean rebuild; @Override public void checkCreate(boolean isBatch) {<FILL_FUNCTION_BODY>} @Override public void checkUpdate() { E.checkArgumentNotNull(this.name, "The name of index label can't be null"); E.checkArgument(this.baseType == null, "The base type of index label '%s' must be null", this.name); E.checkArgument(this.baseValue == null, "The base value of index label '%s' must be null", this.name); E.checkArgument(this.indexType == null, "The index type of index label '%s' must be null", this.name); } private IndexLabel.Builder convert2Builder(HugeGraph g) { IndexLabel.Builder builder = g.schema().indexLabel(this.name); if (this.id != 0) { E.checkArgument(this.id > 0, "Only positive number can be assign as " + "index label id"); E.checkArgument(g.mode() == GraphMode.RESTORING, "Only accept index label id when graph in " + "RESTORING mode, but '%s' is in mode '%s'", g, g.mode()); builder.id(this.id); } if (this.baseType != null) { assert this.baseValue != null; builder.on(this.baseType, this.baseValue); } if (this.indexType != null) { builder.indexType(this.indexType); } if (this.fields != null && this.fields.length > 0) { builder.by(this.fields); } if (this.userdata != null) { builder.userdata(this.userdata); } if (this.checkExist != null) { builder.checkExist(this.checkExist); } if (this.rebuild != null) { builder.rebuild(this.rebuild); } return builder; } @Override public String toString() { return String.format("JsonIndexLabel{name=%s, baseType=%s," + "baseValue=%s, indexType=%s, fields=%s}", this.name, this.baseType, this.baseValue, this.indexType, Arrays.toString(this.fields)); } }
E.checkArgumentNotNull(this.name, "The name of index label can't be null"); E.checkArgumentNotNull(this.baseType, "The base type of index label '%s' " + "can't be null", this.name); E.checkArgument(this.baseType == HugeType.VERTEX_LABEL || this.baseType == HugeType.EDGE_LABEL, "The base type of index label '%s' can only be " + "either VERTEX_LABEL or EDGE_LABEL", this.name); E.checkArgumentNotNull(this.baseValue, "The base value of index label '%s' " + "can't be null", this.name); E.checkArgumentNotNull(this.indexType, "The index type of index label '%s' " + "can't be null", this.name);
786
232
1,018
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/schema/SchemaAPI.java
SchemaAPI
list
class SchemaAPI extends API { private static final Logger LOG = Log.logger(SchemaAPI.class); @GET @Timed @Produces(APPLICATION_JSON_WITH_CHARSET) @RolesAllowed({"admin", "$owner=$graph $action=schema_read"}) public String list(@Context GraphManager manager, @PathParam("graph") String graph) {<FILL_FUNCTION_BODY>} }
LOG.debug("Graph [{}] list all schema", graph); HugeGraph g = graph(manager, graph); SchemaManager schema = g.schema(); Map<String, List<?>> schemaMap = new LinkedHashMap<>(4); schemaMap.put("propertykeys", schema.getPropertyKeys()); schemaMap.put("vertexlabels", schema.getVertexLabels()); schemaMap.put("edgelabels", schema.getEdgeLabels()); schemaMap.put("indexlabels", schema.getIndexLabels()); return manager.serializer(g).writeMap(schemaMap);
115
153
268
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER
apache_incubator-hugegraph
incubator-hugegraph/hugegraph-server/hugegraph-api/src/main/java/org/apache/hugegraph/api/schema/VertexLabelAPI.java
JsonVertexLabel
convert2Builder
class JsonVertexLabel implements Checkable { @JsonProperty("id") public long id; @JsonProperty("name") public String name; @JsonProperty("id_strategy") public IdStrategy idStrategy; @JsonProperty("properties") public String[] properties; @JsonProperty("primary_keys") public String[] primaryKeys; @JsonProperty("nullable_keys") public String[] nullableKeys; @JsonProperty("ttl") public long ttl; @JsonProperty("ttl_start_time") public String ttlStartTime; @JsonProperty("enable_label_index") public Boolean enableLabelIndex; @JsonProperty("user_data") public Userdata userdata; @JsonProperty("check_exist") public Boolean checkExist; @Override public void checkCreate(boolean isBatch) { E.checkArgumentNotNull(this.name, "The name of vertex label can't be null"); } private VertexLabel.Builder convert2Builder(HugeGraph g) {<FILL_FUNCTION_BODY>} @Override public String toString() { return String.format("JsonVertexLabel{" + "name=%s, idStrategy=%s, primaryKeys=%s, nullableKeys=%s, " + "properties=%s, ttl=%s, ttlStartTime=%s}", this.name, this.idStrategy, Arrays.toString(this.primaryKeys), Arrays.toString(this.nullableKeys), Arrays.toString(this.properties), this.ttl, this.ttlStartTime); } }
VertexLabel.Builder builder = g.schema().vertexLabel(this.name); if (this.id != 0) { E.checkArgument(this.id > 0, "Only positive number can be assign as " + "vertex label id"); E.checkArgument(g.mode() == GraphMode.RESTORING, "Only accept vertex label id when graph in " + "RESTORING mode, but '%s' is in mode '%s'", g, g.mode()); builder.id(this.id); } if (this.idStrategy != null) { builder.idStrategy(this.idStrategy); } if (this.properties != null) { builder.properties(this.properties); } if (this.primaryKeys != null) { builder.primaryKeys(this.primaryKeys); } if (this.nullableKeys != null) { builder.nullableKeys(this.nullableKeys); } if (this.enableLabelIndex != null) { builder.enableLabelIndex(this.enableLabelIndex); } if (this.userdata != null) { builder.userdata(this.userdata); } if (this.checkExist != null) { builder.checkExist(this.checkExist); } if (this.ttl != 0) { builder.ttl(this.ttl); } if (this.ttlStartTime != null) { E.checkArgument(this.ttl > 0, "Only set ttlStartTime when ttl is " + "positive, but got ttl: %s", this.ttl); builder.ttlStartTime(this.ttlStartTime); } return builder;
421
458
879
<methods>public non-sealed void <init>() ,public static boolean checkAndParseAction(java.lang.String) ,public static R commit(org.apache.hugegraph.HugeGraph, Callable<R>) ,public static void commit(org.apache.hugegraph.HugeGraph, java.lang.Runnable) ,public static org.apache.hugegraph.HugeGraph graph(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static org.apache.hugegraph.HugeGraph graph4admin(org.apache.hugegraph.core.GraphManager, java.lang.String) ,public static java.lang.Object[] properties(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String ACTION_APPEND,public static final java.lang.String ACTION_CLEAR,public static final java.lang.String ACTION_ELIMINATE,public static final java.lang.String APPLICATION_JSON,public static final java.lang.String APPLICATION_JSON_WITH_CHARSET,public static final java.lang.String APPLICATION_TEXT_WITH_CHARSET,public static final java.lang.String CHARSET,private static final Meter EXPECTED_ERROR_METER,private static final Meter ILLEGAL_ARG_ERROR_METER,public static final java.lang.String JSON,protected static final Logger LOG,private static final Meter SUCCEED_METER,public static final java.lang.String TEXT_PLAIN,private static final Meter UNKNOWN_ERROR_METER