public bool Run()
 {
     string[] bigObj = new string[this._enclosing.GetSizeOfDocument()];
     for (int i = 0; i < this._enclosing.GetSizeOfDocument(); i++)
     {
         bigObj[i] = Test10_DeleteDB._propertyValue;
     }
     for (int i_1 = 0; i_1 < this._enclosing.GetNumberOfDocuments(); i_1++)
     {
         //create a document
         IDictionary<string, object> props = new Dictionary<string, object>();
         props.Put("bigArray", bigObj);
         Body body = new Body(props);
         RevisionInternal rev1 = new RevisionInternal(body, this._enclosing.database);
         Status status = new Status();
         try
         {
             rev1 = this._enclosing.database.PutRevision(rev1, null, false, status);
         }
         catch (Exception t)
         {
             Log.E(Test10_DeleteDB.Tag, "Document create failed", t);
             return false;
         }
     }
     return true;
 }
 public RevisionInternal(Body body, Database database) : this((string)body.GetPropertyForKey
     ("_id"), (string)body.GetPropertyForKey("_rev"), (((bool)body.GetPropertyForKey(
     "_deleted") != null) && ((bool)body.GetPropertyForKey("_deleted") == true)), database
     )
 {
     this.body = body;
 }
        public void TestChangeNotification()
        {
            var changeNotifications = 0;

            EventHandler<DatabaseChangeEventArgs> handler
                = (sender, e) => changeNotifications++;

            database.Changed += handler;

            // create a document
            var documentProperties = new Dictionary<string, object>();
            documentProperties["foo"] = 1;
            documentProperties["bar"] = false;
            documentProperties["baz"] = "touch";
            
            var body = new Body(documentProperties);
            var rev1 = new RevisionInternal(body, database);
            
            var status = new Status();
            database.PutRevision(rev1, null, false, status);
            
            Assert.AreEqual(1, changeNotifications);

            // Analysis disable once DelegateSubtraction
            database.Changed -= handler;
        }
        public void TestChangeNotification()
        {
            var countDown = new CountdownEvent(1);
            EventHandler<DatabaseChangeEventArgs> handler
                = (sender, e) => countDown.Signal();

            database.Changed += handler;

            // create a document
            var documentProperties = new Dictionary<string, object>();
            documentProperties["foo"] = 1;
            documentProperties["bar"] = false;
            documentProperties["baz"] = "touch";
            
            var body = new Body(documentProperties);
            var rev1 = new RevisionInternal(body);

            database.PutRevision(rev1, null, false);
            Sleep(500);
            
            Assert.IsTrue(countDown.Wait(TimeSpan.FromSeconds(1)));

            // Analysis disable once DelegateSubtraction
            database.Changed -= handler;
        }
예제 #5
0
		/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
		public virtual void TestChangeNotification()
		{
			// add listener to database
            database.Changed += (sender, e) => changeNotifications++;
			// create a document
			IDictionary<string, object> documentProperties = new Dictionary<string, object>();
			documentProperties["foo"] = 1;
			documentProperties["bar"] = false;
			documentProperties["baz"] = "touch";
			Body body = new Body(documentProperties);
			RevisionInternal rev1 = new RevisionInternal(body, database);
			Status status = new Status();
			rev1 = database.PutRevision(rev1, null, false, status);
			NUnit.Framework.Assert.AreEqual(1, changeNotifications);
		}
예제 #6
0
		/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
		public virtual void TestChangeNotification()
		{
			Database.ChangeListener changeListener = new _ChangeListener_16(this);
			// add listener to database
			database.AddChangeListener(changeListener);
			// create a document
			IDictionary<string, object> documentProperties = new Dictionary<string, object>();
			documentProperties.Put("foo", 1);
			documentProperties.Put("bar", false);
			documentProperties.Put("baz", "touch");
			Body body = new Body(documentProperties);
			RevisionInternal rev1 = new RevisionInternal(body, database);
			Status status = new Status();
			rev1 = database.PutRevision(rev1, null, false, status);
			NUnit.Framework.Assert.AreEqual(1, changeNotifications);
		}
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public virtual void TestLoadDBPerformance()
 {
     long startMillis = Runtime.CurrentTimeMillis();
     string[] bigObj = new string[GetSizeOfDocument()];
     for (int i = 0; i < GetSizeOfDocument(); i++)
     {
         bigObj[i] = _propertyValue;
     }
     for (int j = 0; j < GetNumberOfShutAndReloadCycles(); j++)
     {
         //Force close and reopen of manager and database to ensure cold
         //start before doc creation
         try
         {
             TearDown();
             manager = new Manager(new LiteTestContext(), Manager.DefaultOptions);
             database = manager.GetExistingDatabase(DefaultTestDb);
         }
         catch (Exception ex)
         {
             Log.E(Tag, "DB teardown", ex);
             Fail();
         }
         for (int k = 0; k < GetNumberOfDocuments(); k++)
         {
             //create a document
             IDictionary<string, object> props = new Dictionary<string, object>();
             props.Put("bigArray", bigObj);
             Body body = new Body(props);
             RevisionInternal rev1 = new RevisionInternal(body, database);
             Status status = new Status();
             try
             {
                 rev1 = database.PutRevision(rev1, null, false, status);
             }
             catch (Exception t)
             {
                 Log.E(Tag, "Document creation failed", t);
                 Fail();
             }
         }
     }
     Log.V("PerformanceStats", Tag + "," + Sharpen.Extensions.ValueOf(Runtime.CurrentTimeMillis
         () - startMillis).ToString() + "," + GetNumberOfDocuments() + "," + GetSizeOfDocument
         () + ",," + GetNumberOfShutAndReloadCycles());
 }
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public virtual void TestCreateDocsUnoptimizedWayPerformance()
 {
     long startMillis = Runtime.CurrentTimeMillis();
     string[] bigObj = new string[GetSizeOfDocument()];
     for (int i = 0; i < GetSizeOfDocument(); i++)
     {
         bigObj[i] = _propertyValue;
     }
     for (int i_1 = 0; i_1 < GetNumberOfDocuments(); i_1++)
     {
         //create a document
         IDictionary<string, object> props = new Dictionary<string, object>();
         props.Put("bigArray", bigObj);
         Body body = new Body(props);
         RevisionInternal rev1 = new RevisionInternal(body, database);
         Status status = new Status();
         rev1 = database.PutRevision(rev1, null, false, status);
     }
     Log.V("PerformanceStats", Tag + "," + Sharpen.Extensions.ValueOf(Runtime.CurrentTimeMillis
         () - startMillis).ToString() + "," + GetNumberOfDocuments() + "," + GetSizeOfDocument
         ());
 }
예제 #9
0
        internal virtual object ParseJSONResponse(HttpURLConnection conn)
        {
            Object result = null;
            var stream = conn.GetOutputStream();
            var bytesRead = 0L;
            const Int32 chunkSize = 8192;
             
            var bytes = stream.ReadAllBytes();

            var responseBody = new Body(bytes);
            if (responseBody != null)
            {
                var json = responseBody.GetJson();
                String jsonString = null;
                if (json != null)
                {
                    jsonString = Runtime.GetStringForBytes(json);
                    try
                    {
                        result = mapper.ReadValue<object>(jsonString);
                    }
                    catch (Exception)
                    {
                        Assert.Fail();
                    }
                }
            }
            return result;
        }
 public PulledRevision(Body body, Database database) : base(body, database)
 {
 }
예제 #11
0
 public virtual void SetJson(byte[] json)
 {
     this.body = new Body(json);
 }
