Added option to disable certificate checking
[pithos-ms-client] / trunk / Pithos.Network / CloudFilesClient.cs
index 63d4211..e11b4d6 100644 (file)
@@ -1,40 +1,44 @@
-// -----------------------------------------------------------------------
-// <copyright file="CloudFilesClient.cs" company="GRNET">
-// Copyright 2011 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>
-// -----------------------------------------------------------------------
-
+#region
+/* -----------------------------------------------------------------------
+ * <copyright file="CloudFilesClient.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>
+ * -----------------------------------------------------------------------
+ */
+#endregion
 
 // **CloudFilesClient** provides a simple client interface to CloudFiles and Pithos
 //
@@ -50,6 +54,7 @@ using System.Diagnostics.Contracts;
 using System.IO;
 using System.Linq;
 using System.Net;
+using System.Reflection;
 using System.Security.Cryptography;
 using System.Text;
 using System.Threading.Tasks;
@@ -62,6 +67,8 @@ namespace Pithos.Network
     [Export(typeof(ICloudClient))]
     public class CloudFilesClient:ICloudClient
     {
+        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
         //CloudFilesClient uses *_baseClient* internally to communicate with the server
         //RestClient provides a REST-friendly interface over the standard WebClient.
         private RestClient _baseClient;
@@ -93,7 +100,7 @@ namespace Pithos.Network
 
         protected Uri RootAddressUri { get; set; }
 
-        private WebProxy _proxy;
+       /* private WebProxy _proxy;
         public WebProxy Proxy
         {
             get { return _proxy; }
@@ -104,7 +111,7 @@ namespace Pithos.Network
                     _baseClient.Proxy = value;                
             }
         }
-
+*/
 
         /* private Uri _proxy;
         public Uri Proxy
@@ -132,7 +139,6 @@ namespace Pithos.Network
         public bool UsePithos { get; set; }
 
 
-        private static readonly ILog Log = LogManager.GetLogger("CloudFilesClient");
 
         public CloudFilesClient(string userName, string apiKey)
         {
@@ -148,14 +154,13 @@ namespace Pithos.Network
             Contract.Ensures(StorageUrl != null);
             Contract.Ensures(_baseClient != null);
             Contract.Ensures(RootAddressUri != null);
-            Contract.EndContractBlock();
+            Contract.EndContractBlock();          
 
             _baseClient = new RestClient
             {
                 BaseAddress = accountInfo.StorageUri.ToString(),
                 Timeout = 10000,
                 Retries = 3,
-                Proxy=this.Proxy
             };
             StorageUrl = accountInfo.StorageUri;
             Token = accountInfo.Token;
@@ -190,8 +195,8 @@ namespace Pithos.Network
 
             using (var authClient = new RestClient{BaseAddress=AuthenticationUrl})
             {                
-                if (Proxy != null)
-                    authClient.Proxy = Proxy;
+               /* if (Proxy != null)
+                    authClient.Proxy = Proxy;*/
 
                 Contract.Assume(authClient.Headers!=null);
 
@@ -211,7 +216,7 @@ namespace Pithos.Network
                     BaseAddress = storageUrl,
                     Timeout = 10000,
                     Retries = 3,
-                    Proxy=Proxy
+                    //Proxy=Proxy
                 };
 
                 StorageUrl = new Uri(storageUrl);
@@ -314,18 +319,21 @@ namespace Pithos.Network
             using (ThreadContext.Stacks["Share"].Push("List Objects"))
             {
                 if (Log.IsDebugEnabled) Log.DebugFormat("START");
-
+                //'since' is not used here because we need to have ListObjects return a NoChange result
+                //for all shared accounts,containers
+                var accounts = ListSharingAccounts();
+                var items = from account in accounts 
+                            let containers = ListContainers(account.name) 
+                            from container in containers 
+                            select ListObjects(account.name, container.Name,since);
+                var objects=items.SelectMany(r=> r).ToList();
+/*
                 var objects = new List<ObjectInfo>();
-                var accounts = ListSharingAccounts(since);
-                foreach (var account in accounts)
+                foreach (var containerObjects in items)
                 {
-                    var containers = ListContainers(account.name);
-                    foreach (var container in containers)
-                    {
-                        var containerObjects = ListObjects(account.name, container.Name);
-                        objects.AddRange(containerObjects);
-                    }
+                    objects.AddRange(containerObjects);
                 }
+*/
                 if (Log.IsDebugEnabled) Log.DebugFormat("END");
                 return objects;
             }
@@ -600,6 +608,8 @@ namespace Pithos.Network
 
                     client.AssertStatusOK("ListObjects failed");
 
+                    if (client.StatusCode==HttpStatusCode.NotModified)
+                        return new[]{new NoModificationInfo(account,container)};
                     //If the result is empty, return an empty list,
                     var infos = String.IsNullOrWhiteSpace(content)
                                     ? new List<ObjectInfo>()
