1
22
23 package com.liferay.portal.util;
24
25 import com.liferay.portal.kernel.log.Log;
26 import com.liferay.portal.kernel.log.LogFactoryUtil;
27 import com.liferay.portal.kernel.servlet.HttpHeaders;
28 import com.liferay.portal.kernel.util.ByteArrayMaker;
29 import com.liferay.portal.kernel.util.ContentTypes;
30 import com.liferay.portal.kernel.util.FileUtil;
31 import com.liferay.portal.kernel.util.GetterUtil;
32 import com.liferay.portal.kernel.util.Http;
33 import com.liferay.portal.kernel.util.StringPool;
34 import com.liferay.portal.kernel.util.StringUtil;
35 import com.liferay.portal.kernel.util.Validator;
36 import com.liferay.util.SystemProperties;
37
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.UnsupportedEncodingException;
41
42 import java.net.URL;
43 import java.net.URLConnection;
44 import java.net.URLDecoder;
45 import java.net.URLEncoder;
46
47 import java.util.ArrayList;
48 import java.util.Date;
49 import java.util.LinkedHashMap;
50 import java.util.List;
51 import java.util.Map;
52 import java.util.StringTokenizer;
53 import java.util.regex.Pattern;
54
55 import javax.portlet.ActionRequest;
56 import javax.portlet.RenderRequest;
57
58 import javax.servlet.http.Cookie;
59 import javax.servlet.http.HttpServletRequest;
60
61 import org.apache.commons.httpclient.Credentials;
62 import org.apache.commons.httpclient.Header;
63 import org.apache.commons.httpclient.HostConfiguration;
64 import org.apache.commons.httpclient.HttpClient;
65 import org.apache.commons.httpclient.HttpMethod;
66 import org.apache.commons.httpclient.HttpState;
67 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
68 import org.apache.commons.httpclient.NTCredentials;
69 import org.apache.commons.httpclient.NameValuePair;
70 import org.apache.commons.httpclient.URI;
71 import org.apache.commons.httpclient.UsernamePasswordCredentials;
72 import org.apache.commons.httpclient.auth.AuthPolicy;
73 import org.apache.commons.httpclient.auth.AuthScope;
74 import org.apache.commons.httpclient.cookie.CookiePolicy;
75 import org.apache.commons.httpclient.methods.DeleteMethod;
76 import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
77 import org.apache.commons.httpclient.methods.GetMethod;
78 import org.apache.commons.httpclient.methods.PostMethod;
79 import org.apache.commons.httpclient.methods.PutMethod;
80 import org.apache.commons.httpclient.methods.RequestEntity;
81 import org.apache.commons.httpclient.methods.StringRequestEntity;
82 import org.apache.commons.httpclient.params.HttpClientParams;
83 import org.apache.commons.httpclient.params.HttpConnectionParams;
84
85
91 public class HttpImpl implements Http {
92
93 public HttpImpl() {
94
95
98 if (Validator.isNotNull(_NON_PROXY_HOSTS)) {
99 String nonProxyHostsRegEx = _NON_PROXY_HOSTS;
100
101 nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll(
102 "\\.", "\\\\.");
103 nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll(
104 "\\*", ".*?");
105 nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll(
106 "\\|", ")|(");
107
108 nonProxyHostsRegEx = "(" + nonProxyHostsRegEx + ")";
109
110 _nonProxyHostsPattern = Pattern.compile(nonProxyHostsRegEx);
111 }
112
113 MultiThreadedHttpConnectionManager connectionManager =
114 new MultiThreadedHttpConnectionManager();
115
116 HttpConnectionParams params = connectionManager.getParams();
117
118 params.setParameter(
119 "maxConnectionsPerHost", new Integer(_MAX_CONNECTIONS_PER_HOST));
120 params.setParameter(
121 "maxTotalConnections", new Integer(_MAX_TOTAL_CONNECTIONS));
122 params.setConnectionTimeout(_TIMEOUT);
123 params.setSoTimeout(_TIMEOUT);
124
125 _client.setHttpConnectionManager(connectionManager);
126 _proxyClient.setHttpConnectionManager(connectionManager);
127
128 if (hasProxyConfig() && Validator.isNotNull(_PROXY_USERNAME)) {
129 if (_PROXY_AUTH_TYPE.equals("username-password")) {
130 _proxyCredentials = new UsernamePasswordCredentials(
131 _PROXY_USERNAME, _PROXY_PASSWORD);
132 }
133 else if (_PROXY_AUTH_TYPE.equals("ntlm")) {
134 _proxyCredentials = new NTCredentials(
135 _PROXY_USERNAME, _PROXY_PASSWORD, _PROXY_NTLM_HOST,
136 _PROXY_NTLM_DOMAIN);
137
138 List<String> authPrefs = new ArrayList<String>();
139
140 authPrefs.add(AuthPolicy.NTLM);
141 authPrefs.add(AuthPolicy.BASIC);
142 authPrefs.add(AuthPolicy.DIGEST);
143
144 _proxyClient.getParams().setParameter(
145 AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
146 }
147 }
148 }
149
150 public String addParameter(String url, String name, boolean value) {
151 return addParameter(url, name, String.valueOf(value));
152 }
153
154 public String addParameter(String url, String name, double value) {
155 return addParameter(url, name, String.valueOf(value));
156 }
157
158 public String addParameter(String url, String name, int value) {
159 return addParameter(url, name, String.valueOf(value));
160 }
161
162 public String addParameter(String url, String name, long value) {
163 return addParameter(url, name, String.valueOf(value));
164 }
165
166 public String addParameter(String url, String name, short value) {
167 return addParameter(url, name, String.valueOf(value));
168 }
169
170 public String addParameter(String url, String name, String value) {
171 if (url == null) {
172 return null;
173 }
174
175 String anchor = StringPool.BLANK;
176
177 int pos = url.indexOf(StringPool.POUND);
178
179 if (pos != -1) {
180 anchor = url.substring(pos);
181 url = url.substring(0, pos);
182 }
183
184 if (url.indexOf(StringPool.QUESTION) == -1) {
185 url += StringPool.QUESTION;
186 }
187
188 if (!url.endsWith(StringPool.QUESTION) &&
189 !url.endsWith(StringPool.AMPERSAND)) {
190
191 url += StringPool.AMPERSAND;
192 }
193
194 return url + name + StringPool.EQUAL + encodeURL(value) + anchor;
195 }
196
197 public String decodeURL(String url) {
198 return decodeURL(url, false);
199 }
200
201 public String decodeURL(String url, boolean unescapeSpace) {
202 if (url == null) {
203 return null;
204 }
205
206 try {
207 url = URLDecoder.decode(url, StringPool.UTF8);
208
209 if (unescapeSpace) {
210 url = StringUtil.replace(url, "%20", StringPool.PLUS);
211 }
212
213 return url;
214 }
215 catch (UnsupportedEncodingException uee) {
216 _log.error(uee, uee);
217
218 return StringPool.BLANK;
219 }
220 }
221
222 public String encodeURL(String url) {
223 return encodeURL(url, false);
224 }
225
226 public String encodeURL(String url, boolean escapeSpaces) {
227 if (url == null) {
228 return null;
229 }
230
231 try {
232 url = URLEncoder.encode(url, StringPool.UTF8);
233
234 if (escapeSpaces) {
235 url = StringUtil.replace(url, StringPool.PLUS, "%20");
236 }
237
238 return url;
239 }
240 catch (UnsupportedEncodingException uee) {
241 _log.error(uee, uee);
242
243 return StringPool.BLANK;
244 }
245 }
246
247 public HttpClient getClient(HostConfiguration hostConfig) {
248 if (isProxyHost(hostConfig.getHost())) {
249 return _proxyClient;
250 }
251 else {
252 return _client;
253 }
254 }
255
256 public String getCompleteURL(HttpServletRequest request) {
257 StringBuffer sb = request.getRequestURL();
258
259 if (sb == null) {
260 sb = new StringBuffer();
261 }
262
263 if (request.getQueryString() != null) {
264 sb.append(StringPool.QUESTION);
265 sb.append(request.getQueryString());
266 }
267
268 String completeURL = sb.toString();
269
270 if (_log.isWarnEnabled()) {
271 if (completeURL.contains("?&")) {
272 _log.warn("Invalid url " + completeURL);
273 }
274 }
275
276 return completeURL;
277 }
278
279 public Cookie[] getCookies() {
280 return _cookies.get();
281 }
282
283 public String getDomain(String url) {
284 url = removeProtocol(url);
285
286 int pos = url.indexOf(StringPool.SLASH);
287
288 if (pos != -1) {
289 return url.substring(0, pos);
290 }
291 else {
292 return url;
293 }
294 }
295
296 public HostConfiguration getHostConfig(String location) throws IOException {
297 if (_log.isDebugEnabled()) {
298 _log.debug("Location is " + location);
299 }
300
301 HostConfiguration hostConfig = new HostConfiguration();
302
303 hostConfig.setHost(new URI(location, false));
304
305 if (isProxyHost(hostConfig.getHost())) {
306 hostConfig.setProxy(_PROXY_HOST, _PROXY_PORT);
307 }
308
309 return hostConfig;
310 }
311
312 public String getParameter(String url, String name) {
313 return getParameter(url, name, true);
314 }
315
316 public String getParameter(String url, String name, boolean escaped) {
317 if (Validator.isNull(url) || Validator.isNull(name)) {
318 return StringPool.BLANK;
319 }
320
321 String[] parts = StringUtil.split(url, StringPool.QUESTION);
322
323 if (parts.length == 2) {
324 String[] params = null;
325
326 if (escaped) {
327 params = StringUtil.split(parts[1], "&");
328 }
329 else {
330 params = StringUtil.split(parts[1], StringPool.AMPERSAND);
331 }
332
333 for (int i = 0; i < params.length; i++) {
334 String[] kvp = StringUtil.split(params[i], StringPool.EQUAL);
335
336 if ((kvp.length == 2) && kvp[0].equals(name)) {
337 return kvp[1];
338 }
339 }
340 }
341
342 return StringPool.BLANK;
343 }
344
345 public Map<String, String[]> getParameterMap(String queryString) {
346 return parameterMapFromString(queryString);
347 }
348
349 public String getProtocol(ActionRequest actionRequest) {
350 return getProtocol(actionRequest.isSecure());
351 }
352
353 public String getProtocol(boolean secure) {
354 if (!secure) {
355 return Http.HTTP;
356 }
357 else {
358 return Http.HTTPS;
359 }
360 }
361
362 public String getProtocol(HttpServletRequest request) {
363 return getProtocol(request.isSecure());
364 }
365
366 public String getProtocol(RenderRequest renderRequest) {
367 return getProtocol(renderRequest.isSecure());
368 }
369
370 public String getProtocol(String url) {
371 int pos = url.indexOf(Http.PROTOCOL_DELIMITER);
372
373 if (pos != -1) {
374 return url.substring(0, pos);
375 }
376 else {
377 return Http.HTTP;
378 }
379 }
380
381 public String getQueryString(String url) {
382 if (Validator.isNull(url)) {
383 return url;
384 }
385
386 int pos = url.indexOf(StringPool.QUESTION);
387
388 if (pos == -1) {
389 return StringPool.BLANK;
390 }
391 else {
392 return url.substring(pos + 1, url.length());
393 }
394 }
395
396 public String getRequestURL(HttpServletRequest request) {
397 return request.getRequestURL().toString();
398 }
399
400 public boolean hasDomain(String url) {
401 return Validator.isNotNull(getDomain(url));
402 }
403
404 public boolean hasProtocol(String url) {
405 int pos = url.indexOf(Http.PROTOCOL_DELIMITER);
406
407 if (pos != -1) {
408 return true;
409 }
410 else {
411 return false;
412 }
413 }
414
415 public boolean hasProxyConfig() {
416 if (Validator.isNotNull(_PROXY_HOST) && (_PROXY_PORT > 0)) {
417 return true;
418 }
419 else {
420 return false;
421 }
422 }
423
424 public boolean isNonProxyHost(String host) {
425 if (_nonProxyHostsPattern == null ||
426 _nonProxyHostsPattern.matcher(host).matches()) {
427
428 return true;
429 }
430 else {
431 return false;
432 }
433 }
434
435 public boolean isProxyHost(String host) {
436 if (hasProxyConfig() && !isNonProxyHost(host)) {
437 return true;
438 }
439 else {
440 return false;
441 }
442 }
443
444 public Map<String, String[]> parameterMapFromString(String queryString) {
445 Map<String, String[]> parameterMap =
446 new LinkedHashMap<String, String[]>();
447
448 if (Validator.isNull(queryString)) {
449 return parameterMap;
450 }
451
452 Map<String, List<String>> tempParameterMap =
453 new LinkedHashMap<String, List<String>>();
454
455 StringTokenizer st = new StringTokenizer(
456 queryString, StringPool.AMPERSAND);
457
458 while (st.hasMoreTokens()) {
459 String token = st.nextToken();
460
461 if (Validator.isNotNull(token)) {
462 String[] kvp = StringUtil.split(token, StringPool.EQUAL);
463
464 String key = kvp[0];
465
466 String value = StringPool.BLANK;
467
468 if (kvp.length > 1) {
469 value = kvp[1];
470 }
471
472 List<String> values = tempParameterMap.get(key);
473
474 if (values == null) {
475 values = new ArrayList<String>();
476
477 tempParameterMap.put(key, values);
478 }
479
480 values.add(value);
481 }
482 }
483
484 for (Map.Entry<String, List<String>> entry :
485 tempParameterMap.entrySet()) {
486
487 String key = entry.getKey();
488 List<String> values = entry.getValue();
489
490 parameterMap.put(key, values.toArray(new String[values.size()]));
491 }
492
493 return parameterMap;
494 }
495
496 public String parameterMapToString(Map<String, String[]> parameterMap) {
497 return parameterMapToString(parameterMap, true);
498 }
499
500 public String parameterMapToString(
501 Map<String, String[]> parameterMap, boolean addQuestion) {
502
503 StringBuilder sb = new StringBuilder();
504
505 if (parameterMap.size() > 0) {
506 if (addQuestion) {
507 sb.append(StringPool.QUESTION);
508 }
509
510 for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
511 String name = entry.getKey();
512 String[] values = entry.getValue();
513
514 for (String value : values) {
515 sb.append(name);
516 sb.append(StringPool.EQUAL);
517 sb.append(encodeURL(value));
518 sb.append(StringPool.AMPERSAND);
519 }
520 }
521
522 sb.deleteCharAt(sb.length() - 1);
523 }
524
525 return sb.toString();
526 }
527
528 public String protocolize(String url, ActionRequest actionRequest) {
529 return protocolize(url, actionRequest.isSecure());
530 }
531
532 public String protocolize(String url, boolean secure) {
533 if (secure) {
534 if (url.startsWith(Http.HTTP_WITH_SLASH)) {
535 return StringUtil.replace(
536 url, Http.HTTP_WITH_SLASH, Http.HTTPS_WITH_SLASH);
537 }
538 }
539 else {
540 if (url.startsWith(Http.HTTPS_WITH_SLASH)) {
541 return StringUtil.replace(
542 url, Http.HTTPS_WITH_SLASH, Http.HTTP_WITH_SLASH);
543 }
544 }
545
546 return url;
547 }
548
549 public String protocolize(String url, HttpServletRequest request) {
550 return protocolize(url, request.isSecure());
551 }
552
553 public String protocolize(String url, RenderRequest renderRequest) {
554 return protocolize(url, renderRequest.isSecure());
555 }
556
557 public String removeDomain(String url) {
558 url = removeProtocol(url);
559
560 int pos = url.indexOf(StringPool.SLASH);
561
562 if (pos > 0) {
563 return url.substring(pos);
564 }
565 else {
566 return url;
567 }
568 }
569
570 public String removeParameter(String url, String name) {
571 int pos = url.indexOf(StringPool.QUESTION);
572
573 if (pos == -1) {
574 return url;
575 }
576
577 String anchor = StringPool.BLANK;
578
579 int anchorPos = url.indexOf(StringPool.POUND);
580
581 if (anchorPos != -1) {
582 anchor = url.substring(anchorPos);
583 url = url.substring(0, anchorPos);
584 }
585
586 StringBuilder sb = new StringBuilder();
587
588 sb.append(url.substring(0, pos + 1));
589
590 StringTokenizer st = new StringTokenizer(
591 url.substring(pos + 1, url.length()), StringPool.AMPERSAND);
592
593 while (st.hasMoreTokens()) {
594 String token = st.nextToken();
595
596 if (Validator.isNotNull(token)) {
597 String[] kvp = StringUtil.split(token, StringPool.EQUAL);
598
599 String key = kvp[0];
600
601 String value = StringPool.BLANK;
602
603 if (kvp.length > 1) {
604 value = kvp[1];
605 }
606
607 if (!key.equals(name)) {
608 sb.append(key);
609 sb.append(StringPool.EQUAL);
610 sb.append(value);
611 sb.append(StringPool.AMPERSAND);
612 }
613 }
614 }
615
616 url = StringUtil.replace(
617 sb.toString(), StringPool.AMPERSAND + StringPool.AMPERSAND,
618 StringPool.AMPERSAND);
619
620 if (url.endsWith(StringPool.AMPERSAND)) {
621 url = url.substring(0, url.length() - 1);
622 }
623
624 if (url.endsWith(StringPool.QUESTION)) {
625 url = url.substring(0, url.length() - 1);
626 }
627
628 return url + anchor;
629 }
630
631 public String removeProtocol(String url) {
632 if (url.startsWith(Http.HTTP_WITH_SLASH)) {
633 return url.substring(Http.HTTP_WITH_SLASH.length() , url.length());
634 }
635 else if (url.startsWith(Http.HTTPS_WITH_SLASH)) {
636 return url.substring(Http.HTTPS_WITH_SLASH.length() , url.length());
637 }
638 else {
639 return url;
640 }
641 }
642
643 public String setParameter(String url, String name, boolean value) {
644 return setParameter(url, name, String.valueOf(value));
645 }
646
647 public String setParameter(String url, String name, double value) {
648 return setParameter(url, name, String.valueOf(value));
649 }
650
651 public String setParameter(String url, String name, int value) {
652 return setParameter(url, name, String.valueOf(value));
653 }
654
655 public String setParameter(String url, String name, long value) {
656 return setParameter(url, name, String.valueOf(value));
657 }
658
659 public String setParameter(String url, String name, short value) {
660 return setParameter(url, name, String.valueOf(value));
661 }
662
663 public String setParameter(String url, String name, String value) {
664 if (url == null) {
665 return null;
666 }
667
668 url = removeParameter(url, name);
669
670 return addParameter(url, name, value);
671 }
672
673 public byte[] URLtoByteArray(Http.Options options) throws IOException {
674 return URLtoByteArray(
675 options.getLocation(), options.getMethod(), options.getHeaders(),
676 options.getCookies(), options.getAuth(), options.getBody(),
677 options.getParts());
678 }
679
680 public byte[] URLtoByteArray(String location) throws IOException {
681 Http.Options options = new Http.Options();
682
683 options.setLocation(location);
684
685 return URLtoByteArray(options);
686 }
687
688 public byte[] URLtoByteArray(String location, boolean post)
689 throws IOException {
690
691 Http.Options options = new Http.Options();
692
693 options.setLocation(location);
694 options.setPost(post);
695
696 return URLtoByteArray(options);
697 }
698
699
702 public byte[] URLtoByteArray(
703 String location, Cookie[] cookies, Http.Auth auth, Http.Body body,
704 boolean post)
705 throws IOException {
706
707 Http.Options options = new Http.Options();
708
709 options.setAuth(auth);
710 options.setBody(body);
711 options.setCookies(cookies);
712 options.setLocation(location);
713 options.setPost(post);
714
715 return URLtoByteArray(options);
716 }
717
718
721 public byte[] URLtoByteArray(
722 String location, Cookie[] cookies, Http.Auth auth,
723 Map<String, String> parts, boolean post)
724 throws IOException {
725
726 Http.Options options = new Http.Options();
727
728 options.setAuth(auth);
729 options.setCookies(cookies);
730 options.setLocation(location);
731 options.setParts(parts);
732 options.setPost(post);
733
734 return URLtoByteArray(options);
735 }
736
737 public String URLtoString(Http.Options options) throws IOException {
738 return new String(URLtoByteArray(options));
739 }
740
741 public String URLtoString(String location) throws IOException {
742 return new String(URLtoByteArray(location));
743 }
744
745 public String URLtoString(String location, boolean post)
746 throws IOException {
747
748 return new String(URLtoByteArray(location, post));
749 }
750
751
754 public String URLtoString(
755 String location, Cookie[] cookies, Http.Auth auth, Http.Body body,
756 boolean post)
757 throws IOException {
758
759 Http.Options options = new Http.Options();
760
761 options.setAuth(auth);
762 options.setBody(body);
763 options.setCookies(cookies);
764 options.setLocation(location);
765 options.setPost(post);
766
767 return new String(URLtoByteArray(options));
768 }
769
770
773 public String URLtoString(
774 String location, Cookie[] cookies, Http.Auth auth,
775 Map<String, String> parts, boolean post)
776 throws IOException {
777
778 Http.Options options = new Http.Options();
779
780 options.setAuth(auth);
781 options.setCookies(cookies);
782 options.setLocation(location);
783 options.setParts(parts);
784 options.setPost(post);
785
786 return new String(URLtoByteArray(options));
787 }
788
789
800 public String URLtoString(URL url) throws IOException {
801 String xml = null;
802
803 if (url != null) {
804 String protocol = url.getProtocol().toLowerCase();
805
806 if (protocol.startsWith(Http.HTTP) ||
807 protocol.startsWith(Http.HTTPS)) {
808
809 return URLtoString(url.toString());
810 }
811
812 URLConnection con = url.openConnection();
813
814 InputStream is = con.getInputStream();
815
816 ByteArrayMaker bam = new ByteArrayMaker();
817 byte[] bytes = new byte[512];
818
819 for (int i = is.read(bytes, 0, 512); i != -1;
820 i = is.read(bytes, 0, 512)) {
821
822 bam.write(bytes, 0, i);
823 }
824
825 xml = new String(bam.toByteArray());
826
827 is.close();
828 bam.close();
829 }
830
831 return xml;
832 }
833
834 protected void proxifyState(HttpState state, HostConfiguration hostConfig) {
835 Credentials proxyCredentials = _proxyCredentials;
836
837 String host = hostConfig.getHost();
838
839 if (isProxyHost(host) && (proxyCredentials != null)) {
840 AuthScope scope = new AuthScope(_PROXY_HOST, _PROXY_PORT, null);
841
842 state.setProxyCredentials(scope, proxyCredentials);
843 }
844 }
845
846 protected org.apache.commons.httpclient.Cookie toCommonsCookie(
847 Cookie cookie) {
848
849 org.apache.commons.httpclient.Cookie commonsCookie =
850 new org.apache.commons.httpclient.Cookie(
851 cookie.getDomain(), cookie.getName(), cookie.getValue(),
852 cookie.getPath(), cookie.getMaxAge(), cookie.getSecure());
853
854 commonsCookie.setVersion(cookie.getVersion());
855
856 return commonsCookie;
857 }
858
859 protected org.apache.commons.httpclient.Cookie[] toCommonsCookies(
860 Cookie[] cookies) {
861
862 if (cookies == null) {
863 return null;
864 }
865
866 org.apache.commons.httpclient.Cookie[] commonCookies =
867 new org.apache.commons.httpclient.Cookie[cookies.length];
868
869 for (int i = 0; i < cookies.length; i++) {
870 commonCookies[i] = toCommonsCookie(cookies[i]);
871 }
872
873 return commonCookies;
874 }
875
876 protected Cookie toServletCookie(
877 org.apache.commons.httpclient.Cookie commonsCookie) {
878
879 Cookie cookie = new Cookie(
880 commonsCookie.getName(), commonsCookie.getValue());
881
882 cookie.setDomain(commonsCookie.getDomain());
883
884 Date expiryDate = commonsCookie.getExpiryDate();
885
886 if (expiryDate != null) {
887 int maxAge =
888 (int)(expiryDate.getTime() - System.currentTimeMillis());
889
890 maxAge = maxAge / 1000;
891
892 if (maxAge > -1) {
893 cookie.setMaxAge(maxAge);
894 }
895 }
896
897 cookie.setPath(commonsCookie.getPath());
898 cookie.setSecure(commonsCookie.getSecure());
899 cookie.setVersion(commonsCookie.getVersion());
900
901 return cookie;
902 }
903
904 protected Cookie[] toServletCookies(
905 org.apache.commons.httpclient.Cookie[] commonsCookies) {
906
907 if (commonsCookies == null) {
908 return null;
909 }
910
911 Cookie[] cookies = new Cookie[commonsCookies.length];
912
913 for (int i = 0; i < commonsCookies.length; i++) {
914 cookies[i] = toServletCookie(commonsCookies[i]);
915 }
916
917 return cookies;
918 }
919
920 protected byte[] URLtoByteArray(
921 String location, Http.Method method, Map<String, String> headers,
922 Cookie[] cookies, Http.Auth auth, Http.Body body, Map<String,
923 String> parts)
924 throws IOException {
925
926 byte[] bytes = null;
927
928 HttpMethod httpMethod = null;
929 HttpState httpState = null;
930
931 try {
932 _cookies.set(null);
933
934 if (location == null) {
935 return bytes;
936 }
937 else if (!location.startsWith(Http.HTTP_WITH_SLASH) &&
938 !location.startsWith(Http.HTTPS_WITH_SLASH)) {
939
940 location = Http.HTTP_WITH_SLASH + location;
941 }
942
943 HostConfiguration hostConfig = getHostConfig(location);
944
945 HttpClient httpClient = getClient(hostConfig);
946
947 if ((method == Http.Method.POST) ||
948 (method == Http.Method.PUT)) {
949
950 if (method == Http.Method.POST) {
951 httpMethod = new PostMethod(location);
952 }
953 else {
954 httpMethod = new PutMethod(location);
955 }
956
957 if (body != null) {
958 RequestEntity requestEntity = new StringRequestEntity(
959 body.getContent(), body.getContentType(),
960 body.getCharset());
961
962 EntityEnclosingMethod entityEnclosingMethod =
963 (EntityEnclosingMethod)httpMethod;
964
965 entityEnclosingMethod.setRequestEntity(requestEntity);
966 }
967 else if ((parts != null) && (parts.size() > 0) &&
968 (method == Http.Method.POST)) {
969
970 List<NameValuePair> nvpList =
971 new ArrayList<NameValuePair>();
972
973 for (Map.Entry<String, String> entry : parts.entrySet()) {
974 String key = entry.getKey();
975 String value = entry.getValue();
976
977 if (value != null) {
978 nvpList.add(new NameValuePair(key, value));
979 }
980 }
981
982 NameValuePair[] nvpArray = nvpList.toArray(
983 new NameValuePair[nvpList.size()]);
984
985 PostMethod postMethod = (PostMethod)httpMethod;
986
987 postMethod.setRequestBody(nvpArray);
988 }
989 }
990 else if (method == Http.Method.DELETE) {
991 httpMethod = new DeleteMethod(location);
992 }
993 else {
994 httpMethod = new GetMethod(location);
995 }
996
997 if ((method == Http.Method.POST) || (method == Http.Method.PUT) &&
998 (body != null)) {
999 }
1000 else if (!_hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
1001 httpMethod.addRequestHeader(
1002 HttpHeaders.CONTENT_TYPE,
1003 ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED);
1004 }
1005
1006 if (!_hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
1007 httpMethod.addRequestHeader(
1008 HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
1009 }
1010
1011 if (headers != null) {
1012 for (Map.Entry<String, String> header : headers.entrySet()) {
1013 httpMethod.addRequestHeader(
1014 header.getKey(), header.getValue());
1015 }
1016 }
1017
1018 httpMethod.getParams().setIntParameter(
1019 HttpClientParams.SO_TIMEOUT, 0);
1020
1021
1023 httpState = new HttpState();
1024
1025 if ((cookies != null) && (cookies.length > 0)) {
1026 org.apache.commons.httpclient.Cookie[] commonsCookies =
1027 toCommonsCookies(cookies);
1028
1029 httpState.addCookies(commonsCookies);
1030
1031 httpMethod.getParams().setCookiePolicy(
1032 CookiePolicy.BROWSER_COMPATIBILITY);
1033 }
1034
1035 if (auth != null) {
1036 httpMethod.setDoAuthentication(true);
1037
1038 httpState.setCredentials(
1039 new AuthScope(
1040 auth.getHost(), auth.getPort(), auth.getRealm()),
1041 new UsernamePasswordCredentials(
1042 auth.getUsername(), auth.getPassword()));
1043 }
1044
1045 proxifyState(httpState, hostConfig);
1046
1047 httpClient.executeMethod(hostConfig, httpMethod, httpState);
1048
1049 Header locationHeader = httpMethod.getResponseHeader("location");
1050
1051 if ((locationHeader != null) && !locationHeader.equals(location)) {
1052 return URLtoByteArray(
1053 locationHeader.getValue(), Http.Method.GET, headers,
1054 cookies, auth, body, parts);
1055 }
1056
1057 InputStream is = httpMethod.getResponseBodyAsStream();
1058
1059 if (is != null) {
1060 bytes = FileUtil.getBytes(is);
1061
1062 is.close();
1063 }
1064
1065 return bytes;
1066 }
1067 finally {
1068 try {
1069 if (httpState != null) {
1070 _cookies.set(toServletCookies(httpState.getCookies()));
1071 }
1072 }
1073 catch (Exception e) {
1074 _log.error(e, e);
1075 }
1076
1077 try {
1078 if (httpMethod != null) {
1079 httpMethod.releaseConnection();
1080 }
1081 }
1082 catch (Exception e) {
1083 _log.error(e, e);
1084 }
1085 }
1086 }
1087
1088 private boolean _hasRequestHeader(HttpMethod httpMethod, String name) {
1089 if (httpMethod.getRequestHeaders(name).length == 0) {
1090 return false;
1091 }
1092 else {
1093 return true;
1094 }
1095 }
1096
1097 private static final String _DEFAULT_USER_AGENT =
1098 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
1099
1100 private static final int _MAX_CONNECTIONS_PER_HOST = GetterUtil.getInteger(
1101 PropsUtil.get(HttpImpl.class.getName() + ".max.connections.per.host"),
1102 2);
1103
1104 private static final int _MAX_TOTAL_CONNECTIONS = GetterUtil.getInteger(
1105 PropsUtil.get(HttpImpl.class.getName() + ".max.total.connections"),
1106 20);
1107
1108 private static final String _NON_PROXY_HOSTS =
1109 SystemProperties.get("http.nonProxyHosts");
1110
1111 private static final String _PROXY_AUTH_TYPE = GetterUtil.getString(
1112 PropsUtil.get(HttpImpl.class.getName() + ".proxy.auth.type"));
1113
1114 private static final String _PROXY_HOST = GetterUtil.getString(
1115 SystemProperties.get("http.proxyHost"));
1116
1117 private static final String _PROXY_NTLM_DOMAIN = GetterUtil.getString(
1118 PropsUtil.get(HttpImpl.class.getName() + ".proxy.ntlm.domain"));
1119
1120 private static final String _PROXY_NTLM_HOST = GetterUtil.getString(
1121 PropsUtil.get(HttpImpl.class.getName() + ".proxy.ntlm.host"));
1122
1123 private static final String _PROXY_PASSWORD = GetterUtil.getString(
1124 PropsUtil.get(HttpImpl.class.getName() + ".proxy.password"));
1125
1126 private static final int _PROXY_PORT = GetterUtil.getInteger(
1127 SystemProperties.get("http.proxyPort"));
1128
1129 private static final String _PROXY_USERNAME = GetterUtil.getString(
1130 PropsUtil.get(HttpImpl.class.getName() + ".proxy.username"));
1131
1132 private static final int _TIMEOUT = GetterUtil.getInteger(
1133 PropsUtil.get(HttpImpl.class.getName() + ".timeout"), 5000);
1134
1135 private static Log _log = LogFactoryUtil.getLog(HttpImpl.class);
1136
1137 private static ThreadLocal<Cookie[]> _cookies = new ThreadLocal<Cookie[]>();
1138
1139 private HttpClient _client = new HttpClient();
1140 private Pattern _nonProxyHostsPattern;
1141 private HttpClient _proxyClient = new HttpClient();
1142 private Credentials _proxyCredentials;
1143
1144}