public static Query GetQuery(Database database, string listDocId)
 {
     View view = database.GetView(ViewName);
     if (view.Map == null)
     {
         view.Map += (IDictionary<string, object> document, EmitDelegate emitter)=> 
         {
             if (Task.DocType.Equals(document.Get("type")))
             {
                 var keys = new AList<object>();
                 keys.AddItem(document.Get("list_id"));
                 keys.AddItem(document.Get("created_at"));
                 emitter(keys, document);
             }
         };
     }
     Query query = view.CreateQuery();
     query.Descending = true;
     IList<object> startKeys = new AList<object>();
     startKeys.AddItem(listDocId);
     startKeys.AddItem(new Dictionary<string, object>());
     IList<object> endKeys = new AList<object>();
     endKeys.AddItem(listDocId);
     query.StartKey = startKeys;
     query.EndKey = endKeys;
     return query;
 }
示例#2
0
		public virtual void TestDatabase()
		{
			Send("PUT", "/database", Status.Created, null);
			IDictionary<string, object> dbInfo = (IDictionary<string, object>)Send("GET", "/database"
				, Status.Ok, null);
			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);
			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="NBoilerpipe.BoilerpipeProcessingException"></exception>
 public bool Process(TextDocument doc)
 {
     bool changes = false;
     IList<TextBlock> blocks = doc.GetTextBlocks();
     IList<TextBlock> blocksNew = new AList<TextBlock>();
     foreach (TextBlock tb in blocks)
     {
         string text = tb.GetText();
         string[] paragraphs = text.Split("[\n\r]+");
         if (paragraphs.Length < 2)
         {
             blocksNew.AddItem(tb);
             continue;
         }
         bool isContent = tb.IsContent();
         ICollection<string> labels = tb.GetLabels();
         foreach (string p in paragraphs)
         {
             TextBlock tbP = new TextBlock(p);
             tbP.SetIsContent(isContent);
             tbP.AddLabels(labels);
             blocksNew.AddItem(tbP);
             changes = true;
         }
     }
     if (changes)
     {
         blocks.Clear();
         Sharpen.Collections.AddAll(blocks, blocksNew);
     }
     return changes;
 }
示例#4
0
 public virtual void LogAllCommits()
 {
     IList<RevCommit> commits = new AList<RevCommit>();
     Git git = Git.Wrap(db);
     WriteTrashFile("Test.txt", "Hello world");
     git.Add().AddFilepattern("Test.txt").Call();
     commits.AddItem(git.Commit().SetMessage("initial commit").Call());
     git.BranchCreate().SetName("branch1").Call();
     Ref checkedOut = git.Checkout().SetName("branch1").Call();
     NUnit.Framework.Assert.AreEqual("refs/heads/branch1", checkedOut.GetName());
     WriteTrashFile("Test1.txt", "Hello world!");
     git.Add().AddFilepattern("Test1.txt").Call();
     commits.AddItem(git.Commit().SetMessage("branch1 commit").Call());
     checkedOut = git.Checkout().SetName("master").Call();
     NUnit.Framework.Assert.AreEqual("refs/heads/master", checkedOut.GetName());
     WriteTrashFile("Test2.txt", "Hello world!!");
     git.Add().AddFilepattern("Test2.txt").Call();
     commits.AddItem(git.Commit().SetMessage("branch1 commit").Call());
     Iterator<RevCommit> log = git.Log().All().Call().Iterator();
     NUnit.Framework.Assert.IsTrue(log.HasNext());
     NUnit.Framework.Assert.IsTrue(commits.Contains(log.Next()));
     NUnit.Framework.Assert.IsTrue(log.HasNext());
     NUnit.Framework.Assert.IsTrue(commits.Contains(log.Next()));
     NUnit.Framework.Assert.IsTrue(log.HasNext());
     NUnit.Framework.Assert.IsTrue(commits.Contains(log.Next()));
     NUnit.Framework.Assert.IsFalse(log.HasNext());
 }
示例#5
0
 /// <exception cref="Kirikiri.Tjs2.VariantException"></exception>
 /// <exception cref="Kirikiri.Tjs2.TJSException"></exception>
 public static void SaveStructuredDataForObject(Dispatch2 dsp, AList<Dispatch2> stack
     , TextWriteStreamInterface stream, string indentstr)
 {
     // check object recursion
     int count = stack.Count;
     for (int i = 0; i < count; i++)
     {
         Dispatch2 d = stack[i];
         if (d == dsp)
         {
             // object recursion detected
             stream.Write("null /* object recursion detected */");
             return;
         }
     }
     // determin dsp's object type
     DictionaryNI dicni;
     ArrayNI arrayni;
     if (dsp != null)
     {
         dicni = (DictionaryNI)dsp.GetNativeInstance(DictionaryClass.ClassID);
         if (dicni != null)
         {
             // dictionary
             stack.AddItem(dsp);
             dicni.SaveStructuredData(stack, stream, indentstr);
             stack.Remove(stack.Count - 1);
             return;
         }
         else
         {
             arrayni = (ArrayNI)dsp.GetNativeInstance(ArrayClass.ClassID);
             if (arrayni != null)
             {
                 // array
                 stack.AddItem(dsp);
                 arrayni.SaveStructuredData(stack, stream, indentstr);
                 stack.Remove(stack.Count - 1);
                 return;
             }
             else
             {
                 // other objects
                 stream.Write("null /* (object) \"");
                 // stored as a null
                 Variant val = new Variant(dsp, dsp);
                 stream.Write(LexBase.EscapeC(val.AsString()));
                 stream.Write("\" */");
                 return;
             }
         }
     }
     stream.Write("null");
 }
示例#6
0
		/// <exception cref="System.IO.IOException"></exception>
        //private IDictionary<DerObjectIdentifier, Asn1Encodable> ExtendUnsignedAttributes(IDictionary
        //    <DerObjectIdentifier, Asn1Encodable> unsignedAttrs, X509Certificate signingCertificate
        //    , DateTime signingDate, CertificateSource optionalCertificateSource)
        private IDictionary ExtendUnsignedAttributes(IDictionary unsignedAttrs
            , X509Certificate signingCertificate, DateTime signingDate
            , CertificateSource optionalCertificateSource)
		{
			ValidationContext validationContext = certificateVerifier.ValidateCertificate(signingCertificate
				, signingDate, optionalCertificateSource, null, null);
			try
			{
				IList<X509CertificateStructure> certificateValues = new AList<X509CertificateStructure
					>();
				AList<CertificateList> crlValues = new AList<CertificateList>();
				AList<BasicOcspResponse> ocspValues = new AList<BasicOcspResponse>();
				foreach (CertificateAndContext c in validationContext.GetNeededCertificates())
				{
					if (!c.Equals(signingCertificate))
					{
                        certificateValues.AddItem(X509CertificateStructure.GetInstance(((Asn1Sequence)Asn1Object.FromByteArray
                            (c.GetCertificate().GetEncoded()))));
					}
				}
				foreach (X509Crl relatedcrl in validationContext.GetNeededCRL())
				{                    
					crlValues.AddItem(CertificateList.GetInstance((Asn1Sequence)Asn1Object.FromByteArray(((X509Crl
						)relatedcrl).GetEncoded())));
				}
				foreach (BasicOcspResp relatedocspresp in validationContext.GetNeededOCSPResp())
				{                    
					ocspValues.AddItem((BasicOcspResponse.GetInstance((Asn1Sequence)Asn1Object.FromByteArray(
						relatedocspresp.GetEncoded()))));
				}
				CertificateList[] crlValuesArray = new CertificateList[crlValues.Count];
				BasicOcspResponse[] ocspValuesArray = new BasicOcspResponse[ocspValues.Count];
				RevocationValues revocationValues = new RevocationValues(Sharpen.Collections.ToArray
					(crlValues, crlValuesArray), Sharpen.Collections.ToArray(ocspValues, ocspValuesArray
					), null);
				//unsignedAttrs.Put(PkcsObjectIdentifiers.IdAAEtsRevocationValues, new Attribute
                unsignedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsRevocationValues, new BcCms.Attribute
					(PkcsObjectIdentifiers.IdAAEtsRevocationValues, new DerSet(revocationValues))
					);
				X509CertificateStructure[] certValuesArray = new X509CertificateStructure[certificateValues
					.Count];
				//unsignedAttrs.Put(PkcsObjectIdentifiers.IdAAEtsCertValues, new Attribute(PkcsObjectIdentifiers.IdAAEtsCertValues, new DerSet(new DerSequence(Sharpen.Collections.ToArray(certificateValues
                unsignedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsCertValues, new BcCms.Attribute(PkcsObjectIdentifiers.IdAAEtsCertValues, new DerSet(new DerSequence(Sharpen.Collections.ToArray(certificateValues
					, certValuesArray)))));
			}
			catch (CertificateEncodingException e)
			{
				throw new RuntimeException(e);
			}
			catch (CrlException e)
			{
				throw new RuntimeException(e);
			}
			return unsignedAttrs;
		}
示例#7
0
		public override IList<AdvancedSignature> GetSignatures()
		{
			IList<AdvancedSignature> infos = new AList<AdvancedSignature>();
			foreach (object o in this.cmsSignedData.GetSignerInfos().GetSigners())
			{
				SignerInformation i = (SignerInformation)o;
				CAdESSignature info = new CAdESSignature(this.cmsSignedData, i.SignerID);
				infos.AddItem(info);
			}
			return infos;
		}
示例#8
0
        /// <summary>Update this remote's definition within the configuration.</summary>
        /// <remarks>Update this remote's definition within the configuration.</remarks>
        /// <param name="rc">the configuration file to store ourselves into.</param>
        public virtual void Update(Config rc)
        {
            IList <string> vlst = new AList <string>();

            vlst.Clear();
            foreach (URIish u in URIs)
            {
                vlst.AddItem(u.ToPrivateString());
            }
            rc.SetStringList(SECTION, Name, KEY_URL, vlst);
            vlst.Clear();
            foreach (URIish u_1 in PushURIs)
            {
                vlst.AddItem(u_1.ToPrivateString());
            }
            rc.SetStringList(SECTION, Name, KEY_PUSHURL, vlst);
            vlst.Clear();
            foreach (RefSpec u_2 in FetchRefSpecs)
            {
                vlst.AddItem(u_2.ToString());
            }
            rc.SetStringList(SECTION, Name, KEY_FETCH, vlst);
            vlst.Clear();
            foreach (RefSpec u_3 in PushRefSpecs)
            {
                vlst.AddItem(u_3.ToString());
            }
            rc.SetStringList(SECTION, Name, KEY_PUSH, vlst);
            Set(rc, KEY_UPLOADPACK, UploadPack, DEFAULT_UPLOAD_PACK);
            Set(rc, KEY_RECEIVEPACK, ReceivePack, DEFAULT_RECEIVE_PACK);
            Set(rc, KEY_TAGOPT, TagOpt.Option(), NGit.Transport.TagOpt.AUTO_FOLLOW.Option());
            Set(rc, KEY_MIRROR, mirror, DEFAULT_MIRROR);
            Set(rc, KEY_TIMEOUT, timeout, 0);
            if (!oldName.Equals(name))
            {
                rc.UnsetSection(SECTION, oldName);
                oldName = name;
            }
        }
示例#9
0
        /// <summary>
        /// Interpret the ChildrenDiff and generate a list of
        /// <see cref="Org.Apache.Hadoop.Hdfs.Protocol.SnapshotDiffReport.DiffReportEntry"/>
        /// .
        /// </summary>
        /// <param name="dirDiff">The ChildrenDiff.</param>
        /// <param name="parentPath">The relative path of the parent.</param>
        /// <param name="fromEarlier">
        /// True indicates
        /// <c>diff=later-earlier</c>
        /// ,
        /// False indicates
        /// <c>diff=earlier-later</c>
        /// </param>
        /// <param name="renameMap">A map containing information about rename operations.</param>
        /// <returns>
        /// A list of
        /// <see cref="Org.Apache.Hadoop.Hdfs.Protocol.SnapshotDiffReport.DiffReportEntry"/>
        /// as the diff report.
        /// </returns>
        private IList <SnapshotDiffReport.DiffReportEntry> GenerateReport(DirectoryWithSnapshotFeature.ChildrenDiff
                                                                          dirDiff, byte[][] parentPath, bool fromEarlier, IDictionary <long, SnapshotDiffInfo.RenameEntry
                                                                                                                                       > renameMap)
        {
            IList <SnapshotDiffReport.DiffReportEntry> list = new AList <SnapshotDiffReport.DiffReportEntry
                                                                         >();
            IList <INode> created = dirDiff.GetList(Diff.ListType.Created);
            IList <INode> deleted = dirDiff.GetList(Diff.ListType.Deleted);

            byte[][] fullPath = new byte[parentPath.Length + 1][];
            System.Array.Copy(parentPath, 0, fullPath, 0, parentPath.Length);
            foreach (INode cnode in created)
            {
                SnapshotDiffInfo.RenameEntry entry = renameMap[cnode.GetId()];
                if (entry == null || !entry.IsRename())
                {
                    fullPath[fullPath.Length - 1] = cnode.GetLocalNameBytes();
                    list.AddItem(new SnapshotDiffReport.DiffReportEntry(fromEarlier ? SnapshotDiffReport.DiffType
                                                                        .Create : SnapshotDiffReport.DiffType.Delete, fullPath));
                }
            }
            foreach (INode dnode in deleted)
            {
                SnapshotDiffInfo.RenameEntry entry = renameMap[dnode.GetId()];
                if (entry != null && entry.IsRename())
                {
                    list.AddItem(new SnapshotDiffReport.DiffReportEntry(SnapshotDiffReport.DiffType.Rename
                                                                        , fromEarlier ? entry.GetSourcePath() : entry.GetTargetPath(), fromEarlier ? entry
                                                                        .GetTargetPath() : entry.GetSourcePath()));
                }
                else
                {
                    fullPath[fullPath.Length - 1] = dnode.GetLocalNameBytes();
                    list.AddItem(new SnapshotDiffReport.DiffReportEntry(fromEarlier ? SnapshotDiffReport.DiffType
                                                                        .Delete : SnapshotDiffReport.DiffType.Create, fullPath));
                }
            }
            return(list);
        }
示例#10
0
        /// <exception cref="System.IO.IOException"/>
        private ICollection <BlockRecoveryCommand.RecoveringBlock> InitRecoveringBlocks()
        {
            ICollection <BlockRecoveryCommand.RecoveringBlock> blocks = new AList <BlockRecoveryCommand.RecoveringBlock
                                                                                   >(1);
            DatanodeInfo mockOtherDN = DFSTestUtil.GetLocalDatanodeInfo();

            DatanodeInfo[] locs = new DatanodeInfo[] { new DatanodeInfo(dn.GetDNRegistrationForBP
                                                                            (block.GetBlockPoolId())), mockOtherDN };
            BlockRecoveryCommand.RecoveringBlock rBlock = new BlockRecoveryCommand.RecoveringBlock
                                                              (block, locs, RecoveryId);
            blocks.AddItem(rBlock);
            return(blocks);
        }
        private static IList <DiffEntry> CompactDstList(IList <DiffEntry> @in)
        {
            AList <DiffEntry> r = new AList <DiffEntry>(@in.Count);

            foreach (DiffEntry e in @in)
            {
                if (e != null)
                {
                    r.AddItem(e);
                }
            }
            return(r);
        }
        private static IList <DiffEntry> CompactSrcList(IList <DiffEntry> @in)
        {
            AList <DiffEntry> r = new AList <DiffEntry>(@in.Count);

            foreach (DiffEntry e in @in)
            {
                if (e.changeType == DiffEntry.ChangeType.DELETE)
                {
                    r.AddItem(e);
                }
            }
            return(r);
        }
示例#13
0
        /// <summary>Returns the CRLs in the context which concern the provided certificate.</summary>
        /// <remarks>
        /// Returns the CRLs in the context which concern the provided certificate. It can happen there are more than one,
        /// even though this is unlikely.
        /// </remarks>
        /// <param name="cert">the X509 certificate</param>
        /// <returns>the list of CRLs related to the certificate</returns>
        public virtual IList <X509Crl> GetRelatedCRLs(CertificateAndContext cert)
        {
            IList <X509Crl> crls = new AList <X509Crl>();

            foreach (X509Crl crl in this.neededCRL)
            {
                if (ConcernsCertificate(crl, cert))
                {
                    crls.AddItem(crl);
                }
            }
            return(crls);
        }
示例#14
0
        /// <returns>
        /// return an array of the unique objects. The return value is
        /// expected to be used by the a combiner.
        /// </returns>
        public virtual AList <object> GetCombinerOutput()
        {
            object key = null;
            IEnumerator <object> iter = uniqItems.Keys.GetEnumerator();
            AList <object>       retv = new AList <object>();

            while (iter.HasNext())
            {
                key = iter.Next();
                retv.AddItem(key);
            }
            return(retv);
        }
示例#15
0
        public static IList <string> GetProxyHostsAndPortsForAmFilter(Configuration conf)
        {
            IList <string> addrs     = new AList <string>();
            string         proxyAddr = conf.Get(YarnConfiguration.ProxyAddress);

            // If PROXY_ADDRESS isn't set, fallback to RM_WEBAPP(_HTTPS)_ADDRESS
            // There could be multiple if using RM HA
            if (proxyAddr == null || proxyAddr.IsEmpty())
            {
                // If RM HA is enabled, try getting those addresses
                if (HAUtil.IsHAEnabled(conf))
                {
                    IList <string> haAddrs = RMHAUtils.GetRMHAWebappAddresses(new YarnConfiguration(conf
                                                                                                    ));
                    foreach (string addr in haAddrs)
                    {
                        try
                        {
                            IPEndPoint socketAddr = NetUtils.CreateSocketAddr(addr);
                            addrs.AddItem(GetResolvedAddress(socketAddr));
                        }
                        catch (ArgumentException)
                        {
                        }
                    }
                }
                // skip if can't resolve
                // If couldn't resolve any of the addresses or not using RM HA, fallback
                if (addrs.IsEmpty())
                {
                    addrs.AddItem(GetResolvedRMWebAppURLWithoutScheme(conf));
                }
            }
            else
            {
                addrs.AddItem(proxyAddr);
            }
            return(addrs);
        }
