public bool Run() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < this._enclosing.GetSizeOfAttachment(); i++) { sb.Append('1'); } byte[] attach1 = Sharpen.Runtime.GetBytesForString(sb.ToString()); try { Status status = new Status(); for (int i_1 = 0; i_1 < this._enclosing.GetNumberOfDocuments(); i_1++) { IDictionary<string, object> rev1Properties = new Dictionary<string, object>(); rev1Properties.Put("foo", 1); rev1Properties.Put("bar", false); RevisionInternal rev1 = this._enclosing.database.PutRevision(new RevisionInternal (rev1Properties, this._enclosing.database), null, false, status); NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode()); this._enclosing.database.InsertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream (attach1), rev1.GetSequence(), Test3_CreateDocsWithAttachments._testAttachmentName , "text/plain", rev1.GetGeneration()); NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode()); } } catch (Exception t) { Log.E(Test3_CreateDocsWithAttachments.Tag, "Document create with attachment failed" , t); return false; } return true; }
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public static Couchbase.Lite.Document CreateTask(Database database, string title, Bitmap image, string listId) { SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" ); Calendar calendar = GregorianCalendar.GetInstance(); string currentTimeString = dateFormatter.Format(calendar.GetTime()); IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("type", DocType); properties.Put("title", title); properties.Put("checked", false); properties.Put("created_at", currentTimeString); properties.Put("list_id", listId); Couchbase.Lite.Document document = database.CreateDocument(); UnsavedRevision revision = document.CreateRevision(); revision.SetUserProperties(properties); if (image != null) { ByteArrayOutputStream @out = new ByteArrayOutputStream(); image.Compress(Bitmap.CompressFormat.Jpeg, 50, @out); ByteArrayInputStream @in = new ByteArrayInputStream(@out.ToByteArray()); revision.SetAttachment("image", "image/jpg", @in); } revision.Save(); return document; }
// Reproduces issue #167 // https://github.com/couchbase/couchbase-lite-android/issues/167 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestLoadRevisionBody() { Document document = database.CreateDocument(); IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("foo", "foo"); properties.Put("bar", false); document.PutProperties(properties); NUnit.Framework.Assert.IsNotNull(document.GetCurrentRevision()); bool deleted = false; RevisionInternal revisionInternal = new RevisionInternal(document.GetId(), document .GetCurrentRevisionId(), deleted, database); EnumSet<Database.TDContentOptions> contentOptions = EnumSet.Of(Database.TDContentOptions .TDIncludeAttachments, Database.TDContentOptions.TDBigAttachmentsFollow); database.LoadRevisionBody(revisionInternal, contentOptions); // now lets purge the document, and then try to load the revision body again NUnit.Framework.Assert.IsTrue(document.Purge()); bool gotExpectedException = false; try { database.LoadRevisionBody(revisionInternal, contentOptions); } catch (CouchbaseLiteException e) { if (e.GetCBLStatus().GetCode() == Status.NotFound) { gotExpectedException = true; } } NUnit.Framework.Assert.IsTrue(gotExpectedException); }
public void TestMultiValPath() { IndexReader reader = IndexReader.Open(directory, true); BoboIndexReader boboReader = BoboIndexReader.GetInstance(reader, facetHandlers); BoboBrowser browser = new BoboBrowser(boboReader); BrowseRequest req = new BrowseRequest(); BrowseSelection sel = new BrowseSelection(PathHandlerName); sel.AddValue("/a"); var propMap = new Dictionary<String, String>(); propMap.Put(PathFacetHandler.SEL_PROP_NAME_DEPTH, "0"); propMap.Put(PathFacetHandler.SEL_PROP_NAME_STRICT, "false"); sel.SetSelectionProperties(propMap); req.AddSelection(sel); FacetSpec fs = new FacetSpec(); fs.MinHitCount = (1); req.SetFacetSpec(PathHandlerName, fs); BrowseResult res = browser.Browse(req); Assert.AreEqual(res.NumHits, 1); IFacetAccessible fa = res.GetFacetAccessor(PathHandlerName); IEnumerable<BrowseFacet> facets = fa.GetFacets(); Console.WriteLine(facets); Assert.AreEqual(1, facets.Count()); BrowseFacet facet = facets.Get(0); Assert.AreEqual(2, facet.FacetValueHitCount); }
public virtual void TestDatabase() { Send("PUT", "/database", Status.Created, null); IDictionary entries = new Dictionary<string, IDictionary<string, object>>(); entries.Put("results", new AList<object>()); entries.Put("last_seq", 0); Send("GET", "/database/_changes?feed=normal&heartbeat=300000&style=all_docs", Status .Ok, entries); IDictionary<string, object> dbInfo = (IDictionary<string, object>)Send("GET", "/database" , Status.Ok, null); NUnit.Framework.Assert.AreEqual(6, dbInfo.Count); NUnit.Framework.Assert.AreEqual(0, dbInfo.Get("doc_count")); NUnit.Framework.Assert.AreEqual(0, dbInfo.Get("update_seq")); NUnit.Framework.Assert.IsTrue((int)dbInfo.Get("disk_size") > 8000); NUnit.Framework.Assert.AreEqual("database", dbInfo.Get("db_name")); NUnit.Framework.Assert.IsTrue(Runtime.CurrentTimeMillis() * 1000 > (long)dbInfo.Get ("instance_start_time")); NUnit.Framework.Assert.IsTrue(dbInfo.ContainsKey("db_uuid")); Send("PUT", "/database", Status.PreconditionFailed, null); Send("PUT", "/database2", Status.Created, null); IList<string> allDbs = new AList<string>(); allDbs.AddItem("cblite-test"); allDbs.AddItem("database"); allDbs.AddItem("database2"); Send("GET", "/_all_dbs", Status.Ok, allDbs); dbInfo = (IDictionary<string, object>)Send("GET", "/database2", Status.Ok, null); NUnit.Framework.Assert.AreEqual("database2", dbInfo.Get("db_name")); Send("DELETE", "/database2", Status.Ok, null); allDbs.Remove("database2"); Send("GET", "/_all_dbs", Status.Ok, allDbs); Send("PUT", "/database%2Fwith%2Fslashes", Status.Created, null); dbInfo = (IDictionary<string, object>)Send("GET", "/database%2Fwith%2Fslashes", Status .Ok, null); NUnit.Framework.Assert.AreEqual("database/with/slashes", dbInfo.Get("db_name")); }
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestNewDocumentHasCurrentRevision() { Document document = database.CreateDocument(); IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("foo", "foo"); properties.Put("bar", false); document.PutProperties(properties); NUnit.Framework.Assert.IsNotNull(document.GetCurrentRevisionId()); NUnit.Framework.Assert.IsNotNull(document.GetCurrentRevision()); }
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestForceInsertEmptyHistory() { IList<string> revHistory = null; RevisionInternal rev = new RevisionInternal("FakeDocId", "1-tango", false, database ); IDictionary<string, object> revProperties = new Dictionary<string, object>(); revProperties.Put("_id", rev.GetDocId()); revProperties.Put("_rev", rev.GetRevId()); revProperties.Put("message", "hi"); rev.SetProperties(revProperties); database.ForceInsert(rev, revHistory, null); }
public void TestForceInsertEmptyHistory() { var rev = new RevisionInternal("FakeDocId", "1-abcd", false); var revProperties = new Dictionary<string, object>(); revProperties.Put("_id", rev.GetDocId()); revProperties.Put("_rev", rev.GetRevId()); revProperties["message"] = "hi"; rev.SetProperties(revProperties); IList<string> revHistory = null; database.ForceInsert(rev, revHistory, null); }
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public static Couchbase.Lite.Document CreateNewList(Database database, string title, string userId) { var dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); var calendar = Calendar.CurrentEra; string currentTimeString = dateFormatter.Format(calendar.GetTime()); IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("type", "list"); properties.Put("title", title); properties.Put("created_at", currentTimeString); properties.Put("owner", "profile:" + userId); properties.Put("members", new AList<string>()); Couchbase.Lite.Document document = database.CreateDocument(); document.PutProperties(properties); return document; }
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 bool Run() { string[] bigObj = new string[this._enclosing.GetSizeOfDocument()]; for (int i = 0; i < this._enclosing.GetSizeOfDocument(); i++) { bigObj[i] = Test11_DeleteDocs._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); Document doc = this._enclosing.database.CreateDocument(); this._enclosing.docs[i_1] = doc; try { doc.PutProperties(props); } catch (CouchbaseLiteException cblex) { Log.E(Test11_DeleteDocs.Tag, "Document creation failed", cblex); return false; } } return true; }
/// <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); }
public virtual void TestParseContentType() { Encoding utf8 = Sharpen.Extensions.GetEncoding("UTF-8"); Dictionary<string, byte[]> contentTypes = new Dictionary<string, byte[]>(); contentTypes.Put("multipart/related; boundary=\"BOUNDARY\"", Sharpen.Runtime.GetBytesForString (new string("\r\n--BOUNDARY"), utf8)); contentTypes.Put("multipart/related; boundary=BOUNDARY", Sharpen.Runtime.GetBytesForString (new string("\r\n--BOUNDARY"), utf8)); contentTypes.Put("multipart/related;boundary=X", Sharpen.Runtime.GetBytesForString (new string("\r\n--X"), utf8)); foreach (string contentType in contentTypes.Keys) { MultipartReaderDelegate delegate_ = null; MultipartReader reader = new MultipartReader(contentType, delegate_); byte[] expectedBoundary = (byte[])contentTypes.Get(contentType); byte[] boundary = reader.GetBoundary(); NUnit.Framework.Assert.IsTrue(Arrays.Equals(boundary, expectedBoundary)); } try { MultipartReaderDelegate delegate_ = null; MultipartReader reader = new MultipartReader("multipart/related; boundary=\"BOUNDARY" , delegate_); NUnit.Framework.Assert.IsTrue("Should not have gotten here, above lines should have thrown exception" , false); } catch (Exception) { } }
public static Authenticator CreatePersonaAuthenticator(string assertion, string email ) { // TODO: REVIEW : Do we need email? IDictionary<string, string> @params = new Dictionary<string, string>(); @params.Put("access_token", assertion); return new TokenAuthenticator("_persona", @params); }
/// <summary>ScriptableOutputStream constructor.</summary> /// <remarks> /// ScriptableOutputStream constructor. /// Creates a ScriptableOutputStream for use in serializing /// JavaScript objects. Calls excludeStandardObjectNames. /// </remarks> /// <param name="out">the OutputStream to write to.</param> /// <param name="scope">the scope containing the object.</param> /// <exception cref="System.IO.IOException"></exception> public ScriptableOutputStream(Stream @out, Scriptable scope) : base(@out) { // API class this.scope = scope; table = new Dictionary<object, string>(); table.Put(scope, string.Empty); EnableReplaceObject(true); ExcludeStandardObjectNames(); }
/// <exception cref="System.Exception"></exception> public virtual void TestPruneRevsToMaxDepthViaCompact() { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("testName", "testDatabaseCompaction"); properties.Put("tag", 1337); Document doc = CreateDocumentWithProperties(database, properties); SavedRevision rev = doc.GetCurrentRevision(); database.SetMaxRevTreeDepth(1); for (int i = 0; i < 10; i++) { IDictionary<string, object> properties2 = new Dictionary<string, object>(properties ); properties2.Put("tag", i); rev = rev.CreateRevision(properties2); } database.Compact(); Document fetchedDoc = database.GetDocument(doc.GetId()); IList<SavedRevision> revisions = fetchedDoc.GetRevisionHistory(); NUnit.Framework.Assert.AreEqual(1, revisions.Count); }
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestCreateDocument() { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("testName", "testCreateDocument"); properties.Put("tag", 1337); Database db = StartDatabase(); Document doc = CreateDocumentWithProperties(db, properties); string docID = doc.GetId(); NUnit.Framework.Assert.IsTrue("Invalid doc ID: " + docID, docID.Length > 10); string currentRevisionID = doc.GetCurrentRevisionId(); NUnit.Framework.Assert.IsTrue("Invalid doc revision: " + docID, currentRevisionID .Length > 10); NUnit.Framework.Assert.AreEqual(doc.GetUserProperties(), properties); NUnit.Framework.Assert.AreEqual(db.GetDocument(docID), doc); db.ClearDocumentCache(); // so we can load fresh copies Document doc2 = db.GetExistingDocument(docID); NUnit.Framework.Assert.AreEqual(doc2.GetId(), docID); NUnit.Framework.Assert.AreEqual(doc2.GetCurrentRevisionId(), currentRevisionID); NUnit.Framework.Assert.IsNull(db.GetExistingDocument("b0gus")); }
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestDeleteDocument() { Document document = database.CreateDocument(); IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("foo", "foo"); properties.Put("bar", false); document.PutProperties(properties); NUnit.Framework.Assert.IsNotNull(document.GetCurrentRevision()); string docId = document.GetId(); document.Delete(); NUnit.Framework.Assert.IsTrue(document.IsDeleted()); Document fetchedDoc = database.GetExistingDocument(docId); NUnit.Framework.Assert.IsNull(fetchedDoc); // query all docs and make sure we don't see that document database.GetAllDocs(new QueryOptions()); Query queryAllDocs = database.CreateAllDocumentsQuery(); QueryEnumerator queryEnumerator = queryAllDocs.Run(); for (IEnumerator<QueryRow> it = queryEnumerator; it.HasNext(); ) { QueryRow row = it.Next(); NUnit.Framework.Assert.IsFalse(row.GetDocument().GetId().Equals(docId)); } }
public virtual void TestServer() { IDictionary<string, object> responseBody = new Dictionary<string, object>(); responseBody.Put("CBLite", "Welcome"); responseBody.Put("couchdb", "Welcome"); responseBody.Put("version", Couchbase.Lite.Router.Router.GetVersionString()); Send("GET", "/", Status.Ok, responseBody); IDictionary<string, object> session = new Dictionary<string, object>(); IDictionary<string, object> userCtx = new Dictionary<string, object>(); IList<string> roles = new AList<string>(); roles.AddItem("_admin"); session.Put("ok", true); userCtx.Put("name", null); userCtx.Put("roles", roles); session.Put("userCtx", userCtx); Send("GET", "/_session", Status.Ok, session); IList<string> allDbs = new AList<string>(); allDbs.AddItem("cblite-test"); Send("GET", "/_all_dbs", Status.Ok, allDbs); Send("GET", "/non-existant", Status.NotFound, null); Send("GET", "/BadName", Status.BadRequest, null); Send("PUT", "/", Status.BadRequest, null); Send("POST", "/", Status.BadRequest, null); }
/// <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()); }
private static readonly double LUCENE_4464_distErrPct = SpatialArgs.DEFAULT_DISTERRPCT;//DEFAULT 2.5% public NtsPolygonTest() { try { IDictionary<string, string> args = new Dictionary<string, string>(); args.Put("spatialContextFactory", typeof(NtsSpatialContextFactory).AssemblyQualifiedName); ctx = SpatialContextFactory.MakeSpatialContext(args /*, getClass().getClassLoader()*/); } catch (TypeLoadException e) //LUCENENET TODO: Does this match NoClassDefFoundError ?? { AssumeTrue("This test requires Spatial4n.Core.NTS: " + e, false); } GeohashPrefixTree grid = new GeohashPrefixTree(ctx, 11);//< 1 meter == 11 maxLevels this.strategy = new RecursivePrefixTreeStrategy(grid, GetType().Name); ((RecursivePrefixTreeStrategy)this.strategy).DistErrPct = (LUCENE_4464_distErrPct);//1% radius (small!) }
/// <exception cref="System.Exception"></exception> public virtual void TestCache() { int retainCount = 1; Cache cache = new Cache<string, Document>(retainCount); IDictionary<string, object> props = new Dictionary<string, object>(); props.Put("foo", "bar"); Document doc1 = CreateDocumentWithProperties(database, props); cache.Put(doc1.GetId(), doc1); IDictionary<string, object> props2 = new Dictionary<string, object>(); props2.Put("foo2", "bar2"); Document doc2 = CreateDocumentWithProperties(database, props2); cache.Put(doc2.GetId(), doc2); NUnit.Framework.Assert.IsNotNull(cache.Get(doc1.GetId())); NUnit.Framework.Assert.IsNotNull(cache.Get(doc2.GetId())); cache.Remove(doc1.GetId()); NUnit.Framework.Assert.IsNull(cache.Get(doc1.GetId())); cache.Clear(); NUnit.Framework.Assert.IsNull(cache.Get(doc2.GetId())); }
/// <exception cref="System.Exception"></exception> public virtual void TestJsonObject() { IDictionary<string, object> dict = new Dictionary<string, object>(); dict.Put("id", "01234567890"); dict.Put("foo", "bar"); dict.Put("int", 5); dict.Put("double", 3.5); dict.Put("bool", true); dict.Put("date", new DateTime().ToString()); ObjectWriter mapper = new ObjectWriter(); byte[] json = mapper.WriteValueAsBytes(dict); JsonDocument jsdoc = new JsonDocument(json); NUnit.Framework.Assert.AreEqual(dict, jsdoc.JsonObject()); }
public bool Run() { for (int i = 0; i < this._enclosing.GetNumberOfDocuments(); i++) { //create a document IDictionary<string, object> props = new Dictionary<string, object>(); props.Put("toogle", true); Document doc = this._enclosing.database.CreateDocument(); this._enclosing.docs[i] = doc; try { doc.PutProperties(props); } catch (CouchbaseLiteException cblex) { Log.E(Test8_DocRevisions.Tag, "Document creation failed", cblex); return false; } } return true; }
public override IDictionary<string, string> LoginParametersForSite(Uri site) { IDictionary<string, string> loginParameters = new Dictionary<string, string>(); try { string accessToken = AccessTokenForEmailAndSite(this.emailAddress, site); if (accessToken != null) { loginParameters.Put(LoginParameterAccessToken, accessToken); return loginParameters; } else { return null; } } catch (Exception e) { Log.E(Log.TagSync, "Error looking login parameters for site", e); } return null; }
/// <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 ()); }
private void SaveLastSequence(SaveLastSequenceCompletionBlock completionHandler) { if (!lastSequenceChanged) { if (completionHandler != null) { completionHandler(); } return; } if (_savingCheckpoint) { // If a save is already in progress, don't do anything. (The completion block will trigger // another save after the first one finishes.) _overdueForSave = true; return; } lastSequenceChanged = false; _overdueForSave = false; Log.D(TAG, "saveLastSequence() called. lastSequence: " + LastSequence); var body = new Dictionary<String, Object>(); if (_remoteCheckpoint != null) { body.PutAll(_remoteCheckpoint); } body["lastSequence"] = LastSequence; var remoteCheckpointDocID = RemoteCheckpointDocID(); if (String.IsNullOrEmpty(remoteCheckpointDocID)) { Log.W(TAG, "remoteCheckpointDocID is null, aborting saveLastSequence()"); return; } _savingCheckpoint = true; SendAsyncRequest(HttpMethod.Put, "/_local/" + remoteCheckpointDocID, body, (result, e) => { _savingCheckpoint = false; if (e != null) { Log.V (TAG, "Unable to save remote checkpoint", e); } if (LocalDatabase == null) { Log.W(TAG, "Database is null, ignoring remote checkpoint response"); if (completionHandler != null) { completionHandler (); } return; } if (!LocalDatabase.Open()) { Log.W(TAG, "Database is closed, ignoring remote checkpoint response"); if (completionHandler != null) { completionHandler (); } return; } if (e != null) { switch (GetStatusFromError(e)) { case StatusCode.NotFound: _remoteCheckpoint = null; _overdueForSave = true; break; case StatusCode.Conflict: RefreshRemoteCheckpointDoc(); break; default: // TODO: On 401 or 403, and this is a pull, remember that remote // TODO: is read-only & don't attempt to read its checkpoint next time. break; } } else { Log.D(TAG, "Save checkpoint response: " + result.ToString()); var response = result.AsDictionary<string, object>(); body.Put ("_rev", response.Get ("rev")); _remoteCheckpoint = body; LocalDatabase.SetLastSequence(LastSequence, RemoteCheckpointDocID(), !IsPull); } if (_overdueForSave) { SaveLastSequence (completionHandler); } else if (completionHandler != null) { completionHandler (); } }); }
private IEnumerable<BrowseFacet> FilterByKeys(IEnumerable<BrowseFacet> facets, char separator, int numFacetsPerKey, string[] values) { var keyOccurences = new Dictionary<string, AtomicInteger>(); var editable = facets.ToList(); string separatorString = Convert.ToString(separator); for (int i = 0; i < facets.Count(); i++) { BrowseFacet facet = facets.ElementAt(i); string value = facet.Value; if (!value.Contains(separatorString)) { editable.Remove(facet); continue; } if (values != null && values.Length > 0) { bool belongsToKeys = false; foreach (var val in values) { if (value.StartsWith(val)) { belongsToKeys = true; break; } } if (!belongsToKeys) { editable.Remove(facet); continue; } } string key = value.Substring(0, value.IndexOf(separatorString)); AtomicInteger numOfKeys = keyOccurences.Get(key); if (numOfKeys == null) { numOfKeys = new AtomicInteger(0); keyOccurences.Put(key, numOfKeys); } int count = numOfKeys.IncrementAndGet(); if (count > numFacetsPerKey) { editable.Remove(facet); } } return editable; }
public virtual void TestMakeRevisionHistoryDict() { IList<RevisionInternal> revs = new AList<RevisionInternal>(); revs.AddItem(Mkrev("4-jkl")); revs.AddItem(Mkrev("3-ghi")); revs.AddItem(Mkrev("2-def")); IList<string> expectedSuffixes = new AList<string>(); expectedSuffixes.AddItem("jkl"); expectedSuffixes.AddItem("ghi"); expectedSuffixes.AddItem("def"); IDictionary<string, object> expectedHistoryDict = new Dictionary<string, object>( ); expectedHistoryDict.Put("start", 4); expectedHistoryDict.Put("ids", expectedSuffixes); IDictionary<string, object> historyDict = Database.MakeRevisionHistoryDict(revs); NUnit.Framework.Assert.AreEqual(expectedHistoryDict, historyDict); revs = new AList<RevisionInternal>(); revs.AddItem(Mkrev("4-jkl")); revs.AddItem(Mkrev("2-def")); expectedSuffixes = new AList<string>(); expectedSuffixes.AddItem("4-jkl"); expectedSuffixes.AddItem("2-def"); expectedHistoryDict = new Dictionary<string, object>(); expectedHistoryDict.Put("ids", expectedSuffixes); historyDict = Database.MakeRevisionHistoryDict(revs); NUnit.Framework.Assert.AreEqual(expectedHistoryDict, historyDict); revs = new AList<RevisionInternal>(); revs.AddItem(Mkrev("12345")); revs.AddItem(Mkrev("6789")); expectedSuffixes = new AList<string>(); expectedSuffixes.AddItem("12345"); expectedSuffixes.AddItem("6789"); expectedHistoryDict = new Dictionary<string, object>(); expectedHistoryDict.Put("ids", expectedSuffixes); historyDict = Database.MakeRevisionHistoryDict(revs); NUnit.Framework.Assert.AreEqual(expectedHistoryDict, historyDict); }
// Replaces the "follows" key with the real attachment data in all attachments to 'doc'. internal bool InlineFollowingAttachmentsIn(RevisionInternal rev) { return rev.MutateAttachments((s, attachment)=> { if (!attachment.ContainsKey("follows")) { return attachment; } var fileURL = FileForAttachmentDict(attachment); byte[] fileData = null; try { var inputStream = fileURL.OpenConnection().GetInputStream(); var os = new ByteArrayOutputStream(); inputStream.CopyTo(os); fileData = os.ToByteArray(); } catch (IOException e) { Log.E(TAG, "could not retrieve attachment data: {0}".Fmt(fileURL.ToString()), e); return null; } var editedAttachment = new Dictionary<string, object>(attachment); editedAttachment.Remove("follows"); editedAttachment.Put("data", Convert.ToBase64String(fileData)); return editedAttachment; }); }