Merge branch 'master' of \\\pk2010\Pithos\
[pithos-ms-client] / trunk / Pithos.Network / RestClient.cs
index a2c5e90..d196752 100644 (file)
@@ -1,6 +1,37 @@
 // -----------------------------------------------------------------------
-// <copyright file="RestClient.cs" company="Microsoft">
-// TODO: Update copyright text.
+// <copyright file="RestClient.cs" company="GRNet">
+// Copyright 2011-2012 GRNET S.A. All rights reserved.
+// 
+// Redistribution and use in source and binary forms, with or
+// without modification, are permitted provided that the following
+// conditions are met:
+// 
+//   1. Redistributions of source code must retain the above
+//      copyright notice, this list of conditions and the following
+//      disclaimer.
+// 
+//   2. Redistributions in binary form must reproduce the above
+//      copyright notice, this list of conditions and the following
+//      disclaimer in the documentation and/or other materials
+//      provided with the distribution.
+// 
+// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
+// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
+// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+// 
+// The views and conclusions contained in the software and
+// documentation are those of the authors and should not be
+// interpreted as representing official policies, either expressed
+// or implied, of GRNET S.A.
 // </copyright>
 // -----------------------------------------------------------------------
 
@@ -85,31 +116,12 @@ namespace Pithos.Network
         }
 
 
-        private WebHeaderCollection _responseHeaders;
-
-        public new WebHeaderCollection ResponseHeaders
-        {
-            get
-            {
-                if (base.ResponseHeaders==null)
-                {
-                    return _responseHeaders;
-                }
-                else
-                {
-                    _responseHeaders = null;
-                    return base.ResponseHeaders;   
-                }
-                
-            }
-
-            set { _responseHeaders = value; }
-        } 
         protected override WebRequest GetWebRequest(Uri address)
         {
             TimedOut = false;
             var webRequest = base.GetWebRequest(address);            
             var request = (HttpWebRequest)webRequest;
+            request.ServicePoint.ConnectionLimit = 50;
             if (IfModifiedSince.HasValue)
                 request.IfModifiedSince = IfModifiedSince.Value;
             request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
@@ -187,7 +199,7 @@ namespace Pithos.Network
             //Does the response have any content to log?
             if (exc.Response.ContentLength > 0)
             {
-                var content = GetContent(exc.Response);
+                var content = LogContent(exc.Response);
                 Log.ErrorFormat(content);
             }
             return false;
@@ -205,19 +217,24 @@ namespace Pithos.Network
 
         public DateTime LastModified { get; private set; }
 
-        private static string GetContent(WebResponse webResponse)
+        private static string LogContent(WebResponse webResponse)
         {
             if (webResponse == null)
                 throw new ArgumentNullException("webResponse");
             Contract.EndContractBlock();
 
-            string content;
-            using (var stream = webResponse.GetResponseStream())
-            using (var reader = new StreamReader(stream))
+            //The response stream must be copied to avoid affecting other code by disposing of the 
+            //original response stream.
+            var stream = webResponse.GetResponseStream();            
+            using(var memStream=new MemoryStream())
+            using (var reader = new StreamReader(memStream))
             {
-                content = reader.ReadToEnd();
+                stream.CopyTo(memStream);                
+                string content = reader.ReadToEnd();
+
+                stream.Seek(0,SeekOrigin.Begin);
+                return content;
             }
-            return content;
         }
 
         public string DownloadStringWithRetry(string address,int retries=0)
@@ -232,10 +249,10 @@ namespace Pithos.Network
             
             var actualRetries = (retries == 0) ? Retries : retries;
 
-            
+            var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress);
+
             var task = Retry(() =>
-            {
-                var uriString = String.Join("/", BaseAddress.TrimEnd('/'), actualAddress);                
+            {                
                 var content = base.DownloadString(uriString);
 
                 if (StatusCode == HttpStatusCode.NoContent)
@@ -244,8 +261,19 @@ namespace Pithos.Network
 
             }, actualRetries);
 
-            var result = task.Result;
-            return result;
+            try
+            {
+                var result = task.Result;
+                return result;
+
+            }
+            catch (AggregateException exc)
+            {
+                //If the task fails, propagate the original exception
+                if (exc.InnerException!=null)
+                    throw exc.InnerException;
+                throw;
+            }
         }
 
         public void Head(string address,int retries=0)
@@ -308,15 +336,20 @@ namespace Pithos.Network
                 if (method == "PUT")
                     request.ContentLength = 0;
 
+                //Have to use try/finally instead of using here, because WebClient needs a valid WebResponse object
+                //in order to return response headers
                 var response = (HttpWebResponse)GetWebResponse(request);
-                //var response = (HttpWebResponse)request.GetResponse();
+                try
+                {
+                    LastModified = response.LastModified;
+                    StatusCode = response.StatusCode;
+                    StatusDescription = response.StatusDescription;
+                }
+                finally
+                {
+                    response.Close();
+                }
                 
-                //ResponseHeaders= response.Headers;
-
-                LastModified = response.LastModified;
-                StatusCode = response.StatusCode;
-                StatusDescription = response.StatusDescription;
-                response.Close();
 
                 return 0;
             }, actualRetries);