`
Jo_Vigoss
  • 浏览: 6934 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用环信给App推送Push消息

    博客分类:
  • Java
阅读更多
import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jx.lcs.common.huanxin.Constants;
import com.jx.lcs.common.huanxin.HTTPMethod;
import com.jx.lcs.common.huanxin.Roles;
import com.jx.lcs.common.huanxin.httpclient.HTTPClientUtils;
import com.jx.lcs.common.huanxin.vo.ClientSecretCredential;
import com.jx.lcs.common.huanxin.vo.Credential;
import com.jx.lcs.common.huanxin.vo.EndPoints;

/**
* REST API Demo: 发送消息 REST API HttpClient4.3实现
*/
public class EasemobMessages {

private static Logger LOGGER = LoggerFactory.getLogger(EasemobMessages.class);
    private static final String APPKEY = Constants.APPKEY;
    private static JsonNodeFactory factory = new JsonNodeFactory(false);

    // 通过app的client_id和client_secret来获取app管理员token
    private static Credential credential = new ClientSecretCredential(Constants.APP_CLIENT_ID,
            Constants.APP_CLIENT_SECRET, Roles.USER_ROLE_APPADMIN);
   
    //发送消息到单个用户
    public static void sendMsgToUser(String fromUid, String toUid, String content) {
    // 给用户发一条文本消息
        String from = fromUid;
        String targetTypeus = "users";
        ObjectNode ext = factory.objectNode();
        ArrayNode targetusers = factory.arrayNode();
        targetusers.add(toUid);
        ObjectNode txtmsg = factory.objectNode();
        txtmsg.put("msg", content);
        txtmsg.put("type","txt");
        ObjectNode sendTxtMessageusernode = sendMessages(targetTypeus, targetusers, txtmsg, from, ext);
        if (null != sendTxtMessageusernode) {
            LOGGER.info("给" + toUid + "发一条文本消息: " + sendTxtMessageusernode.toString());
        }
    }

    public static void main(String[] args) {
   
    /**
         * 注册IM用户[单个]
         */
        ObjectNode datanode = JsonNodeFactory.instance.objectNode();
        datanode.put("username","test");
        datanode.put("password", Constants.DEFAULT_PASSWORD);
        ObjectNode createNewIMUserSingleNode = createNewIMUserSingle(datanode);
        if (null != createNewIMUserSingleNode) {
            LOGGER.info("注册IM用户[单个]: " + createNewIMUserSingleNode.toString());
        }
       
        //  检测用户是否在线
//        String targetuserPrimaryKey = "683697";
//        ObjectNode usernode = getUserStatus(targetuserPrimaryKey);
//        if (null != usernode) {
//            LOGGER.info("检测用户是否在线: " + usernode.toString());
//        }

        // 给用户发一条文本消息
        /*
        String from = "jiayy01";
        String targetTypeus = "users";
        ObjectNode ext = factory.objectNode();
        ArrayNode targetusers = factory.arrayNode();
        targetusers.add("683697");
//        targetusers.add("lurong02");
        ObjectNode txtmsg = factory.objectNode();
        txtmsg.put("msg", "Apple Watch! 嘎嘎 嘎嘎 嘎嘎 嘎嘎!!!");
        txtmsg.put("type","txt");
        ObjectNode sendTxtMessageusernode = sendMessages(targetTypeus, targetusers, txtmsg, from, ext);
        if (null != sendTxtMessageusernode) {
            LOGGER.info("给用户发一条文本消息: " + sendTxtMessageusernode.toString());
        }
        */
       
       
        /*
        // 给一个群组发文本消息
        String targetTypegr = "chatgroups";
        ArrayNode  chatgroupidsNode = (ArrayNode) EasemobChatGroups.getAllChatgroupids().path("data");
        ArrayNode targetgroup = factory.arrayNode();
        targetgroup.add(chatgroupidsNode.get(0).path("groupid").asText());
        ObjectNode sendTxtMessagegroupnode = sendMessages(targetTypegr, targetgroup, txtmsg, from, ext);
        if (null != sendTxtMessagegroupnode) {
            LOGGER.info("给一个群组发文本消息: " + sendTxtMessagegroupnode.toString());
        }

        // 给用户发一条图片消息
        File uploadImgFile = new File("/home/lynch/Pictures/24849.jpg");
        ObjectNode imgDataNode = EasemobFiles.mediaUpload(uploadImgFile);
        String imgFileUUID = imgDataNode.path("entities").get(0).path("uuid").asText();
        String shareSecret = imgDataNode.path("entities").get(0).path("share-secret").asText();
        if (null != imgDataNode) {
            LOGGER.info("上传图片文件: " + imgDataNode.toString());
        }
        ObjectNode imgmsg = factory.objectNode();
        imgmsg.put("type","img");
        imgmsg.put("url", HTTPClientUtils.getURL(Constants.APPKEY.replace("#", "/") + "/chatfiles/" + imgFileUUID).toString());
        imgmsg.put("filename", "24849.jpg");
        imgmsg.put("length", 10);
        imgmsg.put("secret", shareSecret);
        ObjectNode sendimgMessageusernode = sendMessages(targetTypeus, targetusers, imgmsg, from, ext);
        if (null != sendimgMessageusernode) {
            LOGGER.info("给一个群组发文本消息: " + sendimgMessageusernode.toString());
        }
        // 给一个群组发图片消息
        ObjectNode sendimgMessagegroupnode = sendMessages(targetTypegr, targetgroup, imgmsg, from, ext);
        if (null != sendimgMessagegroupnode) {
            LOGGER.info("给一个群组发文本消息: " + sendimgMessagegroupnode.toString());
        }

        // 给用户发一条语音消息
        File uploadAudioFile = new File("/home/lynch/Music/music.MP3");
        ObjectNode audioDataNode = EasemobFiles.mediaUpload(uploadAudioFile);
        String audioFileUUID = audioDataNode.path("entities").get(0).path("uuid").asText();
        String audioFileShareSecret = audioDataNode.path("entities").get(0).path("share-secret").asText();
        if (null != audioDataNode) {
            LOGGER.info("上传语音文件: " + audioDataNode.toString());
        }
        ObjectNode audiomsg = factory.objectNode();
        audiomsg.put("type","audio");
        audiomsg.put("url", HTTPClientUtils.getURL(Constants.APPKEY.replace("#", "/") + "/chatfiles/" + audioFileUUID).toString());
        audiomsg.put("filename", "music.MP3");
        audiomsg.put("length", 10);
        audiomsg.put("secret", audioFileShareSecret);
        ObjectNode sendaudioMessageusernode = sendMessages(targetTypeus, targetusers, audiomsg, from, ext);
        if (null != sendaudioMessageusernode) {
            LOGGER.info("给用户发一条语音消息: " + sendaudioMessageusernode.toString());
        }

        // 给一个群组发语音消息
        ObjectNode sendaudioMessagegroupnode = sendMessages(targetTypegr, targetgroup, audiomsg, from, ext);
        if (null != sendaudioMessagegroupnode) {
            LOGGER.info("给一个群组发语音消息: " + sendaudioMessagegroupnode.toString());
        }

        // 给用户发一条透传消息
        ObjectNode cmdmsg = factory.objectNode();
        cmdmsg.put("action", "gogogo");
        cmdmsg.put("type","cmd");
        ObjectNode sendcmdMessageusernode = sendMessages(targetTypeus, targetusers, cmdmsg, from, ext);
        if (null != sendcmdMessageusernode) {
            LOGGER.info("给用户发一条透传消息: " + sendcmdMessageusernode.toString());
        }
        */
    }

/**
* 检测用户是否在线
*
* @param username
     *
* @return
*/
public static ObjectNode getUserStatus(String username) {
ObjectNode objectNode = factory.objectNode();

// check appKey format
if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
LOGGER.error("Bad format of Appkey: " + APPKEY);
objectNode.put("message", "Bad format of Appkey");
return objectNode;
}

// check properties that must be provided
if (StringUtils.isEmpty(username)) {
LOGGER.error("You must provided a targetUserPrimaryKey .");
objectNode.put("message", "You must provided a targetUserPrimaryKey .");
return objectNode;
}

try {
URL userStatusUrl = HTTPClientUtils.getURL(Constants.APPKEY.replace("#", "/") + "/users/"
+ username + "/status");
objectNode = HTTPClientUtils.sendHTTPRequest(userStatusUrl, credential, null, HTTPMethod.METHOD_GET);
String userStatus = objectNode.get("data").path(username).asText();
if ("online".equals(userStatus)) {
LOGGER.error(String.format("The status of user[%s] is : [%s] .", username, userStatus));
} else if ("offline".equals(userStatus)) {
LOGGER.error(String.format("The status of user[%s] is : [%s] .", username, userStatus));
}
} catch (Exception e) {
e.printStackTrace();
}

return objectNode;
}

/**
* 发送消息
*
* @param targetType
*            消息投递者类型:users 用户, chatgroups 群组
* @param target
*            接收者ID 必须是数组,数组元素为用户ID或者群组ID
* @param msg
*            消息内容
* @param from
*            发送者
* @param ext
*            扩展字段
*
* @return 请求响应
*/
public static ObjectNode sendMessages(String targetType, ArrayNode target, ObjectNode msg, String from,
ObjectNode ext) {

ObjectNode objectNode = factory.objectNode();

ObjectNode dataNode = factory.objectNode();

// check appKey format
if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", APPKEY)) {
LOGGER.error("Bad format of Appkey: " + APPKEY);

objectNode.put("message", "Bad format of Appkey");

return objectNode;
}

// check properties that must be provided
if (!("users".equals(targetType) || "chatgroups".equals(targetType))) {
LOGGER.error("TargetType must be users or chatgroups .");

objectNode.put("message", "TargetType must be users or chatgroups .");

return objectNode;
}

try {
// 构造消息体
dataNode.put("target_type", targetType);
dataNode.put("target", target);
dataNode.put("msg", msg);
dataNode.put("from", from);
dataNode.put("ext", ext);

objectNode = HTTPClientUtils.sendHTTPRequest(EndPoints.MESSAGES_URL, credential, dataNode,
HTTPMethod.METHOD_POST);

objectNode = (ObjectNode) objectNode.get("data");
for (int i = 0; i < target.size(); i++) {
String resultStr = objectNode.path(target.path(i).asText()).asText();
if ("success".equals(resultStr)) {
LOGGER.error(String.format("Message has been send to user[%s] successfully .", target.path(i)
.asText()));
} else if (!"success".equals(resultStr)) {
LOGGER.error(String.format("Message has been send to user[%s] failed .", target.path(i).asText()));
}
}

} catch (Exception e) {
e.printStackTrace();
}

return objectNode;
}

/**
* 注册IM用户[单个]
*
* 给指定Constants.APPKEY创建一个新的用户
*
* @param dataNode
* @return
*/
public static ObjectNode createNewIMUserSingle(ObjectNode dataNode) {

ObjectNode objectNode = factory.objectNode();

// check Constants.APPKEY format
if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", Constants.APPKEY)) {
LOGGER.error("Bad format of Constants.APPKEY: " + Constants.APPKEY);

objectNode.put("message", "Bad format of Constants.APPKEY");

return objectNode;
}

objectNode.removeAll();

// check properties that must be provided
if (null != dataNode && !dataNode.has("username")) {
LOGGER.error("Property that named username must be provided .");

objectNode.put("message", "Property that named username must be provided .");

return objectNode;
}
if (null != dataNode && !dataNode.has("password")) {
LOGGER.error("Property that named password must be provided .");

objectNode.put("message", "Property that named password must be provided .");

return objectNode;
}

try {

    objectNode = HTTPClientUtils.sendHTTPRequest(EndPoints.USERS_URL, credential, dataNode,
HTTPMethod.METHOD_POST);

} catch (Exception e) {
e.printStackTrace();
}

return objectNode;
}

/**
* 注册IM用户[批量]
*
* 给指定Constants.APPKEY创建一批用户
*
* @param dataArrayNode
* @return
*/
public static ObjectNode createNewIMUserBatch(ArrayNode dataArrayNode) {

ObjectNode objectNode = factory.objectNode();

// check Constants.APPKEY format
if (!HTTPClientUtils.match("^(?!-)[0-9a-zA-Z\\-]+#[0-9a-zA-Z]+", Constants.APPKEY)) {
LOGGER.error("Bad format of Constants.APPKEY: " + Constants.APPKEY);

objectNode.put("message", "Bad format of Constants.APPKEY");

return objectNode;
}

// check properties that must be provided
if (dataArrayNode.isArray()) {
for (JsonNode jsonNode : dataArrayNode) {
if (null != jsonNode && !jsonNode.has("username")) {
LOGGER.error("Property that named username must be provided .");

objectNode.put("message", "Property that named username must be provided .");

return objectNode;
}
if (null != jsonNode && !jsonNode.has("password")) {
LOGGER.error("Property that named password must be provided .");

objectNode.put("message", "Property that named password must be provided .");

return objectNode;
}
}
}

try {

objectNode = HTTPClientUtils.sendHTTPRequest(EndPoints.USERS_URL, credential, dataArrayNode,
HTTPMethod.METHOD_POST);

} catch (Exception e) {
e.printStackTrace();
}

return objectNode;
}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics