Wednesday, March 2, 2016

JSON Example with Java + Jersey + Atlassian Stash

This is a sample Java program to read a Git branch information hosted in Atlassian Stash using REST web-services. In this code Jersey Client used to contact Stash. The JSON output is parsed to display branch information.

------------------------------------------------------------------------------------------------------
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.json.JSONException;
import org.json.JSONObject;

public class Try1 {
public static void main(String[] args) {
               // Load server and authentication details to Jersey client
ClientConfig clientConfig = new ClientConfig();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("siddesh", "*****");
clientConfig.register(feature);
Client client = ClientBuilder.newClient(clientConfig);
WebTarget webTarget = client.target("https://mycompany/stash/rest")
.path("api/1.0/projects/MYPROJ/repos/MYREPO/branches").queryParam("filterText", "MYBRANCH");

                // send request to server
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);

                //parse response
Response response = invocationBuilder.get();
System.out.println(response.getStatus());
System.out.println(response.getStatusInfo());
String myResponse = response.readEntity(String.class);
System.out.println(myResponse);

System.out.println("=============================");
try {
JSONObject jsonObject = new JSONObject(myResponse);
//JSONObject branchName = jsonObject.getJSONArray("values").getJSONObject(0).get(displayId);
System.out.println(jsonObject.getJSONArray("values").getJSONObject(0).get("displayId"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
------------------------------------------------------------------------------------------------------

Output

200
OK
{"size":1,"limit":25,"isLastPage":true,"values":[{"id":"refs/heads/MYBRANCH","displayId":"MYBRANCH","latestChangeset":"352f25ss099xx2b1be4c4cce26430ad257e3845f","isDefault":false}],"start":0}
=============================
MYBRANCH

2 comments:

Get your miracle today said...

lololol

gracylayla said...

Hello,
The blog gave me idea to test Ansible with inspec my sincere thanks for sharing this post Please continue to share this kind of post