示例#16
0
        /// <exception cref="System.Exception"/>
        public virtual void TestDataDirValidation()
        {
            DataNode.DataNodeDiskChecker diskChecker = Org.Mockito.Mockito.Mock <DataNode.DataNodeDiskChecker
                                                                                 >();
            Org.Mockito.Mockito.DoThrow(new IOException()).DoThrow(new IOException()).DoNothing
                ().When(diskChecker).CheckDir(Any <LocalFileSystem>(), Any <Path>());
            LocalFileSystem fs = Org.Mockito.Mockito.Mock <LocalFileSystem>();
            AbstractList <StorageLocation> locations = new AList <StorageLocation>();

            locations.AddItem(StorageLocation.Parse("file:/p1/"));
            locations.AddItem(StorageLocation.Parse("file:/p2/"));
            locations.AddItem(StorageLocation.Parse("file:/p3/"));
            IList <StorageLocation> checkedLocations = DataNode.CheckStorageLocations(locations
                                                                                      , fs, diskChecker);

            NUnit.Framework.Assert.AreEqual("number of valid data dirs", 1, checkedLocations.
                                            Count);
            string validDir = checkedLocations.GetEnumerator().Next().GetFile().GetPath();

            Assert.AssertThat("p3 should be valid", new FilePath("/p3/").GetPath(), CoreMatchers.Is
                                  (validDir));
        }
示例#17
0
        public override IList <X509Certificate> GetCertificates()
        {
            IList <X509Certificate> list = new AList <X509Certificate>();

            XmlNodeList nodes;

            nodes = XmlUtils.GetNodeList(signatureElement,
                                         "//ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CertificateValues/xades:EncapsulatedX509Certificate");

            foreach (XmlNode node in nodes)
            {
                byte[] derEncoded = Base64.Decode(
                    System.Text.Encoding.ASCII.GetBytes(node.InnerText));
                X509Certificate cert = new X509CertificateParser().ReadCertificate(derEncoded);
                if (!list.Contains(cert))
                {
                    list.AddItem(cert);
                }
            }

            if (!onlyExtended)
            {
                nodes = XmlUtils.GetNodeList(signatureElement,
                                             "//ds:KeyInfo/ds:X509Data/ds:X509Certificate");

                foreach (XmlNode node in nodes)
                {
                    byte[] derEncoded = Base64.Decode(
                        System.Text.Encoding.ASCII.GetBytes(node.InnerText));
                    X509Certificate cert = new X509CertificateParser().ReadCertificate(derEncoded);
                    if (!list.Contains(cert))
                    {
                        list.AddItem(cert);
                    }
                }
            }

            return(list);
        }
示例#18
0
                               > GetProtocolImplMap(RPC.RpcKind rpcKind)
 {
     if (protocolImplMapArray.Count == 0)
     {
         // initialize for all rpc kinds
         for (int i = 0; i <= RPC.RpcKind.MaxIndex; ++i)
         {
             protocolImplMapArray.AddItem(new Dictionary <RPC.Server.ProtoNameVer, RPC.Server.ProtoClassProtoImpl
                                                          >(10));
         }
     }
     return(protocolImplMapArray[(int)(rpcKind)]);
 }
示例#19
0
        /// <summary>Retrieve all the qualifiers for which the corresponding condition evaluate to true.
        ///     </summary>
        /// <remarks>Retrieve all the qualifiers for which the corresponding condition evaluate to true.
        ///     </remarks>
        /// <param name="cert"></param>
        /// <returns></returns>
        public virtual IList <string> GetQualifiers(CertificateAndContext cert)
        {
            IList <string> list = new AList <string>();

            foreach (KeyValuePair <string, Condition> e in qualifiersAndConditions.EntrySet())
            {
                if (e.Value.Check(cert))
                {
                    list.AddItem(e.Key);
                }
            }
            return(list);
        }
示例#20
0
        /// <summary>
        /// Logically splits the set of input files for the job, splits N lines
        /// of the input as one split.
        /// </summary>
        /// <seealso cref="Org.Apache.Hadoop.Mapred.FileInputFormat{K, V}.GetSplits(Org.Apache.Hadoop.Mapred.JobConf, int)
        ///     "/>
        /// <exception cref="System.IO.IOException"/>
        public override InputSplit[] GetSplits(JobConf job, int numSplits)
        {
            AList <FileSplit> splits = new AList <FileSplit>();

            foreach (FileStatus status in ListStatus(job))
            {
                foreach (FileSplit split in NLineInputFormat.GetSplitsForFile(status, job, N))
                {
                    splits.AddItem(new FileSplit(split));
                }
            }
            return(Sharpen.Collections.ToArray(splits, new FileSplit[splits.Count]));
        }
示例#21
0
        public virtual SnapshottableDirectoryStatus.Bean[] GetSnapshottableDirectories()
        {
            // SnapshotStatsMXBean
            IList <SnapshottableDirectoryStatus.Bean> beans = new AList <SnapshottableDirectoryStatus.Bean
                                                                         >();

            foreach (INodeDirectory d in GetSnapshottableDirs())
            {
                beans.AddItem(ToBean(d));
            }
            return(Sharpen.Collections.ToArray(beans, new SnapshottableDirectoryStatus.Bean[beans
                                                                                            .Count]));
        }
示例#22
0
        /// <exception cref="NGit.Errors.TransportException"></exception>
        private ICollection <Ref> ExpandAutoFollowTags()
        {
            ICollection <Ref>         additionalTags = new AList <Ref>();
            IDictionary <string, Ref> haveRefs       = transport.local.GetAllRefs();

            foreach (Ref r in conn.GetRefs())
            {
                if (!IsTag(r))
                {
                    continue;
                }
                if (r.GetPeeledObjectId() == null)
                {
                    additionalTags.AddItem(r);
                    continue;
                }
                Ref local = haveRefs.Get(r.GetName());
                if (local != null)
                {
                    if (!r.GetObjectId().Equals(local.GetObjectId()))
                    {
                        WantTag(r);
                    }
                }
                else
                {
                    if (askFor.ContainsKey(r.GetPeeledObjectId()) || transport.local.HasObject(r.GetPeeledObjectId
                                                                                                   ()))
                    {
                        WantTag(r);
                    }
                    else
                    {
                        additionalTags.AddItem(r);
                    }
                }
            }
            return(additionalTags);
        }
示例#23
0
        /// <summary>
        /// Parses a string representation of an ACL spec into a list of AclEntry
        /// objects.
        /// </summary>
        /// <remarks>
        /// Parses a string representation of an ACL spec into a list of AclEntry
        /// objects. Example: "user::rwx,user:foo:rw-,group::r--,other::---"
        /// </remarks>
        /// <param name="aclSpec">String representation of an ACL spec.</param>
        /// <param name="includePermission">
        /// for setAcl operations this will be true. i.e. AclSpec should
        /// include permissions.<br />
        /// But for removeAcl operation it will be false. i.e. AclSpec should
        /// not contain permissions.<br />
        /// Example: "user:foo,group:bar"
        /// </param>
        /// <returns>
        /// Returns list of
        /// <see cref="AclEntry"/>
        /// parsed
        /// </returns>
        public static IList <AclEntry> ParseAclSpec(string aclSpec, bool includePermission
                                                    )
        {
            IList <AclEntry>     aclEntries = new AList <AclEntry>();
            ICollection <string> aclStrings = StringUtils.GetStringCollection(aclSpec, ",");

            foreach (string aclStr in aclStrings)
            {
                AclEntry aclEntry = ParseAclEntry(aclStr, includePermission);
                aclEntries.AddItem(aclEntry);
            }
            return(aclEntries);
        }
示例#24
0
        public virtual IList <AdvancedSignature> GetCounterSignatures()
        {
            IList <AdvancedSignature> counterSigs = new AList <AdvancedSignature>();

            foreach (object o in this.signerInformation.GetCounterSignatures().GetSigners())
            {
                SignerInformation i = (SignerInformation)o;
                EU.Europa.EC.Markt.Dss.Validation.Cades.CAdESSignature info = new EU.Europa.EC.Markt.Dss.Validation.Cades.CAdESSignature
                                                                                  (this.cmsSignedData, i.SignerID);
                counterSigs.AddItem(info);
            }
            return(counterSigs);
        }
示例#25
0
            /// <summary>
            /// Generate the requested number of file splits, with the filename
            /// set to the filename of the output file.
            /// </summary>
            /// <exception cref="System.IO.IOException"/>
            public override IList <InputSplit> GetSplits(JobContext job)
            {
                IList <InputSplit> result = new AList <InputSplit>();
                Path outDir    = FileOutputFormat.GetOutputPath(job);
                int  numSplits = job.GetConfiguration().GetInt(MRJobConfig.NumMaps, 1);

                for (int i = 0; i < numSplits; ++i)
                {
                    result.AddItem(new FileSplit(new Path(outDir, "dummy-split-" + i), 0, 1, (string[]
                                                                                              )null));
                }
                return(result);
            }
示例#26
0
        private IList <string> GetProcessed(IList <string> inputs, IList <string> badRecs)
        {
            IList <string> processed = new AList <string>();

            foreach (string input in inputs)
            {
                if (!badRecs.Contains(input))
                {
                    processed.AddItem(input);
                }
            }
            return(processed);
        }
示例#27
0
        /// <summary>Dump a list of currently running jobs</summary>
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="System.Exception"/>
        private void ListJobs(Cluster cluster)
        {
            IList <JobStatus> runningJobs = new AList <JobStatus>();

            foreach (JobStatus job in cluster.GetAllJobStatuses())
            {
                if (!job.IsJobComplete())
                {
                    runningJobs.AddItem(job);
                }
            }
            DisplayJobList(Sharpen.Collections.ToArray(runningJobs, new JobStatus[0]));
        }
        private void AddLocalRequestsToProto()
        {
            MaybeInitBuilder();
            builder.ClearStartContainerRequest();
            IList <YarnServiceProtos.StartContainerRequestProto> protoList = new AList <YarnServiceProtos.StartContainerRequestProto
                                                                                        >();

            foreach (StartContainerRequest r in this.requests)
            {
                protoList.AddItem(ConvertToProtoFormat(r));
            }
            builder.AddAllStartContainerRequest(protoList);
        }
