コード例 #1
0
        public void TestIssue490()
        {
            var sg = new CouchDB("http", GetReplicationServer());
            using (var remoteDb = sg.CreateDatabase("issue490")) {

                var push = database.CreatePushReplication(remoteDb.RemoteUri);
                CreateFilteredDocuments(database, 30);
                CreateNonFilteredDocuments (database, 10);
                RunReplication(push);
                Assert.IsTrue(push.ChangesCount==40);
                Assert.IsTrue(push.CompletedChangesCount==40);

                Assert.IsNull(push.LastError);
                Assert.AreEqual(40, database.DocumentCount);

                for (int i = 0; i <= 5; i++) {
                    pull = database.CreatePullReplication(remoteDb.RemoteUri);
                    pull.Continuous = true;
                    pull.Start ();
                    Task.Delay (1000).Wait();
                    CallToView ();
                    Task.Delay (2000).Wait();
                    RecreateDatabase ();
                }
            }

        }
コード例 #2
0
        private void UpdateReplications(string syncURL)
        {
            
            if (_puller != null)
            {
                _puller.Stop();
            }

            if(_pusher != null)
            {
                _pusher.Stop();
            }

            if (String.IsNullOrEmpty(syncURL))
            {
                return;
            }

            var uri = new Uri(syncURL);
            _puller = _db.CreatePullReplication(uri);
            _puller.Continuous = true;
            _puller.Start();

            _pusher = _db.CreatePushReplication(uri);
            _pusher.Continuous = true;
            _pusher.Start();
        }
コード例 #3
0
        public void StartReplications()
        {
            var push = database.CreatePushReplication(config.Gateway.Uri);
            var pull = database.CreatePullReplication(config.Gateway.Uri);

            var auth = AuthenticatorFactory.CreateBasicAuthenticator(config.User.Name, config.User.Password);

            push.Authenticator = auth;
            pull.Authenticator = auth;

            push.Headers = config.CustomHeaders;
            pull.Headers = config.CustomHeaders;

            push.Continuous = true;
            pull.Continuous = true;

            push.Changed += (sender, e) =>
            {
                // Will be called when the push replication status changes
            };
            pull.Changed += (sender, e) =>
            {
                // Will be called when the pull replication status changes
            };

            //push.Start();
            pull.Start();

            this.push = push;
            this.pull = pull;
        }
コード例 #4
0
	private IEnumerator Start () {
		Debug.LogFormat ("Data path = {0}", Application.persistentDataPath);

#if UNITY_EDITOR_WIN
		Log.SetLogger(new UnityLogger());
#endif
		_db = Manager.SharedInstance.GetDatabase ("spaceshooter");
		_pull = _db.CreatePullReplication (GameController.SYNC_URL);
		_pull.Continuous = true;
		_pull.Start ();
		while (_pull != null && _pull.Status == ReplicationStatus.Active) {
			yield return new WaitForSeconds(0.5f);
		}

		var doc = _db.GetExistingDocument ("player_data");
		if (doc != null) {
			//We have a record!  Get the ship data, if possible.
			string assetName = String.Empty;
			if(doc.UserProperties.ContainsKey("ship_data")) {
				assetName = doc.UserProperties ["ship_data"] as String;
			}
			StartCoroutine(LoadAsset (assetName));
		} else {
			//Create a new record
			doc = _db.GetDocument("player_data");
			doc.PutProperties(new Dictionary<string, object> { { "ship_data", String.Empty } });
		}

		doc.Change += DocumentChanged;
		_push = _db.CreatePushReplication (new Uri ("http://127.0.0.1:4984/spaceshooter"));
		_push.Start();
	}
コード例 #5
0
	public GameObject defaultShip;		//The ship object to use when no alternate is specified

	#endregion

	#region Public Methods

	/// <summary>
	/// Signals that the game is over
	/// </summary>
	public void GameOver()
	{
		//Unregister listeners and stop replication
		var doc = _db.GetExistingDocument ("player_data");
		if (doc != null) {
			doc.Change -= DocumentChanged;
		}

		if (_pull != null) {
			_pull.Stop ();
			_pull = null;
		}
	}
コード例 #6
0
        public void StartSyncGateway(string url = "")
        {
            pull = _database.CreatePullReplication(CreateSyncUri());
            push = _database.CreatePushReplication(CreateSyncUri());

            var authenticator = AuthenticatorFactory.CreateBasicAuthenticator("david", "12345");
            pull.Authenticator = authenticator;
            push.Authenticator = authenticator;

            pull.Continuous = true;
            push.Continuous = true;

            pull.Changed += Pull_Changed;
            push.Changed += Push_Changed;

            pull.Start();
            push.Start();
        }
コード例 #7
0
        public void StopReplication(Replication replication)
        {
            if (replication.Status == ReplicationStatus.Stopped)
            {
                return;
            }

            var replicationDoneSignal      = new CountdownEvent(1);
            var replicationStoppedObserver = new ReplicationStoppedObserver(replicationDoneSignal);

            replication.Changed += replicationStoppedObserver.Changed;
            replication.Stop();

            var success = replicationDoneSignal.Wait(TimeSpan.FromSeconds(10));

            Assert.IsTrue(success);

            // give a little padding to give it a chance to save a checkpoint
            Sleep(2 * 1000);
        }
