自动化立体仓库 - WMS系统
1
ZY
21 小时以前 1b5c0044b4178c7314781ac36f897b781de72064
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
package com.zy.nc;
 
 
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.core.common.Cools;
import com.zy.nc.util.*;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
 
/**
 * 1.从resources/config.properties中读取测试api相关的数据 2.运行程序,测试查看测试结果
 *
 * @author lizhmf
 * @date 2019年6月20日上午10:53:11
 */
public class Test {
 
    // app_secret
    private static String client_secret = null;
    // 公钥
    private static String pubKey = null;
    // app_id
    private static String client_id = null;
    // ncc用户名
    private static String username = null;
    private static String usercode = null;
    // ncc用户名密码
    private static String pwd = null;
    // ncc账套
    private static String busi_center = null;
    private static String dsname = null;
    // 获取token方式:client_credentials、password
    private static String grant_type = null;
    // 服务器ip:port
    private static String baseUrl = null;
    // 返回值压缩加密级别
    private static String secret_level = null;
    // 请求参数
    private static String requestBody = null;
    // openapi请求路径
    private static String apiUrl = null;
 
    // 访问api获取到的access_token
    public static String token = null;
    // 重复调用检查
    public static String repeat_check = null;
    // 接口调用业务标识
    public static String busi_id = null;
 
    /**
     * 启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        try {
//            // 初始化数据
            init();
//            // 请求token
            if (token == null) {
                token = getToken();
            }
            System.out.println("getTokenData:" + token);
            // 测试openapi
            testApi(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 获取access_token
     *
     * @return
     * @throws Exception
     */
    private static String getToken() throws Exception {
        String token = null;
        if ("password".equals(grant_type)) {
            // 密码模式
            token = getTokenByPWD();
        } else if ("client_credentials".equals(grant_type)) {
            // 客户端模式
            token = getTokenByClient();
        }
        return token;
    }
 
    /**
     * 客户端模式获取token
     *
     * @return
     * @throws Exception
     */
    private static String getTokenByClient() throws Exception {
        Map<String, String> paramMap = new HashMap<String, String>();
        // 密码模式认证
        paramMap.put("grant_type", "client_credentials");
        // 第三方应用id
        paramMap.put("client_id", client_id);
        // 第三方应用secret 公钥加密
        String secret_entryption = Encryption.pubEncrypt(pubKey, client_secret);
        System.out.println("secret_entryption::" + secret_entryption);
        paramMap.put("client_secret", URLEncoder.encode(secret_entryption, "utf-8"));
        // 账套编码
        paramMap.put("biz_center", busi_center);
        // // TODO 传递数据源和ncc登录用户
//        paramMap.put("dsname", dsname);
        paramMap.put("usercode", usercode);
 
        // 签名
        String sign = SHA256Util.getSHA256(client_id + client_secret + pubKey, pubKey);
        paramMap.put("signature", sign);
        System.out.println("##gettoken sign::" + sign);
 
        String url = baseUrl + "/nccloud/opm/accesstoken";
        String mediaType = "application/x-www-form-urlencoded";
        String token = doPost(url, paramMap, mediaType, null, "");
        return token;
    }
 
