/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public static Couchbase.Lite.Document CreateTask(Database database, string title, 
     Bitmap image, string listId)
 {
     SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
         );
     Calendar calendar = GregorianCalendar.GetInstance();
     string currentTimeString = dateFormatter.Format(calendar.GetTime());
     IDictionary<string, object> properties = new Dictionary<string, object>();
     properties.Put("type", DocType);
     properties.Put("title", title);
     properties.Put("checked", false);
     properties.Put("created_at", currentTimeString);
     properties.Put("list_id", listId);
     Couchbase.Lite.Document document = database.CreateDocument();
     UnsavedRevision revision = document.CreateRevision();
     revision.SetUserProperties(properties);
     if (image != null)
     {
         ByteArrayOutputStream @out = new ByteArrayOutputStream();
         image.Compress(Bitmap.CompressFormat.Jpeg, 50, @out);
         ByteArrayInputStream @in = new ByteArrayInputStream(@out.ToByteArray());
         revision.SetAttachment("image", "image/jpg", @in);
     }
     revision.Save();
     return document;
 }
Example #2
0
		// test support
		private void Init(string msg)
		{
			rawIn = new ByteArrayInputStream(Constants.EncodeASCII(msg));
			@in = new PacketLineIn(rawIn);
		}
        internal static Document CreateDocWithAttachment(Database database, string attachmentName, string content)
        {
            var properties = new Dictionary<string, object>();
            properties.Put("foo", "bar");

            var doc = CreateDocumentWithProperties(database, properties);
            var rev = doc.CurrentRevision;
            var attachment = rev.GetAttachment(attachmentName);
            Assert.AreEqual(rev.Attachments.Count(), 0);
            Assert.AreEqual(rev.AttachmentNames.Count(), 0);
            Assert.IsNull(attachment);

            var body = new ByteArrayInputStream(Encoding.UTF8.GetBytes(content));
            var rev2 = doc.CreateRevision();
            rev2.SetAttachment(attachmentName, "text/plain; charset=utf-8", body);
            var rev3 = rev2.Save();
            Assert.IsNotNull(rev3);
            Assert.AreEqual(rev3.Attachments.Count(), 1);
            Assert.AreEqual(rev3.AttachmentNames.Count(), 1);

            attachment = rev3.GetAttachment(attachmentName);
            Assert.IsNotNull(attachment);
            Assert.AreEqual(doc, attachment.Document);
            Assert.AreEqual(attachmentName, attachment.Name);

            var attNames = new List<string>();
            attNames.AddItem(attachmentName);
            Assert.AreEqual(rev3.AttachmentNames, attNames);
            Assert.AreEqual("text/plain; charset=utf-8", attachment.ContentType);
            Assert.AreEqual(Encoding.UTF8.GetString(attachment.Content.ToArray()), content);
            Assert.AreEqual(Encoding.UTF8.GetBytes(content).Length, attachment.Length);

            attachment.Dispose();
            return doc;
        }          
		/// <exception cref="System.IO.IOException"></exception>
		private void AssertNoCrLfHelper(string expect, string input)
		{
			byte[] inbytes = Sharpen.Runtime.GetBytesForString(input);
			byte[] expectBytes = Sharpen.Runtime.GetBytesForString(expect);
			for (int i = 0; i < 5; ++i)
			{
				byte[] buf = new byte[i];
				InputStream @in = new ByteArrayInputStream(inbytes);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				OutputStream @out = new AutoCRLFOutputStream(bos);
				if (i > 0)
				{
					int n;
					while ((n = @in.Read(buf)) >= 0)
					{
						@out.Write(buf, 0, n);
					}
				}
				else
				{
					int c;
					while ((c = @in.Read()) != -1)
					{
						@out.Write(c);
					}
				}
				@out.Flush();
				@in.Close();
				@out.Close();
				byte[] actualBytes = bos.ToByteArray();
				NUnit.Framework.Assert.AreEqual(Encode(expectBytes), Encode(actualBytes), "bufsize="
					 + i);
			}
		}
		/// <summary>Regression test for https://github.com/couchbase/couchbase-lite-android-core/issues/70
		/// 	</summary>
		/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
		/// <exception cref="System.IO.IOException"></exception>
		public virtual void TestAttachmentDisappearsAfterSave()
		{
			// create a doc with an attachment
			Document doc = database.CreateDocument();
			string content = "This is a test attachment!";
			ByteArrayInputStream body = new ByteArrayInputStream(Sharpen.Runtime.GetBytesForString
				(content));
			UnsavedRevision rev = doc.CreateRevision();
			rev.SetAttachment("index.html", "text/plain; charset=utf-8", body);
			rev.Save();
			// make sure the doc's latest revision has the attachment
			IDictionary<string, object> attachments = (IDictionary)doc.GetCurrentRevision().GetProperty
				("_attachments");
			NUnit.Framework.Assert.IsNotNull(attachments);
			NUnit.Framework.Assert.AreEqual(1, attachments.Count);
			// make sure the rev has the attachment
			attachments = (IDictionary)rev.GetProperty("_attachments");
			NUnit.Framework.Assert.IsNotNull(attachments);
			NUnit.Framework.Assert.AreEqual(1, attachments.Count);
			// create new properties to add
			IDictionary<string, object> properties = new Dictionary<string, object>();
			properties.Put("foo", "bar");
			// make sure the new rev still has the attachment
			UnsavedRevision rev2 = doc.CreateRevision();
			rev2.GetProperties().PutAll(properties);
			rev2.Save();
			attachments = (IDictionary)rev2.GetProperty("_attachments");
			NUnit.Framework.Assert.IsNotNull(attachments);
			NUnit.Framework.Assert.AreEqual(1, attachments.Count);
		}
