Java钉钉开发_03_通讯录管理之 人员管理 和 部门管理

本文涉及的产品
全局流量管理 GTM,标准版 1个月
云解析 DNS,旗舰版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
简介: 一、本节要点 1.通讯录权限 ISV(应用服务商)默认无管理通讯录的权限,企业应用默认有所有通讯录权限。   2.数据传输格式—JSON 请参见: Java_数据交换_fastJSON_01_用法入门   二、代码实现 1.

一、本节要点

1.通讯录权限

ISV(应用服务商)默认无管理通讯录的权限,企业应用默认有所有通讯录权限。

 

2.数据传输格式—JSON

请参见: Java_数据交换_fastJSON_01_用法入门

 

二、代码实现

1.HTTP请求工具类—HttpHelper

package com.ray.dingtalk.qy.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


/**
 * HTTP请求封装,建议直接使用sdk的API
 */
public class HttpHelper {
    private static final Logger log = LogManager.getLogger(HttpHelper.class);
    
    
    /**
     * @desc :1.发起GET请求
     *  
     * @param url
     * @return JSONObject
     * @throws Exception 
     */
    public static JSONObject doGet(String url) throws Exception {

        //1.生成一个请求
        HttpGet httpGet = new HttpGet(url);
        //2.配置请求的属性
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//2000
        httpGet.setConfig(requestConfig);

        //3.发起请求,获取响应信息    
        //3.1 创建httpClient 
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //3.2 发起请求,获取响应信息    
            response = httpClient.execute(httpGet, new BasicHttpContext());

            //如果返回结果的code不等于200,说明出错了  
            if (response.getStatusLine().getStatusCode() != 200) {

                log.info("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }
            //4.解析请求结果
            HttpEntity entity = response.getEntity();      //reponse返回的数据在entity中 
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");  //将数据转化为string格式  
                log.info("GET请求结果:"+resultStr);
                JSONObject result = JSON.parseObject(resultStr);    //将String转换为 JSONObject

                if(result.getInteger("errcode")==null) {
                    return result;
                }else if (0 == result.getInteger("errcode")) {
                    return result;
                }else {
                    log.info("request url=" + url + ",return value=");
                    log.info(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:"+errCode+", error message:"+errMsg); 
                }
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();                     //释放资源

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

        return null;
    }


    /** 2.发起POST请求
     * @desc :
     *  
     * @param url   请求url
     * @param data  请求参数(json)
     * @return
     * @throws Exception JSONObject
     */
    public static JSONObject doPost(String url, Object data) throws Exception {
        //1.生成一个请求
        HttpPost httpPost = new HttpPost(url);

        //2.配置请求属性
        //2.1 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        //2.2 设置数据传输格式-json
        httpPost.addHeader("Content-Type", "application/json");
        //2.3 设置请求实体,封装了请求参数
        StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
        httpPost.setEntity(requestEntity);

        //3.发起请求,获取响应信息    
        //3.1 创建httpClient 
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {


            //3.3 发起请求,获取响应
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                log.info("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }

            //获取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                log.info("POST请求结果:"+resultStr);

                //解析响应内容
                JSONObject result = JSON.parseObject(resultStr);

                if(result.getInteger("errcode")==null) {
                    return result;
                }else if (0 == result.getInteger("errcode")) {
                    return result;
                }else {
                    log.info("request url=" + url + ",return value=");
                    log.info(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:"+errCode+", error message:"+errMsg); 
                }
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();              //释放资源

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

        return null;
    }


/**
 * @desc : 3.
 *   
 * @param url
 * @param file
 * @return
 * @throws Exception 
 *   JSONObject
 */
    public static JSONObject uploadMedia(String url, File file) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);

        HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("media",
                new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.getName())).build();
        httpPost.setEntity(requestEntity);

        try {
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                log.info("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                JSONObject result = JSON.parseObject(resultStr);
                if (result.getInteger("errcode") == 0) {
                    // 成功
                    //result.remove("errcode");
                    //result.remove("errmsg");
                    return result;
                } else {
                    log.info("request url=" + url + ",return value=");
                    log.info(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:"+errCode+", error message:"+errMsg); 
                }
            }
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();                  //释放资源
                
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    public static File downloadMedia(String url, String fileDir) throws Exception  {
        //1.生成一个请求
        HttpGet httpGet = new HttpGet(url);
        //2.配置请求属性
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpGet.setConfig(requestConfig);

        //3.发起请求,获取响应信息    
        //3.1 创建httpClient 
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        
        //4.设置本地保存的文件  
        File file = new File(fileDir);
        
        try {
            //5. 发起请求,获取响应信息    
            response = httpClient.execute(httpGet, new BasicHttpContext());
            log.info("HttpStatus.SC_OK:"+HttpStatus.SC_OK);  
            log.info("response.getStatusLine().getStatusCode():"+response.getStatusLine().getStatusCode());  

            //请求成功  
            if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){  
                
                //6.取得请求内容  
                HttpEntity entity = response.getEntity();  

                if (entity != null) {  
                    //这里可以得到文件的类型 如image/jpg /zip /tiff 等等 但是发现并不是十分有效,有时明明后缀是.rar但是取到的是null,这点特别说明  
                    log.info(entity.getContentType());  
                    //可以判断是否是文件数据流  
                    log.info(entity.isStreaming());  
                    
                    //6.1 输出流
                    FileOutputStream output = new FileOutputStream(file);  
                    //6.2 输入流:从钉钉服务器返回的文件流,得到网络资源并写入文件  
                    InputStream input = entity.getContent();  
                    
                    //6.3 将数据写入文件:将输入流中的数据写入到输出流
                    byte b[] = new byte[1024];  
                    int j = 0;  
                    while( (j = input.read(b))!=-1){  
                        output.write(b,0,j);  
                    }  
                    output.flush();  
                    output.close();   
                }  
                if (entity != null) {  
                    entity.consumeContent();  
                }  
            }  
        } catch (IOException e) {
            log.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();                       //释放资源
                
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return file;
    }

    

}
View Code

 

2.Token工具类—AuthHelper

package com.ray.dingtalk.qy.auth;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.ray.dingtalk.qy.config.Env;
import com.ray.dingtalk.qy.util.HttpHelper;



/**
 * 钉钉相关配置参数的获取工具类
 * @desc  : AccessToken和jsticket的获取封装
 * 
 * @author: shirayner
 * @date  : 2017年9月27日 下午5:00:25
 */
public class AuthHelper {
    //private static Logger log = LoggerFactory.getLogger(AuthHelper.class);  
    //获取access_token的接口地址,有效期为7200秒
    private static final String GET_ACCESSTOKEN_URL="https://oapi.dingtalk.com/gettoken?corpid=CORPID&corpsecret=CORPSECRET"; 

    //获取getJsapiTicket的接口地址,有效期为7200秒 
    private static final String GET_JSAPITICKET_URL="https://oapi.dingtalk.com/get_jsapi_ticket?access_token=ACCESSTOKE"; 


    /** 1.获取access_token 
     * @desc : 
     *  
     * @param corpId
     * @param corpSecret
     * @return
     * @throws Exception String
     */
    public static String getAccessToken(String corpId,String corpSecret) throws Exception {
        //1.获取请求url
        String url=GET_ACCESSTOKEN_URL.replace("CORPID", corpId).replace("CORPSECRET", corpSecret);

        //2.发起GET请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doGet(url);

        //3.解析结果,获取accessToken
        String accessToken="";  
        if (null != jsonObject) {  
            accessToken=jsonObject.getString("access_token");

            //4.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }  


        return accessToken;
    }

    /**
     * 2、获取JSTicket, 用于js的签名计算
     * 正常的情况下,jsapi_ticket的有效期为7200秒,所以开发者需要在某个地方设计一个定时器,定期去更新jsapi_ticket
     * @throws Exception 
     */
    public static String getJsapiTicket(String accessToken) throws Exception  {
        //1.获取请求url
        String url=GET_JSAPITICKET_URL.replace("ACCESSTOKE", accessToken);

        //2.发起GET请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doGet(url);

        //3.解析结果,获取ticket
        String ticket="";  
        if (null != jsonObject) {  
            ticket=jsonObject.getString("ticket");

            //4.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }  

        return ticket;
    }


    /**
     * @desc : 3.生成签名的函数 
     *  
     * @param ticket jsticket
     * @param nonceStr 随机串,自己定义
     * @param timeStamp 生成签名用的时间戳 
     * @param url 需要进行免登鉴权的页面地址,也就是执行dd.config的页面地址 
     * @return
     * @throws Exception String
     */
    
    public static String getSign(String jsTicket, String nonceStr, Long timeStamp, String url) throws Exception {  
        String plainTex = "jsapi_ticket=" + jsTicket + "&noncestr=" + nonceStr + "&timestamp=" + timeStamp + "&url=" + url;
        System.out.println(plainTex);
        try {  
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(plainTex.getBytes("UTF-8"));
            return byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception(e.getMessage());  
        } catch (UnsupportedEncodingException e) {  
            throw new Exception(e.getMessage());  
        }  
    }  

    //将bytes类型的数据转化为16进制类型  
    private static String byteToHex(byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", new Object[] { Byte.valueOf(b) });
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    
    


    /**
     * @desc :获取前端jsapi需要的配置参数(已弃用,请用getConfig(HttpServletRequest))
     *  
     * @param request      request:在钉钉中点击微应用图标跳转的url地址 
     * @return Map<String,Object>  将需要的参数存入map,并返回
     */
    public static Map<String, Object> getDDConfig(HttpServletRequest request){  

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

        //1.准备好参与签名的字段
        /* 
         *以http://localhost/test.do?a=b&c=d为例 
         *request.getRequestURL的结果是http://localhost/test.do 
         *request.getQueryString的返回值是a=b&c=d 
         */  
        String urlString = request.getRequestURL().toString();
        String queryString = request.getQueryString();

        String queryStringEncode = null;
        String url;
        if (queryString != null) {
            queryStringEncode = URLDecoder.decode(queryString);
            url = urlString + "?" + queryStringEncode;
        } else {
            url = urlString;
        }


        String nonceStr=UUID.randomUUID().toString();      //随机数
        long timeStamp = System.currentTimeMillis() / 1000;     //时间戳参数  

        String signedUrl = url;
        String accessToken = null;
        String ticket = null;
        String signature = null;       //签名

        //2.进行签名,获取signature
        try {  
            accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);  

            ticket=AuthHelper.getJsapiTicket(accessToken);  
            signature=getSign(ticket,nonceStr,timeStamp,signedUrl);  


        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  

        System.out.println("accessToken:"+accessToken);
        System.out.println("ticket:"+ticket);
        System.out.println("nonceStr:"+nonceStr);
        System.out.println("timeStamp:"+timeStamp);
        System.out.println("signedUrl:"+signedUrl);
        System.out.println("signature:"+signature);
        System.out.println("agentId:"+Env.AGENTID);
        System.out.println("corpId:"+Env.CORP_ID);
        
        
        
        //3.将配置参数存入Map
        configMap.put("agentId", Env.AGENTID);
        configMap.put("corpId", Env.CORP_ID);
        configMap.put("timeStamp", timeStamp);
        configMap.put("nonceStr", nonceStr);
        configMap.put("signature", signature);

        return configMap;  
    }  

    public static String getConfig(HttpServletRequest request){  

        //1.准备好参与签名的字段
        /* 
         *以http://localhost/test.do?a=b&c=d为例 
         *request.getRequestURL的结果是http://localhost/test.do 
         *request.getQueryString的返回值是a=b&c=d 
         */  
        String urlString = request.getRequestURL().toString();
        String queryString = request.getQueryString();

        String queryStringEncode = null;
        String url;
        if (queryString != null) {
            queryStringEncode = URLDecoder.decode(queryString);
            url = urlString + "?" + queryStringEncode;
        } else {
            url = urlString;
        }


        String nonceStr=UUID.randomUUID().toString();      //随机数
        long timeStamp = System.currentTimeMillis() / 1000;     //时间戳参数  

        String signedUrl = url;
        String accessToken = null;
        String ticket = null;
        String signature = null;       //签名

        //2.进行签名,获取signature
        try {  
            accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);  

            ticket=AuthHelper.getJsapiTicket(accessToken);  
            signature=getSign(ticket,nonceStr,timeStamp,signedUrl);  


        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  

        System.out.println("accessToken:"+accessToken);
        System.out.println("ticket:"+ticket);
        System.out.println("nonceStr:"+nonceStr);
        System.out.println("timeStamp:"+timeStamp);
        System.out.println("signedUrl:"+signedUrl);
        System.out.println("signature:"+signature);
        System.out.println("agentId:"+Env.AGENTID);
        System.out.println("corpId:"+Env.CORP_ID);
        
        
        
           String configValue = "{jsticket:'" + ticket + "',signature:'" + signature + "',nonceStr:'" + nonceStr + "',timeStamp:'"
                    + timeStamp + "',corpId:'" + Env.CORP_ID + "',agentId:'" + Env.AGENTID + "'}";
            System.out.println(configValue);

        return configValue;  
    }  
    
}
View Code

 

3.成员实体类—User

package com.ray.dingtalk.qy.model.contact;

import java.util.List;

import com.alibaba.fastjson.JSONObject;

/**@desc  : 用户类
 * 
 * @author: shirayner
 * @date  : 2017年9月28日 上午9:38:25
 */
public class User {

    public String userid;
    public String name;     //必须  
    public boolean active;
    public String avatar;
    public List<Long> department;    //必须
    public String position;
    public String mobile;            //必须
    public String tel;
    public String workPlace;
    public String remark;
    public String email;
    public String jobnumber;
    public JSONObject extattr;
    public boolean isAdmin;
    public boolean isBoss;
    public String dingId;
    
    /**
     * @return the userid
     */
    public String getUserid() {
        return userid;
    }
    /**
     * @param userid the userid to set
     */
    public void setUserid(String userid) {
        this.userid = userid;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the active
     */
    public boolean isActive() {
        return active;
    }
    /**
     * @param active the active to set
     */
    public void setActive(boolean active) {
        this.active = active;
    }
    /**
     * @return the avatar
     */
    public String getAvatar() {
        return avatar;
    }
    /**
     * @param avatar the avatar to set
     */
    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }
    /**
     * @return the department
     */
    public List<Long> getDepartment() {
        return department;
    }
    /**
     * @param department the department to set
     */
    public void setDepartment(List<Long> department) {
        this.department = department;
    }
    /**
     * @return the position
     */
    public String getPosition() {
        return position;
    }
    /**
     * @param position the position to set
     */
    public void setPosition(String position) {
        this.position = position;
    }
    /**
     * @return the mobile
     */
    public String getMobile() {
        return mobile;
    }
    /**
     * @param mobile the mobile to set
     */
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    /**
     * @return the tel
     */
    public String getTel() {
        return tel;
    }
    /**
     * @param tel the tel to set
     */
    public void setTel(String tel) {
        this.tel = tel;
    }
    /**
     * @return the workPlace
     */
    public String getWorkPlace() {
        return workPlace;
    }
    /**
     * @param workPlace the workPlace to set
     */
    public void setWorkPlace(String workPlace) {
        this.workPlace = workPlace;
    }
    /**
     * @return the remark
     */
    public String getRemark() {
        return remark;
    }
    /**
     * @param remark the remark to set
     */
    public void setRemark(String remark) {
        this.remark = remark;
    }
    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }
    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }
    /**
     * @return the jobnumber
     */
    public String getJobnumber() {
        return jobnumber;
    }
    /**
     * @param jobnumber the jobnumber to set
     */
    public void setJobnumber(String jobnumber) {
        this.jobnumber = jobnumber;
    }
    /**
     * @return the extattr
     */
    public JSONObject getExtattr() {
        return extattr;
    }
    /**
     * @param extattr the extattr to set
     */
    public void setExtattr(JSONObject extattr) {
        this.extattr = extattr;
    }
    /**
     * @return the isAdmin
     */
    public boolean isAdmin() {
        return isAdmin;
    }
    /**
     * @param isAdmin the isAdmin to set
     */
    public void setAdmin(boolean isAdmin) {
        this.isAdmin = isAdmin;
    }
    /**
     * @return the isBoss
     */
    public boolean isBoss() {
        return isBoss;
    }
    /**
     * @param isBoss the isBoss to set
     */
    public void setBoss(boolean isBoss) {
        this.isBoss = isBoss;
    }
    /**
     * @return the dingId
     */
    public String getDingId() {
        return dingId;
    }
    /**
     * @param dingId the dingId to set
     */
    public void setDingId(String dingId) {
        this.dingId = dingId;
    }
    
    @Override
    public String toString() {
        return "User[userid:" + userid + ", name:" + name + ", active:" + active + ", "
                + "avatar:" + avatar + ", department:" + department +
                ", position:" + position + ", mobile:" + mobile + ", email:" + email + 
                ", extattr:" + extattr;
    }
    
}
View Code

 

4.部门实体类—Department

package com.ray.dingtalk.qy.model.contact;

/**@desc  : 
 * 
 * @author: shirayner
 * @date  : 2017年10月18日 下午2:14:20
 */
public class Department {
    //部门id
    private long id;
    //是    部门名称。长度限制为1~64个字符。不允许包含字符‘-’‘,’以及‘,’。
    private String name;
    //是    父部门id。根部门id为1
    private String parentid;
    //否    在父部门中的次序值。order值小的排序靠前
    private String order;
    //否    是否创建一个关联此部门的企业群,默认为false
    private Boolean createDeptGroup;
    
    
    //否    是否隐藏部门, true表示隐藏, false表示显示
    private Boolean deptHiding;
    //否    可以查看指定隐藏部门的其他部门列表,如果部门隐藏,则此值生效,
    //取值为其他的部门id组成的的字符串,使用 | 符号进行分割。总数不能超过200。
    private String deptPerimits;
    //否    可以查看指定隐藏部门的其他人员列表,如果部门隐藏,则此值生效,取值为其他的人员userid组成的的字符串,
    //使用| 符号进行分割。总数不能超过200。
    private String userPerimits;
    //否    是否本部门的员工仅可见员工自己, 为true时,本部门员工默认只能看到员工自己
    private Boolean outerDept;
    //否    本部门的员工仅可见员工自己为true时,可以配置额外可见部门,值为部门id组成的的字符串,
    //使用|符号进行分割。总数不能超过200。
    private String outerPermitDepts;
    //否    本部门的员工仅可见员工自己为true时,可以配置额外可见人员,值为userid组成的的字符串,
    //使用|符号进行分割。总数不能超过200。
    private String outerPermitUsers;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getParentid() {
        return parentid;
    }
    public void setParentid(String parentid) {
        this.parentid = parentid;
    }
    public String getOrder() {
        return order;
    }
    public void setOrder(String order) {
        this.order = order;
    }
    public Boolean getCreateDeptGroup() {
        return createDeptGroup;
    }
    public void setCreateDeptGroup(Boolean createDeptGroup) {
        this.createDeptGroup = createDeptGroup;
    }
    public Boolean getDeptHiding() {
        return deptHiding;
    }
    public void setDeptHiding(Boolean deptHiding) {
        this.deptHiding = deptHiding;
    }
    public String getDeptPerimits() {
        return deptPerimits;
    }
    public void setDeptPerimits(String deptPerimits) {
        this.deptPerimits = deptPerimits;
    }
    public String getUserPerimits() {
        return userPerimits;
    }
    public void setUserPerimits(String userPerimits) {
        this.userPerimits = userPerimits;
    }
    public Boolean getOuterDept() {
        return outerDept;
    }
    public void setOuterDept(Boolean outerDept) {
        this.outerDept = outerDept;
    }
    public String getOuterPermitDepts() {
        return outerPermitDepts;
    }
    public void setOuterPermitDepts(String outerPermitDepts) {
        this.outerPermitDepts = outerPermitDepts;
    }
    public String getOuterPermitUsers() {
        return outerPermitUsers;
    }
    public void setOuterPermitUsers(String outerPermitUsers) {
        this.outerPermitUsers = outerPermitUsers;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }



}
View Code

 

5.成员管理业务类—UserService

package com.ray.dingtalk.qy.service.contact;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ray.dingtalk.qy.model.contact.User;
import com.ray.dingtalk.qy.util.HttpHelper;

/**@desc  : 成员管理业务类
 * 
 * @author: shirayner
 * @date  : 2017年9月28日 上午9:53:51
 */
public class UserService {
    //1.获取成员详情 接口
    private static final String GET_USER_URL="https://oapi.dingtalk.com/user/get?access_token=ACCESS_TOKEN&userid=ID";
    //2.创建成员 接口
    private static final String CREATE_USER_URL="https://oapi.dingtalk.com/user/create?access_token=ACCESS_TOKEN";
    //3.更新成员
    private static final String UPDATE_USER_URL="https://oapi.dingtalk.com/user/update?access_token=ACCESS_TOKEN";
    //4.删除成员
    private static final String DELETE_USER_URL="https://oapi.dingtalk.com/user/delete?access_token=ACCESS_TOKEN&userid=ID";
    //5.批量删除成员
    private static final String BATCHDELETE_USER_URL="https://oapi.dingtalk.com/user/batchdelete?access_token=ACCESS_TOKEN";
    //6.获取部门成员(simplelist)
    private static final String LIST_DEPARTMENTUSER_URL="https://oapi.dingtalk.com/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENTID";
    //7.获取部门成员(详情)
    private static final String LIST_DEPARTMENTUSERDETAIL_URL="https://oapi.dingtalk.com/user/list?access_token=ACCESS_TOKEN&department_id=DEPARTMENTID";
    //8.获取管理员列表
    private static final String LIST_ADMIN_URL="https://oapi.dingtalk.com/user/get_admin?access_token=ACCESS_TOKEN";
    //9.根据unionid获取成员的userid
    private static final String GET_USERID_BYUNIONID_URL="https://oapi.dingtalk.com/user/getUseridByUnionid?access_token=ACCESS_TOKEN&unionid=UNIONID";
    //10.通过CODE换取用户身份
    private static final String GET_USERINFO_BYCODE_URL="https://oapi.dingtalk.com/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE";

    /** 1.根据userid获取成员详情
     * @desc :获取成员详情
     *   参考文档: https://open-doc.dingtalk.com/docs/doc.htm?spm=0.0.0.0.jjSfQQ&treeId=371&articleId=106816&docType=1#s0
     * @param accessToken
     * @param userId 
     * return JSONObject  返回用户详情
     * @throws Exception 
     */
    public JSONObject getUser(String accessToken, String userId) throws Exception {

        //1.获取请求url
        String url=GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", userId);

        //2.发起GET请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doGet(url);
        System.out.println("jsonObject:"+jsonObject.toString());
        //3.解析结果,获取User
        if (null != jsonObject) {  
            
            //4.请求成功,则返回jsonObject
              if (0==jsonObject.getInteger("errcode")) {
                  return jsonObject;
              }
              
              //5.错误消息处理
              if (0 != jsonObject.getInteger("errcode")) {  
                  int errCode = jsonObject.getInteger("errcode");
                  String errMsg = jsonObject.getString("errmsg");
                  throw new Exception("error code:"+errCode+", error message:"+errMsg); 
              }  
            
        }   

        return null;
    }



    /**2.创建成员
     * @desc :
     *  
     * @param accessToken
     * @param user
     * @return  返回用户id
     * @throws Exception String
     */
    public String createUser(String accessToken,User user) throws Exception {
        //1.准备POST请求参数
        Object data=JSON.toJSON(user);
        System.out.println(data);

        //2.获取请求url
        String url=CREATE_USER_URL.replace("ACCESS_TOKEN", accessToken);

        //3.发起POST请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doPost(url, data);
        System.out.println("jsonObject:"+jsonObject.toString());

        //4.解析结果,获取UserId
        String userId="";
        if (null != jsonObject) {  
            userId=jsonObject.getString("userid");
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

        return userId;
    }


    /**3.更新成员
     * @desc :
     *  参数说明(如果非必须的字段未指定,则钉钉后台不改变该字段之前设置好的值)
     * @param accessToken
     * @param user
     * @return
     * @throws Exception String
     */
    public void updateUser(String accessToken,User user) throws Exception {
        //1.准备POST请求参数
        Object data=JSON.toJSON(user);
        System.out.println(data);

        //2.获取请求url
        String url=UPDATE_USER_URL.replace("ACCESS_TOKEN", accessToken);

        //3.发起POST请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doPost(url, data);
        System.out.println("jsonObject:"+jsonObject.toString());

        //4.解析结果
        if (null != jsonObject) {  

            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

    }

    /** 4.删除成员
     *
     * @param accessToken
     * @param userId void
     * @throws Exception 
     */
    public JSONObject deleteUser(String accessToken, String userId) throws Exception {

        //1.获取请求url
        String url=DELETE_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", userId);

        //2.发起GET请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doGet(url);
        System.out.println("jsonObject:"+jsonObject.toString());
        //3.解析结果,获取User
        if (null != jsonObject) {  
            //4.请求成功,则返回jsonObject
            if (0==jsonObject.getInteger("errcode")) {
                return jsonObject;
            }
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

        return null;
    }


    /** 5.批量删除成员
     * @desc :
     *  
     * @param accessToken
     * @param user
     * @throws Exception void
     */
    public void batchDeleteUser(String accessToken,Map< String , List<String> > userIdlistMap) throws Exception {
        //1.准备POST请求参数
        Object data=JSON.toJSON(userIdlistMap);
        System.out.println(data);

        //2.获取请求url
        String url=BATCHDELETE_USER_URL.replace("ACCESS_TOKEN", accessToken);

        //3.发起POST请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doPost(url, data);
        System.out.println("jsonObject:"+jsonObject.toString());

        //4.解析结果
        if (null != jsonObject) {  

            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

    }



    /** 6.获取部门成员(simplelist)
     * @desc :
     *  
     * @param accessToken
     * @param departmentId
     * return userList 用户列表
     * @throws Exception void
     */
    public JSONObject listDepartmentUser(String accessToken, String departmentId) throws Exception {

        //1.获取请求url
        String url=LIST_DEPARTMENTUSER_URL.replace("ACCESS_TOKEN", accessToken).replace("DEPARTMENTID", departmentId);

        //2.发起GET请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doGet(url);
        System.out.println("jsonObject:"+jsonObject.toString());


        //3.解析结果,获取User
        if (null != jsonObject) {  
            //4.请求成功,则返回jsonObject
              if (0==jsonObject.getInteger("errcode")) {
                  return jsonObject;
              }
              
            
            
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   
        
        return null;
    }



    /** 7.获取部门成员(详情)
     * @desc :
     *  
     * @param accessToken
     * @param departmentId
     * return userList 用户列表
     * @throws Exception void
     */
    public JSONObject listDepartmentUserDetail(String accessToken, String departmentId) throws Exception {

        //1.获取请求url
        String url=LIST_DEPARTMENTUSERDETAIL_URL.replace("ACCESS_TOKEN", accessToken).replace("DEPARTMENTID", departmentId);

        //2.发起GET请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doGet(url);
        System.out.println("jsonObject:"+jsonObject.toString());
        
    
        //3.解析结果,获取User
        if (null != jsonObject) {  
            //4.请求成功,则返回jsonObject
              if (0==jsonObject.getInteger("errcode")) {
                  return jsonObject;
              }
            
            //4.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }  
        
        return null;
    }

    /**8.获取管理员列表
     * @desc :
     *  
     * @param accessToken
     * @return adminList  管理员列表
     * @throws Exception JSONObject
     */
    public JSONObject listAdmin(String accessToken) throws Exception {

        //1.获取请求url
        String url=LIST_ADMIN_URL.replace("ACCESS_TOKEN", accessToken);

        //2.发起GET请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doGet(url);
        System.out.println("jsonObject:"+jsonObject.toString());


        //3.解析结果,获取adminList
        if (null != jsonObject) {  
            //4.请求成功,则返回jsonObject
              if (0==jsonObject.getInteger("errcode")) {
                  return jsonObject;
              }
              
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

        return null;
    }

    /** 9.根据unionid获取成员的userid
     * @desc :
     *  
     * @param accessToken
     * @param unionId
     * @return  用户id
     * @throws Exception JSONObject
     */
    public String getUserIdByUnionId(String accessToken, String unionId) throws Exception {

        //1.获取请求url
        String url=GET_USERID_BYUNIONID_URL.replace("ACCESS_TOKEN", accessToken).replace("UNIONID", unionId);

        //2.发起GET请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doGet(url);
        System.out.println("jsonObject:"+jsonObject.toString());
        //3.解析结果,获取User
        if (null != jsonObject) {  
            //4.请求成功,则返回jsonObject
            if (0==jsonObject.getInteger("errcode")) {
                return jsonObject.getString("userid");
            }
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

        return null;
    }


    /** 10.通过CODE换取用户身份
     * @desc :钉钉服务器返回的用户信息为:
     * userid    员工在企业内的UserID
     * deviceId    手机设备号,由钉钉在安装时随机产生
     * is_sys    是否是管理员
     * sys_level    级别,0:非管理员 1:超级管理员(主管理员) 2:普通管理员(子管理员) 100:老板
     *  
     * @param accessToken
     * @param code
     * @throws Exception void
     */
    public JSONObject getUserInfo(String accessToken,String code) throws Exception {

        //1.获取请求url
        String url=GET_USERINFO_BYCODE_URL.replace("ACCESS_TOKEN", accessToken).replace("CODE", code);

        //2.发起GET请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doGet(url);
        System.out.println("jsonObject:"+jsonObject.toString());

        //3.解析结果,获取User
        if (null != jsonObject) {  
            //4.请求成功,则返回jsonObject
            if (0==jsonObject.getInteger("errcode")) {
                return jsonObject;
            }
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

        return null;
    }



}
View Code

 

6.部门管理业务类—DepartmentServcie

package com.ray.dingtalk.qy.service.contact;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ray.dingtalk.qy.model.contact.Department;
import com.ray.dingtalk.qy.util.HttpHelper;

/**@desc  : 部门管理业务类
 * 
 * @author: shirayner
 * @date  : 2017年10月18日 下午12:39:21
 */
public class DepartmentServcie {
    //1.获取部门列表
    private static final String LIST_DEPARTMENT_URL="https://oapi.dingtalk.com/department/list?access_token=ACCESS_TOKEN&id=ID";
    //2.获取部门详情
    private static final String GET_DEPARTMENTDETAIL_URL="https://oapi.dingtalk.com/department/get?access_token=ACCESS_TOKEN&id=ID";
    //3.创建部门
    private static final String CREATE_DEPARTMENT_URL="https://oapi.dingtalk.com/department/create?access_token=ACCESS_TOKEN";
    //4.更新部门
    private static final String UPDATE_DEPARTMENT_URL="https://oapi.dingtalk.com/department/update?access_token=ACCESS_TOKEN";
    //5.删除部门
    private static final String DELETE_DEPARTMENT_URL="https://oapi.dingtalk.com/department/delete?access_token=ACCESS_TOKEN&id=ID";
    //6.查询部门的所有上级父部门路径
    private static final String LIST_PARENTDEPTS_BYDEPT_URL="https://oapi.dingtalk.com/department/list_parent_depts_by_dept?access_token=ACCESS_TOKEN&id=ID";
    //7.查询指定用户的所有上级父部门路径
    private static final String LIST_PARENTDEPTS_BYUSER_URL="https://oapi.dingtalk.com/department/list_parent_depts?access_token=ACCESS_TOKEN&userId=USERID";

    
    

    /** 1.获取部门列表
     * @desc :获取指定部门下的部门列表
     *  
     * @param accessToken
     * @param departementId 父部门id
     * @return
     * @throws Exception JSONObject
     */
    public JSONObject listDepartment(String accessToken,String departmentId) throws Exception {
        //1.准备请求url
        String url=LIST_DEPARTMENT_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", departmentId);

        //2.调用接口,发送请求
        JSONObject jsonObject=HttpHelper.doGet(url);
        System.out.println(jsonObject);

        //3.解析请求结果
        if (null != jsonObject) {  
            //4.请求成功,则返回jsonObject
            if (0==jsonObject.getInteger("errcode")) {
                return jsonObject;
            }
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

        return null;
    }

    /** 2.获取部门详情
     * @desc :
     *  
     * @param accessToken
     * @param departementId 部门id
     * @return
     * @throws Exception JSONObject
     */
    public JSONObject getDepartmentDetail(String accessToken,String departmentId) throws Exception {
        //1.准备请求url
        String url=GET_DEPARTMENTDETAIL_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", departmentId);

        //2.调用接口,发送请求
        JSONObject jsonObject=HttpHelper.doGet(url);
        System.out.println(jsonObject);

        //3.解析请求结果
        if (null != jsonObject) {  
            //4.请求成功,则返回jsonObject
            if (0==jsonObject.getInteger("errcode")) {
                return jsonObject;
            }
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

        return null;
    }


    /** 3.创建部门
     * @desc :
     *  
     * @param accessToken
     * @param department
     * @return
     * @throws Exception String
     */
    public String createDepartment(String accessToken,Department department) throws Exception {
        //1.准备POST请求参数
        Object data=JSON.toJSON(department);
        System.out.println(data);

        //2.获取请求url
        String url=CREATE_DEPARTMENT_URL.replace("ACCESS_TOKEN", accessToken);

        //3.发起POST请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doPost(url, data);
        System.out.println("jsonObject:"+jsonObject.toString());

        //4.解析结果,获取UserId
        String departmentId="";
        if (null != jsonObject) {  
            departmentId=jsonObject.getString("id");
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

        return departmentId;
    }


    /** 4.更新部门
     * @desc :
     *  
     * @param accessToken
     * @param department    其中id是必须的
     * @return
     * @throws Exception String
     */
    public void updateDepartment(String accessToken,Department department) throws Exception {
        //1.准备POST请求参数
        Object data=JSON.toJSON(department);
        System.out.println(data);

        //2.获取请求url
        String url=UPDATE_DEPARTMENT_URL.replace("ACCESS_TOKEN", accessToken);

        //3.发起POST请求,获取返回结果
        JSONObject jsonObject=HttpHelper.doPost(url, data);
        System.out.println("jsonObject:"+jsonObject.toString());

        //4.解析结果
        if (null != jsonObject) {  
            //5.错误消息处理
            if (0 != jsonObject.getInteger("errcode")) {  
                int errCode = jsonObject.getInteger("errcode");
                String errMsg = jsonObject.getString("errmsg");
                throw new Exception("error code:"+errCode+", error message:"+errMsg); 
            }  
        }   

    }

    /**5.删除部门
     * @desc :
     *  
     * @param accessToken
     * @param departmentId
     * @throws Exception void
     */
      public void deleteDepartment(String accessToken,String departmentId) throws Exception {
        //1.准备请求url
          String url=DELETE_DEPARTMENT_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", departmentId);

          //2.调用接口,发送请求
          JSONObject jsonObject=HttpHelper.doGet(url);
          System.out.println(jsonObject);

          //3.解析请求结果
          if (null != jsonObject) {  
          
              //5.错误消息处理
              if (0 != jsonObject.getInteger("errcode")) {  
                  int errCode = jsonObject.getInteger("errcode");
                  String errMsg = jsonObject.getString("errmsg");
                  throw new Exception("error code:"+errCode+", error message:"+errMsg); 
              }  
          }   

      
      }

      /** 6.查询部门的所有上级父部门路径
       * @desc :
       *  返回的结果按顺序依次为其所有父部门的ID,直到根部门
       * @param accessToken
       * @param departementId 部门id
       * @return
       * @throws Exception JSONObject
       */
      public JSONObject listParentDepartementsByDept(String accessToken,String departmentId) throws Exception {
          //1.准备请求url
          String url=LIST_PARENTDEPTS_BYDEPT_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", departmentId);

          //2.调用接口,发送请求
          JSONObject jsonObject=HttpHelper.doGet(url);
          System.out.println(jsonObject);

          //3.解析请求结果
          if (null != jsonObject) {  
              //4.请求成功,则返回jsonObject
              if (0==jsonObject.getInteger("errcode")) {
                  return jsonObject;
              }
              //5.错误消息处理
              if (0 != jsonObject.getInteger("errcode")) {  
                  int errCode = jsonObject.getInteger("errcode");
                  String errMsg = jsonObject.getString("errmsg");
                  throw new Exception("error code:"+errCode+", error message:"+errMsg); 
              }  
          }   

          return null;
      }
      
      
      /** 7.查询指定用户的所有上级父部门路径
       * @desc :
       *  返回的结果按顺序依次为其所有父部门的ID,直到根部门
       * @param accessToken
       * @param departementId 部门id
       * @return
       * @throws Exception JSONObject
       */
      public JSONObject listParentDepartementsByUser(String accessToken,String userID) throws Exception {
          //1.准备请求url
          String url=LIST_PARENTDEPTS_BYUSER_URL.replace("ACCESS_TOKEN", accessToken).replace("USERID", userID);
          
          //2.调用接口,发送请求
          JSONObject jsonObject=HttpHelper.doGet(url);
          System.out.println(jsonObject);
          
          //3.解析请求结果
          if (null != jsonObject) {  
              //4.请求成功,则返回jsonObject
              if (0==jsonObject.getInteger("errcode")) {
                  return jsonObject;
              }
              //5.错误消息处理
              if (0 != jsonObject.getInteger("errcode")) {  
                  int errCode = jsonObject.getInteger("errcode");
                  String errMsg = jsonObject.getString("errmsg");
                  throw new Exception("error code:"+errCode+", error message:"+errMsg); 
              }  
          }   
          
          return null;
      }

      
      
      
      
}
View Code

 

7.成员管理测试类—UserServiceTest

package com.ray.dingtalk.qy.service.contact;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.ray.dingtalk.qy.auth.AuthHelper;
import com.ray.dingtalk.qy.config.Env;
import com.ray.dingtalk.qy.model.contact.User;

/**@desc  : 成员管理测试类
 * 
 * @author: shirayner
 * @date  : 2017年9月28日 上午10:09:34
 */
public class UserServiceTest {
    
    /**
     * @desc :1.获取成员
     *  
     * @throws Exception void
     */
    @Test
    public void testGetUser() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        String userId="manager6777";
        
        UserService us=new UserService();
        us.getUser(accessToken, userId);
        
        
    }
    
    /**
     * @desc :2.创建成员
     *  
     * @throws Exception void
     */
    @Test
    public void testCreateUser() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        
        User user=new User();
        user.setName("测试2");         //王子明
        List<Long> departmentList=new ArrayList<Long>();
        departmentList.add(new Long(53191107));
        user.setDepartment(departmentList);
        user.setUserid("ceishi2");;
        user.setMobile("18771419624"); //18771419627
        
        
        UserService us=new UserService();
        String userId=us.createUser(accessToken, user);
        System.out.println("userId:"+userId);
        
    }
    
    /** 3.更新成员
     * @desc :参数说明(如果非必须的字段未指定,则钉钉后台不改变该字段之前设置好的值)
     *  
     * @throws Exception void
     */
    @Test
    public void testUpdateUser() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        
        User user=new User();
        user.setName("测试专用");
        List<Long> departmentList=new ArrayList<Long>();
        departmentList.add(new Long(1));
        user.setDepartment(departmentList);
        user.setMobile("13764363757");
        user.setUserid("142322032127997575");
        user.setPosition("网管");
        
        
        UserService us=new UserService();
        us.updateUser(accessToken, user);
        
        
    }
    /** 4.删除成员
     * @desc :
     *  
     * @throws Exception void
     */
    @Test
    public void testDeleteUser() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        String userId="142322032127997575";
        
        UserService us=new UserService();
        us.deleteUser(accessToken, userId);
        
    }
    
    
    /** 5.批量删除成员
     * @desc :
     *  
     * @throws Exception void
     */
    @Test
    public void testBatchDeleteUser() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        
        //1.1为构造JSon做准备:["ceishi1","ceishi2"]
        List<String> userIdlist=new ArrayList<String>();
        userIdlist.add("ceishi1");
        userIdlist.add("ceishi2");
        
        //1.2为构造JSon做准备:{"useridlist":["ceishi1","ceishi2"]}
        Map< String , List<String> > userIdListMap=new HashMap< String, List<String> >();
        userIdListMap.put("useridlist", userIdlist);
        
        
        UserService us=new UserService();
        us.batchDeleteUser(accessToken, userIdListMap);
        
    }
    
    
    /** 6.获取部门成员(simplelist)
     * @desc :
     *  
     * @throws Exception void
     */
    @Test
    public void testListDepartmentUser() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        String departmentId="1";
        
        UserService us=new UserService();
        us.listDepartmentUser(accessToken, departmentId);

    }
    
    /** 7.获取部门成员(详情)
     * @desc :
     *  
     * @throws Exception void
     */
    @Test
    public void testListDepartmentUserDetail() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        String departmentId="1";
        
        UserService us=new UserService();
        us.listDepartmentUserDetail(accessToken, departmentId);    
       
    
    }
    
    /** 8.获取管理员列表
     * @desc :
     *  
     * @throws Exception void
     */
    @Test
    public void testListAdmin() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        
        
        UserService us=new UserService();
        us.listAdmin(accessToken);    

    }
    
    
    
    
}
View Code

 

8.部门管理测试类—DepartmentServcieTest

package com.ray.dingtalk.qy.service.contact;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;

import com.alibaba.fastjson.JSONObject;
import com.ray.dingtalk.qy.auth.AuthHelper;
import com.ray.dingtalk.qy.config.Env;
import com.ray.dingtalk.qy.model.contact.Department;

/**@desc  : 部门管理测试类
 * 
 * @author: shirayner
 * @date  : 2017年10月18日 下午1:31:32
 */
public class DepartmentServcieTest {
    private static final Logger log = LogManager.getLogger(DepartmentServcieTest.class);
    

    /** 1.获取部门列表
     * @throws Exception 
     * @desc :
     *   void
     */
    @Test
    public void testListDepartement() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        String departmentId="1";
        DepartmentServcie departmentServcie= new DepartmentServcie();      
        JSONObject jsonObject=departmentServcie.listDepartment(accessToken, departmentId);
        log.info(jsonObject);
        
    }
    
    /** 2.获取部门详情
     * @throws Exception 
     * @desc :
     *   void
     */
    @Test
    public void testGetDepartementDetail() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        String departmentId="1";
        DepartmentServcie departmentServcie= new DepartmentServcie();      
        JSONObject jsonObject=departmentServcie.getDepartmentDetail(accessToken, departmentId);
        log.info(jsonObject);
        
    }

    /** 3.创建部门
     * @throws Exception 
     * @desc :
     *   void
     */
    @Test
    public void testCreateDepartment() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        Department department =new Department();
        department.setName("HEC北京分公司");
        department.setParentid("1");
        
        
        DepartmentServcie departmentServcie= new DepartmentServcie();      
        String departmentId=departmentServcie.createDepartment(accessToken, department);
        log.info(departmentId);
        
    }
    
    
    /** 4.更新部门
     * 
     * @throws Exception 
     * @desc :
     *   void
     */
    @Test
    public void testUpdateDepartment() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        
        Department department =new Department();
        department.setName("HEC大汉分公司");
        department.setId(53125124);
        
        DepartmentServcie departmentServcie= new DepartmentServcie();      
        departmentServcie.updateDepartment(accessToken, department);
        
        
    }

    
    /** 5.删除部门
     * @throws Exception 
     * @desc :
     *   void
     */
    @Test
    public void testDeleteDepartement() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        
        String departmentId="53181144";
        
        DepartmentServcie departmentServcie= new DepartmentServcie();      
        departmentServcie.deleteDepartment(accessToken, departmentId);
        
    }
    
    /** 6.查询部门的所有上级父部门路径
     * @throws Exception 
     * @desc :
     *   void
     */
    @Test
    public void testListParentDepartementsByDept() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        
        String departmentId="53191107";
        
        DepartmentServcie departmentServcie= new DepartmentServcie();      
        JSONObject jsonObject=departmentServcie.listParentDepartementsByDept(accessToken, departmentId);
        log.info(jsonObject.get("parentIds"));
        
    }
    
    
    /** 7.查询指定用户的所有上级父部门路径
     * @throws Exception 
     * @desc :
     *   void
     */
    @Test
    public void testListParentDepartementsByUser() throws Exception {
        String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
        
        String userID="ceishi2";
        
        DepartmentServcie departmentServcie= new DepartmentServcie();      
        JSONObject jsonObject=departmentServcie.listParentDepartementsByUser(accessToken, userID);
        log.info(jsonObject.get("department"));
        
    }

}
View Code

 

目录
相关文章
|
11天前
|
Java API Maven
如何使用Java开发抖音API接口?
在数字化时代,社交媒体平台如抖音成为生活的重要部分。本文详细介绍了如何用Java开发抖音API接口,从创建开发者账号、申请API权限、准备开发环境,到编写代码、测试运行及注意事项,全面覆盖了整个开发流程。
54 10
|
17天前
|
SQL 安全 Java
安全问题已经成为软件开发中不可忽视的重要议题。对于使用Java语言开发的应用程序来说,安全性更是至关重要
在当今网络环境下,Java应用的安全性至关重要。本文深入探讨了Java安全编程的最佳实践,包括代码审查、输入验证、输出编码、访问控制和加密技术等,帮助开发者构建安全可靠的应用。通过掌握相关技术和工具,开发者可以有效防范安全威胁,确保应用的安全性。
35 4
|
18天前
|
缓存 监控 Java
如何运用JAVA开发API接口?
本文详细介绍了如何使用Java开发API接口,涵盖创建、实现、测试和部署接口的关键步骤。同时,讨论了接口的安全性设计和设计原则,帮助开发者构建高效、安全、易于维护的API接口。
48 4
|
29天前
|
开发框架 JavaScript 前端开发
HarmonyOS UI开发:掌握ArkUI(包括Java UI和JS UI)进行界面开发
【10月更文挑战第22天】随着科技发展,操作系统呈现多元化趋势。华为推出的HarmonyOS以其全场景、多设备特性备受关注。本文介绍HarmonyOS的UI开发框架ArkUI,探讨Java UI和JS UI两种开发方式。Java UI适合复杂界面开发,性能较高;JS UI适合快速开发简单界面,跨平台性好。掌握ArkUI可高效打造符合用户需求的界面。
88 8
|
24天前
|
SQL Java 程序员
倍增 Java 程序员的开发效率
应用计算困境:Java 作为主流开发语言,在数据处理方面存在复杂度高的问题,而 SQL 虽然简洁但受限于数据库架构。SPL(Structured Process Language)是一种纯 Java 开发的数据处理语言,结合了 Java 的架构灵活性和 SQL 的简洁性。SPL 提供简洁的语法、完善的计算能力、高效的 IDE、大数据支持、与 Java 应用无缝集成以及开放性和热切换特性,能够大幅提升开发效率和性能。
|
24天前
|
存储 Java 关系型数据库
在Java开发中,数据库连接是应用与数据交互的关键环节。本文通过案例分析,深入探讨Java连接池的原理与最佳实践
在Java开发中,数据库连接是应用与数据交互的关键环节。本文通过案例分析,深入探讨Java连接池的原理与最佳实践,包括连接创建、分配、复用和释放等操作,并通过电商应用实例展示了如何选择合适的连接池库(如HikariCP)和配置参数,实现高效、稳定的数据库连接管理。
45 2
|
24天前
|
监控 Java 数据库连接
在Java开发中,数据库连接管理是关键问题之一
在Java开发中,数据库连接管理是关键问题之一。本文介绍了连接池技术如何通过预创建和管理数据库连接,提高数据库操作的性能和稳定性,减少资源消耗,并简化连接管理。通过示例代码展示了HikariCP连接池的实际应用。
19 1
|
18天前
|
安全 Java 测试技术
Java开发必读,谈谈对Spring IOC与AOP的理解
Spring的IOC和AOP机制通过依赖注入和横切关注点的分离,大大提高了代码的模块化和可维护性。IOC使得对象的创建和管理变得灵活可控,降低了对象之间的耦合度;AOP则通过动态代理机制实现了横切关注点的集中管理,减少了重复代码。理解和掌握这两个核心概念,是高效使用Spring框架的关键。希望本文对你深入理解Spring的IOC和AOP有所帮助。
31 0
WK
|
24天前
|
开发框架 移动开发 Java
C++和Java哪个更适合开发移动应用
本文对比了C++和Java在移动应用开发中的优劣,从市场需求、学习难度、开发效率、跨平台性和应用领域等方面进行了详细分析。Java在Android开发中占据优势,而C++则适合对性能要求较高的场景。选择应根据具体需求和个人偏好综合考虑。
WK
42 0
WK
|
24天前
|
安全 Java 编译器
C++和Java哪个更适合开发web网站
在Web开发领域,C++和Java各具优势。C++以其高性能、低级控制和跨平台性著称,适用于需要高吞吐量和低延迟的场景,如实时交易系统和在线游戏服务器。Java则凭借其跨平台性、丰富的生态系统和强大的安全性,广泛应用于企业级Web开发,如企业管理系统和电子商务平台。选择时需根据项目需求和技术储备综合考虑。
WK
39 0

热门文章

最新文章

下一篇
无影云桌面