This commit is contained in:
heavyrain.lee
2019-05-24 16:12:57 +08:00
parent 679e76a5f6
commit 3e1efe4c4c
19 changed files with 496 additions and 65 deletions
@@ -29,7 +29,7 @@ import win.liyufan.im.IMTopic;
import java.util.concurrent.Executor;
@Route(APIPath.Friend_Status)
@Route(APIPath.Friend_Update_Status)
@HttpMethod("POST")
public class FriendRelationAction extends AdminAction {
@@ -23,7 +23,7 @@ import io.netty.handler.codec.http.HttpResponseStatus;
import java.util.ArrayList;
import java.util.List;
@Route(APIPath.Friend_List)
@Route(APIPath.Friend_Get_List)
@HttpMethod("POST")
public class FriendRelationGetAction extends AdminAction {
@@ -37,7 +37,7 @@ public class GetUserAction extends AdminAction {
if (request.getNettyRequest() instanceof FullHttpRequest) {
InputGetUserInfo inputUserId = getRequestBody(request.getNettyRequest(), InputGetUserInfo.class);
if (inputUserId != null
&& (!StringUtil.isNullOrEmpty(inputUserId.getUserId()) || !StringUtil.isNullOrEmpty(inputUserId.getName()))) {
&& (!StringUtil.isNullOrEmpty(inputUserId.getUserId()) || !StringUtil.isNullOrEmpty(inputUserId.getName()) || !StringUtil.isNullOrEmpty(inputUserId.getMobile()))) {
WFCMessage.User user = null;
if(!StringUtil.isNullOrEmpty(inputUserId.getUserId())) {
@@ -9,6 +9,7 @@
package com.xiaoleilu.loServer.action.admin;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.pojos.OutputUserBlockStatusList;
import com.google.gson.Gson;
import com.xiaoleilu.loServer.RestResult;
import com.xiaoleilu.loServer.annotation.HttpMethod;
@@ -31,7 +32,9 @@ public class GetUserBlockListAction extends AdminAction {
public boolean action(Request request, Response response) {
if (request.getNettyRequest() instanceof FullHttpRequest) {
response.setStatus(HttpResponseStatus.OK);
RestResult result = RestResult.ok(messagesStore.getUserStatusList());
OutputUserBlockStatusList list = new OutputUserBlockStatusList();
list.setStatusList(messagesStore.getUserStatusList());
RestResult result = RestResult.ok(list);
response.setContent(new Gson().toJson(result));
}
return true;
@@ -13,9 +13,10 @@ public class InputGetUserInfo {
private String name;
private String mobile;
public InputGetUserInfo(String userId, String name) {
public InputGetUserInfo(String userId, String name, String mobile) {
this.userId = userId;
this.name = name;
this.mobile = mobile;
}
public String getMobile() {
@@ -19,8 +19,8 @@ public interface APIPath {
String User_Get_Online_Status = "/admin/user/onlinestatus";
String Friend_Status = "/admin/friend/status";
String Friend_List = "/admin/friend/list";
String Friend_Update_Status = "/admin/friend/status";
String Friend_Get_List = "/admin/friend/list";
String Msg_Send = "/admin/message/send";
String Msg_Recall = "/admin/message/recall";
@@ -33,7 +33,6 @@ public interface APIPath {
String Create_Robot = "/admin/robot/create";
String Channel_Message_Send = "/channel/message/send";
String Robot_User_Info = "/robot/user_info";
@@ -63,9 +63,11 @@ media.server.use_qiniu 0
#Media_Type_FAVORITE = 6
# qiniu media server configuration
## 上传地址,不同的区域,上传地址也不同,请注意现在正确的地址
qiniu.server_url http://up.qbox.me
qiniu.access_key tU3vdBK5BL5j4N7jI5N5uZgq_HQDo170w5C9Amnn
qiniu.secret_key YfQIJdgp5YGhwEw14vGpaD2HJZsuJldWtqens7i5
## bucket名字及Domain
qiniu.bucket_general_name media
qiniu.bucket_general_domain http://cdn.wildfirechat.cn
qiniu.bucket_image_name media
@@ -1,9 +1,19 @@
package cn.wildfirechat.sdk;
import cn.wildfirechat.sdk.utilities.HttpUtils;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
import cn.wildfirechat.sdk.utilities.ChannelHttpUtils;
import cn.wildfirechat.sdk.utilities.RobotHttpUtils;
public class ChatConfig {
public static void init(String url, String secret) {
HttpUtils.init(url, secret);
public static void initAdmin(String url, String secret) {
AdminHttpUtils.init(url, secret);
}
public static void initRobot(String url, String robotId, String secret) {
RobotHttpUtils.init(url, robotId, secret);
}
public static void initChannel(String url, String channelId, String secret) {
ChannelHttpUtils.init(url, channelId, secret);
}
}
@@ -0,0 +1,27 @@
package cn.wildfirechat.sdk;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
public class ChatroomAdmin {
public static IMResult<OutputCreateChatroom> createChatroom(InputCreateChatroom input) throws Exception {
String path = APIPath.Create_Chatroom;
return AdminHttpUtils.httpJsonPost(path, input, OutputCreateChatroom.class);
}
public static IMResult<Void> destroyChatroom(String chatroomId) throws Exception {
String path = APIPath.Chatroom_Destroy;
InputDestoryChatroom input = new InputDestoryChatroom();
input.setChatroomId(chatroomId);
return AdminHttpUtils.httpJsonPost(path, input, Void.class);
}
public static IMResult<OutputGetChatroomInfo> getChatroomInfo(String chatroomId) throws Exception {
String path = APIPath.Chatroom_Info;
InputGetChatroomInfo input = new InputGetChatroomInfo(chatroomId);
return AdminHttpUtils.httpJsonPost(path, input, OutputGetChatroomInfo.class);
}
}
@@ -0,0 +1,26 @@
package cn.wildfirechat.sdk;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
public class FriendAdmin {
public static IMResult<Void> updateFriendStatus(String userId, String targetId, int status) throws Exception {
String path = APIPath.Friend_Update_Status;
InputFriendRequest input = new InputFriendRequest();
input.setUserId(userId);
input.setFriendUid(targetId);
input.setStatus(status);
return AdminHttpUtils.httpJsonPost(path, input, Void.class);
}
public static IMResult<Void> getFriendStatusList(String userId, int status) throws Exception {
String path = APIPath.Friend_Get_List;
InputGetFriendList input = new InputGetFriendList();
input.setUserId(userId);
input.setStatus(0);
return AdminHttpUtils.httpJsonPost(path, input, Void.class);
}
}
@@ -3,7 +3,7 @@ package cn.wildfirechat.sdk;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.HttpUtils;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
import java.util.ArrayList;
import java.util.List;
@@ -20,7 +20,7 @@ public class GroupAdmin {
createGroup.setTo_lines(to_lines);
createGroup.setNotify_message(notify_message);
return HttpUtils.httpJsonPost(path, createGroup, OutputCreateGroupResult.class);
return AdminHttpUtils.httpJsonPost(path, createGroup, OutputCreateGroupResult.class);
}
public static IMResult<Void> dismissGroup(String operator, String groupId, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
@@ -30,7 +30,7 @@ public class GroupAdmin {
dismissGroup.setGroup_id(groupId);
dismissGroup.setTo_lines(to_lines);
dismissGroup.setNotify_message(notify_message);
return HttpUtils.httpJsonPost(path, dismissGroup, Void.class);
return AdminHttpUtils.httpJsonPost(path, dismissGroup, Void.class);
}
public static IMResult<Void> transferGroup(String operator, String groupId, String newOwner, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
@@ -40,7 +40,7 @@ public class GroupAdmin {
transferGroup.setNew_owner(newOwner);
transferGroup.setTo_lines(to_lines);
transferGroup.setNotify_message(notify_message);
return HttpUtils.httpJsonPost(path, transferGroup, Void.class);
return AdminHttpUtils.httpJsonPost(path, transferGroup, Void.class);
}
public static IMResult<Void> addGroupMembers(String operator, String groupId, List<String> groupMemberIds, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
@@ -56,7 +56,7 @@ public class GroupAdmin {
addGroupMember.setMembers(members);
addGroupMember.setTo_lines(to_lines);
addGroupMember.setNotify_message(notify_message);
return HttpUtils.httpJsonPost(path, addGroupMember, Void.class);
return AdminHttpUtils.httpJsonPost(path, addGroupMember, Void.class);
}
public static IMResult<Void> kickoffGroupMembers(String operator, String groupId, List<String> groupMemberIds, List<Integer> to_lines, MessagePayload notify_message) throws Exception {
@@ -66,7 +66,7 @@ public class GroupAdmin {
kickoffGroupMember.setMembers(groupMemberIds);
kickoffGroupMember.setTo_lines(to_lines);
kickoffGroupMember.setNotify_message(notify_message);
return HttpUtils.httpJsonPost(path, kickoffGroupMember, Void.class);
return AdminHttpUtils.httpJsonPost(path, kickoffGroupMember, Void.class);
}
}
@@ -0,0 +1,123 @@
package cn.wildfirechat.sdk;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
public class Main {
public static void main(String[] args) throws Exception {
AdminHttpUtils.init("http://localhost:18080", "123456");
InputOutputUserInfo userInfo = new InputOutputUserInfo();
userInfo.setUserId("userId1");
userInfo.setName("user1");
userInfo.setMobile("13900000000");
userInfo.setDisplayName("user 1");
IMResult<OutputCreateUser> resultCreateUser = UserAdmin.createUser(userInfo);
if (resultCreateUser != null && resultCreateUser.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("Create user " + resultCreateUser.getResult().getName() + " success");
} else {
System.out.println("Create user failure");
System.exit(-1);
}
IMResult<InputOutputUserInfo> resultGetUserInfo1 = UserAdmin.getUserByName(userInfo.getName());
if (resultGetUserInfo1 != null && resultGetUserInfo1.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
if (userInfo.getUserId().equals(resultGetUserInfo1.getResult().getUserId())
&& userInfo.getName().equals(resultGetUserInfo1.getResult().getName())
&& userInfo.getMobile().equals(resultGetUserInfo1.getResult().getMobile())
&& userInfo.getDisplayName().equals(resultGetUserInfo1.getResult().getDisplayName())) {
System.out.println("get user info success");
} else {
System.out.println("get user info by name failure");
System.exit(-1);
}
} else {
System.out.println("get user info by name failure");
System.exit(-1);
}
IMResult<InputOutputUserInfo> resultGetUserInfo2 = UserAdmin.getUserByMobile(userInfo.getMobile());
if (resultGetUserInfo2 != null && resultGetUserInfo2.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
if (userInfo.getUserId().equals(resultGetUserInfo2.getResult().getUserId())
&& userInfo.getName().equals(resultGetUserInfo2.getResult().getName())
&& userInfo.getMobile().equals(resultGetUserInfo2.getResult().getMobile())
&& userInfo.getDisplayName().equals(resultGetUserInfo2.getResult().getDisplayName())) {
System.out.println("get user info success");
} else {
System.out.println("get user info by mobile failure");
System.exit(-1);
}
} else {
System.out.println("get user info by mobile failure");
System.exit(-1);
}
IMResult<InputOutputUserInfo> resultGetUserInfo3 = UserAdmin.getUserByUserId(userInfo.getUserId());
if (resultGetUserInfo3 != null && resultGetUserInfo3.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
if (userInfo.getUserId().equals(resultGetUserInfo3.getResult().getUserId())
&& userInfo.getName().equals(resultGetUserInfo3.getResult().getName())
&& userInfo.getMobile().equals(resultGetUserInfo3.getResult().getMobile())
&& userInfo.getDisplayName().equals(resultGetUserInfo3.getResult().getDisplayName())) {
System.out.println("get user info success");
} else {
System.out.println("get user info by userId failure");
System.exit(-1);
}
} else {
System.out.println("get user info by userId failure");
System.exit(-1);
}
IMResult<OutputGetIMTokenData> resultGetToken = UserAdmin.getUserToken(userInfo.getUserId(), "client111");
if (resultGetToken != null && resultGetToken.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("get token success: " + resultGetToken.getResult().getToken());
} else {
System.out.println("get user token failure");
System.exit(-1);
}
IMResult<Void> resultVoid =UserAdmin.updateUserBlockStatus(userInfo.getUserId(), 1);
if (resultVoid != null && resultVoid.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
System.out.println("block user done");
} else {
System.out.println("block user failure");
System.exit(-1);
}
IMResult<OutputUserStatus> resultCheckUserStatus = UserAdmin.checkUserBlockStatus(userInfo.getUserId());
if (resultCheckUserStatus != null && resultCheckUserStatus.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
if (resultCheckUserStatus.getResult().getStatus() == 1) {
System.out.println("check user status success");
} else {
System.out.println("user status not correct");
System.exit(-1);
}
} else {
System.out.println("block user failure");
System.exit(-1);
}
IMResult<OutputUserBlockStatusList> resultBlockStatusList = UserAdmin.getBlockedList();
if (resultBlockStatusList != null && resultBlockStatusList.getErrorCode() == ErrorCode.ERROR_CODE_SUCCESS) {
boolean success = false;
for (InputOutputUserBlockStatus blockStatus : resultBlockStatusList.getResult().getStatusList()) {
if (blockStatus.getUserId().equals(userInfo.getUserId()) && blockStatus.getStatus() == 1) {
System.out.println("get block list done");
success = true;
break;
}
}
if (!success) {
System.out.println("block user status is not expected");
System.exit(-1);
}
} else {
System.out.println("block user failure");
System.exit(-1);
}
}
}
@@ -3,7 +3,7 @@ package cn.wildfirechat.sdk;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.HttpUtils;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
public class MessageAdmin {
public static IMResult<SendMessageResult> sendMessage(String sender, Conversation conversation, MessagePayload payload) throws Exception {
@@ -12,7 +12,7 @@ public class MessageAdmin {
messageData.setSender(sender);
messageData.setConv(conversation);
messageData.setPayload(payload);
return HttpUtils.httpJsonPost(path, messageData, SendMessageResult.class);
return AdminHttpUtils.httpJsonPost(path, messageData, SendMessageResult.class);
}
public static IMResult<Void> recallMessage(String operator, long messageUid) throws Exception {
@@ -20,6 +20,6 @@ public class MessageAdmin {
RecallMessageData messageData = new RecallMessageData();
messageData.setOperator(operator);
messageData.setMessageUid(messageUid);
return HttpUtils.httpJsonPost(path, messageData, Void.class);
return AdminHttpUtils.httpJsonPost(path, messageData, Void.class);
}
}
@@ -0,0 +1,30 @@
package cn.wildfirechat.sdk;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
import java.util.List;
public class SensitiveAdmin {
public static IMResult<Void> addSensitives(List<String> sensitives) throws Exception {
String path = APIPath.Sensitive_Add;
InputOutputSensitiveWords input = new InputOutputSensitiveWords();
input.setWords(sensitives);
return AdminHttpUtils.httpJsonPost(path, input, Void.class);
}
public static IMResult<Void> removeSensitives(List<String> sensitives) throws Exception {
String path = APIPath.Sensitive_Del;
InputOutputSensitiveWords input = new InputOutputSensitiveWords();
input.setWords(sensitives);
return AdminHttpUtils.httpJsonPost(path, input, Void.class);
}
public static IMResult<InputOutputSensitiveWords> getSensitives(List<String> sensitives) throws Exception {
String path = APIPath.Sensitive_Query;
return AdminHttpUtils.httpJsonPost(path, null, InputOutputSensitiveWords.class);
}
}
@@ -3,48 +3,60 @@ package cn.wildfirechat.sdk;
import cn.wildfirechat.common.APIPath;
import cn.wildfirechat.pojos.*;
import cn.wildfirechat.sdk.model.IMResult;
import cn.wildfirechat.sdk.utilities.HttpUtils;
import cn.wildfirechat.sdk.utilities.AdminHttpUtils;
public class UserAdmin {
public static IMResult<InputOutputUserInfo> getUserByName(String mobile) throws Exception {
public static IMResult<InputOutputUserInfo> getUserByName(String name) throws Exception {
String path = APIPath.User_Get_Info;
InputGetUserInfo getUserInfo = new InputGetUserInfo(null, mobile);
return HttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
InputGetUserInfo getUserInfo = new InputGetUserInfo(null, name, null);
return AdminHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
public static IMResult<InputOutputUserInfo> getUserByUserId(String userId) throws Exception {
String path = APIPath.User_Get_Info;
InputGetUserInfo getUserInfo = new InputGetUserInfo(userId, null, null);
return AdminHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
public static IMResult<InputOutputUserInfo> getUserByMobile(String mobile) throws Exception {
String path = APIPath.User_Get_Info;
InputGetUserInfo getUserInfo = new InputGetUserInfo(null, null, mobile);
return AdminHttpUtils.httpJsonPost(path, getUserInfo, InputOutputUserInfo.class);
}
public static IMResult<OutputCreateUser> createUser(InputOutputUserInfo user) throws Exception {
String path = APIPath.Create_User;
return HttpUtils.httpJsonPost(path, user, OutputCreateUser.class);
return AdminHttpUtils.httpJsonPost(path, user, OutputCreateUser.class);
}
public static IMResult<OutputGetIMTokenData> getUserToken(String userId, String clientId) throws Exception {
String path = APIPath.User_Get_Token;
InputGetToken getToken = new InputGetToken(userId, clientId);
return HttpUtils.httpJsonPost(path, getToken, OutputGetIMTokenData.class);
return AdminHttpUtils.httpJsonPost(path, getToken, OutputGetIMTokenData.class);
}
public static IMResult<Void> updateUserBlockStatus(String userId, int block) throws Exception {
String path = APIPath.User_Update_Block_Status;
InputOutputUserBlockStatus blockStatus = new InputOutputUserBlockStatus(userId, block);
return HttpUtils.httpJsonPost(path, blockStatus, Void.class);
return AdminHttpUtils.httpJsonPost(path, blockStatus, Void.class);
}
public static IMResult<OutputUserStatus> checkUserBlockStatus(String userId) throws Exception {
String path = APIPath.User_Update_Block_Status;
InputGetUserInfo getUserInfo = new InputGetUserInfo(userId, null);
return HttpUtils.httpJsonPost(path, getUserInfo, OutputUserStatus.class);
String path = APIPath.User_Check_Block_Status;
InputGetUserInfo getUserInfo = new InputGetUserInfo(userId, null, null);
return AdminHttpUtils.httpJsonPost(path, getUserInfo, OutputUserStatus.class);
}
public static IMResult<OutputUserBlockStatusList> getBlockedList() throws Exception {
String path = APIPath.User_Get_Blocked_List;
return HttpUtils.httpJsonPost(path, null, OutputUserBlockStatusList.class);
return AdminHttpUtils.httpJsonPost(path, null, OutputUserBlockStatusList.class);
}
//not implement
// public static IMResult<OutputUserBlockStatusList> getUserOnlineStatus(String userId) throws Exception {
// String path = APIPath.User_Get_Online_Status;
// InputGetUserInfo inputGetUserInfo = new InputGetUserInfo(userId, null);
// return HttpUtils.httpJsonPost(path, null, OutputUserBlockStatusList.class);
// return AdminHttpUtils.httpJsonPost(path, null, OutputUserBlockStatusList.class);
// }
@@ -1,30 +0,0 @@
package cn.wildfirechat.sdk.model;
public class SendMessageResult {
private long messageUid;
private long timestamp;
public SendMessageResult() {
}
public SendMessageResult(long messageUid, long timestamp) {
this.messageUid = messageUid;
this.timestamp = timestamp;
}
public long getMessageUid() {
return messageUid;
}
public void setMessageUid(long messageUid) {
this.messageUid = messageUid;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
}
@@ -19,8 +19,8 @@ import java.lang.reflect.Type;
import java.nio.charset.Charset;
public class HttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
public class AdminHttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(AdminHttpUtils.class);
private static String adminUrl;
private static String adminSecret;
@@ -54,7 +54,7 @@ public class HttpUtils {
post.setHeader("timestamp", "" + timestamp);
post.setHeader("sign", sign);
String jsonStr = null;
String jsonStr = "";
if (object != null) {
jsonStr = new Gson().toJson(object);
}
@@ -0,0 +1,114 @@
package cn.wildfirechat.sdk.utilities;
import cn.wildfirechat.sdk.model.IMResult;
import com.google.gson.Gson;
import ikidou.reflect.TypeBuilder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
public class ChannelHttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(ChannelHttpUtils.class);
private static String url;
private static String channelId;
private static String channelSecret;
public static void init(String url, String channelId, String secret) {
ChannelHttpUtils.url = url;
ChannelHttpUtils.channelId = channelId;
ChannelHttpUtils.channelSecret = secret;
}
public static <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception{
if (isNullOrEmpty(url) || isNullOrEmpty(path)) {
LOG.error("Not init IM SDK correctly. Do you forget init it?");
throw new Exception("SDK url or secret lack!");
}
String url = ChannelHttpUtils.url + path;
HttpPost post = null;
try {
HttpClient httpClient = HttpClientBuilder.create().build();
int nonce = (int)(Math.random() * 100000 + 3);
long timestamp = System.currentTimeMillis();
String str = nonce + "|" + channelSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(str);
post = new HttpPost(url);
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Keep-Alive");
post.setHeader("nonce", nonce + "");
post.setHeader("timestamp", "" + timestamp);
post.setHeader("sign", sign);
String jsonStr = null;
if (object != null) {
jsonStr = new Gson().toJson(object);
}
LOG.info("http request content: {}", jsonStr);
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: "+statusCode);
throw new Exception("Http request error with code:" + statusCode);
}else{
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String content = sb.toString();
LOG.info("http request response content: {}", content);
return fromJsonObject(content, clazz);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
if(post != null){
post.releaseConnection();
}
}
}
private static <T> IMResult<T> fromJsonObject(String content, Class<T> clazz) {
Type type = TypeBuilder
.newInstance(IMResult.class)
.addTypeParam(clazz)
.build();
return new Gson().fromJson(content, type);
}
private static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}
}
@@ -0,0 +1,114 @@
package cn.wildfirechat.sdk.utilities;
import cn.wildfirechat.sdk.model.IMResult;
import com.google.gson.Gson;
import ikidou.reflect.TypeBuilder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
public class RobotHttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(RobotHttpUtils.class);
private static String url;
private static String robotId;
private static String robotSecret;
public static void init(String url, String robotId, String secret) {
RobotHttpUtils.url = url;
RobotHttpUtils.robotId = robotId;
RobotHttpUtils.robotSecret = secret;
}
public static <T> IMResult<T> httpJsonPost(String path, Object object, Class<T> clazz) throws Exception{
if (isNullOrEmpty(url) || isNullOrEmpty(path)) {
LOG.error("Not init IM SDK correctly. Do you forget init it?");
throw new Exception("SDK url or secret lack!");
}
String url = RobotHttpUtils.url + path;
HttpPost post = null;
try {
HttpClient httpClient = HttpClientBuilder.create().build();
int nonce = (int)(Math.random() * 100000 + 3);
long timestamp = System.currentTimeMillis();
String str = nonce + "|" + robotSecret + "|" + timestamp;
String sign = DigestUtils.sha1Hex(str);
post = new HttpPost(url);
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Keep-Alive");
post.setHeader("nonce", nonce + "");
post.setHeader("timestamp", "" + timestamp);
post.setHeader("sign", sign);
String jsonStr = null;
if (object != null) {
jsonStr = new Gson().toJson(object);
}
LOG.info("http request content: {}", jsonStr);
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
LOG.info("Request error: "+statusCode);
throw new Exception("Http request error with code:" + statusCode);
}else{
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer();
String line;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String content = sb.toString();
LOG.info("http request response content: {}", content);
return fromJsonObject(content, clazz);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
if(post != null){
post.releaseConnection();
}
}
}
private static <T> IMResult<T> fromJsonObject(String content, Class<T> clazz) {
Type type = TypeBuilder
.newInstance(IMResult.class)
.addTypeParam(clazz)
.build();
return new Gson().fromJson(content, type);
}
private static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}
}