Estudeiro
Estudeiro

Reputation: 403

Using jira REST api

I'm currently trying to get worklogs from jira through java. I'm reading the documentation, about it(https://developer.atlassian.com/cloud/jira/platform/rest/#api/2/issue-createIssue) but i simply can't find some basic information like:

How do i start using that api with java ? Did i have to add something to my pom.xml ? If yes, what dependency ?

For my task(get worklogs), it's better use the java api or the rest API ?

Any of you guys can send me a light, recommend me a book or article about it or something ?

Thx in advance guys.

Upvotes: -1

Views: 2131

Answers (5)

Srk
Srk

Reputation: 1

@Service public class ScheduledTasks {

@Autowired
private CommentRepository commentRepository;

@Autowired
private JiraService jiraService;

@Scheduled(cron = "0 0/10 * * * ?") // runs every 10 minutes
public void processNullJiraIds() {
    // get all records where Jira_id is null
    List<Reviews> comments = reviewRepository.findByJiraIdIsNull();
    
    for (Comment comment : comments) {
        // create issue in Jira
        String jiraId = jiraService.createIssue(comment);
        
        // update the database record
        review.setJiraId(jiraId);
        reviewRepository.save(comment);
    }
}

}

@Service public class JiraService {

private final String JIRA_URL = "https://yourjiraurl/rest/api/2/issue";
private final String JIRA_USERNAME = "your_username";
private final String JIRA_PASSWORD = "your_password";

public String createIssue(Comment comment) {
    HttpHeaders headers = createHeaders(JIRA_USERNAME, JIRA_PASSWORD);
    headers.setContentType(MediaType.APPLICATION_JSON);
    // here you need to define the JSON structure based on your Jira setup
    String requestJson = createRequestJson(comment);

    HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(JIRA_URL, HttpMethod.POST, entity, String.class);
    
    // assuming that Jira returns issue id in the response. If not adjust accordingly.
    String jiraId = parseJiraId(responseEntity.getBody());
    return jiraId;
}

HttpHeaders createHeaders(String username, String password) {
    return new HttpHeaders() {{
        String auth = username + ":" + password;
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        set("Authorization", authHeader);
    }};
}

String createRequestJson(Comment comment) {
    // Here you need to create a JSON payload to create a new issue in Jira.
    // The structure depends on your Jira setup and might include things like project id, issue type, etc.
    // Replace with your actual JSON structure.
    return "{ \"fields\": { \"project\": { \"id\": \"YOUR_PROJECT_ID\" }, \"summary\": \"" + comment.getContent() + "\", \"issuetype\": { \"id\": \"YOUR_ISSUE_TYPE_ID\" } } }";
}

String parseJiraId(String responseJson) {
    // Parse the Jira issue id from the response JSON
    // The exact path depends on the structure of your Jira's response.
    // This is just a placeholder and likely needs to be replaced with your actual code.
    JSONObject jsonObject = new JSONObject(responseJson);
    return jsonObject.getString("id");
}

}

Upvotes: -1

sendon1982
sendon1982

Reputation: 11314

Hi I think it is better to use REST API directly as you do not need to add any pom dependencies.

Here is the simple example with OkHttpClient (you can use any http client)

OkHttpClient client = new OkHttpClient().newBuilder()  .build();

Request request = new Request.Builder()
  .url("https://${JIRA_HOST}/rest/api/2/issue/${JIRA_NUMBER}/worklog")
  .method("GET", null)
  .addHeader("Authorization", "Basic ......................")
  .addHeader("Content-Type", "application/json")
  .build();

Response response = client.newCall(request).execute();

Response JSON (omitted some fields):

{
  "startAt": 0,
  "maxResults": 2,
  "total": 2,
  "worklogs": [
    {
      "comment": "Log work",
      "created": "2023-03-06T13:25:01.773+1100",
      "updated": "2023-03-06T13:25:01.773+1100",
      "started": "2023-03-06T13:24:00.000+1100",
      "timeSpent": "2h",
      "timeSpentSeconds": 7200,
      "id": "1269560",
      "issueId": "4340529"
    },
    {
      "comment": "Working on unit test",
      "created": "2023-03-06T13:25:24.027+1100",
      "updated": "2023-03-06T13:25:24.027+1100",
      "started": "2023-03-03T13:25:00.000+1100",
      "timeSpent": "4h",
      "timeSpentSeconds": 14400,
      "id": "1269561",
      "issueId": "4340529"
    }
  ]
}

Reference link for JIRA REST API: https://docs.atlassian.com/software/jira/docs/api/REST/8.0.2/#api/2/issue-getIssueWorklog

Upvotes: 0

Vishal Kharde
Vishal Kharde

Reputation: 1737

If you want to read/modify Jira issue from an external code then you can use Jira Rest APIs. Following links will be helpful to understand fetching/updating worklog details for an jira issue,

To get all work logs for an Jira issue, https://docs.atlassian.com/software/jira/docs/api/REST/8.0.2/#api/2/issue-getIssueWorklog

TO fetch specific worklog for an Jira issue, https://docs.atlassian.com/software/jira/docs/api/REST/8.0.2/#api/2/issue-getIssueWorklog

Upvotes: 0

Jan B Noir
Jan B Noir

Reputation: 11

If its help you, I give you link to my repo on git, there is program to load scenario test to Jira with Zephyr. There is two simple endpoints, to send post method. Github My pom:

<dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>javax.json</groupId>
            <artifactId>javax.json-api</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.json</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
    </dependencies>

Upvotes: 1

architux
architux

Reputation: 657

You can use JIRA's internal Java API, for example, with Groovy scripts via ScriptRunner plugin for JIRA.

You should import ComponentAccessor to get basic JIRA helper classes for the rest of logic.

Here is a Groovy script snippet to get all Worklog objects for a given issue:

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.worklog.WorklogManager

worklogManager = ComponentAccessor.getWorklogManager()

def issueWorklogItems = worklogManager.getByIssue(issue)

Upvotes: 0

Related Questions