コード例 #8
0
        /// <exception cref="System.Exception"></exception>
        public virtual void TestGetActiveReplications()
        {
            Uri         remote      = GetReplicationURL();
            Replication replication = (Replication)database.CreatePullReplication(remote);

            NUnit.Framework.Assert.AreEqual(0, database.GetAllReplications().Count);
            NUnit.Framework.Assert.AreEqual(0, database.GetActiveReplications().Count);
            replication.Start();
            NUnit.Framework.Assert.AreEqual(1, database.GetAllReplications().Count);
            NUnit.Framework.Assert.AreEqual(1, database.GetActiveReplications().Count);
            CountDownLatch replicationDoneSignal = new CountDownLatch(1);

            LiteTestCase.ReplicationFinishedObserver replicationFinishedObserver = new LiteTestCase.ReplicationFinishedObserver
                                                                                       (replicationDoneSignal);
            replication.AddChangeListener(replicationFinishedObserver);
            bool success = replicationDoneSignal.Await(60, TimeUnit.Seconds);

            NUnit.Framework.Assert.IsTrue(success);
            NUnit.Framework.Assert.AreEqual(1, database.GetAllReplications().Count);
            NUnit.Framework.Assert.AreEqual(0, database.GetActiveReplications().Count);
        }
コード例 #9
0
        public void StartSync(string syncUrl)
        {
            Uri uri;
            try {
                uri = new Uri(syncUrl);
            } catch(UriFormatException) {
                Log.E("TaskManager", "Invalid URL {0}", syncUrl);
                return;
            }

            if(_pull == null) {
                _pull = _db.CreatePullReplication(uri);
                _pull.Continuous = true;
                _pull.Start();
            }

            if(_push == null) {
                _push = _db.CreatePushReplication(uri);
                _push.Continuous = true;
                _push.Start();
            }
        }
コード例 #10
0
        private static CountdownEvent ReplicationWatcherThread(Replication replication)
        {
            var started    = replication.IsRunning;
            var doneSignal = new CountdownEvent(1);

            Task.Factory.StartNew(() =>
            {
                var done = false;
                while (!done)
                {
                    if (replication.IsRunning)
                    {
                        started = true;
                    }

                    var statusIsDone = (
                        replication.Status == ReplicationStatus.Stopped ||
                        replication.Status == ReplicationStatus.Idle
                        );

                    if (started && statusIsDone)
                    {
                        done = true;
                    }

                    try
                    {
                        System.Threading.Thread.Sleep(1000);
                    }
                    catch (Exception e)
                    {
                        Runtime.PrintStackTrace(e);
                    }
                }
                doneSignal.Signal();
            });

            return(doneSignal);
        }
コード例 #11
0
        private void RunReplication(Replication replication)
        {
            var replicationDoneSignal = new CountDownLatch(1);
            var observer = new ReplicationObserver(replicationDoneSignal);

            replication.Changed += observer.Changed;
            replication.Start();

            var replicationDoneSignalPolling = ReplicationWatcherThread(replication);

            Log.D(Tag, "Waiting for replicator to finish.");

            var success = replicationDoneSignal.Await(TimeSpan.FromSeconds(15));

            Assert.IsTrue(success);
            success = replicationDoneSignalPolling.Wait(TimeSpan.FromSeconds(15));
            Assert.IsTrue(success);

            Log.D(Tag, "replicator finished");

            replication.Changed -= observer.Changed;
        }
コード例 #12
0
        private static CountdownEvent ReplicationWatcherThread(Replication replication)
        {
            var started = replication.IsRunning;
            var doneSignal = new CountdownEvent(1);

            Task.Factory.StartNew(()=>
            {
                var done = false;
                while (!done)
                {
                    if (replication.IsRunning)
                    {
                        started = true;
                    }

                    var statusIsDone = (
                        replication.Status == ReplicationStatus.Stopped 
                        || replication.Status == ReplicationStatus.Idle
                    );

                    if (started && statusIsDone)
                    {
                        done = true;
                    }

                    try
                    {
                        System.Threading.Thread.Sleep(1000);
                    }
                    catch (Exception e)
                    {
                        Runtime.PrintStackTrace(e);
                    }
                }
                doneSignal.Signal();
            });

            return doneSignal;
        }
コード例 #13
0
        private Replication CreateReplication(Database db, bool push)
        {
            Replication repl = null;

            if (push)
            {
                repl = db.CreatePushReplication(_listenerDBUri);
            }
            else
            {
                repl = db.CreatePullReplication(_listenerDBUri);
            }

            if (_authScheme == AuthenticationSchemes.Basic)
            {
                repl.Authenticator = new BasicAuthenticator("bob", "slack");
            }
            else if (_authScheme == AuthenticationSchemes.Digest)
            {
                repl.Authenticator = new DigestAuthenticator("bob", "slack");
            }

            return(repl);
        }
コード例 #14
0
 public ReplicationChangeEventArgs(Replication sender)
 {
     Source = sender;
 }