예제 #12
0
 // Used by listener
 public static bool IsValid(Body body)
 {
     return(body.GetPropertyForKey("_id") != null ||
            (body.GetPropertyForKey("_rev") == null && body.GetPropertyForKey("_deleted") == null));
 }
 public PulledRevision(Body body) : base(body)
 {
 }
        public void TestLocalDocs()
        {
            //create a document
            var documentProperties = new Dictionary<string, object>();
            documentProperties["_id"] = "_local/doc1";
            documentProperties["foo"] = 1;
            documentProperties["bar"] = false;
            var body = new Body(documentProperties);
            var rev1 = new RevisionInternal(body);
            rev1 = database.Storage.PutLocalRevision(rev1, null, true);
            Log.V(Tag, "Created " + rev1);
            Assert.AreEqual("_local/doc1", rev1.GetDocId());
            Assert.IsTrue(rev1.GetRevId().StartsWith("1-"));

            //read it back
            var readRev = database.Storage.GetLocalDocument(rev1.GetDocId(), null);
            Assert.IsNotNull(readRev);
            var readRevProps = readRev.GetProperties();
            Assert.AreEqual(rev1.GetDocId(), readRevProps.Get("_id"));
            Assert.AreEqual(rev1.GetRevId(), readRevProps.Get("_rev"));
            AssertPropertiesAreEqual(UserProperties(readRevProps), 
                UserProperties(body.GetProperties()));

            //now update it
            documentProperties = (Dictionary<string, object>)readRev.GetProperties();
            documentProperties["status"] = "updated!";
            body = new Body(documentProperties);
            var rev2 = new RevisionInternal(body);
            var rev2input = rev2;
            rev2 = database.Storage.PutLocalRevision(rev2, rev1.GetRevId(), true);
            Log.V(Tag, "Updated " + rev1);
            Assert.AreEqual(rev1.GetDocId(), rev2.GetDocId());
            Assert.IsTrue(rev2.GetRevId().StartsWith("2-"));
            
            //read it back
            readRev = database.Storage.GetLocalDocument(rev2.GetDocId(), null);
            Assert.IsNotNull(readRev);
            AssertPropertiesAreEqual(UserProperties(readRev.GetProperties()), 
                UserProperties(body.GetProperties()));

            // Try to update the first rev, which should fail:
            var gotException = false;
            try
            {
                database.Storage.PutLocalRevision(rev2input, rev1.GetRevId(), true);
            }
            catch (CouchbaseLiteException e)
            {
                Assert.AreEqual(StatusCode.Conflict, e.CBLStatus.Code);
                gotException = true;
            }
            Assert.IsTrue(gotException);
            
            // Delete it:
            var revD = new RevisionInternal(rev2.GetDocId(), null, true);
            gotException = false;
            try
            {
                var revResult = database.Storage.PutLocalRevision(revD, null, true);
                Assert.IsNull(revResult);
            }
            catch (CouchbaseLiteException e)
            {
                Assert.AreEqual(StatusCode.Conflict, e.CBLStatus.Code);
                gotException = true;
            }
            Assert.IsTrue(gotException);
            revD = database.Storage.PutLocalRevision(revD, rev2.GetRevId(), true);
            
            // Delete nonexistent doc:
            gotException = false;
            var revFake = new RevisionInternal("_local/fake", null, true);
            try
            {
                database.Storage.PutLocalRevision(revFake, null, true);
            }
            catch (CouchbaseLiteException e)
            {
                Assert.AreEqual(StatusCode.NotFound, e.CBLStatus.Code);
                gotException = true;
            }
            Assert.IsTrue(gotException);
            
            // Read it back (should fail):
            readRev = database.Storage.GetLocalDocument(revD.GetDocId(), null);
            Assert.IsNull(readRev);
        }
        public void TestPusher()
        {
            if (!Boolean.Parse((string)GetProperty("replicationTestsEnabled")))
            {
                Assert.Inconclusive("Replication tests disabled.");
                return;
            }

            using (var remoteDb = _sg.CreateDatabase(TempDbName())) {
                var remote = remoteDb.RemoteUri;
                var docIdTimestamp = Convert.ToString((ulong)DateTime.UtcNow.TimeSinceEpoch().TotalMilliseconds);

                // Create some documents:
                var documentProperties = new Dictionary<string, object>();
                var doc1Id = string.Format("doc1-{0}", docIdTimestamp);
                documentProperties["_id"] = doc1Id;
                documentProperties["foo"] = 1;
                documentProperties["bar"] = false;

                var body = new Body(documentProperties);
                var rev1 = new RevisionInternal(body);
                rev1 = database.PutRevision(rev1, null, false);

                documentProperties.SetRevID(rev1.RevID);
                documentProperties["UPDATED"] = true;
                database.PutRevision(new RevisionInternal(documentProperties), rev1.RevID, false);

                documentProperties = new Dictionary<string, object>();
                var doc2Id = string.Format("doc2-{0}", docIdTimestamp);
                documentProperties["_id"] = doc2Id;
                documentProperties["baz"] = 666;
                documentProperties["fnord"] = true;

                database.PutRevision(new RevisionInternal(documentProperties), null, false);

                var doc2 = database.GetDocument(doc2Id);
                var doc2UnsavedRev = doc2.CreateRevision();
                var attachmentStream = GetAsset("attachment.png");
                doc2UnsavedRev.SetAttachment("attachment_testPusher.png", "image/png", attachmentStream);
                var doc2Rev = doc2UnsavedRev.Save();
                doc2UnsavedRev.Dispose();
                attachmentStream.Dispose();

                Assert.IsNotNull(doc2Rev);

                const bool continuous = false;
                var repl = database.CreatePushReplication(remote);
                repl.Continuous = continuous;
                if (!IsSyncGateway(remote)) {
                    repl.CreateTarget = true;
                }

                // Check the replication's properties:
                Assert.AreEqual(database, repl.LocalDatabase);
                Assert.AreEqual(remote, repl.RemoteUrl);
                Assert.IsFalse(repl.IsPull);
                Assert.IsFalse(repl.Continuous);
                Assert.IsNull(repl.Filter);
                Assert.IsNull(repl.FilterParams);
                Assert.IsNull(repl.DocIds);
                // TODO: CAssertNil(r1.headers); still not null!
                // Check that the replication hasn't started running:
                Assert.IsFalse(repl.IsRunning);
                Assert.AreEqual(ReplicationStatus.Stopped, repl.Status);
                Assert.AreEqual(0, repl.CompletedChangesCount);
                Assert.AreEqual(0, repl.ChangesCount);
                Assert.IsNull(repl.LastError);

                RunReplication(repl);

                // TODO: Verify the foloowing 2 asserts. ChangesCount and CompletedChangesCount
                // should already be reset when the replicator stopped.
                Assert.IsNull(repl.LastError);
                Assert.IsTrue(repl.ChangesCount >= 2);
                Assert.IsTrue(repl.CompletedChangesCount >= 2);


                remoteDb.VerifyDocumentExists(doc1Id);

                // Add doc3
                documentProperties = new Dictionary<string, object>();
                var doc3Id = string.Format("doc3-{0}", docIdTimestamp);
                var doc3 = database.GetDocument(doc3Id);
                documentProperties["bat"] = 677;
                doc3.PutProperties(documentProperties);

                // re-run push replication
                var repl2 = database.CreatePushReplication(remote);
                repl2.Continuous = continuous;
                if (!IsSyncGateway(remote)) {
                    repl2.CreateTarget = true;
                }

                var repl2CheckedpointId = repl2.RemoteCheckpointDocID();

                RunReplication(repl2);

                Assert.IsNull(repl2.LastError);

                Sleep(1000);

                // make sure trhe doc has been added
                remoteDb.VerifyDocumentExists(doc3Id);

                Assert.AreEqual(repl2.LastSequence, database.LastSequenceWithCheckpointId(repl2CheckedpointId));

                Sleep(2000);
                var json = GetRemoteDoc(remote, repl2CheckedpointId);
                var remoteLastSequence = (string)json["lastSequence"];
                Assert.AreEqual(repl2.LastSequence, remoteLastSequence);
            }
        }
