【问题标题】:How retrieve a list of attachments JIRA rest api via java?如何通过 java 检索附件列表 JIRA rest api?
【发布时间】:2016-01-11 21:05:41
【问题描述】:

如何使用带有 Java 的 JIRA API 获取附件列表?我不需要附件我只想知道那里有哪些附件,以及它们的 ID。 我遵循了使用查询来获取问题的基础知识,并且我遇到了问题,但不是他们的附件。 我的代码:

[String searchQuery = "(created >= '2015/12/1' ) AND (created < '2016/01/1')" 
JiraAuthentication jiraAuth;
JiraRestClient arc;
// Get JiraAuthentication instance to create basic HTTP authentication
// string
jiraAuth = JiraAuthentication.getInstance();

// Make sure you use a new instance
jiraAuth.initInstance();
jiraAuth = JiraAuthentication.getInstance();

// Get the JIRA Rest Client from the basic HTTP authentication
jrc = jiraAuth.getJrc();

// Receive search results based on query
SearchRestClient searchClient = jrc.getSearchClient();
// limit results to 50
SearchResult result = searchClient.searchJql(searchQuery, 50,0, null);
Iterator<BasicIssue> itIssue = result.getIssues().iterator();

// pull information on individual issues.
while (itIssue.hasNext()) {
   BasicIssue lBasicIssue = (BasicIssue) itIssue.next();
   String lIssueKey = lBasicIssue.getKey();
   Issue issue = jrc.getIssueClient().getIssue(lIssueKey, null);
   //This line should print the list of attachments. but everything is always null.
   System.out.println(issue.getAttachements());
}][1]

我试图从 HBASE-15062 获取信息的一个示例,它具有 api link。在 api 链接中没有显示任何附件,但在实际链接中有 4 个附件。

我知道 Jira api 调用 api/2/issue/{issueIdOrKey}/attachments

我试过了:api/2/issue/12925031/attachments 我收到回复 HTTP Status 405 - Method Not Allowed 这是否意味着我无法获取附件列表或者我只是做错了请求?

如何更改我的 java 代码以获取附件? 是否可以从 APACHE JIRA 获取附件?