コード例 #15
0
 internal void AddActiveReplication(Replication replication)
 {
     ActiveReplicators.Add(replication);
     replication.Changed += (sender, e) => 
     {
         if (e.Source != null && !e.Source.IsRunning && ActiveReplicators != null)
         {
             ActiveReplicators.Remove(e.Source);
         }
     };
 }
コード例 #16
0
        // This is used by the listener
        internal Replication ReplicationWithProperties(IDictionary <string, object> properties)
        {
            // Extract the parameters from the JSON request body:
            // http://wiki.apache.org/couchdb/Replication

            bool push, createTarget;
            var  results = new Dictionary <string, object>()
            {
                { "database", null },
                { "remote", null },
                { "headers", null },
                { "authorizer", null }
            };

            Status result = ParseReplicationProperties(properties, out push, out createTarget, results);

            if (result.IsError)
            {
                throw Misc.CreateExceptionAndLog(Log.To.Listener, result.Code, TAG, "Failed to create replication");
            }

            object continuousObj = properties.Get("continuous");
            bool   continuous    = false;

            if (continuousObj is bool)
            {
                continuous = (bool)continuousObj;
            }

            var         scheduler = new SingleTaskThreadpoolScheduler();
            Replication rep       = null;

            if (push)
            {
                rep = new Pusher((Database)results["database"], (Uri)results["remote"], continuous, new TaskFactory(scheduler));
            }
            else
            {
                rep = new Puller((Database)results["database"], (Uri)results["remote"], continuous, new TaskFactory(scheduler));
            }

            rep.Filter       = properties.Get("filter") as string;
            rep.FilterParams = properties.Get("query_params").AsDictionary <string, object>();
            rep.DocIds       = properties.Get("doc_ids").AsList <string>();
            rep.Headers      = new Dictionary <string, string>();
            foreach (var header in results.Get("headers").AsDictionary <string, string>())
            {
                if (header.Key.ToLowerInvariant() == "cookie")
                {
                    var cookie = default(Cookie);
                    if (CookieParser.TryParse(header.Value, ((Uri)results["remote"]).GetLeftPart(UriPartial.Authority), out cookie))
                    {
                        rep.SetCookie(cookie.Name, cookie.Value, cookie.Path, cookie.Expires, cookie.Secure, cookie.HttpOnly);
                    }
                    else
                    {
                        Log.To.Listener.W(TAG, "Invalid cookie string received ({0}), ignoring...", header.Value);
                    }
                }
                else
                {
                    rep.Headers.Add(header.Key, header.Value);
                }
            }
            rep.Headers       = results.Get("headers").AsDictionary <string, string>();
            rep.Authenticator = results.Get("authorizer") as IAuthenticator;
            if (push)
            {
                ((Pusher)rep).CreateTarget = createTarget;
            }

            var db = (Database)results["database"];

            // If this is a duplicate, reuse an existing replicator:
            var activeReplicators = default(IList <Replication>);
            var existing          = default(Replication);

            if (db.ActiveReplicators.AcquireTemp(out activeReplicators))
            {
                existing = activeReplicators.FirstOrDefault(x => x.LocalDatabase == rep.LocalDatabase &&
                                                            x.RemoteUrl == rep.RemoteUrl && x.IsPull == rep.IsPull &&
                                                            x.RemoteCheckpointDocID().Equals(rep.RemoteCheckpointDocID()));
            }


            return(existing ?? rep);
        }
コード例 #17
0
        private void RunReplication(Replication replication)
        {
            var replicationDoneSignal = new CountDownLatch(1);
            var observer = new ReplicationObserver(replicationDoneSignal);
            replication.Changed += observer.Changed;
            replication.Start();

            var replicationDoneSignalPolling = ReplicationWatcherThread(replication);

            Log.D(Tag, "Waiting for replicator to finish.");

                var success = replicationDoneSignal.Await(TimeSpan.FromSeconds(15));
                Assert.IsTrue(success);
                success = replicationDoneSignalPolling.Wait(TimeSpan.FromSeconds(15));
                Assert.IsTrue(success);

                Log.D(Tag, "replicator finished");

            replication.Changed -= observer.Changed;
        }
    void UpdateSyncUrl ()
    {
        if (Database == null)
            return;

        Uri newRemoteUrl = null;
        var syncPoint = NSUserDefaults.StandardUserDefaults.StringForKey (ConfigViewController.SyncUrlKey);
        if (!String.IsNullOrWhiteSpace (syncPoint))
            newRemoteUrl = new Uri (syncPoint);
        else
            return;
        ForgetSync ();

        pull = Database.CreatePullReplication (newRemoteUrl);
            push = Database.CreatePushReplication (newRemoteUrl);
        pull.Continuous = push.Continuous = true;
        pull.Changed += ReplicationProgress;
        push.Changed += ReplicationProgress;
        pull.Start();
        push.Start();
    }
コード例 #19
0
 public _Runnable_372(Replication replication, CountDownLatch doneSignal)
 {
     this.replication = replication;
     this.doneSignal  = doneSignal;
 }