Example #6
0
		public virtual void TestInCoreLimit_SwitchOnCopy()
		{
			TemporaryBuffer b = new TemporaryBuffer.LocalFile();
			byte[] test = new TestRng(Sharpen.Extensions.GetTestName()).NextBytes(TemporaryBuffer
				.DEFAULT_IN_CORE_LIMIT * 2);
			try
			{
				ByteArrayInputStream @in = new ByteArrayInputStream(test, TemporaryBuffer.DEFAULT_IN_CORE_LIMIT
					, test.Length - TemporaryBuffer.DEFAULT_IN_CORE_LIMIT);
				b.Write(test, 0, TemporaryBuffer.DEFAULT_IN_CORE_LIMIT);
				b.Copy(@in);
				b.Close();
				NUnit.Framework.Assert.AreEqual(test.Length, b.Length());
				{
					byte[] r = b.ToByteArray();
					NUnit.Framework.Assert.IsNotNull(r);
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
				{
					ByteArrayOutputStream o = new ByteArrayOutputStream();
					b.WriteTo(o, null);
					o.Close();
					byte[] r = o.ToByteArray();
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
			}
			finally
			{
				b.Destroy();
			}
		}
Example #7
0
		public virtual void TestOneBlockAndHalf_Copy()
		{
			TemporaryBuffer b = new TemporaryBuffer.LocalFile();
			byte[] test = new TestRng(Sharpen.Extensions.GetTestName()).NextBytes(TemporaryBuffer.Block
				.SZ * 3 / 2);
			try
			{
				ByteArrayInputStream @in = new ByteArrayInputStream(test);
				b.Write(@in.Read());
				b.Copy(@in);
				b.Close();
				NUnit.Framework.Assert.AreEqual(test.Length, b.Length());
				{
					byte[] r = b.ToByteArray();
					NUnit.Framework.Assert.IsNotNull(r);
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
				{
					ByteArrayOutputStream o = new ByteArrayOutputStream();
					b.WriteTo(o, null);
					o.Close();
					byte[] r = o.ToByteArray();
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
			}
			finally
			{
				b.Destroy();
			}
		}
Example #8
0
		//ATTACHMENTS
		/// <exception cref="System.Exception"></exception>
		/// <exception cref="System.IO.IOException"></exception>
		public virtual void TestAttachments()
		{
			IDictionary<string, object> properties = new Dictionary<string, object>();
			properties.Put("testName", "testAttachments");
			Database db = StartDatabase();
			Document doc = CreateDocumentWithProperties(db, properties);
			SavedRevision rev = doc.GetCurrentRevision();
			NUnit.Framework.Assert.AreEqual(rev.GetAttachments().Count, 0);
			NUnit.Framework.Assert.AreEqual(rev.GetAttachmentNames().Count, 0);
			NUnit.Framework.Assert.IsNull(rev.GetAttachment("index.html"));
			string content = "This is a test attachment!";
			ByteArrayInputStream body = new ByteArrayInputStream(Sharpen.Runtime.GetBytesForString
				(content));
			UnsavedRevision rev2 = doc.CreateRevision();
			rev2.SetAttachment("index.html", "text/plain; charset=utf-8", body);
			SavedRevision rev3 = rev2.Save();
			NUnit.Framework.Assert.IsNotNull(rev3);
			NUnit.Framework.Assert.AreEqual(rev3.GetAttachments().Count, 1);
			NUnit.Framework.Assert.AreEqual(rev3.GetAttachmentNames().Count, 1);
			Attachment attach = rev3.GetAttachment("index.html");
			NUnit.Framework.Assert.IsNotNull(attach);
			NUnit.Framework.Assert.AreEqual(doc, attach.GetDocument());
			NUnit.Framework.Assert.AreEqual("index.html", attach.GetName());
			IList<string> attNames = new AList<string>();
			attNames.AddItem("index.html");
			NUnit.Framework.Assert.AreEqual(rev3.GetAttachmentNames(), attNames);
			NUnit.Framework.Assert.AreEqual("text/plain; charset=utf-8", attach.GetContentType
				());
			NUnit.Framework.Assert.AreEqual(IOUtils.ToString(attach.GetContent(), "UTF-8"), content
				);
			NUnit.Framework.Assert.AreEqual(Sharpen.Runtime.GetBytesForString(content).Length
				, attach.GetLength());
			UnsavedRevision newRev = rev3.CreateRevision();
			newRev.RemoveAttachment(attach.GetName());
			SavedRevision rev4 = newRev.Save();
			NUnit.Framework.Assert.IsNotNull(rev4);
			NUnit.Framework.Assert.AreEqual(0, rev4.GetAttachmentNames().Count);
		}
Example #9
0
        public void TestAttachments()
		{
			var properties = new Dictionary<String, Object>();
			properties["testName"] = "testAttachments";
			var db = manager.GetExistingDatabase(DefaultTestDb);

			var doc = CreateDocumentWithProperties(db, properties);
			var rev = doc.CurrentRevision;
			Assert.AreEqual(rev.Attachments.Count(), 0);
            Assert.AreEqual(rev.AttachmentNames.Count(), 0);
            Assert.IsNull(rev.GetAttachment("index.html"));

			var content = "This is a test attachment!";
            var body = new ByteArrayInputStream(Runtime.GetBytesForString(content).ToArray());

			var rev2 = doc.CreateRevision();
            rev2.SetAttachment("index.html", "text/plain; charset=utf-8", body);

			var rev3 = rev2.Save();

			Assert.IsNotNull(rev3);
			Assert.AreEqual(rev3.Attachments.Count(), 1);
            Assert.AreEqual(rev3.AttachmentNames.Count(), 1);

            var attach = rev3.GetAttachment("index.html");
			Assert.IsNotNull(attach);
			Assert.AreEqual(doc, attach.Document);
			Assert.AreEqual("index.html", attach.Name);

			var attNames = new AList<string>();
			attNames.AddItem("index.html");
			Assert.AreEqual(rev3.AttachmentNames, attNames);
			Assert.AreEqual("text/plain; charset=utf-8", attach.ContentType);

            var attachmentContent = Encoding.UTF8.GetString(attach.Content.ToArray());
            Assert.AreEqual(content, attachmentContent);
            Assert.AreEqual(Runtime.GetBytesForString(content).ToArray().Length, attach.Length);

			var newRev = rev3.CreateRevision();
			newRev.RemoveAttachment(attach.Name);
			var rev4 = newRev.Save();
			Assert.IsNotNull(rev4);
            Assert.AreEqual(0, rev4.AttachmentNames.Count());
		}
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 private string CreateDocumentsForPushReplication(string docIdTimestamp, string attachmentType
     )
 {
     string doc1Id;
     string doc2Id;
     // Create some documents:
     IDictionary<string, object> doc1Properties = new Dictionary<string, object>();
     doc1Id = string.Format("doc1-%s", docIdTimestamp);
     doc1Properties.Put("_id", doc1Id);
     doc1Properties.Put("foo", 1);
     doc1Properties.Put("bar", false);
     Body body = new Body(doc1Properties);
     RevisionInternal rev1 = new RevisionInternal(body, database);
     Status status = new Status();
     rev1 = database.PutRevision(rev1, null, false, status);
     NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
     doc1Properties.Put("_rev", rev1.GetRevId());
     doc1Properties.Put("UPDATED", true);
     RevisionInternal rev2 = database.PutRevision(new RevisionInternal(doc1Properties, 
         database), rev1.GetRevId(), false, status);
     NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
     IDictionary<string, object> doc2Properties = new Dictionary<string, object>();
     doc2Id = string.Format("doc2-%s", docIdTimestamp);
     doc2Properties.Put("_id", doc2Id);
     doc2Properties.Put("baz", 666);
     doc2Properties.Put("fnord", true);
     database.PutRevision(new RevisionInternal(doc2Properties, database), null, false, 
         status);
     NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
     Document doc2 = database.GetDocument(doc2Id);
     UnsavedRevision doc2UnsavedRev = doc2.CreateRevision();
     if (attachmentType.Equals("png"))
     {
         InputStream attachmentStream = GetAsset("attachment.png");
         doc2UnsavedRev.SetAttachment("attachment.png", "image/png", attachmentStream);
     }
     else
     {
         if (attachmentType.Equals("txt"))
         {
             StringBuilder sb = new StringBuilder();
             for (int i = 0; i < 1000; i++)
             {
                 sb.Append("This is a large attachemnt.");
             }
             ByteArrayInputStream attachmentStream = new ByteArrayInputStream(Sharpen.Runtime.GetBytesForString
                 (sb.ToString()));
             doc2UnsavedRev.SetAttachment("attachment.txt", "text/plain", attachmentStream);
         }
         else
         {
             throw new RuntimeException("invalid attachment type: " + attachmentType);
         }
     }
     SavedRevision doc2Rev = doc2UnsavedRev.Save();
     NUnit.Framework.Assert.IsNotNull(doc2Rev);
     return doc1Id;
 }
Example #11
0
		/// <exception cref="System.IO.IOException"></exception>
		public override void WriteTo(OutputStream @out)
		{
			if (@out == null)
			{
				throw new ArgumentException("Output stream may not be null");
			}
			InputStream @in = new ByteArrayInputStream(this.content);
			byte[] tmp = new byte[4096];
			int l;
			while ((l = @in.Read(tmp)) != -1)
			{
				@out.Write(tmp, 0, l);
			}
			@out.Flush();
		}
 private void ReaderOperationWithMime(byte[] mime, string part1ExpectedStr, string
      part2ExpectedStr, int recommendedChunkSize)
 {
     Encoding utf8 = Sharpen.Extensions.GetEncoding("UTF-8");
     // if the caller passes in a special chunksize, which is not equal to mime.length, then
     // lets test the algorithm _only_ at that chunksize.  otherwise, test it at every chunksize
     // between 1 and mime.length.  (this is needed because when testing with a very large mime value,
     // the test takes too long to test at every single chunk size)
     int chunkSize = 1;
     if (recommendedChunkSize != mime.Length)
     {
         chunkSize = recommendedChunkSize;
     }
     for (; chunkSize <= recommendedChunkSize; ++chunkSize)
     {
         ByteArrayInputStream mimeInputStream = new ByteArrayInputStream(mime);
         MultipartReaderTest.TestMultipartReaderDelegate delegate_ = new MultipartReaderTest.TestMultipartReaderDelegate
             (this);
         string contentType = "multipart/related; boundary=\"BOUNDARY\"";
         MultipartReader reader = new MultipartReader(contentType, delegate_);
         NUnit.Framework.Assert.IsFalse(reader.Finished());
         int location = 0;
         int length = 0;
         do
         {
             NUnit.Framework.Assert.IsTrue("Parser didn't stop at end", location < mime.Length
                 );
             length = Math.Min(chunkSize, (mime.Length - location));
             byte[] bytesRead = new byte[length];
             mimeInputStream.Read(bytesRead, 0, length);
             reader.AppendData(bytesRead);
             location += chunkSize;
         }
         while (!reader.Finished());
         NUnit.Framework.Assert.AreEqual(delegate_.partList.Count, 2);
         NUnit.Framework.Assert.AreEqual(delegate_.headersList.Count, 2);
         byte[] part1Expected = Sharpen.Runtime.GetBytesForString(part1ExpectedStr, utf8);
         byte[] part2Expected = Sharpen.Runtime.GetBytesForString(part2ExpectedStr, utf8);
         ByteArrayBuffer part1 = delegate_.partList[0];
         ByteArrayBuffer part2 = delegate_.partList[1];
         NUnit.Framework.Assert.IsTrue(Arrays.Equals(part1.ToByteArray(), part1Expected));
         NUnit.Framework.Assert.IsTrue(Arrays.Equals(part2.ToByteArray(), part2Expected));
         IDictionary<string, string> headers1 = delegate_.headersList[0];
         NUnit.Framework.Assert.IsTrue(headers1.ContainsKey("Foo"));
         NUnit.Framework.Assert.AreEqual(headers1.Get("Foo"), "Bar");
         NUnit.Framework.Assert.IsTrue(headers1.ContainsKey("Header"));
         NUnit.Framework.Assert.AreEqual(headers1.Get("Header"), "Val ue");
     }
 }
Example #13
0
		/// <exception cref="Sharpen.URISyntaxException"></exception>
		/// <exception cref="System.NotSupportedException"></exception>
		/// <exception cref="NGit.Errors.TransportException"></exception>
		private FetchResult FetchFromBundle(Repository newRepo, byte[] bundle)
		{
			URIish uri = new URIish("in-memory://");
			ByteArrayInputStream @in = new ByteArrayInputStream(bundle);
			RefSpec rs = new RefSpec("refs/heads/*:refs/heads/*");
			ICollection<RefSpec> refs = Collections.Singleton(rs);
			return new TransportBundleStream(newRepo, uri, @in).Fetch(NullProgressMonitor.INSTANCE
				, refs);
		}
Example #14
0
		/// <summary>
		/// Decodes data from Base64 notation, automatically
		/// detecting gzip-compressed data and decompressing it.
		/// </summary>
		/// <remarks>
		/// Decodes data from Base64 notation, automatically
		/// detecting gzip-compressed data and decompressing it.
		/// </remarks>
		/// <param name="s">the string to decode</param>
		/// <param name="options">encode options such as URL_SAFE</param>
		/// <returns>the decoded data</returns>
		/// <exception cref="System.IO.IOException">if there is an error</exception>
		/// <exception cref="System.ArgumentNullException">if <tt>s</tt> is null</exception>
		/// <since>1.4</since>
		public static byte[] Decode(string s, int options)
		{
			if (s == null)
			{
				throw new ArgumentNullException("Input string was null.");
			}
			// end if
			byte[] bytes;
			try
			{
				bytes = Sharpen.Runtime.GetBytesForString(s, PreferredEncoding);
			}
			catch (UnsupportedEncodingException)
			{
				// end try
				bytes = Sharpen.Runtime.GetBytesForString(s);
			}
			// end catch
			//</change>
			// Decode
			bytes = Decode(bytes, 0, bytes.Length, options);
			// Check to see if it's gzip-compressed
			// GZIP Magic Two-Byte Number: 0x8b1f (35615)
			bool dontGunzip = (options & DontGunzip) != 0;
			if ((bytes != null) && (bytes.Length >= 4) && (!dontGunzip))
			{
				int head = ((int)bytes[0] & unchecked((int)(0xff))) | ((bytes[1] << 8) & unchecked(
					(int)(0xff00)));
				if (GZIPInputStream.GzipMagic == head)
				{
					ByteArrayInputStream bais = null;
					GZIPInputStream gzis = null;
					ByteArrayOutputStream baos = null;
					byte[] buffer = new byte[2048];
					int length = 0;
					try
					{
						baos = new ByteArrayOutputStream();
						bais = new ByteArrayInputStream(bytes);
						gzis = new GZIPInputStream(bais);
						while ((length = gzis.Read(buffer)) >= 0)
						{
							baos.Write(buffer, 0, length);
						}
						// end while: reading input
						// No error? Get new bytes.
						bytes = baos.ToByteArray();
					}
					catch (IOException e)
					{
						// end try
						Sharpen.Runtime.PrintStackTrace(e);
					}
					finally
					{
						// Just return originally-decoded bytes
						// end catch
						try
						{
							baos.Close();
						}
						catch (Exception)
						{
						}
						try
						{
							gzis.Close();
						}
						catch (Exception)
						{
						}
						try
						{
							bais.Close();
						}
						catch (Exception)
						{
						}
					}
				}
			}
			// end finally
			// end if: gzipped
			// end if: bytes.length >= 2
			return bytes;
		}
Example #15
0
		/// <summary>
		/// Attempts to decode Base64 data and deserialize a Java
		/// Object within.
		/// </summary>
		/// <remarks>
		/// Attempts to decode Base64 data and deserialize a Java
		/// Object within. Returns <tt>null</tt> if there was an error.
		/// If <tt>loader</tt> is not null, it will be the class loader
		/// used when deserializing.
		/// </remarks>
		/// <param name="encodedObject">The Base64 data to decode</param>
		/// <param name="options">Various parameters related to decoding</param>
		/// <param name="loader">Optional class loader to use in deserializing classes.</param>
		/// <returns>The decoded and deserialized object</returns>
		/// <exception cref="System.ArgumentNullException">if encodedObject is null</exception>
		/// <exception cref="System.IO.IOException">if there is a general error</exception>
		/// <exception cref="System.TypeLoadException">
		/// if the decoded object is of a
		/// class that cannot be found by the JVM
		/// </exception>
		/// <since>2.3.4</since>
		public static object DecodeToObject(string encodedObject, int options, ClassLoader
			 loader)
		{
			// Decode and gunzip if necessary
			byte[] objBytes = Decode(encodedObject, options);
			ByteArrayInputStream bais = null;
			ObjectInputStream ois = null;
			object obj = null;
			try
			{
				bais = new ByteArrayInputStream(objBytes);
				// If no custom class loader is provided, use Java's builtin OIS.
				if (loader == null)
				{
					ois = new ObjectInputStream(bais);
				}
				else
				{
					// end if: no loader provided
					// Else make a customized object input stream that uses
					// the provided class loader.
					ois = new _ObjectInputStream_1358(loader, bais);
				}
				// Class loader knows of this class.
				// end else: not null
				// end resolveClass
				// end ois
				// end else: no custom class loader
				obj = ois.ReadObject();
			}
			catch (IOException e)
			{
				// end try
				throw;
			}
			catch (TypeLoadException e)
			{
				// Catch and throw in order to execute finally{}
				// end catch
				throw;
			}
			finally
			{
				// Catch and throw in order to execute finally{}
				// end catch
				try
				{
					bais.Close();
				}
				catch (Exception)
				{
				}
				try
				{
					ois.Close();
				}
				catch (Exception)
				{
				}
			}
			// end finally
			return obj;
		}
 /// <exception cref="System.IO.IOException"></exception>
 private void Test(byte[] input, byte[] expected)
 {
     InputStream bis1 = new ByteArrayInputStream(input);
     InputStream cis1 = new EolCanonicalizingInputStream(bis1);
     int index1 = 0;
     for (int b = cis1.Read(); b != -1; b = cis1.Read())
     {
         NUnit.Framework.Assert.AreEqual(expected[index1], unchecked((byte)b));
         index1++;
     }
     NUnit.Framework.Assert.AreEqual(expected.Length, index1);
     for (int bufferSize = 1; bufferSize < 10; bufferSize++)
     {
         byte[] buffer = new byte[bufferSize];
         InputStream bis2 = new ByteArrayInputStream(input);
         InputStream cis2 = new EolCanonicalizingInputStream(bis2);
         int read = 0;
         for (int readNow = cis2.Read(buffer, 0, buffer.Length); readNow != -1 && read < expected
             .Length; readNow = cis2.Read(buffer, 0, buffer.Length))
         {
             for (int index2 = 0; index2 < readNow; index2++)
             {
                 NUnit.Framework.Assert.AreEqual(expected[read + index2], buffer[index2]);
             }
             read += readNow;
         }
         NUnit.Framework.Assert.AreEqual(expected.Length, read);
     }
 }
Example #17
0
		public virtual void TestDataAfterPackFooterSplitHeaderRead()
		{
			TestRepository d = new TestRepository<FileRepository>(db);
			byte[] data = Constants.Encode("a");
			RevBlob b = d.Blob(data);
			int objects = 248;
			TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(32 * 1024);
			PackHeader(pack, objects + 1);
			int offset = 13;
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < offset; i++)
			{
				sb.Append(i);
			}
			offset = sb.ToString().Length;
			int lenByte = (Constants.OBJ_BLOB) << 4 | (offset & unchecked((int)(0x0F)));
			offset >>= 4;
			if (offset > 0)
			{
				lenByte |= 1 << 7;
			}
			pack.Write(lenByte);
			while (offset > 0)
			{
				lenByte = offset & unchecked((int)(0x7F));
				offset >>= 6;
				if (offset > 0)
				{
					lenByte |= 1 << 7;
				}
				pack.Write(lenByte);
			}
			Deflate(pack, Constants.Encode(sb.ToString()));
			for (int i_1 = 0; i_1 < objects; i_1++)
			{
				// The last pack header written falls across the 8192 byte boundary
				// between [8189:8210]
				pack.Write((Constants.OBJ_REF_DELTA) << 4 | 4);
				b.CopyRawTo(pack);
				Deflate(pack, new byte[] { unchecked((int)(0x1)), unchecked((int)(0x1)), unchecked(
					(int)(0x1)), (byte)('b') });
			}
			Digest(pack);
			byte[] packData = pack.ToByteArray();
			byte[] streamData = new byte[packData.Length + 1];
			System.Array.Copy(packData, 0, streamData, 0, packData.Length);
			streamData[packData.Length] = unchecked((int)(0x7e));
			InputStream @in = new ByteArrayInputStream(streamData);
			PackParser p = Index(@in);
			p.SetAllowThin(true);
			p.SetCheckEofAfterPackFooter(false);
			p.SetExpectDataAfterPackFooter(true);
			p.Parse(NullProgressMonitor.INSTANCE);
			NUnit.Framework.Assert.AreEqual(unchecked((int)(0x7e)), @in.Read());
		}
Example #18
0
		public virtual void TestDataAfterPackFooterSplitObjectRead()
		{
			byte[] data = Constants.Encode("0123456789");
			// Build a pack ~17k
			int objects = 900;
			TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(32 * 1024);
			PackHeader(pack, objects);
			for (int i = 0; i < objects; i++)
			{
				pack.Write((Constants.OBJ_BLOB) << 4 | 10);
				Deflate(pack, data);
			}
			Digest(pack);
			byte[] packData = pack.ToByteArray();
			byte[] streamData = new byte[packData.Length + 1];
			System.Array.Copy(packData, 0, streamData, 0, packData.Length);
			streamData[packData.Length] = unchecked((int)(0x7e));
			InputStream @in = new ByteArrayInputStream(streamData);
			PackParser p = Index(@in);
			p.SetAllowThin(true);
			p.SetCheckEofAfterPackFooter(false);
			p.SetExpectDataAfterPackFooter(true);
			p.Parse(NullProgressMonitor.INSTANCE);
			NUnit.Framework.Assert.AreEqual(unchecked((int)(0x7e)), @in.Read());
		}
Example #19
0
		public virtual void TestDataAfterPackFooterSingleRead()
		{
			TestRepository d = new TestRepository<FileRepository>(db);
			RevBlob a = d.Blob("a");
			TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(32 * 1024);
			PackHeader(pack, 1);
			pack.Write((Constants.OBJ_REF_DELTA) << 4 | 4);
			a.CopyRawTo(pack);
			Deflate(pack, new byte[] { unchecked((int)(0x1)), unchecked((int)(0x1)), unchecked(
				(int)(0x1)), (byte)('b') });
			Digest(pack);
			byte[] packData = pack.ToByteArray();
			byte[] streamData = new byte[packData.Length + 1];
			System.Array.Copy(packData, 0, streamData, 0, packData.Length);
			streamData[packData.Length] = unchecked((int)(0x7e));
			InputStream @in = new ByteArrayInputStream(streamData);
			PackParser p = Index(@in);
			p.SetAllowThin(true);
			p.SetCheckEofAfterPackFooter(false);
			p.SetExpectDataAfterPackFooter(true);
			p.Parse(NullProgressMonitor.INSTANCE);
			NUnit.Framework.Assert.AreEqual(unchecked((int)(0x7e)), @in.Read());
		}
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public static void AttachImage(Couchbase.Lite.Document task, Bitmap image)
 {
     if (task == null || image == null)
     {
         return;
     }
     UnsavedRevision revision = task.CreateRevision();
     ByteArrayOutputStream @out = new ByteArrayOutputStream();
     image.Compress(Bitmap.CompressFormat.Jpeg, 50, @out);
     ByteArrayInputStream @in = new ByteArrayInputStream(@out.ToByteArray());
     revision.SetAttachment("image", "image/jpg", @in);
     revision.Save();
 }