Arun Puthussery
Arun Puthussery

Reputation: 53

How to add attachment to an existing JIRA Issue using rest-client API

I could create a jira issue using the rest client API, but i wasn't able to attach the screeshot/attachment to the exsiting JIRA issue. Would be really helpful if anyone could provide a solution which would be really appreciated.

I just wrote the below code snippet for attaching a jpeg file to the existing JIRA Issue. But then i experienced "Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/httpclient/HttpConnectionManager"

Code Snippet :-

private static String addAttachment(String attachmentfilepath) throws URISyntaxException, FileNotFoundException{

    final java.net.URI jiraServerUri = new java.net.URI("https://oliveits.atlassian.net");
    FileInputStream fileStreamPath = new FileInputStream(attachmentfilenamepath);
    JerseyJiraRestClientFactory factory = new JerseyJiraRestClientFactory();
    NullProgressMonitor pm = new NullProgressMonitor();
    System.out.println("Server Url  :"+jiraServerUri);
    JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri,"mobileqa","MobileQA1234");
    Issue issue1 = restClient.getIssueClient().getIssue(newKey, pm);
    final java.net.URI AttachmentUri = new java.net.URI(jiraServerUri+"/rest/api/2/issue/"+newKey+"/attachments");
    System.out.println("URI    :"+issue1.getAttachmentsUri());
    //restClient.getIssueClient().addAttachment(pm,issue1.getAttachmentsUri(), fileStreamPath , imageName);
    restClient.getIssueClient().addAttachment(pm, AttachmentUri, fileStreamPath, imageName);
    return attachmentfilepath;
}

Exception:-

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/httpclient/HttpConnectionManager
at com.atlassian.jira.rest.client.internal.jersey.JerseyJiraRestClientFactory.create(JerseyJiraRestClientFactory.java:34)
at com.atlassian.jira.rest.client.internal.jersey.JerseyJiraRestClientFactory.createWithBasicHttpAuthentication(JerseyJiraRestClientFactory.java:39)
at com.jtricks.JTricksRESTClient.addAttachment(JTricksRESTClient.java:157)
at com.jtricks.JTricksRESTClient.main(JTricksRESTClient.java:101)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.httpclient.HttpConnectionManager
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 4 more

Just added the missing jar files to the classpath. But I'm getting an exception as mentioned below.

Exception Msg-1: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java class com.sun.jersey.multipart.MultiPart, and Java type class com.sun.jersey.multipart.MultiPart, and MIME media type multipart/form-data; boundary=Boundary_1_18541827_1358346116249 was not found

Exception Msg-2: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java class com.sun.jersey.multipart.MultiPart, and Java type class com.sun.jersey.multipart.MultiPart, and MIME media type multipart/form-data; boundary=Boundary_1_18541827_1358346116249 was not found

Upvotes: 0

Views: 4013

Answers (3)

reda baalou
reda baalou

Reputation: 11

if you want to add attachments to a specific category

you can add atchement ( no specific category ) :

    String auth = new String(org.apache.commons.codec.binary.Base64
                    .encodeBase64((jiraUsername + ":" + jiraPassword).getBytes()));
            URI myJiraUri = URI.create(jiraUrl);
            URI myJiraUri = URI.create(jiraUrl);

            restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(myJiraUri,
                    jiraUsername, jiraPassword);

private String attachFileToIssue(JiraRestClient restClient, String jiraIssueId, String auth, String fileName,
        File file) throws IOException {

    Issue issue = restClient.getIssueClient().getIssue(jiraIssueId).claim();

    HttpPost toAttchFilePost = new HttpPost(issue.getAttachmentsUri());

    toAttchFilePost.setHeader("X-Atlassian-Token", "nocheck");
    toAttchFilePost.setHeader("Authorization", "Basic " + auth);

    HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("file", new FileBody(file)).build();

    toAttchFilePost.setEntity(requestEntity);

    LOG.info("send file to attachement" + toAttchFilePost.toString());

    CloseableHttpClient client = HttpClients.createDefault();

    CloseableHttpResponse responseToAttchFile = (CloseableHttpResponse) client.execute(toAttchFilePost);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    responseToAttchFile.getEntity().writeTo(baos);

    LOG.info("attachement in uncategorized status : " + responseToAttchFile.getStatusLine().getStatusCode());

    if (responseToAttchFile.getStatusLine().getStatusCode() == 200) {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(baos.toString());
        String attachments = jsonNode.get(0).get("id").asText();
        return attachments;
    } else {
        System.err.println("Failed to attach file. Status: " + responseToAttchFile.getStatusLine());
        return null;
    }
}

then move the file to the specific category :

HttpPost post = new HttpPost(jiraUrl + "rest/attach-cat/1.0/attachments/move");
    post.setHeader("Authorization", "Basic " + auth);
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");

    String formData = "toCatId=" + toCatId + "&attachments=" + attachmentId + "&issueKey=" + jiraIssueId;
    post.setEntity(new StringEntity(formData));

    try (CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response = client.execute(post)) {
        if (response.getStatusLine().getStatusCode() == 200) {
            return true;
        } else {
            System.err.println("Failed to move file. Status: " + response.getStatusLine());
            return false;
        }
    }

note :

  • toCatId is the cotegory of the attahcment ( you can get that from inspecting u jira in chrom , try to move the file and see the network changes )
  • attachmentId is hte id of the file ( each attachment has a unique id )

Upvotes: 0

David KELLER
David KELLER

Reputation: 636

You can try this :

String issueKey = "your-issue";

JiraRestClient restClient 
  = AsynchronousJiraRestClientFactory()
                .createWithBasicHttpAuthentication(
                        getJiraUri(), 
                        username,
                        password);

Issue issue = restClient.getIssueClient().getIssue(issueKey).claim();
restClient.getIssueClient().addAttachments(issue.getAttachmentsUri(), file).claim();
restClient.close(); 

in the pom.xml

    <properties>
        <jira-rest-java-client-core.version>5.2.4</jira-rest-java-client-core.version>
        <atlassian.fugue.version>5.0.0</atlassian.fugue.version>
    </properties>
...

    <dependencies>
...
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-rest-java-client-core</artifactId>
            <version>${jira-rest-java-client-core.version}</version>
        </dependency>
        
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-rest-java-client-api</artifactId>
            <version>${jira-rest-java-client-core.version}</version>
        </dependency>

        <dependency>
            <groupId>io.atlassian.fugue</groupId>
            <artifactId>fugue</artifactId>
            <version>${atlassian.fugue.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

Upvotes: 0

Archer
Archer

Reputation: 5147

You issue comes from inability to find org.apache.commons.httpclient.HttpConnectionManager class. Look for commons-httpclient JAR in your classpath.

Upvotes: 1

Related Questions