コード例 #20
0
        internal void AddActiveReplication(Replication replication)
        {
            if (ActiveReplicators == null) {
                Log.W(TAG, "ActiveReplicators is null, so replication will not be added");
                return;
            }

            ActiveReplicators.Add(replication);
            replication.Changed += (sender, e) => 
            {
                if (e.Source != null && !e.Source.IsRunning && ActiveReplicators != null)
                {
                    ActiveReplicators.Remove(e.Source);
                }
            };
        }
コード例 #21
0
        protected virtual void RunReplication(Replication replication)
        {
            var replicationDoneSignal = new CountdownEvent(1);
            var observer = new ReplicationObserver(replicationDoneSignal);
            replication.Changed += observer.Changed;
            replication.Start();
            var success = replicationDoneSignal.Wait(TimeSpan.FromSeconds(60));
            Assert.IsTrue(success);

            replication.Changed -= observer.Changed;
        }
コード例 #22
0
        public void TestFacebookAuth()
        {
            var doneEvent = new ManualResetEvent(false);

            var accountStore = new ACAccountStore();
            var accountType  = accountStore.FindAccountType(ACAccountType.Facebook);

            var options = new AccountStoreOptions();

            options.FacebookAppId = FacebookAppId;
            options.SetPermissions(ACFacebookAudience.Friends, new [] { "email" });

            var       success = true;
            ACAccount account = null;

            accountStore.RequestAccess(accountType, options, (result, error) =>
            {
                success = result;
                if (success)
                {
                    var accounts = accountStore.FindAccounts(accountType);
                    account      = accounts != null && accounts.Length > 0 ? accounts[0] : null;
                }
                else
                {
                    Log.W(Tag, "Facebook Login needed. Go to Settings > Facebook and login.");
                    Log.E(Tag, "Facebook Request Access Error : " + error);
                }
                doneEvent.Set();
            });

            doneEvent.WaitOne(TimeSpan.FromSeconds(30));

            Assert.IsTrue(success);
            Assert.IsNotNull(account);

            var token = account.Credential.OAuthToken;

            Assert.IsNotNull(token);
            Assert.IsTrue(token.Length > 0);

            var url = GetReplicationURLWithoutCredentials();

            var cookieStore       = new CookieStore();
            var httpClientFactory = new CouchbaseLiteHttpClientFactory(cookieStore);

            manager.DefaultHttpClientFactory = httpClientFactory;
            Replication replicator = database.CreatePushReplication(url);

            replicator.Authenticator = AuthenticatorFactory.CreateFacebookAuthenticator(token);

            Assert.IsNotNull(replicator);
            Assert.IsNotNull(replicator.Authenticator);
            Assert.IsTrue(replicator.Authenticator is TokenAuthenticator);

            replicator.Start();

            doneEvent.Reset();
            Task.Factory.StartNew(() =>
            {
                var timeout = DateTime.UtcNow + TimeSpan.FromSeconds(30);
                while (DateTime.UtcNow < timeout)
                {
                    if (!replicator.active)
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(10));
                }
                doneEvent.Set();
            });
            doneEvent.WaitOne(TimeSpan.FromSeconds(35));

            var urlStr = url.ToString();

            urlStr = urlStr.EndsWith("/") ? urlStr : urlStr + "/";
            var cookies = httpClientFactory.GetCookieContainer().GetCookies(new Uri(urlStr));

            Assert.IsTrue(cookies.Count == 1);
            Assert.AreEqual("SyncGatewaySession", cookies[0].Name);
        }
