예제 #1
0
        public void TestReadOnlyDb()
        {
            CreateDocuments(database, 10);
            database.Close();

            var options = new ManagerOptions();

            options.ReadOnly = true;
            var readOnlyManager = new Manager(new DirectoryInfo(manager.Directory), options);

            database = readOnlyManager.GetExistingDatabase(database.Name);
            Assert.IsNotNull(database);
            var e = Assert.Throws <CouchbaseLiteException>(() => CreateDocuments(database, 1));

            Assert.AreEqual(StatusCode.Forbidden, e.Code);
            database.Close();

            var dbOptions = new DatabaseOptions();

            dbOptions.ReadOnly = true;
            database           = manager.OpenDatabase(database.Name, dbOptions);
            Assert.IsNotNull(database);
            e = Assert.Throws <CouchbaseLiteException>(() => CreateDocuments(database, 1));
            Assert.AreEqual(StatusCode.Forbidden, e.Code);
            database.Close();

            dbOptions.ReadOnly = false;
            database           = manager.OpenDatabase(database.Name, dbOptions);
            Assert.DoesNotThrow(() => CreateDocuments(database, 1));
        }
예제 #2
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        protected internal virtual Database EnsureEmptyDatabase(string dbName)
        {
            Database db = manager.GetExistingDatabase(dbName);

            if (db != null)
            {
                db.Delete();
            }
            db = manager.GetDatabase(dbName);
            return(db);
        }
예제 #3
0
        protected internal virtual Database EnsureEmptyDatabase(string dbName)
        {
            Database db = manager.GetExistingDatabase(dbName);

            if (db != null)
            {
                bool status = db.Delete();
                NUnit.Framework.Assert.IsTrue(status);
            }
            db = manager.GetDatabase(dbName);
            return(db);
        }
예제 #4
0
        /// <summary>
        /// Opens the named <see cref="EntityDatabase"/> if it exists.
        /// </summary>
        /// <param name="manager">The database manager.</param>
        /// <param name="name">The database name.</param>
        /// <returns>The <see cref="EntityDatabase"/> or <c>null</c> if the database doesn't exist.</returns>
        public static EntityDatabase GetExistingEntityDatabase(this Manager manager, string name)
        {
            Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(name));

            var database = manager.GetExistingDatabase(name);

            if (database == null)
            {
                return(null);
            }

            return(EntityDatabase.From(database));
        }
 /// <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());
 }
예제 #6
0
        protected internal virtual Database EnsureEmptyDatabase(string dbName)
        {
            Database db = manager.GetExistingDatabase(dbName);

            if (db != null)
            {
                var status = false;;

                try {
                    db.Delete();
                    status = true;
                } catch (Exception e) {
                    Log.E(Tag, "Cannot delete database " + e.Message);
                }

                NUnit.Framework.Assert.IsTrue(status);
            }
            db = manager.GetDatabase(dbName);
            return(db);
        }
        protected Database EnsureEmptyDatabase(string dbName)
        {
            var db = manager.GetExistingDatabase(dbName);

            if (db != null)
            {
                var status = false;;

                try {
                    db.Delete();
                    db.Close();
                    status = true;
                } catch (Exception e) {
                    Log.E(TAG, "Cannot delete database " + e.Message);
                }

                Assert.IsTrue(status);
            }
            db = manager.GetDatabase(dbName);
            return(db);
        }
예제 #8
0
        private static Replication SetupReplication(Manager manager, bool continuous, bool createTarget,
            Uri remoteUri, bool isPull, string user, string password)
        {
            if (remoteUri == null) {
                return null;
            }

            var databaseName = remoteUri.Segments.Last();
            var authenticator = default(IAuthenticator);
            if (user != null && password != null) {
                Logger.I("Listener", "Setting session credentials for user '{0}'", user);
                authenticator = AuthenticatorFactory.CreateBasicAuthenticator(user, password);
            }

            if (isPull) {
                Logger.I("Listener", "Pulling from <{0}> --> {1}", remoteUri, databaseName);
            } else {
                Logger.I("Listener", "Pushing {0} --> <{1}>", databaseName, remoteUri);
            }

            var db = manager.GetExistingDatabase(databaseName);
            if (isPull && db == null) {
                db = manager.GetDatabase(databaseName);
            }

            if (db == null) {
                Logger.E("Listener", "Couldn't open database {0}", databaseName);
                return null;
            }

            var repl = isPull ? db.CreatePullReplication(remoteUri) : db.CreatePushReplication(remoteUri);
            repl.Continuous = continuous;
            repl.CreateTarget = createTarget;
            repl.Authenticator = authenticator;
            repl.Changed += (sender, e) => 
            {
                Logger.I("Listener", "*** Replicator status changed ({0} {1}/{2}) ***", e.Status, e.CompletedChangesCount,
                    e.ChangesCount);
                if(e.LastError != null) {
                    Logger.W("Listener", "*** Replicator reported error ***", e);
                } else if(e.Status == ReplicationStatus.Stopped) {
                    Logger.I("Listener", "*** Replicator finished ***");
                }
            };

            repl.Start();
            return repl;
        }
        public void TestReadOnlyDb()
        {
            CreateDocuments(database, 10);
            database.Close();

            var options = new ManagerOptions();
            options.ReadOnly = true;
            var readOnlyManager = new Manager(new DirectoryInfo(manager.Directory), options);
            database = readOnlyManager.GetExistingDatabase(database.Name);
            Assert.IsNotNull(database);
            var e = Assert.Throws<CouchbaseLiteException>(() => CreateDocuments(database, 1));
            Assert.AreEqual(StatusCode.Forbidden, e.Code);
            database.Close();

            var dbOptions = new DatabaseOptions();
            dbOptions.ReadOnly = true;
            database = manager.OpenDatabase(database.Name, dbOptions);
            Assert.IsNotNull(database);
            e = Assert.Throws<CouchbaseLiteException>(() => CreateDocuments(database, 1));
            Assert.AreEqual(StatusCode.Forbidden, e.Code);
            database.Close();

            dbOptions.ReadOnly = false;
            database = manager.OpenDatabase(database.Name, dbOptions);
            Assert.DoesNotThrow(() => CreateDocuments(database, 1));
        }