예제 #16
0
        /// <summary>
        /// Attempt to update a document based on the information in the HTTP request
        /// </summary>
        /// <returns>The resulting status of the operation</returns>
        /// <param name="context">The request context</param>
        /// <param name="db">The database in which the document exists</param>
        /// <param name="docId">The ID of the document being updated</param>
        /// <param name="body">The new document body</param>
        /// <param name="deleting">Whether or not the document is being deleted</param>
        /// <param name="allowConflict">Whether or not to allow a conflict to be inserted</param>
        /// <param name="outRev">The resulting revision of the document</param>
        public static StatusCode UpdateDocument(ICouchbaseListenerContext context, Database db, string docId, Body body, bool deleting, 
            bool allowConflict, out RevisionInternal outRev)
        {
            outRev = null;
            if (body != null && !body.IsValidJSON()) {
                return StatusCode.BadJson;
            }

            string prevRevId;
            if (!deleting) {
                var properties = body.GetProperties();
                deleting = properties.GetCast<bool>("_deleted");
                if (docId == null) {
                    // POST's doc ID may come from the _id field of the JSON body.
                    docId = properties.GetCast<string>("_id");
                    if (docId == null && deleting) {
                        return StatusCode.BadId;
                    }
                }

                // PUT's revision ID comes from the JSON body.
                prevRevId = properties.GetCast<string>("_rev");
            } else {
                // DELETE's revision ID comes from the ?rev= query param
                prevRevId = context.GetQueryParam("rev");
            }

            // A backup source of revision ID is an If-Match header:
            if (prevRevId == null) {
                prevRevId = context.IfMatch();
            }

            if (docId == null && deleting) {
                return StatusCode.BadId;
            }

            RevisionInternal rev = new RevisionInternal(docId, null, deleting);
            rev.SetBody(body);

            StatusCode status = StatusCode.Created;
            try {
                if (docId != null && docId.StartsWith("_local")) {
                    outRev = db.Storage.PutLocalRevision(rev, prevRevId, true); //TODO: Doesn't match iOS
                } else {
                    Status retStatus = new Status();
                    outRev = db.PutRevision(rev, prevRevId, allowConflict, retStatus);
                    status = retStatus.Code;
                }
            } catch(CouchbaseLiteException e) {
                status = e.Code;
            }

            return status;
        }
        public void TestPusher()
        {
            var remote = GetReplicationURL();
            var docIdTimestamp = Convert.ToString(Runtime.CurrentTimeMillis());

            // Create some documents:
            var documentProperties = new Dictionary<string, object>();
            var doc1Id = string.Format("doc1-{0}", docIdTimestamp);
            documentProperties["_id"] = doc1Id;
            documentProperties["foo"] = 1;
            documentProperties["bar"] = false;

            var body = new Body(documentProperties);
            var rev1 = new RevisionInternal(body, database);
            var status = new Status();
            rev1 = database.PutRevision(rev1, null, false, status);
            Assert.AreEqual(StatusCode.Created, status.GetCode());

            documentProperties.Put("_rev", rev1.GetRevId());
            documentProperties["UPDATED"] = true;
            database.PutRevision(new RevisionInternal(documentProperties, database), rev1.GetRevId(), false, status);
            Assert.AreEqual(StatusCode.Created, status.GetCode());

            documentProperties = new Dictionary<string, object>();
            var doc2Id = string.Format("doc2-{0}", docIdTimestamp);
            documentProperties["_id"] = doc2Id;
            documentProperties["baz"] = 666;
            documentProperties["fnord"] = true;

            database.PutRevision(new RevisionInternal(documentProperties, database), null, false, status);
            Assert.AreEqual(StatusCode.Created, status.GetCode());

            var doc2 = database.GetDocument(doc2Id);
            var doc2UnsavedRev = doc2.CreateRevision();
            var attachmentStream = GetAsset("attachment.png");
            doc2UnsavedRev.SetAttachment("attachment.png", "image/png", attachmentStream);
            var doc2Rev = doc2UnsavedRev.Save();

            Assert.IsNotNull(doc2Rev);

            const bool continuous = false;
            var repl = database.CreatePushReplication(remote);
            repl.Continuous = continuous;
            if (!IsSyncGateway(remote)) {
                repl.CreateTarget = true;
            }

            // Check the replication's properties:
            Assert.AreEqual(database, repl.LocalDatabase);
            Assert.AreEqual(remote, repl.RemoteUrl);
            Assert.IsFalse(repl.IsPull);
            Assert.IsFalse(repl.Continuous);
            Assert.IsNull(repl.Filter);
            Assert.IsNull(repl.FilterParams);
            Assert.IsNull(repl.DocIds);
            // TODO: CAssertNil(r1.headers); still not null!
            // Check that the replication hasn't started running:
            Assert.IsFalse(repl.IsRunning);
            Assert.AreEqual((int)repl.Status, (int)ReplicationStatus.Stopped);
            Assert.AreEqual(0, repl.CompletedChangesCount);
            Assert.AreEqual(0, repl.ChangesCount);
            Assert.IsNull(repl.LastError);

            RunReplication(repl);

            // TODO: Verify the foloowing 2 asserts. ChangesCount and CompletedChangesCount
            // should already be reset when the replicator stopped.
             Assert.IsTrue(repl.ChangesCount >= 2);
             Assert.IsTrue(repl.CompletedChangesCount >= 2);
            Assert.IsNull(repl.LastError);

            VerifyRemoteDocExists(remote, doc1Id);

            // Add doc3
            documentProperties = new Dictionary<string, object>();
            var doc3Id = string.Format("doc3-{0}", docIdTimestamp);
            var doc3 = database.GetDocument(doc3Id);
            documentProperties["bat"] = 677;
            doc3.PutProperties(documentProperties);

            // re-run push replication
            var repl2 = database.CreatePushReplication(remote);
            repl2.Continuous = continuous;
            if (!IsSyncGateway(remote))
            {
                repl2.CreateTarget = true;
            }

            var repl2CheckedpointId = repl2.RemoteCheckpointDocID();

            RunReplication(repl2);

            Assert.IsNull(repl2.LastError);

            // make sure trhe doc has been added
            VerifyRemoteDocExists(remote, doc3Id);

            Assert.AreEqual(repl2.LastSequence, database.LastSequenceWithCheckpointId(repl2CheckedpointId));

            System.Threading.Thread.Sleep(2000);
            var json = GetRemoteDoc(remote, repl2CheckedpointId);
            var remoteLastSequence = (string)json["lastSequence"];
            Assert.AreEqual(repl2.LastSequence, remoteLastSequence);

            Log.D(Tag, "testPusher() finished");
        }