コード例 #23
0
        public virtual Replication GetReplicator(IDictionary <string, object> properties)
        {
            // TODO: in the iOS equivalent of this code, there is: {@"doc_ids", _documentIDs}) - write unit test that detects this bug
            // TODO: ditto for "headers"
            Authorizer  authorizer = null;
            Replication repl       = null;
            Uri         remote     = null;
            IDictionary <string, object> remoteMap;
            IDictionary <string, object> sourceMap = ParseSourceOrTarget(properties, "source");
            IDictionary <string, object> targetMap = ParseSourceOrTarget(properties, "target");
            string source = (string)sourceMap.Get("url");
            string target = (string)targetMap.Get("url");
            bool   createTargetBoolean = (bool)properties.Get("create_target");
            bool   createTarget        = (createTargetBoolean != null && createTargetBoolean);
            bool   continuousBoolean   = (bool)properties.Get("continuous");
            bool   continuous          = (continuousBoolean != null && continuousBoolean);
            bool   cancelBoolean       = (bool)properties.Get("cancel");
            bool   cancel = (cancelBoolean != null && cancelBoolean);

            // Map the 'source' and 'target' JSON params to a local database and remote URL:
            if (source == null || target == null)
            {
                throw new CouchbaseLiteException("source and target are both null", new Status(Status
                                                                                               .BadRequest));
            }
            bool     push      = false;
            Database db        = null;
            string   remoteStr = null;

            if (Couchbase.Lite.Manager.IsValidDatabaseName(source))
            {
                db        = GetExistingDatabase(source);
                remoteStr = target;
                push      = true;
                remoteMap = targetMap;
            }
            else
            {
                remoteStr = source;
                if (createTarget && !cancel)
                {
                    bool mustExist = false;
                    db = GetDatabaseWithoutOpening(target, mustExist);
                    if (!db.Open())
                    {
                        throw new CouchbaseLiteException("cannot open database: " + db, new Status(Status
                                                                                                   .InternalServerError));
                    }
                }
                else
                {
                    db = GetExistingDatabase(target);
                }
                if (db == null)
                {
                    throw new CouchbaseLiteException("database is null", new Status(Status.NotFound));
                }
                remoteMap = sourceMap;
            }
            IDictionary <string, object> authMap = (IDictionary <string, object>)remoteMap.Get(
                "auth");

            if (authMap != null)
            {
                IDictionary <string, object> persona = (IDictionary <string, object>)authMap.Get("persona"
                                                                                                 );
                if (persona != null)
                {
                    string email = (string)persona.Get("email");
                    authorizer = new PersonaAuthorizer(email);
                }
                IDictionary <string, object> facebook = (IDictionary <string, object>)authMap.Get("facebook"
                                                                                                  );
                if (facebook != null)
                {
                    string email = (string)facebook.Get("email");
                    authorizer = new FacebookAuthorizer(email);
                }
            }
            try
            {
                remote = new Uri(remoteStr);
            }
            catch (UriFormatException)
            {
                throw new CouchbaseLiteException("malformed remote url: " + remoteStr, new Status
                                                     (Status.BadRequest));
            }
            if (remote == null || !remote.Scheme.StartsWith("http"))
            {
                throw new CouchbaseLiteException("remote URL is null or non-http: " + remoteStr,
                                                 new Status(Status.BadRequest));
            }
            if (!cancel)
            {
                repl = db.GetReplicator(remote, GetDefaultHttpClientFactory(), push, continuous,
                                        GetWorkExecutor());
                if (repl == null)
                {
                    throw new CouchbaseLiteException("unable to create replicator with remote: " + remote
                                                     , new Status(Status.InternalServerError));
                }
                if (authorizer != null)
                {
                    repl.SetAuthorizer(authorizer);
                }
                string filterName = (string)properties.Get("filter");
                if (filterName != null)
                {
                    repl.SetFilter(filterName);
                    IDictionary <string, object> filterParams = (IDictionary <string, object>)properties
                                                                .Get("query_params");
                    if (filterParams != null)
                    {
                        repl.SetFilterParams(filterParams);
                    }
                }
                if (push)
                {
                    ((Pusher)repl).SetCreateTarget(createTarget);
                }
            }
            else
            {
                // Cancel replication:
                repl = db.GetActiveReplicator(remote, push);
                if (repl == null)
                {
                    throw new CouchbaseLiteException("unable to lookup replicator with remote: " + remote
                                                     , new Status(Status.NotFound));
                }
            }
            return(repl);
        }
    void ReplicationProgress (object replication, ReplicationChangeEventArgs args)
    {
        var active = args.Source;
            Debug.WriteLine (String.Format ("Push: {0}, Pull: {1}", push.Status, pull.Status));

      int lastTotal = 0;

      if (_leader == null) {
        if (active.IsPull && (pull.Status == ReplicationStatus.Active && push.Status != ReplicationStatus.Active)) {
          _leader = pull;
        } else if (!active.IsPull && (push.Status == ReplicationStatus.Active && pull.Status != ReplicationStatus.Active)) {
          _leader = push;
        } else {
          _leader = null;
        }
      } 
      if (active == pull) {
        lastTotal = _lastPullCompleted;
      } else {
        lastTotal = _lastPushCompleted;
      }

      Debug.WriteLine (String.Format ("Sync: {2} Progress: {0}/{1};", active.CompletedChangesCount - lastTotal, active.ChangesCount - lastTotal, active == push ? "Push" : "Pull"));

      var progress = (float)(active.CompletedChangesCount - lastTotal) / (float)(Math.Max (active.ChangesCount - lastTotal, 1));

      if (AppDelegate.CurrentSystemVersion < AppDelegate.iOS7) {
        ShowSyncStatusLegacy ();
      } else {
        ShowSyncStatus ();
      }

            Debug.WriteLine (String.Format ("({0:F})", progress));

      if (active == pull) {
        if (AppDelegate.CurrentSystemVersion >= AppDelegate.iOS7) Progress.TintColor = UIColor.White;
      } else {
        if (AppDelegate.CurrentSystemVersion >= AppDelegate.iOS7) Progress.TintColor = UIColor.LightGray;
      }

      Progress.Hidden = false;
      
      if (progress < Progress.Progress)
        Progress.SetProgress (progress, false);
      else
        Progress.SetProgress (progress, false);
       
       if (!(pull.Status != ReplicationStatus.Active && push.Status != ReplicationStatus.Active))
            if (progress < 1f)
                return;
      if (active == null)
        return;
     var initiatorName = active.IsPull ? "Pull" : "Push";

      _lastPushCompleted = push.ChangesCount;
      _lastPullCompleted = pull.ChangesCount;

      if (Progress == null)
        return;
      Progress.Hidden = false;
      Progress.SetProgress (1f, false);

      var t = new System.Timers.Timer (300);
      t.Elapsed += (sender, e) => { 
        InvokeOnMainThread (() => {
          t.Dispose ();
          Progress.Hidden = true;
          Progress.SetProgress (0f, false);
          Debug.WriteLine (String.Format ("{0} Sync Session Finished.", initiatorName));
          ShowSyncButton ();
        });
      };
      t.Start ();

    }
