private List <JiraIssue> createIssueList(Stream s) { XPathDocument doc = XPathUtils.getXmlDocument(s); XPathNavigator nav = doc.CreateNavigator(); XPathExpression localeExpr = nav.Compile("/rss/channel/language"); XPathNodeIterator localeIt = nav.Select(localeExpr); string locale = null; if (localeIt.MoveNext()) { locale = localeIt.Current.Value; } XPathExpression expr = nav.Compile("/rss/channel/item"); XPathNodeIterator it = nav.Select(expr); List <JiraIssue> list = new List <JiraIssue>(); while (it.MoveNext()) { list.Add(new JiraIssue(server, locale, it.Current)); } return(list); }
private List <EmployeeDto> ParseEmployeePageContent(HtmlDocument htmlDoc, string urlBase) { var employees = new List <EmployeeDto>(); var employeeBioElements = htmlDoc.DocumentNode.SelectNodes($"//div[{XPathUtils.GetContainsClassExpression("employee-bio-item")}]"); foreach (var employeeBioElement in employeeBioElements) { var employee = new EmployeeDto(); var bioNameHeader = employeeBioElement.SelectSingleNode($"h2[{XPathUtils.GetContainsClassExpression("employee-bio-name")}]"); if (bioNameHeader != null) { employee.Name = bioNameHeader.FirstChild.InnerHtml; } var bioImageNormal = employeeBioElement.SelectSingleNode($"a/img[{XPathUtils.GetContainsClassExpression("employee-bio-default-image")}]"); if (bioImageNormal != null) { employee.NormalImageUrl = urlBase + bioImageNormal.GetAttributeValue("src", string.Empty); } var bioImageFun = employeeBioElement.SelectSingleNode($"a/img[{XPathUtils.GetContainsClassExpression("employee-bio-alternate-image")}]"); if (bioImageFun != null) { employee.FunImageUrl = urlBase + bioImageFun.GetAttributeValue("src", string.Empty); } employees.Add(employee); } return(employees); }
/// <summary> /// Checks the container is valid. /// </summary> /// <param name="containerDoc">Signed container.</param> /// <exception cref="ArgumentException">Thrown when the container is not valid. /// </exception> private void CheckSignedContainer(XmlDocument containerDoc) { // Check the document is a signed container if (!XmlUtils.CheckElement(containerDoc.DocumentElement, SignedPayloadElement, this.signedPayloadXmlNs)) { throw new ArgumentException("Document is not a signed container"); } XmlNamespaceManager namespaceManager = CreateXmlNamespaceManager(containerDoc); // Check the container has signatures IList <XmlElement> signatureElems = XPathUtils.GetElements(containerDoc, "/sp:signedPayload/sp:signatures/ds:Signature", namespaceManager); if (signatureElems.Count == 0) { throw new XspException("No signatures were found in the signed container"); } // Check the container contains data if (XPathUtils.GetElement(containerDoc, "/sp:signedPayload/sp:signedPayloadData", namespaceManager) == null) { throw new XspException("No data section within the container"); } }
// achtung - gobble all exceptions public int getServerBuildNumber() { string endpoint = server.Url + INFO; try { using (Stream stream = getQueryResultStream(endpoint + getBasicAuthParameter(endpoint), true)) { XPathDocument doc = XPathUtils.getXmlDocument(stream); string code = getRestErrorStatusCode(doc); if (code != null) { return(0); } XPathNavigator nav = doc.CreateNavigator(); XPathExpression expr = nav.Compile("/info/buildNumber"); XPathNodeIterator it = nav.Select(expr); if (it.MoveNext()) { serverBuildNumber = it.Current.ValueAsInt; } } } catch (Exception e) { Debug.WriteLine("RestSession.getServerBuildNumber() - exception (ignored): " + e.Message); } return(serverBuildNumber); }
/// <inheritdoc/> public TControlObject SelectPerIndex(ControlSelectionContext context, int index) { ArgumentUtility.CheckNotNull("context", context); var hasAttributeCheck = XPathUtils.CreateHasAttributeCheck(DiagnosticMetadataAttributes.ControlType, _controlType); var scope = context.Scope.FindXPath(string.Format("(.//*{0})[{1}]", hasAttributeCheck, index)); return(CreateControlObject(context, scope)); }
/// <inheritdoc/> public TextBoxControlObject SelectPerIndex(ControlSelectionContext context, int index) { ArgumentUtility.CheckNotNull("context", context); var hasAttributeCheck = XPathUtils.CreateHasAttributeCheck("type", "text"); var xPathSelector = string.Format("(.//{0}{1})[{2}]", c_htmlTextBoxTag, hasAttributeCheck, index); var scope = context.Scope.FindXPath(xPathSelector); return(CreateControlObject(context, scope)); }
/// <inheritdoc/> UnspecifiedPageObject IFluentControlObjectWithTabs.WithIndex(int index, IWebTestActionOptions actionOptions) { var xPathSelector = string.Format( "(.//span{0})[{1}]", XPathUtils.CreateHasOneOfClassesCheck("tabStripTab", "tabStripTabSelected"), index); var itemScope = Scope.FindXPath(xPathSelector); return(SwitchTo(itemScope, actionOptions)); }
public ICollection <BuildArtifact> getArtifacts(string buildKey) { string buildUrl = string.Format(getCorrectEnpointOrXPath(ALL_ARTIFACTS, ALL_ARTIFACTS_3_0), buildKey); string endpoint = server.Url + buildUrl; using (Stream stream = getQueryResultStream(endpoint + getBasicAuthParameter(endpoint), true)) { XPathDocument doc = XPathUtils.getXmlDocument(stream); string code = getRestErrorStatusCode(doc); if (code != null) { throw new Exception(code); } XPathNavigator nav = doc.CreateNavigator(); List <BuildArtifact> artifacts = new List <BuildArtifact>(); XPathExpression expr = nav.Compile("/build/artifacts/artifact"); XPathNodeIterator it = nav.Select(expr); if (it.MoveNext()) { artifacts.Add(getArtifact(null, it.Current)); } expr = nav.Compile("/result/artifacts/artifact"); it = nav.Select(expr); if (it.MoveNext()) { artifacts.Add(getArtifact(null, it.Current)); } expr = nav.Compile("/result/stages/stage/results/result"); it = nav.Select(expr); while (it.MoveNext()) { string resultKey = XPathUtils.getAttributeSafely(it.Current, "key", null); XPathNodeIterator it2 = it.Clone(); XPathExpression expr3 = it2.Current.Compile("artifacts/artifact"); XPathNodeIterator it3 = it2.Current.Select(expr3); while (it3.MoveNext()) { artifacts.Add(getArtifact(resultKey, it3.Current)); } } return(artifacts); } }
/// <summary> /// Gets a list of digest values. /// </summary> /// <param name="containerDoc">Signed container.</param> /// <returns>List of digest values.</returns> public IList <byte[]> GetDigestValues(XmlDocument containerDoc) { ArgumentUtils.CheckNotNull(containerDoc, "containerDoc"); // Check the document is a signed container if (!XmlUtils.CheckElement(containerDoc.DocumentElement, SignedPayloadElement, this.signedPayloadXmlNs)) { throw new ArgumentException("Document is not a signed container"); } // Create the namespace manager for executing XPath statements XmlNamespaceManager namespaceManager = CreateXmlNamespaceManager( containerDoc); // Get the list of signature elements IList <XmlElement> signatureElems = XPathUtils.GetElements(containerDoc, "/sp:signedPayload/sp:signatures/ds:Signature", namespaceManager); if (signatureElems.Count == 0) { throw new XspException("No 'ds:Signature' elements were found within the " + "'sp:signatures' element"); } // Iterate through each signature to get the digest IList <byte[]> digestList = new List <byte[]>(); foreach (XmlElement signatureElem in signatureElems) { // Extract the digest from the signature IDictionary <string, byte[]> digestValues = this.signedProfileService.GetDigestValues(signatureElem); if (digestValues.Keys.Count == 0) { throw new XspException("Signature contains no refences"); } if (digestValues.Keys.Count > 1) { throw new XspException("Signature contains more than one reference"); } // Get the first value from the values list as there is only one IEnumerator <byte[]> digestEnumerator = digestValues.Values.GetEnumerator(); digestEnumerator.MoveNext(); digestList.Add(digestEnumerator.Current); } return(digestList); }
/// <summary> /// Decrypts an encrypted container Xml element, returning the payload. /// </summary> /// <param name="encryptedPayloadElem">Encrypted container to decrypt.</param> /// <param name="certificate">Certificate to decrypt with.</param> /// <returns>Decrypted payload.</returns> /// <exception cref="XspException">Thrown on error.</exception> public XmlDocument GetData(XmlElement encryptedPayloadElem, X509Certificate2 certificate) { ArgumentUtils.CheckNotNull(encryptedPayloadElem, "encryptedPayloadElem"); ArgumentUtils.CheckNotNull(certificate, "certificate"); // Check the root element belongs to the right namespace if (!XmlUtils.CheckElement(encryptedPayloadElem, EncryptedPayloadElement, this.encryptedPayloadXmlNs)) { throw new ArgumentException("Document is not an encrypted container"); } // Clone the source element so it is not modified XmlElement clonePayloadElem = XmlUtils.Clone(encryptedPayloadElem); // Create a namespace manager for XPath XmlNamespaceManager namespaceManager = CreateXmlNamespaceManager( clonePayloadElem.OwnerDocument); // Get the 'xenc:EncryptedData' element XmlElement encryptedDataElem = XPathUtils.GetElement(clonePayloadElem, "/ep:encryptedPayload/ep:encryptedPayloadData/xenc:EncryptedData", namespaceManager); if (encryptedDataElem == null) { throw new XspException("Encrypted data was not found within the container"); } // Get the 'xenc:EncryptedKey' element list IList <XmlElement> keyElems = XPathUtils.GetElements(clonePayloadElem, "/ep:encryptedPayload/ep:keys/xenc:EncryptedKey", namespaceManager); if (keyElems.Count == 0) { throw new XspException("No encrypted keys found within the container"); } // Decrypt the data this.encryptedProfileService.Decrypt(keyElems, encryptedDataElem, certificate); // Get the payload element XmlElement payloadElem = XPathUtils.GetElement(clonePayloadElem, "/ep:encryptedPayload/ep:encryptedPayloadData/*[1]", namespaceManager); // Return the payload element within a new Xml document return(XmlUtils.CreateXmlDocument(payloadElem)); }
private BambooBuild.PlanState getPlanStateForBuild(string buildKey) { BambooBuild.PlanState state; string endpoint = server.Url + string.Format(PLAN_DETAILS, BambooBuildUtils.getPlanKey(buildKey)); using (Stream stream = getQueryResultStream(endpoint + getBasicAuthParameter(endpoint), true)) { XPathDocument doc = XPathUtils.getXmlDocument(stream); string code = getRestErrorStatusCode(doc); if (code != null) { throw new Exception(code); } XPathNavigator nav = doc.CreateNavigator(); XPathExpression expr = nav.Compile("/plan/isInBuildQueue"); XPathNodeIterator it = nav.Select(expr); string inQueue = "false"; string isBuilding = "false"; if (it.Count > 0) { it.MoveNext(); inQueue = it.Current.Value; } expr = nav.Compile("/plan/isBuilding"); it = nav.Select(expr); if (it.Count > 0) { it.MoveNext(); isBuilding = it.Current.Value; } if (inQueue.Equals("true")) { state = BambooBuild.PlanState.IN_QUEUE; } else if (isBuilding.Equals("true")) { state = BambooBuild.PlanState.BUILDING; } else { state = BambooBuild.PlanState.IDLE; } } return(state); }
public RestSession login(string username, string pwd) { #if OLDSKOOL_AUTH string endpoint = server.Url + LOGIN_ACTION + "?username="******"&password="******"&os_username="******"&os_password="******"/response/auth"); XPathNodeIterator it = nav.Select(expr); if (it.Count == 0) { throw new Exception("Server did not return any authentication token"); } if (it.Count != 1) { throw new Exception("Server returned unexpected number of authentication tokens (" + it.Count + ")"); } it.MoveNext(); authToken = it.Current.Value; getServerBuildNumber(); LoggedIn = true; return(this); } }
public void addLabel(string planKey, int buildNumber, string label) { string endpoint = server.Url + ADD_LABEL_ACTION + "?auth=" + HttpUtility.UrlEncode(authToken, Encoding.UTF8) + "&buildKey=" + HttpUtility.UrlEncode(planKey) + "&buildNumber=" + buildNumber + "&label=" + HttpUtility.UrlEncode(label); using (Stream stream = getQueryResultStream(endpoint, false)) { XPathDocument doc = XPathUtils.getXmlDocument(stream); string code = getRemoteExceptionMessages(doc); if (code != null) { throw new Exception(code); } } }
/// <summary> /// Checks the signatures in a signed payload container and also verifies the /// certificates with the certificate verifier callback. /// </summary> /// <param name="containerDoc">Signed payload container.</param> /// <param name="certificateVerifier">Certificate verifier.</param> /// <exception cref="XspException">Thrown on error.</exception> public void Check(XmlDocument containerDoc, ICertificateVerifier certificateVerifier) { ArgumentUtils.CheckNotNull(containerDoc, "containerDoc"); ArgumentUtils.CheckNotNull(certificateVerifier, "certificateVerifier"); // Check the container is valid CheckSignedContainer(containerDoc); // Get all the signatures in the container IList <XmlElement> signatureElems = XPathUtils.GetElements(containerDoc, "/sp:signedPayload/sp:signatures/ds:Signature", CreateXmlNamespaceManager(containerDoc)); // Check all the signatures verify this.signedProfileService.Check(signatureElems, certificateVerifier); }
/// <inheritdoc/> public FormGridControlObject SelectPerTitle(ControlSelectionContext context, string title) { ArgumentUtility.CheckNotNull("context", context); ArgumentUtility.CheckNotNull("title", title); // Todo RM-6337: Replace with CSS-based search as soon as FormGridManager is able to render the data-title attribute. // Note: it is not that easy, as we do not know the content of the title row on the server...FormGrid is just a design transformator... //var scope = context.Scope.FindCss (string.Format ("table[{0}='{1}']", DiagnosticMetadataAttributes.FormGridTitle, title)); // Note: this implementation assumes that the title cell has the CSS class formGridTitleCell. var hasClassCheck = XPathUtils.CreateHasClassCheck("formGridTitleCell"); var scope = context.Scope.FindXPath(string.Format(".//table[tbody/tr/td{0}='{1}']", hasClassCheck, title)); // This alterantive implementation assumes that the title cell is the very first row and column. // var scope = context.Scope.FindXPath (string.Format (".//table[tbody/tr[1]/td[1]='{0}']", title)); return(CreateControlObject(context, scope)); }
private static List <JiraNamedEntity> getLinks(XPathNavigator nav) { XPathExpression expr = nav.Compile("issuelink/issuekey"); XPathNodeIterator it = nav.Select(expr); List <JiraNamedEntity> result = new List <JiraNamedEntity>(); if (nav.MoveToFirstChild()) { while (it.MoveNext()) { int id = XPathUtils.getAttributeSafely(it.Current, "id", 0); string key = it.Current.Value; result.Add(new JiraNamedEntity(id, key, null)); } nav.MoveToParent(); } return(result); }
/// <summary> /// Decrypts an encrypted container document returning the payload. /// </summary> /// <param name="encryptedPayloadDoc">Encrypted container to decrypt.</param> /// <param name="cipherKey">The cipher key to use to decrypt the document.</param> /// <returns>Decrypted payload.</returns> /// <exception cref="XspException">Thrown on error.</exception> public XmlDocument GetData(XmlDocument encryptedPayloadDoc, byte[] cipherKey) { ArgumentUtils.CheckNotNull(encryptedPayloadDoc, "encryptedPayloadDoc"); ArgumentUtils.CheckNotNull(cipherKey, "cipherKey"); XmlElement docElement = encryptedPayloadDoc.DocumentElement; // Check the root element belongs to the right namespace if (!XmlUtils.CheckElement(docElement, EncryptedPayloadElement, this.encryptedPayloadXmlNs)) { throw new ArgumentException("Document is not an encrypted container"); } // Clone the source element so it is not modified XmlElement clonePayloadElem = XmlUtils.Clone(docElement); // Create a namespace manager for XPath XmlNamespaceManager namespaceManager = CreateXmlNamespaceManager( clonePayloadElem.OwnerDocument); // Get the 'xenc:EncryptedData' element XmlElement encryptedDataElem = XPathUtils.GetElement(clonePayloadElem, "/ep:encryptedPayload/ep:encryptedPayloadData/xenc:EncryptedData", namespaceManager); if (encryptedDataElem == null) { throw new XspException("Encrypted data was not found within the container"); } // Decrypt the element with the cipher key this.encryptedProfileService.Decrypt(encryptedDataElem, cipherKey); // Get the payload element XmlElement payloadElem = XPathUtils.GetElement(clonePayloadElem, "/ep:encryptedPayload/ep:encryptedPayloadData/*[1]", namespaceManager); // Return the payload element within a new Xml document return(XmlUtils.CreateXmlDocument(payloadElem)); }
/// <summary> /// Extracts the payload from the signed payload container. /// </summary> /// <param name="containerDoc">Signed payload container.</param> /// <returns>Payload.</returns> /// <exception cref="XspException">Thrown on error.</exception> public XmlDocument GetData(XmlDocument containerDoc) { ArgumentUtils.CheckNotNull(containerDoc, "containerDoc"); // Check the document is a signed container if (!XmlUtils.CheckElement(containerDoc.DocumentElement, SignedPayloadElement, this.signedPayloadXmlNs)) { throw new ArgumentException("Document is not a signed container"); } // Create an Xml namespace manager for XPathing XmlNamespaceManager namespaceManager = CreateXmlNamespaceManager( containerDoc); // Get the data from the container XmlElement payloadDataElem = XPathUtils.GetElement(containerDoc, "/sp:signedPayload/sp:signedPayloadData/*[1]", namespaceManager); return(XmlUtils.CreateXmlDocument(payloadDataElem)); }
private IEnumerable <BambooTest> getTestsForJob(string job, string number) { string endpoint = server.Url + string.Format(ALL_TESTS_3_0, job, number); using (Stream stream = getQueryResultStream(endpoint + getBasicAuthParameter(endpoint), true)) { XPathDocument doc = XPathUtils.getXmlDocument(stream); string code = getRestErrorStatusCode(doc); if (code != null) { throw new Exception(code); } XPathNavigator nav = doc.CreateNavigator(); XPathExpression expr = nav.Compile("/result/testResults/allTests/testResult"); XPathNodeIterator it = nav.Select(expr); return(retrieveTestsFromXPath(it)); } }
private void getComments(XPathNavigator nav) { XPathExpression expr = nav.Compile("comment"); XPathNodeIterator it = nav.Select(expr); if (!nav.MoveToFirstChild()) { return; } while (it.MoveNext()) { Comment c = new Comment { Body = it.Current.Value, Author = XPathUtils.getAttributeSafely(it.Current, "author", "Unknown"), Created = XPathUtils.getAttributeSafely(it.Current, "created", "Unknown") }; comments.Add(c); } nav.MoveToParent(); }
private void getAttachments(XPathNavigator nav) { XPathExpression expr = nav.Compile("attachment"); XPathNodeIterator it = nav.Select(expr); if (!nav.MoveToFirstChild()) { return; } while (it.MoveNext()) { JiraAttachment a = new JiraAttachment( int.Parse(XPathUtils.getAttributeSafely(it.Current, "id", "0")), XPathUtils.getAttributeSafely(it.Current, "name", "none"), JiraIssueUtils.getDateTimeFromJiraTimeString(ServerLanguage, XPathUtils.getAttributeSafely(it.Current, "created", "none")), XPathUtils.getAttributeSafely(it.Current, "author", "none"), int.Parse(XPathUtils.getAttributeSafely(it.Current, "size", "0"))); attachments.Add(a); } nav.MoveToParent(); }
/// <summary> /// Returns a list of certificates from the signed container. /// </summary> /// <param name="containerDoc">Signed container.</param> /// <returns>List of certificates.</returns> public IList <X509Certificate2> GetSigningCertificates(XmlDocument containerDoc) { ArgumentUtils.CheckNotNull(containerDoc, "containerDoc"); // Check the document is a signed container if (!XmlUtils.CheckElement(containerDoc.DocumentElement, SignedPayloadElement, this.signedPayloadXmlNs)) { throw new ArgumentException("Document is not a signed container"); } // Create the namespace manager for executing XPath statements XmlNamespaceManager namespaceManager = CreateXmlNamespaceManager( containerDoc); // Get the list of signature elements IList <XmlElement> signatureElems = XPathUtils.GetElements(containerDoc, "/sp:signedPayload/sp:signatures/ds:Signature", namespaceManager); if (signatureElems.Count == 0) { throw new XspException("No 'ds:Signature' elements were found " + "within the 'sp:signatures' element"); } IList <X509Certificate2> certs = new List <X509Certificate2>(); foreach (XmlElement signatureElem in signatureElems) { // Add each certificate X509Certificate2 cert = this.signedProfileService.GetSigningCertificate(signatureElem); certs.Add(cert); } return(certs); }
private ICollection <BambooPlan> getPlansFromUrlWithStartIndex(string endpoint, int start) { using (Stream stream = getQueryResultStream(endpoint + getBasicAuthParameter(endpoint) + "&start-index=" + start, true)) { XPathDocument doc = XPathUtils.getXmlDocument(stream); string code = getRestErrorStatusCode(doc); if (code != null) { throw new Exception(code); } XPathNavigator nav = doc.CreateNavigator(); XPathExpression expr = nav.Compile("/plans/plans"); XPathNodeIterator it = nav.Select(expr); int totalPlansCount = 0; int maxResult = 0; int startIndex = 0; if (it.MoveNext()) { totalPlansCount = int.Parse(XPathUtils.getAttributeSafely(it.Current, "size", "0")); maxResult = int.Parse(XPathUtils.getAttributeSafely(it.Current, "max-result", "0")); startIndex = int.Parse(XPathUtils.getAttributeSafely(it.Current, "start-index", "0")); } expr = nav.Compile("/plans/plans/plan"); it = nav.Select(expr); List <BambooPlan> plans = new List <BambooPlan>(); while (it.MoveNext()) { string enabledValue = XPathUtils.getAttributeSafely(it.Current, "enabled", "true"); string key = XPathUtils.getAttributeSafely(it.Current, "key", null); string name = XPathUtils.getAttributeSafely(it.Current, "name", null); bool enabled = true; if (enabledValue != null) { enabled = Boolean.Parse(enabledValue); } it.Current.MoveToFirstChild(); bool favourite = false; do { switch (it.Current.Name) { case "isFavourite": favourite = it.Current.Value.Equals("true"); break; } } while (it.Current.MoveToNext()); if (key == null || name == null) { continue; } BambooPlan plan = new BambooPlan(key, name, enabled, favourite); plans.Add(plan); } // Yes, recursion here. I hope it works as I think it should. If not, we are all doomed if (totalPlansCount > maxResult + startIndex) { plans.AddRange(getPlansFromUrlWithStartIndex(endpoint, startIndex + maxResult)); } return(plans); } }
private void getIssueLinks(XPathNavigator nav) { XPathExpression expr = nav.Compile("issuelinktype"); XPathNodeIterator it = nav.Select(expr); if (!nav.MoveToFirstChild()) { return; } while (it.MoveNext()) { int id = XPathUtils.getAttributeSafely(it.Current, "id", 0); string linkTypeName = null; string outwardLinksName = null; string inwardLinksName = null; List <JiraNamedEntity> outwardIdsAndKeys = null; List <JiraNamedEntity> inwardIdsAndKeys = null; if (it.Current.MoveToFirstChild()) { do { switch (it.Current.Name) { case "name": linkTypeName = it.Current.Value; break; case "outwardlinks": outwardLinksName = XPathUtils.getAttributeSafely(it.Current, "description", null); outwardIdsAndKeys = getLinks(it.Current); break; case "inwardlinks": inwardLinksName = XPathUtils.getAttributeSafely(it.Current, "description", null); inwardIdsAndKeys = getLinks(it.Current); break; } } while (it.Current.MoveToNext()); if (id == 0 || linkTypeName == null) { continue; } IssueLinkType ilt = new IssueLinkType(id, linkTypeName, outwardLinksName, inwardLinksName); if (outwardIdsAndKeys != null) { foreach (JiraNamedEntity entity in outwardIdsAndKeys) { ilt.OutwardLinks.Add(entity.Name); } } if (inwardIdsAndKeys != null) { foreach (JiraNamedEntity entity in inwardIdsAndKeys) { ilt.InwardLinks.Add(entity.Name); } } issueLinks.Add(ilt); } it.Current.MoveToParent(); } nav.MoveToParent(); }
public JiraIssue(JiraServer server, string serverLanguage, XPathNavigator nav) { Server = server; ServerLanguage = serverLanguage; nav.MoveToFirstChild(); do { switch (nav.Name) { case "key": Key = nav.Value; Id = XPathUtils.getAttributeSafely(nav, "id", UNKNOWN); ProjectKey = Key.Substring(0, Key.LastIndexOf('-')); break; case "parent": ParentKey = nav.Value; break; case "subtasks": getSubtasks(nav); break; case "summary": Summary = nav.Value; break; case "attachments": getAttachments(nav); break; case "status": Status = nav.Value; StatusIconUrl = XPathUtils.getAttributeSafely(nav, "iconUrl", null); StatusId = XPathUtils.getAttributeSafely(nav, "id", UNKNOWN); break; case "priority": Priority = nav.Value; PriorityIconUrl = XPathUtils.getAttributeSafely(nav, "iconUrl", null); PriorityId = XPathUtils.getAttributeSafely(nav, "id", UNKNOWN); break; case "description": Description = nav.Value; break; case "type": IssueType = nav.Value; IssueTypeIconUrl = XPathUtils.getAttributeSafely(nav, "iconUrl", null); IssueTypeId = XPathUtils.getAttributeSafely(nav, "id", UNKNOWN); break; case "assignee": Assignee = XPathUtils.getAttributeSafely(nav, "username", "Unknown"); string assigneName = nav.Value; JiraServerCache.Instance.getUsers(server).putUser(new JiraUser(Assignee, assigneName)); break; case "reporter": Reporter = XPathUtils.getAttributeSafely(nav, "username", "Unknown"); string reporterName = nav.Value; JiraServerCache.Instance.getUsers(server).putUser(new JiraUser(Reporter, reporterName)); break; case "created": CreationDate = JiraIssueUtils.getDateTimeFromJiraTimeString(serverLanguage, nav.Value); break; case "updated": UpdateDate = JiraIssueUtils.getDateTimeFromJiraTimeString(serverLanguage, nav.Value); break; case "resolution": Resolution = nav.Value; ResolutionId = XPathUtils.getAttributeSafely(nav, "id", UNKNOWN); break; case "timeestimate": RemainingEstimate = nav.Value; RemainingEstimateInSeconds = XPathUtils.getAttributeSafely(nav, "seconds", UNKNOWN); break; case "timeoriginalestimate": OriginalEstimate = nav.Value; OriginalEstimateInSeconds = XPathUtils.getAttributeSafely(nav, "seconds", UNKNOWN); break; case "timespent": TimeSpent = nav.Value; TimeSpentInSeconds = XPathUtils.getAttributeSafely(nav, "seconds", UNKNOWN); break; case "version": versions.Add(nav.Value); break; case "fixVersion": fixVersions.Add(nav.Value); break; case "component": components.Add(nav.Value); break; case "comments": getComments(nav); break; case "environment": Environment = nav.Value; break; case "issuelinks": getIssueLinks(nav); break; default: break; } } while (nav.MoveToNext()); if (Key == null || Summary == null) { throw new InvalidDataException(); } }
private ICollection <BambooBuild> getBuildsFromUrlWithStartIndex(string endpoint, int start, bool getPlanState, bool withRecursion, string prefix) { using (Stream stream = getQueryResultStream(endpoint + getBasicAuthParameter(endpoint) + (withRecursion ? "&start-index=" + start : ""), true)) { XPathDocument doc = XPathUtils.getXmlDocument(stream); string code = getRestErrorStatusCode(doc); if (code != null) { throw new Exception(code); } XPathNavigator nav = doc.CreateNavigator(); XPathExpression expr; XPathNodeIterator it; int totalBuildsCount = 0; int maxResult = 0; int startIndex = 0; if (!string.IsNullOrEmpty(prefix)) { expr = nav.Compile(prefix); it = nav.Select(expr); if (it.MoveNext()) { totalBuildsCount = int.Parse(XPathUtils.getAttributeSafely(it.Current, "size", "0")); maxResult = int.Parse(XPathUtils.getAttributeSafely(it.Current, "max-result", "0")); startIndex = int.Parse(XPathUtils.getAttributeSafely(it.Current, "start-index", "0")); } } expr = nav.Compile(prefix + "/build"); it = nav.Select(expr); if (it.Count == 0) { expr = nav.Compile(prefix + "/result"); it = nav.Select(expr); } List <BambooBuild> builds = new List <BambooBuild>(); while (it.MoveNext()) { int number = int.Parse(XPathUtils.getAttributeSafely(it.Current, "number", "-1")); string key = XPathUtils.getAttributeSafely(it.Current, "key", null); string state = XPathUtils.getAttributeSafely(it.Current, "state", null); it.Current.MoveToFirstChild(); string buildRelativeTime = null; string buildDurationDescription = null; string masterKey = null; int successfulTestCount = 0; int failedTestCount = 0; string projectName = null; string buildReason = null; List <BambooBuild.RelatedIssue> relatedIssues = new List <BambooBuild.RelatedIssue>(); do { switch (it.Current.Name) { case "master": masterKey = XPathUtils.getAttributeSafely(it.Current, "key", null); break; case "projectName": projectName = it.Current.Value; break; case "buildRelativeTime": buildRelativeTime = it.Current.Value; break; case "buildDurationDescription": buildDurationDescription = it.Current.Value; break; case "successfulTestCount": successfulTestCount = int.Parse(it.Current.Value); break; case "failedTestCount": failedTestCount = int.Parse(it.Current.Value); break; case "buildReason": buildReason = it.Current.Value; break; case "jiraIssues": if (it.Current.HasChildren) { var chnav = it.Clone().Current; if (chnav != null) { chnav.MoveToFirstChild(); do { var issue = getRelatedIssue(chnav); if (issue != null) { relatedIssues.Add(issue); } } while (chnav.MoveToNext()); } } break; } } while (it.Current.MoveToNext()); if (key == null) { continue; } var planState = getPlanState ? getPlanStateForBuild(key) : BambooBuild.PlanState.IDLE; var build = new BambooBuild(server, key, projectName, masterKey, BambooBuild.stringToResult(state), number, buildRelativeTime, buildDurationDescription, successfulTestCount, failedTestCount, buildReason, planState, relatedIssues); builds.Add(build); } // Yes, recursion here. I hope it works as I think it should. If not, we are all doomed if (withRecursion && totalBuildsCount > maxResult + startIndex) { builds.AddRange(getBuildsFromUrlWithStartIndex(endpoint, startIndex + maxResult, getPlanState, true, getCorrectEnpointOrXPath(BUILDS_XML_SUBTREE, BUILDS_XML_SUBTREE_3_0))); } return(builds); } }