@@ -610,21 +620,22 @@ namespace Pithos.Network
                     {
                         info.Container = container;
                         info.Account = account;
+                        info.StorageUri = this.StorageUrl;
                     }
-                    if (Log.IsDebugEnabled) Log.DebugFormat("START");
+                    if (Log.IsDebugEnabled) Log.DebugFormat("END");
                     return infos;
                 }
             }
         }
 
-
-
         public IList<ObjectInfo> ListObjects(string account, string container, string folder, DateTime? since = null)
         {
             if (String.IsNullOrWhiteSpace(container))
                 throw new ArgumentNullException("container");
+/*
             if (String.IsNullOrWhiteSpace(folder))
                 throw new ArgumentNullException("folder");
+*/
             Contract.EndContractBlock();
 
             using (ThreadContext.Stacks["Objects"].Push("List"))
@@ -643,8 +654,17 @@ namespace Pithos.Network
                     var content = client.DownloadStringWithRetry(container, 3);
                     client.AssertStatusOK("ListObjects failed");
 
-                    var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
+                    if (client.StatusCode==HttpStatusCode.NotModified)
+                        return new[]{new NoModificationInfo(account,container,folder)};
 
+                    var infos = JsonConvert.DeserializeObject<IList<ObjectInfo>>(content);
+                    foreach (var info in infos)
+                    {
+                        info.Account = account;
+                        if (info.Container == null)
+                            info.Container = container;
+                        info.StorageUri = this.StorageUrl;
+                    }
                     if (Log.IsDebugEnabled) Log.DebugFormat("END");
                     return infos;
                 }
@@ -1015,7 +1035,8 @@ namespace Pithos.Network
             client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
             var jsonHash = hash.ToJson();
             var uploadTask=client.UploadStringTask(uri, "PUT", jsonHash);
-            
+            if (Log.IsDebugEnabled)
+                Log.DebugFormat("Hashes:\r\n{0}", jsonHash);
             return uploadTask.ContinueWith(t =>
             {
 
@@ -1034,28 +1055,28 @@ namespace Pithos.Network
                 {
                     var ex = t.Exception.InnerException;
                     var we = ex as WebException;
+                    
                     var response = we.Response as HttpWebResponse;
                     if (response!=null && response.StatusCode==HttpStatusCode.Conflict)
                     {
                         //In case of 409 the missing parts will be in the response content                        
                         using (var stream = response.GetResponseStream())
-                        using(var reader=new StreamReader(stream))
+                        using(var reader=stream.GetLoggedReader(Log,response.ContentLength))
                         {
-                            Debug.Assert(stream.Position == 0);
-                            //We need to cleanup the content before returning it because it contains
+                            //We used to have to cleanup the content before returning it because it contains
                             //error content after the list of hashes
-                            var hashes = new List<string>();
-                            string line=null;
-                            //All lines up to the first empty line are hashes
-                            while(!String.IsNullOrWhiteSpace(line=reader.ReadLine()))
-                            {
-                                hashes.Add(line);
-                            }
-
+                            //
+                            //As of 30/1/2012, the result is a proper Json array so we don't need to read the content
+                            //line by line
+                            
+                            var serializer = new JsonSerializer();                            
+                            serializer.Error += (sender, args) => Log.ErrorFormat("Deserialization error at [{0}] [{1}]", args.ErrorContext.Error, args.ErrorContext.Member);
+                            var hashes = (List<string>)serializer.Deserialize(reader, typeof(List<string>));
                             return hashes;
                         }                        
                     }                    
                     //Any other status code is unexpected and the exception should be rethrown
+                    Log.LogError(response);
                     throw ex;
                     
                 }
@@ -1067,6 +1088,7 @@ namespace Pithos.Network
 
         }
 
+        
         public Task<byte[]> GetBlock(string account, string container, Uri relativeUrl, long start, long? end)
         {
             if (String.IsNullOrWhiteSpace(Token))
@@ -1345,6 +1367,7 @@ namespace Pithos.Network
 
                 client.Headers.Add("X-Move-From", sourceUrl);
                 client.AllowedStatusCodes.Add(HttpStatusCode.NotFound);
+                Log.InfoFormat("[TRASH] [{0}] to [{1}]",sourceUrl,targetUrl);
                 client.PutWithRetry(targetUrl, 3);
 
                 var expectedCodes = new[] {HttpStatusCode.OK, HttpStatusCode.NoContent, HttpStatusCode.Created,HttpStatusCode.NotFound};
@@ -1359,7 +1382,13 @@ namespace Pithos.Network
             return new WebException(String.Format("{0} failed with unexpected status code {1}", operation, statusCode));
         }
 
-        
+
+/*
+        public IEnumerable<ObjectInfo> ListDirectories(ContainerInfo container)
+        {
+            var directories=this.ListObjects(container.Account, container.Name, "/");
+        }
+*/
     }
 
     public class ShareAccountInfo