Added missing converter
[pithos-ms-client] / trunk / Pithos.Network / TreeHash.cs
index 2f036b1..e9a9e6a 100644 (file)
@@ -1,11 +1,54 @@
+#region
+/* -----------------------------------------------------------------------
+ * <copyright file="TreeHash.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
 using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
+using System.Diagnostics.Contracts;
 using System.IO;
 using System.Text;
 using System.Threading.Tasks;
-using Newtonsoft.Json;
+
 using System.Linq;
+using Newtonsoft.Json;
 using Newtonsoft.Json.Linq;
 
 namespace Pithos.Network
@@ -16,7 +59,27 @@ namespace Pithos.Network
         private const int DEFAULT_BLOCK_SIZE = 4*1024*1024;
         public string BlockHash { get; set; }
         public int BlockSize { get; set; }
-        public long Bytes { get; set; }
+        
+        private long _bytes;
+        public long Bytes
+        {
+            get
+            {
+                Contract.Ensures(Contract.Result<long>() >= 0);
+                return _bytes;
+            }
+            set
+            {
+                if (value<0)
+                    throw new ArgumentOutOfRangeException("Bytes");
+                Contract.Requires(value >= 0);
+                Contract.EndContractBlock();
+                
+                _bytes = value;
+            }
+        }
+        
+
 
         public Guid FileId { get; set; }
 
@@ -26,18 +89,26 @@ namespace Pithos.Network
             get { return _topHash.Value; }
         }
 
-        private IList<byte[]> _hashes;
+        private IList<byte[]> _hashes=new List<byte[]>();
+
         public IList<byte[]> Hashes
         {
             get { return _hashes; }
             set
             {
                 _hashes = value;
-                _topHash.Force();                
+                _topHash.Force();
             }
         }
 
-        public TreeHash(string algorithm)
+        [ContractInvariantMethod]
+        private void Invariants()
+        {
+            Contract.Invariant(_bytes>=0);
+        }
+        
+
+       public TreeHash(string algorithm)
         {
             BlockHash = algorithm;            
             _topHash = new Lazy<byte[]>(() =>
@@ -102,30 +173,29 @@ namespace Pithos.Network
         }
 
         //Saves the Json representation to a file
-        public Task Save(string filePath)
+        public async Task Save(string filePath)
         {
+            if (String.IsNullOrWhiteSpace(filePath))
+                throw new ArgumentNullException("filePath");
+
             var fileName = FileId.ToString("N");
             var path = Path.Combine(filePath, fileName);
             if (!Directory.Exists(filePath))
                 Directory.CreateDirectory(filePath);
-
-            return Task.Factory
-                .StartNew<string>(ToJson)
-                .ContinueWith(jsonTask=> 
-                FileAsync.WriteAllText(path, jsonTask.Result)).Unwrap();
+            
+            var json=await TaskEx.Run(()=>ToJson());
+            await FileAsync.WriteAllText(path, json);
         }
 
-        public static Task<TreeHash> LoadTreeHash(string dataPath,Guid fileId)
+        public static async Task<TreeHash> LoadTreeHash(string dataPath,Guid fileId)
         {
             var fileName = fileId.ToString("N");
             var path = Path.Combine(dataPath, fileName);
-            return FileAsync.ReadAllText(path).ContinueWith(loadTask =>
-            {
-                var json = loadTask.Result;
-                var treeHash = Parse(json);
-                treeHash.FileId = fileId;
-                return treeHash;
-            });
+            
+            var json=await FileAsync.ReadAllText(path);
+            var treeHash = Parse(json);
+            treeHash.FileId = fileId;
+            return treeHash;
         }
 
         public static TreeHash Empty = new TreeHash(DEFAULT_HASH_ALGORITHM)
@@ -139,9 +209,12 @@ namespace Pithos.Network
         public static TreeHash Parse(string json)
         {
             if (String.IsNullOrWhiteSpace(json))
-                return Empty;
+                return Empty;            
 
             var value = JsonConvert.DeserializeObject<JObject>(json);
+            if (value==null)
+                throw new ArgumentException("The json parameter doesn't contain any json data","json");
+            Contract.Assume(value!=null);
 
             var blockHash = (string) value["block_hash"];
             var size = value.Value<int>("block_size");