示例#29
0
        /// <summary>Get an RPC proxy for each NN in an HA nameservice.</summary>
        /// <remarks>
        /// Get an RPC proxy for each NN in an HA nameservice. Used when a given RPC
        /// call should be made on every NN in an HA nameservice, not just the active.
        /// </remarks>
        /// <param name="conf">configuration</param>
        /// <param name="nsId">the nameservice to get all of the proxies for.</param>
        /// <returns>a list of RPC proxies for each NN in the nameservice.</returns>
        /// <exception cref="System.IO.IOException">in the event of error.</exception>
        public static IList <ClientProtocol> GetProxiesForAllNameNodesInNameservice(Configuration
                                                                                    conf, string nsId)
        {
            IList <NameNodeProxies.ProxyAndInfo <ClientProtocol> > proxies = GetProxiesForAllNameNodesInNameservice
                                                                             <ClientProtocol>(conf, nsId);
            IList <ClientProtocol> namenodes = new AList <ClientProtocol>(proxies.Count);

            foreach (NameNodeProxies.ProxyAndInfo <ClientProtocol> proxy in proxies)
            {
                namenodes.AddItem(proxy.GetProxy());
            }
            return(namenodes);
        }
示例#30
0
            /// <summary>Load the deleted list in a DirectoryDiff</summary>
            /// <exception cref="System.IO.IOException"/>
            private IList <INode> LoadDeletedList(IList <INodeReference> refList, InputStream @in
                                                  , INodeDirectory dir, IList <long> deletedNodes, IList <int> deletedRefNodes)
            {
                IList <INode> dlist = new AList <INode>(deletedRefNodes.Count + deletedNodes.Count);

                // load non-reference inodes
                foreach (long deletedId in deletedNodes)
                {
                    INode deleted = fsDir.GetInode(deletedId);
                    dlist.AddItem(deleted);
                    AddToDeletedList(deleted, dir);
                }
                // load reference nodes in the deleted list
                foreach (int refId in deletedRefNodes)
                {
                    INodeReference deletedRef = refList[refId];
                    dlist.AddItem(deletedRef);
                    AddToDeletedList(deletedRef, dir);
                }
                dlist.Sort(new _IComparer_303());
                return(dlist);
            }
 public static string[] GetAllMatches(string input)
 {
     Sharpen.Pattern p = Sharpen.Pattern.Compile("([0-9]*\\.[0-9]+|[0-9]+|[a-zA-Z]+|[^\\w\\s])"
         );
     Matcher m = p.Matcher(input);
     AList<string> matches = new AList<string>();
     while (m.Find())
     {
         matches.AddItem(m.Group());
     }
     string[] matchArr = new string[matches.Count];
     return Sharpen.Collections.ToArray(matches, matchArr);
 }
示例#32
0
        /// <summary>Divides the given string into lines.</summary>
        /// <remarks>Divides the given string into lines.</remarks>
        /// <param name="s">the string to read</param>
        /// <returns>the string divided into lines</returns>
        /// <since>2.0</since>
        public static IList <string> ReadLines(string s)
        {
            IList <string> l  = new AList <string>();
            StringBuilder  sb = new StringBuilder();

            for (int i = 0; i < s.Length; i++)
            {
                char c = s[i];
                if (c == '\n')
                {
                    l.AddItem(sb.ToString());
                    sb.Length = 0;
                    continue;
                }
                if (c == '\r')
                {
                    if (i + 1 < s.Length)
                    {
                        c = s[++i];
                        l.AddItem(sb.ToString());
                        sb.Length = 0;
                        if (c != '\n')
                        {
                            sb.Append(c);
                        }
                        continue;
                    }
                    else
                    {
                        // EOF
                        l.AddItem(sb.ToString());
                        break;
                    }
                }
                sb.Append(c);
            }
            l.AddItem(sb.ToString());
            return(l);
        }
示例#33
0
        /// <summary>Translate an absolute path into a list of path components.</summary>
        /// <remarks>
        /// Translate an absolute path into a list of path components.
        /// We merge double slashes into a single slash here.
        /// POSIX root path, i.e. '/', does not get an entry in the list.
        /// </remarks>
        /// <exception cref="System.IO.IOException"/>
        private static IList <string> GetPathComponents(string path)
        {
            AList <string> ret = new AList <string>();

            foreach (string component in path.Split(Path.Separator))
            {
                if (!component.IsEmpty())
                {
                    ret.AddItem(component);
                }
            }
            return(ret);
        }
示例#34
0
        /// <exception cref="System.IO.IOException"/>
        public virtual void TestChangeVolumeWithRunningCheckDirs()
        {
            RoundRobinVolumeChoosingPolicy <FsVolumeImpl> blockChooser = new RoundRobinVolumeChoosingPolicy
                                                                         <FsVolumeImpl>();

            conf.SetLong(DFSConfigKeys.DfsDatanodeScanPeriodHoursKey, -1);
            BlockScanner blockScanner = new BlockScanner(datanode, conf);
            FsVolumeList volumeList   = new FsVolumeList(Sharpen.Collections.EmptyList <VolumeFailureInfo
                                                                                        >(), blockScanner, blockChooser);
            IList <FsVolumeImpl> oldVolumes = new AList <FsVolumeImpl>();
            // Initialize FsVolumeList with 5 mock volumes.
            int NumVolumes = 5;

            for (int i = 0; i < NumVolumes; i++)
            {
                FsVolumeImpl volume = Org.Mockito.Mockito.Mock <FsVolumeImpl>();
                oldVolumes.AddItem(volume);
                Org.Mockito.Mockito.When(volume.GetBasePath()).ThenReturn("data" + i);
                FsVolumeReference @ref = Org.Mockito.Mockito.Mock <FsVolumeReference>();
                Org.Mockito.Mockito.When(@ref.GetVolume()).ThenReturn(volume);
                volumeList.AddVolume(@ref);
            }
            // When call checkDirs() on the 2nd volume, anther "thread" removes the 5th
            // volume and add another volume. It does not affect checkDirs() running.
            FsVolumeImpl      newVolume = Org.Mockito.Mockito.Mock <FsVolumeImpl>();
            FsVolumeReference newRef    = Org.Mockito.Mockito.Mock <FsVolumeReference>();

            Org.Mockito.Mockito.When(newRef.GetVolume()).ThenReturn(newVolume);
            Org.Mockito.Mockito.When(newVolume.GetBasePath()).ThenReturn("data4");
            FsVolumeImpl blockedVolume = volumeList.GetVolumes()[1];

            Org.Mockito.Mockito.DoAnswer(new _Answer_295(volumeList, newRef)).When(blockedVolume
                                                                                   ).CheckDirs();
            FsVolumeImpl brokenVolume = volumeList.GetVolumes()[2];

            Org.Mockito.Mockito.DoThrow(new DiskChecker.DiskErrorException("broken")).When(brokenVolume
                                                                                           ).CheckDirs();
            volumeList.CheckDirs();
            // Since FsVolumeImpl#checkDirs() get a snapshot of the list of volumes
            // before running removeVolume(), it is supposed to run checkDirs() on all
            // the old volumes.
            foreach (FsVolumeImpl volume_1 in oldVolumes)
            {
                Org.Mockito.Mockito.Verify(volume_1).CheckDirs();
            }
            // New volume is not visible to checkDirs() process.
            Org.Mockito.Mockito.Verify(newVolume, Org.Mockito.Mockito.Never()).CheckDirs();
            NUnit.Framework.Assert.IsTrue(volumeList.GetVolumes().Contains(newVolume));
            NUnit.Framework.Assert.IsFalse(volumeList.GetVolumes().Contains(brokenVolume));
            NUnit.Framework.Assert.AreEqual(NumVolumes - 1, volumeList.GetVolumes().Count);
        }
示例#35
0
        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"));
        }
示例#36
0
        /// <exception cref="System.IO.IOException"/>
        public override InputSplit[] GetSplits(JobConf conf, int numSplits)
        {
            AList <InputSplit> result = new AList <InputSplit>();
            FileSystem         local  = FileSystem.GetLocal(conf);

            foreach (Path dir in GetInputPaths(conf))
            {
                foreach (FileStatus file in local.ListStatus(dir))
                {
                    result.AddItem(new WordCountInputFormat.WordCountInputSplit(file.GetPath()));
                }
            }
            return(Sharpen.Collections.ToArray(result, new InputSplit[result.Count]));
        }
示例#37
0
        internal virtual ICollection <string> GetVolumesLowOnSpace()
        {
            if (Log.IsDebugEnabled())
            {
                Log.Debug("Going to check the following volumes disk space: " + volumes);
            }
            ICollection <string> lowVolumes = new AList <string>();

            foreach (NameNodeResourceChecker.CheckedVolume volume in volumes.Values)
            {
                lowVolumes.AddItem(volume.GetVolume());
            }
            return(lowVolumes);
        }
示例#38
0
        /// <summary>
        /// Gets all the declared methods of a class including methods declared in
        /// superclasses.
        /// </summary>
        public static IList <MethodInfo> GetDeclaredMethodsIncludingInherited(Type clazz)
        {
            IList <MethodInfo> methods = new AList <MethodInfo>();

            while (clazz != null)
            {
                foreach (MethodInfo method in Runtime.GetDeclaredMethods(clazz))
                {
                    methods.AddItem(method);
                }
                clazz = clazz.BaseType;
            }
            return(methods);
        }