コード例 #25
0
        internal Replication ReplicationWithProperties(IDictionary <string, object> properties)
        {
            // Extract the parameters from the JSON request body:
            // http://wiki.apache.org/couchdb/Replication

            bool push, createTarget;
            var  results = new Dictionary <string, object>()
            {
                { "database", null },
                { "remote", null },
                { "headers", null },
                { "authorizer", null }
            };

            Status result = ParseReplicationProperties(properties, out push, out createTarget, results);

            if (result.IsError)
            {
                throw new CouchbaseLiteException(result.Code);
            }

            object continuousObj = properties.Get("continuous");
            bool   continuous    = false;

            if (continuousObj is bool)
            {
                continuous = (bool)continuousObj;
            }

            var         scheduler = new SingleTaskThreadpoolScheduler();
            Replication rep       = null;

            if (push)
            {
                rep = new Pusher((Database)results["database"], (Uri)results["remote"], continuous, new TaskFactory(scheduler));
            }
            else
            {
                rep = new Puller((Database)results["database"], (Uri)results["remote"], continuous, new TaskFactory(scheduler));
            }

            rep.Filter         = properties.Get("filter") as string;
            rep.FilterParams   = properties.Get("query_params") as IDictionary <string, object>;
            rep.DocIds         = properties.Get("doc_ids") as IEnumerable <string>;
            rep.RequestHeaders = results.Get("headers") as IDictionary <string, object>;
            rep.Authenticator  = results.Get("authorizer") as IAuthenticator;
            if (push)
            {
                ((Pusher)rep).CreateTarget = createTarget;
            }

            var db = (Database)results["database"];

            // If this is a duplicate, reuse an existing replicator:
            var existing = db.ActiveReplicators.FirstOrDefault(x => x.LocalDatabase == rep.LocalDatabase &&
                                                               x.RemoteUrl == rep.RemoteUrl && x.IsPull == rep.IsPull &&
                                                               x.RemoteCheckpointDocID().Equals(rep.RemoteCheckpointDocID()));


            return(existing ?? rep);
        }
コード例 #26
0
        private static CountdownEvent ReplicationWatcherThread(Replication replication, ReplicationObserver observer)
        {
            var started = replication.IsRunning;
            var doneSignal = new CountdownEvent(1);

            Task.Factory.StartNew(()=>
            {
                var done = observer.IsReplicationFinished(); //Prevent race condition where the replicator stops before this portion is reached
                while (!done)
                {
                    if (replication.IsRunning)
                    {
                        started = true;
                    }

                    var statusIsDone = (
                        replication.Status == ReplicationStatus.Stopped 
                        || replication.Status == ReplicationStatus.Idle
                    );

                    if (started && statusIsDone)
                    {
                        break;
                    }

                    try
                    {
                        Thread.Sleep(1000);
                    }
                    catch (Exception e)
                    {
                        Runtime.PrintStackTrace(e);
                    }
                }
                doneSignal.Signal();
            });

            return doneSignal;
        }
コード例 #27
0
        public void TestGetReplicator()
        {
            if (!Boolean.Parse((string)Runtime.Properties["replicationTestsEnabled"]))
            {
                Assert.Inconclusive("Replication tests disabled.");
                return;
            }
            var replicationUrl = GetReplicationURL();
            var replicator = database.CreatePullReplication(replicationUrl);
            Assert.IsNotNull(replicator);
            Assert.IsTrue(replicator.IsPull);
            Assert.IsFalse(replicator.Continuous);
            Assert.IsFalse(replicator.IsRunning);

            replicator.Start();
            Assert.IsTrue(replicator.IsRunning);

            var activeReplicators = new Replication[database.ActiveReplicators.Count];
            database.ActiveReplicators.CopyTo(activeReplicators, 0);
            Assert.AreEqual(1, activeReplicators.Length);
            Assert.AreEqual(replicator, activeReplicators [0]);

            replicator.Stop();

            // Wait for a second to ensure that the replicator finishes
            // updating all status (esp Database.ActiveReplicator that will
            // be updated when receiving a Replication.Changed event which
            // is distached asynchronously when running tests.
            System.Threading.Thread.Sleep(1000);

            Assert.IsFalse(replicator.IsRunning);
            activeReplicators = new Replication[database.ActiveReplicators.Count];
            database.ActiveReplicators.CopyTo(activeReplicators, 0);
            Assert.AreEqual(0, activeReplicators.Length);
        }
