简体   繁体   English

如何通过java检索附件列表JIRA rest api?

[英]How retrieve a list of attachments JIRA rest api via java?

How do I get the list of attachments using JIRA API with Java? 如何使用JIRA API和Java获取附件列表? I don't need the attachments I just want to know what attachments are there, and their ID. 我不需要附件我只想知道附件是什么,以及他们的ID。 I followed basics of using a query to get issues and I am getting issues but not their attachments. 我遵循了使用查询来解决问题的基础知识,但我遇到了问题,但没有问题。 My code: 我的代码:

[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]

One example where I am trying to get information is from HBASE-15062, which has the api link . 我试图获取信息的一个例子来自HBASE-15062,它有api 链接 In the api link there doesn't show any attachments but in the actual link there are 4 attachments. 在api链接中没有显示任何附件,但在实际链接中有4个附件。

I know about the Jira api call api/2/issue/{issueIdOrKey}/attachments . 我知道Jira api调用api/2/issue/{issueIdOrKey}/attachments

I tried : api/2/issue/12925031/attachments I get the response HTTP Status 405 - Method Not Allowed Does this mean I cannot get attachment list or am I just doing the request wrong? 我试过: api / 2 / issue / 12925031 / attachments我收到响应HTTP Status 405 - Method Not Allowed这是否意味着我无法获取附件列表或我只是做错了请求?

How can I change my java code to get the attachments? 如何更改我的java代码以获取附件? Is getting attachments possible from the APACHE JIRA? 是否可以从APACHE JIRA获得附件?

From what I can see there is a ticket in Atlassian JIRA for what you experience: REST issue get no longer shows attachments information . 从我所看到的,在Atlassian JIRA中有一张票可以获得您的体验: REST问题不再显示附件信息 Apache's JIRA case is even mentioned in this comment . 本评论中甚至提到了Apache的JIRA案例。 Quoting another comment : 引用另一条评论

Attachments are visible in Issue View webpage, but not visible on REST while the field is hidden from the default screen. 附件在“问题视图”网页中可见,但在默认屏幕中隐藏字段时,在REST上不可见。

The bug has been resolved, but the users don't seem to like it and demand a proper fix : 该错误已经解决,但用户似乎不喜欢它并要求正确修复

The "Resolution" above is not a resolution but a workaround for this bug. 上面的“解决方案”不是解决方案,而是此错误的解决方法。 A proper resolution is for Atlassian to fix this bug so that attachments are always listed in the JSON. 适当的解决方案是让Atlassian修复此错误,以便始终在JSON中列出附件。 There is no way a GUI setting should affect the REST API JSON output - that's clearly wrong! GUI设置无法影响REST API JSON输出 - 这显然是错误的! Please reopen and fix this issue. 请重新打开并解决此问题。

I agree with them, but it doesn't change the fact that currently your only option to achieve your goal cleanly is to have the issue acted on by Apache. 我同意他们的观点,但这并没有改变这样一个事实,即目前你干净利落地实现目标的唯一选择就是让Apache采取行动。 Anyway I seem to have a workaround. 无论如何,我似乎有一个解决方法。

Workaround 解决方法

I don't know the client tool you're using, so I'll describe the workaround using the pure REST approach. 我不知道您正在使用的客户端工具,因此我将使用纯REST方法描述解决方法。 When an attachment is added to an issue, the event is noted in the ticket's change log: 将附件添加到问题时,会在故障单的更改日志中记录该事件:

https://issues.apache.org/jira/rest/api/2/issue/HBASE-15062?expand=changelog 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"
               }
            ]
         },
         (...)
      ]
   }
}

Let's consider the first attachment in the log with id 12780132. Knowing the id you can query the API for the details of the attachment: 让我们考虑一下id为12780132的日志中的第一个附件。了解id后,您可以在API中查询附件的详细信息:

https://issues.apache.org/jira/rest/api/2/attachment/12780132 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"
}

Now you have all the info to download the attachment: 现在您拥有了下载附件的所有信息:

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

Hope it helps, take care! 希望它有所帮助,保重!

I would like to say jannis answer lead me to the answer for this question. 我想说jannis的回答引导我回答这个问题。

jannis method that adds the parameter ?expand=changelog is the only way to get attachments. 添加参数的jannis方法?expand=changelog是获取附件的唯一方法。 The java call for getIssue() needs to change I found how to add parameters here , the api info is here . getIssue()的java调用需要更改我发现如何在这里添加参数,api信息在这里

getIssue(String issueKey, ProgressMonitor progressMonitor) was used: getIssue(String issueKey, ProgressMonitor progressMonitor)

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

Issue getIssue(String issueKey, Iterable<IssueRestClient.Expandos> expand, ProgressMonitor progressMonitor) should be used: Issue getIssue(String issueKey, Iterable<IssueRestClient.Expandos> expand, ProgressMonitor progressMonitor)

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

With the changed call to getIssue the changelog field should be populated. 通过更改对getIssue的调用,应填充changelog字段。 You can then use this field to look at attachments by iterating through the change log. 然后,您可以通过迭代更改日志来使用此字段查看附件。 I did this: 我这样做了:

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..

}

It's easier than you think but unexpected. 它比你想象的容易,但出人意料。 FYI the following is groovy, so the java would be slightly different. 仅供参考,以下是groovy,所以java会略有不同。

Make sure Attachment shows on your default screen (it must for Jira-Rest-Java-Client's getIssue to populate the getAttachments() result. Sounds crazy, but when I added it and modified Default Field configuration to show it - the following all worked. 确保在默认屏幕上显示附件(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 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
}

I added parameter fields=*all to search URL. 我添加了参数fields = * all来搜索URL。 And the server included attachment and comments fields into every issue. 服务器在每个问题中都包含附件和注释字段。

So result URL must be like that: 所以结果URL必须是这样的:

http://{host}/rest/api/2/search?jql={jqlQuery}&fields=*all HTTP:// {主机} /休息/ API / 2 /搜索JQL = {jqlQuery}&字段= *所有

Jira version: 6.3.13. Jira版本:6.3.13。

Workaround from jannis was not working for me. jannis的解决方法对我不起作用。 Attachments were absent from history in the changelog. 更改日志中没有附件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM