-
Notifications
You must be signed in to change notification settings - Fork 1
/
Update_LOINC.gradle
2094 lines (1826 loc) · 84.1 KB
/
Update_LOINC.gradle
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
****************************
* LOINC Vocabulary update *
* Version 0.0.7 *
****************************
*/
group 'com.sci.vocabulary'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'groovy'
sourceCompatibility = 1.8
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath 'org.apache.poi:poi:3.9'
classpath 'org.apache.poi:poi-ooxml:3.9'
classpath 'org.apache.httpcomponents:httpclient:4.5.3'
classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.5.2'
classpath 'com.squareup.okhttp3:okhttp:3.5.0'
classpath 'commons-io:commons-io:2.5'
classpath 'org.apache.httpcomponents:httpclient:4.5.3'
classpath 'org.apache.httpcomponents:httpcore:4.4.6'
classpath 'commons-httpclient:commons-httpclient:3.1'
classpath 'commons-io:commons-io:2.5'
classpath 'org.apache.commons:commons-lang3:3.5'
classpath 'com.google.guava:guava:21.0'
classpath group: 'commons-io', name: 'commons-io', version: '2.5'
}
}
/*
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath 'org.apache.poi:poi:3.9'
classpath 'org.apache.poi:poi-ooxml:3.9'
}
*/
import groovy.io.FileType
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.apache.poi.ss.usermodel.Sheet
/*
task compileOne(type: JavaCompile) {
source = sourceSets.main.java.srcDir
include 'inc.odysseus.utils/StringBuilderWrapper.java'
classpath = sourceSets.main.output.classesDir
destinationDir = sourceSets.main.output.classesDir
}
compileOne.options.compilerArgs = ["-sourcepath", "${projectDir}/src/main/java"]
*/
/**
* JAVA-CODE SECTION.
*
* Temporary java code are located here. If future it's need to move it toi separate java-module.
*/
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.io.FileUtils
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.NameValuePair;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URISyntaxException
import java.nio.charset.StandardCharsets
import java.nio.file.StandardCopyOption
import java.nio.file.StandardOpenOption
import java.util.*
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
/**
* Created by Sanders on 5/23/2017.
*/
public class IllegalUpdateStateException extends Exception {
public IllegalUpdateStateException(String message) {
super(message);
}
public IllegalUpdateStateException(Throwable cause) {
super(cause);
}
public IllegalUpdateStateException(String message, Throwable cause) {
super(message, cause);
}
}
public class DownloadResourceHelper {
/**
* Names of using cookies.
*
* COOKIE_JSESSIONID - session identifier on UMLS login service;
* COOKIE_CASTGC - client authentication cookie for UMLS login service;
* COOKIE_MOD_AUTH_CAS - client ticket-authentication cookie for UMLS download service.
*/
public static final String COOKIE_JSESSIONID = "JSESSIONID";
public static final String COOKIE_CASTGC = "CASTGC";
public static final String COOKIE_CASPRIVACY = "CASPRIVACY";
public static final String COOKIE_MOD_AUTH_CAS = "MOD_AUTH_CAS";
public static final int NUMBER_OF_ATTEMPTS = 3;
private CloseableHttpClient httpClient;
private File downloadPath;
private Properties resourceProperties;
/**
* Presumably "Login Ticket" parameter.
* Used on user form during authentication, generated by UMLS login service when new session is created.
*/
private String ltParam;
/**
* Class-level cookie store
*/
private List<Cookie> localCookieStore;
/**
* Apache CookieStore for all cookies.
* Isn't used because of using class-level cookie store.
*/
// private CookieStore cookieStore;
/**
* Instance of Download Helper.
*/
private static DownloadResourceHelper singleInstance;
/**
* Contructor
*/
private DownloadResourceHelper(File downloadPath, boolean autoRedirects, String propertyFilePath) {
if (downloadPath == null || !downloadPath.exists()) {
// Prepare temporary storage for content
this.downloadPath = Files.createTempDir();
this.downloadPath.deleteOnExit();
} else
this.downloadPath = downloadPath;
System.out.println(String.format("Used temporary folder: %s", this.downloadPath.getPath()));
this.localCookieStore = new ArrayList<>();
// Load resource properties
this.resourceProperties = loadProps(propertyFilePath);
// Create HttpClient
HttpClientBuilder httpClientBuilder = HttpClients.custom()
//.setProxy(new HttpHost("127.0.0.1", 8888))
.addInterceptorLast(new HttpRequestInterceptor() {
public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
debugRequestHeaders(httpRequest);
}
})
.addInterceptorLast(new HttpResponseInterceptor() {
public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
debugResponseHeaders(httpResponse);
}
});
// Configure HttpClient
if (autoRedirects) {
// With automatic redirect processing (further used for UMLS download)
httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()) // adds HTTP REDIRECT support to GET and POST methods
;
} else {
// With step-by-step redirect processing (firstly used for LOINC download)
httpClientBuilder
.disableCookieManagement()
.disableRedirectHandling()
.addInterceptorLast(new HttpRequestInterceptor() {
public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
/**
* Remove default headers
*/
httpRequest.removeHeaders("Accept");
httpRequest.removeHeaders("Accept-Encoding");
httpRequest.removeHeaders("Accept-Language");
httpRequest.removeHeaders("Connection");
httpRequest.removeHeaders("Cache-Control");
httpRequest.removeHeaders("Pragma");
httpRequest.removeHeaders("User-Agent");
httpRequest.removeHeaders("Referer");
/**
* Add common request headers
*/
httpRequest.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpRequest.addHeader("Accept-Encoding", "gzip, deflate, sdch, br");
httpRequest.addHeader("Accept-Language", "en-US,en;q=0.8,ru;q=0.6,uk;q=0.4");
httpRequest.addHeader("Cache-Control", "no-cache");
httpRequest.addHeader("Connection", "keep-alive");
httpRequest.addHeader("Pragma", "no-cache");
httpRequest.addHeader("Upgrade-Insecure-Requests", "1");
httpRequest.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
}
})
.addInterceptorLast(new HttpResponseInterceptor() {
public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
/**
* Adding of cookie from response to class-level local storage.
*/
saveClientCookie(httpResponse);
}
});
}
this.httpClient = httpClientBuilder.build();
}
/**
* Get Downloader instance
*
* @return
*/
public static DownloadResourceHelper getDownloadResourceHelper(String propertyFileName) {
return getDownloadResourceHelper(null, false, propertyFileName);
}
public static DownloadResourceHelper getDownloadResourceHelper(boolean autoRedirects, String propertyFileName) {
return getDownloadResourceHelper(null, autoRedirects, propertyFileName);
}
public static DownloadResourceHelper getDownloadResourceHelper(File downloadPath, boolean autoRedirects, String propertyFileName) {
if (singleInstance == null) {
singleInstance = new DownloadResourceHelper(downloadPath, autoRedirects, propertyFileName);
}
return singleInstance;
}
/**
* Extract header value from response
*
* @param response
* @param name
* @return
*/
private String getResponseHeaderValue(HttpResponse response, String name) {
Header header = response.getLastHeader(name);
if (header == null) {
return "";
} else {
return header.getValue();
}
}
/**
* Convert array to List
*
* @param objects
* @return
*/
/*
private <T> List<T> getListFromArray(T[] objects) {
List<T> result = new ArrayList<T>();
for (T c: objects) {
if (c != null)
result.add(c);
}
return result;
}
*/
/**
* Return all saved client's cookies.
*
* @return
*/
private List<Cookie> getAllStoredCookies() {
List<Cookie> ckList = new ArrayList<>();
Iterator<Cookie> it = this.localCookieStore.iterator();
while (it.hasNext()) {
ckList.add(it.next());
}
return ckList;
}
/**
* Get client cookie from local storage.
*
* @param name
* @return
*/
private Cookie getClientCookie(String name) {
Cookie cookie = null;
Iterator<Cookie> it = this.localCookieStore.iterator();
while (it.hasNext()) {
Cookie c = it.next();
if (c.getName().equalsIgnoreCase(name)) {
cookie = c;
break;
}
}
return cookie;
}
/**
* Class-level Cookie Storage.
*
* @param response
*/
private void saveClientCookie(HttpResponse response) {
Header[] chArray = response.getHeaders("Set-Cookie");
if (chArray == null)
return;
List<Header> chList = Arrays.asList(chArray);
for (Header header: chList) {
boolean skipCookie = false;
String nameValue = header.getValue().substring(0, header.getValue().indexOf(";"));
Cookie newCookie = new BasicClientCookie(nameValue.split("=")[0], nameValue.split("=")[1]);
Iterator<Cookie> it = this.localCookieStore.iterator();
while (it.hasNext()) {
Cookie c = it.next();
if (c.getName().equalsIgnoreCase(newCookie.getName())) {
skipCookie = true;
continue;
}
}
if (!skipCookie)
this.localCookieStore.add(newCookie);
}
}
/**
* Add multiple cookies to response.
*
* @param request
* @param cookies
* @return
*/
private HttpRequest setRequestCookies(HttpRequest request, List<Cookie> cookies) {
if (cookies == null || cookies.isEmpty())
return request;
StringBuilder sb = new StringBuilder();
for (Cookie c: cookies) {
if (c != null) {
if (sb.toString().length() != 0)
sb.append(";");
sb.append(String.format("%s=%s", c.getName(), c.getValue()));
}
}
if (sb.length() > 0)
request.addHeader("Cookie", sb.toString());
return request;
}
/**
* Convert parameter's map to name-value format, for convenient usage for Apache's classes.
*
* @param params
* @return
*/
private List<NameValuePair> toMapNameValuePairs(Map<String, String> params) {
List<NameValuePair> nvpList = new ArrayList<>();
Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
String name = entry.getKey();
String value = entry.getValue();
if (StringUtils.isNotBlank(name) && StringUtils.isNoneBlank(value))
nvpList.add(new BasicNameValuePair(name, value));
}
return nvpList;
}
/**
* Prepare GET request.
*
* @param url
* @return
* @throws IOException
* @throws URISyntaxException
*/
private HttpGet prepareGet(String url) throws IOException, URISyntaxException {
return prepareGet(url, null, null);
}
/**
* Prepare GET request with adding multiple cookies.
*
* @param url
* @param cookies
* @return
* @throws IOException
* @throws URISyntaxException
*/
private HttpGet prepareGet(String url, List<Cookie> cookies) throws IOException, URISyntaxException {
return prepareGet(url, null, cookies);
}
/**
* Prepare parametrised GET request with adding multiple cookies.
*
* @param url
* @param params
* @param cookies
* @return
* @throws IOException
* @throws URISyntaxException
*/
private HttpGet prepareGet(String url, Map<String, String> params, List<Cookie> cookies) throws IOException, URISyntaxException {
if (params != null && !params.isEmpty()) {
URIBuilder uriBuilder = new URIBuilder(url);
List<NameValuePair> pairList = toMapNameValuePairs(params);
uriBuilder.addParameters(pairList);
url = uriBuilder.toString();
}
HttpGet request = new HttpGet(url);
setRequestCookies(request, cookies);
return request;
}
/**
* Prepare parametrised POST request
*
* @param url
* @param params
* @return
* @throws IOException
* @throws URISyntaxException
*/
private HttpPost preparePost(String url, Map<String, String> params) throws IOException, URISyntaxException {
return preparePost(url, params, null);
}
/**
* Prepare parametrised POST request with adding multiple cookies.
*
* @param url
* @param params
* @param cookies
* @return
* @throws IOException
* @throws URISyntaxException
*/
private HttpPost preparePost(String url, Map<String, String> params, List<Cookie> cookies) throws IOException, URISyntaxException {
HttpPost request = new HttpPost(url);
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairList = toMapNameValuePairs(params);
request.setEntity(new UrlEncodedFormEntity(pairList));
}
setRequestCookies(request, cookies);
return request;
}
public String getDownloadPath() {
return this.downloadPath.getPath();
}
/**
* Return resource property value by it's name
*
* @param name
* @return
*/
public String getPropertyByName(String name) {
return resourceProperties.getProperty(name);
}
/**
* Load resource properties
*/
public static Properties loadProps(String fileName) {
Properties resourceProperties = new Properties();
if (StringUtils.isNotBlank(fileName)) {
try {
resourceProperties.load(new FileInputStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
return resourceProperties;
}
/*
* FOR TRACING PURPOSES ONLY
*/
private void debugStepNumber(int stepNum, String fileUrl) {
debugStepNumber(stepNum, fileUrl, "GET");
}
private void debugStepNumber(int stepNum, String fileUrl, String requestMethod) {
System.out.println(String.format("\nStep %d. %s url: %s", stepNum, requestMethod, fileUrl));
}
private <T extends HttpRequest> void debugRequestHeaders(T request) {
return;
System.out.println("!!!!! Request headers:");
List<Header> lHeader = Arrays.asList(request.getAllHeaders());
for (Header h: lHeader) {
System.out.println(String.format("\t%s: %s", h.getName(), h.getValue()));
}
}
private void debugResponseHeaders(HttpResponse response) {
debugResponseHeaders(response, null);
}
private <T extends HttpResponse> void debugResponseHeaders(T response, String responseBody) {
return;
System.out.println("\n!!!!! Response:");
System.out.println("\tresponse.getStatusLine():" + response.getStatusLine());
System.out.println("\tcontent-type:" + getResponseHeaderValue(response, "Content-Type"));
System.out.println("\tlocation:" + getResponseHeaderValue(response, "Location"));
System.out.println("\tset-cookie:");
List<Header> listHeaders = Arrays.asList(response.getHeaders("Set-Cookie"));
for (Header h: listHeaders) {
System.out.println("\t\t" + h.getValue());
}
System.out.println("\tcontent-disposition:" + getResponseHeaderValue(response, "Content-Disposition"));
if (StringUtils.isNotBlank(responseBody))
System.out.println("\tresponseBody:" + responseBody);
List<Header> lHeader = Arrays.asList(response.getAllHeaders());
for (Header h: lHeader) {
System.out.println(String.format("\t%s: %s", h.getName(), h.getValue()));
}
}
/*
* FOR TRACING PURPOSES ONLY
*/
public String repeatableDownloadUmlsResourceManualProcessing(String fileUrl, String userName, String password, String fileName, String packageDescription) {
/**
* Try three times redownload if error occurs
*/
return downloadUmlsResourceManualProcessing(fileUrl, userName, password, fileName, packageDescription,true, NUMBER_OF_ATTEMPTS);
}
public String repeatableDownloadUmlsResourceWithRedirects(String fileUrl, String userName, String password, String fileName, String packageDescription) {
/**
* Try three times redownload if error occurs
*/
return downloadUmlsResourceWithRedirects(fileUrl, userName, password, fileName, packageDescription,true, NUMBER_OF_ATTEMPTS);
}
public String repeatableDownloadLoincResource(String fileUrl, String fileName, String packageDescription) {
/**
* Try three times redownload if error occurs
*/
return downloadLoincResource(fileUrl, fileName, packageDescription, true, NUMBER_OF_ATTEMPTS);
}
// Just login UMLS
private boolean loginUmls(String loginUrl, String userName, String password) {
CloseableHttpResponse response = null;
try {
HttpGet request = prepareGet(loginUrl);
response = httpClient.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != HttpStatus.SC_OK) {
throw new HttpException(String.format("Unable to login UMLS service\n%s", response.getStatusLine()));
} else
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (response != null)
response.close();
} catch (IOException ioe) {}
}
}
// Just download UMLS routine
public String downloadUmlsResource(String fileUrl, String fileName, String packageDescription, boolean isTryRedownload, int numberOfTries) {
debugStepNumber(5, fileUrl);
CloseableHttpResponse response = null;
OutputStream outputStream = null;
HttpGet request = null;
try {
List<Cookie> cookies = new ArrayList<>();
cookies.add(getClientCookie(COOKIE_MOD_AUTH_CAS));
request = prepareGet(fileUrl, cookies);
debugRequestHeaders(request);
response = httpClient.execute(request);
debugResponseHeaders(response);
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != HttpStatus.SC_OK) {
numberOfTries--;
if (isTryRedownload && numberOfTries >= 0) {
System.out.println(String.format("Attention!\nThere is some problem of content downloading: %s.\nTry again, attempt %d of %d....", response.getStatusLine(), NUMBER_OF_ATTEMPTS - numberOfTries, NUMBER_OF_ATTEMPTS));
if (response != null)
try {
response.close();
} catch (IOException ioe) {}
return downloadUmlsResource(fileUrl, fileName, packageDescription, isTryRedownload, numberOfTries);
} else {
throw new HttpException(String.format("Unable to download %s\n%s", packageDescription, response.getStatusLine()));
}
} else if (getResponseHeaderValue(response, "Content-Type").indexOf("zip") < 0) {
throw new HttpException(String.format("%s is not a ZIP archive", packageDescription));
}
// Eval downloaded file name
String contentDisposition = getResponseHeaderValue(response, "Content-Disposition");
if (contentDisposition.length() > 0)
fileName = contentDisposition.substring(contentDisposition.lastIndexOf("filename") + 9).replace("\"", "").replace(";", "");
String filePath = String.format("%s%s%s", this.downloadPath.getPath(), File.separator, fileName);
String contentLength = getResponseHeaderValue(response,"Content-Length");
System.out.println(String.format("Downloaded '%s' file with %s bytes", fileName, contentLength));
// Save file to stream
outputStream = new FileOutputStream(new File(filePath));
IOUtils.copyLarge(response.getEntity().getContent(), outputStream);
outputStream.flush();
return fileName;
} catch (Exception e) {
if (request != null)
request.abort();
e.printStackTrace();
return StringUtils.EMPTY;
} finally {
try {
if (response != null)
response.close();
} catch (IOException ioe) {}
try {
if (outputStream != null)
outputStream.close();
} catch (IOException ioe) {}
}
}
// Login and download resource
public String downloadUmlsResourceManualProcessing(String fileUrl, String userName, String password, String fileName, String packageDescription, boolean isTryRedownload, int numberOfTries) {
this.localCookieStore.clear();
/*
* REQUEST 1
* Just get JSESSION cookie
*/
debugStepNumber(1, fileUrl);
this.ltParam = requestUmlsLoginTicket(fileUrl);
/*
* REQUEST 2
* Login to UMLS
*/
CloseableHttpResponse response = null;
HttpPost postRequest = null;
System.out.println("Login UMLS service...");
debugStepNumber(2, fileUrl);
try {
Map<String, String> params = new HashMap<>();
params.put("username", userName);
params.put("password", password);
params.put("lt", this.ltParam);
params.put("_eventId", "submit");
params.put("submit", "Sign In");
List<Cookie> cookies = new ArrayList<>();
cookies.add(getClientCookie(COOKIE_JSESSIONID));
postRequest = preparePost(fileUrl, params, cookies);
postRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
debugRequestHeaders(postRequest);
response = httpClient.execute(postRequest);
// Buffer response content
BufferedHttpEntity bufEntity = new BufferedHttpEntity(response.getEntity());
StringWriter writer = new StringWriter();
IOUtils.copy(bufEntity.getContent(), writer, StandardCharsets.UTF_8);
writer.flush();
String responseBody = writer.toString().trim();
debugResponseHeaders(response, responseBody);
// Get URL for further processing
String locationHeaderValue = getResponseHeaderValue(response, "Location");
if (StringUtils.isNotBlank(locationHeaderValue))
fileUrl = locationHeaderValue;
} catch (Exception e) {
postRequest.abort();
e.printStackTrace();
return StringUtils.EMPTY;
} finally {
try {
if (response != null)
response.close();
} catch (IOException ioe) {}
}
/*
* REQUEST 3
* Authorize on download service with ticket
*/
debugStepNumber(3, fileUrl);
HttpGet getRequest= null;
try {
List<Cookie> cookies = new ArrayList<>();
cookies.add(getClientCookie(COOKIE_JSESSIONID));
cookies.add(getClientCookie(COOKIE_CASTGC));
getRequest = prepareGet(fileUrl, cookies);
debugRequestHeaders(getRequest);
response = httpClient.execute(getRequest);
// Buffer response content
BufferedHttpEntity bufEntity = new BufferedHttpEntity(response.getEntity());
StringWriter writer = new StringWriter();
IOUtils.copy(bufEntity.getContent(), writer, StandardCharsets.UTF_8);
writer.flush();
String responseBody = writer.toString().trim();
debugResponseHeaders(response, responseBody);
// Get URL for further processing
String locationHeaderValue = getResponseHeaderValue(response, "Location");
if (StringUtils.isNotBlank(locationHeaderValue))
fileUrl = locationHeaderValue;
} catch (Exception e) {
getRequest.abort();
e.printStackTrace();
return StringUtils.EMPTY;
} finally {
try {
if (response != null)
response.close();
} catch (IOException ioe) {}
}
/*
* REQUEST 4
* Authorize on download service
* Seems that this piece of code is redundant.
*/
/*
debugStepNumber(4, fileUrl);
if (getRequest != null)
getRequest.reset();
try {
getRequest = prepareGet(fileUrl);
debugRequestHeaders(getRequest);
response = httpClient.execute(getRequest);
// Buffer response content
BufferedHttpEntity bufEntity = new BufferedHttpEntity(response.getEntity());
StringWriter writer = new StringWriter();
IOUtils.copy(bufEntity.getContent(), writer, StandardCharsets.UTF_8);
writer.flush();
String responseBody = writer.toString().trim();
debugResponseHeaders(response, responseBody);
// Get URL for further processing
String locationHeaderValue = getResponseHeaderValue(response, "Location");
if (StringUtils.isNotBlank(locationHeaderValue))
fileUrl = locationHeaderValue;
} catch (Exception e) {
getRequest.abort();
e.printStackTrace();
return StringUtils.EMPTY;
} finally {
try {
if (response != null)
response.close();
} catch (IOException ioe) {}
}
*/
/*
* REQUEST final
* Download resource
*/
return downloadUmlsResource(fileUrl, fileName, packageDescription, isTryRedownload, numberOfTries);
}
private String requestUmlsLoginTicket(String url) {
CloseableHttpResponse response = null;
HttpGet request = null;
try {
request = prepareGet(url);
debugRequestHeaders(request);
response = httpClient.execute(request);
// Buffer response content
BufferedHttpEntity bufEntity = new BufferedHttpEntity(response.getEntity());
StringWriter writer = new StringWriter();
IOUtils.copy(bufEntity.getContent(), writer, StandardCharsets.UTF_8);
writer.flush();
String responseBody = writer.toString().trim();
debugResponseHeaders(response, responseBody);
// Remember dynamically generated presumably "Login Ticket" form parameter
Pattern ltPattern = Pattern.compile("name=\"lt\" value=\"(\\w+)\"");
Matcher m = ltPattern.matcher(responseBody);
String ltParam = StringUtils.EMPTY;
while (m.find()) {
ltParam = m.group(1);
}
return ltParam;
} catch (Exception e) {
if (request != null)
request.abort();
e.printStackTrace();
return StringUtils.EMPTY;
} finally {
try {
if (response != null)
response.close();
} catch (IOException ioe) {}
}
}
public String downloadUmlsResourceWithRedirects(String fileUrl, String userName, String password, String fileName, String packageDescription, boolean isTryRedownload, int numberOfTries) {
/*
* REQUEST 1
* Just get JSESSION cookie
*/
debugStepNumber(1, fileUrl);
this.ltParam = requestUmlsLoginTicket(fileUrl);
/*
* REQUEST 2
* Login to UMLS and download package
*/
CloseableHttpResponse response = null;
OutputStream outputStream;
HttpPost postRequest = null;
System.out.println("Login UMLS service...");
debugStepNumber(2, fileUrl, "POST");
try {
Map<String, String> params = new HashMap<>();
params.put("username", userName);
params.put("password", password);
params.put("lt", this.ltParam);
params.put("_eventId", "submit");
params.put("submit", "Sign In");
postRequest = preparePost(fileUrl, params);
postRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
debugRequestHeaders(postRequest);
response = httpClient.execute(postRequest);
debugResponseHeaders(response);
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != HttpStatus.SC_OK) {
numberOfTries--;
if (isTryRedownload && numberOfTries >= 0) {
if (response != null)
try {
response.close();
} catch (IOException ioe) {}
System.out.println(String.format("Attention!\nThere is some problem of content downloading: %s.\nTry again, attempt %d of %d....",
response.getStatusLine(), NUMBER_OF_ATTEMPTS - numberOfTries, NUMBER_OF_ATTEMPTS));
return downloadUmlsResourceWithRedirects(fileUrl, userName, password, fileName, packageDescription, isTryRedownload, numberOfTries);
} else {
throw new HttpException(String.format("Unable to download %s\n%s", packageDescription, response.getStatusLine()));
}
} else if (getResponseHeaderValue(response, "Content-Type").indexOf("zip") < 0) {
throw new HttpException(String.format("%s is not a ZIP archive", packageDescription));
}
// Eval downloaded file name
String contentDisposition = getResponseHeaderValue(response, "Content-Disposition");
if (contentDisposition.length() > 0)
fileName = contentDisposition.substring(contentDisposition.lastIndexOf("filename") + 9).replace("\"", "").replace(";", "");
String filePath = String.format("%s%s%s", this.downloadPath.getPath(), File.separator, fileName);
String contentLength = getResponseHeaderValue(response,"Content-Length");
System.out.println(String.format("Downloaded '%s' file with %s bytes", fileName, contentLength));
outputStream = new FileOutputStream(new File(filePath));
IOUtils.copyLarge(response.getEntity().getContent(), outputStream);
outputStream.flush();
} catch (Exception e) {
postRequest.abort();
e.printStackTrace();
return StringUtils.EMPTY;
} finally {
try {
if (response != null)
response.close();
} catch (IOException ioe) {}
}
return fileName;
}
public boolean loginLoinc(String loginUrl, String userName, String password) {
CloseableHttpResponse response = null;
HttpPost request = null;
// Login LOINC services
try {
Map<String, String> params = new HashMap<String, String>();
params.put("log", userName);
params.put("pwd", password);
params.put("wp-submit", "Log In");
request = preparePost(loginUrl, params);
response = httpClient.execute(request);
return true;
} catch (Exception e) {
if (request != null)
request.abort();
e.printStackTrace();
return false;
} finally {
try {
if (response != null)
response.close();
} catch (IOException ioe) {}
}
}
public String downloadLoincResource(String fileUrl, String fileName, String packageDescription, boolean isTryRedownload, int numberOfTries) {
OutputStream outputStream = null;
CloseableHttpResponse response = null;
HttpPost postRequest = null;
try {
Map<String, String> params = new HashMap<String, String>();
params.put("tc_accepted", "1");
params.put("tc_submit", "Download");
List<Cookie> cookies = getAllStoredCookies();
postRequest = preparePost(fileUrl, params, cookies);
response = httpClient.execute(postRequest);