package com.shangyu.utils;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpDelete;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.methods.HttpPut;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

import org.json.JSONObject;

import com.shangyu.core.utils.PropertyUtils;


public class SysUserHuanXinService{

private static String tokenurl = PropertyUtils.getPropertyValue("shangyu.properties", "hx_tokenurl");

private static String userurl = PropertyUtils.getPropertyValue("shangyu.properties", "hx_userurl");

private static String client_id = PropertyUtils.getPropertyValue("shangyu.properties", "hx_client_id");

private static String client_secret = PropertyUtils.getPropertyValue("shangyu.properties", "hx_client_secret");

private static String grant_type = PropertyUtils.getPropertyValue("shangyu.properties", "hx_grant_type");

private static String charset = PropertyUtils.getPropertyValue("shangyu.properties", "charset");

private static String msgurl = PropertyUtils.getPropertyValue("shangyu.properties", "hx_messagesurl");

/**

* 添加所有用户带环信服务器

*/

/*public  void addUsers() {

Map<String, Object> param = new HashMap<String, Object>();

SysUserService sysuser = SpringContextHelper.getBean(SysUserService.class);

System.out.println(sysuser);

List<SysUser> userlist = sysuser.findByMap(param);

System.out.println(userlist.size()+"==========");

for (SysUser sue : userlist) {

suhs.addHuanXinUser(sue.getUid(), sue.getPlainPassword(), sue.getRealName());

}

}*/

/**

* @author hekang

* @return strtoken

* @throws ClientProtocolException

* @throws IOException

*/

public static String getToken() throws ClientProtocolException, IOException{

Map<String,String> createMap = new HashMap<String,String>();

        createMap.put("client_id", client_id);  

        createMap.put("client_secret", client_secret);  

        createMap.put("grant_type", grant_type); 

        HttpPost httpPost = new HttpPost(tokenurl); 

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();  

        nvps.add(new BasicNameValuePair("Content-Type", "application/json"));

        for(NameValuePair nameValuePair:nvps){

        httpPost.addHeader(nameValuePair.getName(), nameValuePair.getValue());

        }

        try {

httpPost.setEntity(new StringEntity(JsonUtils.pojo2json(createMap), charset));

} catch (Exception e) {

e.printStackTrace();

System.out.println(e.getMessage());

}

        HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);

        String retSrc = EntityUtils.toString(httpResponse.getEntity());

        JSONObject obj = new JSONObject(retSrc); 

        String strtoken = obj.get("access_token").toString();

return strtoken;

}

/**

* addHuanXinUser 

* 描述:添加环信用户信息

* @author hekang

* @param uid

* @param PlainPassword

* @param realName

*/

public void addHuanXinUser(String uid, String PlainPassword, String realName){

        Map<String,String> params = new HashMap<String,String>();

        params.put("username", uid);  

        params.put("password", PlainPassword);  

        params.put("nickname", realName); 

        HttpPost httpPost = new HttpPost(userurl);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();  

        nvps.add(new BasicNameValuePair("Content-Type", "application/json"));

        String token;

try {

token = getToken();

System.out.println("---token----"+token);

nvps.add(new BasicNameValuePair("Authorization", "Bearer "+token));

} catch (ClientProtocolException e) {

e.printStackTrace();

System.out.println("--ClientProtocolException--"+e.getMessage());

} catch (IOException e) {

e.printStackTrace();

System.out.println("--IOException--"+e.getMessage());

}

for(NameValuePair nameValuePair:nvps){

        httpPost.addHeader(nameValuePair.getName(), nameValuePair.getValue());

        }

        try {

        httpPost.setEntity(new StringEntity(JsonUtils.pojo2json(params),"utf-8"));

} catch (Exception e) {

e.printStackTrace();

}

        

        try {

HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);

if(httpResponse != null){

int statusCode = httpResponse.getStatusLine().getStatusCode();

if(statusCode == 200){

System.out.println("--add--");

}

}

String retSrc = EntityUtils.toString(httpResponse.getEntity());

System.out.println("---success---"+retSrc);

/*JSONObject json = new JSONObject(retSrc);

   if("duplicate_unique_property_exists".equals(json.get("error").toString())){

   System.out.println("---该用户已经存在---不允许再次添加-");

   }*/

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

        System.out.println("-----add---end---success---");

}

/**

* deleteByuid

* 描述:删除环信用户

* @author hekang

* @param uid

*/