コード例 #28
0
        private void PutReplicationOffline(Replication replication)
        {
            var doneEvent = new ManualResetEvent(false);
            replication.Changed += (object sender, ReplicationChangeEventArgs e) => 
            {
                if (e.Source.Status == ReplicationStatus.Offline) {
                    doneEvent.Set();
                }
            };

            replication.GoOffline();

            var success = doneEvent.WaitOne(TimeSpan.FromSeconds(30));
            Assert.IsTrue(success);
        }
コード例 #29
0
 internal Boolean Close()
 {
     if (!_isOpen)
     {
         return false;
     }
     if (_views != null)
     {
         foreach (View view in _views.Values)
         {
             view.DatabaseClosing();
         }
     }
     _views = null;
     if (ActiveReplicators != null)
     {
         // 
         var activeReplicators = new Replication[ActiveReplicators.Count];
         ActiveReplicators.CopyTo(activeReplicators, 0);
         foreach (Replication replicator in activeReplicators)
         {
             replicator.DatabaseClosing();
         }
         ActiveReplicators = null;
     }
     if (StorageEngine != null && StorageEngine.IsOpen)
     {
         StorageEngine.Close();
     }
     _isOpen = false;
     _transactionLevel = 0;
     return true;
 }
コード例 #30
0
 internal void AddReplication(Replication replication)
 {
     lock (_allReplicatorsLocker) { AllReplicators.Add(replication); }
 }
    void ForgetSync ()
    {
      var nctr = NSNotificationCenter.DefaultCenter;

      if (pull != null) {
        pull.Changed -= ReplicationProgress;
        pull.Stop();
        pull = null;
      }

      if (push != null) {
        push.Changed -= ReplicationProgress;
        push.Stop();
        push = null;
      }
    }
コード例 #32
0
        public void TestFacebookAuth()
        {
            var sg = new SyncGateway("http", GetReplicationServer());

            using (var remoteDb = sg.CreateDatabase("facebook")) {
                remoteDb.DisableGuestAccess();
                var doneEvent = new ManualResetEvent(false);

                var accountStore = new ACAccountStore();
                var accountType  = accountStore.FindAccountType(ACAccountType.Facebook);

                var options = new AccountStoreOptions();
                options.FacebookAppId = FacebookAppId;
                options.SetPermissions(ACFacebookAudience.Friends, new [] { "email" });

                var       success = true;
                ACAccount account = null;
                accountStore.RequestAccess(accountType, options, (result, error) =>
                {
                    success = result;
                    if (success)
                    {
                        var accounts = accountStore.FindAccounts(accountType);
                        account      = accounts != null && accounts.Length > 0 ? accounts[0] : null;
                    }
                    else
                    {
                        Log.W(Tag, "Facebook Login needed. Go to Settings > Facebook and login.");
                        Log.E(Tag, "Facebook Request Access Error : " + error);
                    }
                    doneEvent.Set();
                });

                doneEvent.WaitOne(TimeSpan.FromSeconds(30));

                Assert.IsTrue(success);
                Assert.IsNotNull(account);

                var token = account.Credential.OAuthToken;
                Assert.IsNotNull(token);
                Assert.IsTrue(token.Length > 0);

                var url = remoteDb.RemoteUri;

                var cookieStore       = new CookieStore(manager.Directory);
                var httpClientFactory = new CouchbaseLiteHttpClientFactory(cookieStore);
                manager.DefaultHttpClientFactory = httpClientFactory;
                Replication replicator = database.CreatePushReplication(url);
                replicator.Authenticator = AuthenticatorFactory.CreateFacebookAuthenticator(token);

                Assert.IsNotNull(replicator);
                Assert.IsNotNull(replicator.Authenticator);
                Assert.IsTrue(replicator.Authenticator is TokenAuthenticator);

                CreateDocuments(database, 20);

                RunReplication(replicator);

                var urlStr = url.ToString();
                urlStr = urlStr.EndsWith("/") ? urlStr : urlStr + "/";
                //var cookies = httpClientFactory.GetCookieContainer().GetCookies(new Uri(urlStr));
                //Assert.IsTrue(cookies.Count == 1);
                //Assert.AreEqual("SyncGatewaySession", cookies[0].Name);
            }
        }
コード例 #33
0
        private void RunReplication(Replication replication)
        {
            var replicationDoneSignal = new CountdownEvent(1);
            var observer = new ReplicationObserver(replicationDoneSignal);
            replication.Changed += observer.Changed;
            replication.Start();

            var replicationDoneSignalPolling = ReplicationWatcherThread(replication, observer);

            Log.D(Tag, "Waiting for replicator to finish.");

            var success = WaitHandle.WaitAll(new[] { replicationDoneSignal.WaitHandle, replicationDoneSignalPolling.WaitHandle }, 60*1000);
            Assert.IsTrue(success);

            Log.D(Tag, "replicator finished");

            replication.Changed -= observer.Changed;
        }
コード例 #34
0
    IEnumerator DoReplication(Replication replication)
    {
        replication.Start ();

        while (replication != null && replication.Status == ReplicationStatus.Active) {
            yield return new WaitForSeconds(0.5f);
        }
    }
