本文整理汇总了C#中HashSet.AddItem方法的典型用法代码示例。如果您正苦于以下问题:C# HashSet.AddItem方法的具体用法?C# HashSet.AddItem怎么用?C# HashSet.AddItem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HashSet
的用法示例。
在下文中一共展示了HashSet.AddItem方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetResourceListing
/// <summary>List directory contents for a resource folder.</summary>
/// <remarks>List directory contents for a resource folder. Not recursive.</remarks>
/// <author>Andrew Reslan</author>
/// <param name="clazz">Any java class that lives in the same place as the resources folder
/// </param>
/// <param name="path">Should end with "/", but not start with one.</param>
/// <returns>An array of the name of each member item, or null if path does not denote a directory
/// </returns>
/// <exception cref="Sharpen.URISyntaxException">Sharpen.URISyntaxException</exception>
/// <exception cref="System.IO.IOException">System.IO.IOException</exception>
public static string[] GetResourceListing(Type clazz, string path)
{
Uri dirURL = clazz.GetClassLoader().GetResource(path);
if (dirURL != null && dirURL.Scheme.Equals("file"))
{
return new FilePath(dirURL.ToURI()).List();
}
if (dirURL != null && dirURL.Scheme.Equals("jar"))
{
string jarPath = Sharpen.Runtime.Substring(dirURL.AbsolutePath, 5, dirURL.AbsolutePath
.IndexOf("!"));
JarFile jar = new JarFile(URLDecoder.Decode(jarPath, "UTF-8"));
Enumeration<JarEntry> entries = ((Enumeration<JarEntry>)jar.Entries());
ICollection<string> result = new HashSet<string>();
while (entries.MoveNext())
{
string name = entries.Current.GetName();
if (name.StartsWith(path))
{
string entry = Sharpen.Runtime.Substring(name, path.Length);
int checkSubdir = entry.IndexOf("/");
if (checkSubdir >= 0)
{
// if it is a subdirectory, we just return the directory name
entry = Sharpen.Runtime.Substring(entry, 0, checkSubdir);
}
result.AddItem(entry);
}
}
return Sharpen.Collections.ToArray(result, new string[result.Count]);
}
throw new NotSupportedException("Cannot list files for URL " + dirURL);
}
示例2: AllKeys
public ICollection<BlobKey> AllKeys()
{
ICollection<BlobKey> result = new HashSet<BlobKey>();
FilePath file = new FilePath(path);
FilePath[] contents = file.ListFiles();
foreach (FilePath attachment in contents)
{
if (attachment.IsDirectory())
{
continue;
}
BlobKey attachmentKey = new BlobKey();
GetKeyForFilename(attachmentKey, attachment.GetPath());
result.AddItem(attachmentKey);
}
return result;
}
示例3: QueueWants
/// <exception cref="NGit.Errors.TransportException"></exception>
private void QueueWants(ICollection<Ref> want)
{
HashSet<ObjectId> inWorkQueue = new HashSet<ObjectId>();
foreach (Ref r in want)
{
ObjectId id = r.GetObjectId();
try
{
RevObject obj = revWalk.ParseAny(id);
if (obj.Has(COMPLETE))
{
continue;
}
if (inWorkQueue.AddItem(id))
{
obj.Add(IN_WORK_QUEUE);
workQueue.AddItem(obj);
}
}
catch (MissingObjectException)
{
if (inWorkQueue.AddItem(id))
{
workQueue.AddItem(id);
}
}
catch (IOException e)
{
throw new TransportException(MessageFormat.Format(JGitText.Get().cannotRead, id.Name
), e);
}
}
}
示例4: ListPackDirectory
private ICollection<string> ListPackDirectory()
{
string[] nameList = packDirectory.List();
if (nameList == null)
{
return Sharpen.Collections.EmptySet<string>();
}
ICollection<string> nameSet = new HashSet<string>();
foreach (string name in nameList)
{
if (name.StartsWith("pack-"))
{
nameSet.AddItem(name);
}
}
return nameSet;
}
示例5: SendPack
/// <exception cref="System.IO.IOException"></exception>
private void SendPack()
{
bool sideband = options.Contains(OPTION_SIDE_BAND) || options.Contains(OPTION_SIDE_BAND_64K
);
if (!biDirectionalPipe)
{
// Ensure the request was fully consumed. Any remaining input must
// be a protocol error. If we aren't at EOF the implementation is broken.
int eof = rawIn.Read();
if (0 <= eof)
{
throw new CorruptObjectException(MessageFormat.Format(JGitText.Get().expectedEOFReceived
, "\\x" + Sharpen.Extensions.ToHexString(eof)));
}
}
ProgressMonitor pm = NullProgressMonitor.INSTANCE;
OutputStream packOut = rawOut;
SideBandOutputStream msgOut = null;
if (sideband)
{
int bufsz = SideBandOutputStream.SMALL_BUF;
if (options.Contains(OPTION_SIDE_BAND_64K))
{
bufsz = SideBandOutputStream.MAX_BUF;
}
packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA, bufsz, rawOut);
if (!options.Contains(OPTION_NO_PROGRESS))
{
msgOut = new SideBandOutputStream(SideBandOutputStream.CH_PROGRESS, bufsz, rawOut
);
pm = new SideBandProgressMonitor(msgOut);
}
}
try
{
if (wantAll.IsEmpty())
{
preUploadHook.OnSendPack(this, wantIds, commonBase);
}
else
{
preUploadHook.OnSendPack(this, wantAll, commonBase);
}
}
catch (UploadPackMayNotContinueException noPack)
{
if (sideband && noPack.Message != null)
{
noPack.SetOutput();
SideBandOutputStream err = new SideBandOutputStream(SideBandOutputStream.CH_ERROR
, SideBandOutputStream.SMALL_BUF, rawOut);
err.Write(Constants.Encode(noPack.Message));
err.Flush();
}
throw;
}
PackConfig cfg = packConfig;
if (cfg == null)
{
cfg = new PackConfig(db);
}
PackWriter pw = new PackWriter(cfg, walk.GetObjectReader());
try
{
pw.SetUseCachedPacks(true);
pw.SetReuseDeltaCommits(true);
pw.SetDeltaBaseAsOffset(options.Contains(OPTION_OFS_DELTA));
pw.SetThin(options.Contains(OPTION_THIN_PACK));
pw.SetReuseValidatingObjects(false);
if (commonBase.IsEmpty())
{
ICollection<ObjectId> tagTargets = new HashSet<ObjectId>();
foreach (Ref @ref in refs.Values)
{
if (@ref.GetPeeledObjectId() != null)
{
tagTargets.AddItem(@ref.GetPeeledObjectId());
}
else
{
if (@ref.GetObjectId() == null)
{
continue;
}
else
{
if (@ref.GetName().StartsWith(Constants.R_HEADS))
{
tagTargets.AddItem(@ref.GetObjectId());
}
}
}
}
pw.SetTagTargets(tagTargets);
}
RevWalk rw = walk;
if (wantAll.IsEmpty())
{
pw.PreparePack(pm, wantIds, commonBase);
//.........这里部分代码省略.........
示例6: GetAdditionalHaves
/// <summary>
/// Objects known to exist but not expressed by
/// <see cref="NGit.Repository.GetAllRefs()">NGit.Repository.GetAllRefs()</see>
/// .
/// <p>
/// When a repository borrows objects from another repository, it can
/// advertise that it safely has that other repository's references, without
/// exposing any other details about the other repository. This may help
/// a client trying to push changes avoid pushing more than it needs to.
/// </summary>
/// <returns>unmodifiable collection of other known objects.</returns>
public override ICollection<ObjectId> GetAdditionalHaves()
{
HashSet<ObjectId> r = new HashSet<ObjectId>();
foreach (FileObjectDatabase.AlternateHandle d in objectDatabase.MyAlternates())
{
if (d is FileObjectDatabase.AlternateRepository)
{
Repository repo;
repo = ((FileObjectDatabase.AlternateRepository)d).repository;
foreach (Ref @ref in repo.GetAllRefs().Values)
{
r.AddItem(@ref.GetObjectId());
}
Sharpen.Collections.AddAll(r, repo.GetAdditionalHaves());
}
}
return r;
}
示例7: SendPack
/// <exception cref="System.IO.IOException"></exception>
private void SendPack(bool sideband)
{
ProgressMonitor pm = NullProgressMonitor.INSTANCE;
OutputStream packOut = rawOut;
SideBandOutputStream msgOut = null;
if (sideband)
{
int bufsz = SideBandOutputStream.SMALL_BUF;
if (options.Contains(OPTION_SIDE_BAND_64K))
{
bufsz = SideBandOutputStream.MAX_BUF;
}
packOut = new SideBandOutputStream(SideBandOutputStream.CH_DATA, bufsz, rawOut);
if (!options.Contains(OPTION_NO_PROGRESS))
{
msgOut = new SideBandOutputStream(SideBandOutputStream.CH_PROGRESS, bufsz, rawOut
);
pm = new SideBandProgressMonitor(msgOut);
}
}
try
{
if (wantAll.IsEmpty())
{
preUploadHook.OnSendPack(this, wantIds, commonBase);
}
else
{
preUploadHook.OnSendPack(this, wantAll, commonBase);
}
}
catch (ServiceMayNotContinueException noPack)
{
if (sideband && noPack.Message != null)
{
noPack.SetOutput();
SideBandOutputStream err = new SideBandOutputStream(SideBandOutputStream.CH_ERROR
, SideBandOutputStream.SMALL_BUF, rawOut);
err.Write(Constants.Encode(noPack.Message));
err.Flush();
}
throw;
}
PackConfig cfg = packConfig;
if (cfg == null)
{
cfg = new PackConfig(db);
}
PackWriter pw = new PackWriter(cfg, walk.GetObjectReader());
try
{
pw.SetUseCachedPacks(true);
pw.SetReuseDeltaCommits(true);
pw.SetDeltaBaseAsOffset(options.Contains(OPTION_OFS_DELTA));
pw.SetThin(options.Contains(OPTION_THIN_PACK));
pw.SetReuseValidatingObjects(false);
if (commonBase.IsEmpty() && refs != null)
{
ICollection<ObjectId> tagTargets = new HashSet<ObjectId>();
foreach (Ref @ref in refs.Values)
{
if (@ref.GetPeeledObjectId() != null)
{
tagTargets.AddItem(@ref.GetPeeledObjectId());
}
else
{
if (@ref.GetObjectId() == null)
{
continue;
}
else
{
if (@ref.GetName().StartsWith(Constants.R_HEADS))
{
tagTargets.AddItem(@ref.GetObjectId());
}
}
}
}
pw.SetTagTargets(tagTargets);
}
if (depth > 0)
{
pw.SetShallowPack(depth, unshallowCommits);
}
RevWalk rw = walk;
if (wantAll.IsEmpty())
{
pw.PreparePack(pm, wantIds, commonBase);
}
else
{
walk.Reset();
ObjectWalk ow = walk.ToObjectWalkWithSameObjects();
pw.PreparePack(pm, ow, wantAll, commonBase);
rw = ow;
}
if (options.Contains(OPTION_INCLUDE_TAG) && refs != null)
//.........这里部分代码省略.........
示例8: ExpandPushWildcardsFor
private static ICollection<RefSpec> ExpandPushWildcardsFor(Repository db, ICollection
<RefSpec> specs)
{
IDictionary<string, Ref> localRefs = db.GetAllRefs();
ICollection<RefSpec> procRefs = new HashSet<RefSpec>();
foreach (RefSpec spec in specs)
{
if (spec.IsWildcard())
{
foreach (Ref localRef in localRefs.Values)
{
if (spec.MatchSource(localRef))
{
procRefs.AddItem(spec.ExpandFromSource(localRef));
}
}
}
else
{
procRefs.AddItem(spec);
}
}
return procRefs;
}
示例9: NativeJavaClass
/// <exception cref="Kirikiri.Tjs2.VariantException"></exception>
/// <exception cref="Kirikiri.Tjs2.TJSException"></exception>
public NativeJavaClass(string name, Type c)
: base(name)
{
mJavaClass = c;
string classname = name;
mClassID = TJS.RegisterNativeClass(classname);
try
{
HashSet<string> registProp = new HashSet<string>();
// set/getで重复しないようにチェック
MethodInfo[] methods = c.GetMethods();
foreach (MethodInfo m in methods)
{
string methodName = m.Name;
int flag = 0;
if (m.IsStatic)
{
flag |= Interface.STATICMEMBER;
}
if ("constructor".Equals(methodName))
{
// コンストラクタ
RegisterNCM(classname, new NativeJavaClassConstructor(m, mClassID), classname, Interface
.nitMethod, flag);
}
else
{
if (methodName.StartsWith("prop_"))
{
// プロパティ prop_ で始まるものはプロパティとみなす
Type[] @params = Sharpen.Runtime.GetParameterTypes(m);
MethodInfo setMethod = null;
MethodInfo getMethod = null;
string propName = null;
if (methodName.StartsWith("prop_set_"))
{
if (@params.Length == 1)
{
setMethod = m;
propName = Sharpen.Runtime.Substring(methodName, "prop_set_".Length);
if (registProp.Contains(propName) == false)
{
string getMethodName = "prop_get_" + propName;
foreach (MethodInfo getm in methods)
{
if (getm.Name.Equals(getMethodName))
{
Type[] p = Sharpen.Runtime.GetParameterTypes(getm);
if (p.Length == 0 && getm.ReturnType.Equals(typeof(void)) != true)
{
getMethod = getm;
break;
}
}
}
}
}
}
else
{
if (methodName.StartsWith("prop_get_"))
{
if (@params.Length == 0 && m.ReturnType.Equals(typeof(void)) != true)
{
getMethod = m;
propName = Sharpen.Runtime.Substring(methodName, "prop_get_".Length);
if (registProp.Contains(propName) == false)
{
string setMethodName = "prop_set_" + propName;
foreach (MethodInfo setm in methods)
{
if (setm.Name.Equals(setMethodName))
{
Type[] p = Sharpen.Runtime.GetParameterTypes(setm);
if (p.Length == 1)
{
setMethod = setm;
break;
}
}
}
}
}
}
}
if (propName != null && registProp.Contains(propName) == false)
{
if (setMethod != null || getMethod != null)
{
RegisterNCM(propName, new NativeJavaClassProperty(getMethod, setMethod, mClassID)
, classname, Interface.nitProperty, flag);
registProp.AddItem(propName);
}
}
}
else
{
// 通常メソッド
//.........这里部分代码省略.........
示例10: WritePack
/// <exception cref="System.IO.IOException"></exception>
private void WritePack(IDictionary<string, RemoteRefUpdate> refUpdates, ProgressMonitor
monitor)
{
ICollection<ObjectId> remoteObjects = new HashSet<ObjectId>();
ICollection<ObjectId> newObjects = new HashSet<ObjectId>();
PackWriter writer = new PackWriter(transport.GetPackConfig(), local.NewObjectReader
());
try
{
foreach (Ref r in GetRefs())
{
remoteObjects.AddItem(r.GetObjectId());
}
Sharpen.Collections.AddAll(remoteObjects, additionalHaves);
foreach (RemoteRefUpdate r_1 in refUpdates.Values)
{
if (!ObjectId.ZeroId.Equals(r_1.GetNewObjectId()))
{
newObjects.AddItem(r_1.GetNewObjectId());
}
}
writer.SetUseCachedPacks(true);
writer.SetThin(thinPack);
writer.SetReuseValidatingObjects(false);
writer.SetDeltaBaseAsOffset(capableOfsDelta);
writer.PreparePack(monitor, newObjects, remoteObjects);
writer.WritePack(monitor, monitor, @out);
}
finally
{
writer.Release();
}
packTransferTime = writer.GetStatistics().GetTimeWriting();
}
示例11: TestAttachments
//.........这里部分代码省略.........
gotRev1 = database.GetDocumentWithIDAndRev(
rev1.GetDocId(), rev1.GetRevId(), DocumentContentOptions.IncludeAttachments);
gotAttachmentDict = gotRev1.GetProperties()
.Get("_attachments")
.AsDictionary<string, object>()
.Get(testAttachmentName)
.AsDictionary<string,object>();
Assert.AreEqual(innerDict.Select(kvp => kvp.Key).OrderBy(k => k), gotAttachmentDict.Select(kvp => kvp.Key).OrderBy(k => k));
// Add a second revision that doesn't update the attachment:
var rev2Properties = new Dictionary<string, object>();
rev2Properties.Put("_id", rev1.GetDocId());
rev2Properties["foo"] = 2;
rev2Properties["bazz"] = false;
var rev2 = database.PutRevision(new RevisionInternal(rev2Properties,
database), rev1.GetRevId(), false, status);
Assert.AreEqual(StatusCode.Created, status.GetCode());
database.CopyAttachmentNamedFromSequenceToSequence(
testAttachmentName, rev1.GetSequence(), rev2.GetSequence());
// Add a third revision of the same document:
var rev3Properties = new Dictionary<string, object>();
rev3Properties.Put("_id", rev2.GetDocId());
rev3Properties["foo"] = 2;
rev3Properties["bazz"] = false;
var rev3 = database.PutRevision(new RevisionInternal(
rev3Properties, database), rev2.GetRevId(), false, status);
Assert.AreEqual(StatusCode.Created, status.GetCode());
var attach2 = Runtime.GetBytesForString("<html>And this is attach2</html>").ToArray();
database.InsertAttachmentForSequenceWithNameAndType(
new ByteArrayInputStream(attach2), rev3.GetSequence(),
testAttachmentName, "text/html", rev2.GetGeneration());
// Check the 2nd revision's attachment:
var attachment2 = database.GetAttachmentForSequence(rev2.GetSequence(), testAttachmentName);
Assert.AreEqual("text/plain", attachment2.ContentType);
data = attachment2.Content.ToArray();
Assert.IsTrue(Arrays.Equals(attach1, data));
// Workaround :
// Not closing the content stream will cause Sharing Violation
// Exception when trying to get the same attachment going forward.
attachment2.ContentStream.Close();
// Check the 3rd revision's attachment:
var attachment3 = database.GetAttachmentForSequence(rev3.GetSequence(), testAttachmentName);
Assert.AreEqual("text/html", attachment3.ContentType);
data = attachment3.Content.ToArray();
Assert.IsTrue(Arrays.Equals(attach2, data));
var attachmentDictForRev3 = database.GetAttachmentsDictForSequenceWithContent(rev3.GetSequence(), DocumentContentOptions.None)
.Get(testAttachmentName)
.AsDictionary<string,object>();
if (attachmentDictForRev3.ContainsKey("follows"))
{
if (((bool)attachmentDictForRev3.Get("follows")) == true)
{
throw new RuntimeException("Did not expected attachment dict 'follows' key to be true"
);
}
else
{
throw new RuntimeException("Did not expected attachment dict to have 'follows' key"
);
}
}
// Workaround :
// Not closing the content stream will cause Sharing Violation
// Exception when trying to get the same attachment going forward.
attachment3.ContentStream.Close();
// Examine the attachment store:
Assert.AreEqual(2, attachments.Count());
var expected = new HashSet<BlobKey>();
expected.AddItem(BlobStore.KeyForBlob(attach1));
expected.AddItem(BlobStore.KeyForBlob(attach2));
Assert.AreEqual(expected.Count, attachments.AllKeys().Count());
foreach(var key in attachments.AllKeys()) {
Assert.IsTrue(expected.Contains(key));
}
database.Compact();
// This clears the body of the first revision
Assert.AreEqual(1, attachments.Count());
var expected2 = new HashSet<BlobKey>();
expected2.AddItem(BlobStore.KeyForBlob(attach2));
Assert.AreEqual(expected2.Count, attachments.AllKeys().Count());
foreach(var key in attachments.AllKeys()) {
Assert.IsTrue(expected2.Contains(key));
}
}
示例12: TestAttachments
/// <exception cref="System.Exception"></exception>
public virtual void TestAttachments()
{
string testAttachmentName = "test_attachment";
BlobStore attachments = database.GetAttachments();
NUnit.Framework.Assert.AreEqual(0, attachments.Count());
NUnit.Framework.Assert.AreEqual(new HashSet<object>(), attachments.AllKeys());
Status status = new Status();
IDictionary<string, object> rev1Properties = new Dictionary<string, object>();
rev1Properties.Put("foo", 1);
rev1Properties.Put("bar", false);
RevisionInternal rev1 = database.PutRevision(new RevisionInternal(rev1Properties,
database), null, false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
byte[] attach1 = Sharpen.Runtime.GetBytesForString("This is the body of attach1");
database.InsertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach1
), rev1.GetSequence(), testAttachmentName, "text/plain", rev1.GetGeneration());
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
Attachment attachment = database.GetAttachmentForSequence(rev1.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/plain", attachment.GetContentType());
byte[] data = IOUtils.ToByteArray(attachment.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach1, data));
IDictionary<string, object> innerDict = new Dictionary<string, object>();
innerDict.Put("content_type", "text/plain");
innerDict.Put("digest", "sha1-gOHUOBmIMoDCrMuGyaLWzf1hQTE=");
innerDict.Put("length", 27);
innerDict.Put("stub", true);
innerDict.Put("revpos", 1);
IDictionary<string, object> attachmentDict = new Dictionary<string, object>();
attachmentDict.Put(testAttachmentName, innerDict);
IDictionary<string, object> attachmentDictForSequence = database.GetAttachmentsDictForSequenceWithContent
(rev1.GetSequence(), EnumSet.NoneOf<Database.TDContentOptions>());
NUnit.Framework.Assert.AreEqual(attachmentDict, attachmentDictForSequence);
RevisionInternal gotRev1 = database.GetDocumentWithIDAndRev(rev1.GetDocId(), rev1
.GetRevId(), EnumSet.NoneOf<Database.TDContentOptions>());
IDictionary<string, object> gotAttachmentDict = (IDictionary<string, object>)gotRev1
.GetProperties().Get("_attachments");
NUnit.Framework.Assert.AreEqual(attachmentDict, gotAttachmentDict);
// Check the attachment dict, with attachments included:
Sharpen.Collections.Remove(innerDict, "stub");
innerDict.Put("data", Base64.EncodeBytes(attach1));
attachmentDictForSequence = database.GetAttachmentsDictForSequenceWithContent(rev1
.GetSequence(), EnumSet.Of(Database.TDContentOptions.TDIncludeAttachments));
NUnit.Framework.Assert.AreEqual(attachmentDict, attachmentDictForSequence);
gotRev1 = database.GetDocumentWithIDAndRev(rev1.GetDocId(), rev1.GetRevId(), EnumSet
.Of(Database.TDContentOptions.TDIncludeAttachments));
gotAttachmentDict = (IDictionary<string, object>)gotRev1.GetProperties().Get("_attachments"
);
NUnit.Framework.Assert.AreEqual(attachmentDict, gotAttachmentDict);
// Add a second revision that doesn't update the attachment:
IDictionary<string, object> rev2Properties = new Dictionary<string, object>();
rev2Properties.Put("_id", rev1.GetDocId());
rev2Properties.Put("foo", 2);
rev2Properties.Put("bazz", false);
RevisionInternal rev2 = database.PutRevision(new RevisionInternal(rev2Properties,
database), rev1.GetRevId(), false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
database.CopyAttachmentNamedFromSequenceToSequence(testAttachmentName, rev1.GetSequence
(), rev2.GetSequence());
// Add a third revision of the same document:
IDictionary<string, object> rev3Properties = new Dictionary<string, object>();
rev3Properties.Put("_id", rev2.GetDocId());
rev3Properties.Put("foo", 2);
rev3Properties.Put("bazz", false);
RevisionInternal rev3 = database.PutRevision(new RevisionInternal(rev3Properties,
database), rev2.GetRevId(), false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
byte[] attach2 = Sharpen.Runtime.GetBytesForString("<html>And this is attach2</html>"
);
database.InsertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach2
), rev3.GetSequence(), testAttachmentName, "text/html", rev2.GetGeneration());
// Check the 2nd revision's attachment:
Attachment attachment2 = database.GetAttachmentForSequence(rev2.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/plain", attachment2.GetContentType());
data = IOUtils.ToByteArray(attachment2.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach1, data));
// Check the 3rd revision's attachment:
Attachment attachment3 = database.GetAttachmentForSequence(rev3.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/html", attachment3.GetContentType());
data = IOUtils.ToByteArray(attachment3.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach2, data));
// Examine the attachment store:
NUnit.Framework.Assert.AreEqual(2, attachments.Count());
ICollection<BlobKey> expected = new HashSet<BlobKey>();
expected.AddItem(BlobStore.KeyForBlob(attach1));
expected.AddItem(BlobStore.KeyForBlob(attach2));
NUnit.Framework.Assert.AreEqual(expected, attachments.AllKeys());
database.Compact();
// This clears the body of the first revision
NUnit.Framework.Assert.AreEqual(1, attachments.Count());
ICollection<BlobKey> expected2 = new HashSet<BlobKey>();
expected2.AddItem(BlobStore.KeyForBlob(attach2));
NUnit.Framework.Assert.AreEqual(expected2, attachments.AllKeys());
}
示例13: RunLiveQuery
// kick something off that will s
/// <exception cref="System.Exception"></exception>
public virtual void RunLiveQuery(string methodNameToCall)
{
Database db = StartDatabase();
CountDownLatch doneSignal = new CountDownLatch(11);
// 11 corresponds to startKey=23; endKey=33
// run a live query
View view = db.GetView("vu");
view.SetMap(new _Mapper_817(), "1");
LiveQuery query = view.CreateQuery().ToLiveQuery();
query.SetStartKey(23);
query.SetEndKey(33);
Log.I(Tag, "Created " + query);
// these are the keys that we expect to see in the livequery change listener callback
ICollection<int> expectedKeys = new HashSet<int>();
for (int i = 23; i < 34; i++)
{
expectedKeys.AddItem(i);
}
// install a change listener which decrements countdown latch when it sees a new
// key from the list of expected keys
LiveQuery.ChangeListener changeListener = new _ChangeListener_836(expectedKeys, doneSignal
);
query.AddChangeListener(changeListener);
// create the docs that will cause the above change listener to decrement countdown latch
int kNDocs = 50;
CreateDocumentsAsync(db, kNDocs);
if (methodNameToCall.Equals("start"))
{
// start the livequery running asynchronously
query.Start();
}
else
{
if (methodNameToCall.Equals("startWaitForRows"))
{
query.Start();
query.WaitForRows();
}
else
{
NUnit.Framework.Assert.IsNull(query.GetRows());
query.Run();
// this will block until the query completes
NUnit.Framework.Assert.IsNotNull(query.GetRows());
}
}
// wait for the doneSignal to be finished
bool success = doneSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue("Done signal timed out, live query never ran", success
);
// stop the livequery since we are done with it
query.RemoveChangeListener(changeListener);
query.Stop();
}
示例14: TestAttachments
//.........这里部分代码省略.........
catch (SQLException e)
{
Log.E(Database.Tag, "Error setting rev1 no_attachments to false", e);
throw new CouchbaseLiteException(Status.InternalServerError);
}
Attachment attachment = database.GetAttachmentForSequence(rev1.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/plain", attachment.GetContentType());
byte[] data = IOUtils.ToByteArray(attachment.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach1, data));
IDictionary<string, object> innerDict = new Dictionary<string, object>();
innerDict.Put("content_type", "text/plain");
innerDict.Put("digest", "sha1-gOHUOBmIMoDCrMuGyaLWzf1hQTE=");
innerDict.Put("length", 27);
innerDict.Put("stub", true);
innerDict.Put("revpos", 1);
IDictionary<string, object> attachmentDict = new Dictionary<string, object>();
attachmentDict.Put(testAttachmentName, innerDict);
IDictionary<string, object> attachmentDictForSequence = database.GetAttachmentsDictForSequenceWithContent
(rev1.GetSequence(), EnumSet.NoneOf<Database.TDContentOptions>());
NUnit.Framework.Assert.AreEqual(attachmentDict, attachmentDictForSequence);
RevisionInternal gotRev1 = database.GetDocumentWithIDAndRev(rev1.GetDocId(), rev1
.GetRevId(), EnumSet.NoneOf<Database.TDContentOptions>());
IDictionary<string, object> gotAttachmentDict = (IDictionary<string, object>)gotRev1
.GetProperties().Get("_attachments");
NUnit.Framework.Assert.AreEqual(attachmentDict, gotAttachmentDict);
// Check the attachment dict, with attachments included:
Sharpen.Collections.Remove(innerDict, "stub");
innerDict.Put("data", Base64.EncodeBytes(attach1));
attachmentDictForSequence = database.GetAttachmentsDictForSequenceWithContent(rev1
.GetSequence(), EnumSet.Of(Database.TDContentOptions.TDIncludeAttachments));
NUnit.Framework.Assert.AreEqual(attachmentDict, attachmentDictForSequence);
gotRev1 = database.GetDocumentWithIDAndRev(rev1.GetDocId(), rev1.GetRevId(), EnumSet
.Of(Database.TDContentOptions.TDIncludeAttachments));
gotAttachmentDict = (IDictionary<string, object>)gotRev1.GetProperties().Get("_attachments"
);
NUnit.Framework.Assert.AreEqual(attachmentDict, gotAttachmentDict);
// Add a second revision that doesn't update the attachment:
IDictionary<string, object> rev2Properties = new Dictionary<string, object>();
rev2Properties.Put("_id", rev1.GetDocId());
rev2Properties.Put("foo", 2);
rev2Properties.Put("bazz", false);
RevisionInternal rev2 = database.PutRevision(new RevisionInternal(rev2Properties,
database), rev1.GetRevId(), false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
database.CopyAttachmentNamedFromSequenceToSequence(testAttachmentName, rev1.GetSequence
(), rev2.GetSequence());
// Add a third revision of the same document:
IDictionary<string, object> rev3Properties = new Dictionary<string, object>();
rev3Properties.Put("_id", rev2.GetDocId());
rev3Properties.Put("foo", 2);
rev3Properties.Put("bazz", false);
RevisionInternal rev3 = database.PutRevision(new RevisionInternal(rev3Properties,
database), rev2.GetRevId(), false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
byte[] attach2 = Sharpen.Runtime.GetBytesForString("<html>And this is attach2</html>"
);
database.InsertAttachmentForSequenceWithNameAndType(new ByteArrayInputStream(attach2
), rev3.GetSequence(), testAttachmentName, "text/html", rev2.GetGeneration());
// Check the 2nd revision's attachment:
Attachment attachment2 = database.GetAttachmentForSequence(rev2.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/plain", attachment2.GetContentType());
data = IOUtils.ToByteArray(attachment2.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach1, data));
// Check the 3rd revision's attachment:
Attachment attachment3 = database.GetAttachmentForSequence(rev3.GetSequence(), testAttachmentName
);
NUnit.Framework.Assert.AreEqual("text/html", attachment3.GetContentType());
data = IOUtils.ToByteArray(attachment3.GetContent());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(attach2, data));
IDictionary<string, object> attachmentDictForRev3 = (IDictionary<string, object>)
database.GetAttachmentsDictForSequenceWithContent(rev3.GetSequence(), EnumSet.NoneOf
<Database.TDContentOptions>()).Get(testAttachmentName);
if (attachmentDictForRev3.ContainsKey("follows"))
{
if (((bool)attachmentDictForRev3.Get("follows")) == true)
{
throw new RuntimeException("Did not expected attachment dict 'follows' key to be true"
);
}
else
{
throw new RuntimeException("Did not expected attachment dict to have 'follows' key"
);
}
}
// Examine the attachment store:
NUnit.Framework.Assert.AreEqual(2, attachments.Count());
ICollection<BlobKey> expected = new HashSet<BlobKey>();
expected.AddItem(BlobStore.KeyForBlob(attach1));
expected.AddItem(BlobStore.KeyForBlob(attach2));
NUnit.Framework.Assert.AreEqual(expected, attachments.AllKeys());
database.Compact();
// This clears the body of the first revision
NUnit.Framework.Assert.AreEqual(1, attachments.Count());
ICollection<BlobKey> expected2 = new HashSet<BlobKey>();
expected2.AddItem(BlobStore.KeyForBlob(attach2));
NUnit.Framework.Assert.AreEqual(expected2, attachments.AllKeys());
}
示例15: OnCompletion
public void OnCompletion(object result, Exception e)
{
try
{
if (e == null)
{
ICollection<string> failedIDs = new HashSet<string>();
// _bulk_docs response is really an array, not a dictionary!
IList<IDictionary<string, object>> items = (IList)result;
foreach (IDictionary<string, object> item in items)
{
Status status = this._enclosing.StatusFromBulkDocsResponseItem(item);
if (status.IsError())
{
// One of the docs failed to save.
Log.W(Log.TagSync, "%s: _bulk_docs got an error: %s", item, this);
// 403/Forbidden means validation failed; don't treat it as an error
// because I did my job in sending the revision. Other statuses are
// actual replication errors.
if (status.GetCode() != Status.Forbidden)
{
string docID = (string)item.Get("id");
failedIDs.AddItem(docID);
}
}
}
// TODO - port from iOS
// NSURL* url = docID ? [_remote URLByAppendingPathComponent: docID] : nil;
// error = CBLStatusToNSError(status, url);
// Remove from the pending list all the revs that didn't fail:
foreach (RevisionInternal revisionInternal in changes)
{
if (!failedIDs.Contains(revisionInternal.GetDocId()))
{
this._enclosing.RemovePending(revisionInternal);
}
}
}
if (e != null)
{
this._enclosing.SetError(e);
this._enclosing.RevisionFailed();
}
else
{
Log.V(Log.TagSync, "%s: POSTed to _bulk_docs", this._enclosing);
}
this._enclosing.AddToCompletedChangesCount(numDocsToSend);
}
finally
{
Log.V(Log.TagSync, "%s | %s: uploadBulkDocs.sendAsyncRequest() calling asyncTaskFinished()"
, this, Sharpen.Thread.CurrentThread());
this._enclosing.AsyncTaskFinished(1);
}
}