예제 #18
0
		public static Body BodyWithJSON(IEnumerable<Byte> json)
		{
            var result = new Body(json);
			return result;
		}
        // Processes a change in the subscribed database
        private void DatabaseChanged(object sender, DatabaseChangeEventArgs args)
        {
            foreach (var change in args.Changes) {
                var rev = change.AddedRevision;
                var winningRev = change.WinningRevisionId;

                if (!ChangesIncludeConflicts) {
                    if (winningRev == null) {
                        continue; // this change doesn't affect the winning rev ID, no need to send it
                    }

                    if (rev.Equals(winningRev)) {
                        // This rev made a _different_ rev current, so substitute that one.
                        // We need to emit the current sequence # in the feed, so put it in the rev.
                        // This isn't correct internally (this is an old rev so it has an older sequence)
                        // but consumers of the _changes feed don't care about the internal state.
                        if (ChangesIncludeDocs) {
                            Db.LoadRevisionBody(rev);
                        }
                    }
                }

                if (!Db.RunFilter(ChangesFilter, FilterParams, rev)) {
                    continue;
                }

                if (ChangesFeedMode == ChangesFeedMode.LongPoll) {
                    _changes.Add(rev);
                } else {
                    var written = Response.SendContinuousLine(DatabaseMethods.ChangesDictForRev(rev, this), ChangesFeedMode);
                    if (!written) {
                        Terminate();
                    }
                }
            }

            if (ChangesFeedMode == ChangesFeedMode.LongPoll && _changes.Count > 0) {
                var body = new Body(DatabaseMethods.ResponseBodyForChanges(_changes, 0, this));
                Response.WriteData(body.AsJson(), true);
                Terminate ();
            }
        }
예제 #20
0
		public static Body BodyWithProperties(IDictionary<string
			, object> properties)
		{
            var result = new Body(properties);
			return result;
		}
예제 #21
0
 internal void SetProperties(IDictionary <string, object> properties)
 {
     _body = new Body(properties);
 }
예제 #22
0
 public virtual void SetBody(Body body)
 {
     this.body = body;
 }
예제 #23
0
 internal void SetBody(Body body)
 {
     _body = body;
 }
예제 #24
0
 // Used by plugins
 internal void SetJson(IEnumerable <Byte> json)
 {
     _body = new Body(json);
 }
예제 #25
0
		/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
		public virtual void TestCRUDOperations()
		{
			database.AddChangeListener(this);
			string privateUUID = database.PrivateUUID();
			string publicUUID = database.PublicUUID();
			Log.V(Tag, "DB private UUID = '" + privateUUID + "', public UUID = '" + publicUUID
				 + "'");
			NUnit.Framework.Assert.IsTrue(privateUUID.Length >= 20);
			NUnit.Framework.Assert.IsTrue(publicUUID.Length >= 20);
			//create a document
			IDictionary<string, object> documentProperties = new Dictionary<string, object>();
			documentProperties["foo"] = 1;
			documentProperties["bar"] = false;
			documentProperties["baz"] = "touch";
			Body body = new Body(documentProperties);
			RevisionInternal rev1 = new RevisionInternal(body, database);
			Status status = new Status();
			rev1 = database.PutRevision(rev1, null, false, status);
			Log.V(Tag, "Created " + rev1);
			NUnit.Framework.Assert.IsTrue(rev1.GetDocId().Length >= 10);
			NUnit.Framework.Assert.IsTrue(rev1.GetRevId().StartsWith("1-"));
			//read it back
			RevisionInternal readRev = database.GetDocumentWithIDAndRev(rev1.GetDocId(), null
				, EnumSet.NoneOf<TDContentOptions>());
			NUnit.Framework.Assert.IsNotNull(readRev);
			IDictionary<string, object> readRevProps = readRev.Properties;
			NUnit.Framework.Assert.AreEqual(UserProperties(readRevProps), UserProperties(body
				.Properties));
			//now update it
			documentProperties = readRev.Properties;
			documentProperties["status"] = "updated!";
			body = new Body(documentProperties);
			RevisionInternal rev2 = new RevisionInternal(body, database);
			RevisionInternal rev2input = rev2;
			rev2 = database.PutRevision(rev2, rev1.GetRevId(), false, status);
			Log.V(Tag, "Updated " + rev1);
			NUnit.Framework.Assert.AreEqual(rev1.GetDocId(), rev2.GetDocId());
			NUnit.Framework.Assert.IsTrue(rev2.GetRevId().StartsWith("2-"));
			//read it back
			readRev = database.GetDocumentWithIDAndRev(rev2.GetDocId(), null, EnumSet.NoneOf<
				TDContentOptions>());
			NUnit.Framework.Assert.IsNotNull(readRev);
			NUnit.Framework.Assert.AreEqual(UserProperties(readRev.Properties), UserProperties
				(body.Properties));
			// Try to update the first rev, which should fail:
			bool gotExpectedError = false;
			try
			{
				database.PutRevision(rev2input, rev1.GetRevId(), false, status);
			}
			catch (CouchbaseLiteException e)
			{
				gotExpectedError = e.GetCBLStatus().GetCode() == StatusCode.Conflict;
			}
			NUnit.Framework.Assert.IsTrue(gotExpectedError);
			// Check the changes feed, with and without filters:
			RevisionList changes = database.ChangesSince(0, null, null);
			Log.V(Tag, "Changes = " + changes);
			NUnit.Framework.Assert.AreEqual(1, changes.Count);
            changes = database.ChangesSince(0, null, (revision, items) => "updated!".Equals (revision.Properties.Get ("status")));
			NUnit.Framework.Assert.AreEqual(1, changes.Count);
            changes = database.ChangesSince(0, null, (revision, items) => "not updated!".Equals (revision.Properties.Get ("status")));
			NUnit.Framework.Assert.AreEqual(0, changes.Count);
			// Delete it:
			RevisionInternal revD = new RevisionInternal(rev2.GetDocId(), null, true, database
				);
			RevisionInternal revResult = null;
			gotExpectedError = false;
			try
			{
				revResult = database.PutRevision(revD, null, false, status);
			}
			catch (CouchbaseLiteException e)
			{
				gotExpectedError = e.GetCBLStatus().GetCode() == StatusCode.Conflict;
			}
			NUnit.Framework.Assert.IsTrue(gotExpectedError);
			NUnit.Framework.Assert.IsNull(revResult);
			revD = database.PutRevision(revD, rev2.GetRevId(), false, status);
			NUnit.Framework.Assert.AreEqual(StatusCode.Ok, status.GetCode());
			NUnit.Framework.Assert.AreEqual(revD.GetDocId(), rev2.GetDocId());
			NUnit.Framework.Assert.IsTrue(revD.GetRevId().StartsWith("3-"));
			// Delete nonexistent doc:
			RevisionInternal revFake = new RevisionInternal("fake", null, true, database);
			gotExpectedError = false;
			try
			{
				database.PutRevision(revFake, null, false, status);
			}
			catch (CouchbaseLiteException e)
			{
				gotExpectedError = e.GetCBLStatus().GetCode() == StatusCode.NotFound;
			}
			NUnit.Framework.Assert.IsTrue(gotExpectedError);
			// Read it back (should fail):
			readRev = database.GetDocumentWithIDAndRev(revD.GetDocId(), null, EnumSet.NoneOf<TDContentOptions>());
			NUnit.Framework.Assert.IsNull(readRev);
			// Get Changes feed
			changes = database.ChangesSince(0, null, null);
			NUnit.Framework.Assert.IsTrue(changes.Count == 1);
			// Get Revision History
			IList<RevisionInternal> history = database.GetRevisionHistory(revD);
			NUnit.Framework.Assert.AreEqual(revD, history[0]);
			NUnit.Framework.Assert.AreEqual(rev2, history[1]);
			NUnit.Framework.Assert.AreEqual(rev1, history[2]);
		}
        public void TestCRUDOperations()
        {
            database.Changed += (sender, e) => {
                var changes = e.Changes.ToList();
                foreach (DocumentChange change in changes)
                {
                    var rev = change.AddedRevision;
                    Assert.IsNotNull(rev);
                    Assert.IsNotNull(rev.GetDocId());
                    Assert.IsNotNull(rev.GetRevId());
                    Assert.AreEqual(rev.GetDocId(), rev.GetProperties()["_id"]);
                    Assert.AreEqual(rev.GetRevId(), rev.GetProperties()["_rev"]);
                }
            };

            var privateUUID = database.PrivateUUID();
            var publicUUID = database.PublicUUID();
            Log.V(Tag, "DB private UUID = '" + privateUUID + "', public UUID = '" + 
                publicUUID + "'");
            Assert.IsTrue(privateUUID.Length >= 20);
            Assert.IsTrue(publicUUID.Length >= 20);

            //create a document
            var documentProperties = new Dictionary<string, object>();
            documentProperties["foo"] = 1;
            documentProperties["bar"] = false;
            documentProperties["baz"] = "touch";

            var body = new Body(documentProperties);
            var rev1 = new RevisionInternal(body);

            rev1 = database.PutRevision(rev1, null, false);
            Log.V(Tag, "Created " + rev1);
            Assert.IsTrue(rev1.GetDocId().Length >= 10);
            Assert.IsTrue(rev1.GetRevId().StartsWith("1-"));

            //read it back
            var readRev = database.GetDocument(rev1.GetDocId(), null, 
                true);
            Assert.IsNotNull(readRev);

            var userReadRevProps = UserProperties(readRev.GetProperties());
            var userBodyProps = UserProperties(body.GetProperties());
            Assert.AreEqual(userReadRevProps.Count, userBodyProps.Count);
            foreach(var key in userReadRevProps.Keys) 
            {
                Assert.AreEqual(userReadRevProps[key], userBodyProps[key]);
            }

            //now update it
            documentProperties = (Dictionary<string, object>)readRev.GetProperties();
            documentProperties["status"] = "updated!";
            body = new Body(documentProperties);
            var rev2 = new RevisionInternal(body);
            var rev2input = rev2;
            rev2 = database.PutRevision(rev2, rev1.GetRevId(), false);
            Log.V(Tag, "Updated " + rev1);
            Assert.AreEqual(rev1.GetDocId(), rev2.GetDocId());
            Assert.IsTrue(rev2.GetRevId().StartsWith("2-"));

            //read it back
            readRev = database.GetDocument(rev2.GetDocId(), null, 
                true);
            Assert.IsNotNull(readRev);
            Assert.AreEqual(UserProperties(readRev.GetProperties()), UserProperties
                (body.GetProperties()));

            // Try to update the first rev, which should fail:
            var ex = Assert.Throws<CouchbaseLiteException>(() => database.PutRevision(rev2input, rev1.GetRevId(), false));
            Assert.AreEqual(StatusCode.Conflict, ex.Code);

            // Check the changes feed, with and without filters:
            var changeRevisions = database.ChangesSince(0, ChangesOptions.Default, null, null);

            Log.V(Tag, "Changes = " + changeRevisions);
            Assert.AreEqual(1, changeRevisions.Count);

            changeRevisions = database.ChangesSince(0, ChangesOptions.Default, 
                (revision, items) => "updated!".Equals (revision.Properties.Get("status")), null);
            Assert.AreEqual(1, changeRevisions.Count);

            changeRevisions = database.ChangesSince(0, ChangesOptions.Default, 
                (revision, items) => "not updated!".Equals (revision.Properties.Get("status")), null);
            Assert.AreEqual(0, changeRevisions.Count);

            // Delete it:
            var revD = new RevisionInternal(rev2.GetDocId(), null, true);
            ex = Assert.Throws<CouchbaseLiteException>(() => database.PutRevision(revD, null, false));
            Assert.AreEqual(StatusCode.Conflict, ex.Code);

            revD = database.PutRevision(revD, rev2.GetRevId(), false);
            Assert.AreEqual(revD.GetDocId(), rev2.GetDocId());
            Assert.IsTrue(revD.GetRevId().StartsWith("3-"));
            
            // Delete nonexistent doc:
            var revFake = new RevisionInternal("fake", null, true);
            ex = Assert.Throws<CouchbaseLiteException>(() => database.PutRevision(revFake, null, false));
            Assert.AreEqual(StatusCode.NotFound, ex.Code);

            // Read it back (should fail):
            readRev = database.GetDocument(revD.GetDocId(), null, 
                true);
            Assert.IsNull(readRev);

            // Get Changes feed:
            changeRevisions = database.ChangesSince(0, ChangesOptions.Default, null, null);
            Assert.IsTrue(changeRevisions.Count == 1);

            // Get Revision History:
            IList<RevisionInternal> history = database.Storage.GetRevisionHistory(revD, null);
            Assert.AreEqual(revD, history[0]);
            Assert.AreEqual(rev2, history[1]);
            Assert.AreEqual(rev1, history[2]);
        }
