Hi All,
As far as i saw, many people (include me) use REST API calls from Jira to GET/POST data from/to Bitbucket/Bamboo.
Most people are using hard coded credentials with Base64 Encode.
However, putting your credentials hard coded (even in Base64 Encode format) is not the best practice, so i will share here a way that many users are not familiar with.
By using the following, you will be able to perform your REST API calls from Jira without putting credentials.
This will use the current login user credentials in Jira, to connect to Bitbucket/Bamboo
import com.atlassian.applinks.api.ApplicationLinkRequestFactory;
import com.atlassian.applinks.api.ApplicationLink;
import com.atlassian.applinks.api.ApplicationLinkService;
import com.atlassian.applinks.api.application.bamboo.BambooApplicationType;
import com.atlassian.applinks.api.application.bitbucket.BitbucketApplicationType;
In order to use this technique you will have to link Bitbucket/Bamboo to your Jira link applications.
And here is an example for how to use it:
/*to get the Bitbucket link*/
private ApplicationLink getPrimaryBitbucketLinkLink() {
ApplicationLinkService applicationLinkService = ComponentLocator.getComponent(ApplicationLinkService.class);
final ApplicationLink bitbucketLink = applicationLinkService.getPrimaryApplicationLink(BitbucketApplicationType.class);
return bitbucketLink;
}
/*to get the Bamboo link*/
private ApplicationLink getPrimaryBambooLink() {
ApplicationLinkService applicationLinkService = ComponentLocator.getComponent(ApplicationLinkService.class);
final ApplicationLink bambooLink = applicationLinkService.getPrimaryApplicationLink(BambooApplicationType.class);
return bambooLink;
}
/*REST API GET request*/
private JSONObject getJsonData(ApplicationLink applicationLink, String restURL) throws Exception {
ApplicationLink appLink = applicationLink;
ApplicationLinkRequestFactory authenticatedRequestFactory = appLink.createAuthenticatedRequestFactory();
final Response[] res = new Response[1];
authenticatedRequestFactory
.createRequest(Request.MethodType.GET, restURL)
.addHeader("Content-Type", "application/json")
.execute(new ResponseHandler<Response>() {
@Override
public void handle(Response response) {
if (response.getStatusCode() != HttpURLConnection.HTTP_OK) {
try {
throw new Exception(response.getResponseBodyAsString());
} catch (Exception e) {
e.printStackTrace();
}
}
res[0] = response;
}
});
JSONObject jsonObject = new JSONObject(res[0].getResponseBodyAsString());
return jsonObject;
}
/*call the getJsonData function to get data from where we want*/
getJsonData(getPrimaryBitbucketLinkLink(), "/rest/api/latest/....")
Hope this will serve you well as it served me.
Feel free to reply my article and ask questions or share your thought with my methods.
Thanks,
Nir Haimov
Nir Haimov
Jira Expert Developer
Israel
116 accepted answers
11 comments