【问题讨论】:

    标签: java apache jira jira-rest-api jira-rest-java-api


    【解决方案1】:

    据我所见,Atlassian JIRA 中有一张票可以说明您的体验:REST issue get no longer shows attachments informationthis comment 中甚至提到了 Apache 的 JIRA 案例。引用another comment:

    附件在问题视图网页中可见,但在 REST 上不可见,而该字段在默认屏幕中隐藏。

    bug已经解决了,但是用户好像不太喜欢demand a proper fix:

    上面的“解决方案”不是解决方案,而是此错误的解决方法。 Atlassian 的正确解决方案是修复此错误,以便始终在 JSON 中列出附件。 GUI 设置不会影响 REST API JSON 输出——这显然是错误的!请重新打开并解决此问题。

    我同意他们的观点,但这并没有改变这样一个事实,即目前您干净地实现目标的唯一选择是让 Apache 解决问题。无论如何,我似乎有一个解决方法。

    解决方法

    我不知道您使用的客户端工具,所以我将描述使用纯 REST 方法的解决方法。将附件添加到问题时,该事件会记录在工单的更改日志中:

    https://issues.apache.org/jira/rest/api/2/issue/HBASE-15062?expand=changelog

    {
       (...),          
       "changelog": {
          "startAt":0,
          "maxResults":8,
          "total":8,
          "histories":[
             (...),
             {                 
                "id":"15174314",
                "author":{...},
                "created":"2015-12-31T15:55:43.318+0000",
                "items":[  
                   {  
                      "field":"Attachment",
                      "fieldtype":"jira",
                      "from":null,
                      "fromString":null,
                      "to":"12780132",
                      "toString":"HBASE-15062-v0.patch"
                   }
                ]
             },
             {  
                "id":"15174320",
                "author":{...},
                "created":"2015-12-31T16:06:03.165+0000",
                "items":[  
                   {  
                      "field":"Attachment",
                      "fieldtype":"jira",
                      "from":null,
                      "fromString":null,
                      "to":"12780133",
                      "toString":"HBASE-15062-v1.patch"
                   }
                ]
             },             
             {  
                "id":"15184002",
                "author":{...},
                "created":"2016-01-04T08:04:50.969+0000",
                "items":[  
                   {  
                      "field":"Attachment",
                      "fieldtype":"jira",
                      "from":null,
                      "fromString":null,
                      "to":"12780273",
                      "toString":"HBASE-15062-v1.patch"
                   }
                ]
             },
             {  
                "id":"15187193",
                "author":{...},
                "created":"2016-01-05T21:30:48.977+0000",
                "items":[  
                   {  
                      "field":"Attachment",
                      "fieldtype":"jira",
                      "from":null,
                      "fromString":null,
                      "to":"12780629",
                      "toString":"HBASE-15062-v1.patch"
                   }
                ]
             },
             (...)
          ]
       }
    }
    

    让我们考虑日志中第一个 id 为 12780132 的附件。知道了 id,您可以查询 API 以获取附件的详细信息:

    https://issues.apache.org/jira/rest/api/2/attachment/12780132

    {  
       "self":"https://issues.apache.org/jira/rest/api/2/attachment/12780132",
       "filename":"HBASE-15062-v0.patch",
       "author":{  
          "self":"https://issues.apache.org/jira/rest/api/2/user?username=asamir",
          "key":"asamir",
          "name":"asamir",
          "avatarUrls":{  
             "48x48":"https://issues.apache.org/jira/secure/useravatar?avatarId=10452",
             "24x24":"https://issues.apache.org/jira/secure/useravatar?size=small&avatarId=10452",
             "16x16":"https://issues.apache.org/jira/secure/useravatar?size=xsmall&avatarId=10452",
             "32x32":"https://issues.apache.org/jira/secure/useravatar?size=medium&avatarId=10452"
          },
          "displayName":"Samir Ahmic",
          "active":true
       },
       "created":"2015-12-31T15:55:43.304+0000",
       "size":2173,
       "mimeType":"text/x-patch",
       "properties":{  
    
       },
       "content":"https://issues.apache.org/jira/secure/attachment/12780132/HBASE-15062-v0.patch"
    }
    

    现在您拥有下载附件的所有信息:

    https://issues.apache.org/jira/secure/attachment/12780132/HBASE-15062-v0.patch.

    希望对你有帮助,保重!

    【讨论】:

      【解决方案2】:

      我想说jannis 回答引导我找到这个问题的答案。

      添加参数?expand=changelogjannis方法是获取附件的唯一方法。 getIssue()的java调用需要更改我找到了如何添加参数here,api信息是here

      getIssue(String issueKey, ProgressMonitor progressMonitor) 被使用:

      Issue issue = jrc.getIssueClient().getIssue(lIssueKey, null);
      

      应该使用Issue getIssue(String issueKey, Iterable&lt;IssueRestClient.Expandos&gt; expand, ProgressMonitor progressMonitor)

         Issue issue = jrc.getIssueClient().getIssue(lIssueKey, Arrays.asList(IssueRestClient.Expandos.CHANGELOG), null);
      

      通过更改对 getIssue 的调用,应填充更改日志字段。然后,您可以使用此字段通过迭代更改日志来查看附件。我这样做了:

      private null findAttachments(Issue issue) {
          String FieldName = "Attachment";
          Iterable<ChangelogGroup> changes = issue.getChangelog();
          StringBuilder attachments = new StringBuilder();
          StringBuilder attachmentsIDs = new StringBuilder();
      
          for (ChangelogGroup change: changes){
              //Multiple change items per group. 
              for(ChangelogItem item: change.getItems()){
                  if(item.getField().equals(FieldName)){
                      //Gets attachment name.
                      attachments.append((String) item.getToString());
                      //Gets attachment ID to download if needed.
                      attachmentsIDs.append((String) item.getTo());
                  }
              }
          }
          //Do something with attachments here..
      
      }
      

      【讨论】:

      • 我猜你可能已经想到了,但请记住附件删除也包含在更改日志中(getTo() 在这种情况下可能会导致 null - 未经测试)。不要忘记相应地从attachmentsattachmentIDs 中删除附件。
      • ^_^ 花了大约 5 分钟的调试时间才意识到这一点,现在它们被删除并根据需要添加。
      【解决方案3】:

      这比您想象的要容易,但出乎意料。仅供参考,以下是 groovy,所以 java 会略有不同。

      确保附件显示在您的默认屏幕上(它必须让 Jira-Rest-Java-Client 的 getIssue 填充 getAttachments() 结果。听起来很疯狂,但是当我添加它并修改默认字段配置以显示它时 - 以下一切正常。

          @Test
      void addAttachmentTest() {
          String priority = "Blocker"
          String project = "TESTRELENG"
          String summary = "summary addAttachmentTest@${hostName} - ${now.getTime()}"
          String description = "desc addAttachmentTest@${hostName} - ${now.getTime()}"
      
      
          // Create Issue
          def issue = controller.addBug(project, priority, summary, description)
      
          // Create Attachment File
          File attachment = new File("build/testdata/${name.getMethodName()}/attachment.txt")
          attachment.parentFile.mkdirs()
          def expectedText ="${name.getMethodName()} - ${hostName} - ${now.getTime()}"
          attachment.write(expectedText)
      
          // add attachment
          controller.addAttachment(issue.getKey(), attachment)
          Issue result = controller.getIssue(issue.key)
      
          // Verify
          File outputFile = new File(attachment.parentFile, "output.txt")
          controller.downloadAttachment(result.key, attachment.name, outputFile)
          assertEquals(attachment.text, outputFile.text)
      
          // Clean up
          controller.deleteIssue(issue.getKey())
      }
      

      JiraController

      class JiraController {
         def user
         def url
         def password
         JiraRestClient client
        ....
      JiraRestClient getClient() {
          if (null == client) {
              AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
              client = factory.create(url.toURI(), new BasicHttpAuthenticationHandler(user,password))
      
          }
          return client
      }
      ...
      Issue getIssue(String issueKey) {
          Issue issue
          try {
              issue = getClient().getIssueClient().getIssue(issueKey).claim()
          } catch (RestClientException e) {
              throw new JiraControllerException("Cannot access ${issueKey} due to permissions.", e)
          }
          return issue
      }
      ...
      /**
       * Get Attachment Info object
       * @param issueKey
       * @param attachmentName
       * @return
       */
      public Attachment getAttachmentByName(String issueKey, String attachmentName) {
          Issue issue = getIssue(issueKey)
          Attachment found = issue.attachments.find() { Attachment attachment ->
              attachment.filename == attachmentName
          }
          if (!found) {
              def names = issue.attachments.collect() { Attachment a -> a.filename}
              throw new JiraControllerException("Cannot Locate ${issueKey} Attachment ${attachmentName}.  Options: " + names)
          }
          return found
      }
      

      【讨论】:

        【解决方案4】:

        我在搜索 URL 中添加了参数 fields=*all。并且服务器在每个问题中都包含附件和 cmets 字段。

        所以结果 URL 必须是这样的:

        http://{host}/rest/api/2/search?jql={jqlQuery}&fields=*all

        Jira 版本:6.3.13。

        jannis 的解决方法对我不起作用。变更日志中的历史记录中没有附件。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-20
          • 2021-09-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多