Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Next challenges

Recent achievements

Recognition

  • Give kudos
  • My kudos

Leaderboard

  • Global

Trophy case

Kudos (beta program)

Kudos logo

You've been invited into the Kudos (beta program) private group. Chat with others in the program, or give feedback to Atlassian.

View group

It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

How to receive file content with Bitbuckets Java API?

Hey there,

so I do have a file with content on my bitbucket.org repositories which I'd like to call up from my java programme. I found this Bitbucket Java API ( https://docs.atlassian.com/bitbucket-server/javadoc/5.9.0/api/reference/packages.html ) but not a future usage of the Authentication or UserService class. What Properties has the Authentication class? Is the API even usable for bitbucket.org or is this only for self-hosted bitbucket servers?

 

So in short: Can someone show me a java code snippet how get text file content in a String from his bitbucket.org repositories?

 

Thanks!

 

 

2 answers

1 accepted

So after MONTHS for trying, googling and failing - here a result that works. If you have a better solution please comment :)

org.json is required.

 

ArrayList<String> lines = new ArrayList<>();

String username = "<yourusername>";
String apppassword = "<yourAppPassword>";
String reponame = "<reponame>";
byte[] encodedAuth = Base64.getEncoder().encode((username+":"+apppassword).getBytes());


HttpURLConnection connection = (HttpURLConnection) new URL("https://api.bitbucket.org/2.0/repositories/"+username+"/"+reponame+"/commits").openConnection();
connection.setRequestProperty("Authorization", "Basic " + new String(encodedAuth));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
JSONObject lastestCommit = new JSONObject(new JSONObject(reader.readLine()).getJSONArray("values").get(0).toString());

connection = (HttpURLConnection) new URL("https://api.bitbucket.org/2.0/repositories/"+username+"/"+reponame+"/src/"+lastestCommit.getString("hash")+"/names?raw").openConnection();
connection.setRequestProperty("Authorization", "Basic " + new String(encodedAuth));
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
    lines.add(line);
}
connection.disconnect();

I happen to automate the process of creating repository for microserice architecture along with the bitbucket pipeline to be created to for the created repo. 

I did it in two steps, 

1) Authentication: Firstly you need to get the authentication token(JWT) from bit bucket in order to authenticate all the api calls you might do further to it, like create repo, commit , delete etc. For this you will need key and secret , which can be generated as in link below.

https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html

and futher to this, you need to use following code along with generated key and secret in following way ( I have returned request header along with bearer token). I have used spring boot restTemplate for calling rest api, you may use any other.

 

MultiValueMap<String, String> map= new LinkedMultiValueMap<>();

map.add("grant_type", "client_credentials");

HttpHeaders header = new HttpHeaders();

header.setBasicAuth(<key>,<secret>);

header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, header);

ResponseEntity<Object> responseEntity = restTemplate.postForEntity("https://bitbucket.org/site/oauth2/access_token", request, Object.class);

LinkedHashMap body = (LinkedHashMap)responseEntity.getBody();

header = new HttpHeaders();

header.setContentType(MediaType.APPLICATION_JSON);

header.set(HttpHeaders.AUTHORIZATION, "Bearer " + requireNonNull(body).get("access_token").toString());

return header;

Now to create repository use the header from above code in following way

 

json request = {    
"scm": "git",
"project": {
"key": "<project key from bitbucket or UUID>"
},
"is_private":true/false,
"fork_policy":"no_forks",
"language":"<programming language>",
"name":"my-repo",

}
HttpEntity<Repository> requestEntity = new HttpEntity<>(<json request>, <header from above>);

ResponseEntity<Object> result = restTemplate.postForEntity("https://api.bitbucket.org/2.0/repositories/{username or team}/{repository name in lowercase}/", requestEntity, Object.class);

System.out.println(result.getStatusCode());

 If you get 200 ok you are done creating a repository. 

 

Similarly you can do it for other CRUD operations using bitbucker developer portal.

https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D#put

Suggest an answer

Log in or Sign up to answer
TAGS
Community showcase
Published in Bitbucket

Powering DevOps with Bitbucket Server & Data Center

Hi everyone, The Cloud team recently announced 12 new DevOps features that help developers ship better code, faster   ! While we’re all excited about the new improvements to Bitbucket ...

1,898 views 0 7
Read article

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you