예제 #10
0
        public static void Main(string[] args)
        {
            var timeoutStr = "90000";
            var options = new OptionSet() {
                { "push", "push replication", v => _isPush = v == "push" },
                { "pull", "pull replication", v => _isPull = v == "pull" },
                { "f|file=",  "CBLite file path", v =>
                    _path = v },
                { "u|url=",  "URL to replicate with", v => _url = v },
                { "t|timeout=", "Set the timeout for HTTP requests in milliseconds (default is 90000)", v => timeoutStr = v },
                { "h|help",  "show this message and exit", v => _showHelp = v != null },

            };

            List<string> extra;
            try {
                extra = options.Parse(args);
                if (extra.Count == 1)
                {
                    // Should be just a file path. Will validate below.
                    _path = extra[0];
                }
            } catch (OptionException e) {
                Console.Write("cbreplicate: ");
                OutputUsingColor(
                    color: ConsoleColor.Red,
                    format: e.Message
                );
                Console.WriteLine();
                Console.WriteLine("Try `cbreplicate --help' for more information.");
                Environment.ExitCode = (int)Exit.InvalidOptions;
                return;
            }

            if (_showHelp || args.Length == 0) {
                var writer = new StringWriter(new StringBuilder("usage: cb-replicate [options] [file path]" + Environment.NewLine + Environment.NewLine));
                options.WriteOptionDescriptions(writer);

                _helpText = writer.ToString();

                writer.Close();

                ShowHelp();
                return;
            }

            int timeout;
            if(Int32.TryParse(timeoutStr, out timeout)) {
                Manager.DefaultOptions.RequestTimeout = TimeSpan.FromMilliseconds(timeout);
            }

            if (String.IsNullOrWhiteSpace(_path)) {
                OutputUsingColor(
                    color: ConsoleColor.Red,
                    format: "The path to the database was empty text or all whitespace.{0}",
                    args: Environment.NewLine
                );
                ShowHelp();
                Environment.ExitCode = (int)Exit.PathIsNullOrEmpty;
                return;
            }

            FileInfo file;
            if (!File.Exists(_path)) {
                // See if they gave us a relative path.
                _path = Path.Combine(Environment.CurrentDirectory, _path);
                if (!File.Exists(_path) && _isPush) {
                    OutputUsingColor(
                        color: ConsoleColor.Red,
                        format: "The path {0} is not valid. A valid CBLite database is required for push replication",
                        args: _path
                    );
                    Environment.ExitCode = (int)Exit.PathDoesNotExist;
                    return;
                }
            }

            file = new FileInfo(_path);

            var man = new Manager(file.Directory, Manager.DefaultOptions);

            try
            {
                _db = _isPull ? man.GetDatabase(file.Name.Split('.')[0]) : man.GetExistingDatabase(file.Name.Split('.')[0]);
            }
            catch (Exception ex)
            {
                OutputUsingColor(
                    color: ConsoleColor.Red,
                    format: "Error opening the database: {0}{1}",
                    args: new[] { ex.Message, Environment.NewLine }
                );
                Environment.ExitCode = (int)Exit.CannotOpenDatabase;
                return;
            }

            if (_db == null)
            {
                OutputUsingColor(
                    color: ConsoleColor.Red,
                    format: "No CBLite db found at '{0}'. Push replication requires and existing CBLite database.",
                    args: _path
                );
                Environment.ExitCode = (int)Exit.PathDoesNotExist;
                return;
            }

            if (_isPush)
            {
                try
                {
                    Push();
                }
                catch (Exception ex)
                {
                    OutputUsingColor(
                        color: ConsoleColor.Red,
                        format: "Unhandled exception during push replication: {0}",
                        args: ex.Message
                    );
                    Environment.ExitCode = (int)Exit.UnhandledException;
                    return;
                }
            }
            else if (_isPull)
            {
                try
                {
                    Pull();
                }
                catch (Exception ex)
                {
                    OutputUsingColor(
                        color: ConsoleColor.Red,
                        format: "Unhandled exception during pull replication: {0}",
                        args: ex.Message
                    );
                    Environment.ExitCode = (int)Exit.UnhandledException;
                    return;
                }
            }

            bool doneWaiting;

            Console.CancelKeyPress += (sender, e) => {
                if (e.Cancel) {
                    _done = _mre.Set();
                }
            };

            do {
                doneWaiting = _mre.WaitOne(100);
            } while(!_done || !doneWaiting);
        }