예제 #27
0
        // Perform a document operation on the specified database
        private static CouchbaseLiteResponse UpdateDb(ICouchbaseListenerContext context, Database db, string docId, Body body, bool deleting)
        {
            var response = context.CreateResponse();
            if (docId != null) {
                // On PUT/DELETE, get revision ID from either ?rev= query, If-Match: header, or doc body:
                string revParam = context.GetQueryParam("rev");
                string ifMatch = context.RequestHeaders["If-Match"];
                if (ifMatch != null) {
                    if (revParam == null) {
                        revParam = ifMatch;
                    } else if (!revParam.Equals(ifMatch)) {
                        return context.CreateResponse(StatusCode.BadRequest);
                    }
                }

                if (revParam != null && body != null) {
                    var revProp = body.GetPropertyForKey("_rev");
                    if (revProp == null) {
                        // No _rev property in body, so use ?rev= query param instead:
                        var props = body.GetProperties();
                        props["_rev"] = revParam;
                        body = new Body(props);
                    } else if (!revProp.Equals(revParam)) {
                        return context.CreateResponse(StatusCode.BadRequest); // mismatch between _rev and rev
                    }
                }
            }

            RevisionInternal rev;
            StatusCode status = UpdateDocument(context, db, docId, body, deleting, false, out rev);
            if ((int)status < 300) {
                context.CacheWithEtag(rev.GetRevId()); // set ETag
                if (!deleting) {
                    var url = context.RequestUrl;
                    if (docId != null) {
                        response["Location"] = url.AbsoluteUri;
                    }
                }

                response.JsonBody = new Body(new Dictionary<string, object> {
                    { "ok", true },
                    { "id", rev.GetDocId() },
                    { "rev", rev.GetRevId() }
                });
            }

            response.InternalStatus = status;
            return response;
        }
        /// <summary>
        /// Create and update multiple documents at the same time within a single request.
        /// </summary>
        /// <returns>The response state for further HTTP processing</returns>
        /// <param name="context">The context of the Couchbase Lite HTTP request</param>
        /// <remarks>
        /// http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_bulk_docs
        /// </remarks>
        public static ICouchbaseResponseState ProcessDocumentChangeOperations(ICouchbaseListenerContext context)
        {
            return PerformLogicWithDatabase(context, true, db =>
            {
                var postBody = context.BodyAs<Dictionary<string, object>>();
                if(postBody == null) {
                    return context.CreateResponse(StatusCode.BadJson);
                }
                    
                if(!postBody.ContainsKey("docs")) {
                    return context.CreateResponse(StatusCode.BadParam);
                }
                var docs = postBody["docs"].AsList<IDictionary<string, object>>();

                bool allOrNothing;
                postBody.TryGetValue<bool>("all_or_nothing", out allOrNothing);

                bool newEdits;
                postBody.TryGetValue<bool>("new_edits", out newEdits);

                var response = context.CreateResponse();
                StatusCode status = StatusCode.Ok;
                bool success = db.RunInTransaction(() => {
                    List<IDictionary<string, object>> results = new List<IDictionary<string, object>>(docs.Count);
                    var castContext = context as ICouchbaseListenerContext2;
                    var source = castContext != null && !castContext.IsLoopbackRequest ? castContext.Sender : null;
                    foreach(var doc in docs) {
                        string docId = doc.CblID();
                        RevisionInternal rev = null;
                        Body body = new Body(doc);

                        if(!newEdits) {
                            if(!RevisionInternal.IsValid(body)) {
                                status = StatusCode.BadParam;
                            } else {
                                rev = new RevisionInternal(body);
                                var history = Database.ParseCouchDBRevisionHistory(doc);
                                try {
                                    db.ForceInsert(rev, history, source);
                                } catch(CouchbaseLiteException e) {
                                    status = e.Code;
                                }
                            } 
                        } else {
                            status = DocumentMethods.UpdateDocument(context, db, docId, body, false, allOrNothing, out rev);
                        }

                        IDictionary<string, object> result = null;
                        if((int)status < 300) {
                            Debug.Assert(rev != null && rev.RevID != null);
                            if(newEdits) {
                                result = new Dictionary<string, object>
                                {
                                    { "id", rev.DocID },
                                    { "rev", rev.RevID },
                                    { "status", (int)status }
                                };
                            }
                        } else if((int)status >= 500) {
                            return false; // abort the whole thing if something goes badly wrong
                        } else if(allOrNothing) {
                            return false; // all_or_nothing backs out if there's any error
                        } else {
                            var info = Status.ToHttpStatus(status);
                            result = new Dictionary<string, object>
                            {
                                { "id", docId },
                                { "error", info.Item2 },
                                { "status", info.Item1 }
                            };
                        }

                        if(result != null) {
                            results.Add(result);
                        }
                    }

                    response.JsonBody = new Body(results.Cast<object>().ToList());
                    return true;
                });

                if(!success) {
                    response.InternalStatus = status;
                }

                return response;
            }).AsDefaultState();
        }
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public virtual void TestLocalDocs()
 {
     //create a document
     IDictionary<string, object> documentProperties = new Dictionary<string, object>();
     documentProperties.Put("_id", "_local/doc1");
     documentProperties.Put("foo", 1);
     documentProperties.Put("bar", false);
     Body body = new Body(documentProperties);
     RevisionInternal rev1 = new RevisionInternal(body, database);
     Status status = new Status();
     rev1 = database.PutLocalRevision(rev1, null);
     Log.V(Tag, "Created " + rev1);
     NUnit.Framework.Assert.AreEqual("_local/doc1", rev1.GetDocId());
     NUnit.Framework.Assert.IsTrue(rev1.GetRevId().StartsWith("1-"));
     //read it back
     RevisionInternal readRev = database.GetLocalDocument(rev1.GetDocId(), null);
     NUnit.Framework.Assert.IsNotNull(readRev);
     IDictionary<string, object> readRevProps = readRev.GetProperties();
     NUnit.Framework.Assert.AreEqual(rev1.GetDocId(), readRev.GetProperties().Get("_id"
         ));
     NUnit.Framework.Assert.AreEqual(rev1.GetRevId(), readRev.GetProperties().Get("_rev"
         ));
     NUnit.Framework.Assert.AreEqual(UserProperties(readRevProps), UserProperties(body
         .GetProperties()));
     //now update it
     documentProperties = readRev.GetProperties();
     documentProperties.Put("status", "updated!");
     body = new Body(documentProperties);
     RevisionInternal rev2 = new RevisionInternal(body, database);
     RevisionInternal rev2input = rev2;
     rev2 = database.PutLocalRevision(rev2, rev1.GetRevId());
     Log.V(Tag, "Updated " + rev1);
     NUnit.Framework.Assert.AreEqual(rev1.GetDocId(), rev2.GetDocId());
     NUnit.Framework.Assert.IsTrue(rev2.GetRevId().StartsWith("2-"));
     //read it back
     readRev = database.GetLocalDocument(rev2.GetDocId(), null);
     NUnit.Framework.Assert.IsNotNull(readRev);
     NUnit.Framework.Assert.AreEqual(UserProperties(readRev.GetProperties()), UserProperties
         (body.GetProperties()));
     // Try to update the first rev, which should fail:
     bool gotException = false;
     try
     {
         database.PutLocalRevision(rev2input, rev1.GetRevId());
     }
     catch (CouchbaseLiteException e)
     {
         NUnit.Framework.Assert.AreEqual(Status.Conflict, e.GetCBLStatus().GetCode());
         gotException = true;
     }
     NUnit.Framework.Assert.IsTrue(gotException);
     // Delete it:
     RevisionInternal revD = new RevisionInternal(rev2.GetDocId(), null, true, database
         );
     gotException = false;
     try
     {
         RevisionInternal revResult = database.PutLocalRevision(revD, null);
         NUnit.Framework.Assert.IsNull(revResult);
     }
     catch (CouchbaseLiteException e)
     {
         NUnit.Framework.Assert.AreEqual(Status.Conflict, e.GetCBLStatus().GetCode());
         gotException = true;
     }
     NUnit.Framework.Assert.IsTrue(gotException);
     revD = database.PutLocalRevision(revD, rev2.GetRevId());
     // Delete nonexistent doc:
     gotException = false;
     RevisionInternal revFake = new RevisionInternal("_local/fake", null, true, database
         );
     try
     {
         database.PutLocalRevision(revFake, null);
     }
     catch (CouchbaseLiteException e)
     {
         NUnit.Framework.Assert.AreEqual(Status.NotFound, e.GetCBLStatus().GetCode());
         gotException = true;
     }
     NUnit.Framework.Assert.IsTrue(gotException);
     // Read it back (should fail):
     readRev = database.GetLocalDocument(revD.GetDocId(), null);
     NUnit.Framework.Assert.IsNull(readRev);
 }
        /// <summary>
        /// Creates (and executes) a temporary view based on the view function supplied in the JSON request.
        /// </summary>
        /// <returns>The response state for further HTTP processing</returns>
        /// <param name="context">The context of the Couchbase Lite HTTP request</param>
        /// <remarks>
        /// http://docs.couchdb.org/en/latest/api/database/temp-views.html#post--db-_temp_view
        /// </remarks>
        public static ICouchbaseResponseState ExecuteTemporaryViewFunction(ICouchbaseListenerContext context)
        {
            var response = context.CreateResponse();
            if (context.RequestHeaders["Content-Type"] == null || 
                !context.RequestHeaders["Content-Type"].StartsWith("application/json")) {
                response.InternalStatus = StatusCode.UnsupportedType;
                return response.AsDefaultState();
            }

            IEnumerable<byte> json = context.BodyStream.ReadAllBytes();
            var requestBody = new Body(json);
            if (!requestBody.IsValidJSON()) {
                response.InternalStatus = StatusCode.BadJson;
                return response.AsDefaultState();
            }

            var props = requestBody.GetProperties();
            if (props == null) {
                response.InternalStatus = StatusCode.BadJson;
                return response.AsDefaultState();
            }

            var options = context.QueryOptions;
            if (options == null) {
                response.InternalStatus = StatusCode.BadRequest;
                return response.AsDefaultState();
            }

            return PerformLogicWithDatabase(context, true, db =>
            {
                if (context.CacheWithEtag(db.GetLastSequenceNumber().ToString())) {
                    response.InternalStatus = StatusCode.NotModified;
                    return response;
                }

                var view = db.GetView("@@TEMPVIEW@@");
                var status = view.Compile(props, "javascript");
                if(status.IsError) {
                    response.InternalStatus = status.Code;
                    return response;
                }

                try {
                    view.UpdateIndex_Internal();
                    return QueryView(context, null, view, options);
                } catch(CouchbaseLiteException e) {
                    response.InternalStatus = e.CBLStatus.Code;
                }

                return response;
            }).AsDefaultState();

        }
        public void TestPusherDeletedDoc()
        {
            if (!Boolean.Parse((string)Runtime.Properties["replicationTestsEnabled"]))
            {
                Assert.Inconclusive("Replication tests disabled.");
                return;
            }
            var remote = GetReplicationURL();
            var docIdTimestamp = Convert.ToString(Runtime.CurrentTimeMillis());

            // Create some documentsConvert
            var documentProperties = new Dictionary<string, object>();
            var doc1Id = string.Format("doc1-{0}", docIdTimestamp);
            documentProperties["_id"] = doc1Id;
            documentProperties["foo"] = 1;
            documentProperties["bar"] = false;

            var body = new Body(documentProperties);
            var rev1 = new RevisionInternal(body);
            var status = new Status();
            rev1 = database.PutRevision(rev1, null, false, status);
            Assert.AreEqual(StatusCode.Created, status.Code);

            documentProperties["_rev"] = rev1.GetRevId();
            documentProperties["UPDATED"] = true;
            documentProperties["_deleted"] = true;
            database.PutRevision(new RevisionInternal(documentProperties), rev1.GetRevId(), false, status);
            Assert.IsTrue((int)status.Code >= 200 && (int)status.Code < 300);

            var repl = database.CreatePushReplication(remote);
            if (!IsSyncGateway(remote)) {
                ((Pusher)repl).CreateTarget = true;
            }

            RunReplication(repl);

            Assert.IsNull(repl.LastError);

            // make sure doc1 is deleted
            var replicationUrlTrailing = new Uri(string.Format ("{0}/", remote));
            var pathToDoc = new Uri(replicationUrlTrailing, doc1Id);
            Log.D(Tag, "Send http request to " + pathToDoc);
            var httpRequestDoneSignal = new CountDownLatch(1);
                var httpclient = new HttpClient();
                try
                {
                    var getDocResponse = httpclient.GetAsync(pathToDoc.ToString()).Result;
                    var statusLine = getDocResponse.StatusCode;
                    Log.D(ReplicationTest.Tag, "statusLine " + statusLine);
                    Assert.AreEqual(Couchbase.Lite.StatusCode.NotFound, statusLine.GetStatusCode());                        
                }
                catch (ProtocolViolationException e)
                {
                    Assert.IsNull(e, "Got ClientProtocolException: " + e.Message);
                }
                catch (IOException e)
                {
                    Assert.IsNull(e, "Got IOException: " + e.Message);
                }
                finally
                {
                    httpRequestDoneSignal.CountDown();
                }
            Log.D(Tag, "Waiting for http request to finish");
            try
            {
                httpRequestDoneSignal.Await(TimeSpan.FromSeconds(10));
                Log.D(Tag, "http request finished");
            }
            catch (Exception e)
            {
                Runtime.PrintStackTrace(e);
            }
            Log.D(Tag, "testPusherDeletedDoc() finished");
        }
