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/broker/src/main/java/io/moquette/imhandler/KickoffGroupMember.java
|
KickoffGroupMember
|
action
|
class KickoffGroupMember extends GroupHandler<WFCMessage.RemoveGroupMemberRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.RemoveGroupMemberRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
ErrorCode errorCode;
WFCMessage.GroupInfo groupInfo = m_messagesStore.getGroupInfo(request.getGroupId());
if (groupInfo == null) {
errorCode = ErrorCode.ERROR_CODE_NOT_EXIST;
} else {
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if (!isAdmin && groupInfo.getType() == ProtoConstants.GroupType.GroupType_Organization) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
boolean isAllow = isAdmin;
if (!isAllow) {
if (groupInfo.getOwner() != null) {
if (request.getRemovedMemberList().contains(groupInfo.getOwner())) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
if (groupInfo.getOwner() != null && groupInfo.getOwner().equals(fromUser)) {
isAllow = true;
}
}
if (!isAllow) {
WFCMessage.GroupMember gm = m_messagesStore.getGroupMember(request.getGroupId(), fromUser);
if (gm != null && gm.getType() == ProtoConstants.GroupMemberType.GroupMemberType_Manager) {
isAllow = true;
}
}
if (!isAllow && (groupInfo.getType() == ProtoConstants.GroupType.GroupType_Normal || groupInfo.getType() == ProtoConstants.GroupType.GroupType_Restricted)) {
errorCode = ErrorCode.ERROR_CODE_NOT_RIGHT;
} else {
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_User && !m_messagesStore.isAllowClientCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_Robot && !m_messagesStore.isAllowRobotCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Kickoff_Group_Member) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
//send notify message first, then kickoff the member
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, groupInfo.getTargetId(), request.getToLineList(), request.getNotifyContent());
} else {
WFCMessage.MessageContent content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, null, request.getRemovedMemberList()).getKickokfMemberGroupNotifyContent();
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content);
}
if((m_messagesStore.getVisibleQuitKickoffNotification() & 0x02) > 0) {
Set<String> toUsers = m_messagesStore.getGroupManagers(request.getGroupId(), true);
toUsers.addAll(request.getRemovedMemberList());
WFCMessage.MessageContent content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, null, request.getRemovedMemberList()).getKickokfMemberVisibleGroupNotifyContent();
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content, toUsers);
}
errorCode = m_messagesStore.kickoffGroupMembers(fromUser, isAdmin, request.getGroupId(), request.getRemovedMemberList());
}
}
return errorCode;
| 94
| 1,009
| 1,103
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/KickoffPCClientHandler.java
|
KickoffPCClientHandler
|
action
|
class KickoffPCClientHandler extends GroupHandler<WFCMessage.IDBuf> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.IDBuf request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
String pcClientId = request.getId();
if (StringUtil.isNullOrEmpty(pcClientId)) {
return ErrorCode.INVALID_PARAMETER;
}
return m_sessionsStore.kickoffPCClient(fromUser, pcClientId);
| 92
| 71
| 163
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/LoadRemoteMessagesHandler.java
|
LoadRemoteMessagesHandler
|
action
|
class LoadRemoteMessagesHandler extends IMHandler<WFCMessage.LoadRemoteMessages> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.LoadRemoteMessages request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
ErrorCode errorCode = ErrorCode.ERROR_CODE_SUCCESS;
long beforeUid = request.getBeforeUid();
if (beforeUid == 0) {
beforeUid = Long.MAX_VALUE;
}
if (request.getConversation().getType() == ProtoConstants.ConversationType.ConversationType_Group) {
if (!m_messagesStore.isMemberInGroup(fromUser, request.getConversation().getTarget())) {
return ErrorCode.ERROR_CODE_NOT_IN_GROUP;
}
}
if (request.getConversation().getType() == ProtoConstants.ConversationType.ConversationType_Channel) {
if (!m_messagesStore.canSendMessageInChannel(fromUser, request.getConversation().getTarget())) {
return ErrorCode.ERROR_CODE_NOT_IN_CHANNEL;
}
}
WFCMessage.PullMessageResult result = m_messagesStore.loadRemoteMessages(fromUser, request.getConversation(), beforeUid, request.getCount(), request.getContentTypeList());
byte[] data = result.toByteArray();
LOG.info("User {} load message with count({}), payload size({})", fromUser, result.getMessageCount(), data.length);
ackPayload.ensureWritable(data.length).writeBytes(data);
return errorCode;
| 91
| 341
| 432
|
<methods>public void <init>() ,public abstract cn.wildfirechat.common.ErrorCode action(ByteBuf, java.lang.String, java.lang.String, cn.wildfirechat.proto.ProtoConstants.RequestSourceType, cn.wildfirechat.proto.WFCMessage.LoadRemoteMessages, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void afterAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void doHandler(java.lang.String, java.lang.String, java.lang.String, byte[], io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) ,public static io.moquette.spi.impl.MessagesPublisher getPublisher() ,public static void init(io.moquette.spi.IMessagesStore, io.moquette.spi.ISessionsStore, io.moquette.spi.impl.MessagesPublisher, cn.wildfirechat.server.ThreadPoolExecutorWrapper, io.moquette.server.Server) ,public cn.wildfirechat.common.ErrorCode preAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) <variables>protected static final Logger LOG,protected static java.lang.String actionName,private Class#RAW dataCls,private static win.liyufan.im.RateLimiter mLimitCounter,protected static io.moquette.server.Server mServer,private static cn.wildfirechat.server.ThreadPoolExecutorWrapper m_imBusinessExecutor,protected static io.moquette.spi.IMessagesStore m_messagesStore,protected static io.moquette.spi.ISessionsStore m_sessionsStore,private java.lang.reflect.Method parseDataMethod,protected static io.moquette.spi.impl.MessagesPublisher publisher
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/ModifyGroupAliasHandler.java
|
ModifyGroupAliasHandler
|
action
|
class ModifyGroupAliasHandler extends GroupHandler<WFCMessage.ModifyGroupMemberAlias> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.ModifyGroupMemberAlias request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_User && !m_messagesStore.isAllowClientCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_Robot && !m_messagesStore.isAllowRobotCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
ErrorCode errorCode = m_messagesStore.modifyGroupMemberAlias(fromUser, request.getGroupId(), request.getAlias(), null, isAdmin);
if (errorCode == ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent()&& request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), request.getNotifyContent());
} else {
WFCMessage.MessageContent content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getAlias(), "").getModifyGroupMemberAliasNotifyContent();
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content);
}
}
return errorCode;
| 99
| 375
| 474
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/ModifyGroupInfoHandler.java
|
ModifyGroupInfoHandler
|
action
|
class ModifyGroupInfoHandler extends GroupHandler<WFCMessage.ModifyGroupInfoRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.ModifyGroupInfoRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_User && !m_messagesStore.isAllowClientCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_Robot && !m_messagesStore.isAllowRobotCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if(request.getType() == Modify_Group_Mute) {
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Mute_Group) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
} else {
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Modify_Group_Info) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
}
ErrorCode errorCode= m_messagesStore.modifyGroupInfo(fromUser, request.getGroupId(), request.getType(), request.getValue(), isAdmin);
if (errorCode == ERROR_CODE_SUCCESS) {
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), request.getNotifyContent());
} else {
WFCMessage.MessageContent content = null;
if (request.getType() == Modify_Group_Name) {
content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getValue(), "").getChangeGroupNameNotifyContent();
} else if(request.getType() == Modify_Group_Portrait) {
content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getValue(), "").getChangeGroupPortraitNotifyContent();
} else if(request.getType() == Modify_Group_Mute) {
content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getValue(), "").getChangeGroupMuteNotifyContent();
} else if(request.getType() == Modify_Group_JoinType) {
content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getValue(), "").getChangeGroupJointypeNotifyContent();
} else if(request.getType() == Modify_Group_PrivateChat) {
content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getValue(), "").getChangeGroupPrivatechatNotifyContent();
} else if(request.getType() == Modify_Group_Searchable) {
content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getValue(), "").getChangeGroupSearchableNotifyContent();
} else if(request.getType() == Modify_Group_Extra) {
content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getValue(), "").getChangeGroupExtraNotifyContent();
}
if (content != null) {
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content);
}
}
}
return errorCode;
| 96
| 921
| 1,017
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/ModifyGroupMemberAliasHandler.java
|
ModifyGroupMemberAliasHandler
|
action
|
class ModifyGroupMemberAliasHandler extends GroupHandler<WFCMessage.ModifyGroupMemberAlias> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.ModifyGroupMemberAlias request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_User && !m_messagesStore.isAllowClientCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_Robot && !m_messagesStore.isAllowRobotCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
ErrorCode errorCode = m_messagesStore.modifyGroupMemberAlias(fromUser, request.getGroupId(), request.getAlias(), request.getMemberId(), isAdmin);
if (errorCode == ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent()&& request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), request.getNotifyContent());
} else {
WFCMessage.MessageContent content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getAlias(), request.getMemberId()).getModifyGroupMemberAliasNotifyContent();
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content);
}
}
return errorCode;
| 100
| 383
| 483
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/ModifyGroupMemberExtraHandler.java
|
ModifyGroupMemberExtraHandler
|
action
|
class ModifyGroupMemberExtraHandler extends GroupHandler<WFCMessage.ModifyGroupMemberExtra> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.ModifyGroupMemberExtra request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_User && !m_messagesStore.isAllowClientCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_Robot && !m_messagesStore.isAllowRobotCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
ErrorCode errorCode = m_messagesStore.modifyGroupMemberExtra(fromUser, request.getGroupId(), request.getExtra(), request.getMemberId(), isAdmin);
if (errorCode == ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent()&& request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), request.getNotifyContent());
} else {
WFCMessage.MessageContent content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getExtra(), request.getMemberId()).getModifyGroupMemberExtraNotifyContent();
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content);
}
}
return errorCode;
| 97
| 379
| 476
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/ModifyMyInfoHandler.java
|
ModifyMyInfoHandler
|
action
|
class ModifyMyInfoHandler extends IMHandler<WFCMessage.ModifyMyInfoRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.ModifyMyInfoRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
try {
return m_messagesStore.modifyUserInfo(fromUser, request);
} catch (Exception e) {
e.printStackTrace();
Utility.printExecption(LOG, e);
return ErrorCode.ERROR_CODE_SERVER_ERROR;
}
| 96
| 71
| 167
|
<methods>public void <init>() ,public abstract cn.wildfirechat.common.ErrorCode action(ByteBuf, java.lang.String, java.lang.String, cn.wildfirechat.proto.ProtoConstants.RequestSourceType, cn.wildfirechat.proto.WFCMessage.ModifyMyInfoRequest, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void afterAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void doHandler(java.lang.String, java.lang.String, java.lang.String, byte[], io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) ,public static io.moquette.spi.impl.MessagesPublisher getPublisher() ,public static void init(io.moquette.spi.IMessagesStore, io.moquette.spi.ISessionsStore, io.moquette.spi.impl.MessagesPublisher, cn.wildfirechat.server.ThreadPoolExecutorWrapper, io.moquette.server.Server) ,public cn.wildfirechat.common.ErrorCode preAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) <variables>protected static final Logger LOG,protected static java.lang.String actionName,private Class#RAW dataCls,private static win.liyufan.im.RateLimiter mLimitCounter,protected static io.moquette.server.Server mServer,private static cn.wildfirechat.server.ThreadPoolExecutorWrapper m_imBusinessExecutor,protected static io.moquette.spi.IMessagesStore m_messagesStore,protected static io.moquette.spi.ISessionsStore m_sessionsStore,private java.lang.reflect.Method parseDataMethod,protected static io.moquette.spi.impl.MessagesPublisher publisher
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/MultiCastMessageHandler.java
|
MultiCastMessageHandler
|
action
|
class MultiCastMessageHandler extends IMHandler<WFCMessage.MultiCastMessage> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.MultiCastMessage multiCastMessage, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
ErrorCode errorCode = ErrorCode.ERROR_CODE_SUCCESS;
if (!isAdmin) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
long timestamp = System.currentTimeMillis();
long messageId = 0;
try {
messageId = MessageShardingUtil.generateId();
} catch (Exception e) {
e.printStackTrace();
return ErrorCode.ERROR_CODE_SERVER_ERROR;
}
WFCMessage.Message message = WFCMessage.Message.newBuilder()
.setContent(multiCastMessage.getContent())
.setConversation(WFCMessage.Conversation.newBuilder().setTarget(fromUser).setType(ConversationType_Private).setLine(multiCastMessage.getLine()).build())
.setFromUser(fromUser)
.setMessageId(messageId)
.setServerTimestamp(timestamp)
.build();
saveAndMulticast(fromUser, clientID, message, multiCastMessage.getToList());
ackPayload = ackPayload.capacity(20);
ackPayload.writeLong(messageId);
ackPayload.writeLong(timestamp);
return errorCode;
| 96
| 328
| 424
|
<methods>public void <init>() ,public abstract cn.wildfirechat.common.ErrorCode action(ByteBuf, java.lang.String, java.lang.String, cn.wildfirechat.proto.ProtoConstants.RequestSourceType, cn.wildfirechat.proto.WFCMessage.MultiCastMessage, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void afterAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void doHandler(java.lang.String, java.lang.String, java.lang.String, byte[], io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) ,public static io.moquette.spi.impl.MessagesPublisher getPublisher() ,public static void init(io.moquette.spi.IMessagesStore, io.moquette.spi.ISessionsStore, io.moquette.spi.impl.MessagesPublisher, cn.wildfirechat.server.ThreadPoolExecutorWrapper, io.moquette.server.Server) ,public cn.wildfirechat.common.ErrorCode preAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) <variables>protected static final Logger LOG,protected static java.lang.String actionName,private Class#RAW dataCls,private static win.liyufan.im.RateLimiter mLimitCounter,protected static io.moquette.server.Server mServer,private static cn.wildfirechat.server.ThreadPoolExecutorWrapper m_imBusinessExecutor,protected static io.moquette.spi.IMessagesStore m_messagesStore,protected static io.moquette.spi.ISessionsStore m_sessionsStore,private java.lang.reflect.Method parseDataMethod,protected static io.moquette.spi.impl.MessagesPublisher publisher
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/PullMessageHandler.java
|
PullMessageHandler
|
action
|
class PullMessageHandler extends IMHandler<WFCMessage.PullMessageRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.PullMessageRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
ErrorCode errorCode = ErrorCode.ERROR_CODE_SUCCESS;
if (request.getType() == ProtoConstants.PullType.Pull_ChatRoom && !m_messagesStore.checkUserClientInChatroom(fromUser, clientID, null)) {
errorCode = ErrorCode.ERROR_CODE_NOT_IN_CHATROOM;
} else {
WFCMessage.PullMessageResult result = m_messagesStore.fetchMessage(fromUser, clientID, request.getId(), request.getType());
byte[] data = result.toByteArray();
LOG.info("User {} pull message with count({}), payload size({})", fromUser, result.getMessageCount(), data.length);
ackPayload.ensureWritable(data.length).writeBytes(data);
}
return errorCode;
| 93
| 203
| 296
|
<methods>public void <init>() ,public abstract cn.wildfirechat.common.ErrorCode action(ByteBuf, java.lang.String, java.lang.String, cn.wildfirechat.proto.ProtoConstants.RequestSourceType, cn.wildfirechat.proto.WFCMessage.PullMessageRequest, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void afterAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void doHandler(java.lang.String, java.lang.String, java.lang.String, byte[], io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) ,public static io.moquette.spi.impl.MessagesPublisher getPublisher() ,public static void init(io.moquette.spi.IMessagesStore, io.moquette.spi.ISessionsStore, io.moquette.spi.impl.MessagesPublisher, cn.wildfirechat.server.ThreadPoolExecutorWrapper, io.moquette.server.Server) ,public cn.wildfirechat.common.ErrorCode preAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) <variables>protected static final Logger LOG,protected static java.lang.String actionName,private Class#RAW dataCls,private static win.liyufan.im.RateLimiter mLimitCounter,protected static io.moquette.server.Server mServer,private static cn.wildfirechat.server.ThreadPoolExecutorWrapper m_imBusinessExecutor,protected static io.moquette.spi.IMessagesStore m_messagesStore,protected static io.moquette.spi.ISessionsStore m_sessionsStore,private java.lang.reflect.Method parseDataMethod,protected static io.moquette.spi.impl.MessagesPublisher publisher
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/QuitGroupHandler.java
|
QuitGroupHandler
|
action
|
class QuitGroupHandler extends GroupHandler<WFCMessage.QuitGroupRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.QuitGroupRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_User && !m_messagesStore.isAllowClientCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_Robot && !m_messagesStore.isAllowRobotCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Quit_Group) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
ErrorCode errorCode = m_messagesStore.quitGroup(fromUser, request.getGroupId(), isAdmin);
if (errorCode == ErrorCode.ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), request.getNotifyContent());
} else {
WFCMessage.MessageContent content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, null, "").getQuitGroupNotifyContent();
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content);
}
if((m_messagesStore.getVisibleQuitKickoffNotification() & 0x01) > 0) {
Set<String> toUsers = m_messagesStore.getGroupManagers(request.getGroupId(), true);
WFCMessage.MessageContent content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, null, "").getQuitVisibleGroupNotifyContent();
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content, toUsers);
}
}
return errorCode;
| 93
| 586
| 679
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/RecallMessageHandler.java
|
RecallMessageHandler
|
action
|
class RecallMessageHandler extends IMHandler<WFCMessage.INT64Buf> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.INT64Buf int64Buf, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
ErrorCode errorCode = m_messagesStore.recallMessage(int64Buf.getId(), fromUser, clientID, isAdmin, ackPayload);
if(errorCode != ErrorCode.ERROR_CODE_SUCCESS) {
return errorCode;
}
WFCMessage.Message message = m_messagesStore.getMessage(int64Buf.getId());
if (message == null) {
return ErrorCode.ERROR_CODE_NOT_EXIST;
}
publish(message.getFromUser(), clientID, message, requestSourceType);
return errorCode;
| 97
| 172
| 269
|
<methods>public void <init>() ,public abstract cn.wildfirechat.common.ErrorCode action(ByteBuf, java.lang.String, java.lang.String, cn.wildfirechat.proto.ProtoConstants.RequestSourceType, cn.wildfirechat.proto.WFCMessage.INT64Buf, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void afterAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void doHandler(java.lang.String, java.lang.String, java.lang.String, byte[], io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) ,public static io.moquette.spi.impl.MessagesPublisher getPublisher() ,public static void init(io.moquette.spi.IMessagesStore, io.moquette.spi.ISessionsStore, io.moquette.spi.impl.MessagesPublisher, cn.wildfirechat.server.ThreadPoolExecutorWrapper, io.moquette.server.Server) ,public cn.wildfirechat.common.ErrorCode preAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) <variables>protected static final Logger LOG,protected static java.lang.String actionName,private Class#RAW dataCls,private static win.liyufan.im.RateLimiter mLimitCounter,protected static io.moquette.server.Server mServer,private static cn.wildfirechat.server.ThreadPoolExecutorWrapper m_imBusinessExecutor,protected static io.moquette.spi.IMessagesStore m_messagesStore,protected static io.moquette.spi.ISessionsStore m_sessionsStore,private java.lang.reflect.Method parseDataMethod,protected static io.moquette.spi.impl.MessagesPublisher publisher
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/RecallMultiCastMessageHandler.java
|
RecallMultiCastMessageHandler
|
action
|
class RecallMultiCastMessageHandler extends IMHandler<WFCMessage.RecallMultiCastMessageRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.RecallMultiCastMessageRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if (!isAdmin) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
ErrorCode errorCode = m_messagesStore.recallCastMessage(request.getMessageId(), fromUser);
if(errorCode != ErrorCode.ERROR_CODE_SUCCESS) {
return errorCode;
}
publishRecallMultiCastMsg(request.getMessageId(), request.getReceiverList());
return errorCode;
| 98
| 137
| 235
|
<methods>public void <init>() ,public abstract cn.wildfirechat.common.ErrorCode action(ByteBuf, java.lang.String, java.lang.String, cn.wildfirechat.proto.ProtoConstants.RequestSourceType, cn.wildfirechat.proto.WFCMessage.RecallMultiCastMessageRequest, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void afterAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void doHandler(java.lang.String, java.lang.String, java.lang.String, byte[], io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) ,public static io.moquette.spi.impl.MessagesPublisher getPublisher() ,public static void init(io.moquette.spi.IMessagesStore, io.moquette.spi.ISessionsStore, io.moquette.spi.impl.MessagesPublisher, cn.wildfirechat.server.ThreadPoolExecutorWrapper, io.moquette.server.Server) ,public cn.wildfirechat.common.ErrorCode preAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) <variables>protected static final Logger LOG,protected static java.lang.String actionName,private Class#RAW dataCls,private static win.liyufan.im.RateLimiter mLimitCounter,protected static io.moquette.server.Server mServer,private static cn.wildfirechat.server.ThreadPoolExecutorWrapper m_imBusinessExecutor,protected static io.moquette.spi.IMessagesStore m_messagesStore,protected static io.moquette.spi.ISessionsStore m_sessionsStore,private java.lang.reflect.Method parseDataMethod,protected static io.moquette.spi.impl.MessagesPublisher publisher
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/RouteHandler.java
|
RouteHandler
|
action
|
class RouteHandler extends IMHandler<WFCMessage.RouteRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.RouteRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
MemorySessionStore.Session session = m_sessionsStore.sessionForClientAndUser(fromUser, clientID);
if (session == null) {
ErrorCode errorCode = m_sessionsStore.loadActiveSession(fromUser, clientID);
if (errorCode != ErrorCode.ERROR_CODE_SUCCESS) {
return errorCode;
}
session = m_sessionsStore.sessionForClientAndUser(fromUser, clientID);
}
if (session == null || session.getDeleted() > 0) {
if(session == null) {
LOG.error("Session for <{}, {}> not exist", fromUser, clientID);
} else {
LOG.error("Session for <{}, {}> deleted", fromUser, clientID);
}
return ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH;
}
if(request.getPlatform() != session.getPlatform() && m_messagesStore.existSignatures()) {
LOG.error("Session <{}, {}> platform is {} mismatch the request {}", session.getUsername(), session.getClientID(), session.getPlatform(), request.getPlatform());
return ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH;
}
String serverIp = mServer.getServerIp();
String longPort = mServer.getLongPort();
String shortPort = mServer.getShortPort();
ClientSession clientSession = m_sessionsStore.sessionForClient(clientID);
boolean isSessionAlreadyStored = clientSession != null;
if (!isSessionAlreadyStored) {
m_sessionsStore.loadActiveSession(fromUser, clientID);
} else {
m_sessionsStore.updateExistSession(fromUser, clientID, request, true);
}
WFCMessage.RouteResponse response = WFCMessage.RouteResponse.newBuilder().setHost(serverIp).setLongPort(Integer.parseInt(longPort)).setShortPort(Integer.parseInt(shortPort)).build();
byte[] data = response.toByteArray();
ackPayload.ensureWritable(data.length).writeBytes(data);
return ErrorCode.ERROR_CODE_SUCCESS;
| 87
| 556
| 643
|
<methods>public void <init>() ,public abstract cn.wildfirechat.common.ErrorCode action(ByteBuf, java.lang.String, java.lang.String, cn.wildfirechat.proto.ProtoConstants.RequestSourceType, cn.wildfirechat.proto.WFCMessage.RouteRequest, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void afterAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void doHandler(java.lang.String, java.lang.String, java.lang.String, byte[], io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) ,public static io.moquette.spi.impl.MessagesPublisher getPublisher() ,public static void init(io.moquette.spi.IMessagesStore, io.moquette.spi.ISessionsStore, io.moquette.spi.impl.MessagesPublisher, cn.wildfirechat.server.ThreadPoolExecutorWrapper, io.moquette.server.Server) ,public cn.wildfirechat.common.ErrorCode preAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) <variables>protected static final Logger LOG,protected static java.lang.String actionName,private Class#RAW dataCls,private static win.liyufan.im.RateLimiter mLimitCounter,protected static io.moquette.server.Server mServer,private static cn.wildfirechat.server.ThreadPoolExecutorWrapper m_imBusinessExecutor,protected static io.moquette.spi.IMessagesStore m_messagesStore,protected static io.moquette.spi.ISessionsStore m_sessionsStore,private java.lang.reflect.Method parseDataMethod,protected static io.moquette.spi.impl.MessagesPublisher publisher
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/SetFriendAliasRequestHandler.java
|
SetFriendAliasRequestHandler
|
action
|
class SetFriendAliasRequestHandler extends GroupHandler<WFCMessage.AddFriendRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.AddFriendRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
long[] head = new long[1];
ErrorCode errorCode = m_messagesStore.setFriendAliasRequest(fromUser, request.getTargetUid(), request.getReason(), head);
if (errorCode == ERROR_CODE_SUCCESS) {
publisher.publishNotification(IMTopic.NotifyFriendTopic, fromUser, head[0]);
}
return errorCode;
| 93
| 99
| 192
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/SetGroupManagerHandler.java
|
SetGroupManagerHandler
|
action
|
class SetGroupManagerHandler extends GroupHandler<WFCMessage.SetGroupManagerRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.SetGroupManagerRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_User && !m_messagesStore.isAllowClientCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_Robot && !m_messagesStore.isAllowRobotCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Set_Group_Manage) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
ErrorCode errorCode = m_messagesStore.setGroupManager(fromUser, request.getGroupId(), request.getType(), request.getUserIdList(), isAdmin);
if (errorCode == ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), request.getNotifyContent());
} else {
WFCMessage.MessageContent content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, request.getType() + "", request.getUserIdList()).getSetGroupManagerNotifyContent();
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content);
}
}
return errorCode;
| 93
| 482
| 575
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/SyncFriendRequestUnreadHandler.java
|
SyncFriendRequestUnreadHandler
|
action
|
class SyncFriendRequestUnreadHandler extends GroupHandler<WFCMessage.Version> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.Version request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
long[] head = new long[1];
ErrorCode errorCode = m_messagesStore.SyncFriendRequestUnread(fromUser, request.getVersion(), head);
if (errorCode == ERROR_CODE_SUCCESS) {
publisher.publishNotification(IMTopic.NotifyFriendRequestTopic, fromUser, head[0]);
}
return errorCode;
| 90
| 93
| 183
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/TransferGroupHandler.java
|
TransferGroupHandler
|
action
|
class TransferGroupHandler extends GroupHandler<WFCMessage.TransferGroupRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.TransferGroupRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
boolean isAdmin = requestSourceType == ProtoConstants.RequestSourceType.Request_From_Admin;
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_User && !m_messagesStore.isAllowClientCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(request.hasNotifyContent() && request.getNotifyContent().getType() > 0 && requestSourceType == ProtoConstants.RequestSourceType.Request_From_Robot && !m_messagesStore.isAllowRobotCustomGroupNotification()) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
if(requestSourceType == ProtoConstants.RequestSourceType.Request_From_User) {
int forbiddenClientOperation = m_messagesStore.getGroupForbiddenClientOperation();
if((forbiddenClientOperation & ProtoConstants.ForbiddenClientGroupOperationMask.Forbidden_Transfer_Group) > 0) {
return ErrorCode.ERROR_CODE_NOT_RIGHT;
}
}
ErrorCode errorCode = m_messagesStore.transferGroup(fromUser, request.getGroupId(), request.getNewOwner(), isAdmin);
if (errorCode == ERROR_CODE_SUCCESS) {
if (request.hasNotifyContent() && request.getNotifyContent().getType() > 0) {
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), request.getNotifyContent());
} else {
WFCMessage.MessageContent content = new GroupNotificationBinaryContent(request.getGroupId(), fromUser, null, request.getNewOwner()).getTransferGroupNotifyContent();
sendGroupNotification(fromUser, request.getGroupId(), request.getToLineList(), content);
}
}
return errorCode;
| 92
| 468
| 560
|
<methods>public non-sealed void <init>() <variables>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/UploadDeviceTokenHandler.java
|
UploadDeviceTokenHandler
|
action
|
class UploadDeviceTokenHandler extends IMHandler<WFCMessage.UploadDeviceTokenRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.UploadDeviceTokenRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
MemorySessionStore.Session session = m_sessionsStore.getSession(clientID);
session.setPlatform(request.getPlatform());
session.setAppName(request.getAppName());
if (request.getPlatform() == ProtoConstants.Platform.Platform_iOS && request.getPushType() == 2) {
LOG.info("Set device token, userId {}", fromUser);
session.setVoipDeviceToken(request.getDeviceToken());
m_sessionsStore.updateSessionToken(session, true);
} else {
LOG.info("Set device token, userId {}, platform {}, pushType {}", fromUser, session.getPlatform(), request.getPushType());
session.setDeviceToken(request.getDeviceToken());
session.setPushType(request.getPushType());
m_sessionsStore.updateSessionToken(session, false);
m_sessionsStore.cleanDuplatedToken(session.getClientID(), session.getPushType(), session.getDeviceToken(), false, session.getAppName());
}
return ErrorCode.ERROR_CODE_SUCCESS;
| 94
| 276
| 370
|
<methods>public void <init>() ,public abstract cn.wildfirechat.common.ErrorCode action(ByteBuf, java.lang.String, java.lang.String, cn.wildfirechat.proto.ProtoConstants.RequestSourceType, cn.wildfirechat.proto.WFCMessage.UploadDeviceTokenRequest, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void afterAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void doHandler(java.lang.String, java.lang.String, java.lang.String, byte[], io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) ,public static io.moquette.spi.impl.MessagesPublisher getPublisher() ,public static void init(io.moquette.spi.IMessagesStore, io.moquette.spi.ISessionsStore, io.moquette.spi.impl.MessagesPublisher, cn.wildfirechat.server.ThreadPoolExecutorWrapper, io.moquette.server.Server) ,public cn.wildfirechat.common.ErrorCode preAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) <variables>protected static final Logger LOG,protected static java.lang.String actionName,private Class#RAW dataCls,private static win.liyufan.im.RateLimiter mLimitCounter,protected static io.moquette.server.Server mServer,private static cn.wildfirechat.server.ThreadPoolExecutorWrapper m_imBusinessExecutor,protected static io.moquette.spi.IMessagesStore m_messagesStore,protected static io.moquette.spi.ISessionsStore m_sessionsStore,private java.lang.reflect.Method parseDataMethod,protected static io.moquette.spi.impl.MessagesPublisher publisher
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/imhandler/UserSearchHandler.java
|
UserSearchHandler
|
action
|
class UserSearchHandler extends IMHandler<WFCMessage.SearchUserRequest> {
@Override
public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.SearchUserRequest request, Qos1PublishHandler.IMCallback callback) {<FILL_FUNCTION_BODY>}
}
|
List<WFCMessage.User> users = m_messagesStore.searchUser(request.getKeyword(), request.getFuzzy(), request.getPage());
WFCMessage.SearchUserResult.Builder builder = WFCMessage.SearchUserResult.newBuilder();
builder.addAllEntry(users);
byte[] data = builder.build().toByteArray();
ackPayload.ensureWritable(data.length).writeBytes(data);
return ErrorCode.ERROR_CODE_SUCCESS;
| 90
| 124
| 214
|
<methods>public void <init>() ,public abstract cn.wildfirechat.common.ErrorCode action(ByteBuf, java.lang.String, java.lang.String, cn.wildfirechat.proto.ProtoConstants.RequestSourceType, cn.wildfirechat.proto.WFCMessage.SearchUserRequest, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void afterAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback) ,public void doHandler(java.lang.String, java.lang.String, java.lang.String, byte[], io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) ,public static io.moquette.spi.impl.MessagesPublisher getPublisher() ,public static void init(io.moquette.spi.IMessagesStore, io.moquette.spi.ISessionsStore, io.moquette.spi.impl.MessagesPublisher, cn.wildfirechat.server.ThreadPoolExecutorWrapper, io.moquette.server.Server) ,public cn.wildfirechat.common.ErrorCode preAction(java.lang.String, java.lang.String, java.lang.String, io.moquette.spi.impl.Qos1PublishHandler.IMCallback, cn.wildfirechat.proto.ProtoConstants.RequestSourceType) <variables>protected static final Logger LOG,protected static java.lang.String actionName,private Class#RAW dataCls,private static win.liyufan.im.RateLimiter mLimitCounter,protected static io.moquette.server.Server mServer,private static cn.wildfirechat.server.ThreadPoolExecutorWrapper m_imBusinessExecutor,protected static io.moquette.spi.IMessagesStore m_messagesStore,protected static io.moquette.spi.ISessionsStore m_sessionsStore,private java.lang.reflect.Method parseDataMethod,protected static io.moquette.spi.impl.MessagesPublisher publisher
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/logging/LoggingUtils.java
|
LoggingUtils
|
getInterceptorIds
|
class LoggingUtils {
public static <T extends InterceptHandler> Collection<String> getInterceptorIds(Collection<T> handlers) {<FILL_FUNCTION_BODY>}
private LoggingUtils() {
}
}
|
Collection<String> result = new ArrayList<>(handlers.size());
for (T handler : handlers) {
result.add(handler.getID());
}
return result;
| 62
| 50
| 112
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/persistence/ServerAPIHelper.java
|
ServerAPIHelper
|
sendRequest
|
class ServerAPIHelper {
private static final Logger LOG = LoggerFactory.getLogger(ServerAPIHelper.class);
public static final String CHECK_USER_ONLINE_REQUEST = "check_user_online";
public static final String KICKOFF_USER_REQUEST = "kickoff_user";
private static Server server;
public static ConcurrentHashMap<Integer, RequestInfo> requestMap = new ConcurrentHashMap<>();
private static AtomicInteger aiRequestId = new AtomicInteger(1);
public static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
public static void init(Server s) {
server = s;
}
public interface Callback {
void onSuccess(byte[] response);
void onError(ErrorCode errorCode);
void onTimeout();
Executor getResponseExecutor();
}
public static void sendRequest(String fromUser, String clientId, String request, byte[] message, Callback callback, ProtoConstants.RequestSourceType requestSourceType) {<FILL_FUNCTION_BODY>}
public static void sendResponse(int errorCode, byte[] message, String toUuid, int requestId) {
LOG.debug("send async reponse to {} with requestId {}", toUuid, requestId);
if (requestId > 0) {
RequestInfo info = requestMap.remove(requestId);
LOG.debug("receive async reponse requestId {}, errorCode {}", requestId, errorCode);
if(info != null) {
info.future.cancel(true);
if (info.callback != null) {
info.callback.getResponseExecutor().execute(() -> {
if (errorCode == 0 || errorCode == ErrorCode.ERROR_CODE_SUCCESS_GZIPED.getCode()) {
info.callback.onSuccess(message);
} else {
info.callback.onError(ErrorCode.fromCode(errorCode));
}
});
} else {
}
}
}
}
}
|
int requestId = 0;
if (callback != null) {
requestId = aiRequestId.incrementAndGet();
if (requestId == Integer.MAX_VALUE) {
if(!aiRequestId.compareAndSet(Integer.MAX_VALUE, 1)) {
requestId = aiRequestId.incrementAndGet();
}
}
requestMap.put(requestId, new RequestInfo(fromUser, clientId, callback, message, requestId, request));
}
server.onApiMessage(fromUser, clientId, message, requestId, "", request, requestSourceType);
| 505
| 153
| 658
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/ConnectionDescriptor.java
|
ConnectionDescriptor
|
toString
|
class ConnectionDescriptor {
private static final Logger LOG = LoggerFactory.getLogger(ConnectionDescriptor.class);
public enum ConnectionState {
// Connection states
DISCONNECTED,
SENDACK,
SESSION_CREATED,
MESSAGES_REPUBLISHED,
ESTABLISHED,
// Disconnection states
MESSAGES_DROPPED,
INTERCEPTORS_NOTIFIED;
}
public final String clientID;
private final Channel channel;
private final AtomicReference<ConnectionState> channelState = new AtomicReference<>(ConnectionState.DISCONNECTED);
public ConnectionDescriptor(String clientID, Channel session) {
this.clientID = clientID;
this.channel = session;
}
public void writeAndFlush(Object payload) {
this.channel.writeAndFlush(payload);
}
public void setupAutoFlusher(int flushIntervalMs) {
try {
this.channel.pipeline().addAfter(
"idleEventHandler",
"autoFlusher",
new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS));
} catch (NoSuchElementException nseex) {
// the idleEventHandler is not present on the pipeline
this.channel.pipeline()
.addFirst("autoFlusher", new AutoFlushHandler(flushIntervalMs, TimeUnit.MILLISECONDS));
}
}
public boolean doesNotUseChannel(Channel channel) {
return !(this.channel.equals(channel));
}
public boolean close() {
LOG.info("Closing connection descriptor. MqttClientId = {}.", clientID);
final boolean success = assignState(ConnectionState.INTERCEPTORS_NOTIFIED, ConnectionState.DISCONNECTED);
if (!success) {
return false;
}
this.channel.close();
return true;
}
public String getUsername() {
return NettyUtils.userName(this.channel);
}
public void abort() {
LOG.info("Closing connection descriptor. MqttClientId = {}.", clientID);
// try {
// this.channel.disconnect().sync();
this.channel.close(); // .sync();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
public boolean assignState(ConnectionState expected, ConnectionState newState) {
LOG.debug(
"Updating state of connection descriptor. MqttClientId = {}, expectedState = {}, newState = {}.",
clientID,
expected,
newState);
boolean retval = channelState.compareAndSet(expected, newState);
if (!retval) {
LOG.error(
"Unable to update state of connection descriptor."
+ " MqttclientId = {}, expectedState = {}, newState = {}.",
clientID,
expected,
newState);
}
return retval;
}
@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;
ConnectionDescriptor that = (ConnectionDescriptor) o;
if (clientID != null ? !clientID.equals(that.clientID) : that.clientID != null)
return false;
return !(channel != null ? !channel.equals(that.channel) : that.channel != null);
}
public BytesMetrics getBytesMetrics() {
return BytesMetricsHandler.getBytesMetrics(channel);
}
public MessageMetrics getMessageMetrics() {
return MessageMetricsHandler.getMessageMetrics(channel);
}
@Override
public int hashCode() {
int result = clientID != null ? clientID.hashCode() : 0;
result = 31 * result + (channel != null ? channel.hashCode() : 0);
return result;
}
public Channel getChannel() {
return channel;
}
}
|
return "ConnectionDescriptor{" + "clientID=" + clientID + ", state="
+ channelState.get() + '}';
| 1,052
| 36
| 1,088
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/ConnectionDescriptorStore.java
|
ConnectionDescriptorStore
|
getSessions
|
class ConnectionDescriptorStore implements IConnectionsManager {
private static final Logger LOG = LoggerFactory.getLogger(ConnectionDescriptorStore.class);
private final ConcurrentMap<String, ConnectionDescriptor> connectionDescriptors;
private final ISessionsStore sessionsStore;
public ConnectionDescriptorStore(ISessionsStore sessionsStore) {
this.connectionDescriptors = new ConcurrentHashMap<>();
this.sessionsStore = sessionsStore;
}
public boolean sendMessage(MqttMessage message, Integer messageID, String clientID, ErrorCode errorCode) {
final MqttMessageType messageType = message.fixedHeader().messageType();
try {
if (messageID != null) {
LOG.info("Sending {} message CId=<{}>, messageId={}, errorCode={}", messageType, clientID, messageID, errorCode);
} else {
LOG.debug("Sending {} message CId=<{}>", messageType, clientID);
}
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
if (descriptor == null) {
if (messageID != null) {
LOG.error("Client has just disconnected. {} message could not be sent. CId=<{}>, messageId={}",
messageType, clientID, messageID);
} else {
LOG.error("Client has just disconnected. {} could not be sent. CId=<{}>", messageType, clientID);
}
/*
* If the client has just disconnected, its connection descriptor will be null. We
* don't have to make the broker crash: we'll just discard the PUBACK message.
*/
return false;
}
descriptor.writeAndFlush(message);
return true;
} catch (Throwable e) {
String errorMsg = "Unable to send " + messageType + " message. CId=<" + clientID + ">";
if (messageID != null) {
errorMsg += ", messageId=" + messageID;
}
LOG.error(errorMsg, e);
return false;
}
}
public ConnectionDescriptor addConnection(ConnectionDescriptor descriptor) {
return connectionDescriptors.putIfAbsent(descriptor.clientID, descriptor);
}
public boolean removeConnection(ConnectionDescriptor descriptor) {
return connectionDescriptors.remove(descriptor.clientID, descriptor);
}
public ConnectionDescriptor getConnection(String clientID) {
return connectionDescriptors.get(clientID);
}
@Override
public boolean isConnected(String clientID) {
return connectionDescriptors.containsKey(clientID);
}
@Override
public int getActiveConnectionsNo() {
return connectionDescriptors.size();
}
@Override
public Collection<String> getConnectedClientIds() {
return connectionDescriptors.keySet();
}
@Override
public boolean closeConnection(String clientID, boolean closeImmediately) {
ConnectionDescriptor descriptor = connectionDescriptors.get(clientID);
if (descriptor == null) {
LOG.error("Connection descriptor doesn't exist. MQTT connection cannot be closed. CId=<{}>, " +
"closeImmediately={}", clientID, closeImmediately);
return false;
}
if (closeImmediately) {
descriptor.abort();
return true;
} else {
return descriptor.close();
}
}
@Override
public MqttSession getSessionStatus(String clientID) {
LOG.info("Retrieving status of session. CId=<{}>", clientID);
ClientSession session = sessionsStore.sessionForClient(clientID);
if (session == null) {
LOG.error("MQTT client ID doesn't have an associated session. CId=<{}>", clientID);
return null;
}
return buildMqttSession(session);
}
@Override
public Collection<MqttSession> getSessions() {<FILL_FUNCTION_BODY>}
private MqttSession buildMqttSession(ClientSession session) {
MqttSession result = new MqttSession();
result.setCleanSession(true);
ConnectionDescriptor descriptor = this.getConnection(session.clientID);
if (descriptor != null) {
result.setConnectionEstablished(true);
BytesMetrics bytesMetrics = descriptor.getBytesMetrics();
MessageMetrics messageMetrics = descriptor.getMessageMetrics();
result.setConnectionMetrics(new MqttConnectionMetrics(bytesMetrics.readBytes(), bytesMetrics.wroteBytes(),
messageMetrics.messagesRead(), messageMetrics.messagesWrote()));
} else {
result.setConnectionEstablished(false);
}
result.setPendingPublishMessagesNo(session.getPendingPublishMessagesNo());
result.setSecondPhaseAckPendingMessages(session.getSecondPhaseAckPendingMessages());
result.setInflightMessages(session.getInflightMessagesNo());
return result;
}
}
|
LOG.info("Retrieving status of all sessions.");
Collection<MqttSession> result = new ArrayList<>();
for (ClientSession session : sessionsStore.getAllSessions()) {
result.add(buildMqttSession(session));
}
return result;
| 1,260
| 71
| 1,331
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/DefaultMoquetteSslContextCreator.java
|
DefaultMoquetteSslContextCreator
|
initSSLContext
|
class DefaultMoquetteSslContextCreator implements ISslContextCreator {
private static final Logger LOG = LoggerFactory.getLogger(DefaultMoquetteSslContextCreator.class);
private IConfig props;
public DefaultMoquetteSslContextCreator(IConfig props) {
this.props = props;
}
@Override
public SSLContext initSSLContext() {<FILL_FUNCTION_BODY>}
private InputStream jksDatastore(String jksPath) throws FileNotFoundException {
URL jksUrl = getClass().getClassLoader().getResource(jksPath);
if (jksUrl != null) {
LOG.info("Starting with jks at {}, jks normal {}", jksUrl.toExternalForm(), jksUrl);
return getClass().getClassLoader().getResourceAsStream(jksPath);
}
LOG.warn("No keystore has been found in the bundled resources. Scanning filesystem...");
File jksFile = new File(jksPath);
if (jksFile.exists()) {
LOG.info("Loading external keystore. Url = {}.", jksFile.getAbsolutePath());
return new FileInputStream(jksFile);
}
LOG.warn("The keystore file does not exist. Url = {}.", jksFile.getAbsolutePath());
return null;
}
}
|
LOG.info("Checking SSL configuration properties...");
final String jksPath = props.getProperty(BrokerConstants.JKS_PATH_PROPERTY_NAME);
LOG.info("Initializing SSL context. KeystorePath = {}.", jksPath);
if (jksPath == null || jksPath.isEmpty()) {
// key_store_password or key_manager_password are empty
LOG.warn("The keystore path is null or empty. The SSL context won't be initialized.");
return null;
}
// if we have the port also the jks then keyStorePassword and keyManagerPassword
// has to be defined
final String keyStorePassword = props.getProperty(BrokerConstants.KEY_STORE_PASSWORD_PROPERTY_NAME);
final String keyManagerPassword = props.getProperty(BrokerConstants.KEY_MANAGER_PASSWORD_PROPERTY_NAME);
if (keyStorePassword == null || keyStorePassword.isEmpty()) {
// key_store_password or key_manager_password are empty
LOG.warn("The keystore password is null or empty. The SSL context won't be initialized.");
return null;
}
if (keyManagerPassword == null || keyManagerPassword.isEmpty()) {
// key_manager_password or key_manager_password are empty
LOG.warn("The key manager password is null or empty. The SSL context won't be initialized.");
return null;
}
// if client authentification is enabled a trustmanager needs to be
// added to the ServerContext
String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false");
boolean needsClientAuth = Boolean.valueOf(sNeedsClientAuth);
try {
LOG.info("Loading keystore. KeystorePath = {}.", jksPath);
InputStream jksInputStream = jksDatastore(jksPath);
SSLContext serverContext = SSLContext.getInstance("TLS");
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(jksInputStream, keyStorePassword.toCharArray());
LOG.info("Initializing key manager...");
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keyManagerPassword.toCharArray());
TrustManager[] trustManagers = null;
if (needsClientAuth) {
LOG.warn(
"Client authentication is enabled. "
+ "The keystore will be used as a truststore. KeystorePath = {}.",
jksPath);
// use keystore as truststore, as server needs to trust certificates signed by the
// server certificates
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
trustManagers = tmf.getTrustManagers();
}
// init sslContext
LOG.info("Initializing SSL context...");
serverContext.init(kmf.getKeyManagers(), trustManagers, null);
LOG.info("The SSL context has been initialized successfully.");
return serverContext;
} catch (NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | KeyStoreException
| KeyManagementException | IOException ex) {
LOG.error(
"Unable to initialize SSL context. Cause = {}, errorMessage = {}.",
ex.getCause(),
ex.getMessage());
return null;
}
| 347
| 864
| 1,211
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/config/ClasspathResourceLoader.java
|
ClasspathResourceLoader
|
loadResource
|
class ClasspathResourceLoader implements IResourceLoader {
private static final Logger LOG = LoggerFactory.getLogger(ClasspathResourceLoader.class);
private final String defaultResource;
private final ClassLoader classLoader;
public ClasspathResourceLoader() {
this(IConfig.DEFAULT_CONFIG);
}
public ClasspathResourceLoader(String defaultResource) {
this(defaultResource, Thread.currentThread().getContextClassLoader());
}
public ClasspathResourceLoader(String defaultResource, ClassLoader classLoader) {
this.defaultResource = defaultResource;
this.classLoader = classLoader;
}
@Override
public Reader loadDefaultResource() {
return loadResource(defaultResource);
}
@Override
public Reader loadResource(String relativePath) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "classpath resource";
}
}
|
LOG.info("Loading resource. RelativePath = {}.", relativePath);
InputStream is = this.classLoader.getResourceAsStream(relativePath);
return is != null ? new InputStreamReader(is) : null;
| 235
| 58
| 293
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/config/ConfigurationParser.java
|
ConfigurationParser
|
parse
|
class ConfigurationParser {
private static final Logger LOG = LoggerFactory.getLogger(ConfigurationParser.class);
private Properties m_properties = new Properties();
/**
* Parse the configuration from file.
*/
void parse(File file) throws ParseException {
if (file == null) {
LOG.warn("parsing NULL file, so fallback on default configuration!");
return;
}
if (!file.exists()) {
LOG.warn(
String.format(
"parsing not existing file %s, so fallback on default configuration!",
file.getAbsolutePath()));
return;
}
try {
FileReader reader = new FileReader(file);
parse(reader);
} catch (FileNotFoundException fex) {
LOG.warn(
String.format(
"parsing not existing file %s, so fallback on default configuration!",
file.getAbsolutePath()),
fex);
return;
}
}
/**
* Parse the configuration
*
* @throws ParseException
* if the format is not compliant.
*/
void parse(Reader reader) throws ParseException {<FILL_FUNCTION_BODY>}
Properties getProperties() {
return m_properties;
}
}
|
if (reader == null) {
// just log and return default properties
LOG.warn("parsing NULL reader, so fallback on default configuration!");
return;
}
BufferedReader br = new BufferedReader(reader);
String line;
try {
while ((line = br.readLine()) != null) {
line = line.trim();
int commentMarker = line.indexOf('#');
if (commentMarker != -1) {
if (commentMarker == 0) {
// skip its a comment
continue;
} else {
String[] ss = line.split(" ");
if(ss.length != 2) {
throw new ParseException(line, commentMarker);
}
}
} else {
if (line.isEmpty() || line.matches("^\\s*$")) {
// skip it's a black line
continue;
}
}
// split till the first space
int delimiterIdx = line.indexOf(' ');
String key;
String value = "";
if (delimiterIdx > 0) {
key = line.substring(0, delimiterIdx).trim();
value = line.substring(delimiterIdx).trim();
} else {
key = line.trim();
}
m_properties.put(key, value);
}
} catch (IOException ex) {
throw new ParseException("Failed to read", 1);
} finally {
try {
reader.close();
} catch (IOException e) {
// ignore
}
}
| 331
| 406
| 737
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/config/FileResourceLoader.java
|
FileResourceLoader
|
loadResource
|
class FileResourceLoader implements IResourceLoader {
private static final Logger LOG = LoggerFactory.getLogger(FileResourceLoader.class);
private final File defaultFile;
private final String parentPath;
public FileResourceLoader() {
this((File) null);
}
public FileResourceLoader(File defaultFile) {
this(defaultFile, System.getProperty("wildfirechat.path", null));
}
public FileResourceLoader(String parentPath) {
this(null, parentPath);
}
public FileResourceLoader(File defaultFile, String parentPath) {
this.defaultFile = defaultFile;
this.parentPath = parentPath;
}
@Override
public Reader loadDefaultResource() {
if (defaultFile != null) {
return loadResource(defaultFile);
} else {
throw new IllegalArgumentException("Default file not set!");
}
}
@Override
public Reader loadResource(String relativePath) {
return loadResource(new File(parentPath, relativePath));
}
public Reader loadResource(File f) {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return "file";
}
}
|
LOG.info("Loading file. Path = {}.", f.getAbsolutePath());
if (f.isDirectory()) {
LOG.error("The given file is a directory. Path = {}.", f.getAbsolutePath());
throw new ResourceIsDirectoryException("File \"" + f + "\" is a directory!");
}
try {
return new FileReader(f);
} catch (FileNotFoundException e) {
LOG.error("The file does not exist. Path = {}.", f.getAbsolutePath());
return null;
}
| 313
| 137
| 450
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/netty/AutoFlushHandler.java
|
WriterIdleTimeoutTask
|
run
|
class WriterIdleTimeoutTask implements Runnable {
private final ChannelHandlerContext ctx;
WriterIdleTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
if (!ctx.channel().isOpen()) {
return;
}
// long lastWriteTime = IdleStateHandler.this.lastWriteTime;
// long lastWriteTime = lastWriteTime;
long nextDelay = writerIdleTimeNanos - (System.nanoTime() - lastWriteTime);
if (nextDelay <= 0) {
// Writer is idle - set a new timeout and notify the callback.
writerIdleTimeout = ctx.executor().schedule(this, writerIdleTimeNanos, TimeUnit.NANOSECONDS);
try {
/*
* IdleStateEvent event; if (firstWriterIdleEvent) { firstWriterIdleEvent =
* false; event = IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT; } else { event =
* IdleStateEvent.WRITER_IDLE_STATE_EVENT; }
*/
channelIdle(ctx/* , event */);
} catch (Throwable t) {
ctx.fireExceptionCaught(t);
}
} else {
// Write occurred before the timeout - set a new timeout with shorter delay.
writerIdleTimeout = ctx.executor().schedule(this, nextDelay, TimeUnit.NANOSECONDS);
}
| 77
| 318
| 395
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/netty/MoquetteIdleTimeoutHandler.java
|
MoquetteIdleTimeoutHandler
|
userEventTriggered
|
class MoquetteIdleTimeoutHandler extends ChannelDuplexHandler {
private static final Logger LOG = LoggerFactory.getLogger(MoquetteIdleTimeoutHandler.class);
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (evt instanceof IdleStateEvent) {
IdleState e = ((IdleStateEvent) evt).state();
if (e == IdleState.READER_IDLE) {
LOG.info("Firing channel inactive event. MqttClientId = {}.", NettyUtils.clientID(ctx.channel()));
// fire a channelInactive to trigger publish of Will
ctx.fireChannelInactive();
ctx.close();
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug(
"Firing Netty event. MqttClientId = {}, eventClass = {}.",
NettyUtils.clientID(ctx.channel()),
evt.getClass().getName());
}
super.userEventTriggered(ctx, evt);
}
| 84
| 201
| 285
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/netty/NettyAcceptor.java
|
PipelineInitializer
|
initFactory
|
class PipelineInitializer {
abstract void init(ChannelPipeline pipeline) throws Exception;
}
private static final Logger LOG = LoggerFactory.getLogger(NettyAcceptor.class);
EventLoopGroup m_bossGroup;
EventLoopGroup m_workerGroup;
BytesMetricsCollector m_bytesMetricsCollector = new BytesMetricsCollector();
MessageMetricsCollector m_metricsCollector = new MessageMetricsCollector();
private Optional<? extends ChannelInboundHandler> metrics;
private Optional<? extends ChannelInboundHandler> errorsCather;
private int nettySoBacklog;
private boolean nettySoReuseaddr;
private boolean nettyTcpNodelay;
private boolean nettySoKeepalive;
private int nettyChannelTimeoutSeconds;
private Class<? extends ServerSocketChannel> channelClass;
@Override
public void initialize(ProtocolProcessor processor, IConfig props, ISslContextCreator sslCtxCreator)
throws IOException {
LOG.info("Initializing Netty acceptor...");
nettySoBacklog = Integer.parseInt(props.getProperty(BrokerConstants.NETTY_SO_BACKLOG_PROPERTY_NAME, "128"));
nettySoReuseaddr = Boolean
.parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_REUSEADDR_PROPERTY_NAME, "true"));
nettyTcpNodelay = Boolean
.parseBoolean(props.getProperty(BrokerConstants.NETTY_TCP_NODELAY_PROPERTY_NAME, "true"));
nettySoKeepalive = Boolean
.parseBoolean(props.getProperty(BrokerConstants.NETTY_SO_KEEPALIVE_PROPERTY_NAME, "true"));
nettyChannelTimeoutSeconds = Integer
.parseInt(props.getProperty(BrokerConstants.NETTY_CHANNEL_TIMEOUT_SECONDS_PROPERTY_NAME, "10"));
boolean epoll = Boolean.parseBoolean(props.getProperty(BrokerConstants.NETTY_EPOLL_PROPERTY_NAME, "false"));
if (epoll) {
// 由于目前只支持TCP MQTT, 所以bossGroup的线程数配置为1
LOG.info("Netty is using Epoll");
m_bossGroup = new EpollEventLoopGroup(1);
m_workerGroup = new EpollEventLoopGroup();
channelClass = EpollServerSocketChannel.class;
} else {
LOG.info("Netty is using NIO");
m_bossGroup = new NioEventLoopGroup(1);
m_workerGroup = new NioEventLoopGroup();
channelClass = NioServerSocketChannel.class;
}
final NettyMQTTHandler mqttHandler = new NettyMQTTHandler(processor);
this.metrics = Optional.empty();
this.errorsCather = Optional.empty();
initializePlainTCPTransport(mqttHandler, props);
}
private void initFactory(String host, int port, String protocol, final PipelineInitializer pipeliner) {<FILL_FUNCTION_BODY>
|
LOG.info("Initializing server. Protocol={}", protocol);
ServerBootstrap b = new ServerBootstrap();
b.group(m_bossGroup, m_workerGroup).channel(channelClass)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
try {
pipeliner.init(pipeline);
} catch (Throwable th) {
LOG.error("Severe error during pipeline creation", th);
throw th;
}
}
})
.option(ChannelOption.SO_BACKLOG, 10240) // 服务端可连接队列大小
.option(ChannelOption.SO_BACKLOG, nettySoBacklog)
.option(ChannelOption.SO_REUSEADDR, nettySoReuseaddr)
.childOption(ChannelOption.TCP_NODELAY, nettyTcpNodelay)
.childOption(ChannelOption.SO_KEEPALIVE, nettySoKeepalive);
try {
LOG.info("Binding server. host={}, port={}", host, port);
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(host, port);
LOG.info("Server has been bound. host={}, port={}", host, port);
f.sync().addListener(FIRE_EXCEPTION_ON_FAILURE);
} catch (InterruptedException ex) {
LOG.error("An interruptedException was caught while initializing server. Protocol={}", protocol, ex);
} catch (Exception e) {
e.printStackTrace();
LOG.error("端口 {} 已经被占用或者无权限使用。如果无权限使用,请以root权限运行;如果被占用,请检查该端口被那个程序占用,找到程序停掉。\n查找端口被那个程序占用的命令是: netstat -tunlp | grep {}", port, port);
System.out.println("端口 " + port + " 已经被占用或者无权限使用。如果无权限使用,请以root权限运行;如果被占用,请检查该端口被那个程序占用,找到程序停掉。\n查找端口被那个程序占用的命令是: netstat -tunlp | grep " + port);
System.exit(-1);
}
| 786
| 602
| 1,388
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/netty/NettyMQTTHandler.java
|
NettyMQTTHandler
|
channelRead
|
class NettyMQTTHandler extends ChannelInboundHandlerAdapter {
private static final Logger LOG = LoggerFactory.getLogger(NettyMQTTHandler.class);
private final ProtocolProcessor m_processor;
public NettyMQTTHandler(ProtocolProcessor processor) {
m_processor = processor;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {<FILL_FUNCTION_BODY>}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
String clientID = NettyUtils.clientID(ctx.channel());
if (clientID != null && !clientID.isEmpty()) {
LOG.info("Notifying connection lost event. MqttClientId = {}.", clientID);
m_processor.processConnectionLost(clientID, ctx.channel(), false);
}
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.error("An unexpected exception was caught while processing MQTT message. Closing Netty channel. CId={}, " +
"cause={}, errorMessage={}", NettyUtils.clientID(ctx.channel()), cause.getCause(), cause.getMessage());
for (StackTraceElement ste : cause.getStackTrace()) {
LOG.error(ste.toString());
}
ctx.close();
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
if (ctx.channel().isWritable()) {
m_processor.notifyChannelWritable(ctx.channel());
}
ctx.fireChannelWritabilityChanged();
}
}
|
try {
if (!(message instanceof MqttMessage)) {
LOG.error("Unknown mqtt message type {}, {}", message.getClass().getName(), message);
return;
}
MqttMessage msg = (MqttMessage) message;
MqttMessageType messageType = msg.fixedHeader().messageType();
LOG.info("Processing MQTT message, type={}", messageType);
switch (messageType) {
case CONNECT:
m_processor.processConnect(ctx.channel(), (MqttConnectMessage) msg);
break;
case SUBSCRIBE:
m_processor.processSubscribe(ctx.channel(), (MqttSubscribeMessage) msg);
break;
case UNSUBSCRIBE:
m_processor.processUnsubscribe(ctx.channel(), (MqttUnsubscribeMessage) msg);
break;
case PUBLISH:
m_processor.processPublish(ctx.channel(), (MqttPublishMessage) msg);
break;
case PUBREC:
m_processor.processPubRec(ctx.channel(), msg);
break;
case PUBCOMP:
m_processor.processPubComp(ctx.channel(), msg);
break;
case PUBREL:
m_processor.processPubRel(ctx.channel(), msg);
break;
case DISCONNECT:
m_processor.processDisconnect(ctx.channel(), msg.fixedHeader().isDup(), msg.fixedHeader().isRetain());
break;
case PUBACK:
m_processor.processPubAck(ctx.channel(), (MqttPubAckMessage) msg);
break;
case PINGREQ:
MqttFixedHeader pingHeader = new MqttFixedHeader(
MqttMessageType.PINGRESP,
false,
AT_MOST_ONCE,
false,
0);
MqttMessage pingResp = new MqttMessage(pingHeader);
ctx.writeAndFlush(pingResp);
break;
default:
LOG.error("Unkonwn MessageType:{}", messageType);
break;
}
} catch (Throwable ex) {
LOG.error("Exception was caught while processing MQTT message, " + ex.getCause(), ex);
ctx.fireExceptionCaught(ex);
ctx.close();
} finally {
ReferenceCountUtil.release(message);
}
| 423
| 613
| 1,036
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/netty/metrics/BytesMetricsCollector.java
|
BytesMetricsCollector
|
computeMetrics
|
class BytesMetricsCollector {
private AtomicLong readBytes = new AtomicLong();
private AtomicLong wroteBytes = new AtomicLong();
public BytesMetrics computeMetrics() {<FILL_FUNCTION_BODY>}
public void sumReadBytes(long count) {
readBytes.getAndAdd(count);
}
public void sumWroteBytes(long count) {
wroteBytes.getAndAdd(count);
}
}
|
BytesMetrics allMetrics = new BytesMetrics();
allMetrics.incrementRead(readBytes.get());
allMetrics.incrementWrote(wroteBytes.get());
return allMetrics;
| 117
| 52
| 169
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/netty/metrics/BytesMetricsHandler.java
|
BytesMetricsHandler
|
close
|
class BytesMetricsHandler extends ChannelDuplexHandler {
private static final Logger LOG = LoggerFactory.getLogger(BytesMetricsHandler.class);
private static final AttributeKey<BytesMetrics> ATTR_KEY_METRICS = AttributeKey.valueOf("BytesMetrics");
private static final AttributeKey<String> ATTR_KEY_USERNAME = AttributeKey.valueOf(ATTR_USERNAME);
private BytesMetricsCollector m_collector;
public BytesMetricsHandler(BytesMetricsCollector collector) {
m_collector = collector;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Attribute<BytesMetrics> attr = ctx.channel().attr(ATTR_KEY_METRICS);
attr.set(new BytesMetrics());
super.channelActive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
BytesMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
metrics.incrementRead(((ByteBuf) msg).readableBytes());
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
BytesMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
metrics.incrementWrote(((ByteBuf) msg).writableBytes());
ctx.write(msg, promise);
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {<FILL_FUNCTION_BODY>}
public static BytesMetrics getBytesMetrics(Channel channel) {
return channel.attr(ATTR_KEY_METRICS).get();
}
}
|
BytesMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
String userId = ctx.channel().attr(ATTR_KEY_USERNAME).get();
if (userId == null) {
userId = "";
}
LOG.info("channel<{}> closing after read {} bytes and wrote {} bytes", userId, metrics.readBytes(), metrics.wroteBytes());
m_collector.sumReadBytes(metrics.readBytes());
m_collector.sumWroteBytes(metrics.wroteBytes());
super.close(ctx, promise);
| 443
| 149
| 592
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/netty/metrics/MQTTMessageLogger.java
|
MQTTMessageLogger
|
logMQTTMessage
|
class MQTTMessageLogger extends ChannelDuplexHandler {
private static final Logger LOG = LoggerFactory.getLogger("messageLogger");
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) {
logMQTTMessage(ctx, message, "C->B");
ctx.fireChannelRead(message);
}
private void logMQTTMessage(ChannelHandlerContext ctx, Object message, String direction) {<FILL_FUNCTION_BODY>}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
String clientID = NettyUtils.clientID(ctx.channel());
if (clientID != null && !clientID.isEmpty()) {
LOG.info("Channel closed <{}>", clientID);
}
ctx.fireChannelInactive();
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
logMQTTMessage(ctx, msg, "C<-B");
ctx.write(msg, promise);
}
}
|
if (!(message instanceof MqttMessage)) {
return;
}
MqttMessage msg = (MqttMessage) message;
String clientID = NettyUtils.clientID(ctx.channel());
MqttMessageType messageType = msg.fixedHeader().messageType();
switch (messageType) {
case CONNECT:
case CONNACK:
case PINGREQ:
case PINGRESP:
case DISCONNECT:
LOG.info("{} {} <{}>", direction, messageType, clientID);
break;
case SUBSCRIBE:
MqttSubscribeMessage subscribe = (MqttSubscribeMessage) msg;
LOG.info("{} SUBSCRIBE <{}> to topics {}", direction, clientID,
subscribe.payload().topicSubscriptions());
break;
case UNSUBSCRIBE:
MqttUnsubscribeMessage unsubscribe = (MqttUnsubscribeMessage) msg;
LOG.info("{} UNSUBSCRIBE <{}> to topics <{}>", direction, clientID, unsubscribe.payload().topics());
break;
case PUBLISH:
MqttPublishMessage publish = (MqttPublishMessage) msg;
LOG.info("{} PUBLISH <{}> to topics <{}>", direction, clientID, publish.variableHeader().topicName());
break;
case PUBREC:
case PUBCOMP:
case PUBREL:
case PUBACK:
case UNSUBACK:
LOG.info("{} {} <{}> packetID <{}>", direction, messageType, clientID, messageId(msg));
break;
case SUBACK:
MqttSubAckMessage suback = (MqttSubAckMessage) msg;
final List<Integer> grantedQoSLevels = suback.payload().grantedQoSLevels();
LOG.info("{} SUBACK <{}> packetID <{}>, grantedQoses {}", direction, clientID, messageId(msg),
grantedQoSLevels);
break;
}
| 265
| 522
| 787
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/netty/metrics/MessageMetricsCollector.java
|
MessageMetricsCollector
|
computeMetrics
|
class MessageMetricsCollector {
private AtomicLong readMsgs = new AtomicLong();
private AtomicLong wroteMsgs = new AtomicLong();
public MessageMetrics computeMetrics() {<FILL_FUNCTION_BODY>}
public void sumReadMessages(long count) {
readMsgs.getAndAdd(count);
}
public void sumWroteMessages(long count) {
wroteMsgs.getAndAdd(count);
}
}
|
MessageMetrics allMetrics = new MessageMetrics();
allMetrics.incrementRead(readMsgs.get());
allMetrics.incrementWrote(wroteMsgs.get());
return allMetrics;
| 119
| 52
| 171
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/server/netty/metrics/MessageMetricsHandler.java
|
MessageMetricsHandler
|
close
|
class MessageMetricsHandler extends ChannelDuplexHandler {
private static final Logger LOG = LoggerFactory.getLogger(MessageMetricsHandler.class);
private static final AttributeKey<MessageMetrics> ATTR_KEY_METRICS = AttributeKey.valueOf("MessageMetrics");
private static final AttributeKey<String> ATTR_KEY_USERNAME = AttributeKey.valueOf(ATTR_USERNAME);
private MessageMetricsCollector m_collector;
public MessageMetricsHandler(MessageMetricsCollector collector) {
m_collector = collector;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Attribute<MessageMetrics> attr = ctx.channel().attr(ATTR_KEY_METRICS);
attr.set(new MessageMetrics());
super.channelActive(ctx);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
MessageMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
metrics.incrementRead(1);
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
MessageMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
metrics.incrementWrote(1);
ctx.write(msg, promise);
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {<FILL_FUNCTION_BODY>}
public static MessageMetrics getMessageMetrics(Channel channel) {
return channel.attr(ATTR_KEY_METRICS).get();
}
}
|
MessageMetrics metrics = ctx.channel().attr(ATTR_KEY_METRICS).get();
String userId = ctx.channel().attr(ATTR_KEY_USERNAME).get();
if (userId == null) {
userId = "";
}
LOG.info("channel<{}> closing after read {} messages and wrote {} messages", userId, metrics.messagesRead(), metrics.messagesWrote());
m_collector.sumReadMessages(metrics.messagesRead());
m_collector.sumWroteMessages(metrics.messagesWrote());
super.close(ctx, promise);
| 421
| 148
| 569
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/ClientSession.java
|
InboundFlightZone
|
inFlightAckWaiting
|
class InboundFlightZone {
public IMessagesStore.StoredMessage lookup(int messageID) {
return m_sessionsStore.inboundInflight(clientID, messageID);
}
public void waitingRel(int messageID, IMessagesStore.StoredMessage msg) {
m_sessionsStore.markAsInboundInflight(clientID, messageID, msg);
}
}
private static final Logger LOG = LoggerFactory.getLogger(ClientSession.class);
public final String clientID;
private final ISessionsStore m_sessionsStore;
// private BlockingQueue<AbstractMessage> m_queueToPublish = new
// ArrayBlockingQueue<>(Constants.MAX_MESSAGE_QUEUE);
private final OutboundFlightZone outboundFlightZone;
private final InboundFlightZone inboundFlightZone;
public ClientSession(String clientID, ISessionsStore sessionsStore) {
this.clientID = clientID;
this.m_sessionsStore = sessionsStore;
this.outboundFlightZone = new OutboundFlightZone();
this.inboundFlightZone = new InboundFlightZone();
}
/**
* Return the list of persisted publishes for the given clientID. For QoS1 and QoS2 with clean
* session flag, this method return the list of missed publish events while the client was
* disconnected.
*
* @return the list of messages to be delivered for client related to the session.
*/
public Queue<IMessagesStore.StoredMessage> queue() {
LOG.info("Retrieving enqueued messages. CId={}", clientID);
return this.m_sessionsStore.queue(clientID);
}
@Override
public String toString() {
return "ClientSession{clientID='" + clientID + '\'' + "}";
}
public void disconnect(String userId, boolean cleanSession, boolean disableSession) {
if (cleanSession) {
LOG.info("Client disconnected. Removing its subscriptions. ClientId={}", clientID);
// cleanup topic subscriptions
cleanSession(userId);
} else if(disableSession) {
LOG.info("Client disconnected. disable session. ClientId={}", clientID);
m_sessionsStore.disableSession(userId, this.clientID);
}
}
public void cleanSession(String userId) {
m_sessionsStore.cleanSession(userId, this.clientID);
}
public int nextPacketId() {
return this.m_sessionsStore.nextPacketID(this.clientID);
}
public IMessagesStore.StoredMessage inFlightAcknowledged(int messageID) {
return outboundFlightZone.acknowledged(messageID);
}
/**
* Mark the message identified by guid as publish in flight.
*
* @return the packetID for the message in flight.
* */
public int inFlightAckWaiting(IMessagesStore.StoredMessage msg) {<FILL_FUNCTION_BODY>
|
LOG.debug("Adding message ot inflight zone. ClientId={}", clientID);
int messageId = ClientSession.this.nextPacketId();
outboundFlightZone.waitingAck(messageId, msg);
return messageId;
| 781
| 65
| 846
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/MessageGUID.java
|
MessageGUID
|
toString
|
class MessageGUID implements Serializable {
private static final long serialVersionUID = 4315161987111542406L;
private final String guid;
public MessageGUID(String guid) {
this.guid = guid;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
MessageGUID that = (MessageGUID) o;
return guid != null ? guid.equals(that.guid) : that.guid == null;
}
@Override
public int hashCode() {
return guid != null ? guid.hashCode() : 0;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "MessageGUID{" + "guid='" + guid + '\'' + '}';
| 227
| 26
| 253
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/BrokerInterceptor.java
|
BrokerInterceptor
|
notifyClientDisconnected
|
class BrokerInterceptor implements Interceptor {
private static final Logger LOG = LoggerFactory.getLogger(BrokerInterceptor.class);
private final Map<Class<?>, List<InterceptHandler>> handlers;
private final ExecutorService executor;
private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers) {
LOG.info("Initializing broker interceptor. InterceptorIds={}", getInterceptorIds(handlers));
this.handlers = new HashMap<>();
for (Class<?> messageType : InterceptHandler.ALL_MESSAGE_TYPES) {
this.handlers.put(messageType, new CopyOnWriteArrayList<InterceptHandler>());
}
for (InterceptHandler handler : handlers) {
this.addInterceptHandler(handler);
}
executor = Executors.newFixedThreadPool(poolSize);
}
/**
* Configures a broker interceptor, with a thread pool of one thread.
*
* @param handlers
*/
BrokerInterceptor(List<InterceptHandler> handlers) {
this(1, handlers);
}
/**
* Configures a broker interceptor using the pool size specified in the IConfig argument.
*/
BrokerInterceptor(IConfig props, List<InterceptHandler> handlers) {
this(Integer.parseInt(props.getProperty(BrokerConstants.BROKER_INTERCEPTOR_THREAD_POOL_SIZE, "1")), handlers);
}
/**
* Shutdown graciously the executor service
*/
void stop() {
LOG.info("Shutting down interceptor thread pool...");
executor.shutdown();
try {
LOG.info("Waiting for thread pool tasks to terminate...");
executor.awaitTermination(10L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
if (!executor.isTerminated()) {
LOG.warn("Forcing shutdown of interceptor thread pool...");
executor.shutdownNow();
}
}
@Override
public void notifyClientConnected(final MqttConnectMessage msg) {
for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) {
LOG.debug("Sending MQTT CONNECT message to interceptor. CId={}, interceptorId={}",
msg.payload().clientIdentifier(), handler.getID());
executor.execute(() -> handler.onConnect(new InterceptConnectMessage(msg)));
}
}
@Override
public void notifyClientDisconnected(final String clientID, final String username) {<FILL_FUNCTION_BODY>}
@Override
public void notifyClientConnectionLost(final String clientID, final String username) {
for (final InterceptHandler handler : this.handlers.get(InterceptConnectionLostMessage.class)) {
LOG.debug("Notifying unexpected MQTT client disconnection to interceptor CId={}, username={}, " +
"interceptorId={}", clientID, username, handler.getID());
executor.execute(() -> handler.onConnectionLost(new InterceptConnectionLostMessage(clientID, username)));
}
}
@Override
public void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg) {
for (final InterceptHandler handler : this.handlers.get(InterceptAcknowledgedMessage.class)) {
LOG.debug("Notifying MQTT ACK message to interceptor. CId={}, messageId={}, topic={}, interceptorId={}",
msg.getMsg().getClientID(), msg.getPacketID(), msg.getTopic(), handler.getID());
executor.execute(() -> handler.onMessageAcknowledged(msg));
}
}
@Override
public void addInterceptHandler(InterceptHandler interceptHandler) {
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
LOG.info("Adding MQTT message interceptor. InterceptorId={}, handledMessageTypes={}",
interceptHandler.getID(), interceptedMessageTypes);
for (Class<?> interceptMessageType : interceptedMessageTypes) {
this.handlers.get(interceptMessageType).add(interceptHandler);
}
}
@Override
public void removeInterceptHandler(InterceptHandler interceptHandler) {
Class<?>[] interceptedMessageTypes = getInterceptedMessageTypes(interceptHandler);
LOG.info("Removing MQTT message interceptor. InterceptorId={}, handledMessageTypes={}",
interceptHandler.getID(), interceptedMessageTypes);
for (Class<?> interceptMessageType : interceptedMessageTypes) {
this.handlers.get(interceptMessageType).remove(interceptHandler);
}
}
private static Class<?>[] getInterceptedMessageTypes(InterceptHandler interceptHandler) {
Class<?>[] interceptedMessageTypes = interceptHandler.getInterceptedMessageTypes();
if (interceptedMessageTypes == null) {
return InterceptHandler.ALL_MESSAGE_TYPES;
}
return interceptedMessageTypes;
}
}
|
for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) {
LOG.debug("Notifying MQTT client disconnection to interceptor. CId={}, username={}, interceptorId={}",
clientID, username, handler.getID());
executor.execute(() -> handler.onDisconnect(new InterceptDisconnectMessage(clientID, username)));
}
| 1,355
| 106
| 1,461
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/DesUtil.java
|
DesUtil
|
encrypt
|
class DesUtil {
private final static String Key = "abcdefgh";
private final static String DES = "AES";
public static void main(String[] args) throws Exception {
String data = "123 456";
System.err.println(encrypt(data));
System.err.println(decrypt(encrypt(data)));
System.out.println(decrypt("JF5dX/TlOg529KAhh+vywjzIp5Msktmf"));
}
/**
* Description 根据键值进行加密
* @param data
* @return
* @throws Exception
*/
public static String encrypt(String data) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Description 根据键值进行解密
* @param data
* @return
* @throws IOException
* @throws Exception
*/
public static String decrypt(String data) throws IOException,
Exception {
if (data == null)
return null;
byte[] buf = Base64.getDecoder().decode(data);
byte[] bt = decrypt(buf,Key.getBytes());
return new String(bt);
}
/**
* Description 根据键值进行加密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
/**
* Description 根据键值进行解密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
}
|
byte[] bt = encrypt(data.getBytes(), Key.getBytes());
String strs = new String(Base64.getEncoder().encode(bt));
return strs;
| 853
| 50
| 903
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/InternalRepublisher.java
|
InternalRepublisher
|
publishRetained
|
class InternalRepublisher {
private static final Logger LOG = LoggerFactory.getLogger(InternalRepublisher.class);
private final PersistentQueueMessageSender messageSender;
InternalRepublisher(PersistentQueueMessageSender messageSender) {
this.messageSender = messageSender;
}
void publishRetained(ClientSession targetSession, Collection<IMessagesStore.StoredMessage> messages) {<FILL_FUNCTION_BODY>}
void publishStored(ClientSession clientSession, Queue<IMessagesStore.StoredMessage> publishedEvents) {
IMessagesStore.StoredMessage pubEvt;
while ((pubEvt = publishedEvents.poll()) != null) {
// put in flight zone
LOG.debug("Adding message ot inflight zone. ClientId={}, guid={}, topic={}", clientSession.clientID,
pubEvt.getGuid(), pubEvt.getTopic());
int messageId = clientSession.inFlightAckWaiting(pubEvt);
MqttPublishMessage publishMsg = notRetainedPublish(pubEvt);
// set the PacketIdentifier only for QoS > 0
if (publishMsg.fixedHeader().qosLevel() != MqttQoS.AT_MOST_ONCE) {
publishMsg = notRetainedPublish(pubEvt, messageId);
}
this.messageSender.sendPublish(clientSession, publishMsg);
}
}
private MqttPublishMessage notRetainedPublish(IMessagesStore.StoredMessage storedMessage, Integer messageID) {
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getPayload(), false,
messageID);
}
private MqttPublishMessage notRetainedPublish(IMessagesStore.StoredMessage storedMessage) {
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getPayload(), false,
0);
}
private MqttPublishMessage retainedPublish(IMessagesStore.StoredMessage storedMessage) {
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getPayload(), true,
0);
}
private MqttPublishMessage retainedPublish(IMessagesStore.StoredMessage storedMessage, Integer packetID) {
return createPublishForQos(storedMessage.getTopic(), storedMessage.getQos(), storedMessage.getPayload(), true,
packetID);
}
public static MqttPublishMessage createPublishForQos(String topic, MqttQoS qos, ByteBuf message, boolean retained,
int messageId) {
MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0);
MqttPublishVariableHeader varHeader = new MqttPublishVariableHeader(topic, messageId);
return new MqttPublishMessage(fixedHeader, varHeader, message);
}
}
|
for (IMessagesStore.StoredMessage storedMsg : messages) {
// fire as retained the message
MqttPublishMessage publishMsg = retainedPublish(storedMsg);
if (storedMsg.getQos() != MqttQoS.AT_MOST_ONCE) {
LOG.debug("Adding message to inflight zone. ClientId={}, topic={}", targetSession.clientID,
storedMsg.getTopic());
int packetID = targetSession.inFlightAckWaiting(storedMsg);
// set the PacketIdentifier only for QoS > 0
publishMsg = retainedPublish(storedMsg, packetID);
}
this.messageSender.sendPublish(targetSession, publishMsg);
}
| 780
| 193
| 973
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/PersistentQueueMessageSender.java
|
PersistentQueueMessageSender
|
sendPublish
|
class PersistentQueueMessageSender {
private static final Logger LOG = LoggerFactory.getLogger(PersistentQueueMessageSender.class);
private final ConnectionDescriptorStore connectionDescriptorStore;
PersistentQueueMessageSender(ConnectionDescriptorStore connectionDescriptorStore) {
this.connectionDescriptorStore = connectionDescriptorStore;
}
void sendPush(String sender, int conversationType, String target, int line, long messageId, String deviceId, String pushContent, String pushData, int messageContentType, long serverTime, String senderName, String senderPortrait, String targetName, String targetPortrait, int unReceivedMsg, int mentionType, boolean isHiddenDetail, String language) {
LOG.info("Send push to {}, message from {}", deviceId, sender);
PushMessage pushMessage = new PushMessage(sender, conversationType, target, line, messageContentType, serverTime, senderName, senderPortrait, targetName, targetPortrait, unReceivedMsg, mentionType, isHiddenDetail, language);
pushMessage.pushContent = pushContent;
pushMessage.pushData = pushData;
pushMessage.messageId = messageId;
PushServer.getServer().pushMessage(pushMessage, deviceId, pushContent);
}
void sendPush(String sender, String target, String deviceId, String pushContent, int pushContentType, long serverTime, String senderName, int unReceivedMsg, String language) {
LOG.info("Send push to {}, message from {}", deviceId, sender);
PushMessage pushMessage = new PushMessage(sender, target, serverTime, senderName, unReceivedMsg, language, pushContentType);
pushMessage.pushContent = pushContent;
PushServer.getServer().pushMessage(pushMessage, deviceId, pushContent);
}
boolean sendPublish(ClientSession clientsession, MqttPublishMessage pubMessage) {
String clientId = clientsession.clientID;
return sendPublish(clientId, pubMessage);
}
boolean sendPublish(String clientId, MqttPublishMessage pubMessage) {<FILL_FUNCTION_BODY>}
}
|
final int messageId = pubMessage.variableHeader().packetId();
final String topicName = pubMessage.variableHeader().topicName();
if (LOG.isDebugEnabled()) {
LOG.debug("Sending PUBLISH message. MessageId={}, CId={}, topic={}, qos={}, payload={}", messageId,
clientId, topicName, DebugUtils.payload2Str(pubMessage.payload()));
} else {
LOG.info("Sending PUBLISH message. MessageId={}, CId={}, topic={}", messageId, clientId, topicName);
}
boolean messageDelivered = connectionDescriptorStore.sendMessage(pubMessage, messageId, clientId, null);
if(!messageDelivered) {
LOG.warn("PUBLISH message could not be delivered. MessageId={}, CId={}, topic={}", messageId, clientId, topicName);
}
return messageDelivered;
| 519
| 238
| 757
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/ProtocolProcessorBootstrapper.java
|
ProtocolProcessorBootstrapper
|
loadClass
|
class ProtocolProcessorBootstrapper {
private static final Logger LOG = LoggerFactory.getLogger(ProtocolProcessorBootstrapper.class);
public static final String INMEMDB_STORE_CLASS = "io.moquette.persistence.MemoryStorageService";
private ISessionsStore m_sessionsStore;
private Runnable storeShutdown;
private final ProtocolProcessor m_processor = new ProtocolProcessor();
private ConnectionDescriptorStore connectionDescriptors;
public ProtocolProcessorBootstrapper() {
}
/**
* Initialize the processing part of the broker.
*
* @param props
* the properties carrier where some props like port end host could be loaded. For
* the full list check of configurable properties check wildfirechat.conf file.
* @param embeddedObservers
* a list of callbacks to be notified of certain events inside the broker. Could be
* empty list of null.
* @param authenticator
* an implementation of the authenticator to be used, if null load that specified in
* config and fallback on the default one (permit all).
* @param authorizator
* an implementation of the authorizator to be used, if null load that specified in
* config and fallback on the default one (permit all).
* @param server
* the server to init.
* @return the processor created for the broker.
*/
public ProtocolProcessor init(IConfig props, List<? extends InterceptHandler> embeddedObservers,
IAuthenticator authenticator, IAuthorizator authorizator, Server server, IStore store) {
IMessagesStore messagesStore;
messagesStore = store.messagesStore();
m_sessionsStore = store.sessionsStore();
storeShutdown = new Runnable() {
@Override
public void run() {
store.close();
}
};
LOG.info("Configuring message interceptors...");
List<InterceptHandler> observers = new ArrayList<>(embeddedObservers);
String interceptorClassName = props.getProperty(BrokerConstants.INTERCEPT_HANDLER_PROPERTY_NAME);
if (interceptorClassName != null && !interceptorClassName.isEmpty()) {
InterceptHandler handler = loadClass(interceptorClassName, InterceptHandler.class, Server.class, server);
if (handler != null) {
observers.add(handler);
}
}
BrokerInterceptor interceptor = new BrokerInterceptor(props, observers);
LOG.info("Configuring MQTT authenticator...");
authenticator = new TokenAuthenticator();
LOG.info("Configuring MQTT authorizator...");
String authorizatorClassName = props.getProperty(BrokerConstants.AUTHORIZATOR_CLASS_NAME, "");
if (authorizator == null && !authorizatorClassName.isEmpty()) {
authorizator = loadClass(authorizatorClassName, IAuthorizator.class, IConfig.class, props);
}
if (authorizator == null) {
authorizator = new PermitAllAuthorizator();
LOG.info("An {} authorizator instance will be used", authorizator.getClass().getName());
}
LOG.info("Initializing connection descriptor store...");
connectionDescriptors = new ConnectionDescriptorStore(m_sessionsStore);
LOG.info("Initializing MQTT protocol processor...");
m_processor.init(connectionDescriptors, messagesStore, m_sessionsStore, authenticator, authorizator, interceptor, server);
return m_processor;
}
@SuppressWarnings("unchecked")
private <T, U> T loadClass(String className, Class<T> intrface, Class<U> constructorArgClass, U props) {<FILL_FUNCTION_BODY>}
public ISessionsStore getSessionsStore() {
return m_sessionsStore;
}
public void shutdown() {
if (storeShutdown != null)
storeShutdown.run();
if (m_processor != null)
m_processor.shutdown();
// if (m_interceptor != null)
// m_interceptor.stop();
}
public ConnectionDescriptorStore getConnectionDescriptors() {
return connectionDescriptors;
}
}
|
T instance = null;
try {
// check if constructor with constructor arg class parameter
// exists
LOG.info("Invoking constructor with {} argument. ClassName={}, interfaceName={}",
constructorArgClass.getName(), className, intrface.getName());
instance = this.getClass().getClassLoader()
.loadClass(className)
.asSubclass(intrface)
.getConstructor(constructorArgClass)
.newInstance(props);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
LOG.warn("Unable to invoke constructor with {} argument. ClassName={}, interfaceName={}, cause={}, errorMessage={}",
constructorArgClass.getName(), className, intrface.getName(), ex.getCause(), ex.getMessage());
return null;
} catch (NoSuchMethodException | InvocationTargetException e) {
try {
LOG.info("Invoking default constructor. ClassName={}, interfaceName={}",
className, intrface.getName());
// fallback to default constructor
instance = this.getClass().getClassLoader()
.loadClass(className)
.asSubclass(intrface)
.newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
LOG.error("Unable to invoke default constructor. ClassName={}, interfaceName={}, cause={}, errorMessage={}",
className, intrface.getName(), ex.getCause(), ex.getMessage());
return null;
}
}
return instance;
| 1,099
| 386
| 1,485
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/QosPublishHandler.java
|
QosPublishHandler
|
checkWriteOnTopic
|
class QosPublishHandler {
private static final Logger LOG = LoggerFactory.getLogger(QosPublishHandler.class);
protected final IAuthorizator m_authorizator;
protected QosPublishHandler(IAuthorizator m_authorizator) {
this.m_authorizator = m_authorizator;
}
public boolean checkWriteOnTopic(Topic topic, Channel channel) {<FILL_FUNCTION_BODY>}
}
|
String clientID = NettyUtils.clientID(channel);
String username = NettyUtils.userName(channel);
if (!m_authorizator.canWrite(topic, username, clientID)) {
LOG.error("MQTT client is not authorized to publish on topic. CId={}, topic={}", clientID, topic);
return true;
}
return false;
| 121
| 98
| 219
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/Utils.java
|
Utils
|
readBytesAndRewind
|
class Utils {
public static <T, K> T defaultGet(Map<K, T> map, K key, T defaultValue) {
T value = map.get(key);
if (value != null) {
return value;
}
return defaultValue;
}
public static int messageId(MqttMessage msg) {
return ((MqttMessageIdVariableHeader) msg.variableHeader()).messageId();
}
public static byte[] readBytesAndRewind(ByteBuf payload) {<FILL_FUNCTION_BODY>}
private Utils() {
}
}
|
byte[] payloadContent = new byte[payload.readableBytes()];
int mark = payload.readerIndex();
payload.readBytes(payloadContent);
payload.readerIndex(mark);
return payloadContent;
| 156
| 57
| 213
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/security/ACLFileParser.java
|
ACLFileParser
|
parse
|
class ACLFileParser {
private static final Logger LOG = LoggerFactory.getLogger(ACLFileParser.class);
/**
* Parse the configuration from file.
*
* @param file
* to parse
* @return the collector of authorizations form reader passed into.
* @throws ParseException
* if the format is not compliant.
*/
public static AuthorizationsCollector parse(File file) throws ParseException {
if (file == null) {
LOG.warn("parsing NULL file, so fallback on default configuration!");
return AuthorizationsCollector.emptyImmutableCollector();
}
if (!file.exists()) {
LOG.warn(
String.format(
"parsing not existing file %s, so fallback on default configuration!",
file.getAbsolutePath()));
return AuthorizationsCollector.emptyImmutableCollector();
}
try {
FileReader reader = new FileReader(file);
return parse(reader);
} catch (FileNotFoundException fex) {
LOG.warn(
String.format(
"parsing not existing file %s, so fallback on default configuration!",
file.getAbsolutePath()),
fex);
return AuthorizationsCollector.emptyImmutableCollector();
}
}
/**
* Parse the ACL configuration file
*
* @param reader
* to parse
* @return the collector of authorizations form reader passed into.
* @throws ParseException
* if the format is not compliant.
*/
public static AuthorizationsCollector parse(Reader reader) throws ParseException {<FILL_FUNCTION_BODY>}
private ACLFileParser() {
}
}
|
if (reader == null) {
// just log and return default properties
LOG.warn("parsing NULL reader, so fallback on default configuration!");
return AuthorizationsCollector.emptyImmutableCollector();
}
BufferedReader br = new BufferedReader(reader);
String line;
AuthorizationsCollector collector = new AuthorizationsCollector();
try {
while ((line = br.readLine()) != null) {
int commentMarker = line.indexOf('#');
if (commentMarker != -1) {
if (commentMarker == 0) {
// skip its a comment
continue;
} else {
// it's a malformed comment
throw new ParseException(line, commentMarker);
}
} else {
if (line.isEmpty() || line.matches("^\\s*$")) {
// skip it's a black line
continue;
}
collector.parse(line);
}
}
} catch (IOException ex) {
throw new ParseException("Failed to read", 1);
}
return collector;
| 439
| 277
| 716
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/security/Authorization.java
|
Authorization
|
equals
|
class Authorization {
protected final Topic topic;
protected final Permission permission;
/**
* Access rights
*/
enum Permission {
READ, WRITE, READWRITE
}
Authorization(Topic topic) {
this(topic, Permission.READWRITE);
}
Authorization(Topic topic, Permission permission) {
this.topic = topic;
this.permission = permission;
}
public boolean grant(Permission desiredPermission) {
return permission == desiredPermission || permission == READWRITE;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = topic.hashCode();
result = 31 * result + permission.hashCode();
return result;
}
}
|
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Authorization that = (Authorization) o;
if (permission != that.permission)
return false;
if (!topic.equals(that.topic))
return false;
return true;
| 217
| 92
| 309
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/security/AuthorizationsCollector.java
|
AuthorizationsCollector
|
canDoOperation
|
class AuthorizationsCollector implements IAuthorizator {
private List<Authorization> m_globalAuthorizations = new ArrayList<>();
private List<Authorization> m_patternAuthorizations = new ArrayList<>();
private Map<String, List<Authorization>> m_userAuthorizations = new HashMap<>();
private boolean m_parsingUsersSpecificSection;
private boolean m_parsingPatternSpecificSection;
private String m_currentUser = "";
static final AuthorizationsCollector emptyImmutableCollector() {
AuthorizationsCollector coll = new AuthorizationsCollector();
coll.m_globalAuthorizations = Collections.emptyList();
coll.m_patternAuthorizations = Collections.emptyList();
coll.m_userAuthorizations = Collections.emptyMap();
return coll;
}
void parse(String line) throws ParseException {
Authorization acl = parseAuthLine(line);
if (acl == null) {
// skip it's a user
return;
}
if (m_parsingUsersSpecificSection) {
// TODO in java 8 switch to m_userAuthorizations.putIfAbsent(m_currentUser, new
// ArrayList());
if (!m_userAuthorizations.containsKey(m_currentUser)) {
m_userAuthorizations.put(m_currentUser, new ArrayList<Authorization>());
}
List<Authorization> userAuths = m_userAuthorizations.get(m_currentUser);
userAuths.add(acl);
} else if (m_parsingPatternSpecificSection) {
m_patternAuthorizations.add(acl);
} else {
m_globalAuthorizations.add(acl);
}
}
protected Authorization parseAuthLine(String line) throws ParseException {
String[] tokens = line.split("\\s+");
String keyword = tokens[0].toLowerCase();
switch (keyword) {
case "topic":
return createAuthorization(line, tokens);
case "user":
m_parsingUsersSpecificSection = true;
m_currentUser = tokens[1];
m_parsingPatternSpecificSection = false;
return null;
case "pattern":
m_parsingUsersSpecificSection = false;
m_currentUser = "";
m_parsingPatternSpecificSection = true;
return createAuthorization(line, tokens);
default:
throw new ParseException(String.format("invalid line definition found %s", line), 1);
}
}
private Authorization createAuthorization(String line, String[] tokens) throws ParseException {
if (tokens.length > 2) {
// if the tokenized lines has 3 token the second must be the permission
try {
Authorization.Permission permission = Authorization.Permission.valueOf(tokens[1].toUpperCase());
// bring topic with all original spacing
Topic topic = new Topic(line.substring(line.indexOf(tokens[2])));
return new Authorization(topic, permission);
} catch (IllegalArgumentException iaex) {
throw new ParseException("invalid permission token", 1);
}
}
Topic topic = new Topic(tokens[1]);
return new Authorization(topic);
}
@Override
public boolean canWrite(Topic topic, String user, String client) {
return canDoOperation(topic, Authorization.Permission.WRITE, user, client);
}
@Override
public boolean canRead(Topic topic, String user, String client) {
return canDoOperation(topic, Authorization.Permission.READ, user, client);
}
private boolean canDoOperation(Topic topic, Authorization.Permission permission, String username, String client) {<FILL_FUNCTION_BODY>}
private boolean matchACL(List<Authorization> auths, Topic topic, Authorization.Permission permission) {
for (Authorization auth : auths) {
if (auth.grant(permission)) {
if (topic.match(auth.topic)) {
return true;
}
}
}
return false;
}
private boolean isNotEmpty(String client) {
return client != null && !client.isEmpty();
}
public boolean isEmpty() {
return m_globalAuthorizations.isEmpty();
}
}
|
if (matchACL(m_globalAuthorizations, topic, permission)) {
return true;
}
if (isNotEmpty(client) || isNotEmpty(username)) {
for (Authorization auth : m_patternAuthorizations) {
Topic substitutedTopic = new Topic(auth.topic.toString().replace("%c", client).replace("%u", username));
if (auth.grant(permission)) {
if (topic.match(substitutedTopic)) {
return true;
}
}
}
}
if (isNotEmpty(username)) {
if (m_userAuthorizations.containsKey(username)) {
List<Authorization> auths = m_userAuthorizations.get(username);
if (matchACL(auths, topic, permission)) {
return true;
}
}
}
return false;
| 1,089
| 221
| 1,310
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/security/DBAuthenticator.java
|
DBAuthenticator
|
checkValid
|
class DBAuthenticator implements IAuthenticator {
private static final Logger LOG = LoggerFactory.getLogger(DBAuthenticator.class);
private final MessageDigest messageDigest;
private final PreparedStatement preparedStatement;
public DBAuthenticator(IConfig conf) {
this(
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DRIVER, ""),
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_URL, ""),
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_QUERY, ""),
conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DIGEST, ""));
}
/**
* provide authenticator from SQL database
*
* @param driver
* : jdbc driver class like : "org.postgresql.Driver"
* @param jdbcUrl
* : jdbc url like : "jdbc:postgresql://host:port/dbname"
* @param sqlQuery
* : sql query like : "SELECT PASSWORD FROM USER WHERE LOGIN=?"
* @param digestMethod
* : password encoding algorithm : "MD5", "SHA-1", "SHA-256"
*/
public DBAuthenticator(String driver, String jdbcUrl, String sqlQuery, String digestMethod) {
try {
Class.forName(driver);
final Connection connection = DriverManager.getConnection(jdbcUrl);
this.messageDigest = MessageDigest.getInstance(digestMethod);
this.preparedStatement = connection.prepareStatement(sqlQuery);
} catch (ClassNotFoundException cnfe) {
LOG.error(String.format("Can't find driver %s", driver), cnfe);
throw new RuntimeException(cnfe);
} catch (SQLException sqle) {
LOG.error(String.format("Can't connect to %s", jdbcUrl), sqle);
throw new RuntimeException(sqle);
} catch (NoSuchAlgorithmException nsaex) {
LOG.error(String.format("Can't find %s for password encoding", digestMethod), nsaex);
throw new RuntimeException(nsaex);
}
}
@Override
public synchronized boolean checkValid(String clientId, String username, byte[] password) {<FILL_FUNCTION_BODY>}
@Override
protected void finalize() throws Throwable {
this.preparedStatement.close();
this.preparedStatement.getConnection().close();
super.finalize();
}
}
|
// Check Username / Password in DB using sqlQuery
if (username == null || password == null) {
LOG.info("username or password was null");
return false;
}
ResultSet r = null;
try {
this.preparedStatement.setString(1, username);
r = this.preparedStatement.executeQuery();
if (r.next()) {
final String foundPwq = r.getString(1);
messageDigest.update(password);
byte[] digest = messageDigest.digest();
String encodedPasswd = new String(Hex.encodeHex(digest));
return foundPwq.equals(encodedPasswd);
}
r.close();
} catch (SQLException e) {
e.printStackTrace();
Utility.printExecption(LOG, e);
}
return false;
| 648
| 219
| 867
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/security/ResourceAuthenticator.java
|
ResourceAuthenticator
|
parse
|
class ResourceAuthenticator implements IAuthenticator {
protected static final Logger LOG = LoggerFactory.getLogger(ResourceAuthenticator.class);
private Map<String, String> m_identities = new HashMap<>();
public ResourceAuthenticator(IResourceLoader resourceLoader, String resourceName) {
try {
MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException nsaex) {
LOG.error("Can't find SHA-256 for password encoding", nsaex);
throw new RuntimeException(nsaex);
}
LOG.info(String.format("Loading password %s %s", resourceLoader.getName(), resourceName));
Reader reader = null;
try {
reader = resourceLoader.loadResource(resourceName);
if (reader == null) {
LOG.warn(String.format("Parsing not existing %s %s", resourceLoader.getName(), resourceName));
} else {
parse(reader);
}
} catch (IResourceLoader.ResourceIsDirectoryException e) {
LOG.warn(String.format("Trying to parse directory %s", resourceName));
} catch (ParseException pex) {
LOG.warn(
String.format("Format error in parsing password %s %s", resourceLoader.getName(), resourceName),
pex);
}
}
private void parse(Reader reader) throws ParseException {<FILL_FUNCTION_BODY>}
@Override
public boolean checkValid(String clientId, String username, byte[] password) {
if (username == null || password == null) {
LOG.info("username or password was null");
return false;
}
String foundPwq = m_identities.get(username);
if (foundPwq == null) {
return false;
}
String encodedPasswd = DigestUtils.sha256Hex(password);
return foundPwq.equals(encodedPasswd);
}
}
|
if (reader == null) {
return;
}
BufferedReader br = new BufferedReader(reader);
String line;
try {
while ((line = br.readLine()) != null) {
int commentMarker = line.indexOf('#');
if (commentMarker != -1) {
if (commentMarker == 0) {
// skip its a comment
continue;
} else {
// it's a malformed comment
throw new ParseException(line, commentMarker);
}
} else {
if (line.isEmpty() || line.matches("^\\s*$")) {
// skip it's a black line
continue;
}
// split till the first space
int delimiterIdx = line.indexOf(':');
String username = line.substring(0, delimiterIdx).trim();
String password = line.substring(delimiterIdx + 1).trim();
m_identities.put(username, password);
}
}
} catch (IOException ex) {
throw new ParseException("Failed to read", 1);
}
| 501
| 288
| 789
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/security/TokenAuthenticator.java
|
TokenAuthenticator
|
main
|
class TokenAuthenticator implements IAuthenticator, ITokenGenerator {
public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public boolean checkValid(String clientId, String username, byte[] password) {
String id = Tokenor.getUserId(password);
if (id != null && id.equals(username)) {
return true;
}
return false;
}
@Override
public String generateToken(String username) {
return Tokenor.getToken(username);
}
}
|
TokenAuthenticator authenticator = new TokenAuthenticator();
String strToken = authenticator.generateToken("user1");
if (authenticator.checkValid(null, "user1", strToken.getBytes())) {
System.out.println("pass" + strToken);
} else {
System.out.println("fail" + strToken);
}
| 142
| 97
| 239
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/subscriptions/Token.java
|
Token
|
match
|
class Token {
static final Token EMPTY = new Token("");
static final Token MULTI = new Token("#");
static final Token SINGLE = new Token("+");
final String name;
protected Token(String s) {
name = s;
}
protected String name() {
return name;
}
protected boolean match(Token t) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Token other = (Token) obj;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
return name;
}
}
|
if (t == MULTI || t == SINGLE) {
return false;
}
if (this == MULTI || this == SINGLE) {
return true;
}
return equals(t);
| 311
| 62
| 373
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/impl/subscriptions/Topic.java
|
Topic
|
equals
|
class Topic implements Serializable {
private static final Logger LOG = LoggerFactory.getLogger(Topic.class);
private static final long serialVersionUID = 2438799283749822L;
private final String topic;
private transient List<Token> tokens;
private transient boolean valid;
public Topic(String topic) {
this.topic = topic;
}
public String getTopic() {
return topic;
}
public List<Token> getTokens() {
if (tokens == null) {
try {
tokens = parseTopic(topic);
valid = true;
} catch (ParseException e) {
valid = false;
LOG.error("Error parsing the topic: {}, message: {}", topic, e.getMessage());
}
}
return tokens;
}
private List<Token> parseTopic(String topic) throws ParseException {
List<Token> res = new ArrayList<>();
String[] splitted = topic.split("/");
if (splitted.length == 0) {
res.add(Token.EMPTY);
}
if (topic.endsWith("/")) {
// Add a fictious space
String[] newSplitted = new String[splitted.length + 1];
System.arraycopy(splitted, 0, newSplitted, 0, splitted.length);
newSplitted[splitted.length] = "";
splitted = newSplitted;
}
for (int i = 0; i < splitted.length; i++) {
String s = splitted[i];
if (s.isEmpty()) {
// if (i != 0) {
// throw new ParseException("Bad format of topic, expetec topic name between
// separators", i);
// }
res.add(Token.EMPTY);
} else if (s.equals("#")) {
// check that multi is the last symbol
if (i != splitted.length - 1) {
throw new ParseException(
"Bad format of topic, the multi symbol (#) has to be the last one after a separator",
i);
}
res.add(Token.MULTI);
} else if (s.contains("#")) {
throw new ParseException("Bad format of topic, invalid subtopic name: " + s, i);
} else if (s.equals("+")) {
res.add(Token.SINGLE);
} else if (s.contains("+")) {
throw new ParseException("Bad format of topic, invalid subtopic name: " + s, i);
} else {
res.add(new Token(s));
}
}
return res;
}
public boolean isValid() {
if (tokens == null)
getTokens();
return valid;
}
/**
* Verify if the 2 topics matching respecting the rules of MQTT Appendix A
*
* @param subscriptionTopic
* the topic filter of the subscription
* @return true if the two topics match.
*/
// TODO reimplement with iterators or with queues
public boolean match(Topic subscriptionTopic) {
List<Token> msgTokens = getTokens();
List<Token> subscriptionTokens = subscriptionTopic.getTokens();
int i = 0;
for (; i < subscriptionTokens.size(); i++) {
Token subToken = subscriptionTokens.get(i);
if (subToken != Token.MULTI && subToken != Token.SINGLE) {
if (i >= msgTokens.size()) {
return false;
}
Token msgToken = msgTokens.get(i);
if (!msgToken.equals(subToken)) {
return false;
}
} else {
if (subToken == Token.MULTI) {
return true;
}
if (subToken == Token.SINGLE) {
// skip a step forward
}
}
}
// if last token was a SINGLE then treat it as an empty
// if (subToken == Token.SINGLE && (i - msgTokens.size() == 1)) {
// i--;
// }
return i == msgTokens.size();
}
@Override
public String toString() {
return topic;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return topic.hashCode();
}
/**
* Factory method
* */
public static Topic asTopic(String s) {
return new Topic(s);
}
}
|
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Topic other = (Topic) obj;
return Objects.equals(this.topic, other.topic);
| 1,219
| 72
| 1,291
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/moquette/spi/security/Tokenor.java
|
Tokenor
|
getToken
|
class Tokenor {
private static String KEY = "testim";
private static long expiredTime = Long.MAX_VALUE;
public static void setKey(String key) {
if (!StringUtil.isNullOrEmpty(key)) {
KEY = key;
}
}
public static void setExpiredTime(long expiredTime) {
Tokenor.expiredTime = expiredTime;
}
public static String getUserId(byte[] password) {
try {
String signKey =
DES.decryptDES(new String(password));
if (signKey.startsWith(KEY + "|")) {
signKey = signKey.substring(KEY.length() + 1);
long timestamp = Long.parseLong(signKey.substring(0, signKey.indexOf('|')));
if (expiredTime > 0 && System.currentTimeMillis() - timestamp > expiredTime) {
return null;
}
String id = signKey.substring(signKey.indexOf('|') + 1);
return id;
}
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
return null;
}
public static String getToken(String username) {<FILL_FUNCTION_BODY>}
}
|
String signKey = KEY + "|" + (System.currentTimeMillis()) + "|" + username;
try {
return DES.encryptDES(signKey);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
| 330
| 81
| 411
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttCodecUtil.java
|
MqttCodecUtil
|
validateFixedHeader
|
class MqttCodecUtil {
private static final char[] TOPIC_WILDCARDS = {'#', '+'};
static final AttributeKey<MqttVersion> MQTT_VERSION_KEY = AttributeKey.valueOf("NETTY_CODEC_MQTT_VERSION");
static MqttVersion getMqttVersion(ChannelHandlerContext ctx) {
Attribute<MqttVersion> attr = ctx.channel().attr(MQTT_VERSION_KEY);
MqttVersion version = attr.get();
if (version == null) {
return MqttVersion.MQTT_3_1_1;
}
return version;
}
static void setMqttVersion(ChannelHandlerContext ctx, MqttVersion version) {
Attribute<MqttVersion> attr = ctx.channel().attr(MQTT_VERSION_KEY);
attr.set(version);
}
static boolean isValidPublishTopicName(String topicName) {
// publish topic name must not contain any wildcard
for (char c : TOPIC_WILDCARDS) {
if (topicName.indexOf(c) >= 0) {
return false;
}
}
return true;
}
static boolean isValidMessageId(int messageId) {
return messageId != 0;
}
static boolean isValidClientId(MqttVersion mqttVersion, int maxClientIdLength, String clientId) {
if (mqttVersion == MqttVersion.MQTT_3_1) {
return clientId != null && clientId.length() >= MqttConstant.MIN_CLIENT_ID_LENGTH &&
clientId.length() <= maxClientIdLength;
}
if (mqttVersion.protocolLevel() >= MqttVersion.MQTT_3_1_1.protocolLevel()) {
// In 3.1.3.1 Client Identifier of MQTT 3.1.1 and 5.0 specifications, The Server MAY allow ClientId’s
// that contain more than 23 encoded bytes. And, The Server MAY allow zero-length ClientId.
return clientId != null;
}
throw new IllegalArgumentException(mqttVersion + " is unknown mqtt version");
}
static MqttFixedHeader validateFixedHeader(ChannelHandlerContext ctx, MqttFixedHeader mqttFixedHeader) {<FILL_FUNCTION_BODY>}
static MqttFixedHeader resetUnusedFields(MqttFixedHeader mqttFixedHeader) {
switch (mqttFixedHeader.messageType()) {
case CONNECT:
case CONNACK:
case PUBACK:
case PUBREC:
case PUBCOMP:
case SUBACK:
case UNSUBACK:
case PINGREQ:
case PINGRESP:
case DISCONNECT:
if (mqttFixedHeader.isDup() ||
mqttFixedHeader.qosLevel() != MqttQoS.AT_MOST_ONCE ||
mqttFixedHeader.isRetain()) {
return new MqttFixedHeader(
mqttFixedHeader.messageType(),
false,
MqttQoS.AT_MOST_ONCE,
false,
mqttFixedHeader.remainingLength());
}
return mqttFixedHeader;
case PUBREL:
case SUBSCRIBE:
case UNSUBSCRIBE:
if (mqttFixedHeader.isRetain()) {
return new MqttFixedHeader(
mqttFixedHeader.messageType(),
mqttFixedHeader.isDup(),
mqttFixedHeader.qosLevel(),
false,
mqttFixedHeader.remainingLength());
}
return mqttFixedHeader;
default:
return mqttFixedHeader;
}
}
private MqttCodecUtil() { }
}
|
switch (mqttFixedHeader.messageType()) {
case PUBREL:
case SUBSCRIBE:
case UNSUBSCRIBE:
if (mqttFixedHeader.qosLevel() != MqttQoS.AT_LEAST_ONCE) {
throw new DecoderException(mqttFixedHeader.messageType().name() + " message must have QoS 1");
}
return mqttFixedHeader;
case AUTH:
if (MqttCodecUtil.getMqttVersion(ctx) != MqttVersion.MQTT_5) {
throw new DecoderException("AUTH message requires at least MQTT 5");
}
return mqttFixedHeader;
default:
return mqttFixedHeader;
}
| 1,000
| 204
| 1,204
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttConnAckVariableHeader.java
|
MqttConnAckVariableHeader
|
toString
|
class MqttConnAckVariableHeader {
private final MqttConnectReturnCode connectReturnCode;
private final boolean sessionPresent;
private final MqttProperties properties;
public MqttConnAckVariableHeader(MqttConnectReturnCode connectReturnCode, boolean sessionPresent) {
this(connectReturnCode, sessionPresent, MqttProperties.NO_PROPERTIES);
}
public MqttConnAckVariableHeader(MqttConnectReturnCode connectReturnCode, boolean sessionPresent,
MqttProperties properties) {
this.connectReturnCode = connectReturnCode;
this.sessionPresent = sessionPresent;
this.properties = MqttProperties.withEmptyDefaults(properties);
}
public MqttConnectReturnCode connectReturnCode() {
return connectReturnCode;
}
public boolean isSessionPresent() {
return sessionPresent;
}
public MqttProperties properties() {
return properties;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("connectReturnCode=").append(connectReturnCode)
.append(", sessionPresent=").append(sessionPresent)
.append(']')
.toString();
| 271
| 69
| 340
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttConnectPayload.java
|
MqttConnectPayload
|
willMessage
|
class MqttConnectPayload {
private final String clientIdentifier;
private final MqttProperties willProperties;
private final String willTopic;
private final byte[] willMessage;
private final String userName;
private final byte[] password;
private final byte[] signature;
/**
* @deprecated use {@link MqttConnectPayload#MqttConnectPayload(String,
* MqttProperties, String, byte[], String, byte[])} instead
*/
@Deprecated
public MqttConnectPayload(
String clientIdentifier,
String willTopic,
String willMessage,
String userName,
String password) {
this(
clientIdentifier,
MqttProperties.NO_PROPERTIES,
willTopic,
willMessage.getBytes(CharsetUtil.UTF_8),
userName,
password.getBytes(CharsetUtil.UTF_8), null);
}
public MqttConnectPayload(
String clientIdentifier,
String willTopic,
byte[] willMessage,
String userName,
byte[] password) {
this(clientIdentifier,
MqttProperties.NO_PROPERTIES,
willTopic,
willMessage,
userName,
password, null);
}
public MqttConnectPayload(
String clientIdentifier,
MqttProperties willProperties,
String willTopic,
byte[] willMessage,
String userName,
byte[] password,
byte[] signature) {
this.clientIdentifier = clientIdentifier;
this.willProperties = MqttProperties.withEmptyDefaults(willProperties);
this.willTopic = willTopic;
this.willMessage = willMessage;
this.userName = userName;
this.password = password;
this.signature = signature;
}
public String clientIdentifier() {
return clientIdentifier;
}
public MqttProperties willProperties() {
return willProperties;
}
public String willTopic() {
return willTopic;
}
/**
* @deprecated use {@link MqttConnectPayload#willMessageInBytes()} instead
*/
@Deprecated
public String willMessage() {<FILL_FUNCTION_BODY>}
public byte[] willMessageInBytes() {
return willMessage;
}
public String userName() {
return userName;
}
/**
* @deprecated use {@link MqttConnectPayload#passwordInBytes()} instead
*/
@Deprecated
public String password() {
return password == null ? null : new String(password, CharsetUtil.UTF_8);
}
public byte[] passwordInBytes() {
return password;
}
public byte[] signatureInBytes() {
return signature;
}
@Override
public String toString() {
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("clientIdentifier=").append(clientIdentifier)
.append(", willTopic=").append(willTopic)
.append(", willMessage=").append(Arrays.toString(willMessage))
.append(", userName=").append(userName)
.append(", password=").append(Arrays.toString(password))
.append(']')
.toString();
}
}
|
return willMessage == null ? null : new String(willMessage, CharsetUtil.UTF_8);
| 857
| 27
| 884
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttConnectVariableHeader.java
|
MqttConnectVariableHeader
|
toString
|
class MqttConnectVariableHeader {
private final String name;
private final int version;
private final boolean hasUserName;
private final boolean hasPassword;
private final boolean isWillRetain;
private final int willQos;
private final boolean isWillFlag;
private final boolean isCleanSession;
private final int keepAliveTimeSeconds;
private final MqttProperties properties;
public MqttConnectVariableHeader(
String name,
int version,
boolean hasUserName,
boolean hasPassword,
boolean isWillRetain,
int willQos,
boolean isWillFlag,
boolean isCleanSession,
int keepAliveTimeSeconds) {
this(name,
version,
hasUserName,
hasPassword,
isWillRetain,
willQos,
isWillFlag,
isCleanSession,
keepAliveTimeSeconds,
MqttProperties.NO_PROPERTIES);
}
public MqttConnectVariableHeader(
String name,
int version,
boolean hasUserName,
boolean hasPassword,
boolean isWillRetain,
int willQos,
boolean isWillFlag,
boolean isCleanSession,
int keepAliveTimeSeconds,
MqttProperties properties) {
this.name = name;
this.version = version;
this.hasUserName = hasUserName;
this.hasPassword = hasPassword;
this.isWillRetain = isWillRetain;
this.willQos = willQos;
this.isWillFlag = isWillFlag;
this.isCleanSession = isCleanSession;
this.keepAliveTimeSeconds = keepAliveTimeSeconds;
this.properties = MqttProperties.withEmptyDefaults(properties);
}
public String name() {
return name;
}
public int version() {
return version;
}
public boolean hasUserName() {
return hasUserName;
}
public boolean hasPassword() {
return hasPassword;
}
public boolean isWillRetain() {
return isWillRetain;
}
public int willQos() {
return willQos;
}
public boolean isWillFlag() {
return isWillFlag;
}
public boolean isCleanSession() {
return isCleanSession;
}
public int keepAliveTimeSeconds() {
return keepAliveTimeSeconds;
}
public MqttProperties properties() {
return properties;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("name=").append(name)
.append(", version=").append(version)
.append(", hasUserName=").append(hasUserName)
.append(", hasPassword=").append(hasPassword)
.append(", isWillRetain=").append(isWillRetain)
.append(", isWillFlag=").append(isWillFlag)
.append(", isCleanSession=").append(isCleanSession)
.append(", keepAliveTimeSeconds=").append(keepAliveTimeSeconds)
.append(']')
.toString();
| 678
| 171
| 849
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttFixedHeader.java
|
MqttFixedHeader
|
toString
|
class MqttFixedHeader {
private final MqttMessageType messageType;
private final boolean isDup;
private final MqttQoS qosLevel;
private final boolean isRetain;
private final int remainingLength;
public MqttFixedHeader(
MqttMessageType messageType,
boolean isDup,
MqttQoS qosLevel,
boolean isRetain,
int remainingLength) {
this.messageType = ObjectUtil.checkNotNull(messageType, "messageType");
this.isDup = isDup;
this.qosLevel = ObjectUtil.checkNotNull(qosLevel, "qosLevel");
this.isRetain = isRetain;
this.remainingLength = remainingLength;
}
public MqttMessageType messageType() {
return messageType;
}
public boolean isDup() {
return isDup;
}
public MqttQoS qosLevel() {
return qosLevel;
}
public boolean isRetain() {
return isRetain;
}
public int remainingLength() {
return remainingLength;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("messageType=").append(messageType)
.append(", isDup=").append(isDup)
.append(", qosLevel=").append(qosLevel)
.append(", isRetain=").append(isRetain)
.append(", remainingLength=").append(remainingLength)
.append(']')
.toString();
| 327
| 119
| 446
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttMessage.java
|
MqttMessage
|
toString
|
class MqttMessage {
private final MqttFixedHeader mqttFixedHeader;
private final Object variableHeader;
private final Object payload;
private final DecoderResult decoderResult;
// Constants for fixed-header only message types with all flags set to 0 (see
// https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Table_2.2_-)
public static final MqttMessage PINGREQ = new MqttMessage(new MqttFixedHeader(MqttMessageType.PINGREQ, false,
MqttQoS.AT_MOST_ONCE, false, 0));
public static final MqttMessage PINGRESP = new MqttMessage(new MqttFixedHeader(MqttMessageType.PINGRESP, false,
MqttQoS.AT_MOST_ONCE, false, 0));
public static final MqttMessage DISCONNECT = new MqttMessage(new MqttFixedHeader(MqttMessageType.DISCONNECT, false,
MqttQoS.AT_MOST_ONCE, false, 0));
public MqttMessage(MqttFixedHeader mqttFixedHeader) {
this(mqttFixedHeader, null, null);
}
public MqttMessage(MqttFixedHeader mqttFixedHeader, Object variableHeader) {
this(mqttFixedHeader, variableHeader, null);
}
public MqttMessage(MqttFixedHeader mqttFixedHeader, Object variableHeader, Object payload) {
this(mqttFixedHeader, variableHeader, payload, DecoderResult.SUCCESS);
}
public MqttMessage(
MqttFixedHeader mqttFixedHeader,
Object variableHeader,
Object payload,
DecoderResult decoderResult) {
this.mqttFixedHeader = mqttFixedHeader;
this.variableHeader = variableHeader;
this.payload = payload;
this.decoderResult = decoderResult;
}
public MqttFixedHeader fixedHeader() {
return mqttFixedHeader;
}
public Object variableHeader() {
return variableHeader;
}
public Object payload() {
return payload;
}
public DecoderResult decoderResult() {
return decoderResult;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("fixedHeader=").append(fixedHeader() != null ? fixedHeader().toString() : "")
.append(", variableHeader=").append(variableHeader() != null ? variableHeader.toString() : "")
.append(", payload=").append(payload() != null ? payload.toString() : "")
.append(']')
.toString();
| 649
| 116
| 765
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttMessageBuilders.java
|
UnsubscribeBuilder
|
build
|
class UnsubscribeBuilder {
private List<String> topicFilters;
private int messageId;
private MqttProperties properties;
UnsubscribeBuilder() {
}
public UnsubscribeBuilder addTopicFilter(String topic) {
if (topicFilters == null) {
topicFilters = new ArrayList<String>(5);
}
topicFilters.add(topic);
return this;
}
public UnsubscribeBuilder messageId(int messageId) {
this.messageId = messageId;
return this;
}
public UnsubscribeBuilder properties(MqttProperties properties) {
this.properties = properties;
return this;
}
public MqttUnsubscribeMessage build() {<FILL_FUNCTION_BODY>}
}
|
MqttFixedHeader mqttFixedHeader =
new MqttFixedHeader(MqttMessageType.UNSUBSCRIBE, false, MqttQoS.AT_LEAST_ONCE, false, 0);
MqttMessageIdAndPropertiesVariableHeader mqttVariableHeader =
new MqttMessageIdAndPropertiesVariableHeader(messageId, properties);
MqttUnsubscribePayload mqttSubscribePayload = new MqttUnsubscribePayload(topicFilters);
return new MqttUnsubscribeMessage(mqttFixedHeader, mqttVariableHeader, mqttSubscribePayload);
| 200
| 155
| 355
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttMessageFactory.java
|
MqttMessageFactory
|
newMessage
|
class MqttMessageFactory {
public static MqttMessage newMessage(MqttFixedHeader mqttFixedHeader, Object variableHeader, Object payload) {<FILL_FUNCTION_BODY>}
public static MqttMessage newInvalidMessage(Throwable cause) {
return new MqttMessage(null, null, null, DecoderResult.failure(cause));
}
public static MqttMessage newInvalidMessage(MqttFixedHeader mqttFixedHeader, Object variableHeader,
Throwable cause) {
return new MqttMessage(mqttFixedHeader, variableHeader, null, DecoderResult.failure(cause));
}
private MqttMessageFactory() { }
}
|
switch (mqttFixedHeader.messageType()) {
case CONNECT :
return new MqttConnectMessage(
mqttFixedHeader,
(MqttConnectVariableHeader) variableHeader,
(MqttConnectPayload) payload);
case CONNACK:
return new MqttConnAckMessage(mqttFixedHeader, (MqttConnAckVariableHeader) variableHeader);
case SUBSCRIBE:
return new MqttSubscribeMessage(
mqttFixedHeader,
(MqttMessageIdVariableHeader) variableHeader,
(MqttSubscribePayload) payload);
case SUBACK:
return new MqttSubAckMessage(
mqttFixedHeader,
(MqttMessageIdVariableHeader) variableHeader,
(MqttSubAckPayload) payload);
case UNSUBACK:
return new MqttUnsubAckMessage(
mqttFixedHeader,
(MqttMessageIdVariableHeader) variableHeader,
(MqttUnsubAckPayload) payload);
case UNSUBSCRIBE:
return new MqttUnsubscribeMessage(
mqttFixedHeader,
(MqttMessageIdVariableHeader) variableHeader,
(MqttUnsubscribePayload) payload);
case PUBLISH:
return new MqttPublishMessage(
mqttFixedHeader,
(MqttPublishVariableHeader) variableHeader,
(ByteBuf) payload);
case PUBACK:
//Having MqttPubReplyMessageVariableHeader or MqttMessageIdVariableHeader
return new MqttPubAckMessage(mqttFixedHeader, (MqttMessageIdVariableHeader) variableHeader);
case PUBREC:
case PUBREL:
case PUBCOMP:
//Having MqttPubReplyMessageVariableHeader or MqttMessageIdVariableHeader
return new MqttMessage(mqttFixedHeader, variableHeader);
case PINGREQ:
case PINGRESP:
return new MqttMessage(mqttFixedHeader);
case DISCONNECT:
case AUTH:
//Having MqttReasonCodeAndPropertiesVariableHeader
return new MqttMessage(mqttFixedHeader,
variableHeader);
default:
throw new IllegalArgumentException("unknown message type: " + mqttFixedHeader.messageType());
}
| 178
| 612
| 790
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttMessageIdAndPropertiesVariableHeader.java
|
MqttMessageIdAndPropertiesVariableHeader
|
toString
|
class MqttMessageIdAndPropertiesVariableHeader extends MqttMessageIdVariableHeader {
private final MqttProperties properties;
public MqttMessageIdAndPropertiesVariableHeader(int messageId, MqttProperties properties) {
super(messageId);
if (messageId < 1 || messageId > 0xffff) {
throw new IllegalArgumentException("messageId: " + messageId + " (expected: 1 ~ 65535)");
}
this.properties = MqttProperties.withEmptyDefaults(properties);
}
public MqttProperties properties() {
return properties;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
MqttMessageIdAndPropertiesVariableHeader withDefaultEmptyProperties() {
return this;
}
}
|
return StringUtil.simpleClassName(this) + "[" +
"messageId=" + messageId() +
", properties=" + properties +
']';
| 210
| 45
| 255
|
<methods>public static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader from(int) ,public int messageId() ,public java.lang.String toString() ,public io.netty.handler.codec.mqtt.MqttMessageIdAndPropertiesVariableHeader withEmptyProperties() <variables>private final non-sealed int messageId
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttMessageIdVariableHeader.java
|
MqttMessageIdVariableHeader
|
from
|
class MqttMessageIdVariableHeader {
private final int messageId;
public static MqttMessageIdVariableHeader from(int messageId) {<FILL_FUNCTION_BODY>}
protected MqttMessageIdVariableHeader(int messageId) {
this.messageId = messageId;
}
public int messageId() {
return messageId;
}
@Override
public String toString() {
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("messageId=").append(messageId)
.append(']')
.toString();
}
public MqttMessageIdAndPropertiesVariableHeader withEmptyProperties() {
return new MqttMessageIdAndPropertiesVariableHeader(messageId, MqttProperties.NO_PROPERTIES);
}
MqttMessageIdAndPropertiesVariableHeader withDefaultEmptyProperties() {
return withEmptyProperties();
}
}
|
if (messageId < 1 || messageId > 0xffff) {
throw new IllegalArgumentException("messageId: " + messageId + " (expected: 1 ~ 65535)");
}
return new MqttMessageIdVariableHeader(messageId);
| 242
| 68
| 310
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttPubReplyMessageVariableHeader.java
|
MqttPubReplyMessageVariableHeader
|
toString
|
class MqttPubReplyMessageVariableHeader extends MqttMessageIdVariableHeader {
private final byte reasonCode;
private final MqttProperties properties;
public static final byte REASON_CODE_OK = 0;
public MqttPubReplyMessageVariableHeader(int messageId, byte reasonCode, MqttProperties properties) {
super(messageId);
if (messageId < 1 || messageId > 0xffff) {
throw new IllegalArgumentException("messageId: " + messageId + " (expected: 1 ~ 65535)");
}
this.reasonCode = reasonCode;
this.properties = MqttProperties.withEmptyDefaults(properties);
}
public byte reasonCode() {
return reasonCode;
}
public MqttProperties properties() {
return properties;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return StringUtil.simpleClassName(this) + "[" +
"messageId=" + messageId() +
", reasonCode=" + reasonCode +
", properties=" + properties +
']';
| 237
| 56
| 293
|
<methods>public static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader from(int) ,public int messageId() ,public java.lang.String toString() ,public io.netty.handler.codec.mqtt.MqttMessageIdAndPropertiesVariableHeader withEmptyProperties() <variables>private final non-sealed int messageId
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttPublishVariableHeader.java
|
MqttPublishVariableHeader
|
toString
|
class MqttPublishVariableHeader {
private final String topicName;
private int packetId;
private final MqttProperties properties;
public MqttPublishVariableHeader(String topicName, int packetId) {
this(topicName, packetId, MqttProperties.NO_PROPERTIES);
}
public MqttPublishVariableHeader(String topicName, int packetId, MqttProperties properties) {
this.topicName = topicName;
this.packetId = packetId;
this.properties = MqttProperties.withEmptyDefaults(properties);
}
public String topicName() {
return topicName;
}
/**
* @deprecated Use {@link #packetId()} instead.
*/
@Deprecated
public int messageId() {
return packetId;
}
public int packetId() {
return packetId;
}
public MqttProperties properties() {
return properties;
}
public void setPacketId(int packetId) {
this.packetId = packetId;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("topicName=").append(topicName)
.append(", packetId=").append(packetId)
.append(']')
.toString();
| 306
| 68
| 374
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttReasonCodeAndPropertiesVariableHeader.java
|
MqttReasonCodeAndPropertiesVariableHeader
|
toString
|
class MqttReasonCodeAndPropertiesVariableHeader {
private final byte reasonCode;
private final MqttProperties properties;
public static final byte REASON_CODE_OK = 0;
public MqttReasonCodeAndPropertiesVariableHeader(byte reasonCode,
MqttProperties properties) {
this.reasonCode = reasonCode;
this.properties = MqttProperties.withEmptyDefaults(properties);
}
public byte reasonCode() {
return reasonCode;
}
public MqttProperties properties() {
return properties;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("reasonCode=").append(reasonCode)
.append(", properties=").append(properties)
.append(']')
.toString();
| 171
| 65
| 236
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttSubAckPayload.java
|
MqttSubAckPayload
|
grantedQoSLevels
|
class MqttSubAckPayload {
private final List<Integer> reasonCodes;
public MqttSubAckPayload(int... reasonCodes) {
ObjectUtil.checkNotNull(reasonCodes, "reasonCodes");
List<Integer> list = new ArrayList<Integer>(reasonCodes.length);
for (int v: reasonCodes) {
list.add(v);
}
this.reasonCodes = Collections.unmodifiableList(list);
}
public MqttSubAckPayload(Iterable<Integer> reasonCodes) {
ObjectUtil.checkNotNull(reasonCodes, "reasonCodes");
List<Integer> list = new ArrayList<Integer>();
for (Integer v: reasonCodes) {
if (v == null) {
break;
}
list.add(v);
}
this.reasonCodes = Collections.unmodifiableList(list);
}
public List<Integer> grantedQoSLevels() {<FILL_FUNCTION_BODY>}
public List<Integer> reasonCodes() {
return reasonCodes;
}
@Override
public String toString() {
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("reasonCodes=").append(reasonCodes)
.append(']')
.toString();
}
}
|
List<Integer> qosLevels = new ArrayList<Integer>(reasonCodes.size());
for (int code: reasonCodes) {
if (code > MqttQoS.EXACTLY_ONCE.value()) {
qosLevels.add(MqttQoS.FAILURE.value());
} else {
qosLevels.add(code);
}
}
return qosLevels;
| 360
| 113
| 473
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttSubscribePayload.java
|
MqttSubscribePayload
|
toString
|
class MqttSubscribePayload {
private final List<MqttTopicSubscription> topicSubscriptions;
public MqttSubscribePayload(List<MqttTopicSubscription> topicSubscriptions) {
this.topicSubscriptions = Collections.unmodifiableList(topicSubscriptions);
}
public List<MqttTopicSubscription> topicSubscriptions() {
return topicSubscriptions;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder(StringUtil.simpleClassName(this)).append('[');
for (int i = 0; i < topicSubscriptions.size(); i++) {
builder.append(topicSubscriptions.get(i)).append(", ");
}
if (!topicSubscriptions.isEmpty()) {
builder.setLength(builder.length() - 2);
}
return builder.append(']').toString();
| 135
| 108
| 243
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttSubscriptionOption.java
|
MqttSubscriptionOption
|
valueOf
|
class MqttSubscriptionOption {
public enum RetainedHandlingPolicy {
SEND_AT_SUBSCRIBE(0),
SEND_AT_SUBSCRIBE_IF_NOT_YET_EXISTS(1),
DONT_SEND_AT_SUBSCRIBE(2);
private final int value;
RetainedHandlingPolicy(int value) {
this.value = value;
}
public int value() {
return value;
}
public static RetainedHandlingPolicy valueOf(int value) {<FILL_FUNCTION_BODY>}
}
private final MqttQoS qos;
private final boolean noLocal;
private final boolean retainAsPublished;
private final RetainedHandlingPolicy retainHandling;
public static MqttSubscriptionOption onlyFromQos(MqttQoS qos) {
return new MqttSubscriptionOption(qos, false, false, RetainedHandlingPolicy.SEND_AT_SUBSCRIBE);
}
public MqttSubscriptionOption(MqttQoS qos,
boolean noLocal,
boolean retainAsPublished,
RetainedHandlingPolicy retainHandling) {
this.qos = qos;
this.noLocal = noLocal;
this.retainAsPublished = retainAsPublished;
this.retainHandling = retainHandling;
}
public MqttQoS qos() {
return qos;
}
public boolean isNoLocal() {
return noLocal;
}
public boolean isRetainAsPublished() {
return retainAsPublished;
}
public RetainedHandlingPolicy retainHandling() {
return retainHandling;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MqttSubscriptionOption that = (MqttSubscriptionOption) o;
if (noLocal != that.noLocal) {
return false;
}
if (retainAsPublished != that.retainAsPublished) {
return false;
}
if (qos != that.qos) {
return false;
}
return retainHandling == that.retainHandling;
}
@Override
public int hashCode() {
int result = qos.hashCode();
result = 31 * result + (noLocal ? 1 : 0);
result = 31 * result + (retainAsPublished ? 1 : 0);
result = 31 * result + retainHandling.hashCode();
return result;
}
@Override
public String toString() {
return "SubscriptionOption[" +
"qos=" + qos +
", noLocal=" + noLocal +
", retainAsPublished=" + retainAsPublished +
", retainHandling=" + retainHandling +
']';
}
}
|
switch (value) {
case 0:
return SEND_AT_SUBSCRIBE;
case 1:
return SEND_AT_SUBSCRIBE_IF_NOT_YET_EXISTS;
case 2:
return DONT_SEND_AT_SUBSCRIBE;
default:
throw new IllegalArgumentException("invalid RetainedHandlingPolicy: " + value);
}
| 780
| 105
| 885
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttTopicSubscription.java
|
MqttTopicSubscription
|
toString
|
class MqttTopicSubscription {
private final String topicFilter;
private final MqttSubscriptionOption option;
public MqttTopicSubscription(String topicFilter, MqttQoS qualityOfService) {
this.topicFilter = topicFilter;
this.option = MqttSubscriptionOption.onlyFromQos(qualityOfService);
}
public MqttTopicSubscription(String topicFilter, MqttSubscriptionOption option) {
this.topicFilter = topicFilter;
this.option = option;
}
public String topicName() {
return topicFilter;
}
public MqttQoS qualityOfService() {
return option.qos();
}
public MqttSubscriptionOption option() {
return option;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("topicFilter=").append(topicFilter)
.append(", option=").append(this.option)
.append(']')
.toString();
| 231
| 67
| 298
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttUnsubAckMessage.java
|
MqttUnsubAckMessage
|
fallbackVariableHeader
|
class MqttUnsubAckMessage extends MqttMessage {
public MqttUnsubAckMessage(MqttFixedHeader mqttFixedHeader,
MqttMessageIdAndPropertiesVariableHeader variableHeader,
MqttUnsubAckPayload payload) {
super(mqttFixedHeader, variableHeader, MqttUnsubAckPayload.withEmptyDefaults(payload));
}
public MqttUnsubAckMessage(MqttFixedHeader mqttFixedHeader,
MqttMessageIdVariableHeader variableHeader,
MqttUnsubAckPayload payload) {
this(mqttFixedHeader, fallbackVariableHeader(variableHeader), payload);
}
public MqttUnsubAckMessage(MqttFixedHeader mqttFixedHeader,
MqttMessageIdVariableHeader variableHeader) {
this(mqttFixedHeader, variableHeader, null);
}
private static MqttMessageIdAndPropertiesVariableHeader fallbackVariableHeader(
MqttMessageIdVariableHeader variableHeader) {<FILL_FUNCTION_BODY>}
@Override
public MqttMessageIdVariableHeader variableHeader() {
return (MqttMessageIdVariableHeader) super.variableHeader();
}
public MqttMessageIdAndPropertiesVariableHeader idAndPropertiesVariableHeader() {
return (MqttMessageIdAndPropertiesVariableHeader) super.variableHeader();
}
@Override
public MqttUnsubAckPayload payload() {
return (MqttUnsubAckPayload) super.payload();
}
}
|
if (variableHeader instanceof MqttMessageIdAndPropertiesVariableHeader) {
return (MqttMessageIdAndPropertiesVariableHeader) variableHeader;
}
return new MqttMessageIdAndPropertiesVariableHeader(variableHeader.messageId(), MqttProperties.NO_PROPERTIES);
| 398
| 72
| 470
|
<methods>public void <init>(io.netty.handler.codec.mqtt.MqttFixedHeader) ,public void <init>(io.netty.handler.codec.mqtt.MqttFixedHeader, java.lang.Object) ,public void <init>(io.netty.handler.codec.mqtt.MqttFixedHeader, java.lang.Object, java.lang.Object) ,public void <init>(io.netty.handler.codec.mqtt.MqttFixedHeader, java.lang.Object, java.lang.Object, DecoderResult) ,public DecoderResult decoderResult() ,public io.netty.handler.codec.mqtt.MqttFixedHeader fixedHeader() ,public java.lang.Object payload() ,public java.lang.String toString() ,public java.lang.Object variableHeader() <variables>public static final io.netty.handler.codec.mqtt.MqttMessage DISCONNECT,public static final io.netty.handler.codec.mqtt.MqttMessage PINGREQ,public static final io.netty.handler.codec.mqtt.MqttMessage PINGRESP,private final non-sealed DecoderResult decoderResult,private final non-sealed io.netty.handler.codec.mqtt.MqttFixedHeader mqttFixedHeader,private final non-sealed java.lang.Object payload,private final non-sealed java.lang.Object variableHeader
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttUnsubAckPayload.java
|
MqttUnsubAckPayload
|
withEmptyDefaults
|
class MqttUnsubAckPayload {
private final List<Short> unsubscribeReasonCodes;
private static final MqttUnsubAckPayload EMPTY = new MqttUnsubAckPayload();
public static MqttUnsubAckPayload withEmptyDefaults(MqttUnsubAckPayload payload) {<FILL_FUNCTION_BODY>}
public MqttUnsubAckPayload(short... unsubscribeReasonCodes) {
ObjectUtil.checkNotNull(unsubscribeReasonCodes, "unsubscribeReasonCodes");
List<Short> list = new ArrayList<Short>(unsubscribeReasonCodes.length);
for (Short v: unsubscribeReasonCodes) {
list.add(v);
}
this.unsubscribeReasonCodes = Collections.unmodifiableList(list);
}
public MqttUnsubAckPayload(Iterable<Short> unsubscribeReasonCodes) {
ObjectUtil.checkNotNull(unsubscribeReasonCodes, "unsubscribeReasonCodes");
List<Short> list = new ArrayList<Short>();
for (Short v: unsubscribeReasonCodes) {
ObjectUtil.checkNotNull(v, "unsubscribeReasonCode");
list.add(v);
}
this.unsubscribeReasonCodes = Collections.unmodifiableList(list);
}
public List<Short> unsubscribeReasonCodes() {
return unsubscribeReasonCodes;
}
@Override
public String toString() {
return new StringBuilder(StringUtil.simpleClassName(this))
.append('[')
.append("unsubscribeReasonCodes=").append(unsubscribeReasonCodes)
.append(']')
.toString();
}
}
|
if (payload == null) {
return EMPTY;
} else {
return payload;
}
| 441
| 33
| 474
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/io/netty/handler/codec/mqtt/MqttUnsubscribePayload.java
|
MqttUnsubscribePayload
|
toString
|
class MqttUnsubscribePayload {
private final List<String> topics;
public MqttUnsubscribePayload(List<String> topics) {
this.topics = Collections.unmodifiableList(topics);
}
public List<String> topics() {
return topics;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder(StringUtil.simpleClassName(this)).append('[');
for (int i = 0; i < topics.size(); i++) {
builder.append("topicName = ").append(topics.get(i)).append(", ");
}
if (!topics.isEmpty()) {
builder.setLength(builder.length() - 2);
}
return builder.append("]").toString();
| 107
| 111
| 218
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/FrequencyLimistCounter.java
|
FrequencyLimistCounter
|
main
|
class FrequencyLimistCounter {
private final Map<String, Integer> CACHE_MAP = new HashMap<>();
private final Map<String, Long> CACHE_TIME_MAP = new HashMap<>();
private long CACHE_HOLD_TIME = 5 * 1000;
private int FREQUENCY_LIMIT = 100;
private final SpinLock mLock = new SpinLock();
private long lastFullScanTime = System.currentTimeMillis();
//2个小时全部扫描一次
private static final long fullScanDuration = 2*60*60*1000;
public FrequencyLimistCounter(int limitTimeSec, int limitCount) {
this.CACHE_HOLD_TIME = limitTimeSec * 1000;
this.FREQUENCY_LIMIT = limitCount;
}
public FrequencyLimistCounter() {
}
/**
* 增加对象计数并返回是否超频
* @param cacheName
* @return ture 超频; false 不超频
*/
public boolean increaseAndCheck(String cacheName) {
mLock.lock();
try {
tryFullScan();
Long cacheHoldTime = CACHE_TIME_MAP.get(cacheName);
if (cacheHoldTime != null && cacheHoldTime < System.currentTimeMillis()) {
CACHE_MAP.remove(cacheName);
CACHE_TIME_MAP.remove(cacheName);
}
Integer count = CACHE_MAP.get(cacheName);
if (count != null) {
CACHE_MAP.put(cacheName, ++count);
} else {
count = 0;
CACHE_MAP.put(cacheName, ++count);
CACHE_TIME_MAP.put(cacheName, (System.currentTimeMillis() + CACHE_HOLD_TIME));//缓存失效时间
}
if (count >= FREQUENCY_LIMIT) {
return true;
}
return false;
} finally {
mLock.unLock();
}
}
//去掉超时的数据,如果在一个低频使用的系统中,会残留大量超时无用的信息
private void tryFullScan() {
if (System.currentTimeMillis() - lastFullScanTime > fullScanDuration) {
lastFullScanTime = System.currentTimeMillis();
for (Map.Entry<String, Long> entry : CACHE_TIME_MAP.entrySet()
) {
if (entry.getValue() < lastFullScanTime) {
CACHE_MAP.remove(entry.getKey());
CACHE_TIME_MAP.remove(entry.getKey());
}
}
}
}
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
FrequencyLimistCounter counter = new FrequencyLimistCounter(5, 100);
String name = "test";
for (int i = 0; i < 50; i++) {
if(counter.increaseAndCheck(name)) {
System.out.println("test failure 1");
System.exit(-1);
}
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 49; i++) {
if(counter.increaseAndCheck(name)) {
System.out.println("test failure 2");
System.exit(-1);
}
}
if(!counter.increaseAndCheck(name)) {
System.out.println("test failure 3");
System.exit(-1);
}
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 99; i++) {
if(counter.increaseAndCheck(name)) {
System.out.println("test failure 4");
System.exit(-1);
}
}
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 99; i++) {
if(counter.increaseAndCheck(name)) {
System.out.println("test failure 5");
System.exit(-1);
}
}
| 740
| 434
| 1,174
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/GitRepositoryState.java
|
GitRepositoryState
|
getGitRepositoryState
|
class GitRepositoryState {
public final String tags;
public final String branch;
public final String dirty;
public final String remoteOriginUrl;
public final String commitId;
public final String commitIdAbbrev;
public final String describe;
public final String describeShort;
public final String commitUserName;
public final String commitUserEmail;
public final String commitMessageFull;
public final String commitMessageShort;
public final String commitTime;
public final String closestTagName;
public final String closestTagCommitCount;
public final String buildUserName;
public final String buildUserEmail;
public final String buildTime;
public final String buildHost;
public final String buildVersion;
public final long runTime;
private GitRepositoryState(Properties properties) {
this.tags = String.valueOf(properties.get("git.tags"));
this.branch = String.valueOf(properties.get("git.branch"));
this.dirty = String.valueOf(properties.get("git.dirty"));
this.remoteOriginUrl = String.valueOf(properties.get("git.remote.origin.url"));
this.commitId = String.valueOf(properties.get("git.commit.id.full")); // OR properties.get("git.commit.id") depending on your configuration
this.commitIdAbbrev = String.valueOf(properties.get("git.commit.id.abbrev"));
this.describe = String.valueOf(properties.get("git.commit.id.describe"));
this.describeShort = String.valueOf(properties.get("git.commit.id.describe-short"));
this.commitUserName = String.valueOf(properties.get("git.commit.user.name"));
this.commitUserEmail = String.valueOf(properties.get("git.commit.user.email"));
this.commitMessageFull = String.valueOf(properties.get("git.commit.message.full"));
this.commitMessageShort = String.valueOf(properties.get("git.commit.message.short"));
this.commitTime = String.valueOf(properties.get("git.commit.time"));
this.closestTagName = String.valueOf(properties.get("git.closest.tag.name"));
this.closestTagCommitCount = String.valueOf(properties.get("git.closest.tag.commit.count"));
this.buildUserName = String.valueOf(properties.get("git.build.user.name"));
this.buildUserEmail = String.valueOf(properties.get("git.build.user.email"));
this.buildTime = String.valueOf(properties.get("git.build.time"));
this.buildHost = String.valueOf(properties.get("git.build.host"));
this.buildVersion = String.valueOf(properties.get("git.build.version"));
this.runTime = Server.getServer().getRunTime();
}
public static GitRepositoryState getGitRepositoryState() throws IOException {<FILL_FUNCTION_BODY>}
}
|
Properties properties = new Properties();
try {
String configPath = System.getProperty("wildfirechat.path", null);
File f = new File(configPath, "config/git.properties");
InputStream inputStream = new FileInputStream(f);
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
properties.load(bf);
} catch (IOException e) {
}
GitRepositoryState gitRepositoryState = new GitRepositoryState(properties);
return gitRepositoryState;
| 753
| 131
| 884
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/HttpUtils.java
|
HttpUtils
|
onResponse
|
class HttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
static private OkHttpClient client = new OkHttpClient();
public interface HttpCallback {
void onSuccess(String content);
void onFailure(int statusCode, String errorMessage);
}
public enum HttpPostType {
POST_TYPE_Push,
POST_TYPE_Grout_Event_Callback,
POST_TYPE_Grout_Member_Event_Callback,
POST_TYPE_User_Relation_Event_Callback,
POST_TYPE_User_Info_Event_Callback,
POST_TYPE_Channel_Info_Event_Callback,
POST_TYPE_Channel_Subscriber_Event_Callback,
POST_TYPE_Chatroom_Info_Event_Callback,
POST_TYPE_Chatroom_Member_Event_Callback,
POST_TYPE_Robot_Message_Callback,
POST_TYPE_Channel_Message_Callback,
POST_TYPE_Forward_Message_Callback,
POST_TYPE_User_Online_Event_Callback,
POST_TYPE_Server_Exception_Callback,
POST_TYPE_Forward_Recall_Callback;
}
public static void httpJsonPost(String url, String jsonStr, HttpPostType postType) {
httpJsonPost(url, jsonStr, null, postType);
}
public static void httpJsonPost(String url, String jsonStr, HttpCallback httpCallback, HttpPostType postType) {
//消息推送内容为 {"sender":"uCGUxUaa","senderName":"杨","convType":0,"target":"usq7v7UU","targetName":"鞋子","userId":"usq7v7UU","line":0,"cntType":400,"serverTime":1610590766485,"pushMessageType":1,"pushType":2,"pushContent":"","pushData":"","unReceivedMsg":1,"mentionedType":0,"packageName":"cn.wildfirechat.chat","deviceToken":"AFoieP9P6u6CccIkRK23gRwUJWKqSkdiqnb-6gC1kL7Wv-9XNoEYBPU7VsINU_q8_WTKfafe35qWu7ya7Z-NmgOTX9XVW3A3zd6ilh--quj6ccINXRvVnh8QmI9QQ","isHiddenDetail":false,"language":"zh"}
//推送信息只打印前100个字符,防止敏感信息打印到日志中去。
LOG.info("POST to {} with data {}...", url, jsonStr.substring(0, Math.min(jsonStr.length(), 100)));
if (StringUtil.isNullOrEmpty(url)) {
LOG.error("http post failure with empty url");
return;
}
RequestBody body = RequestBody.create(JSON, jsonStr);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
String logText;
if(postType == HttpPostType.POST_TYPE_Push) {
logText = "Http请求到推送服务失败,请检查推送服务是否正在运行或者配置文件中推送服务地址是否正确。";
} else if(postType == HttpPostType.POST_TYPE_Robot_Message_Callback) {
logText = "Http请求转发消息到机器人服务失败,请检查机器人服务是否部署且在机器人信息中的回调地址是否正确。\n如果不需要机器人及机器人服务,请关掉应用服务中自动添加机器人好友和发送机器人欢迎语的代码,用户不给机器人发送消息就不会有转发请求了。";
} else if(postType == HttpPostType.POST_TYPE_Channel_Message_Callback ||
postType == HttpPostType.POST_TYPE_Channel_Subscriber_Event_Callback) {
logText = "Http请求到频道服务失败,请检查频道服务是否部署且在频道信息中的回调地址是否正确。";
} else {
logText = "Http请求回调地址失败,请检查IM服务配置文件中对应的回调地址是否正确";
}
System.out.println(logText);
e.printStackTrace();
LOG.error(logText);
LOG.error("POST to {} failed", url);
if(httpCallback != null) {
httpCallback.onFailure(-1, e.getMessage());
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {<FILL_FUNCTION_BODY>}
});
}
}
|
LOG.info("POST to {} success with response: {}", url, response.body());
try {
if(httpCallback != null) {
int code = response.code();
if(code == 200) {
if(response.body() != null && response.body().contentLength() > 0) {
httpCallback.onSuccess(response.body().string());
} else {
httpCallback.onSuccess(null);
}
} else {
httpCallback.onFailure(code, response.message());
}
}
if (response.body() != null) {
response.body().close();
}
} catch (Exception e) {
e.printStackTrace();
}
| 1,209
| 183
| 1,392
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/IDUtils.java
|
IDUtils
|
toUid
|
class IDUtils {
private static final int RADIX = 36;
private static final int IDLEN = 9;
private static final int[] FACTOR = {29,19,1,11,7,17,13,23,5};
private static char getChar(long number) {
if (number < 26) {
return (char)('a' + number);
} else {
return (char)('0' + number - 26);
}
}
public static String toUid(long id) {<FILL_FUNCTION_BODY>}
public static void main(String[] args) {
HashSet<String> idset = new HashSet<>();
for (long i = 0; i < 1000000000000L; i++) {
String uid = toUid(i);
if(!idset.add(uid)) {
System.out.println("error, dupliate id");
System.exit(-1);
}
}
}
}
|
StringBuilder sb = new StringBuilder();
for (int i = 0; i < IDLEN; i++) {
long bit = ((id % RADIX) * FACTOR[i] + FACTOR[i] + 5)%RADIX;
sb.append(getChar(bit));
id = id / RADIX;
}
return sb.toString();
| 272
| 97
| 369
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/MessageBundle.java
|
MessageBundle
|
setMessage
|
class MessageBundle implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8959293027687263752L;
private String fromUser;
private String fromClientId;
private int type;
private int line;
private String targetId;
private WFCMessage.Message message;
private long messageId;
public MessageBundle() {
}
public MessageBundle(long messageId, String fromUser, String fromClientId, WFCMessage.Message message) {
super();
this.fromUser = fromUser;
this.fromClientId = fromClientId;
this.type = message.getConversation().getType();
this.targetId = message.getConversation().getTarget();
this.line = message.getConversation().getLine();
this.message = message;
this.messageId = messageId;
}
public int getLine() {
return line;
}
public long getMessageId() {
return messageId;
}
public String getFromUser() {
return fromUser;
}
public String getFromClientId() {
return fromClientId;
}
public int getType() {
return type;
}
public String getTargetId() {
return targetId;
}
public WFCMessage.Message getMessage() {
return message;
}
public void setFromClientId(String fromClientId) {
this.fromClientId = fromClientId;
}
public void setMessage(WFCMessage.Message message) {<FILL_FUNCTION_BODY>}
}
|
this.fromUser = message.getFromUser();
this.type = message.getConversation().getType();
this.targetId = message.getConversation().getTarget();
this.line = message.getConversation().getLine();
this.message = message;
this.messageId = message.getMessageId();
| 401
| 82
| 483
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/MessageShardingUtil.java
|
MessageShardingUtil
|
getMessageTable
|
class MessageShardingUtil {
private static SpinLock mLock = new SpinLock();
private static volatile int rotateId = 0;
private static volatile long timeId = 0;
private static int nodeId = 0;
private static int rotateIdWidth = 15;
private static int rotateIdMask = 0x7FFF;
private static int nodeIdWidth = 6;
private static int nodeIdMask = 0x3F;
private static final long T201801010000 = 1514736000000L;
public static void setNodeId(int nodeId) {
MessageShardingUtil.nodeId = nodeId;
}
/**
* ID = timestamp(43) + nodeId(6) + rotateId(15)
* 所以时间限制是到2157/5/15(2的42次幂代表的时间 + (2018-1970))。节点数限制是小于64,每台服务器每毫秒最多发送32768条消息
* @return
*/
public static long generateId() throws Exception {
mLock.lock();
rotateId = (rotateId + 1)&rotateIdMask;
long id = System.currentTimeMillis() - T201801010000;
if (id > timeId) {
timeId = id;
rotateId = 1;
} else if(id == timeId) {
if (rotateId == (rotateIdMask - 1)) { //当前空间已经用完,等待下一个空间打开
while (id <= timeId) {
id = System.currentTimeMillis() - T201801010000;
}
mLock.unLock();
return generateId();
}
} else { //id < timeId;
if (rotateId > (rotateIdMask -1)*9/10) { //空间已经接近用完
if (timeId - id < 3000) { //时间回拨小于3秒,等待时间赶上回拨之前记录
while (id < timeId) {
id = System.currentTimeMillis() - T201801010000;
}
mLock.unLock();
return generateId();
} else { //时间回拨大于3秒,抛出异常,这段时间消息将不可用。
mLock.unLock();
throw new Exception("Time turn back " + (timeId - id) + " ms, it too long!!!");
}
} else {
id = timeId;
}
}
id <<= nodeIdWidth;
id += (nodeId & nodeIdMask);
id <<= rotateIdWidth;
id += rotateId;
mLock.unLock();
return id;
}
public static String getMessageTable(long mid) {<FILL_FUNCTION_BODY>}
static Calendar getCalendarFromMessageId(long mid) {
Calendar calendar = Calendar.getInstance();
if (mid != Long.MAX_VALUE && mid != 0) {
mid >>= (nodeIdWidth + rotateIdWidth);
Date date = new Date(mid + T201801010000);
calendar.setTime(date);
} else {
Date date = new Date(System.currentTimeMillis());
calendar.setTime(date);
}
return calendar;
}
public static long getMsgIdFromTimestamp(long timestamp) {
long id = timestamp - T201801010000;
id <<= rotateIdWidth;
id <<= nodeIdWidth;
return id;
}
public static String getPreviousMessageTable(long mid) {
return getMessageTable(mid, -1);
}
public static String getMessageTable(long mid, int offset) {
if (DBUtil.IsEmbedDB) {
return null;
}
mid >>= (nodeIdWidth + rotateIdWidth);
Date date = new Date(mid + T201801010000);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
year %= 3;
month = month + offset;
while (month < 0) {
month += 12;
year = (year + 3 - 1)%3;
}
while (month >= 12) {
month -= 12;
year = (year + 1)%3;
}
return "t_messages_" + (year * 12 + month);
}
public static void main(String[] args) throws Exception {
ConcurrentHashMap<Long, Integer> messageIds = new ConcurrentHashMap<>();
int threadCount = 1000;
int loop = 1000000;
for (int i = 0; i < threadCount; i++) {
new Thread(()->{
for (int j = 0; j < loop; j++) {
try {
long mid = generateId();
if(messageIds.put(mid, j) != null) {
System.out.println("Duplicated message id !!!!!!" + mid);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
Thread.sleep(1000 * 60 * 10);
}
}
|
if (DBUtil.IsEmbedDB) {
return "t_messages";
}
Calendar calendar = Calendar.getInstance();
if (mid != Long.MAX_VALUE && mid != 0) {
mid >>= (nodeIdWidth + rotateIdWidth);
Date date = new Date(mid + T201801010000);
calendar.setTime(date);
} else {
Date date = new Date(System.currentTimeMillis());
calendar.setTime(date);
}
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
year %= 3;
return "t_messages_" + (year * 12 + month);
| 1,423
| 190
| 1,613
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/RateLimiter.java
|
RateLimiter
|
main
|
class RateLimiter {
private static final int DEFAULT_LIMIT_TIME_SECOND = 5;
private static final int DEFAULT_LIMIT_COUNT = 100;
private static final long expire = 2 * 60 * 60 * 1000;
private double rate = (double) DEFAULT_LIMIT_COUNT / (DEFAULT_LIMIT_TIME_SECOND);
private long capacity = DEFAULT_LIMIT_COUNT * 1000;
private long lastCleanTime;
private Map<String, Long> requestCountMap = new HashMap<>();
private Map<String, Long> requestTimeMap = new HashMap<>();
private SpinLock lock = new SpinLock();
public RateLimiter() {
}
public RateLimiter(int limitTimeSecond, int limitCount) {
if (limitTimeSecond <= 0 || limitCount <= 0) {
throw new IllegalArgumentException();
}
this.capacity = limitCount * 1000;
this.rate = (double) limitCount / limitTimeSecond;
}
/**
* 漏桶算法,https://en.wikipedia.org/wiki/Leaky_bucket
*/
public boolean isGranted(String userId) {
try {
lock.lock();
long current = System.currentTimeMillis();
cleanUp(current);
Long lastRequestTime = requestTimeMap.get(userId);
long count = 0;
if (lastRequestTime == null) {
count += 1000;
requestTimeMap.put(userId, current);
requestCountMap.put(userId, count);
return true;
} else {
count = requestCountMap.get(userId);
lastRequestTime = requestTimeMap.get(userId);
count -= (current - lastRequestTime) * rate;
count = count > 0 ? count : 0;
requestTimeMap.put(userId, current);
if (count < capacity) {
count += 1000;
requestCountMap.put(userId, count);
return true;
} else {
requestCountMap.put(userId, count);
return false;
}
}
} finally {
lock.unLock();
}
}
private void cleanUp(long current) {
if (current - lastCleanTime > expire) {
for (Iterator<Map.Entry<String, Long>> it = requestTimeMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Long> entry = it.next();
if (entry.getValue() < current - expire) {
it.remove();
requestCountMap.remove(entry.getKey());
}
}
lastCleanTime = current;
}
}
public static void main(String[] args) throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
RateLimiter limiter = new RateLimiter(1, 10);
long start = System.currentTimeMillis();
for (int i = 0; i < 53; i++) {
if (!limiter.isGranted("test")) {
System.out.println("1 too frequency " + i);
}
}
Thread.sleep(1 * 1000);
System.out.println("sleep 1 s");
for (int i = 0; i < 53; i++) {
if (!limiter.isGranted("test")) {
System.out.println("2 too frequency " + i);
}
}
Thread.sleep(5 * 1000);
System.out.println("sleep 5 s");
for (int i = 0; i < 53; i++) {
if (!limiter.isGranted("test")) {
System.out.println("3 too frequency " + i);
}
}
Thread.sleep(5 * 1000);
System.out.println("sleep 5 s");
long second = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
if (!limiter.isGranted("test")) {
System.out.println("4 too frequency " + i);
}
Thread.sleep(50);
}
System.out.println("second: " + (System.currentTimeMillis() - second));
System.out.println("end: " + (System.currentTimeMillis() - start));
| 731
| 399
| 1,130
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/SensitiveFilter.java
|
SensitiveFilter
|
getUrlLength
|
class SensitiveFilter {
public enum MatchType {
MIN_MATCH("最小匹配规则"),MAX_MATCH("最大匹配规则");
String desc;
MatchType(String desc) {
this.desc = desc;
}
}
private Map<Object,Object> sensitiveWordsMap;
private static final String END_FLAG="end";
public boolean isContainSensitiveWord(String text){
Set<String> sensitiveWords = getSensitiveWords(text, MatchType.MIN_MATCH);
if(sensitiveWords!=null&&sensitiveWords.size()>0){
return true;
}
return false;
}
private int getUrlLength(String text, int i) {<FILL_FUNCTION_BODY>}
public Set<String> getSensitiveWords(String text,MatchType matchType){
Set<String> sensitiveWords=new HashSet<>();
if(text==null||text.trim().length()==0){
return sensitiveWords;
}
String originalText = text;
text = text.toLowerCase();
for(int i=0;i<text.length();i++){
int urlLength = getUrlLength(text, i);
if(urlLength > 0) {
i = i + urlLength;
continue;
}
int sensitiveWordLength = getSensitiveWordLength(text, i, matchType);
if(sensitiveWordLength>0){
String sensitiveWord = originalText.substring(i, i + sensitiveWordLength);
sensitiveWords.add(sensitiveWord);
if(matchType==MatchType.MIN_MATCH){
break;
}
i=i+sensitiveWordLength-1;
}
}
return sensitiveWords;
}
public int getSensitiveWordLength(String text,int startIndex,MatchType matchType){
if(text==null||text.trim().length()==0){
throw new IllegalArgumentException("The input text must not be empty.");
}
char currentChar;
Map<Object,Object> currentMap=sensitiveWordsMap;
int wordLength=0;
boolean endFlag=false;
for(int i=startIndex;i<text.length();i++){
currentChar=text.charAt(i);
Map<Object,Object> subMap=(Map<Object,Object>) currentMap.get(currentChar);
if(subMap==null){
break;
}else {
wordLength++;
if(subMap.containsKey(END_FLAG)){
endFlag=true;
if(matchType==MatchType.MIN_MATCH){
break;
}else {
currentMap=subMap;
}
}else {
currentMap=subMap;
}
}
}
if(!endFlag){
wordLength=0;
}
return wordLength;
}
public SensitiveFilter(Set<String> sensitiveWords){
sensitiveWordsMap=new ConcurrentHashMap<>(sensitiveWords.size());
if(sensitiveWords==null||sensitiveWords.isEmpty()){
//throw new IllegalArgumentException("Senditive words must not be empty!");
return;
}
String currentWord;
Map<Object,Object> currentMap;
Map<Object,Object> subMap;
Iterator<String> iterator = sensitiveWords.iterator();
while (iterator.hasNext()){
currentWord=iterator.next();
if(currentWord==null||currentWord.trim().length()<1){ //敏感词长度必须大于等于1
continue;
}
currentMap=sensitiveWordsMap;
for(int i=0;i<currentWord.length();i++){
char c=currentWord.charAt(i);
subMap=(Map<Object, Object>) currentMap.get(c);
if(subMap==null){
subMap=new HashMap<>();
currentMap.put(c,subMap);
currentMap=subMap;
}else {
currentMap= subMap;
}
if(i==currentWord.length()-1){
//如果是最后一个字符,则put一个结束标志,这里只需要保存key就行了,value为null可以节省空间。
//如果不是最后一个字符,则不需要存这个结束标志,同样也是为了节省空间。
currentMap.put(END_FLAG,null);
}
}
}
}
public static void main(String[] args) {
Set<String> words = new HashSet<>();
words.add("sb");
words.add("xx");
SensitiveFilter sensitiveFilter = new SensitiveFilter(words);
String text1 = "u sb a";
Set<String> ss = sensitiveFilter.getSensitiveWords(text1, MatchType.MIN_MATCH);
System.out.println(ss.size());
text1 = "u xx";
ss = sensitiveFilter.getSensitiveWords(text1, MatchType.MIN_MATCH);
System.out.println(ss.size());
text1 = "a url is https://sdsbhe.com here";
ss = sensitiveFilter.getSensitiveWords(text1, MatchType.MIN_MATCH);
System.out.println(ss.size());
text1 = "a url is https://sdsbhe.com";
ss = sensitiveFilter.getSensitiveWords(text1, MatchType.MIN_MATCH);
System.out.println(ss.size());
text1 = "a url is https://sdsbhe.com\nsb";
ss = sensitiveFilter.getSensitiveWords(text1, MatchType.MIN_MATCH);
System.out.println(ss.size());
}
}
|
boolean startUrl = false;
if(text.charAt(i) == 'h') {
if(text.length() > i + 6 && text.substring(i, i+7).equals("http://")) {
startUrl = true;
} else if(text.length() > i + 7 && text.substring(i, i+8).equals("https://")) {
startUrl = true;
}
}
if(startUrl) {
for (int j = i+1; j < text.length(); j++) {
char ch = text.charAt(j);
if(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') {
return j-i;
}
}
return text.length() - i - 1;
}
return 0;
| 1,467
| 213
| 1,680
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/SpinLock.java
|
SpinLock
|
lock
|
class SpinLock {
//java中原子(CAS)操作
AtomicReference<Thread> owner = new AtomicReference<>();//持有自旋锁的线程对象
private int count;
public void lock() {<FILL_FUNCTION_BODY>}
public void unLock() {
Thread cur = Thread.currentThread();
owner.compareAndSet(cur, null);
}
}
|
Thread cur = Thread.currentThread();
//lock函数将owner设置为当前线程,并且预测原来的值为空。unlock函数将owner设置为null,并且预测值为当前线程。当有第二个线程调用lock操作时由于owner值不为空,导致循环
//一直被执行,直至第一个线程调用unlock函数将owner设置为null,第二个线程才能进入临界区。
while (!owner.compareAndSet(null, cur)){
}
| 106
| 126
| 232
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/UUIDGenerator.java
|
UUIDGenerator
|
getUUID
|
class UUIDGenerator {
public static String getUUID() {<FILL_FUNCTION_BODY>}
}
|
UUID uuid = UUID.randomUUID();
String str = uuid.toString();
str = str.replace("-", "");
return str;
| 29
| 42
| 71
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/broker/src/main/java/win/liyufan/im/Utility.java
|
Utility
|
formatJson
|
class Utility {
private static Map<String, IMExceptionEvent> exceptionEventHashMap = new ConcurrentHashMap<>();
static AtomicLong SendExceptionExpireTime = new AtomicLong(0);
static int SendExceptionDuration = 180000;
static long lastSendTime = System.currentTimeMillis();
static {
new Thread(()->{
while (true) {
try {
Thread.sleep(60 * 1000);
sendExceptionEvent();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public static InetAddress getLocalAddress(){
try {
Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
while( b.hasMoreElements()){
for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses())
if ( f.getAddress().isSiteLocalAddress())
return f.getAddress();
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
public static void printExecption(Logger LOG, Exception e) {
printExecption(LOG, e, 0);
}
public static void printExecption(Logger LOG, Exception e, int eventType) {
String message = "";
for(StackTraceElement stackTraceElement : e.getStackTrace()) {
message = message + System.lineSeparator() + stackTraceElement.toString();
}
LOG.error("Exception: {}", e.getMessage());
LOG.error(message);
if(eventType > 0) {
String key = eventType+(e.getMessage() != null ? e.getMessage().split("\n")[0] : "null");
IMExceptionEvent event = exceptionEventHashMap.get(key);
if(event == null) {
event = new IMExceptionEvent();
event.event_type = eventType;
event.msg = e.getMessage();
event.call_stack = message;
event.count = 0;
exceptionEventHashMap.put(key, event);
}
event.count++;
sendExceptionEvent();
}
}
private static String gMonitorEventAddress;
public static void setMonitorEventAddress(String gMonitorEventAddress) {
Utility.gMonitorEventAddress = gMonitorEventAddress;
}
private static void sendExceptionEvent() {
if(StringUtil.isNullOrEmpty(gMonitorEventAddress)) {
return;
}
long now = System.currentTimeMillis();
long t = SendExceptionExpireTime.getAndUpdate((long l) -> now - l >= SendExceptionDuration ? now : l);
if(now - t >= SendExceptionDuration) {
for (Map.Entry<String, IMExceptionEvent> entry : exceptionEventHashMap.entrySet()) {
if(entry.getValue().count > 0) {
String jsonStr = GsonUtil.gson.toJson(entry.getValue());
Server.getServer().getCallbackScheduler().execute(() -> HttpUtils.httpJsonPost(gMonitorEventAddress, jsonStr, HttpUtils.HttpPostType.POST_TYPE_Server_Exception_Callback));
entry.getValue().count = 0;
lastSendTime = now;
}
}
if(now - lastSendTime > 24 * 3600 * 1000) {
lastSendTime = now;
IMExceptionEvent event = new IMExceptionEvent();
event.event_type = 0;
event.msg = "监控心跳通知";
event.call_stack = "别担心!这个是心跳消息,已经有24小时没有出现异常消息了!";
event.count = IMExceptionEvent.EventType.HEART_BEAT;
String jsonStr = GsonUtil.gson.toJson(event);
Server.getServer().getCallbackScheduler().execute(() -> HttpUtils.httpJsonPost(gMonitorEventAddress, jsonStr, HttpUtils.HttpPostType.POST_TYPE_Server_Exception_Callback));
}
}
}
public static String getMacAddress() throws UnknownHostException,
SocketException {
InetAddress ipAddress = InetAddress.getLocalHost();
NetworkInterface networkInterface = NetworkInterface
.getByInetAddress(ipAddress);
byte[] macAddressBytes = networkInterface.getHardwareAddress();
StringBuilder macAddressBuilder = new StringBuilder();
for (int macAddressByteIndex = 0; macAddressByteIndex < macAddressBytes.length; macAddressByteIndex++) {
String macAddressHexByte = String.format("%02X",
macAddressBytes[macAddressByteIndex]);
macAddressBuilder.append(macAddressHexByte);
if (macAddressByteIndex != macAddressBytes.length - 1)
{
macAddressBuilder.append(":");
}
}
return macAddressBuilder.toString();
}
/**
* 格式化
*
* @param jsonStr
* @return
* @author lizhgb
* @Date 2015-10-14 下午1:17:35
* @Modified 2017-04-28 下午8:55:35
*/
public static String formatJson(String jsonStr) {<FILL_FUNCTION_BODY>}
/**
* 添加space
*
* @param sb
* @param indent
* @author lizhgb
* @Date 2015-10-14 上午10:38:04
*/
private static void addIndentBlank(StringBuilder sb, int indent) {
for (int i = 0; i < indent; i++) {
sb.append('\t');
}
}
}
|
if (null == jsonStr || "".equals(jsonStr))
return "";
StringBuilder sb = new StringBuilder();
char last = '\0';
char current = '\0';
int indent = 0;
boolean isInQuotationMarks = false;
for (int i = 0; i < jsonStr.length(); i++) {
last = current;
current = jsonStr.charAt(i);
switch (current) {
case '"':
if (last != '\\'){
isInQuotationMarks = !isInQuotationMarks;
}
sb.append(current);
break;
case '{':
case '[':
sb.append(current);
if (!isInQuotationMarks) {
sb.append('\n');
indent++;
addIndentBlank(sb, indent);
}
break;
case '}':
case ']':
if (!isInQuotationMarks) {
sb.append('\n');
indent--;
addIndentBlank(sb, indent);
}
sb.append(current);
break;
case ',':
sb.append(current);
if (last != '\\' && !isInQuotationMarks) {
sb.append('\n');
addIndentBlank(sb, indent);
}
break;
default:
sb.append(current);
}
}
return sb.toString();
| 1,453
| 390
| 1,843
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/messagecontentbuilder/MessageContentBuilder.java
|
MessageContentBuilder
|
encodeBase
|
class MessageContentBuilder {
private int mentionedType;
private List<String> mentionedTargets;
private String extra;
public MessageContentBuilder mentionedType(int mentionedType) {
this.mentionedType = mentionedType;
return this;
}
public MessageContentBuilder mentionedTargets(List<String> mentionedTargets) {
this.mentionedTargets = mentionedTargets;
return this;
}
public MessageContentBuilder extra(String extra) {
this.extra = extra;
return this;
}
protected MessagePayload encodeBase() {<FILL_FUNCTION_BODY>}
abstract public MessagePayload build();
}
|
MessagePayload payload = new MessagePayload();
payload.setMentionedType(mentionedType);
payload.setMentionedTarget(mentionedTargets);
payload.setExtra(extra);
return payload;
| 164
| 56
| 220
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/messagecontentbuilder/RichNotificationContentBuilder.java
|
RichNotificationContentBuilder
|
addItem
|
class RichNotificationContentBuilder extends MessageContentBuilder{
private String title;
private String desc;
private String remark;
private JSONArray datas;
private String exName;
private String exPortrait;
private String exUrl;
private String appId;
public static RichNotificationContentBuilder newBuilder(String title, String desc, String exUrl) {
RichNotificationContentBuilder builder = new RichNotificationContentBuilder();
builder.title = title;
builder.desc = desc;
builder.exUrl = exUrl;
return builder;
}
public RichNotificationContentBuilder remark(String remark) {
this.remark = remark;
return this;
}
public RichNotificationContentBuilder exName(String exName) {
this.exName = exName;
return this;
}
public RichNotificationContentBuilder exPortrait(String exPortrait) {
this.exPortrait = exPortrait;
return this;
}
public RichNotificationContentBuilder appId(String appId) {
this.appId = appId;
return this;
}
public RichNotificationContentBuilder addItem(String key, String value) {
return addItem(key, value, null);
}
public RichNotificationContentBuilder addItem(String key, String value, String color) {<FILL_FUNCTION_BODY>}
@Override
public MessagePayload build() {
MessagePayload payload = encodeBase();
payload.setType(ProtoConstants.ContentType.Rich_Notification);
payload.setPersistFlag(ProtoConstants.PersistFlag.Persist_And_Count);
payload.setPushContent(title);
payload.setContent(desc);
JSONObject jsonObject = new JSONObject();
if(!StringUtil.isNullOrEmpty(remark))
jsonObject.put("remark", remark);
if(!StringUtil.isNullOrEmpty(exName))
jsonObject.put("exName", exName);
if(!StringUtil.isNullOrEmpty(exPortrait))
jsonObject.put("exPortrait", exPortrait);
if(!StringUtil.isNullOrEmpty(exUrl))
jsonObject.put("exUrl", exUrl);
if(!StringUtil.isNullOrEmpty(appId))
jsonObject.put("appId", appId);
if(datas != null && !datas.isEmpty())
jsonObject.put("datas", datas);
payload.setBase64edData(Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8)));
return payload;
}
}
|
if(this.datas == null) {
this.datas = new JSONArray();
}
JSONObject item = new JSONObject();
item.put("key", key);
item.put("value", value == null ? "" : value);
if(!StringUtil.isNullOrEmpty(color)) {
item.put("color", color);
}
this.datas.add(item);
return this;
| 648
| 109
| 757
|
<methods>public non-sealed void <init>() ,public abstract cn.wildfirechat.pojos.MessagePayload build() ,public cn.wildfirechat.messagecontentbuilder.MessageContentBuilder extra(java.lang.String) ,public cn.wildfirechat.messagecontentbuilder.MessageContentBuilder mentionedTargets(List<java.lang.String>) ,public cn.wildfirechat.messagecontentbuilder.MessageContentBuilder mentionedType(int) <variables>private java.lang.String extra,private List<java.lang.String> mentionedTargets,private int mentionedType
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/messagecontentbuilder/SoundMessageContentBuilder.java
|
SoundMessageContentBuilder
|
build
|
class SoundMessageContentBuilder extends MediaMessageContentBuilder {
private int duration;
public static SoundMessageContentBuilder newBuilder(int duration) {
SoundMessageContentBuilder builder = new SoundMessageContentBuilder();
builder.duration = duration;
return builder;
}
@Override
public MessagePayload build() {<FILL_FUNCTION_BODY>}
}
|
MessagePayload payload = encodeBase();
payload.setType(ProtoConstants.ContentType.Voice);
payload.setMediaType(ProtoConstants.MessageMediaType.VOICE);
payload.setPersistFlag(ProtoConstants.PersistFlag.Persist_And_Count);
JSONObject jsonObject = new JSONObject();
jsonObject.put("duration", duration);
payload.setContent(jsonObject.toJSONString());
return payload;
| 90
| 111
| 201
|
<methods>public non-sealed void <init>() ,public cn.wildfirechat.messagecontentbuilder.MediaMessageContentBuilder remoteMediaUrl(java.lang.String) <variables>private java.lang.String remoteMediaUrl
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/messagecontentbuilder/StreamingTextMessageContentBuilder.java
|
StreamingTextMessageContentBuilder
|
build
|
class StreamingTextMessageContentBuilder extends MessageContentBuilder{
private String text;
private String streamId;
private boolean generating;
public static StreamingTextMessageContentBuilder newBuilder(String streamId) {
StreamingTextMessageContentBuilder builder = new StreamingTextMessageContentBuilder();
builder.generating = false;
builder.streamId = streamId;
return builder;
}
public StreamingTextMessageContentBuilder text(String text) {
this.text = text;
return this;
}
public StreamingTextMessageContentBuilder generating(boolean generating) {
this.generating = generating;
return this;
}
@Override
public MessagePayload build() {<FILL_FUNCTION_BODY>}
}
|
MessagePayload payload = encodeBase();
payload.setSearchableContent(text);
payload.setContent(streamId);
if(generating) {
//正在生成消息的类型是14,存储标记位为透传为4。
payload.setType(14);
payload.setPersistFlag(4);
} else {
//已经生成消息的类型是15,存储标记位为透传为3。
payload.setType(15);
payload.setPersistFlag(3);
}
return payload;
| 187
| 145
| 332
|
<methods>public non-sealed void <init>() ,public abstract cn.wildfirechat.pojos.MessagePayload build() ,public cn.wildfirechat.messagecontentbuilder.MessageContentBuilder extra(java.lang.String) ,public cn.wildfirechat.messagecontentbuilder.MessageContentBuilder mentionedTargets(List<java.lang.String>) ,public cn.wildfirechat.messagecontentbuilder.MessageContentBuilder mentionedType(int) <variables>private java.lang.String extra,private List<java.lang.String> mentionedTargets,private int mentionedType
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/messagecontentbuilder/TextMessageContentBuilder.java
|
TextMessageContentBuilder
|
build
|
class TextMessageContentBuilder extends MessageContentBuilder{
private String text;
public static TextMessageContentBuilder newBuilder(String text) {
TextMessageContentBuilder builder = new TextMessageContentBuilder();
builder.text = text;
return builder;
}
@Override
public MessagePayload build() {<FILL_FUNCTION_BODY>}
}
|
MessagePayload payload = encodeBase();
payload.setType(ProtoConstants.ContentType.Text);
payload.setPersistFlag(ProtoConstants.PersistFlag.Persist_And_Count);
payload.setSearchableContent(text);
return payload;
| 89
| 67
| 156
|
<methods>public non-sealed void <init>() ,public abstract cn.wildfirechat.pojos.MessagePayload build() ,public cn.wildfirechat.messagecontentbuilder.MessageContentBuilder extra(java.lang.String) ,public cn.wildfirechat.messagecontentbuilder.MessageContentBuilder mentionedTargets(List<java.lang.String>) ,public cn.wildfirechat.messagecontentbuilder.MessageContentBuilder mentionedType(int) <variables>private java.lang.String extra,private List<java.lang.String> mentionedTargets,private int mentionedType
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/pojos/ArticleContent.java
|
Article
|
addSubArticle
|
class Article {
public String id;
public String cover;
public String title;
public String digest;
public String url;
public boolean rr;
public Article() {
}
public Article(String id, String cover, String title, String digest, String url, boolean rr) {
this.id = id;
this.cover = cover;
this.title = title;
this.digest = digest;
this.url = url;
this.rr = rr;
}
}
public Article top;
public List<Article> subArticles;
public ArticleContent() {
}
public ArticleContent(String id, String cover, String title, String digest, String url, boolean rr) {
this.top = new Article(id, cover, title, digest, url, rr);
}
public ArticleContent addSubArticle(String id, String cover, String title, String digest, String url, boolean rr) {<FILL_FUNCTION_BODY>
|
if (subArticles == null)
subArticles = new ArrayList<>();
subArticles.add(new Article(id, cover, title, digest, url, rr));
return this;
| 257
| 52
| 309
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/pojos/BroadMessageData.java
|
BroadMessageData
|
isValide
|
class BroadMessageData {
private String sender;
private int line;
private MessagePayload payload;
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(BroadMessageData sendMessageData) {<FILL_FUNCTION_BODY>}
public WFCMessage.Message toProtoMessage() {
return WFCMessage.Message.newBuilder().setFromUser(sender)
.setConversation(WFCMessage.Conversation.newBuilder().setType(ProtoConstants.ConversationType.ConversationType_Private).setTarget(sender).setLine(line))
.setContent(payload.toProtoMessageContent())
.build();
}
}
|
if(sendMessageData == null ||
StringUtil.isNullOrEmpty(sendMessageData.getSender()) ||
sendMessageData.getPayload() == null) {
return false;
}
return true;
| 288
| 59
| 347
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/pojos/InputAddGroupMember.java
|
InputAddGroupMember
|
toProtoGroupRequest
|
class InputAddGroupMember extends InputGroupBase {
private String group_id;
private List<PojoGroupMember> members;
public String getGroup_id() {
return group_id;
}
public void setGroup_id(String group_id) {
this.group_id = group_id;
}
public List<PojoGroupMember> getMembers() {
return members;
}
public void setMembers(List<PojoGroupMember> members) {
this.members = members;
}
public boolean isValide() {
return true;
}
public WFCMessage.AddGroupMemberRequest toProtoGroupRequest() {<FILL_FUNCTION_BODY>}
}
|
WFCMessage.AddGroupMemberRequest.Builder addGroupBuilder = WFCMessage.AddGroupMemberRequest.newBuilder();
addGroupBuilder.setGroupId(group_id);
for (PojoGroupMember pojoGroupMember : getMembers()) {
WFCMessage.GroupMember.Builder groupMemberBuilder = WFCMessage.GroupMember.newBuilder().setMemberId(pojoGroupMember.getMember_id());
if (!StringUtil.isNullOrEmpty(pojoGroupMember.getAlias())) {
groupMemberBuilder.setAlias(pojoGroupMember.getAlias());
}
groupMemberBuilder.setType(pojoGroupMember.getType());
if(!StringUtil.isNullOrEmpty(pojoGroupMember.getExtra())) {
groupMemberBuilder.setExtra(pojoGroupMember.getExtra());
}
addGroupBuilder.addAddedMember(groupMemberBuilder);
}
if (to_lines != null) {
for (Integer line : to_lines
) {
addGroupBuilder.addToLine(line);
}
}
if (notify_message != null) {
addGroupBuilder.setNotifyContent(notify_message.toProtoMessageContent());
}
return addGroupBuilder.build();
| 186
| 309
| 495
|
<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/InputCreateChannel.java
|
InputCreateChannel
|
toProtoChannelInfo
|
class InputCreateChannel {
private String owner;
private String name;
private String targetId;
private String callback;
private String portrait;
private int auto;
private String secret;
private String desc;
private int state;
private String extra;
private long updateDt;
public WFCMessage.ChannelInfo toProtoChannelInfo() {<FILL_FUNCTION_BODY>}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTargetId() {
return targetId;
}
public void setTargetId(String targetId) {
this.targetId = targetId;
}
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
public String getPortrait() {
return portrait;
}
public void setPortrait(String portrait) {
this.portrait = portrait;
}
public int getAuto() {
return auto;
}
public void setAuto(int auto) {
this.auto = auto;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public long getUpdateDt() {
return updateDt;
}
public void setUpdateDt(long updateDt) {
this.updateDt = updateDt;
}
}
|
WFCMessage.ChannelInfo.Builder builder = WFCMessage.ChannelInfo.newBuilder().setOwner(owner);
if (!StringUtil.isNullOrEmpty(name))
builder = builder.setName(name);
if (!StringUtil.isNullOrEmpty(targetId))
builder = builder.setTargetId(targetId);
if (!StringUtil.isNullOrEmpty(callback))
builder = builder.setCallback(callback);
if (!StringUtil.isNullOrEmpty(portrait))
builder = builder.setPortrait(portrait);
builder = builder.setAutomatic(auto);
if (!StringUtil.isNullOrEmpty(secret))
builder = builder.setSecret(secret);
if (!StringUtil.isNullOrEmpty(desc))
builder = builder.setDesc(desc);
builder = builder.setStatus(state);
if (!StringUtil.isNullOrEmpty(extra))
builder = builder.setExtra(extra);
if (!StringUtil.isNullOrEmpty(name))
builder = builder.setUpdateDt(updateDt);
else
builder = builder.setUpdateDt(System.currentTimeMillis());
return builder.build();
| 566
| 292
| 858
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/pojos/InputCreateChatroom.java
|
InputCreateChatroom
|
toChatroomInfo
|
class InputCreateChatroom {
private String chatroomId;
private String title;
private String desc;
private String portrait;
private String extra;
private Integer state;
public WFCMessage.ChatroomInfo toChatroomInfo() {<FILL_FUNCTION_BODY>}
public InputCreateChatroom() {
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getChatroomId() {
return chatroomId;
}
public void setChatroomId(String chatroomId) {
this.chatroomId = chatroomId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPortrait() {
return portrait;
}
public void setPortrait(String portrait) {
this.portrait = portrait;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
}
|
WFCMessage.ChatroomInfo.Builder builder = WFCMessage.ChatroomInfo.newBuilder().setTitle(title);
if (!StringUtil.isNullOrEmpty(desc)) {
builder.setDesc(desc);
}
if (!StringUtil.isNullOrEmpty(portrait)) {
builder.setPortrait(portrait);
}
long current = System.currentTimeMillis();
builder.setCreateDt(current).setUpdateDt(current).setMemberCount(0);
if (!StringUtil.isNullOrEmpty(extra)) {
builder.setExtra(extra);
}
if (state == null || state == 0) {
builder.setState(ProtoConstants.ChatroomState.Chatroom_State_Normal);
} else if(state == 1) {
builder.setState(ProtoConstants.ChatroomState.Chatroom_State_NotStart);
} else {
builder.setState(ProtoConstants.ChatroomState.Chatroom_State_End);
}
return builder.build();
| 343
| 260
| 603
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/pojos/InputCreateGroup.java
|
InputCreateGroup
|
toProtoGroupRequest
|
class InputCreateGroup extends InputGroupBase {
private PojoGroup group;
public boolean isValide() {
return true;
}
public WFCMessage.CreateGroupRequest toProtoGroupRequest() {<FILL_FUNCTION_BODY>}
public PojoGroup getGroup() {
return group;
}
public void setGroup(PojoGroup group) {
this.group = group;
}
}
|
WFCMessage.Group.Builder groupBuilder = WFCMessage.Group.newBuilder();
WFCMessage.GroupInfo.Builder groupInfoBuilder = WFCMessage.GroupInfo.newBuilder();
PojoGroupInfo group_info = group.getGroup_info();
if (!StringUtil.isNullOrEmpty(group_info.target_id)) {
groupInfoBuilder.setTargetId(group_info.getTarget_id());
}
if (!StringUtil.isNullOrEmpty(group_info.name)) {
groupInfoBuilder.setName(group_info.getName());
}
if (!StringUtil.isNullOrEmpty(group_info.portrait)) {
groupInfoBuilder.setPortrait(group_info.getPortrait());
}
if (!StringUtil.isNullOrEmpty(group_info.owner)) {
groupInfoBuilder.setOwner(group_info.getOwner());
}
groupInfoBuilder.setType(group_info.getType());
if (!StringUtil.isNullOrEmpty(group_info.extra)) {
groupInfoBuilder.setExtra(group_info.getExtra());
}
if (group_info.join_type > 0 && group_info.join_type < 128) {
groupInfoBuilder.setJoinType(group_info.join_type);
}
if (group_info.mute > 0 && group_info.mute < 128) {
groupInfoBuilder.setMute(group_info.mute);
}
if (group_info.private_chat > 0 && group_info.private_chat < 128) {
groupInfoBuilder.setPrivateChat(group_info.private_chat);
}
if (group_info.searchable > 0 && group_info.searchable < 128) {
groupInfoBuilder.setSearchable(group_info.searchable);
}
if(group_info.history_message > 0&& group_info.history_message < 128) {
groupInfoBuilder.setHistoryMessage(group_info.history_message);
}
if(group_info.max_member_count > 0) {
groupInfoBuilder.setMaxMemberCount(group_info.max_member_count);
}
if(group_info.isSuper_group()) {
groupInfoBuilder.setSuperGroup(1);
}
groupInfoBuilder.setDeleted(0);
groupBuilder.setGroupInfo(groupInfoBuilder);
if(group.getMembers() != null) {
for (PojoGroupMember pojoGroupMember : group.getMembers()) {
WFCMessage.GroupMember.Builder groupMemberBuilder = WFCMessage.GroupMember.newBuilder().setMemberId(pojoGroupMember.getMember_id());
if (!StringUtil.isNullOrEmpty(pojoGroupMember.getAlias())) {
groupMemberBuilder.setAlias(pojoGroupMember.getAlias());
}
groupMemberBuilder.setType(pojoGroupMember.getType());
if (!StringUtil.isNullOrEmpty(pojoGroupMember.getExtra())) {
groupMemberBuilder.setExtra(pojoGroupMember.extra);
}
groupBuilder.addMembers(groupMemberBuilder);
}
}
WFCMessage.CreateGroupRequest.Builder createGroupReqBuilder = WFCMessage.CreateGroupRequest.newBuilder();
createGroupReqBuilder.setGroup(groupBuilder);
if (to_lines != null) {
for (Integer line : to_lines
) {
createGroupReqBuilder.addToLine(line);
}
}
if (notify_message != null) {
createGroupReqBuilder.setNotifyContent(notify_message.toProtoMessageContent());
}
return createGroupReqBuilder.build();
| 111
| 942
| 1,053
|
<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/InputCreateRobot.java
|
InputCreateRobot
|
toUser
|
class InputCreateRobot {
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 WFCMessage.Robot toRobot() {
WFCMessage.Robot.Builder builder = WFCMessage.Robot.newBuilder();
if (!StringUtil.isNullOrEmpty(userId))
builder.setUid(userId);
if (!StringUtil.isNullOrEmpty(owner))
builder.setOwner(owner);
if (!StringUtil.isNullOrEmpty(secret))
builder.setSecret(secret);
if (!StringUtil.isNullOrEmpty(callback))
builder.setCallback(callback);
if (!StringUtil.isNullOrEmpty(robotExtra))
builder.setExtra(robotExtra);
builder.setState(0);
return builder.build();
}
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 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;
}
}
|
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.setType(ProtoConstants.UserType.UserType_Robot);
newUserBuilder.setGender(gender);
newUserBuilder.setUpdateDt(System.currentTimeMillis());
return newUserBuilder.build();
| 1,040
| 305
| 1,345
|
<no_super_class>
|
wildfirechat_im-server
|
im-server/common/src/main/java/cn/wildfirechat/pojos/InputDismissGroup.java
|
InputDismissGroup
|
toProtoGroupRequest
|
class InputDismissGroup 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.DismissGroupRequest toProtoGroupRequest() {<FILL_FUNCTION_BODY>}
}
|
WFCMessage.DismissGroupRequest.Builder dismissGroupBuilder = WFCMessage.DismissGroupRequest.newBuilder();
dismissGroupBuilder.setGroupId(group_id);
if (to_lines != null) {
for (Integer line : to_lines
) {
dismissGroupBuilder.addToLine(line);
}
}
if (notify_message != null) {
dismissGroupBuilder.setNotifyContent(notify_message.toProtoMessageContent());
}
return dismissGroupBuilder.build();
| 157
| 137
| 294
|
<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/InputKickoffGroupMember.java
|
InputKickoffGroupMember
|
toProtoGroupRequest
|
class InputKickoffGroupMember extends InputGroupBase {
private String group_id;
private List<String> members;
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 isValide() {
if (StringUtil.isNullOrEmpty(group_id) || StringUtil.isNullOrEmpty(operator) || members == null || members.isEmpty())
return false;
return true;
}
public WFCMessage.RemoveGroupMemberRequest toProtoGroupRequest() {<FILL_FUNCTION_BODY>}
}
|
WFCMessage.RemoveGroupMemberRequest.Builder removedGroupBuilder = WFCMessage.RemoveGroupMemberRequest.newBuilder();
removedGroupBuilder.setGroupId(group_id);
removedGroupBuilder.addAllRemovedMember(members);
if (to_lines != null) {
for (Integer line : to_lines
) {
removedGroupBuilder.addToLine(line);
}
}
if (notify_message != null) {
removedGroupBuilder.setNotifyContent(notify_message.toProtoMessageContent());
}
return removedGroupBuilder.build();
| 220
| 149
| 369
|
<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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.