示例#39
0
 public static Query GetQueryById(Database database, string userId)
 {
     View view = database.GetView(ByIdViewName);
     if (view.GetMap() == null)
     {
         Mapper map = new _Mapper_52();
         view.SetMap(map, null);
     }
     Query query = view.CreateQuery();
     IList<object> keys = new AList<object>();
     keys.AddItem(userId);
     query.SetKeys(keys);
     return query;
 }
示例#40
0
 /// <exception cref="Sharpen.SAXException"></exception>
 public bool Start(NBoilerpipeContentHandler instance, string localName, HtmlAttributeCollection atts)
 {
     IList<string> labels = new AList<string> (5);
     labels.AddItem (DefaultLabels.MARKUP_PREFIX + localName);
     string classVal = atts ["class"].Value;
     if (classVal != null && classVal.Length > 0) {
         classVal = PAT_NUM.Matcher (classVal).ReplaceAll ("#");
         classVal = classVal.Trim ();
         string[] vals = classVal.Split ("[ ]+");
         labels.AddItem (DefaultLabels.MARKUP_PREFIX + "." + classVal.Replace (' ', '.'));
         if (vals.Length > 1) {
             foreach (string s in vals) {
                 labels.AddItem (DefaultLabels.MARKUP_PREFIX + "." + s);
             }
         }
     }
     var att = atts["id"];
     var id =  ( atts !=null) ? att.Name : "";
     if (id != null && id.Length > 0) {
         id = PAT_NUM.Matcher (id).ReplaceAll ("#");
         labels.AddItem (DefaultLabels.MARKUP_PREFIX + "#" + id);
     }
     ICollection<string> ancestors = GetAncestorLabels ();
     IList<string> labelsWithAncestors = new AList<string> ((ancestors.Count + 1) * labels
         .Count);
     foreach (string l in labels) {
         foreach (string an in ancestors) {
             labelsWithAncestors.AddItem (an);
             labelsWithAncestors.AddItem (an + " " + l);
         }
         labelsWithAncestors.AddItem (l);
     }
     instance.AddLabelAction (new LabelAction (Sharpen.Collections.ToArray (labelsWithAncestors
         , new string[labelsWithAncestors.Count])));
     labelStack.AddItem (labels);
     return isBlockLevel;
 }
 public IList<CertificateAndContext> GetCertificateBySubjectName(X509Name subjectName
     )
 {
     IList<CertificateAndContext> list = new AList<CertificateAndContext>();
     foreach (X509Certificate cert in GetCertificates())
     {
         if (subjectName.Equals(cert.SubjectDN))
         {
             CertificateAndContext cc = new CertificateAndContext(cert);
             cc.SetCertificateSource(sourceType);
             list.AddItem(cc);
         }
     }
     return list;
 }
 /// <exception cref="System.Exception"></exception>
 public virtual void TestJsonArray()
 {
     IList<object> array = new AList<object>();
     array.AddItem("01234567890");
     array.AddItem("bar");
     array.AddItem(5);
     array.AddItem(3.5);
     array.AddItem(true);
     array.AddItem(new DateTime().ToString());
     ObjectWriter mapper = new ObjectWriter();
     byte[] json = mapper.WriteValueAsBytes(array);
     JsonDocument jsdoc = new JsonDocument(json);
     NUnit.Framework.Assert.AreEqual(array, jsdoc.JsonObject());
 }
示例#43
0
		/// <exception cref="System.IO.IOException"></exception>
		public virtual Document ExtendSignatures(Document document, Document originalData
			, SignatureParameters parameters)
		{
			try
			{
				CmsSignedData signedData = new CmsSignedData(document.OpenStream());
				SignerInformationStore signerStore = signedData.GetSignerInfos();
				AList<SignerInformation> siArray = new AList<SignerInformation>();				

                foreach (SignerInformation si in signerStore.GetSigners())
                {                    
                    try
                    {
                        //jbonilla - Hack para evitar errores cuando una firma ya ha sido extendida.
                        //Se asume que sólo se extiende las firmas desde BES.
                        //TODO jbonilla - Se debería validar hasta qué punto se extendió (BES, T, C, X, XL).
                        if(si.UnsignedAttributes.Count == 0)
                        {
                            siArray.AddItem(ExtendCMSSignature(signedData, si, parameters, originalData));
                        }
                        else
                        {
                            LOG.Error("Already extended?");
                            siArray.AddItem(si);
                        }                        
                    }
                    catch (IOException)
                    {
                        LOG.Error("Exception when extending signature");
                        siArray.AddItem(si);
                    }
                }
				
				SignerInformationStore newSignerStore = new SignerInformationStore(siArray);
				CmsSignedData extended = CmsSignedData.ReplaceSigners(signedData, newSignerStore);
				return new InMemoryDocument(extended.GetEncoded());
			}
			catch (CmsException)
			{
				throw new IOException("Cannot parse CMS data");
			}
		}
示例#44
0
		public override IList<Couchbase.Lite.SavedRevision> GetRevisionHistory()
		{
			IList<Couchbase.Lite.SavedRevision> revisions = new AList<Couchbase.Lite.SavedRevision
				>();
			IList<RevisionInternal> internalRevisions = GetDatabase().GetRevisionHistory(revisionInternal
				);
			foreach (RevisionInternal internalRevision in internalRevisions)
			{
				if (internalRevision.GetRevId().Equals(GetId()))
				{
					revisions.AddItem(this);
				}
				else
				{
					Couchbase.Lite.SavedRevision revision = document.GetRevisionFromRev(internalRevision
						);
					revisions.AddItem(revision);
				}
			}
			Sharpen.Collections.Reverse(revisions);
			return Sharpen.Collections.UnmodifiableList(revisions);
		}
