PageRenderTime 89ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/linbox/im/server/router/handlers/SendMsgHandler.java

https://gitlab.com/Mr.Tomato/linbox_server
Java | 207 lines | 157 code | 47 blank | 3 comment | 17 complexity | c7f5e5436101b975eff1b800e04e5301 MD5 | raw file
  1. package com.linbox.im.server.router.handlers;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.linbox.im.exceptions.IMConsumerException;
  5. import com.linbox.im.exceptions.IMException;
  6. import com.linbox.im.message.*;
  7. import com.linbox.im.server.router.handlers.dispatcher.SendDispatcher;
  8. import com.linbox.im.server.service.IOutboxService;
  9. import com.linbox.im.server.storage.dao.IGroupMessageDAO;
  10. import com.linbox.im.server.storage.dao.IMessageDAO;
  11. import com.linbox.im.server.storage.dao.ISessionMessageDAO;
  12. import com.linbox.im.server.storage.entity.SessionMessageEntity;
  13. import com.linbox.im.utils.IMUtils;
  14. import com.linbox.im.server.storage.entity.GroupMessageEntity;
  15. import org.apache.commons.lang.StringUtils;
  16. import org.apache.kafka.clients.consumer.ConsumerRecord;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.beans.factory.annotation.Qualifier;
  21. import org.springframework.stereotype.Service;
  22. /**
  23. * Created by lrsec on 7/2/15.
  24. */
  25. @Service
  26. @Qualifier("sendMsgHandler")
  27. public class SendMsgHandler implements Handler<String, String> {
  28. private static Logger logger = LoggerFactory.getLogger(SendMsgHandler.class);
  29. @Autowired
  30. private ISessionMessageDAO sessionMessageDAO;
  31. @Autowired
  32. private IGroupMessageDAO groupMessageDAO;
  33. @Autowired
  34. private IMessageDAO messageDAO;
  35. @Autowired
  36. private IOutboxService outboxService;
  37. @Autowired
  38. private SendDispatcher dispatcher;
  39. @Override
  40. public void handle(ConsumerRecord<String, String> record) {
  41. String json = record.value();
  42. try {
  43. logger.debug("Start handling SendMsgRequest: {}", json);
  44. MessageWrapper wrapper = JSON.parseObject(json, MessageWrapper.class);
  45. SendMsgRequest request = JSON.parseObject(((JSONObject)wrapper.content).toJSONString(), SendMsgRequest.class);
  46. wrapper.content = request;
  47. if(request == null) {
  48. logger.error("SendMsgRequest format is not correct. Json string: {}", json);
  49. return;
  50. }
  51. String userId = request.userId;
  52. if(StringUtils.isBlank(userId)) {
  53. logger.error("Can not find avaiable user id for SendMsgRequest {}", json);
  54. return;
  55. }
  56. try {
  57. MessageType type = MessageType.parse(request.type);
  58. if (type == null) {
  59. logger.error("Can not parse MessageType in SendMsgRequest {}", json);
  60. throw new IMException("Unknown MessageType " + Integer.toString(request.type));
  61. }
  62. switch(type) {
  63. case Session:
  64. String remoteId = request.remoteId;
  65. if (StringUtils.isBlank(remoteId)) {
  66. logger.error("Can not find corresponding remote id for SendMsgRequest: {}", json);
  67. throw new IMException("Cannot find remote id for SendMsgRequest: " + json);
  68. }
  69. Message body = request.msg;
  70. if (body == null) {
  71. logger.error("No msg in SendMsgRequest: {}", json);
  72. throw new IMException("Empty message between " + userId + " and " + remoteId + ". rid: " + request.rId);
  73. }
  74. SessionMessageEntity dao = sessionMessageDAO.findMsgByRId(body.rId, body.fromUserId, body.toUserId);
  75. if (dao == null) {
  76. String sessionKey = IMUtils.getSessionKey(userId, remoteId);
  77. body.msgId = messageDAO.generateMsgId(sessionKey);
  78. body.sendTime = System.currentTimeMillis();
  79. dao = sessionMessageDAO.insert(body);
  80. logger.debug("Save SessionMessageDao into DB. Message: {}. Dao: {}", JSON.toJSONString(body), JSON.toJSONString(dao));
  81. dispatcher.dispatchToSingle(remoteId, userId, sessionKey, MessageType.Session, body);
  82. } else {
  83. logger.debug("Find existing SessionMessageDao for message: {}. Dao: {}", JSON.toJSONString(body), JSON.toJSONString(dao));
  84. }
  85. sendSuccessResponse(userId, request, dao);
  86. break;
  87. case Group:
  88. String groupId = request.groupId;
  89. if (StringUtils.isBlank(groupId)) {
  90. logger.error("Can not find corresponding group id for SendMsgRequest: {}", json);
  91. throw new IMException("Cannot find group id for SendMsgRequest: " + json);
  92. }
  93. Message groupMsgBody = request.msg;
  94. if (groupMsgBody == null) {
  95. logger.error("No msg in SendMsgRequest: {}", json);
  96. throw new IMException("Empty message between " + userId + " and group " + groupId + ". rid: " + request.rId);
  97. }
  98. GroupMessageEntity groupMsgDao = groupMessageDAO.findMsgByRId(groupMsgBody.rId, groupMsgBody.fromUserId, groupMsgBody.groupId);
  99. if (groupMsgDao == null) {
  100. groupMsgBody.msgId = messageDAO.generateMsgId(groupId);
  101. groupMsgBody.sendTime = System.currentTimeMillis();
  102. groupMsgDao = groupMessageDAO.insert(groupMsgBody);
  103. logger.debug("Save GroupMessageDao into DB. Message: {}. Dao: {}", JSON.toJSONString(groupMsgBody), JSON.toJSONString(groupMsgDao));
  104. dispatcher.dispatchToGroup(groupId, groupMsgBody);
  105. } else {
  106. logger.debug("Find existing GroupMessageDao for message: {}. Dao: {}", JSON.toJSONString(groupMsgBody), JSON.toJSONString(groupMsgDao));
  107. }
  108. sendSuccessResponse(userId, request, groupMsgDao);
  109. break;
  110. default:
  111. logger.error("Message type {} is not handled in SendMsgRequest. SendMsgRequest: {}", type.getValue(), json);
  112. throw new IMException("Unhandled MessageType " + type.getValue() + " for SendMsgCallback");
  113. }
  114. } catch (Exception e) {
  115. logger.error("Exception when handling SendMsgRequest.", e);
  116. sendFailResponse(userId, request, e.getMessage());
  117. }
  118. } catch (Exception e) {
  119. throw new IMConsumerException(e, json);
  120. }
  121. }
  122. private void sendSuccessResponse(String userId, SendMsgRequest request, SessionMessageEntity sessionEntity) {
  123. SendMsgResponse resp = new SendMsgResponse();
  124. resp.rId = request.rId;
  125. resp.msgRId = sessionEntity.RId;
  126. resp.userId = request.userId;
  127. resp.remoteId = request.remoteId;
  128. resp.groupId = request.groupId;
  129. resp.msgId = sessionEntity.MsgID;
  130. resp.sendTime = sessionEntity.SendTime;
  131. resp.type = request.type;
  132. resp.status = 200;
  133. outboxService.put(userId, resp.toWrapperJson());
  134. }
  135. private void sendSuccessResponse(String userId, SendMsgRequest request, GroupMessageEntity groupEntity) {
  136. SendMsgResponse resp = new SendMsgResponse();
  137. resp.rId = request.rId;
  138. resp.msgRId = groupEntity.RId;
  139. resp.userId = request.userId;
  140. resp.remoteId = request.remoteId;
  141. resp.groupId = request.groupId;
  142. resp.msgId = groupEntity.MsgID;
  143. resp.sendTime = groupEntity.SendTime;
  144. resp.type = request.type;
  145. resp.status = 200;
  146. outboxService.put(userId, resp.toWrapperJson());
  147. }
  148. private void sendFailResponse(String userId, SendMsgRequest request, String errMsg) {
  149. SendMsgResponse errResp = new SendMsgResponse();
  150. errResp.rId = request.rId;
  151. errResp.msgRId = request.msg.rId;
  152. errResp.userId = request.userId;
  153. errResp.remoteId = request.remoteId;
  154. errResp.groupId = request.groupId;
  155. errResp.type = request.type;
  156. errResp.status = 500;
  157. errResp.errMsg = errMsg;
  158. outboxService.put(userId, errResp.toWrapperJson());
  159. }
  160. }