public void deleteByuid(String uid){

String token;

HttpResponse httpResponse;


HttpDelete httpdelete = new HttpDelete(userurl+"/"+uid);

List<NameValuePair> nvps = new ArrayList<NameValuePair>();  

        nvps.add(new BasicNameValuePair("Content-Type", "application/json"));

try {

token = getToken();

nvps.add(new BasicNameValuePair("Authorization", "Bearer "+token));

} catch (ClientProtocolException e1) {

e1.printStackTrace();

} catch (IOException e1) {

e1.printStackTrace();

}

        for(NameValuePair nameValuePair:nvps){

        httpdelete.addHeader(nameValuePair.getName(), nameValuePair.getValue());

        }

        try {

httpResponse = new DefaultHttpClient().execute(httpdelete);

if(httpResponse != null){

int statusCode = httpResponse.getStatusLine().getStatusCode();

if(statusCode == 200){

System.out.println("--del--");

}

}

String retSrc = EntityUtils.toString(httpResponse.getEntity());

System.out.println("----success----"+retSrc);

/*JSONObject json = new JSONObject(retSrc);

if("service_resource_not_found".equals(json.get("error").toString())){

System.out.println("--环信服务器不存在该用户--");

}*/

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

        System.out.println("---del---end---success---");

}

/**

* put 

* 描述:更新环信昵称

* @author hekang

* @param uid

*/

public void putHuanXinUser(String uid,String password,String nickname){

System.out.println("--11uid--"+uid+"--password--"+password+"--nickname--"+nickname);

String token;

HttpPut httpput = new HttpPut(userurl+"/"+uid);

        Map<String,String> params = new HashMap<String,String>();

        //params.put("username", uid);

        if(!"".equals(password) && password != null){

        params.put("password", password);  

        }

        if(!"".equals(nickname)){

        params.put("nickname", nickname); 

        }

List<NameValuePair> nvps = new ArrayList<NameValuePair>();  

   nvps.add(new BasicNameValuePair("Content-Type", "application/json"));

try {

token = getToken();

nvps.add(new BasicNameValuePair("Authorization", "Bearer "+token));

} catch (ClientProtocolException e) {

e.printStackTrace();

System.out.println("--ClientProtocolException--"+e.getMessage());

} catch (IOException e) {

e.printStackTrace();

System.out.println("--IOException--"+e.getMessage());

}

for(NameValuePair nameValuePair:nvps){

httpput.addHeader(nameValuePair.getName(), nameValuePair.getValue());

        }

DefaultHttpClient client = new DefaultHttpClient();

try {

httpput.setEntity(new StringEntity(JsonUtils.pojo2json(params),"utf-8"));

HttpResponse response = client.execute(httpput);

if(response != null){

int statusCode = response.getStatusLine().getStatusCode();

if(statusCode == 200){

System.out.println("--put--");

}

}

String retSrc = EntityUtils.toString(response.getEntity());

System.out.println("---success---"+retSrc);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}


/**

* get 

* 描述:获取单个环信用户信息

* @author hekang

* @param uid

* 获取单个用户信息

*/

public void getHuanXinUser(String uid){

String token;

HttpResponse httpResponse;

HttpGet httpGet = new HttpGet(userurl+"/"+uid);

List<NameValuePair> nvps = new ArrayList<NameValuePair>();  

        nvps.add(new BasicNameValuePair("Content-Type", "application/json"));

try {

token = getToken();

nvps.add(new BasicNameValuePair("Authorization", "Bearer "+token));

} catch (ClientProtocolException e1) {

e1.printStackTrace();

} catch (IOException e1) {

e1.printStackTrace();

}

        for(NameValuePair nameValuePair:nvps){

        httpGet.addHeader(nameValuePair.getName(), nameValuePair.getValue());

        }

        try {

httpResponse = new DefaultHttpClient().execute(httpGet);

if(httpResponse != null){

int statusCode = httpResponse.getStatusLine().getStatusCode();

if(statusCode == 200){

System.out.println("--get--");

}

}

String retSrc = EntityUtils.toString(httpResponse.getEntity());

System.out.println("----success----"+retSrc);

/*JSONObject json = new JSONObject(retSrc);

if("service_resource_not_found".equals(json.get("error").toString())){

System.out.println("--环信服务器不存在该用户--");

}*/

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* @author hekang

* 获取该app下的所有环信用户

*/

public String getAllHuanXinUsers(){

String token;

HttpResponse httpResponse;

BufferedReader in = null;  

String content = null; 

HttpGet httpGet = new HttpGet(userurl);

List<NameValuePair> nvps = new ArrayList<NameValuePair>();  

        nvps.add(new BasicNameValuePair("Content-Type", "application/json"));

try {

token = getToken();

nvps.add(new BasicNameValuePair("Authorization", "Bearer "+token));

} catch (ClientProtocolException e1) {

e1.printStackTrace();

} catch (IOException e1) {

e1.printStackTrace();

}

        for(NameValuePair nameValuePair:nvps){

        httpGet.addHeader(nameValuePair.getName(), nameValuePair.getValue());

        }

        try {

httpResponse = new DefaultHttpClient().execute(httpGet);

in = new BufferedReader(new InputStreamReader(httpResponse.getEntity()  

.getContent()));

StringBuffer sb = new StringBuffer("");  

String line = "";  

String NL = System.getProperty("line.separator");  

while ((line = in.readLine()) != null) {  

                sb.append(line + NL);  

            } 

in.close();

content = sb.toString();  

System.out.println("---allusers---"+content);

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally {  

            if (in != null) {  

                try {  

                    in.close();// 最后要关闭BufferedReader  

                } catch (Exception e) {  

                    e.printStackTrace();  

                }  

            }  

        }

return content;  

}

/**

   * @Title: addMessages

   * @Description: 发送消息

   * @param     参数

   * @return void    返回类型

   * @throws

*/

public static void addMessages(String msg, String[] newUserIds, String userid){

Map<String, Object> param = new HashMap<String, Object>();

String result = null;

// 创建默认的httpClient实例.

CloseableHttpClient httpclient = HttpClients.createDefault(); 

//创建httpPost

HttpPost httpPost = new HttpPost(msgurl);

try {

//String[] userArr = new String[]{"4028803557ad88a10157ada6bdb4001f","4028803557ad88a10157ada73ac40020","4028803557ad88a10157ad9d44130013"};

Map<String, Object> msgmap = new HashMap<String, Object>();

msgmap.put("type", "txt");

msgmap.put("msg", msg);

//msgmap.put("msg", "hello from rest! 道路比较滑,注意安全!");

param.put("target_type", "users");//users 给用户发消息。chatgroups: 给群发消息,chatrooms: 给聊天室发消息

param.put("from", userid);//表示消息发送者。无此字段Server会默认设置为"from":"admin",有from字段但值为空串("")时请求失败

param.put("target", newUserIds);//接收人数组,数组长度建议不大于20

param.put("msg", msgmap);//消息类型及文本

httpPost.addHeader("Content-Type", "application/json");

httpPost.addHeader("Authorization", "Bearer "+getToken().toString());

httpPost.setEntity(new StringEntity(JsonUtils.pojo2json(param), charset));

CloseableHttpResponse httpResponse = httpclient.execute(httpPost);

try {

if(httpResponse.getStatusLine().getStatusCode() == 200){

System.out.println("--addmessges--success");

}

HttpEntity entity = httpResponse.getEntity();

if(entity != null){

result = EntityUtils.toString(entity, charset);

}

} finally {

httpResponse.close();

}

} catch (Exception e) {

e.printStackTrace();

}finally {

// 关闭连接,释放资源

try {

httpclient.close();

} catch (IOException e) {

}

}

System.out.println("---result---"+result);

}

public static void main(String[] args) {

SysUserHuanXinService sys = new SysUserHuanXinService();

//sys.putHuanXinUser("12", "1234567890", "admin");

//sys.addMessages("hello ", args, "12");

}

}


注释:

配置文件:shangyu.properties

#huanxin_message

hx_client_id=YXA75UxWkI34Eea-M5V9ogKt0Q

hx_client_secret=YXA7ahOOOn95cT-LC0_jvc5qisc9LKU

hx_grant_type=client_credentials

hx_tokenurl=https://a1.easemob.com/97501822/officeautomationsyste/token

hx_userurl=https://a1.easemob.com/97501822/officeautomationsyste/users

hx_messagesurl=https://a1.easemob.com/97501822/officeautomationsyste/messages

charset=UTF-8

apply_admin=sykjapplay0101


请假通知与审批提醒:


//环信申请通知

private static String apply_admin = PropertyUtils.getPropertyValue("shangyu.properties", "apply_admin");

String[] newUserIds = new String[]{auditor};

if(StringUtils.isEmpty(apply_admin)){

apply_admin = session.getUserId();

}

SysUserHuanXinService.addMessages("请假申请", newUserIds, apply_admin);//申请


//公告通知

String[] userId = entity.getNotifyUsers();//获取选中的所有接受通知的人

String userIdsString = userId[0];

String[] userIds = userIdsString.split(",");

List<String> userIdList = new ArrayList<String>();

for (int i = 0; i < userIds.length; i++) {

if (userIds[i].indexOf("user") >= 0) {

String newUserId = userIds[i].substring(userIds[i].indexOf("|") + 1, userIds[i].length());

userIdList.add(newUserId);

}

}

String[] newUserIds = new String[userIdList.size()];

userIdList.toArray(newUserIds);//集合转数组(并且指定数组类型)

//newUserIds = userIdList.toArray(newUserIds);

SysUserHuanXinService.addMessages(entity.getContent(), newUserIds, admin.getUser().getUid());//newUserIds必须是数组


使用到的工具类有:--------JsonUtils工具类----------


    package com.shangyu.utils;

    import java.util.HashMap;

    import java.util.Iterator;

    import java.util.List;

    import java.util.Map;

    import org.json.JSONObject;

    import net.minidev.json.JSONArray;

    import net.minidev.json.JSONValue;

    public class JsonUtils {

    public static String pojo2json(Object pojo){

    String jsonStr = JSONValue.toJSONString(pojo);

    return jsonStr;

    }

    

    /**

     * json

     * @param json

     * @return

     */

    public static Object json2pojo(String json){

    Object obj = null;

    try {

    obj = JSONValue.parse(json);

    } catch (Exception e) {

    e.printStackTrace();

    }

    return obj;

    }

    /**

     * list

     * @param <T>

     * @param list

     * @return

     */

    public static <T> String list2json(List<T> list){

            String jsonStr = JSONValue.toJSONString(list);

    return jsonStr;

    }

    /**

     * json

     * @param json

     * @return

     */

    public static List json2list(String json){

    Object obj=JSONValue.parse(json);

            JSONArray array=(JSONArray)obj;

    return array;

    }

    

    public static Map jsonToObject(String jsonStr) throws Exception {

    JSONObject jsonObj = new JSONObject(jsonStr);

    Iterator<String> nameItr = jsonObj.keys();

    String name;

    Map<String, String> outMap = new HashMap<String, String>();

    while (nameItr.hasNext()) {

    name = nameItr.next();

    outMap.put(name, jsonObj.getString(name));

    }

    return outMap;

    }

    }



//-------------------PropertyUtils工具类------------------------------

package com.shangyu.core.utils;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Enumeration;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Properties;

import java.util.Set;

import java.util.TreeSet;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.BeanFactoryAware;

import org.springframework.util.ResourceUtils;


/**

 * @ClassName: PropertyUtils

 * @Description: TODO(属性操作工具类)

 * @author xiaowei

 * @date 2014年10月16日 下午3:29:00

 * 

 */

public class PropertyUtils implements BeanFactoryAware {


public List<String> getList(String prefix) {

if (properties == null || prefix == null) {

return Collections.emptyList();

}

List<String> list = new ArrayList<String>();

Enumeration<?> en = properties.propertyNames();

String key;

while (en.hasMoreElements()) {

key = (String) en.nextElement();

if (key.startsWith(prefix)) {

list.add(properties.getProperty(key));

}

}

return list;

}


public Set<String> getSet(String prefix) {

if (properties == null || prefix == null) {

return Collections.emptySet();

}

Set<String> set = new TreeSet<String>();

Enumeration<?> en = properties.propertyNames();

String key;

while (en.hasMoreElements()) {

key = (String) en.nextElement();

if (key.startsWith(prefix)) {

set.add(properties.getProperty(key));

}

}

return set;

}


public Map<String, String> getMap(String prefix) {

if (properties == null || prefix == null) {

return Collections.emptyMap();

}

Map<String, String> map = new HashMap<String, String>();

Enumeration<?> en = properties.propertyNames();

String key;

int len = prefix.length();

while (en.hasMoreElements()) {

key = (String) en.nextElement();

if (key.startsWith(prefix)) {

map.put(key.substring(len), properties.getProperty(key));

}

}

return map;

}


public Properties getProperties(String prefix) {

Properties props = new Properties();

if (properties == null || prefix == null) {

return props;

}

Enumeration<?> en = properties.propertyNames();

String key;

int len = prefix.length();

while (en.hasMoreElements()) {

key = (String) en.nextElement();

if (key.startsWith(prefix)) {

props.put(key.substring(len), properties.getProperty(key));

}

}

return props;

}


public String getPropertiesString(String prefix) {

String property = "";

if (properties == null || prefix == null) {

return property;

}

Enumeration<?> en = properties.propertyNames();

String key;

while (en.hasMoreElements()) {

key = (String) en.nextElement();

if (key.equals(prefix)) {

return properties.getProperty(key);

}

}

return property;

}


public Map<String, Object> getBeanMap(String prefix) {

Map<String, String> keyMap = getMap(prefix);

if (keyMap.isEmpty()) {

return Collections.emptyMap();

}

Map<String, Object> resultMap = new HashMap<String, Object>(keyMap.size());

String key, value;

for (Map.Entry<String, String> entry : keyMap.entrySet()) {

key = entry.getKey();

value = entry.getValue();

resultMap.put(key, beanFactory.getBean(value, Object.class));

}

return resultMap;

}


public static Properties getProperties(File file) {

Properties props = new Properties();

InputStream in;

try {

in = new FileInputStream(file);

props.load(in);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return props;

}


public static String getPropertyValue(String filename, String key) {

File resource;

try {

resource = ResourceUtils.getFile("classpath:config/"+filename);

Properties props = getProperties(resource);

return (String) props.get(key);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

return null;

}


private BeanFactory beanFactory;

private Properties properties;


public void setProperties(Properties properties) {

this.properties = properties;

}


public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

this.beanFactory = beanFactory;

}


}