示例#45
0
		public virtual void TestServer()
		{
			IDictionary<string, object> responseBody = new Dictionary<string, object>();
			responseBody["CBLite"] = "Welcome";
			responseBody["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["ok"] = true;
			userCtx["name"] = null;
			userCtx["roles"] = roles;
			session["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);
		}
 public override IList<X509Certificate> GetCertificates()
 {
     IList<X509Certificate> certs = new AList<X509Certificate>();
     try
     {
         //foreach (X509Certificate c in ocspResp.GetCerts(null))
         foreach (X509Certificate c in ocspResp.GetCerts())
         {
             LOG.Info(c.SubjectDN + " issued by " + c.IssuerDN
                  + " serial number " + c.SerialNumber);
             certs.AddItem(c);
         }
     }
     catch (OcspException)
     {
         throw new EncodingException(EncodingException.MSG.OCSP_CANNOT_BE_READ);
     }
     /*catch (NoSuchProviderException e)
     {
         // Provider (BouncyCastle) not found. Should never happens.
         throw new RuntimeException(e);
     }*/
     return certs;
 }
示例#47
0
		/// <summary>Filter a list of commands according to result.</summary>
		/// <remarks>Filter a list of commands according to result.</remarks>
		/// <param name="commands">commands to filter.</param>
		/// <param name="want">desired status to filter by.</param>
		/// <returns>
		/// a copy of the command list containing only those commands with
		/// the desired status.
		/// </returns>
		/// <since>2.0</since>
		public static IList<NGit.Transport.ReceiveCommand> Filter(IList<NGit.Transport.ReceiveCommand
			> commands, ReceiveCommand.Result want)
		{
			IList<NGit.Transport.ReceiveCommand> r = new AList<NGit.Transport.ReceiveCommand>
				(commands.Count);
			foreach (NGit.Transport.ReceiveCommand cmd in commands)
			{
				if (cmd.GetResult() == want)
				{
					r.AddItem(cmd);
				}
			}
			return r;
		}
示例#48
0
 /// <exception cref="Kirikiri.Tjs2.TJSException"></exception>
 /// <exception cref="Kirikiri.Tjs2.VariantException"></exception>
 public virtual void AssignStructure(Dispatch2 dsp, AList<Dispatch2> stack)
 {
     // assign structured data from dsp
     ArrayNI arrayni = (ArrayNI)dsp.GetNativeInstance(ArrayClass.ClassID);
     if (arrayni != null)
     {
         // copy from array
         stack.AddItem(dsp);
         try
         {
             mItems.Clear();
             int count = arrayni.mItems.Count;
             for (int i = 0; i < count; i++)
             {
                 Variant v = arrayni.mItems[i];
                 if (v.IsObject())
                 {
                     // object
                     Dispatch2 dsp1 = v.AsObject();
                     // determin dsp's object type
                     //DictionaryNI dicni = null;
                     //ArrayNI arrayni1 = null;
                     if (dsp1 != null && dsp1.GetNativeInstance(DictionaryClass.ClassID) != null)
                     {
                         //dicni = (DictionaryNI)ni.mValue;
                         // dictionary
                         bool objrec = false;
                         int scount = stack.Count;
                         for (int j = 0; j < scount; j++)
                         {
                             Dispatch2 d = stack[j];
                             if (d == dsp1)
                             {
                                 // object recursion detected
                                 objrec = true;
                                 break;
                             }
                         }
                         if (objrec)
                         {
                             mItems.AddItem(new Variant());
                         }
                         else
                         {
                             // becomes null
                             Dispatch2 newobj = TJS.CreateDictionaryObject();
                             mItems.AddItem(new Variant(newobj, newobj));
                             DictionaryNI newni;
                             if ((newni = (DictionaryNI)newobj.GetNativeInstance(DictionaryClass.ClassID)) !=
                                 null)
                             {
                                 newni.AssignStructure(dsp1, stack);
                             }
                         }
                     }
                     else
                     {
                         if (dsp1 != null && dsp1.GetNativeInstance(ArrayClass.ClassID) != null)
                         {
                             // array
                             bool objrec = false;
                             int scount = stack.Count;
                             for (int j = 0; j < scount; j++)
                             {
                                 Dispatch2 d = stack[j];
                                 if (d == dsp1)
                                 {
                                     // object recursion detected
                                     objrec = true;
                                     break;
                                 }
                             }
                             if (objrec)
                             {
                                 mItems.AddItem(new Variant());
                             }
                             else
                             {
                                 // becomes null
                                 Dispatch2 newobj = TJS.CreateArrayObject();
                                 mItems.AddItem(new Variant(newobj, newobj));
                                 ArrayNI newni;
                                 if ((newni = (ArrayNI)newobj.GetNativeInstance(ArrayClass.ClassID)) != null)
                                 {
                                     newni.AssignStructure(dsp1, stack);
                                 }
                             }
                         }
                         else
                         {
                             // other object types
                             mItems.AddItem(v);
                         }
                     }
                 }
                 else
                 {
                     // others
                     mItems.AddItem(v);
                 }
             }
         }
         finally
         {
             stack.Remove(stack.Count - 1);
         }
     }
     else
     {
         throw new TJSException(Error.SpecifyDicOrArray);
     }
 }
		/// <summary>Construct the merge commit message.</summary>
		/// <remarks>Construct the merge commit message.</remarks>
		/// <param name="refsToMerge">the refs which will be merged</param>
		/// <param name="target">the branch ref which will be merged into</param>
		/// <returns>merge commit message</returns>
		public virtual string Format(IList<Ref> refsToMerge, Ref target)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append("Merge ");
			IList<string> branches = new AList<string>();
			IList<string> remoteBranches = new AList<string>();
			IList<string> tags = new AList<string>();
			IList<string> commits = new AList<string>();
			IList<string> others = new AList<string>();
			foreach (Ref @ref in refsToMerge)
			{
				if (@ref.GetName().StartsWith(Constants.R_HEADS))
				{
					branches.AddItem("'" + Repository.ShortenRefName(@ref.GetName()) + "'");
				}
				else
				{
					if (@ref.GetName().StartsWith(Constants.R_REMOTES))
					{
						remoteBranches.AddItem("'" + Repository.ShortenRefName(@ref.GetName()) + "'");
					}
					else
					{
						if (@ref.GetName().StartsWith(Constants.R_TAGS))
						{
							tags.AddItem("'" + Repository.ShortenRefName(@ref.GetName()) + "'");
						}
						else
						{
							if (@ref.GetName().Equals(@ref.GetObjectId().GetName()))
							{
								commits.AddItem("'" + @ref.GetName() + "'");
							}
							else
							{
								others.AddItem(@ref.GetName());
							}
						}
					}
				}
			}
			IList<string> listings = new AList<string>();
			if (!branches.IsEmpty())
			{
				listings.AddItem(JoinNames(branches, "branch", "branches"));
			}
			if (!remoteBranches.IsEmpty())
			{
				listings.AddItem(JoinNames(remoteBranches, "remote branch", "remote branches"));
			}
			if (!tags.IsEmpty())
			{
				listings.AddItem(JoinNames(tags, "tag", "tags"));
			}
			if (!commits.IsEmpty())
			{
				listings.AddItem(JoinNames(commits, "commit", "commits"));
			}
			if (!others.IsEmpty())
			{
				listings.AddItem(StringUtils.Join(others, ", ", " and "));
			}
			sb.Append(StringUtils.Join(listings, ", "));
			string targetName = target.GetLeaf().GetName();
			if (!targetName.Equals(Constants.R_HEADS + Constants.MASTER))
			{
				string targetShortName = Repository.ShortenRefName(target.GetName());
				sb.Append(" into " + targetShortName);
			}
			return sb.ToString();
		}
示例#50
0
			/// <exception cref="NGit.Errors.TransportException"></exception>
			public virtual SystemProcess Exec(string command, int timeout)
			{
				string ssh = SystemReader.GetInstance().Getenv("GIT_SSH");
				bool putty = ssh.ToLower().Contains("plink");
				IList<string> args = new AList<string>();
				args.AddItem(ssh);
				if (putty && !ssh.ToLower().Contains("tortoiseplink"))
				{
					args.AddItem("-batch");
				}
				if (0 < this._enclosing.GetURI().GetPort())
				{
					args.AddItem(putty ? "-P" : "-p");
					args.AddItem(this._enclosing.GetURI().GetPort().ToString());
				}
				if (this._enclosing.GetURI().GetUser() != null)
				{
					args.AddItem(this._enclosing.GetURI().GetUser() + "@" + this._enclosing.GetURI().
						GetHost());
				}
				else
				{
					args.AddItem(this._enclosing.GetURI().GetHost());
				}
				args.AddItem(command);
				ProcessStartInfo pb = new ProcessStartInfo();
				pb.SetCommand(args);
				if (this._enclosing.local.Directory != null)
				{
					pb.EnvironmentVariables.Put(Constants.GIT_DIR_KEY, this._enclosing.local.Directory
						.GetPath());
				}
				try
				{
					return pb.Start();
				}
				catch (IOException err)
				{
					throw new TransportException(err.Message, err);
				}
			}
 private static Operator[] GetOperatorsFromLexeme(Operator[] ops, Lexeme lex)
 {
     AList<Operator> list = new AList<Operator>();
     foreach (Operator op in ops)
     {
         if (lex.GetType() == Lexeme.OPERATOR && lex.GetValue().Equals(op.symbol))
         {
             list.AddItem(op);
         }
     }
     return Sharpen.Collections.ToArray(list, new Operator[list.Count]);
 }
示例#52
0
 public IList<string> GetAllDatabaseNames()
 {
     string[] databaseFiles = directoryFile.List(new _FilenameFilter_178());
     IList<string> result = new AList<string>();
     foreach (string databaseFile in databaseFiles)
     {
         string trimmed = Sharpen.Runtime.Substring(databaseFile, 0, databaseFile.Length -
              Couchbase.Lite.Manager.DatabaseSuffix.Length);
         string replaced = trimmed.Replace(':', '/');
         result.AddItem(replaced);
     }
     result.Sort();
     return Sharpen.Collections.UnmodifiableList(result);
 }
        /// <summary>Returns an expression-tree that represents the expression string.</summary>
        /// <remarks>Returns an expression-tree that represents the expression string.  Returns null if the string is empty.
        /// 	</remarks>
        /// <exception cref="ExpressionParseException">If the string is invalid.</exception>
        public static Expression Parse(string s)
        {
            if (s == null)
            {
                throw new ExpressionParseException("Expression string cannot be null.", -1);
            }
            AList<Lexeme> lexemes = Lexify(s);
            //Make tokens
            System.Console.Out.WriteLine("Lexemes:");
            foreach (Lexeme item in lexemes)
            {
                System.Console.Out.Write(item.ToString());
            }
            Operator[] operators = GetOperators();
            string nl = Runtime.GetProperty("line.separator");
            System.Console.Out.WriteLine(nl + "Operators:");
            foreach (Operator oper in operators)
            {
                System.Console.Out.Write(oper.ToString() + " ");
            }
            System.Console.Out.Write(nl);
            //build tree
            Stack<Expression> terms = new Stack<Expression>();
            Stack<Expression> exprOps = new Stack<Expression>();
            Stack<Expression> exprList = new Stack<Expression>();
            Stack<Operator> opStack = new Stack<Operator>();
            Stack<Lexeme> operands = new Stack<Lexeme>();
            // contains expression nodes
            Stack<Lexeme> ops = new Stack<Lexeme>();
            // contains open brackets ( and operators ^,*,/,+,-
            //boolean term = true; // indicates a term should come next, not an operator
            //boolean signed = false; // indicates if the current term has been signed
            //boolean negate = false; // indicates if the sign of the current term is negated
            bool inTermOrPostOp = false;
            //1. While there are still tokens to be read in
            for (int i = 0; i < lexemes.Count; i++)
            {
                //1.1 Get the next token.
                Expression contents;
                Operator currentOperator;
                Lexeme current = lexemes[i];
                switch (current.GetType())
                {
                    case Lexeme.NUMBER:
                    {
                        //1.2.1 A number: push it onto the value stack.
                        inTermOrPostOp = true;
                        operands.AddItem(current);
                        if (debuggging)
                        {
                            System.Console.Out.WriteLine("push term: " + current.GetValue());
                        }
                        terms.AddItem(new NumberNode(current.GetValue()));
                        break;
                    }

                    case Lexeme.WORD:
                    {
                        //1.2.2 A variable: get its value, and push onto the value stack.
                        //maybe variable, maybe function name?
                        operands.AddItem(current);
                        inTermOrPostOp = true;
                        terms.AddItem(new VariableNode(current.GetValue()));
                        if (debuggging)
                        {
                            System.Console.Out.WriteLine("push term: " + current.GetValue());
                        }
                        break;
                    }

                    case Lexeme.LPAREN:
                    {
                        //1.2.3 A left parenthesis: push it onto the operator stack.
                        inTermOrPostOp = false;
                        //is function
                        if (!operands.IsEmpty() && operands.Peek().GetType() == Lexeme.WORD)
                        {
                            Expression funcName = terms.Pop();
                            currentOperator = GetOperatorFromLexeme(operators, operands.Peek(), inTermOrPostOp
                                );
                            opStack.AddItem(currentOperator);
                            if (debuggging)
                            {
                                System.Console.Out.WriteLine("push: " + currentOperator.GetSymbol());
                            }
                        }
                        ops.AddItem(current);
                        currentOperator = GetOperatorFromLexeme(operators, current, inTermOrPostOp);
                        opStack.AddItem(currentOperator);
                        if (debuggging)
                        {
                            System.Console.Out.WriteLine("push: " + currentOperator.GetSymbol());
                        }
                        break;
                    }

                    case Lexeme.COMMA:
                    {
                        operands.AddItem(current);
                        while (!opStack.IsEmpty() && (!opStack.Peek().GetSymbol().Equals("(") && !opStack
                            .Peek().GetSymbol().Equals(",")))
                        {
                            Operator topOperator = opStack.Pop();
                            if (debuggging)
                            {
                                System.Console.Out.WriteLine("pop: " + topOperator.GetSymbol());
                            }
                            Expression[] children;
                            if (topOperator.IsBinary())
                            {
                                Expression operand1 = terms.Pop();
                                Expression operand2 = terms.Pop();
                                children = new Expression[] { operand2, operand1 };
                            }
                            else
                            {
                                //check assoc here
                                Expression operand = terms.Pop();
                                children = new Expression[] { operand };
                            }
                            terms.AddItem(new OpNode(children, topOperator));
                        }
                        inTermOrPostOp = false;
                        if (!opStack.IsEmpty())
                        {
                            opStack.Pop();
                        }
                        else
                        {
                            // remove '(' paren from stack;
                            throw new ExpressionParseException("Expression string cannot missing leading (" +
                                 current, i);
                        }
                        currentOperator = GetOperatorFromLexeme(operators, current, inTermOrPostOp);
                        opStack.AddItem(currentOperator);
                        //terms.add(terms.pop());
                        break;
                    }

                    case Lexeme.RPAREN:
                    {
                        //1.2.4 A right parenthesis:
                        operands.AddItem(current);
                        while (!opStack.IsEmpty() && (!opStack.Peek().GetSymbol().Equals("(") && !opStack
                            .Peek().GetSymbol().Equals(",")))
                        {
                            Operator topOperator = opStack.Pop();
                            if (debuggging)
                            {
                                System.Console.Out.WriteLine("pop: " + topOperator.GetSymbol());
                            }
                            Expression[] children;
                            if (topOperator.IsBinary())
                            {
                                Expression operand1 = terms.Pop();
                                Expression operand2 = terms.Pop();
                                children = new Expression[] { operand2, operand1 };
                            }
                            else
                            {
                                //check assoc here
                                Expression operand = terms.Pop();
                                children = new Expression[] { operand };
                            }
                            terms.AddItem(new OpNode(children, topOperator));
                        }
                        inTermOrPostOp = true;
                        //maybe check if paren?
                        if (!opStack.IsEmpty())
                        {
                            opStack.Pop();
                        }
                        else
                        {
                            // remove '(' paren from stack;
                            throw new ExpressionParseException("Expression string cannot missing leading (",
                                i);
                        }
                        if (!opStack.IsEmpty() && opStack.Peek().IsFunc())
                        {
                            AList<Expression> args = new AList<Expression>();
                            while (!terms.IsEmpty())
                            {
                                if (args.Count < opStack.Peek().GetOperandsSize())
                                {
                                    args.AddItem(terms.Pop());
                                }
                                else
                                {
                                    break;
                                }
                            }
                            //check if args.size()==opStack.peek().getOperandsSize()
                            Collections.Reverse(args);
                            terms.AddItem(new FuncNode(opStack.Peek().GetSymbol(), Sharpen.Collections.ToArray
                                (args, new Expression[args.Count]), opStack.Pop()));
                        }
                        else
                        {
                            contents = terms.Pop();
                            terms.AddItem(new ParensNode(new Expression[] { contents }));
                        }
                        break;
                    }

                    case Lexeme.OPERATOR:
                    {
                        Lexeme thisOp = current;
                        currentOperator = GetOperatorFromLexeme(operators, current, inTermOrPostOp);
                        inTermOrPostOp = false;
                        operands.AddItem(current);
                        //Operator topOp;
                        while (!opStack.IsEmpty() && opStack.Peek().GetPrecednce() >= currentOperator.GetPrecednce
                            ())
                        {
                            //Lexeme poppedOp = ops.pop();
                            Operator topOperator = opStack.Pop();
                            Expression[] children;
                            if (topOperator.IsBinary())
                            {
                                Expression operand1 = terms.Pop();
                                Expression operand2 = terms.Pop();
                                children = new Expression[] { operand2, operand1 };
                            }
                            else
                            {
                                //check assoc here
                                Expression operand = terms.Pop();
                                children = new Expression[] { operand };
                            }
                            terms.AddItem(new OpNode(children, topOperator));
                        }
                        //Apply the operator to the operands, in the correct order.
                        //4 Push the result onto the value stack.
                        //might have to go x->pop(), y->pop(); push(x) for right assoc unary
                        //ops.add(current);
                        opStack.AddItem(currentOperator);
                        break;
                    }

                    default:
                    {
                        throw new ExpressionParseException("Unknown token type", -1);
                    }
                }
            }
            //2. While the operator stack is not empty
            while (!opStack.IsEmpty())
            {
                Operator poppedOp = opStack.Pop();
                Expression[] children;
                if (poppedOp.IsBinary())
                {
                    Expression operand1 = terms.Pop();
                    Expression operand2 = terms.Pop();
                    children = new Expression[] { operand2, operand1 };
                }
                else
                {
                    //check assoc here
                    Expression operand = terms.Pop();
                    children = new Expression[] { operand };
                }
                terms.AddItem(new OpNode(children, poppedOp));
            }
            return terms.Peek();
        }
示例#54
0
 internal Cursor ResultSetWithOptions(QueryOptions options)
 {
     if (options == null)
     {
         options = new QueryOptions();
     }
     // OPT: It would be faster to use separate tables for raw-or ascii-collated views so that
     // they could be indexed with the right Collation, instead of having to specify it here.
     var collationStr = string.Empty;
     if (Collation == ViewCollation.ASCII)
     {
         collationStr += " COLLATE JSON_ASCII";
     }
     else
     {
         if (Collation == ViewCollation.Raw)
         {
             collationStr += " COLLATE JSON_RAW";
         }
     }
     var sql = "SELECT key, value, docid, revs.sequence";
     if (options.IsIncludeDocs())
     {
         sql = sql + ", revid, json";
     }
     sql = sql + " FROM maps, revs, docs WHERE maps.view_id=@";
     var argsList = new AList<string>();
     argsList.AddItem(Sharpen.Extensions.ToString(Id));
     if (options.GetKeys() != null)
     {
         sql += " AND key in (";
         var item = "@";
         foreach (object key in options.GetKeys())
         {
             sql += item;
             item = ", @";
             argsList.AddItem(ToJSONString(key));
         }
         sql += ")";
     }
     var minKey = options.GetStartKey();
     var maxKey = options.GetEndKey();
     var inclusiveMin = true;
     var inclusiveMax = options.IsInclusiveEnd();
     if (options.IsDescending())
     {
         minKey = maxKey;
         maxKey = options.GetStartKey();
         inclusiveMin = inclusiveMax;
         inclusiveMax = true;
     }
     if (minKey != null)
     {
         System.Diagnostics.Debug.Assert((minKey is string));
         sql += inclusiveMin ? " AND key >= @" : " AND key > @";
         sql += collationStr;
         argsList.AddItem(ToJSONString(minKey));
     }
     if (maxKey != null)
     {
         System.Diagnostics.Debug.Assert((maxKey is string));
         if (inclusiveMax)
         {
             sql += " AND key <= @";
         }
         else
         {
             sql += " AND key < @";
         }
         sql += collationStr;
         argsList.AddItem(ToJSONString(maxKey));
     }
     sql = sql + " AND revs.sequence = maps.sequence AND docs.doc_id = revs.doc_id ORDER BY key";
     sql += collationStr;
     if (options.IsDescending())
     {
         sql = sql + " DESC";
     }
     sql = sql + " LIMIT @ OFFSET @";
     argsList.AddItem(options.GetLimit().ToString());
     argsList.AddItem(options.GetSkip().ToString());
     Log.V(Database.Tag, "Query " + Name + ": " + sql);
     var cursor = Database.StorageEngine.RawQuery(sql, CommandBehavior.SequentialAccess, argsList.ToArray());
     return cursor;
 }
示例#55
0
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        internal IList<QueryRow> ReducedQuery(Cursor cursor, Boolean group, Int32 groupLevel)
        {
            IList<object> keysToReduce = null;
            IList<object> valuesToReduce = null;
            object lastKey = null;

            var reduce = Reduce;
            // FIXME: If reduce is null, then so are keysToReduce and ValuesToReduce, which can throw an NRE below.
            if (reduce != null)
            {
                keysToReduce = new AList<Object>(ReduceBatchSize);
                valuesToReduce = new AList<Object>(ReduceBatchSize);
            }

            var rows = new AList<QueryRow>();
            cursor.MoveToNext();

            while (!cursor.IsAfterLast())
            {
                var keyData = FromJSON(cursor.GetBlob(0));
                var value = FromJSON(cursor.GetBlob(1));
                System.Diagnostics.Debug.Assert((keyData != null));
                if (group && !GroupTogether(keyData, lastKey, groupLevel))
                {
                    if (lastKey != null)
                    {
                        // This pair starts a new group, so reduce & record the last one:
                        var reduced = (reduce != null) ? reduce(keysToReduce, valuesToReduce, false) : null;

                        var key = GroupKey(lastKey, groupLevel);
                        var row = new QueryRow(null, 0, key, reduced, null);
                        row.Database = Database;
                        rows.AddItem(row); // NOTE.ZJG: Change to `yield return row` to convert to a generator.

                        keysToReduce.Clear();
                        valuesToReduce.Clear();
                    }
                    lastKey = keyData;
                }
                keysToReduce.AddItem(keyData);
                valuesToReduce.AddItem(value);
                cursor.MoveToNext();
            }
            // NOTE.ZJG: Need to handle grouping differently if switching this to a generator.
            if (keysToReduce.Count > 0)
            {
                // Finish the last group (or the entire list, if no grouping):
                var key = group ? GroupKey(lastKey, groupLevel) : null;
                var reduced = (reduce != null) ? reduce(keysToReduce, valuesToReduce, false) : null;
                var row = new QueryRow(null, 0, key, reduced, null);
                row.Database = Database;
                rows.AddItem(row);
            }
            return rows;
        }
示例#56
0
        /// <summary>Queries the view.</summary>
        /// <remarks>Queries the view. Does NOT first update the index.</remarks>
        /// <param name="options">The options to use.</param>
        /// <returns>An array of QueryRow objects.</returns>
        /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
        internal IEnumerable<QueryRow> QueryWithOptions(QueryOptions options)
        {
            if (options == null)
                options = new QueryOptions();

            Cursor cursor = null;
            IList<QueryRow> rows = new AList<QueryRow>();
            try
            {
                cursor = ResultSetWithOptions(options);
                int groupLevel = options.GetGroupLevel();
                var group = options.IsGroup() || (groupLevel > 0);
                var reduce = options.IsReduce() || group;
                var reduceBlock = Reduce;

                if (reduce && (reduceBlock == null) && !group)
                {
                    var msg = "Cannot use reduce option in view " + Name + " which has no reduce block defined";
                    Log.W(Database.Tag, msg);
                    throw new CouchbaseLiteException(StatusCode.BadRequest);
                }

                if (reduce || group)
                {
                    // Reduced or grouped query:
                    rows = ReducedQuery(cursor, group, groupLevel);
                }
                else
                {
                    // regular query
                    cursor.MoveToNext();
                    while (!cursor.IsAfterLast())
                    {
                        var keyData = FromJSON(cursor.GetBlob(0));
                        // TODO: delay parsing this for increased efficiency
                        var value = FromJSON(cursor.GetBlob(1));
                        // TODO: ditto
                        var docId = cursor.GetString(2);
                        var sequenceLong = cursor.GetLong(3);
                        var sequence = Convert.ToInt32(sequenceLong);

                        IDictionary<string, object> docContents = null;
                        if (options.IsIncludeDocs())
                        {
                            // http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Linked_documents
                            if (value is IDictionary<string,object> && ((IDictionary<string,object>)value).ContainsKey("_id"))
                            {
                                string linkedDocId = (string)((IDictionary<string,object>)value).Get("_id");
                                RevisionInternal linkedDoc = Database.GetDocumentWithIDAndRev(linkedDocId, null, 
                                    EnumSet.NoneOf<TDContentOptions>());
                                docContents = linkedDoc.GetProperties();
                            }
                            else
                            {
                                var revId = cursor.GetString(4);
                                docContents = Database.DocumentPropertiesFromJSON(cursor.GetBlob(5), docId, revId, false, sequenceLong, options.GetContentOptions());
                            }
                        }
                        var row = new QueryRow(docId, sequence, keyData, value, docContents);
                        row.Database = Database;
                        rows.AddItem<QueryRow>(row);  // NOTE.ZJG: Change to `yield return row` to convert to a generator.
                        cursor.MoveToNext();
                    }
                }
            }
            catch (SQLException e)
            {
                var errMsg = string.Format("Error querying view: {0}", this);
                Log.E(Database.Tag, errMsg, e);
                throw new CouchbaseLiteException(errMsg, e, new Status(StatusCode.DbError));
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Close();
                }
            }
            return rows;
        }
