-
Notifications
You must be signed in to change notification settings - Fork 210
/
HttpUtils.java
387 lines (326 loc) · 14.2 KB
/
HttpUtils.java
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http:https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qlangtech.tis.manage.common;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qlangtech.tis.ajax.AjaxResult;
import com.qlangtech.tis.manage.common.ConfigFileContext.HTTPMethod;
import com.qlangtech.tis.manage.common.ConfigFileContext.StreamProcess;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author 百岁([email protected])
* @date 2014年11月4日上午11:24:38
*/
public class HttpUtils {
public interface IMsgProcess {
public void err(String content);
}
// =================================================================
// >> 测试环境使用
public static void addMockGlobalParametersConfig() {
addMockApply(1, "global_parameters_config_action", "global_params.json");
}
public static void addMockApply(int order, String testStr, String classpath) {
addMockApply(order, testStr, classpath, HttpUtils.class);
}
public static CacheMockRes addMockApply(int order, String testStr, String classpath, Class<?> clazz) {
return addMockApply(order, testStr, new ClasspathRes(order, classpath, clazz));
}
public static void addMockApply(String testStr, IClasspathRes classpathRes) {
addMockApply(-1, testStr, classpathRes);
}
public static CacheMockRes addMockApply(int orderIndex, MockMatchKey test, IClasspathRes classpathRes) {
if (HttpUtils.mockConnMaker == null) {
HttpUtils.mockConnMaker = new DefaultMockConnectionMaker();
}
CacheMockRes cacheMockRes = mockConnMaker.resourceStore.get(test);
if (cacheMockRes == null) {
cacheMockRes = new CacheMockRes();
mockConnMaker.resourceStore.put(test, cacheMockRes);
}
if (orderIndex < 0) {
cacheMockRes.resources.add(classpathRes);
} else {
while (orderIndex > (cacheMockRes.resources.size() - 1)) {
cacheMockRes.resources.add(null);
}
cacheMockRes.resources.set(orderIndex, classpathRes);
}
return cacheMockRes;
}
public static CacheMockRes addMockApply(int orderIndex, String testStr, IClasspathRes classpathRes) {
return addMockApply(orderIndex, new MockMatchKey(testStr, false, false), classpathRes);
}
public static DefaultMockConnectionMaker mockConnMaker;
public static <T> T processContent(String urlString, StreamProcess<T> process) {
try {
URL url = new URL(urlString);
return ConfigFileContext.processContent(url, process);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> T get(URL url, StreamProcess<T> process) {
return ConfigFileContext.processContent(url, process);
}
public static <T> T processContent(URL url, StreamProcess<T> process) {
return ConfigFileContext.processContent(url, process);
}
public static <T> T processContent(URL url, StreamProcess<T> process, int maxRetry) {
return ConfigFileContext.processContent(url, process, maxRetry);
}
public static <T> T post(URL url, byte[] content, PostFormStreamProcess<T> process) {
return ConfigFileContext.processContent(url, content, process);
}
public static <T> T post(URL url, String content, PostFormStreamProcess<T> process) {
return ConfigFileContext.processContent(url, content, process);
}
public static <T> T post(URL url, List<PostParam> params, PostFormStreamProcess<T> process) {
return process(url, params, process, HTTPMethod.POST);
}
public static <T> T process(URL url, List<PostParam> params, PostFormStreamProcess<T> process, HTTPMethod httpMethod) {
return ConfigFileContext.processContent(url, process, httpMethod, process.getContentType().serializeParams(params), 1);
}
public static <T> T post(String urlString, List<PostParam> params, PostFormStreamProcess<T> process) {
try {
URL url = new URL(urlString);
return post(url, params, process);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public static <T> T delete(String urlString, List<PostParam> params, PostFormStreamProcess<T> process) {
try {
return process(new URL(urlString), params, process, HTTPMethod.DELETE);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public static <T> T put(String urlString, List<PostParam> params, PostFormStreamProcess<T> process) {
try {
return process(new URL(urlString), params, process, HTTPMethod.PUT);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public static <T> AjaxResult<T> soapRemote(final String url, Class<T> clazz) {
return soapRemote(url, Collections.emptyList(), clazz, true);
}
public static <T> AjaxResult<T> soapRemote(final String url, List<PostParam> params, Class<T> clazz) {
return soapRemote(url, params, clazz, true);
}
/**
* 向console节点发送http请求,并且按照console节点返回信息的格式反序列化
*
* @param url
* @param params
* @param clazz
* @param errorShortCircuit
* @return
*/
public static <T> AjaxResult<T> soapRemote(final String url, List<PostParam> params, Class<T> clazz, boolean errorShortCircuit) {
return HttpUtils.post(url, params, new PostFormStreamProcess<AjaxResult<T>>() {
@Override
public ContentType getContentType() {
return ContentType.Application_x_www_form_urlencoded;
}
@Override
public AjaxResult<T> p(int status, InputStream stream, Map<String, List<String>> headerFields) {
AjaxResult<T> r = new AjaxResult<>();
JSONObject result = null;
try {
result = JSON.parseObject(IOUtils.toString(stream, TisUTF8.get()));
} catch (IOException e) {
throw new RuntimeException(e);
}
JSONArray errors = null;
JSONArray msgs = null;
r.setSuccess(result.getBoolean(IAjaxResult.KEY_SUCCESS));
if (!r.isSuccess()) {
errors = result.getJSONArray(IAjaxResult.KEY_ERROR_MSG);
List<String> errMsg = ((Stream<Object>) errors.stream()).map((rr) -> {
if (rr instanceof String) {
return (String) rr;
} else if (rr instanceof com.alibaba.fastjson.JSONObject) {
com.alibaba.fastjson.JSONObject err = (com.alibaba.fastjson.JSONObject) rr;
return err.entrySet().stream()
.map((entry) -> entry.getKey() + "->" + entry.getValue())
.collect(Collectors.joining("\n"));
}
throw new IllegalStateException("illegal type:" + rr.getClass().getName());
}).collect(Collectors.toList());
r.setErrormsg(errMsg);
if (errorShortCircuit) {
throw new IllegalStateException(Joiner.on("\n").join(r.getErrormsg()));
}
}
msgs = result.getJSONArray(IAjaxResult.KEY_MSG);
r.setMsg(((Stream<Object>) msgs.stream()).map((m) -> (String) m).collect(Collectors.toList()));
if (clazz == Void.class) {
return r;
}
if (result.containsKey(IAjaxResult.KEY_BIZRESULT)) {
r.setBizresult(result.getObject(IAjaxResult.KEY_BIZRESULT, clazz));
}
return r;
}
});
}
public static class PostParam {
private final String key;
private final Object value;
public PostParam(String key, Object value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return this.key;
}
public String getValue() {
return String.valueOf(this.value);
}
}
public static class MockMatchKey {
private final String matchTxt;
private final boolean startWith;
private final boolean endWith;
public MockMatchKey(String matchTxt, boolean startWith, boolean endWith) {
this.matchTxt = matchTxt;
this.startWith = startWith;
this.endWith = endWith;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MockMatchKey that = (MockMatchKey) o;
return Objects.equals(matchTxt, that.matchTxt);
}
@Override
public int hashCode() {
return Objects.hash(matchTxt);
}
}
public static class DefaultMockConnectionMaker implements MockConnectionMaker {
private final Map<MockMatchKey, CacheMockRes> /*** url test */
resourceStore = Maps.newHashMap();
public void clearStubs() {
this.resourceStore.clear();
}
@Override
public MockHttpURLConnection create(URL url, List<ConfigFileContext.Header> heads, HTTPMethod method, byte[] content) {
MockMatchKey matchKey = null;
for (Map.Entry<MockMatchKey, CacheMockRes> entry : resourceStore.entrySet()) {
matchKey = entry.getKey();
if (matchKey.startWith) {
if (StringUtils.startsWith(url.toString(), matchKey.matchTxt)) {
return createConnection(url, heads, method, content, entry.getValue().get());
}
// return null;
} else if (matchKey.endWith) {
if (StringUtils.endsWith(url.toString(), matchKey.matchTxt)) {
return createConnection(url, heads, method, content, entry.getValue().get());
}
// return null;
} else if (StringUtils.indexOf(url.toString(), matchKey.matchTxt) > -1) {
return createConnection(url, heads, method, content, entry.getValue().get());
}
}
return null;
}
protected MockHttpURLConnection createConnection(URL url, List<ConfigFileContext.Header> heads
, HTTPMethod method, byte[] content, IClasspathRes cpRes) {
return new MockHttpURLConnection(cpRes.getResourceAsStream(url), cpRes.headerFields());
}
}
public static class CacheMockRes {
// 测试每访问一次递增1
int getIndex = 0;
List<IClasspathRes> resources = Lists.newArrayList();
IClasspathRes lastElemnet = null;
int resFetchCount = 0;
public boolean verfiyResHasFetch() {
return resFetchCount > 0;
}
IClasspathRes get() {
IClasspathRes res = null;
if (getIndex >= resources.size()) {
res = this.lastElemnet;
} else {
res = (lastElemnet = resources.get(getIndex++));
}
IClasspathRes finalRes = res;
return new IClasspathRes() {
@Override
public InputStream getResourceAsStream(URL url) {
resFetchCount++;
return finalRes.getResourceAsStream(url);
}
@Override
public Map<String, List<String>> headerFields() {
return finalRes.headerFields();
}
};
}
}
public interface IClasspathRes {
InputStream getResourceAsStream(URL url);
default Map<String, List<String>> headerFields() {
return Collections.emptyMap();
}
}
public static class ClasspathRes implements IClasspathRes {
public final int order;
private final String classpath;
private final Class<?> relClass;
public ClasspathRes(int order, String classpath, Class<?> relClass) {
this.classpath = classpath;
this.relClass = relClass;
this.order = order;
}
public InputStream getResourceAsStream(URL url) {
return getResourceAsStream(classpath);
}
public InputStream getResourceAsStream(String cpResName) {
return this.relClass.getResourceAsStream(cpResName);
}
}
public static abstract class LatestUpdateTimestampClasspathRes implements IClasspathRes {
@Override
public Map<String, List<String>> headerFields() {
return ImmutableMap.of(ConfigFileContext.KEY_HEAD_LAST_UPDATE, Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
}
}
}