コード例 #35
0
        public void TestGetReplicator()
        {
            if (!Boolean.Parse((string)Runtime.Properties["replicationTestsEnabled"]))
            {
                Assert.Inconclusive("Replication tests disabled.");
                return;
            }

            using (var remoteDb = _sg.CreateDatabase(TempDbName())) {
                var replicationUrl = remoteDb.RemoteUri;
                var replicator = database.CreatePullReplication(replicationUrl);
                Assert.IsNotNull(replicator);
                Assert.IsTrue(replicator.IsPull);
                Assert.IsFalse(replicator.Continuous);
                Assert.IsFalse(replicator.IsRunning);

                ReplicationStatus lastStatus = replicator.Status;
                var mre = new ManualResetEventSlim();
                replicator.Changed += (sender, e) =>
                {
                    if (lastStatus != e.Source.Status) {
                        lastStatus = e.Source.Status;
                        mre.Set();
                    }
                };
                replicator.Start();
                Assert.IsTrue(mre.Wait(TimeSpan.FromSeconds(10)), "Timed out waiting for replicator to start");
                Assert.IsTrue(replicator.IsRunning);

                var activeReplicators = new Replication[database.ActiveReplicators.Count];
                database.ActiveReplicators.CopyTo(activeReplicators, 0);
                Assert.AreEqual(1, activeReplicators.Length);
                Assert.AreEqual(replicator, activeReplicators[0]);

                replicator.Stop();

                mre.Reset();
                Assert.IsTrue(mre.Wait(TimeSpan.FromSeconds(10)), "Timed out waiting for replicator to stop");
                Assert.IsFalse(replicator.IsRunning);
                Sleep(500);
                activeReplicators = new Replication[database.ActiveReplicators.Count];
                database.ActiveReplicators.CopyTo(activeReplicators, 0);
                Assert.AreEqual(0, activeReplicators.Length);
            }
        }
コード例 #36
0
 void SetupReplication()
 {
     syncGateWayURI = "http://" + hostName + ":" + portNumber.ToString() + "/" + databaseName;
     pullReplication = database.CreatePullReplication (new Uri (syncGateWayURI));
     pushReplication = database.CreatePushReplication (new Uri (syncGateWayURI));
 }
コード例 #37
0
        internal bool Close()
        {
            var success = true;
            if (_isOpen) {
                Log.D("Closing database at {0}", Path);
                if (_views != null) {
                    foreach (var view in _views) {
                        view.Value.Close();
                    }
                }

                if (ActiveReplicators != null) {
                    var activeReplicatorCopy = new Replication[ActiveReplicators.Count];
                    ActiveReplicators.CopyTo(activeReplicatorCopy, 0);
                    foreach (var repl in activeReplicatorCopy) {
                        repl.DatabaseClosing();
                    }

                    ActiveReplicators = null;
                }

                try {
                    Storage.Close();
                } catch(Exception) {
                    success = false;
                }

                Storage = null;

                _isOpen = false;
                UnsavedRevisionDocumentCache.Clear();
                DocumentCache = new LruCache<string, Document>(DocumentCache.MaxSize);
            }

            Manager.ForgetDatabase(this);
            return success;
        }
コード例 #38
0
        public void StopReplication(Replication replication)
        {
            var replicationDoneSignal = new CountdownEvent(1);
            var replicationStoppedObserver = new ReplicationObserver(replicationDoneSignal);
            replication.Changed += replicationStoppedObserver.Changed;
            replication.Stop();

            var success = replicationDoneSignal.Wait(TimeSpan.FromSeconds(30));
            Assert.IsTrue(success);

            // give a little padding to give it a chance to save a checkpoint
            System.Threading.Thread.Sleep(2 * 1000);
        }
コード例 #39
0
 internal void ForgetReplication(Replication replication)
 {
     lock (_allReplicatorsLocker) { AllReplicators.Remove(replication); }
 }
コード例 #40
0
        internal bool AddReplication(Replication replication)
        {
            lock (_allReplicatorsLocker) {
                if (AllReplications.All(x => x.RemoteCheckpointDocID() != replication.RemoteCheckpointDocID())) {
                    AllReplicators.Add(replication);
                    return true;
                }

                return false;

            }
        }
コード例 #41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Couchbase.Lite.ReplicationChangeEventArgs"/> class.
 /// </summary>
 /// <param name="sender">The <see cref="Couchbase.Lite.Replication"/> that raised the event.</param>
 /// <param name="transition">The transition that caused the state in the replication, if applicable</param>
 public ReplicationChangeEventArgs (Replication sender, ReplicationStateTransition transition)
 {
     _source = sender;
     _transition = transition;
 }
コード例 #42
0
        internal bool AddActiveReplication(Replication replication)
        {
            if (ActiveReplicators == null) {
                Log.W(TAG, "ActiveReplicators is null, so replication will not be added");
                return false;
            }

            if (ActiveReplicators.All(x => x.RemoteCheckpointDocID() != replication.RemoteCheckpointDocID())) {
                ActiveReplicators.Add(replication);
            } else {
                return false;
            }

            replication.Changed += (sender, e) => {
                if (e.Source != null && !e.Source.IsRunning && ActiveReplicators != null)
                {
                    ActiveReplicators.Remove(e.Source);
                }
            };

            return true;
        }