示例#57
0
		/// <exception cref="System.IO.IOException"></exception>
		private void ResolveDeltasWithExternalBases(ProgressMonitor progress)
		{
			GrowEntries(baseById.Size());
			if (needBaseObjectIds)
			{
				baseObjectIds = new ObjectIdSubclassMap<ObjectId>();
			}
			IList<PackParser.DeltaChain> missing = new AList<PackParser.DeltaChain>(64);
			foreach (PackParser.DeltaChain baseId in baseById)
			{
				if (baseId.head == null)
				{
					continue;
				}
				if (needBaseObjectIds)
				{
					baseObjectIds.Add(baseId);
				}
				ObjectLoader ldr;
				try
				{
					ldr = readCurs.Open(baseId);
				}
				catch (MissingObjectException)
				{
					missing.AddItem(baseId);
					continue;
				}
				PackParser.DeltaVisit visit = new PackParser.DeltaVisit();
				visit.data = ldr.GetCachedBytes(int.MaxValue);
				visit.id = baseId;
				int typeCode = ldr.GetType();
				PackedObjectInfo oe = NewInfo(baseId, null, null);
				if (OnAppendBase(typeCode, visit.data, oe))
				{
					entries[entryCount++] = oe;
				}
				visit.nextChild = FirstChildOf(oe);
				ResolveDeltas(visit.Next(), typeCode, new PackParser.ObjectTypeAndSize(), progress
					);
				if (progress.IsCancelled())
				{
					throw new IOException(JGitText.Get().downloadCancelledDuringIndexing);
				}
			}
			foreach (PackParser.DeltaChain @base in missing)
			{
				if (@base.head != null)
				{
					throw new MissingObjectException(@base, "delta base");
				}
			}
			OnEndThinPack();
		}
