1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    *
5    *
6    *
7    * The contents of this file are subject to the terms of the Liferay Enterprise
8    * Subscription License ("License"). You may not use this file except in
9    * compliance with the License. You can obtain a copy of the License by
10   * contacting Liferay, Inc. See the License for the specific language governing
11   * permissions and limitations under the License, including but not limited to
12   * distribution rights of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
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.ContentTypes;
29  import com.liferay.portal.kernel.util.FileUtil;
30  import com.liferay.portal.kernel.util.GetterUtil;
31  import com.liferay.portal.kernel.util.Http;
32  import com.liferay.portal.kernel.util.StringPool;
33  import com.liferay.portal.kernel.util.StringUtil;
34  import com.liferay.portal.kernel.util.Validator;
35  import com.liferay.util.SystemProperties;
36  
37  import java.io.ByteArrayOutputStream;
38  import java.io.IOException;
39  import java.io.InputStream;
40  import java.io.UnsupportedEncodingException;
41  
42  import java.net.InetAddress;
43  import java.net.URL;
44  import java.net.URLConnection;
45  import java.net.URLDecoder;
46  import java.net.URLEncoder;
47  
48  import java.util.ArrayList;
49  import java.util.Date;
50  import java.util.LinkedHashMap;
51  import java.util.List;
52  import java.util.Map;
53  import java.util.StringTokenizer;
54  import java.util.regex.Pattern;
55  
56  import javax.portlet.ActionRequest;
57  import javax.portlet.RenderRequest;
58  
59  import javax.servlet.http.Cookie;
60  import javax.servlet.http.HttpServletRequest;
61  
62  import org.apache.commons.httpclient.Credentials;
63  import org.apache.commons.httpclient.Header;
64  import org.apache.commons.httpclient.HostConfiguration;
65  import org.apache.commons.httpclient.HttpClient;
66  import org.apache.commons.httpclient.HttpMethod;
67  import org.apache.commons.httpclient.HttpState;
68  import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
69  import org.apache.commons.httpclient.NTCredentials;
70  import org.apache.commons.httpclient.NameValuePair;
71  import org.apache.commons.httpclient.URI;
72  import org.apache.commons.httpclient.UsernamePasswordCredentials;
73  import org.apache.commons.httpclient.auth.AuthPolicy;
74  import org.apache.commons.httpclient.auth.AuthScope;
75  import org.apache.commons.httpclient.cookie.CookiePolicy;
76  import org.apache.commons.httpclient.methods.DeleteMethod;
77  import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
78  import org.apache.commons.httpclient.methods.GetMethod;
79  import org.apache.commons.httpclient.methods.PostMethod;
80  import org.apache.commons.httpclient.methods.PutMethod;
81  import org.apache.commons.httpclient.methods.RequestEntity;
82  import org.apache.commons.httpclient.methods.StringRequestEntity;
83  import org.apache.commons.httpclient.params.HttpClientParams;
84  import org.apache.commons.httpclient.params.HttpConnectionParams;
85  
86  /**
87   * <a href="HttpImpl.java.html"><b><i>View Source</i></b></a>
88   *
89   * @author Brian Wing Shun Chan
90   */
91  public class HttpImpl implements Http {
92  
93      public HttpImpl() {
94  
95          // Mimic behavior found in
96          // http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html
97  
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 getIpAddress(String url) {
313         try {
314             URL urlObj = new URL(url);
315 
316             InetAddress address = InetAddress.getByName(urlObj.getHost());
317 
318             return address.getHostAddress();
319         }
320         catch (Exception e) {
321             return url;
322         }
323     }
324 
325     public String getParameter(String url, String name) {
326         return getParameter(url, name, true);
327     }
328 
329     public String getParameter(String url, String name, boolean escaped) {
330         if (Validator.isNull(url) || Validator.isNull(name)) {
331             return StringPool.BLANK;
332         }
333 
334         String[] parts = StringUtil.split(url, StringPool.QUESTION);
335 
336         if (parts.length == 2) {
337             String[] params = null;
338 
339             if (escaped) {
340                 params = StringUtil.split(parts[1], "&amp;");
341             }
342             else {
343                 params = StringUtil.split(parts[1], StringPool.AMPERSAND);
344             }
345 
346             for (int i = 0; i < params.length; i++) {
347                 String[] kvp = StringUtil.split(params[i], StringPool.EQUAL);
348 
349                 if ((kvp.length == 2) && kvp[0].equals(name)) {
350                     return kvp[1];
351                 }
352             }
353         }
354 
355         return StringPool.BLANK;
356     }
357 
358     public Map<String, String[]> getParameterMap(String queryString) {
359         return parameterMapFromString(queryString);
360     }
361 
362     public String getProtocol(ActionRequest actionRequest) {
363         return getProtocol(actionRequest.isSecure());
364     }
365 
366     public String getProtocol(boolean secure) {
367         if (!secure) {
368             return Http.HTTP;
369         }
370         else {
371             return Http.HTTPS;
372         }
373     }
374 
375     public String getProtocol(HttpServletRequest request) {
376         return getProtocol(request.isSecure());
377     }
378 
379     public String getProtocol(RenderRequest renderRequest) {
380         return getProtocol(renderRequest.isSecure());
381     }
382 
383     public String getProtocol(String url) {
384         int pos = url.indexOf(Http.PROTOCOL_DELIMITER);
385 
386         if (pos != -1) {
387             return url.substring(0, pos);
388         }
389         else {
390             return Http.HTTP;
391         }
392     }
393 
394     public String getQueryString(String url) {
395         if (Validator.isNull(url)) {
396             return url;
397         }
398 
399         int pos = url.indexOf(StringPool.QUESTION);
400 
401         if (pos == -1) {
402             return StringPool.BLANK;
403         }
404         else {
405             return url.substring(pos + 1, url.length());
406         }
407     }
408 
409     public String getRequestURL(HttpServletRequest request) {
410         return request.getRequestURL().toString();
411     }
412 
413     public boolean hasDomain(String url) {
414         return Validator.isNotNull(getDomain(url));
415     }
416 
417     public boolean hasProtocol(String url) {
418         int pos = url.indexOf(Http.PROTOCOL_DELIMITER);
419 
420         if (pos != -1) {
421             return true;
422         }
423         else {
424             return false;
425         }
426     }
427 
428     public boolean hasProxyConfig() {
429         if (Validator.isNotNull(_PROXY_HOST) && (_PROXY_PORT > 0)) {
430             return true;
431         }
432         else {
433             return false;
434         }
435     }
436 
437     public boolean isNonProxyHost(String host) {
438         if (_nonProxyHostsPattern == null ||
439             _nonProxyHostsPattern.matcher(host).matches()) {
440 
441             return true;
442         }
443         else {
444             return false;
445         }
446     }
447 
448     public boolean isProxyHost(String host) {
449         if (hasProxyConfig() && !isNonProxyHost(host)) {
450             return true;
451         }
452         else {
453             return false;
454         }
455     }
456 
457     public Map<String, String[]> parameterMapFromString(String queryString) {
458         Map<String, String[]> parameterMap =
459             new LinkedHashMap<String, String[]>();
460 
461         if (Validator.isNull(queryString)) {
462             return parameterMap;
463         }
464 
465         Map<String, List<String>> tempParameterMap =
466             new LinkedHashMap<String, List<String>>();
467 
468         StringTokenizer st = new StringTokenizer(
469             queryString, StringPool.AMPERSAND);
470 
471         while (st.hasMoreTokens()) {
472             String token = st.nextToken();
473 
474             if (Validator.isNotNull(token)) {
475                 String[] kvp = StringUtil.split(token, StringPool.EQUAL);
476 
477                 String key = kvp[0];
478 
479                 String value = StringPool.BLANK;
480 
481                 if (kvp.length > 1) {
482                     value = kvp[1];
483                 }
484 
485                 List<String> values = tempParameterMap.get(key);
486 
487                 if (values == null) {
488                     values = new ArrayList<String>();
489 
490                     tempParameterMap.put(key, values);
491                 }
492 
493                 values.add(value);
494             }
495         }
496 
497         for (Map.Entry<String, List<String>> entry :
498                 tempParameterMap.entrySet()) {
499 
500             String key = entry.getKey();
501             List<String> values = entry.getValue();
502 
503             parameterMap.put(key, values.toArray(new String[values.size()]));
504         }
505 
506         return parameterMap;
507     }
508 
509     public String parameterMapToString(Map<String, String[]> parameterMap) {
510         return parameterMapToString(parameterMap, true);
511     }
512 
513     public String parameterMapToString(
514         Map<String, String[]> parameterMap, boolean addQuestion) {
515 
516         StringBuilder sb = new StringBuilder();
517 
518         if (parameterMap.size() > 0) {
519             if (addQuestion) {
520                 sb.append(StringPool.QUESTION);
521             }
522 
523             for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
524                 String name = entry.getKey();
525                 String[] values = entry.getValue();
526 
527                 for (String value : values) {
528                     sb.append(name);
529                     sb.append(StringPool.EQUAL);
530                     sb.append(encodeURL(value));
531                     sb.append(StringPool.AMPERSAND);
532                 }
533             }
534 
535             sb.deleteCharAt(sb.length() - 1);
536         }
537 
538         return sb.toString();
539     }
540 
541     public String protocolize(String url, ActionRequest actionRequest) {
542         return protocolize(url, actionRequest.isSecure());
543     }
544 
545     public String protocolize(String url, boolean secure) {
546         if (secure) {
547             if (url.startsWith(Http.HTTP_WITH_SLASH)) {
548                 return StringUtil.replace(
549                     url, Http.HTTP_WITH_SLASH, Http.HTTPS_WITH_SLASH);
550             }
551         }
552         else {
553             if (url.startsWith(Http.HTTPS_WITH_SLASH)) {
554                 return StringUtil.replace(
555                     url, Http.HTTPS_WITH_SLASH, Http.HTTP_WITH_SLASH);
556             }
557         }
558 
559         return url;
560     }
561 
562     public String protocolize(String url, HttpServletRequest request) {
563         return protocolize(url, request.isSecure());
564     }
565 
566     public String protocolize(String url, RenderRequest renderRequest) {
567         return protocolize(url, renderRequest.isSecure());
568     }
569 
570     public String removeDomain(String url) {
571         url = removeProtocol(url);
572 
573         int pos = url.indexOf(StringPool.SLASH);
574 
575         if (pos > 0) {
576             return url.substring(pos);
577         }
578         else {
579             return url;
580         }
581     }
582 
583     public String removeParameter(String url, String name) {
584         int pos = url.indexOf(StringPool.QUESTION);
585 
586         if (pos == -1) {
587             return url;
588         }
589 
590         String anchor = StringPool.BLANK;
591 
592         int anchorPos = url.indexOf(StringPool.POUND);
593 
594         if (anchorPos != -1) {
595             anchor = url.substring(anchorPos);
596             url = url.substring(0, anchorPos);
597         }
598 
599         StringBuilder sb = new StringBuilder();
600 
601         sb.append(url.substring(0, pos + 1));
602 
603         StringTokenizer st = new StringTokenizer(
604             url.substring(pos + 1, url.length()), StringPool.AMPERSAND);
605 
606         while (st.hasMoreTokens()) {
607             String token = st.nextToken();
608 
609             if (Validator.isNotNull(token)) {
610                 String[] kvp = StringUtil.split(token, StringPool.EQUAL);
611 
612                 String key = kvp[0];
613 
614                 String value = StringPool.BLANK;
615 
616                 if (kvp.length > 1) {
617                     value = kvp[1];
618                 }
619 
620                 if (!key.equals(name)) {
621                     sb.append(key);
622                     sb.append(StringPool.EQUAL);
623                     sb.append(value);
624                     sb.append(StringPool.AMPERSAND);
625                 }
626             }
627         }
628 
629         url = StringUtil.replace(
630             sb.toString(), StringPool.AMPERSAND + StringPool.AMPERSAND,
631             StringPool.AMPERSAND);
632 
633         if (url.endsWith(StringPool.AMPERSAND)) {
634             url = url.substring(0, url.length() - 1);
635         }
636 
637         if (url.endsWith(StringPool.QUESTION)) {
638             url = url.substring(0, url.length() - 1);
639         }
640 
641         return url + anchor;
642     }
643 
644     public String removeProtocol(String url) {
645         if (url.startsWith(Http.HTTP_WITH_SLASH)) {
646             return url.substring(Http.HTTP_WITH_SLASH.length() , url.length());
647         }
648         else if (url.startsWith(Http.HTTPS_WITH_SLASH)) {
649             return url.substring(Http.HTTPS_WITH_SLASH.length() , url.length());
650         }
651         else {
652             return url;
653         }
654     }
655 
656     public String setParameter(String url, String name, boolean value) {
657         return setParameter(url, name, String.valueOf(value));
658     }
659 
660     public String setParameter(String url, String name, double value) {
661         return setParameter(url, name, String.valueOf(value));
662     }
663 
664     public String setParameter(String url, String name, int value) {
665         return setParameter(url, name, String.valueOf(value));
666     }
667 
668     public String setParameter(String url, String name, long value) {
669         return setParameter(url, name, String.valueOf(value));
670     }
671 
672     public String setParameter(String url, String name, short value) {
673         return setParameter(url, name, String.valueOf(value));
674     }
675 
676     public String setParameter(String url, String name, String value) {
677         if (url == null) {
678             return null;
679         }
680 
681         url = removeParameter(url, name);
682 
683         return addParameter(url, name, value);
684     }
685 
686     public byte[] URLtoByteArray(Http.Options options) throws IOException {
687         return URLtoByteArray(
688             options.getLocation(), options.getMethod(), options.getHeaders(),
689             options.getCookies(), options.getAuth(), options.getBody(),
690             options.getParts());
691     }
692 
693     public byte[] URLtoByteArray(String location) throws IOException {
694         Http.Options options = new Http.Options();
695 
696         options.setLocation(location);
697 
698         return URLtoByteArray(options);
699     }
700 
701     public byte[] URLtoByteArray(String location, boolean post)
702         throws IOException {
703 
704         Http.Options options = new Http.Options();
705 
706         options.setLocation(location);
707         options.setPost(post);
708 
709         return URLtoByteArray(options);
710     }
711 
712     /**
713      * @deprecated
714      */
715     public byte[] URLtoByteArray(
716             String location, Cookie[] cookies, Http.Auth auth, Http.Body body,
717             boolean post)
718         throws IOException {
719 
720         Http.Options options = new Http.Options();
721 
722         options.setAuth(auth);
723         options.setBody(body);
724         options.setCookies(cookies);
725         options.setLocation(location);
726         options.setPost(post);
727 
728         return URLtoByteArray(options);
729     }
730 
731     /**
732      * @deprecated
733      */
734     public byte[] URLtoByteArray(
735             String location, Cookie[] cookies, Http.Auth auth,
736             Map<String, String> parts, boolean post)
737         throws IOException {
738 
739         Http.Options options = new Http.Options();
740 
741         options.setAuth(auth);
742         options.setCookies(cookies);
743         options.setLocation(location);
744         options.setParts(parts);
745         options.setPost(post);
746 
747         return URLtoByteArray(options);
748     }
749 
750     public String URLtoString(Http.Options options) throws IOException {
751         return new String(URLtoByteArray(options));
752     }
753 
754     public String URLtoString(String location) throws IOException {
755         return new String(URLtoByteArray(location));
756     }
757 
758     public String URLtoString(String location, boolean post)
759         throws IOException {
760 
761         return new String(URLtoByteArray(location, post));
762     }
763 
764     /**
765      * @deprecated
766      */
767     public String URLtoString(
768             String location, Cookie[] cookies, Http.Auth auth, Http.Body body,
769             boolean post)
770         throws IOException {
771 
772         Http.Options options = new Http.Options();
773 
774         options.setAuth(auth);
775         options.setBody(body);
776         options.setCookies(cookies);
777         options.setLocation(location);
778         options.setPost(post);
779 
780         return new String(URLtoByteArray(options));
781     }
782 
783     /**
784      * @deprecated
785      */
786     public String URLtoString(
787             String location, Cookie[] cookies, Http.Auth auth,
788             Map<String, String> parts, boolean post)
789         throws IOException {
790 
791         Http.Options options = new Http.Options();
792 
793         options.setAuth(auth);
794         options.setCookies(cookies);
795         options.setLocation(location);
796         options.setParts(parts);
797         options.setPost(post);
798 
799         return new String(URLtoByteArray(options));
800     }
801 
802     /**
803      * This method only uses the default Commons HttpClient implementation when
804      * the URL object represents a HTTP resource. The URL object could also
805      * represent a file or some JNDI resource. In that case, the default Java
806      * implementation is used.
807      *
808      * @param  url URL object
809      * @return A string representation of the resource referenced by the
810      *         URL object
811      */
812     public String URLtoString(URL url) throws IOException {
813         String xml = null;
814 
815         if (url != null) {
816             String protocol = url.getProtocol().toLowerCase();
817 
818             if (protocol.startsWith(Http.HTTP) ||
819                 protocol.startsWith(Http.HTTPS)) {
820 
821                 return URLtoString(url.toString());
822             }
823 
824             URLConnection con = url.openConnection();
825 
826             InputStream is = con.getInputStream();
827 
828             ByteArrayOutputStream baos = new ByteArrayOutputStream();
829             byte[] bytes = new byte[512];
830 
831             for (int i = is.read(bytes, 0, 512); i != -1;
832                     i = is.read(bytes, 0, 512)) {
833 
834                 baos.write(bytes, 0, i);
835             }
836 
837             xml = new String(baos.toByteArray());
838 
839             is.close();
840             baos.close();
841         }
842 
843         return xml;
844     }
845 
846     protected void proxifyState(HttpState state, HostConfiguration hostConfig) {
847         Credentials proxyCredentials = _proxyCredentials;
848 
849         String host = hostConfig.getHost();
850 
851         if (isProxyHost(host) && (proxyCredentials != null)) {
852             AuthScope scope = new AuthScope(_PROXY_HOST, _PROXY_PORT, null);
853 
854             state.setProxyCredentials(scope, proxyCredentials);
855         }
856     }
857 
858     protected org.apache.commons.httpclient.Cookie toCommonsCookie(
859         Cookie cookie) {
860 
861         org.apache.commons.httpclient.Cookie commonsCookie =
862             new org.apache.commons.httpclient.Cookie(
863             cookie.getDomain(), cookie.getName(), cookie.getValue(),
864             cookie.getPath(), cookie.getMaxAge(), cookie.getSecure());
865 
866         commonsCookie.setVersion(cookie.getVersion());
867 
868         return commonsCookie;
869     }
870 
871     protected org.apache.commons.httpclient.Cookie[] toCommonsCookies(
872         Cookie[] cookies) {
873 
874         if (cookies == null) {
875             return null;
876         }
877 
878         org.apache.commons.httpclient.Cookie[] commonCookies =
879             new org.apache.commons.httpclient.Cookie[cookies.length];
880 
881         for (int i = 0; i < cookies.length; i++) {
882             commonCookies[i] = toCommonsCookie(cookies[i]);
883         }
884 
885         return commonCookies;
886     }
887 
888     protected Cookie toServletCookie(
889         org.apache.commons.httpclient.Cookie commonsCookie) {
890 
891         Cookie cookie = new Cookie(
892             commonsCookie.getName(), commonsCookie.getValue());
893 
894         cookie.setDomain(commonsCookie.getDomain());
895 
896         Date expiryDate = commonsCookie.getExpiryDate();
897 
898         if (expiryDate != null) {
899             int maxAge =
900                 (int)(expiryDate.getTime() - System.currentTimeMillis());
901 
902             maxAge = maxAge / 1000;
903 
904             if (maxAge > -1) {
905                 cookie.setMaxAge(maxAge);
906             }
907         }
908 
909         cookie.setPath(commonsCookie.getPath());
910         cookie.setSecure(commonsCookie.getSecure());
911         cookie.setVersion(commonsCookie.getVersion());
912 
913         return cookie;
914     }
915 
916     protected Cookie[] toServletCookies(
917         org.apache.commons.httpclient.Cookie[] commonsCookies) {
918 
919         if (commonsCookies == null) {
920             return null;
921         }
922 
923         Cookie[] cookies = new Cookie[commonsCookies.length];
924 
925         for (int i = 0; i < commonsCookies.length; i++) {
926             cookies[i] = toServletCookie(commonsCookies[i]);
927         }
928 
929         return cookies;
930     }
931 
932     protected byte[] URLtoByteArray(
933             String location, Http.Method method, Map<String, String> headers,
934             Cookie[] cookies, Http.Auth auth, Http.Body body, Map<String,
935             String> parts)
936         throws IOException {
937 
938         byte[] bytes = null;
939 
940         HttpMethod httpMethod = null;
941         HttpState httpState = null;
942 
943         try {
944             _cookies.set(null);
945 
946             if (location == null) {
947                 return bytes;
948             }
949             else if (!location.startsWith(Http.HTTP_WITH_SLASH) &&
950                      !location.startsWith(Http.HTTPS_WITH_SLASH)) {
951 
952                 location = Http.HTTP_WITH_SLASH + location;
953             }
954 
955             HostConfiguration hostConfig = getHostConfig(location);
956 
957             HttpClient httpClient = getClient(hostConfig);
958 
959             if ((method == Http.Method.POST) ||
960                 (method == Http.Method.PUT)) {
961 
962                 if (method == Http.Method.POST) {
963                     httpMethod = new PostMethod(location);
964                 }
965                 else {
966                     httpMethod = new PutMethod(location);
967                 }
968 
969                 if (body != null) {
970                     RequestEntity requestEntity = new StringRequestEntity(
971                         body.getContent(), body.getContentType(),
972                         body.getCharset());
973 
974                     EntityEnclosingMethod entityEnclosingMethod =
975                         (EntityEnclosingMethod)httpMethod;
976 
977                     entityEnclosingMethod.setRequestEntity(requestEntity);
978                 }
979                 else if ((parts != null) && (parts.size() > 0) &&
980                          (method == Http.Method.POST)) {
981 
982                     List<NameValuePair> nvpList =
983                         new ArrayList<NameValuePair>();
984 
985                     for (Map.Entry<String, String> entry : parts.entrySet()) {
986                         String key = entry.getKey();
987                         String value = entry.getValue();
988 
989                         if (value != null) {
990                             nvpList.add(new NameValuePair(key, value));
991                         }
992                     }
993 
994                     NameValuePair[] nvpArray = nvpList.toArray(
995                         new NameValuePair[nvpList.size()]);
996 
997                     PostMethod postMethod = (PostMethod)httpMethod;
998 
999                     postMethod.setRequestBody(nvpArray);
1000                }
1001            }
1002            else if (method == Http.Method.DELETE) {
1003                httpMethod = new DeleteMethod(location);
1004            }
1005            else {
1006                httpMethod = new GetMethod(location);
1007            }
1008
1009            if ((method == Http.Method.POST) || (method == Http.Method.PUT) &&
1010                (body != null)) {
1011            }
1012            else if (!_hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
1013                httpMethod.addRequestHeader(
1014                    HttpHeaders.CONTENT_TYPE,
1015                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED);
1016            }
1017
1018            if (!_hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
1019                httpMethod.addRequestHeader(
1020                    HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
1021            }
1022
1023            if (headers != null) {
1024                for (Map.Entry<String, String> header : headers.entrySet()) {
1025                    httpMethod.addRequestHeader(
1026                        header.getKey(), header.getValue());
1027                }
1028            }
1029
1030            httpMethod.getParams().setIntParameter(
1031                HttpClientParams.SO_TIMEOUT, 0);
1032
1033            //httpMethod.setFollowRedirects(true);
1034
1035            httpState = new HttpState();
1036
1037            if ((cookies != null) && (cookies.length > 0)) {
1038                org.apache.commons.httpclient.Cookie[] commonsCookies =
1039                    toCommonsCookies(cookies);
1040
1041                httpState.addCookies(commonsCookies);
1042
1043                httpMethod.getParams().setCookiePolicy(
1044                    CookiePolicy.BROWSER_COMPATIBILITY);
1045            }
1046
1047            if (auth != null) {
1048                httpMethod.setDoAuthentication(true);
1049
1050                httpState.setCredentials(
1051                    new AuthScope(
1052                        auth.getHost(), auth.getPort(), auth.getRealm()),
1053                    new UsernamePasswordCredentials(
1054                        auth.getUsername(), auth.getPassword()));
1055            }
1056
1057            proxifyState(httpState, hostConfig);
1058
1059            httpClient.executeMethod(hostConfig, httpMethod, httpState);
1060
1061            Header locationHeader = httpMethod.getResponseHeader("location");
1062
1063            if ((locationHeader != null) && !locationHeader.equals(location)) {
1064                return URLtoByteArray(
1065                    locationHeader.getValue(), Http.Method.GET, headers,
1066                    cookies, auth, body, parts);
1067            }
1068
1069            InputStream is = httpMethod.getResponseBodyAsStream();
1070
1071            if (is != null) {
1072                bytes = FileUtil.getBytes(is);
1073
1074                is.close();
1075            }
1076
1077            return bytes;
1078        }
1079        finally {
1080            try {
1081                if (httpState != null) {
1082                    _cookies.set(toServletCookies(httpState.getCookies()));
1083                }
1084            }
1085            catch (Exception e) {
1086                _log.error(e, e);
1087            }
1088
1089            try {
1090                if (httpMethod != null) {
1091                    httpMethod.releaseConnection();
1092                }
1093            }
1094            catch (Exception e) {
1095                _log.error(e, e);
1096            }
1097        }
1098    }
1099
1100    private boolean _hasRequestHeader(HttpMethod httpMethod, String name) {
1101        if (httpMethod.getRequestHeaders(name).length == 0) {
1102            return false;
1103        }
1104        else {
1105            return true;
1106        }
1107    }
1108
1109    private static final String _DEFAULT_USER_AGENT =
1110        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
1111
1112    private static final int _MAX_CONNECTIONS_PER_HOST = GetterUtil.getInteger(
1113        PropsUtil.get(HttpImpl.class.getName() + ".max.connections.per.host"),
1114        2);
1115
1116    private static final int _MAX_TOTAL_CONNECTIONS = GetterUtil.getInteger(
1117        PropsUtil.get(HttpImpl.class.getName() + ".max.total.connections"),
1118        20);
1119
1120    private static final String _NON_PROXY_HOSTS =
1121        SystemProperties.get("http.nonProxyHosts");
1122
1123    private static final String _PROXY_AUTH_TYPE = GetterUtil.getString(
1124        PropsUtil.get(HttpImpl.class.getName() + ".proxy.auth.type"));
1125
1126    private static final String _PROXY_HOST = GetterUtil.getString(
1127        SystemProperties.get("http.proxyHost"));
1128
1129    private static final String _PROXY_NTLM_DOMAIN = GetterUtil.getString(
1130        PropsUtil.get(HttpImpl.class.getName() + ".proxy.ntlm.domain"));
1131
1132    private static final String _PROXY_NTLM_HOST = GetterUtil.getString(
1133        PropsUtil.get(HttpImpl.class.getName() + ".proxy.ntlm.host"));
1134
1135    private static final String _PROXY_PASSWORD = GetterUtil.getString(
1136        PropsUtil.get(HttpImpl.class.getName() + ".proxy.password"));
1137
1138    private static final int _PROXY_PORT = GetterUtil.getInteger(
1139        SystemProperties.get("http.proxyPort"));
1140
1141    private static final String _PROXY_USERNAME = GetterUtil.getString(
1142        PropsUtil.get(HttpImpl.class.getName() + ".proxy.username"));
1143
1144    private static final int _TIMEOUT = GetterUtil.getInteger(
1145        PropsUtil.get(HttpImpl.class.getName() + ".timeout"), 5000);
1146
1147    private static Log _log = LogFactoryUtil.getLog(HttpImpl.class);
1148
1149    private static ThreadLocal<Cookie[]> _cookies = new ThreadLocal<Cookie[]>();
1150
1151    private HttpClient _client = new HttpClient();
1152    private Pattern _nonProxyHostsPattern;
1153    private HttpClient _proxyClient = new HttpClient();
1154    private Credentials _proxyCredentials;
1155
1156}