예제 #32
0
 public virtual void SetProperties(IDictionary <string, object> properties)
 {
     this.body = new Body(properties);
 }
        public void TestPusherDeletedDoc()
        {
            if (!Boolean.Parse((string)GetProperty("replicationTestsEnabled")))
            {
                Assert.Inconclusive("Replication tests disabled.");
                return;
            }

            using (var remoteDb = _sg.CreateDatabase(TempDbName())) {
                var remote = remoteDb.RemoteUri;
                var docIdTimestamp = Convert.ToString((ulong)DateTime.UtcNow.TimeSinceEpoch().TotalMilliseconds);

                // Create some documentsConvert
                var documentProperties = new Dictionary<string, object>();
                var doc1Id = string.Format("doc1-{0}", docIdTimestamp);
                documentProperties["_id"] = doc1Id;
                documentProperties["foo"] = 1;
                documentProperties["bar"] = false;

                var body = new Body(documentProperties);
                var rev1 = new RevisionInternal(body);
                rev1 = database.PutRevision(rev1, null, false);

                documentProperties.SetRevID(rev1.RevID);
                documentProperties["UPDATED"] = true;
                documentProperties["_deleted"] = true;
                database.PutRevision(new RevisionInternal(documentProperties), rev1.RevID, false);

                var repl = database.CreatePushReplication(remote);
                if (!IsSyncGateway(remote)) {
                    ((Pusher)repl).CreateTarget = true;
                }

                RunReplication(repl);

                Assert.IsNull(repl.LastError);

                // make sure doc1 is deleted
                var replicationUrlTrailing = new Uri(string.Format("{0}/", remote));
                var pathToDoc = new Uri(replicationUrlTrailing, doc1Id);
                WriteDebug("Send http request to " + pathToDoc);
                var httpRequestDoneSignal = new CountdownEvent(1);
                using (var httpclient = new HttpClient()) {
                    try {
                        var getDocResponse = httpclient.GetAsync(pathToDoc.ToString()).Result;
                        var statusLine = getDocResponse.StatusCode;
                        WriteDebug("statusLine " + statusLine);
                        Assert.AreEqual(Couchbase.Lite.StatusCode.NotFound, statusLine.GetStatusCode());                        
                    }
                    catch (ProtocolViolationException e) {
                        Assert.IsNull(e, "Got ClientProtocolException: " + e.Message);
                    }
                    catch (IOException e) {
                        Assert.IsNull(e, "Got IOException: " + e.Message);
                    }
                    finally {
                        httpRequestDoneSignal.Signal();
                    }
                    WriteDebug("Waiting for http request to finish");
                    try {
                        httpRequestDoneSignal.Wait(TimeSpan.FromSeconds(10));
                        WriteDebug("http request finished");
                    }
                    catch (Exception e) {
                        Console.WriteLine("Exception during TestPusherDeletedDoc", e);
                    }
                }
            }
        }