示例#58
0
 /// <summary>
 /// Find commits that are reachable from <code>start</code> until a commit
 /// that is reachable from <code>end</code> is encountered.
 /// </summary>
 /// <remarks>
 /// Find commits that are reachable from <code>start</code> until a commit
 /// that is reachable from <code>end</code> is encountered. In other words,
 /// Find of commits that are in <code>start</code>, but not in
 /// <code>end</code>.
 /// <p>
 /// Note that this method calls
 /// <see cref="RevWalk.Reset()">RevWalk.Reset()</see>
 /// at the beginning.
 /// Also note that the existing rev filter on the walk is left as-is, so be
 /// sure to set the right rev filter before calling this method.
 /// </remarks>
 /// <param name="walk">the rev walk to use</param>
 /// <param name="start">the commit to start counting from</param>
 /// <param name="end">
 /// the commit where counting should end, or null if counting
 /// should be done until there are no more commits
 /// </param>
 /// <returns>the commits found</returns>
 /// <exception cref="NGit.Errors.MissingObjectException">NGit.Errors.MissingObjectException
 /// 	</exception>
 /// <exception cref="NGit.Errors.IncorrectObjectTypeException">NGit.Errors.IncorrectObjectTypeException
 /// 	</exception>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 public static IList<RevCommit> Find(RevWalk walk, RevCommit start, RevCommit end)
 {
     walk.Reset();
     walk.MarkStart(start);
     if (end != null)
     {
         walk.MarkUninteresting(end);
     }
     IList<RevCommit> commits = new AList<RevCommit>();
     foreach (RevCommit c in walk)
     {
         commits.AddItem(c);
     }
     return commits;
 }
示例#59
0
		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);
		}
        public static AList<Lexeme> Lexify(string s)
        {
            int position = 0;
            string[] tokens = GetAllMatches(s);
            foreach (string token in tokens)
            {
                System.Console.Out.WriteLine(token);
            }
            AList<Lexeme> tokBuf = new AList<Lexeme>();
            //try {
            foreach (string token_1 in tokens)
            {
                position += token_1.Length;
                Lexer.TokenType type = Lexer.TokenType.UNSET;
                if (token_1.Matches("^[0-9]+$"))
                {
                    type = Lexer.TokenType.INT;
                }
                else
                {
                    if (token_1.Matches("^[0-9]*\\.[0-9]+$"))
                    {
                        type = Lexer.TokenType.DECIMAL;
                    }
                    else
                    {
                        if (token_1.Matches("^([a-zA-Z]+)$"))
                        {
                            type = Lexer.TokenType.WORD;
                        }
                        else
                        {
                            if (token_1.Matches("^([^\\w\\s])$"))
                            {
                                type = Lexer.TokenType.OPERATOR;
                            }
                        }
                    }
                }
                switch (type)
                {
                    case Lexer.TokenType.INT:
                    {
                        // int
                        tokBuf.AddItem(new Lexeme(Lexeme.NUMBER, token_1));
                        break;
                    }

                    case Lexer.TokenType.DECIMAL:
                    {
                        // double
                        tokBuf.AddItem(new Lexeme(Lexeme.NUMBER, token_1));
                        break;
                    }

                    case Lexer.TokenType.WORD:
                    {
                        tokBuf.AddItem(new Lexeme(Lexeme.WORD, token_1));
                        break;
                    }

                    case Lexer.TokenType.OPERATOR:
                    {
                        // operator
                        if (token_1.Equals("("))
                        {
                            tokBuf.AddItem(new Lexeme(Lexeme.LPAREN, token_1));
                        }
                        else
                        {
                            if (token_1.Equals(")"))
                            {
                                tokBuf.AddItem(new Lexeme(Lexeme.RPAREN, token_1));
                            }
                            else
                            {
                                if (token_1.Equals(","))
                                {
                                    tokBuf.AddItem(new Lexeme(Lexeme.COMMA, token_1));
                                }
                                else
                                {
                                    tokBuf.AddItem(new Lexeme(Lexeme.OPERATOR, token_1));
                                }
                            }
                        }
                        break;
                    }
                }
            }
            return tokBuf;
        }