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 package fr.paris.lutece.util.httpaccess;
35
36 import java.io.BufferedOutputStream;
37 import java.io.ByteArrayOutputStream;
38 import java.io.File;
39 import java.io.FileOutputStream;
40 import java.io.IOException;
41 import java.io.OutputStream;
42 import java.net.URI;
43 import java.net.URISyntaxException;
44 import java.nio.charset.Charset;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Map.Entry;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
52
53 import org.apache.commons.fileupload.FileItem;
54 import org.apache.commons.lang3.StringUtils;
55 import org.apache.hc.client5.http.classic.methods.HttpDelete;
56 import org.apache.hc.client5.http.classic.methods.HttpGet;
57 import org.apache.hc.client5.http.classic.methods.HttpPost;
58 import org.apache.hc.client5.http.classic.methods.HttpPut;
59 import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
60 import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
61 import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
62 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
63 import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
64 import org.apache.hc.core5.http.ContentType;
65 import org.apache.hc.core5.http.Header;
66 import org.apache.hc.core5.http.HttpEntity;
67 import org.apache.hc.core5.http.NameValuePair;
68 import org.apache.hc.core5.http.ParseException;
69 import org.apache.hc.core5.http.ProtocolException;
70 import org.apache.hc.core5.http.io.entity.EntityUtils;
71 import org.apache.hc.core5.http.io.entity.StringEntity;
72 import org.apache.hc.core5.http.message.BasicNameValuePair;
73 import org.apache.hc.core5.net.URIBuilder;
74
75 import fr.paris.lutece.portal.service.util.AppLogService;
76 import fr.paris.lutece.util.signrequest.AuthenticateRequestInformations;
77 import fr.paris.lutece.util.signrequest.RequestAuthenticator;
78
79
80
81
82
83 public class HttpAccess
84 {
85
86
87
88 private static final String PATTERN_FILENAME = ".*filename=\"([^\"]+)";
89
90
91 private static final String DEFAULT_MIME_TYPE = "application/octet-stream";
92
93
94 private static final String DEFAULT_JSON_MIME_TYPE = "application/json";
95
96
97 private static final String SEPARATOR_CONTENT_TYPE = ";";
98
99
100 private static final String PROPERTY_HEADER_CONTENT_DISPOSITION = "Content-Disposition";
101
102
103 private static final String PROPERTY_HEADER_CONTENT_LENGTH = "Content-Length";
104
105
106 private static final String PROPERTY_HEADER_CONTENT_TYPE = "Content-Type";
107
108
109
110 private static final String PROPERTY_HTTP_REQUEST_POST = "POST";
111
112
113 private static final String PROPERTY_HTTP_REQUEST_PUT = "PUT";
114
115
116 private static final String PROPERTY_HTTP_REQUEST_DELETE = "DELETE";
117
118
119
120 private static final String DEFAULT_CHARSET = "UTF-8";
121
122
123 private ResponseStatusValidator _responseValidator;
124
125
126 private HttpAccessService _accessService;
127
128
129
130
131 public HttpAccess( )
132 {
133 _accessService = HttpAccessService.getInstance( );
134 _responseValidator = HttpAccessService.getInstance( );
135 }
136
137
138
139
140
141
142 public HttpAccess( ResponseStatusValidator validator )
143 {
144 _accessService = HttpAccessService.getInstance( );
145 _responseValidator = validator;
146 }
147
148
149
150
151
152
153
154
155 public HttpAccess( HttpAccessService accessService,ResponseStatusValidator validator)
156 {
157 _accessService = accessService;
158 _responseValidator =validator;
159 }
160
161
162
163
164
165
166 public HttpAccess( HttpAccessService accessService)
167 {
168 _accessService = accessService;
169 _responseValidator =HttpAccessService.getInstance( );
170 }
171
172
173
174
175
176
177
178
179
180
181
182
183
184 public String doGet( String strUrl ) throws HttpAccessException
185 {
186 return doGet( strUrl, null, null );
187 }
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202 public String doGet( String strUrl, RequestAuthenticator authenticator, List<String> listElements ) throws HttpAccessException
203 {
204 return doGet( strUrl, authenticator, listElements, null );
205 }
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222 public String doGet( String strUrl, RequestAuthenticator authenticator, List<String> listElements, Map<String, String> headers ) throws HttpAccessException
223 {
224 return doGet( strUrl, authenticator, listElements, headers, null );
225 }
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244 public String doGet( String strUrl, RequestAuthenticator authenticator, List<String> listElements, Map<String, String> headersRequest,
245 Map<String, String> headersResponse ) throws HttpAccessException
246 {
247 String strResponseBody = StringUtils.EMPTY;
248
249 HttpUriRequestBase httpGet = new HttpGet(strUrl);
250 addSecurityInformations(httpGet, strUrl, authenticator, listElements);
251
252
253 if (headersRequest != null) {
254 headersRequest.forEach((k, v) -> httpGet.addHeader(k, v));
255 }
256
257
258 strResponseBody=getResponseBody(httpGet, strUrl, headersResponse);
259
260
261 return strResponseBody;
262 }
263
264
265
266
267
268
269
270
271
272
273
274
275 public String doPost( String strUrl, Map<String, String> params ) throws HttpAccessException
276 {
277 return doPost( strUrl, params, null, null );
278 }
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295 public String doPost( String strUrl, Map<String, String> params, RequestAuthenticator authenticator, List<String> listElements ) throws HttpAccessException
296 {
297 return doPost( strUrl, params, authenticator, listElements, null );
298 }
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317 public String doPost( String strUrl, Map<String, String> params, RequestAuthenticator authenticator, List<String> listElements,
318 Map<String, String> headersRequest ) throws HttpAccessException
319 {
320 return doPost( strUrl, params, authenticator, listElements, headersRequest, null );
321 }
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342 public String doPost( String strUrl, Map<String, String> params, RequestAuthenticator authenticator, List<String> listElements,
343 Map<String, String> headersRequest, Map<String, String> headersResponse ) throws HttpAccessException
344 {
345
346 HttpUriRequestBase httpPost = new HttpPost(strUrl);
347
348 return doSendFormEntity(httpPost, strUrl, params, authenticator, listElements, headersRequest, headersResponse);
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 public String doRequestEnclosingMethod( String strUrl, String strMethod, String strContent, String contentType, String charset,
379 RequestAuthenticator authenticator, List<String> listElements, Map<String, String> headersRequest, Map<String, String> headersResponse )
380 throws HttpAccessException
381 {
382 String strResponseBody = StringUtils.EMPTY;
383 HttpUriRequestBase httpRequest;
384
385 switch( strMethod )
386 {
387 case PROPERTY_HTTP_REQUEST_PUT:
388
389 httpRequest=new HttpPut(strUrl);
390 break;
391
392 case PROPERTY_HTTP_REQUEST_POST:
393 httpRequest = new HttpPost(strUrl);
394 break;
395
396 case PROPERTY_HTTP_REQUEST_DELETE:
397 httpRequest = new HttpDelete(strUrl);
398 break;
399 default:
400 httpRequest = new HttpPost(strUrl);
401 break;
402 }
403
404
405
406 if (headersRequest != null) {
407 headersRequest.forEach((k, v) -> httpRequest.addHeader(k, v));
408 }
409 addSecurityInformations(httpRequest, strUrl, authenticator, listElements);
410 httpRequest.setEntity(new StringEntity(strContent, ContentType.APPLICATION_JSON, charset, false));
411
412 strResponseBody=getResponseBody(httpRequest, strUrl, headersResponse);
413
414
415 return strResponseBody;
416 }
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437 public String doPostJSON( String strUrl, String strJSON, RequestAuthenticator authenticator, List<String> listElements, Map<String, String> headersRequest,
438 Map<String, String> headersResponse ) throws HttpAccessException
439 {
440 return doRequestEnclosingMethod( strUrl, PROPERTY_HTTP_REQUEST_POST, strJSON, DEFAULT_JSON_MIME_TYPE, !StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? _accessService.getHttpClientConfiguration().getContentCharset():DEFAULT_CHARSET, authenticator, listElements,
441 headersRequest, headersResponse );
442 }
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459 public String doPostJSON( String strUrl, String strJSON, Map<String, String> headersRequest, Map<String, String> headersResponse )
460 throws HttpAccessException
461 {
462 return doRequestEnclosingMethod( strUrl, PROPERTY_HTTP_REQUEST_POST, strJSON, DEFAULT_JSON_MIME_TYPE, !StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? _accessService.getHttpClientConfiguration().getContentCharset():DEFAULT_CHARSET, null, null, headersRequest,
463 headersResponse );
464 }
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485 public String doPutJSON( String strUrl, String strJSON, RequestAuthenticator authenticator, List<String> listElements, Map<String, String> headersRequest,
486 Map<String, String> headersResponse ) throws HttpAccessException
487 {
488 return doRequestEnclosingMethod( strUrl, PROPERTY_HTTP_REQUEST_PUT, strJSON, DEFAULT_JSON_MIME_TYPE, !StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? _accessService.getHttpClientConfiguration().getContentCharset():DEFAULT_CHARSET, authenticator, listElements,
489 headersRequest, headersResponse );
490 }
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507 public String doPutJSON( String strUrl, String strJSON, Map<String, String> headersRequest, Map<String, String> headersResponse ) throws HttpAccessException
508 {
509 return doRequestEnclosingMethod( strUrl, PROPERTY_HTTP_REQUEST_PUT, strJSON, DEFAULT_JSON_MIME_TYPE, !StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? _accessService.getHttpClientConfiguration().getContentCharset():DEFAULT_CHARSET, null, null, headersRequest,
510 headersResponse );
511 }
512
513
514
515
516
517
518
519
520
521
522
523
524 public String doPostMultiValues( String strUrl, Map<String, List<String>> params ) throws HttpAccessException
525 {
526 return doPostMultiValues( strUrl, params, null, null );
527 }
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544 public String doPostMultiValues( String strUrl, Map<String, List<String>> params, RequestAuthenticator authenticator, List<String> listElements )
545 throws HttpAccessException
546 {
547 return doPostMultiValues( strUrl, params, authenticator, listElements, null );
548 }
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567 public String doPostMultiValues( String strUrl, Map<String, List<String>> params, RequestAuthenticator authenticator, List<String> listElements,
568 Map<String, String> headersRequest ) throws HttpAccessException
569 {
570
571 return doPostMultiValues(strUrl, params, authenticator, listElements, headersRequest, null);
572 }
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593 public String doPostMultiValues( String strUrl, Map<String, List<String>> params, RequestAuthenticator authenticator, List<String> listElements,
594 Map<String, String> headersRequest, Map<String, String> headersResponse ) throws HttpAccessException
595 {
596
597
598 String strResponseBody = StringUtils.EMPTY;
599 HttpUriRequestBase httpPost = new HttpPost(strUrl);
600
601
602 List<NameValuePair> nvps = new ArrayList<>();
603
604
605 if (headersRequest != null) {
606 headersRequest.forEach((k, v) -> httpPost.addHeader(k, v));
607 }
608
609
610 if ( params != null ){
611 params.forEach((k, v) -> v.stream().forEach(y-> nvps.add(new BasicNameValuePair(k, y))));
612 }
613
614
615 addSecurityInformations(httpPost, strUrl, authenticator, listElements);
616 httpPost.setEntity(new UrlEncodedFormEntity(nvps, !StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? Charset.forName(_accessService.getHttpClientConfiguration().getContentCharset()):Charset.forName(DEFAULT_CHARSET)));
617
618 strResponseBody=getResponseBody(httpPost, strUrl, headersResponse);
619
620 return strResponseBody;
621 }
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636 public String doPostMultiPart( String strUrl, Map<String, List<String>> params, Map<String, FileItem> fileItems ) throws HttpAccessException
637 {
638 return doPostMultiPart( strUrl, params, fileItems, null, null );
639 }
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658 public String doPostMultiPart( String strUrl, Map<String, List<String>> params, Map<String, FileItem> fileItems, RequestAuthenticator authenticator,
659 List<String> listElements ) throws HttpAccessException
660 {
661 return doPostMultiPart( strUrl, params, fileItems, authenticator, listElements, null );
662 }
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683 public String doPostMultiPart( String strUrl, Map<String, List<String>> params, Map<String, FileItem> fileItems, RequestAuthenticator authenticator,
684 List<String> listElements, Map<String, String> headersRequest ) throws HttpAccessException
685 {
686 return doPostMultiPart( strUrl, params, fileItems, authenticator, listElements, headersRequest, null );
687 }
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710 public String doPostMultiPart( String strUrl, Map<String, List<String>> params, Map<String, FileItem> fileItems, RequestAuthenticator authenticator,
711 List<String> listElements, Map<String, String> headersRequest, Map<String, String> headersResponse ) throws HttpAccessException
712 {
713 String strResponseBody = StringUtils.EMPTY;
714 HttpUriRequestBase httpPost = new HttpPost(strUrl);
715
716 if (headersRequest != null) {
717 headersRequest.forEach((k, v) -> httpPost.addHeader(k, v));
718 }
719
720 ArrayList<File> listFiles = new ArrayList<File>( );
721
722 MultipartEntityBuilder builder = MultipartEntityBuilder.create();
723
724
725 if ( ( fileItems != null ) && !fileItems.isEmpty( ) )
726 {
727
728 for ( Entry<String, FileItem> paramFileItem : fileItems.entrySet( ) )
729 {
730 FileItem fileItem = paramFileItem.getValue( );
731
732 if ( fileItem != null )
733 {
734 try
735 {
736 String strContentType = null;
737 String strCharset = null;
738 if ( StringUtils.isNotBlank( fileItem.getContentType( ) ) )
739 {
740 String [ ] splitContentType = StringUtils.split( fileItem.getContentType( ), SEPARATOR_CONTENT_TYPE );
741 if ( splitContentType.length > 0 && StringUtils.isNotBlank( splitContentType [0] ) )
742 {
743 strContentType = splitContentType [0];
744 }
745 if ( splitContentType.length > 1 && StringUtils.isNotBlank( splitContentType [1] ) && splitContentType [1] .toUpperCase().contains("CHARSET") )
746 {
747
748 String [ ] splitCharset =splitContentType [1].split("=");
749 if(splitCharset.length>1)
750 {
751 strCharset = splitCharset [1];
752 }
753
754
755
756 }
757 }
758
759 if ( fileItem.isInMemory( ) )
760 {
761
762 ContentType contentType= !StringUtils.isEmpty(strContentType)?ContentType.create(strContentType,!StringUtils.isEmpty(strCharset)?Charset.forName(strCharset):Charset.forName(DEFAULT_CHARSET)):ContentType.DEFAULT_BINARY;
763
764 builder.addBinaryBody(paramFileItem.getKey( ), fileItem.get( ),contentType,fileItem.getName());
765
766
767 }
768 else
769 {
770 File file = File.createTempFile( "httpaccess-multipart-", null );
771
772 listFiles.add( file );
773 fileItem.write( file );
774 ContentType contentType= !StringUtils.isEmpty(strContentType)?ContentType.create(strContentType,!StringUtils.isEmpty(strCharset)?Charset.forName(strCharset):Charset.forName(DEFAULT_CHARSET)):ContentType.DEFAULT_BINARY;
775
776 builder.addBinaryBody(paramFileItem.getKey( ), file,contentType ,fileItem.getName());
777
778
779 }
780
781
782
783 }
784 catch( Exception e )
785 {
786 String strError = "HttpAccess - Error writing file '" + fileItem.getName( ) + "' : ";
787 AppLogService.error( strError + e.getMessage( ), e );
788 throw new HttpAccessException( strError + e.getMessage( ), e );
789 }
790 }
791 }
792 }
793 if ( ( params != null ) && !params.isEmpty( ) )
794 {
795
796 ContentType contentType= ContentType.create("text/plain",!StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? Charset.forName(_accessService.getHttpClientConfiguration().getContentCharset()):Charset.forName(DEFAULT_CHARSET));
797
798 params.forEach((k, v) -> { v.stream().forEach( y -> { builder.addTextBody(k,y,contentType);});});
799
800 }
801
802 addSecurityInformations(httpPost, strUrl, authenticator, listElements);
803 builder.setCharset( !StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? Charset.forName(_accessService.getHttpClientConfiguration().getContentCharset()):Charset.forName(DEFAULT_CHARSET));
804 HttpEntity entityForm = builder.build();
805 httpPost.setEntity(entityForm);
806
807 strResponseBody=getResponseBody(httpPost, strUrl, headersResponse);
808
809
810
811 return strResponseBody;
812 }
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833 public String doPut( String strUrl, RequestAuthenticator authenticator, List<String> listElements, Map<String, String> params,
834 Map<String, String> headersRequest, Map<String, String> headersResponse ) throws HttpAccessException
835 {
836
837 HttpPut httpPut = new HttpPut(strUrl);
838 return doSendFormEntity(httpPut, strUrl, params, authenticator, listElements, headersRequest, headersResponse);
839 }
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857 private String doSendFormEntity( HttpUriRequestBase httprequestBase,String strUrl, Map<String, String> params, RequestAuthenticator authenticator, List<String> listElements,
858 Map<String, String> headersRequest, Map<String, String> headersResponse ) throws HttpAccessException
859 {
860 String strResponseBody = StringUtils.EMPTY;
861
862 List<NameValuePair> nvps = new ArrayList<>();
863
864 if (headersRequest != null) {
865 headersRequest.forEach((k, v) -> httprequestBase.addHeader(k, v));
866 }
867 if (params != null) {
868 params.forEach((k, v) -> nvps.add(new BasicNameValuePair(k, v)));
869 }
870
871 addSecurityInformations(httprequestBase, strUrl, authenticator, listElements);
872 httprequestBase.setEntity(new UrlEncodedFormEntity(nvps, !StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? Charset.forName(_accessService.getHttpClientConfiguration().getContentCharset()):Charset.forName(DEFAULT_CHARSET)));
873
874 strResponseBody=getResponseBody(httprequestBase, strUrl, headersResponse);
875
876
877 return strResponseBody;
878 }
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901 public String doDelete( String strUrl, RequestAuthenticator authenticator, List<String> listElements, Map<String, String> headersRequest,
902 Map<String, String> headersResponse ) throws HttpAccessException
903 {
904 String strResponseBody = StringUtils.EMPTY;
905
906 HttpUriRequestBase httpDelete = new HttpDelete(strUrl);
907 addSecurityInformations(httpDelete, strUrl, authenticator, listElements);
908
909
910 if (headersRequest != null) {
911 headersRequest.forEach((k, v) -> httpDelete.addHeader(k, v));
912 }
913
914
915 strResponseBody=getResponseBody(httpDelete, strUrl, headersResponse);
916
917
918 return strResponseBody;
919 }
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940 public String doDeleteJSON( String strUrl, String strJSON, RequestAuthenticator authenticator, List<String> listElements, Map<String, String> headersRequest,
941 Map<String, String> headersResponse ) throws HttpAccessException
942 {
943 return doRequestEnclosingMethod( strUrl, PROPERTY_HTTP_REQUEST_DELETE, strJSON, DEFAULT_JSON_MIME_TYPE, !StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? _accessService.getHttpClientConfiguration().getContentCharset():DEFAULT_CHARSET, authenticator, listElements,
944 headersRequest, headersResponse );
945 }
946
947
948
949
950
951
952
953
954
955
956
957 public void downloadFile( String strUrl, String strFilePath ) throws HttpAccessException
958 {
959 BufferedOutputStream bos = null;
960
961 try
962 {
963 FileOutputStream fos = new FileOutputStream( strFilePath );
964 bos = new BufferedOutputStream( fos );
965 downloadFile( strUrl, bos );
966
967 }
968 catch( IOException e )
969 {
970 throwHttpAccessException( strUrl, e );
971 }
972 finally
973 {
974 try
975 {
976 if ( bos != null )
977 {
978 bos.close( );
979 }
980 }
981 catch( IOException e )
982 {
983 AppLogService.error( "HttpAccess - Error closing stream : " + e.getMessage( ), e );
984 throw new HttpAccessException( e.getMessage( ), e );
985 }
986
987 }
988 }
989
990
991
992
993
994
995
996
997
998
999
1000 public void downloadFile( String strUrl, OutputStream outputStream ) throws HttpAccessException
1001 {
1002 HttpGet httpGet = new HttpGet(strUrl);
1003
1004 try {
1005
1006 CloseableHttpClient httpClient = _accessService.getHttpClient(httpGet.getUri().getHost());
1007 try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
1008
1009 int nResponse = response.getCode();
1010 validateResponseStatus(nResponse, httpGet.getMethod(), response, strUrl);
1011
1012 HttpEntity entity = response.getEntity();
1013
1014
1015 if(entity!=null)
1016 {
1017 entity.writeTo(outputStream);
1018
1019 }
1020
1021
1022 }
1023 }
1024 catch (IOException | ParseException | URISyntaxException e) {
1025 throwHttpAccessException(strUrl, e);
1026 }
1027 finally
1028 {
1029 try
1030 {
1031 if ( outputStream != null )
1032 {
1033 outputStream.close( );
1034 }
1035
1036 }
1037 catch( IOException e )
1038 {
1039 AppLogService.error( "HttpAccess - Error closing stream : " + e.getMessage( ), e );
1040 throw new HttpAccessException( e.getMessage( ), e );
1041 }
1042
1043
1044 }
1045
1046
1047 }
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058 public String getFileName( String strUrl ) throws HttpAccessException
1059 {
1060 String strFileName = null;
1061
1062 HttpGet httpGet = new HttpGet(strUrl);
1063
1064
1065 try {
1066 CloseableHttpClient httpClient = _accessService.getHttpClient(httpGet.getUri().getHost());
1067 try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
1068
1069 int nResponse = response.getCode();
1070 validateResponseStatus(nResponse, httpGet.getMethod(), response, strUrl);
1071
1072
1073 Header headerContentDisposition= response.getHeader(PROPERTY_HEADER_CONTENT_DISPOSITION);
1074 if ( headerContentDisposition != null )
1075 {
1076 String headerValue = headerContentDisposition.getValue( );
1077 Pattern p = Pattern.compile( PATTERN_FILENAME );
1078 Matcher matcher = p.matcher( headerValue );
1079
1080 if ( matcher.matches( ) )
1081 {
1082 strFileName = matcher.group( 1 );
1083 }
1084 }
1085 else
1086 {
1087 String [ ] tab = strUrl.split( "/" );
1088 strFileName = tab [tab.length - 1];
1089 }
1090
1091
1092
1093 }
1094 }
1095 catch (IOException | URISyntaxException|ProtocolException e) {
1096 throwHttpAccessException(strUrl, e);
1097 }
1098
1099
1100
1101 return strFileName;
1102
1103
1104
1105 }
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116 public FileItem downloadFile( String strUrl ) throws HttpAccessException
1117 {
1118 MemoryFileItem fileItem = null;
1119 HttpGet httpGet = new HttpGet(strUrl);
1120
1121 try {
1122
1123 CloseableHttpClient httpClient = _accessService.getHttpClient(httpGet.getUri().getHost());
1124 try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
1125
1126 int nResponse = response.getCode();
1127 validateResponseStatus(nResponse, httpGet.getMethod(), response, strUrl);
1128
1129 String strFileName = StringUtils.EMPTY;
1130
1131 Header headerContentDisposition= response.getHeader(PROPERTY_HEADER_CONTENT_DISPOSITION);
1132 if ( headerContentDisposition != null )
1133 {
1134 String headerValue = headerContentDisposition.getValue( );
1135 Pattern p = Pattern.compile( PATTERN_FILENAME );
1136 Matcher matcher = p.matcher( headerValue );
1137
1138 if ( matcher.matches( ) )
1139 {
1140 strFileName = matcher.group( 1 );
1141 }
1142 }
1143 else
1144 {
1145 String [ ] tab = strUrl.split( "/" );
1146 strFileName = tab [tab.length - 1];
1147 }
1148
1149
1150
1151 long lSize = 0;
1152 Header headerContentLength= response.getHeader(PROPERTY_HEADER_CONTENT_LENGTH);
1153 if ( headerContentLength != null )
1154 {
1155 lSize = Long.parseLong( headerContentLength.getValue());
1156 }
1157
1158
1159 String strContentType = StringUtils.EMPTY;
1160
1161 Header headerContentType = response.getHeader( PROPERTY_HEADER_CONTENT_TYPE );
1162
1163 if ( headerContentType != null )
1164 {
1165 strContentType = headerContentType.getValue( );
1166
1167 if ( StringUtils.isNotBlank( strContentType ) )
1168 {
1169 int nIndexOfSeparator = strContentType.indexOf( SEPARATOR_CONTENT_TYPE );
1170 strContentType = strContentType.substring( 0, nIndexOfSeparator );
1171 }
1172 }
1173
1174 if ( StringUtils.isBlank( strContentType ) )
1175 {
1176 strContentType = DEFAULT_MIME_TYPE;
1177 }
1178
1179
1180 HttpEntity entity = response.getEntity();
1181
1182
1183 if(entity!=null)
1184 {
1185 ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
1186 entity.writeTo(outputStream);
1187 fileItem = new MemoryFileItem(outputStream.toByteArray(), strFileName, lSize, strContentType );
1188 }
1189
1190
1191 }
1192 }
1193
1194 catch (IOException | URISyntaxException|ProtocolException e) {
1195 throwHttpAccessException(strUrl, e);
1196 }
1197
1198 return fileItem;
1199 }
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211 private void validateResponseStatus( int nResponseStatus,String strMethodName, CloseableHttpResponse response, String strUrl ) throws HttpAccessException, ParseException
1212 {
1213 if ( !_responseValidator.validate( nResponseStatus ) )
1214 {
1215 String strError = "HttpAccess - Error executing method " + strMethodName + " at URL : " + stripPassword( strUrl ) + " - return code : " + nResponseStatus;
1216 String strResponseBody;
1217 try
1218 {
1219
1220 HttpEntity entity = response.getEntity();
1221
1222
1223 strResponseBody = " Response Body : \n" + entity!=null?EntityUtils.toString(entity): " unable to get Response Body.";
1224
1225 }
1226 catch( IOException ex )
1227 {
1228 strResponseBody = " unable to get Response Body.";
1229 }
1230 strError += strResponseBody;
1231
1232 throw new InvalidResponseStatus( strError, nResponseStatus, null );
1233 }
1234
1235 }
1236
1237
1238
1239
1240
1241
1242
1243
1244 private void throwHttpAccessException( String strUrl, Exception exception ) throws HttpAccessException
1245 {
1246 String strError = "HttpAccess - Error URL : " + stripPassword( strUrl ) + "' : ";
1247 AppLogService.error( strError + exception.getMessage( ), exception );
1248 throw new HttpAccessException( strError + exception.getMessage( ), exception );
1249 }
1250
1251
1252
1253
1254
1255
1256
1257 private String stripPassword( String strUrl )
1258 {
1259 if ( strUrl != null && strUrl.indexOf( "?" ) > 0 && strUrl.toLowerCase( ).indexOf( "password", strUrl.indexOf( "?" ) ) > 0 )
1260 {
1261 return strUrl.substring( 0, strUrl.toLowerCase( ).indexOf( "password", strUrl.indexOf( "?" ) ) ) + "***" ;
1262 }
1263 else
1264 {
1265 return strUrl;
1266 }
1267 }
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279 private void addSecurityInformations(HttpUriRequestBase httpRequest,String strTargetUrl,RequestAuthenticator authenticator,List<String> listElements)
1280 {
1281
1282 if (authenticator != null) {
1283 AuthenticateRequestInformations securityInformations = authenticator.getSecurityInformations(listElements);
1284
1285 if (!securityInformations.getSecurityParameteres().isEmpty()) {
1286
1287 List<NameValuePair> nvps = new ArrayList<>();
1288
1289 securityInformations.getSecurityParameteres().forEach((k, v) -> nvps.add(new BasicNameValuePair(k, v)));
1290
1291 try {
1292 URI uri = new URIBuilder(new URI(strTargetUrl)).addParameters(nvps).build();
1293 httpRequest.setUri(uri);
1294 } catch (URISyntaxException e) {
1295 throw new RuntimeException(e);
1296 }
1297
1298 }
1299
1300 if (!securityInformations.getSecurityHeaders().isEmpty()) {
1301
1302 securityInformations.getSecurityHeaders().forEach((k, v) -> httpRequest.addHeader(k, v));
1303 }
1304
1305 }
1306
1307
1308
1309 }
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321 private String getResponseBody( HttpUriRequestBase httpRequest,String strUrl,Map<String,String> mapResponseHeader ) throws HttpAccessException
1322 {
1323 String strResponseBody= StringUtils.EMPTY;
1324 try (CloseableHttpClient httpClient = _accessService.getHttpClient(httpRequest.getUri().getHost())){
1325
1326 try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
1327
1328 int nResponse = response.getCode();
1329 validateResponseStatus(nResponse, httpRequest.getMethod(), response, strUrl);
1330
1331 if (mapResponseHeader != null && response.getHeaders() != null) {
1332
1333 Arrays.asList(response.getHeaders()).stream()
1334 .forEach(x -> mapResponseHeader.put(x.getName(), x.getValue()));
1335
1336 }
1337 HttpEntity entity = response.getEntity();
1338 strResponseBody = EntityUtils.toString(entity,!StringUtils.isEmpty( _accessService.getHttpClientConfiguration().getContentCharset())? Charset.forName(_accessService.getHttpClientConfiguration().getContentCharset()):Charset.forName(DEFAULT_CHARSET));
1339
1340 }
1341
1342 }
1343
1344 catch (IOException | ParseException | URISyntaxException e) {
1345 throwHttpAccessException(strUrl, e);
1346 }
1347
1348 return strResponseBody;
1349 }
1350
1351
1352 }