예제 #34
0
 internal RevisionInternal(Body body)
     : this(body.GetPropertyForKey <string>("_id"), body.GetPropertyForKey <string>("_rev"), body.GetPropertyForKey <bool>("_deleted"))
 {
     this._body = body;
 }
        /// <summary>
        /// A database purge permanently removes the references to deleted documents from the database.
        /// </summary>
        /// <returns>The response state for further HTTP processing</returns>
        /// <param name="context">The context of the Couchbase Lite HTTP request</param>
        /// <remarks>
        /// http://docs.couchdb.org/en/latest/api/database/misc.html#post--db-_purge
        /// </remarks>
        public static ICouchbaseResponseState Purge(ICouchbaseListenerContext context)
        {
            return PerformLogicWithDatabase(context, true, db =>
            {
                var body = context.BodyAs<Dictionary<string, IList<string>>>();
                if(body == null) {
                    return context.CreateResponse(StatusCode.BadJson);
                }

                var purgedRevisions = db.Storage.PurgeRevisions(body);
                if(purgedRevisions == null) {
                    return context.CreateResponse(StatusCode.DbError);
                }

                var responseBody = new Body(new Dictionary<string, object>
                {
                    { "purged", purgedRevisions }
                });

                var retVal = context.CreateResponse();
                retVal.JsonBody = responseBody;
                return retVal;
            }).AsDefaultState();
        }