    /**
     * 密码模式获取token
     *
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unused")
    private static String getTokenByPWD() throws Exception {
        Map<String, String> paramMap = new HashMap<String, String>();
        // 密码模式认证
        paramMap.put("grant_type", "password");
        // 第三方应用id
        paramMap.put("client_id", client_id);
        // 第三方应用secret 公钥加密
        paramMap.put("client_secret", URLEncoder.encode(Encryption.pubEncrypt(pubKey, client_secret), "utf-8"));
//        paramMap.put("client_secret", client_secret);
        // ncc用户名
        paramMap.put("username", username);
        // 密码 公钥加密
        paramMap.put("password", URLEncoder.encode(Encryption.pubEncrypt(pubKey, pwd), "utf-8"));
//        paramMap.put("password", pwd);
        // 账套编码
        paramMap.put("biz_center", busi_center);
        // 签名
        String sign = SHA256Util.getSHA256(client_id + client_secret + username + pwd + pubKey, pubKey);
        System.out.println("sign_getToken::" + sign);
        paramMap.put("signature", sign);
 
        String url = baseUrl + "/nccloud/opm/accesstoken";
        String mediaType = "application/x-www-form-urlencoded";
        String token = doPost(url, paramMap, mediaType, null, "");
        return token;
    }
 
    /**
     * 请求openapi
     *
     * @param token
     * @throws Exception
     */
    private static void testApi(String token) throws Exception {
        // token转对象,获取api访问所用token和secret
        ResultMessageUtil returnData = JSONObject.parseObject(token, ResultMessageUtil.class);
        Map<String, Object> data = (Map<String, Object>) returnData.getData();
        String access_token = (String) data.get("access_token");
        String security_key = (String) data.get("security_key");
        String refresh_token = (String) data.get("refresh_token");
        long expire_in = new Double((double) data.get("expires_in")).longValue();
        long ts = new Double((double) data.get("ts")).longValue();
        if (ts + expire_in < System.currentTimeMillis()) {
            token = getToken();
            returnData = JSONObject.parseObject(token, ResultMessageUtil.class);
            data = (Map<String, Object>) returnData.getData();
            access_token = (String) data.get("access_token");
            security_key = (String) data.get("security_key");
            refresh_token = (String) data.get("refresh_token");
        }
        System.out.println("【ACCESS_TOKEN】:" + access_token);
 
        // 请求路径
        String url = baseUrl + apiUrl;
        // header 参数
        Map<String, String> headermap = new HashMap<>();
        headermap.put("access_token", access_token);
        headermap.put("client_id", client_id);
 
        StringBuffer sb = new StringBuffer();
        sb.append(client_id);
        if (!Cools.isEmpty(requestBody)) {
            // sb.append(requestBody.replaceAll("\\s*|\t|\r|\n", "").trim());
            sb.append(requestBody);
        }
        sb.append(pubKey);
        String sign = SHA256Util.getSHA256(sb.toString(), pubKey);
        headermap.put("signature", sign);
 
        if (!Cools.isEmpty(busi_id)) {
            headermap.put("busi_id", busi_id);
        }
        if (!Cools.isEmpty(repeat_check)) {
            headermap.put("repeat_check", repeat_check);
        }
//        headermap.put("ucg_flag", "y");
 
        String mediaType = "application/json;charset=utf-8";
 
        // 表体数据json
        // 根据安全级别选择加密或压缩请求表体参数
        String json = dealRequestBody(requestBody, security_key, secret_level);
 
        // 返回值
        String result = doPost(url, null, mediaType, headermap, json);
        String result2 = dealResponseBody(result, security_key, secret_level);
        System.out.println("【RESULT】:" + result);
        System.out.println("result解密:" + result2);
    }
 
    /**
     * 返回值进行过加密和压缩,对返回值进行解压和解密
     *
     * @param source
     * @param security_key
     * @param level
     * @return
     * @throws Exception
     */
    private static String dealResponseBody(String source, String security_key, String level) throws Exception {
        String result = null;
 
        if (StringUtils.isEmpty(level) || SecretConst.LEVEL0.equals(level)) {
            result = source;
        } else if (SecretConst.LEVEL1.equals(level)) {
            result = Decryption.symDecrypt(security_key, source);
        } else if (SecretConst.LEVEL2.equals(level)) {
            result = CompressUtil.gzipDecompress(source);
        } else if (SecretConst.LEVEL3.equals(level)) {
            result = CompressUtil.gzipDecompress(Decryption.symDecrypt(security_key, source));
        } else if (SecretConst.LEVEL4.equals(level)) {
            result = Decryption.symDecrypt(security_key, CompressUtil.gzipDecompress(source));
        } else {
            throw new Exception("无效的安全等级");
        }
 
        return result;
    }
 
