Merge branch 'master' of \\\pk2010\Pithos\
[pithos-ms-client] / trunk / Pithos.Network / RestClient.cs
index ebcae22..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>
 // -----------------------------------------------------------------------
 
@@ -13,6 +44,7 @@ using System.Runtime.Serialization;
 using System.Threading.Tasks;
 using log4net;
 
+
 namespace Pithos.Network
 {
     using System;
@@ -83,11 +115,13 @@ namespace Pithos.Network
             this.Proxy = other.Proxy;
         }
 
+
         protected override WebRequest GetWebRequest(Uri address)
         {
             TimedOut = false;
-            var webRequest = base.GetWebRequest(address);
+            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;
@@ -106,50 +140,73 @@ namespace Pithos.Network
 
         public DateTime? IfModifiedSince { get; set; }
 
+        //Asynchronous version
         protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
         {
-            return ProcessResponse(()=>base.GetWebResponse(request, result));
-        }
+            Log.InfoFormat("ASYNC [{0}] {1}",request.Method, request.RequestUri);
+            HttpWebResponse response = null;
+
+            try
+            {
+                response = (HttpWebResponse)base.GetWebResponse(request, result);
+            }
+            catch (WebException exc)
+            {
+                if (!TryGetResponse(exc, out response))
+                    throw;
+            }
+
+            StatusCode = response.StatusCode;
+            LastModified = response.LastModified;
+            StatusDescription = response.StatusDescription;
+            return response;
 
-        protected override WebResponse GetWebResponse(WebRequest request)
-        {
-            return ProcessResponse(() => base.GetWebResponse(request));
         }
+      
 
-        private WebResponse ProcessResponse(Func<WebResponse> getResponse)
+        //Synchronous version
+        protected override WebResponse GetWebResponse(WebRequest request)
         {
+            HttpWebResponse response = null;
             try
-            {
-                var response = (HttpWebResponse)getResponse();
-                StatusCode = response.StatusCode;
-                LastModified = response.LastModified;
-                StatusDescription = response.StatusDescription;
-                return response;
+            {                                
+                response = (HttpWebResponse)base.GetWebResponse(request);
             }
             catch (WebException exc)
             {
-                if (exc.Response != null)
-                {
-                    var response = (exc.Response as HttpWebResponse);
-                    if (AllowedStatusCodes.Contains(response.StatusCode))
-                    {
-                        StatusCode = response.StatusCode;
-                        LastModified = response.LastModified;
-                        StatusDescription = response.StatusDescription;
+                if (!TryGetResponse(exc, out response))
+                    throw;
+            }
 
-                        return response;
-                    }
-                    if (exc.Response.ContentLength > 0)
-                    {
-                        string content = GetContent(exc.Response);
-                        Log.ErrorFormat(content);
-                    }
-                }
-                throw;
+            StatusCode = response.StatusCode;
+            LastModified = response.LastModified;
+            StatusDescription = response.StatusDescription;
+            return response;
+        }
+
+        private bool TryGetResponse(WebException exc, out HttpWebResponse response)
+        {
+            response = null;
+            //Fail on empty response
+            if (exc.Response == null)
+                return false;
+
+            response = (exc.Response as HttpWebResponse);
+            //Succeed on allowed status codes
+            if (AllowedStatusCodes.Contains(response.StatusCode))
+                return true;
+
+            //Does the response have any content to log?
+            if (exc.Response.ContentLength > 0)
+            {
+                var content = LogContent(exc.Response);
+                Log.ErrorFormat(content);
             }
+            return false;
         }
 
-        private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified};
+        private readonly List<HttpStatusCode> _allowedStatusCodes=new List<HttpStatusCode>{HttpStatusCode.NotModified};        
+
         public List<HttpStatusCode> AllowedStatusCodes
         {
             get
@@ -160,23 +217,29 @@ 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)
         {
+            
             if (address == null)
                 throw new ArgumentNullException("address");
 
@@ -185,12 +248,11 @@ namespace Pithos.Network
             TraceStart("GET",actualAddress);            
             
             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)
@@ -199,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)
@@ -219,17 +292,27 @@ namespace Pithos.Network
             RetryWithoutContent(address, retries, "DELETE");
         }
 
-        public string GetHeaderValue(string headerName)
+        public string GetHeaderValue(string headerName,bool optional=false)
         {
             if (this.ResponseHeaders==null)
                 throw new InvalidOperationException("ResponseHeaders are null");
             Contract.EndContractBlock();
 
             var values=this.ResponseHeaders.GetValues(headerName);
-            if (values == null)
-                throw new WebException(String.Format("The {0}  header is missing", headerName));
-            else
+            if (values != null)
                 return values[0];
+
+            if (optional)            
+                return null;            
+            //A required header was not found
+            throw new WebException(String.Format("The {0}  header is missing", headerName));
+        }
+
+        public void SetNonEmptyHeaderValue(string headerName, string value)
+        {
+            if (String.IsNullOrWhiteSpace(value))
+                return;
+            Headers.Add(headerName,value);
         }
 
         private void RetryWithoutContent(string address, int retries, string method)
@@ -252,9 +335,20 @@ namespace Pithos.Network
                 TraceStart(method, uriString);
                 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);
-                StatusCode = response.StatusCode;
-                StatusDescription = response.StatusDescription;                
+                try
+                {
+                    LastModified = response.LastModified;
+                    StatusCode = response.StatusCode;
+                    StatusDescription = response.StatusDescription;
+                }
+                finally
+                {
+                    response.Close();
+                }
                 
 
                 return 0;
@@ -275,7 +369,7 @@ namespace Pithos.Network
                 {
                     Log.ErrorFormat("[{0}] FAILED for {1} with \n{2}", method, address, exc);
                 }
-                throw;
+                throw exc;
 
             }
             catch(Exception ex)
@@ -439,6 +533,21 @@ namespace Pithos.Network
             var builder = new UriBuilder(String.Join("/", BaseAddress, container, objectName));
             return builder;
         }
+
+        public Dictionary<string, string> GetMeta(string metaPrefix)
+        {
+            if (String.IsNullOrWhiteSpace(metaPrefix))
+                throw new ArgumentNullException("metaPrefix");
+            Contract.EndContractBlock();
+
+            var keys = ResponseHeaders.AllKeys.AsQueryable();
+            var dict = (from key in keys
+                        where key.StartsWith(metaPrefix)
+                        let name = key.Substring(metaPrefix.Length)
+                        select new { Name = name, Value = ResponseHeaders[key] })
+                        .ToDictionary(t => t.Name, t => t.Value);
+            return dict;
+        }
     }
 
     public class RetryException:Exception