예제 #36
0
		/// <exception cref="System.Exception"></exception>
		public virtual void TestPusherDeletedDoc()
		{
			CountDownLatch replicationDoneSignal = new CountDownLatch(1);
			Uri remote = GetReplicationURL();
			string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis());
			// Create some documents:
			IDictionary<string, object> documentProperties = new Dictionary<string, object>();
			string doc1Id = string.Format("doc1-%s", docIdTimestamp);
			documentProperties.Put("_id", doc1Id);
			documentProperties.Put("foo", 1);
			documentProperties.Put("bar", false);
			Body body = new Body(documentProperties);
			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());
			documentProperties.Put("_rev", rev1.GetRevId());
			documentProperties.Put("UPDATED", true);
			documentProperties.Put("_deleted", true);
			RevisionInternal rev2 = database.PutRevision(new RevisionInternal(documentProperties
				, database), rev1.GetRevId(), false, status);
			NUnit.Framework.Assert.IsTrue(status.GetCode() >= 200 && status.GetCode() < 300);
			Replication repl = database.CreatePushReplication(remote);
			((Pusher)repl).SetCreateTarget(true);
			RunReplication(repl);
			// make sure doc1 is deleted
			Uri replicationUrlTrailing = new Uri(string.Format("%s/", remote.ToExternalForm()
				));
			Uri pathToDoc = new Uri(replicationUrlTrailing, doc1Id);
			Log.D(Tag, "Send http request to " + pathToDoc);
			CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
			BackgroundTask getDocTask = new _BackgroundTask_216(pathToDoc, httpRequestDoneSignal
				);
			getDocTask.Execute();
			Log.D(Tag, "Waiting for http request to finish");
			try
			{
				httpRequestDoneSignal.Await(300, TimeUnit.Seconds);
				Log.D(Tag, "http request finished");
			}
			catch (Exception e)
			{
				Sharpen.Runtime.PrintStackTrace(e);
			}
			Log.D(Tag, "testPusherDeletedDoc() finished");
		}
        /// <summary>
        /// Queries the specified view using the specified options
        /// </summary>
        /// <returns>The HTTP response containing the results of the query</returns>
        /// <param name="context">The request context</param>
        /// <param name="db">The database to run the query in</param>
        /// <param name="view">The view to query</param>
        /// <param name="options">The options to apply to the query</param>
        public static CouchbaseLiteResponse QueryView(ICouchbaseListenerContext context, Database db, View view, QueryOptions options)
        {
            var result = view.QueryWithOptions(options);

            object updateSeq = options.UpdateSeq ? (object)view.LastSequenceIndexed : null;
            var mappedResult = new List<object>();
            foreach (var row in result) {
                row.Database = db;
                var dict = row.AsJSONDictionary();
                if (context.ContentOptions != DocumentContentOptions.None) {
                    var doc = dict.Get("doc").AsDictionary<string, object>();
                    if (doc != null) {
                        // Add content options:
                        RevisionInternal rev = new RevisionInternal(doc);
                        var status = new Status();
                        rev = DocumentMethods.ApplyOptions(context.ContentOptions, rev, context, db, status);
                        if (rev != null) {
                            dict["doc"] = rev.GetProperties();
                        }
                    }
                }

                mappedResult.Add(dict);
            }

            var body = new Body(new NonNullDictionary<string, object> {
                { "rows", mappedResult },
                { "total_rows", view.TotalRows },
                { "offset", options.Skip },
                { "update_seq", updateSeq }
            });

            var retVal = context.CreateResponse();
            retVal.JsonBody = body;
            return retVal;
        }
예제 #38
0
		/// <exception cref="System.Exception"></exception>
		public virtual void TestPusher()
		{
			CountDownLatch replicationDoneSignal = new CountDownLatch(1);
			Uri remote = GetReplicationURL();
			string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis());
			// Create some documents:
			IDictionary<string, object> documentProperties = new Dictionary<string, object>();
			string doc1Id = string.Format("doc1-%s", docIdTimestamp);
			documentProperties.Put("_id", doc1Id);
			documentProperties.Put("foo", 1);
			documentProperties.Put("bar", false);
			Body body = new Body(documentProperties);
			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());
			documentProperties.Put("_rev", rev1.GetRevId());
			documentProperties.Put("UPDATED", true);
			RevisionInternal rev2 = database.PutRevision(new RevisionInternal(documentProperties
				, database), rev1.GetRevId(), false, status);
			NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
			documentProperties = new Dictionary<string, object>();
			string doc2Id = string.Format("doc2-%s", docIdTimestamp);
			documentProperties.Put("_id", doc2Id);
			documentProperties.Put("baz", 666);
			documentProperties.Put("fnord", true);
			database.PutRevision(new RevisionInternal(documentProperties, database), null, false
				, status);
			NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
			bool continuous = false;
			Replication repl = database.CreatePushReplication(remote);
			repl.SetContinuous(continuous);
			repl.SetCreateTarget(true);
			// Check the replication's properties:
			NUnit.Framework.Assert.AreEqual(database, repl.GetLocalDatabase());
			NUnit.Framework.Assert.AreEqual(remote, repl.GetRemoteUrl());
			NUnit.Framework.Assert.IsFalse(repl.IsPull());
			NUnit.Framework.Assert.IsFalse(repl.IsContinuous());
			NUnit.Framework.Assert.IsTrue(repl.ShouldCreateTarget());
			NUnit.Framework.Assert.IsNull(repl.GetFilter());
			NUnit.Framework.Assert.IsNull(repl.GetFilterParams());
			// TODO: CAssertNil(r1.doc_ids);
			// TODO: CAssertNil(r1.headers);
			// Check that the replication hasn't started running:
			NUnit.Framework.Assert.IsFalse(repl.IsRunning());
			NUnit.Framework.Assert.AreEqual(Replication.ReplicationStatus.ReplicationStopped, 
				repl.GetStatus());
			NUnit.Framework.Assert.AreEqual(0, repl.GetCompletedChangesCount());
			NUnit.Framework.Assert.AreEqual(0, repl.GetChangesCount());
			NUnit.Framework.Assert.IsNull(repl.GetLastError());
			RunReplication(repl);
			// make sure doc1 is there
			// TODO: make sure doc2 is there (refactoring needed)
			Uri replicationUrlTrailing = new Uri(string.Format("%s/", remote.ToExternalForm()
				));
			Uri pathToDoc = new Uri(replicationUrlTrailing, doc1Id);
			Log.D(Tag, "Send http request to " + pathToDoc);
			CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
			BackgroundTask getDocTask = new _BackgroundTask_122(pathToDoc, doc1Id, httpRequestDoneSignal
				);
			//Closes the connection.
			getDocTask.Execute();
			Log.D(Tag, "Waiting for http request to finish");
			try
			{
				httpRequestDoneSignal.Await(300, TimeUnit.Seconds);
				Log.D(Tag, "http request finished");
			}
			catch (Exception e)
			{
				Sharpen.Runtime.PrintStackTrace(e);
			}
			Log.D(Tag, "testPusher() finished");
		}