4

I'm currently developing my first java program who'll make a call to a rest api(jira rest api, to be more especific).

So, if i go to my browser and type the url = "http://my-jira-domain/rest/api/latest/search?jql=assignee=currentuser()&fields=worklog"

I get a response(json) with all the worklogs of the current user. But my problem is, how i do my java program to do this ? Like,connect to this url, get the response and store it in a object ?

I use spring, with someone know how to this with it. Thx in advance guys.

Im adding, my code here:

RestTemplate restTemplate = new RestTemplate();
String url;
url = http://my-jira-domain/rest/api/latest/search/jql=assignee=currentuser()&fields=worklog
jiraResponse = restTemplate.getForObject(url,JiraWorklogResponse.class);

JiraWorkLogResponse is a simple class with some attributes only.

Edit, My entire class:

@Controller
@RequestMapping("/jira/worklogs")
public class JiraWorkLog {

    private static final Logger logger = Logger.getLogger(JiraWorkLog.class.getName() );
@RequestMapping(path = "/get", method = RequestMethod.GET, produces = "application/json")

    public ResponseEntity getWorkLog() {


    RestTemplate restTemplate = new RestTemplate();
    String url;
    JiraProperties jiraProperties = null;


    url = "http://my-jira-domain/rest/api/latest/search?jql=assignee=currentuser()&fields=worklog";

    ResponseEntity<JiraWorklogResponse> jiraResponse;
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders = this.createHeaders();


    try {
        jiraResponse = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(httpHeaders),JiraWorklogResponse.class);



    }catch (Exception e){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }

    return ResponseEntity.status(HttpStatus.OK).body(jiraResponse);

}


private HttpHeaders createHeaders(){
    HttpHeaders headers = new HttpHeaders(){
        {
            set("Authorization", "Basic something");
        }
    };
    return headers;
}

This code is returning : org.springframework.http.converter.HttpMessageNotWritableException

Anyone knows why ?

Estudeiro
  • 383
  • 2
  • 4
  • 18

4 Answers4

2

All you need is http client. It could be for example RestTemplate (related to spring, easy client) or more advanced and a little more readable for me Retrofit (or your favorite client).

With this client you can execute requests like this to obtain JSON:

 RestTemplate coolRestTemplate = new RestTemplate();
 String url = "http://host/user/";
 ResponseEntity<String> response
 = restTemplate.getForEntity(userResourceUrl + "/userId", String.class);

Generally recommened way to map beetwen JSON and objects/collections in Java is Jackson/Gson libraries. Instead them for quickly check you can:

  1. Define POJO object:

    public class User implements Serializable {
    private String name;
    private String surname;
    // standard getters and setters
    }
    
  2. Use getForObject() method of RestTemplate.

    User user = restTemplate.getForObject(userResourceUrl + "/userId", User.class);
    

To get basic knowledge about working with RestTemplate and Jackson , I recommend you, really great articles from baeldung:

http://www.baeldung.com/rest-template

http://www.baeldung.com/jackson-object-mapper-tutorial

B.Ohara
  • 241
  • 1
  • 2
  • 10
  • ok. But do you know how i pass my credentials trough http headers with java ? Because probably the rest api wil have some authentication. – Estudeiro Jun 15 '18 at 14:03
  • In case of authentication in much easier to use RestTemplate.exchange method. Just check first answer: https://stackoverflow.com/questions/15462128/basic-authentication-with-resttemplate-compilation-error-the-constructor-htt – B.Ohara Jun 15 '18 at 14:14
  • Yeah, it's getting clear now. With your help i'm now able to make headers, but i'm getting this error : "org.springframework.http.converter.HttpMessageNotWritableException" I'm going to post my code so far – Estudeiro Jun 15 '18 at 16:39
  • Estudeiro it's looks that there is problem with mapping beetwen http response and you class JiraWorklogResponse. To verify it you should check if response from Jira has possibilty to map to this class (It's only quess). If problem still occurs, you sholud provide full stack trace of exception. – B.Ohara Jun 21 '18 at 11:56
0

Since you are using Spring you can take a look at RestTemplate of spring-web project.

A simple rest call using the RestTemplate can be:

RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos";
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
pleft
  • 7,567
  • 2
  • 21
  • 45
  • i'm using something like this, i'll post my code here. And can you explain me why we use the (fooResourceUrl + "/1") ? What the "/1" is for ? – Estudeiro Jun 15 '18 at 13:35
0

The issue could be because of the serialization. Define a proper Model with fields coming to the response. That should solve your problem.

May not be a better option for a newbie, but I felt spring-cloud-feign has helped me to keep the code clean.

Basically, you will be having an interface for invoking the JIRA api.

@FeignClient("http://my-jira-domain/")
public interface JiraClient {  
    @RequestMapping(value = "rest/api/latest/search?jql=assignee=currentuser()&fields=", method = GET)
    JiraWorklogResponse search();
}

And in your controller, you just have to inject the JiraClient and invoke the method

jiraClient.search();

And it also provides easy way to pass the headers.

Thiru
  • 2,541
  • 4
  • 25
  • 39
0

i'm back and with a solution (:

@Controller
@RequestMapping("/jira/worklogs")
public class JiraWorkLog {

    private static final Logger logger = Logger.getLogger(JiraWorkLog.class.getName() );

    @RequestMapping(path = "/get", method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<JiraWorklogIssue> getWorkLog(@RequestParam(name = "username") String username) {


        String theUrl = "http://my-jira-domain/rest/api/latest/search?jql=assignee="+username+"&fields=worklog";
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<JiraWorklogIssue> response = null;
        try {
            HttpHeaders headers = createHttpHeaders();
            HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
            response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, JiraWorklogIssue.class);
            System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
        }
        catch (Exception eek) {
            System.out.println("** Exception: "+ eek.getMessage());
        }

        return response;

    }

    private HttpHeaders createHttpHeaders()
    {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Basic encoded64 username:password");
        return headers;
    }

}

The code above works, but can someone explain to me these two lines ?

HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
                response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, JiraWorklogIssue.class);

And, this is a good code ? thx (:

Estudeiro
  • 383
  • 2
  • 4
  • 18