    /**
     * 初始化参数
     */
    private static void init() {
        // TODO Auto-generated method stub
        Properties properties = new Properties();
 
        String filepath = "config.properties";
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classloader.getResourceAsStream(filepath);
        try {
            InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
            properties.load(reader);
 
            client_secret = new String(properties.getProperty("client_secret").getBytes("utf-8"), "utf-8");
            client_id = properties.getProperty("client_id");
            pubKey = properties.getProperty("pubKey");
            username = properties.getProperty("username");
            usercode = properties.getProperty("usercode");
            pwd = properties.getProperty("pwd");
            busi_center = properties.getProperty("busi_center");
            dsname = properties.getProperty("dsname");
            baseUrl = properties.getProperty("baseUrl");
            requestBody = new String(properties.getProperty("requestBody").getBytes("utf-8"), "utf-8");
            apiUrl = properties.getProperty("apiUrl");
            grant_type = properties.getProperty("grant_type");
            secret_level = properties.getProperty("secret_level");
            repeat_check = properties.getProperty("repeat_check");
            busi_id = properties.getProperty("busi_id");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    // 根据安全级别设置,表体是否加密或压缩
    private static String dealRequestBody(String source, String security_key, String level) throws Exception {
        String result = null;
        if (StringUtils.isEmpty(level) || SecretConst.LEVEL0.equals(level)) {
            result = source;
        } else if (SecretConst.LEVEL1.equals(level)) {
            result = Encryption.symEncrypt(security_key, source);
        } else if (SecretConst.LEVEL2.equals(level)) {
            result = CompressUtil.gzipCompress(source);
        } else if (SecretConst.LEVEL3.equals(level)) {
            result = Encryption.symEncrypt(security_key, CompressUtil.gzipCompress(source));
        } else if (SecretConst.LEVEL4.equals(level)) {
            result = CompressUtil.gzipCompress(Encryption.symEncrypt(security_key, source));
        } else {
            throw new Exception("无效的安全等级");
        }
 
        return result;
    }
 
    /**
     * 发送post请求
     *
     * @param baseUrl
     * @param paramMap
     * @param mediaType
     * @param headers
     * @param json
     * @return
     */
    private static String doPost(String baseUrl, Map<String, String> paramMap, String mediaType,
                                 Map<String, String> headers, String json) throws Exception {
 
        HttpURLConnection urlConnection = null;
        InputStream in = null;
        OutputStream out = null;
        BufferedReader bufferedReader = null;
        String result = null;
        try {
            StringBuffer sb = new StringBuffer();
            sb.append(baseUrl);
            if (paramMap != null) {
                sb.append("?");
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    sb.append(key + "=" + value).append("&");
                }
                baseUrl = sb.toString().substring(0, sb.toString().length() - 1);
            }
 
            URL urlObj = new URL(baseUrl);
            urlConnection = (HttpURLConnection) urlObj.openConnection();
            urlConnection.setConnectTimeout(50000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.addRequestProperty("content-type", mediaType);
            if (headers != null) {
                for (String key : headers.keySet()) {
                    urlConnection.addRequestProperty(key, headers.get(key));
                }
            }
            out = urlConnection.getOutputStream();
            out.write(json.getBytes("utf-8"));
            out.flush();
            int resCode = urlConnection.getResponseCode();
            System.out.println("状态码::" + resCode);
//            if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) {
            in = urlConnection.getInputStream();
//            } else {
//                in = urlConnection.getErrorStream();
//            }
            bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuffer temp = new StringBuffer();
            String line = bufferedReader.readLine();
            while (line != null) {
                temp.append(line).append("\r\n");
                line = bufferedReader.readLine();
            }
            String ecod = urlConnection.getContentEncoding();
            if (ecod == null) {
                ecod = Charset.forName("utf-8").name();
            }
            result = new String(temp.toString().getBytes("utf-8"), ecod);
            System.out.println(result);
        } catch (Exception e) {
            System.out.println(e);
            throw e;
        } finally {
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            urlConnection.disconnect();
        }
        return result;
    }
 
    class SecretConst {
        /**
         * LEVEL0 不压缩、不加密
         */
        public static final String LEVEL0 = "L0";
        /**
         * LEVEL1 只加密、不压缩
         */
        public static final String LEVEL1 = "L1";
        /**
         * LEVEL2 只压缩、不加密
         */
        public static final String LEVEL2 = "L2";
        /**
         * LEVEL3 先压缩、后加密
         */
        public static final String LEVEL3 = "L3";
        /**
         * LEVEL4 先加密、后压缩
         */
        public static final String LEVEL4 = "L4";
    }
}