forked from webex/webex-java-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
763 lines (676 loc) · 29.6 KB
/
Copy pathClient.java
File metadata and controls
763 lines (676 loc) · 29.6 KB
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
package com.ciscospark;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonParser;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.SecureRandom;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Copyright (c) 2015 Cisco Systems, Inc. See LICENSE file.
*/
class Client {
private static final String TRACKING_ID = "TrackingID";
public static final String ISO8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
final URI baseUri;
String accessToken;
String authCode;
final URI redirectUri;
String refreshToken;
final String clientId;
final String clientSecret;
final Logger logger;
Client(URI baseUri, String authCode, URI redirectUri, String accessToken, String refreshToken, String clientId, String clientSecret, Logger logger) {
this.authCode = authCode;
this.redirectUri = redirectUri;
this.baseUri = baseUri;
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.logger = logger;
}
<T> T post(Class<T> clazz, String path, T body) {
return readJson(clazz, request("POST", path, null, body));
}
<T> T post(Class<T> clazz, URL url, T body) {
return readJson(clazz, request(url, "POST", body).inputStream);
}
<T> T put(Class<T> clazz, String path, T body) {
return readJson(clazz, request("PUT", path, null, body));
}
<T> T put(Class<T> clazz, URL url, T body) {
return readJson(clazz, request(url, "PUT", body).inputStream);
}
<T> T get(Class<T> clazz, String path, List<String[]> params) {
return readJson(clazz, request("GET", path, params, null));
}
<T> T get(Class<T> clazz, URL url) {
return readJson(clazz, request(url, "GET", null).inputStream);
}
<T> Iterator<T> list(Class<T> clazz, String path, List<String[]> params) {
return new PagingIterator<T>(clazz, getUrl(path, params));
}
<T> Iterator<T> list(Class<T> clazz, URL url) {
return new PagingIterator<T>(clazz, url);
}
<T> T head(Class<T> clazz, String path, List<String[]> params){
return readHeaders(clazz, requestHeaders("HEAD", path, params, null));
}
<T> T head(Class<T> clazz, URL url){
return readHeaders(clazz, request(url, "HEAD", null).connection.getHeaderFields());
}
void delete(String path) {
delete(getUrl(path, null));
}
void delete(URL url) {
try {
HttpsURLConnection connection = getConnection(url);
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
checkForErrorResponse(connection, responseCode);
} catch (IOException ex) {
throw new SparkException(ex);
}
}
public <T> LinkedResponse<List<T>> paginate(final Class<T> clazz, URL url) {
LinkedResponse.BodyCreator<List<T>> function = new LinkedResponse.BodyCreator<List<T>>() {
@Override
public List<T> create(InputStream istream) {
JsonParser parser = Json.createParser(istream);
Client.this.scrollToItemsArray(parser);
List<T> result = new ArrayList<T>();
for (JsonParser.Event event = parser.next();
event == JsonParser.Event.START_OBJECT;
event = parser.next()) {
result.add(readObject(clazz, parser));
}
return result;
}
};
try {
return new LinkedResponse<List<T>>(this, url, function);
} catch (IOException e) {
throw new SparkException("io error", e);
}
}
public <T> LinkedResponse<List<T>> paginate(Class<T> clazz, String paths, List<String[]> params) {
URL url = getUrl(paths, params);
return paginate(clazz, url);
}
<T> InputStream request(String method, String path, List<String[]> params, T body) {
URL url = getUrl(path, params);
return request(url, method, body).inputStream;
}
<T> Map<String, List<String>> requestHeaders(String method, String path, List<String[]> params, T body) {
URL url = getUrl(path, params);
return request(url, method, body).connection.getHeaderFields();
}
static class Response {
HttpsURLConnection connection;
InputStream inputStream;
public Response(HttpsURLConnection connection, InputStream inputStream) {
this.connection = connection;
this.inputStream = inputStream;
}
}
<T> Response request(URL url, String method, T body) {
if (accessToken == null) {
if (!authenticate()) {
throw new NotAuthenticatedException();
}
}
try {
return doRequest(url, method, body);
} catch (NotAuthenticatedException ex) {
if (authenticate()) {
return doRequest(url, method, body);
} else {
throw ex;
}
}
}
private boolean authenticate() {
if (clientId != null && clientSecret != null) {
if (authCode != null && redirectUri != null) {
log(Level.FINE, "Requesting access token");
URL url = getUrl("/access_token", null);
AccessTokenRequest body = new AccessTokenRequest();
body.setGrant_type("authorization_code");
body.setClient_id(clientId);
body.setClient_secret(clientSecret);
body.setCode(authCode);
body.setRedirect_uri(redirectUri);
Response response = doRequest(url, "POST", body);
AccessTokenResponse responseBody = readJson(AccessTokenResponse.class, response.inputStream);
accessToken = responseBody.getAccess_token();
refreshToken = responseBody.getRefresh_token();
authCode = null;
return true;
} else if (refreshToken != null) {
log(Level.FINE, "Refreshing access token");
URL url = getUrl("/access_token", null);
AccessTokenRequest body = new AccessTokenRequest();
body.setClient_id(clientId);
body.setClient_secret(clientSecret);
body.setRefresh_token(refreshToken);
body.setGrant_type("refresh_token");
Response response = doRequest(url, "POST", body);
AccessTokenResponse responseBody = readJson(AccessTokenResponse.class, response.inputStream);
accessToken = responseBody.getAccess_token();
return true;
}
}
return false;
}
private void log(Level level, String msg, Object... args) {
if (logger != null && logger.isLoggable(level)) {
logger.log(level, msg, args);
}
}
private <T> Response doRequest(URL url, String method, T body) {
return doRequest(url, method, body, 0);
}
private <T> Response doRequest(URL url, String method, T body, int retryNumber) {
try {
HttpsURLConnection connection = getConnection(url);
String trackingId = connection.getRequestProperty(TRACKING_ID);
connection.setRequestMethod(method);
if (logger != null && logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Request {0}: {1} {2}",
new Object[]{trackingId, method, connection.getURL().toString()});
}
if (body != null) {
connection.setDoOutput(true);
if (logger != null && logger.isLoggable(Level.FINEST)) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
writeJson(body, byteArrayOutputStream);
logger.log(Level.FINEST, "Request Body {0}: {1}",
new Object[]{trackingId, byteArrayOutputStream.toString()});
byteArrayOutputStream.writeTo(connection.getOutputStream());
} else {
writeJson(body, connection.getOutputStream());
}
}
int responseCode = connection.getResponseCode();
if (logger != null && logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Response {0}: {1} {2}",
new Object[]{trackingId, responseCode, connection.getResponseMessage()});
}
if (responseCode == 429) {
if(retryNumber>5)
throw new RuntimeException("Too many retry after HTTP response 429");
// retry based of Retry-After response header
final String retryAfter = connection.getHeaderField("Retry-After");
try {
Thread.sleep(Long.parseLong(retryAfter));
return doRequest(url, method, body, retryNumber+1);
} catch (InterruptedException e) {
log(Level.SEVERE, e.getMessage());
}
} else {
checkForErrorResponse(connection, responseCode);
}
if (logger != null && logger.isLoggable(Level.FINEST)) {
InputStream inputStream = logResponse(trackingId, connection.getInputStream());
return new Response(connection, inputStream);
} else {
InputStream inputStream = connection.getInputStream();
return new Response(connection, inputStream);
}
} catch (IOException ex) {
throw new SparkException("io error", ex);
}
}
private InputStream logResponse(String trackingId, InputStream inputStream) throws IOException {
if (inputStream == null) {
return null;
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte buf[] = new byte[16 * 1024];
int count;
while ((count = inputStream.read(buf)) != -1) {
byteArrayOutputStream.write(buf, 0, count);
}
logger.log(Level.FINEST, "Response Body {0}: {1}",
new Object[]{trackingId, byteArrayOutputStream.toString()});
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
private void checkForErrorResponse(HttpsURLConnection connection, int responseCode) throws NotAuthenticatedException, IOException {
if (responseCode == 401) {
throw new NotAuthenticatedException();
} else if (responseCode < 200 || responseCode >= 400) {
final StringBuilder errorMessageBuilder = new StringBuilder("bad response code ");
errorMessageBuilder.append(responseCode);
try {
String responseMessage = connection.getResponseMessage();
if (responseMessage != null) {
errorMessageBuilder.append(" ");
errorMessageBuilder.append(responseMessage);
}
} catch (IOException ex) {
// ignore
}
ErrorMessage errorMessage;
if (logger != null && logger.isLoggable(Level.FINEST)) {
InputStream inputStream = logResponse(connection.getRequestProperty(TRACKING_ID), connection.getErrorStream());
errorMessage = parseErrorMessage(inputStream);
} else {
errorMessage = parseErrorMessage(connection.getErrorStream());
}
if (errorMessage != null) {
errorMessageBuilder.append(": ");
errorMessageBuilder.append(errorMessage.message);
}
throw new SparkException(errorMessageBuilder.toString());
}
}
static class ErrorMessage {
String message;
String trackingId;
}
private static ErrorMessage parseErrorMessage(InputStream errorStream) {
try {
if (errorStream == null) {
return null;
}
JsonReader reader = Json.createReader(errorStream);
JsonObject jsonObject = reader.readObject();
ErrorMessage result = new ErrorMessage();
result.message = jsonObject.getString("message");
result.trackingId = jsonObject.getString("trackingId");
return result;
} catch (Exception ex) {
return null;
}
}
private HttpsURLConnection getConnection(URL url) throws IOException {
try {
SSLContext ssl = SSLContext.getInstance("TLSv1.2");
ssl.init(null, null, new SecureRandom());
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssl.getSocketFactory());
connection.setRequestProperty("Content-type", "application/json");
if (accessToken != null) {
String authorization = accessToken;
if (!authorization.startsWith("Bearer ")) {
authorization = "Bearer " + accessToken;
}
connection.setRequestProperty("Authorization", authorization);
}
connection.setRequestProperty(TRACKING_ID, UUID.randomUUID().toString());
return connection;
} catch (Exception ex) {
throw new IOException(ex.getMessage());
}
}
private static <T> T readHeaders(Class<T> clazz, Map<String, List<String>> headerFields){
try{
T result = clazz.newInstance();
for (Field field : clazz.getDeclaredFields()){
field.setAccessible(true);
Object fieldObject = field.get(result);
if (fieldObject instanceof HeaderField &&
headerFields.containsKey(((HeaderField) fieldObject).getHeaderName())){
((HeaderField) fieldObject).setHeaderValue(headerFields.get(((HeaderField) fieldObject).getHeaderName()));
}
}
return result;
} catch (Exception ex) {
throw new SparkException(ex);
}
}
private static <T> T readJson(Class<T> clazz, InputStream inputStream) {
JsonParser parser = Json.createParser(inputStream);
parser.next();
return readObject(clazz, parser);
}
private static <T> T readObject(Class<T> clazz, JsonParser parser) {
try {
T result = clazz.newInstance();
List<Object> list = null;
Field field = null;
String key = "";
PARSER_LOOP:
while (parser.hasNext()) {
JsonParser.Event event = parser.next();
switch (event) {
case KEY_NAME:
key = parser.getString();
try {
field = clazz.getDeclaredField(key);
field.setAccessible(true);
} catch (Exception ex) {
// ignore
}
break;
case VALUE_FALSE:
if (field != null) {
field.set(result, false);
field = null;
}
break;
case VALUE_TRUE:
if (field != null) {
field.set(result, true);
field = null;
}
break;
case VALUE_NUMBER:
if (field != null) {
Object value = (parser.isIntegralNumber() ? parser.getInt() : parser.getBigDecimal());
field.set(result, value);
field = null;
}
break;
case VALUE_STRING:
if (list != null) {
list.add(parser.getString());
} else if (field != null) {
if (field.getType().isAssignableFrom(String.class)) {
field.set(result, parser.getString());
} else if (field.getType().isAssignableFrom(Date.class)) {
DateFormat dateFormat = new SimpleDateFormat(ISO8601_FORMAT);
field.set(result, dateFormat.parse(parser.getString()));
} else if (field.getType().isAssignableFrom(URI.class)) {
field.set(result, URI.create(parser.getString()));
}
field = null;
}
break;
case VALUE_NULL:
field = null;
break;
case START_ARRAY:
list = new ArrayList<Object>();
break;
case END_ARRAY:
if (field != null) {
Class itemClazz;
if (field.getType().equals(String[].class)) {
itemClazz = String.class;
} else if (field.getType().equals(URI[].class)) {
itemClazz = URI.class;
ListIterator<Object> iterator = list.listIterator();
while (iterator.hasNext()) {
Object next = iterator.next();
iterator.set(URI.create(next.toString()));
}
} else if (field.getType().getComponentType() != null /* this is an array class */) {
itemClazz = field.getType().getComponentType(); // this would also cover the String array we had previously
} else {
throw new SparkException("bad field class: " + field.getType());
}
Object array = Array.newInstance(itemClazz, list.size());
field.set(result, list.toArray((Object[]) array));
field = null;
}
list = null;
break;
case START_OBJECT:
// we should construct these objects recursively
// the field type points us in the direction of the class to instantiate
if (null != field) {
if (null != list) {
// we are in a list - we likely have a s at the end, which we should drop
list.add(readObject(field.getType().getComponentType(), parser));
} else {
// in case of PhoneNumber this would return a PhoneNumber object
field.set(result, readObject(field.getType(), parser));
}
} else {
list = null;
}
break;
case END_OBJECT:
break PARSER_LOOP;
default:
throw new SparkException("bad json event: " + event);
}
}
return result;
} catch (SparkException ex) {
throw ex;
} catch (Exception ex) {
throw new SparkException(ex);
}
}
private URL getUrl(String path, List<String[]> params) {
final StringBuilder urlStringBuilder = new StringBuilder(baseUri.toString() + path);
if (params != null) {
urlStringBuilder.append("?");
for (String param[] : params) {
urlStringBuilder
.append(Client.this.encode(param[0]))
.append("=")
.append(Client.this.encode(param[1]))
.append("&");
}
}
URL url;
try {
url = new URL(urlStringBuilder.toString());
} catch (MalformedURLException e) {
throw new SparkException("bad url: " + urlStringBuilder, e);
}
return url;
}
private String encode(String value) {
try {
return URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new SparkException(ex);
}
}
private void writeJson(Object body, OutputStream ostream) {
JsonGenerator jsonGenerator = Json.createGenerator(ostream);
jsonGenerator.writeStartObject();
for (Field field : body.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
Object value = field.get(body);
if (value == null) {
continue;
}
Type type = field.getType();
if (type == String.class) {
jsonGenerator.write(field.getName(), (String) value);
} else if (type == Integer.class) {
jsonGenerator.write(field.getName(), (Integer) value);
} else if (type == BigDecimal.class) {
jsonGenerator.write(field.getName(), (BigDecimal) value);
} else if (type == Date.class) {
DateFormat dateFormat = new SimpleDateFormat(ISO8601_FORMAT);
jsonGenerator.write(field.getName(), dateFormat.format(value));
} else if (type == URI.class) {
jsonGenerator.write(field.getName(), value.toString());
} else if (type == JsonArray.class) {
jsonGenerator.write(field.getName(), (JsonArray) value);
} else if (type == Boolean.class) {
jsonGenerator.write(field.getName(), (Boolean) value);
} else if (type == String[].class) {
jsonGenerator.writeStartArray(field.getName());
for (String st : (String[]) value) {
jsonGenerator.write(st);
}
jsonGenerator.writeEnd();
} else if (type == URI[].class) {
jsonGenerator.writeStartArray(field.getName());
for (URI uri : (URI[]) value) {
jsonGenerator.write(uri.toString());
}
jsonGenerator.writeEnd();
}
} catch (IllegalAccessException ex) {
// ignore
}
}
jsonGenerator.writeEnd();
jsonGenerator.flush();
jsonGenerator.close();
}
private class PagingIterator<T> implements Iterator<T> {
private final Class<T> clazz;
private URL url;
private HttpsURLConnection connection;
private JsonParser parser;
T current;
public PagingIterator(Class<T> clazz, URL url) {
this.clazz = clazz;
this.url = url;
}
@Override
public boolean hasNext() {
try {
if (current == null) {
if (parser == null) {
Response response = request(url, "GET", null);
InputStream inputStream = response.inputStream;
connection = response.connection;
parser = Json.createParser(inputStream);
scrollToItemsArray(parser);
}
JsonParser.Event event = parser.next();
if (event != JsonParser.Event.START_OBJECT) {
HttpsURLConnection next = getLink(connection, "next");
if (next == null || (next.getURL().equals(url))) {
return false;
} else {
connection = next;
url = connection.getURL();
parser = null;
return hasNext();
}
}
current = readObject(clazz, parser);
}
return current != null;
} catch (IOException ex) {
throw new SparkException(ex);
}
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return current;
} finally {
current = null;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private void scrollToItemsArray(JsonParser parser) {
JsonParser.Event event;
while (parser.hasNext()) {
event = parser.next();
if (event == JsonParser.Event.KEY_NAME && parser.getString().equals("items")) {
break;
}
}
event = parser.next();
if (event != JsonParser.Event.START_ARRAY) {
throw new SparkException("bad json");
}
}
private static final Pattern linkPattern = Pattern.compile("\\s*<(\\S+)>\\s*;\\s*rel=\"(\\S+)\",?");
private HttpsURLConnection getLink(HttpsURLConnection connection, String rel) throws IOException {
String link = connection.getHeaderField("Link");
return parseLinkHeader(link, rel);
}
private HttpsURLConnection parseLinkHeader(String link, String desiredRel) throws IOException {
HttpsURLConnection result = null;
if (link != null && !"".equals(link)) {
Matcher matcher = linkPattern.matcher(link);
while (matcher.find()) {
String url = matcher.group(1);
String foundRel = matcher.group(2);
if (desiredRel.equals(foundRel)) {
result = getConnection(new URL(url));
break;
}
}
}
return result;
}
public File getFile(URL url) {
File file = this.doRequest4File(url);
return file;
}
private File doRequest4File(URL url) {
try {
HttpURLConnection connection = this.getConnection(url);
String trackingId = connection.getRequestProperty("TrackingID");
connection.setRequestMethod("GET");
if (this.logger != null && this.logger.isLoggable(Level.FINE)) {
this.logger.log(Level.FINE, "Request {0}: {1} {2}", new Object[]{trackingId, "GET", connection.getURL().toString()});
}
int responseCode = connection.getResponseCode();
if (this.logger != null && this.logger.isLoggable(Level.FINE)) {
this.logger.log(Level.FINE, "Response {0}: {1} {2}", new Object[]{trackingId, responseCode, connection.getResponseMessage()});
}
if (responseCode != 200) {
this.logger.info("No file to download. Server replied HTTP code: " + responseCode);
connection.disconnect();
return null;
} else {
String fileName = "";
String disposition = connection.getHeaderField("Content-Disposition");
String contentType = connection.getContentType();
int contentLength = connection.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10, disposition.length() - 1);
}
} else {
String fileURL = url.toString();
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
}
if (this.logger != null && this.logger.isLoggable(Level.FINE)) {
this.logger.info("Content-Type = " + contentType);
this.logger.info("Content-Disposition = " + disposition);
this.logger.info("Content-Length = " + contentLength);
this.logger.info("fileName = " + fileName);
}
InputStream inputStream = connection.getInputStream();
String tempDirectory = System.getProperty("java.io.tmpdir");
Path saveFilePath = Paths.get(tempDirectory, fileName);
File file = saveFilePath.toFile();
FileOutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[512];
int bytesRead;
while((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
return file;
}
} catch (IOException var16) {
throw new SparkException("io error", var16);
}
}
}