Modifying a collection property using the Rally Rest API in Java - java

I'm trying to modify the TestSets property of a TestCase.
JsonArray newTestSets = new JsonArray();
... add values as needed ( in the simplest case I'm clearing the property )
JsonObject updates = new JsonObject();
updates.add("TestSets", newTestSets);
I create the updateRequest like I do for all other updates
UpdateRequest updateRequest = new UpdateRequest(ref, updates)
I don't get any error but nothing has changed. The TestCase is still in several TestSets
What am I missing?

I verified that it works to update TestSets collection on a TestCase. See this github repo.
public class UpdateTestSetsOnTestCase {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String workspaceRef = "/workspace/12352608129";
String applicationName = "RestExample_updateTestSetsOnTC";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
try {
String setID = "TS24";
String testid = "TC3";
QueryRequest tsRequest = new QueryRequest("TestSet");
tsRequest.setWorkspace(workspaceRef);
tsRequest.setQueryFilter(new QueryFilter("FormattedID", "=", setID));
QueryResponse tsQueryResponse = restApi.query(tsRequest);
if(tsQueryResponse.getTotalResultCount() == 0){
System.out.println("Cannot find tag: " + setID);
return;
}
JsonObject tsJsonObject = tsQueryResponse.getResults().get(0).getAsJsonObject();
String tsRef = tsJsonObject.get("_ref").getAsString();
System.out.println(tsRef);
QueryRequest testCaseRequest = new QueryRequest("TestCase");
testCaseRequest.setWorkspace(workspaceRef);
testCaseRequest.setFetch(new Fetch("FormattedID", "Name", "TestSets"));
testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", testid));
QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);;
if (testCaseQueryResponse.getTotalResultCount() == 0) {
System.out.println("Cannot find test case : " + testid);
return;
}
JsonObject testCaseJsonObject = testCaseQueryResponse.getResults().get(0).getAsJsonObject();
String testCaseRef = testCaseJsonObject.get("_ref").getAsString();
System.out.println(testCaseRef);
int numberOfTestSets = testCaseJsonObject.getAsJsonObject("TestSets").get("Count").getAsInt();
System.out.println(numberOfTestSets + " testset(s) on " + testid);
QueryRequest testsetCollectionRequest = new QueryRequest(testCaseJsonObject.getAsJsonObject("TestSets"));
testsetCollectionRequest.setFetch(new Fetch("FormattedID"));
JsonArray testsets = restApi.query(testsetCollectionRequest).getResults();
for (int j=0;j<numberOfTestSets;j++){
System.out.println("FormattedID: " + testsets.get(j).getAsJsonObject().get("FormattedID"));
}
testsets.add(tsJsonObject);
JsonObject testCaseUpdate = new JsonObject();
testCaseUpdate.add("TestSets", testsets);
UpdateRequest updateTestCaseRequest = new UpdateRequest(testCaseRef,testCaseUpdate);
UpdateResponse updateTestCaseResponse = restApi.update(updateTestCaseRequest);
if (updateTestCaseResponse.wasSuccessful()) {
QueryRequest testsetCollectionRequest2 = new QueryRequest(testCaseJsonObject.getAsJsonObject("TestSets"));
testsetCollectionRequest2.setFetch(new Fetch("FormattedID"));
JsonArray testsetsAfterUpdate = restApi.query(testsetCollectionRequest2).getResults();
int numberOfTestSetsAfterUpdate = restApi.query(testsetCollectionRequest2).getResults().size();
System.out.println("Successfully updated : " + testid + " TestSets after update: " + numberOfTestSetsAfterUpdate);
for (int j=0;j<numberOfTestSetsAfterUpdate;j++){
System.out.println("FormattedID: " + testsetsAfterUpdate.get(j).getAsJsonObject().get("FormattedID"));
}
}
} finally {
restApi.close();
}
}
}

Related

Internal Server Error Exception from Facebook Graph API

I am trying to fetch campaign,ad level information from Facebook Using Graph API.
Campaign level information is getting with zero error for all accounts.
But for the Ad Level info, I am not getting the entire data. The API returns only 50. Remaining ads are getting with an exception called "Internal Server Error".
I've been getting this problem all day for one particular account. Every other Account works fine.
Below is the HTTP response:
response = (okhttp3.Response) Response{protocol=http/1.1, code=500, message=Internal Server Error,
url=https://graph.facebook.com/v3.3/act_fbAccountId/ads?access_token=myAccessToken&fields=%5B%22account_id%22%2C%22campaign_id%22%2C%22adset_id%22%2C%22id%22%2C%22bid_amount%22%2C%22name%22%2C%22status%22%2C%22preview_shareable_link%22%5D&limit=25&after=QVFIUkFzZAVdONXEwMXc5NjlOWURwczRQN0V3QW12NndRa0I4ZAUxsSjNkZA0FTRHR1U1dnaTQ5MTh2QnJ3bzNwWkNPd21jbC1tbjRmZAF81WVBsc0txaERCMHVn}
Below is the code
public List facebookAdsSynchThroughJson(String accessTokens, Long advertAccId, Properties googleStructureProperties, byte isOnScheduler, String appSecret) {
this.access_tokens = accessTokens;
this.appSecret = appSecret;
APIContext context = new APIContext(accessTokens, appSecret).enableDebug(true);
List<FacebookAdsStructure> adsList = new ArrayList<>();
String ads = "";
JSONObject advertIdObj = null;
JSONArray dataList = null;
ObjectMapper mapper = null;
boolean cond = true;
boolean success = false;
int limitValue = 100;
try {
while (cond) {
try {
AdAccount adAccount = new AdAccount(advertAccId, context).get().execute();
List adsFields = new ArrayList();
adsFields.add("account_id");
adsFields.add("campaign_id");
adsFields.add("adset_id");
adsFields.add("id");
adsFields.add("bid_amount");
adsFields.add("name");
adsFields.add("status");
adsFields.add("preview_shareable_link");
Map<String, Object> adsmap = new HashMap<>();
adsmap.put("fields", adsFields);
adsmap.put("limit", limitValue);
ads = adAccount.getAds().setParams(adsmap).execute().getRawResponseAsJsonObject().toString();
} catch (APIException ex) {
LOGGER.info("Exception thrown when fetching ads for Account Id: " + advertAccId + " with limit value: " + limitValue);
LOGGER.error(ex);
if (limitValue > 6) {
cond = true;
limitValue = limitValue / 2;
} else {
cond = false;
success = false;
break;
}
}
if (!ads.isEmpty()) {
cond = false;
success = true;
}
}
if (success) {
advertIdObj = new JSONObject(ads);
dataList = advertIdObj.getJSONArray("data");
mapper = new ObjectMapper();
adsList = mapper.readValue(dataList.toString(), new TypeReference<List<FacebookAdsStructure>>() {
});
JsonObject obj;
JsonParser parser = new JsonParser();
JsonElement result = parser.parse(ads);
obj = result.getAsJsonObject();
int maxTries = 1;
if (obj.has("data") && maxTries <= 5) {
while (obj.has("paging") && maxTries <= 5) {
JsonObject paging = obj.get("paging").getAsJsonObject();
if (paging.has("cursors")) {
JsonObject cursors = paging.get("cursors").getAsJsonObject();
String before = cursors.has("before") ? cursors.get("before").getAsString() : null;
String after = cursors.has("after") ? cursors.get("after").getAsString() : null;
}
String previous = paging.has("previous") ? paging.get("previous").getAsString() : null;
String next = paging.has("next") ? paging.get("next").getAsString() : "empty";
if (!next.equalsIgnoreCase("empty")) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.build();
Request request1 = new Request.Builder().url(next).get().build();
Response response = client.newCall(request1).execute();
if (response.isSuccessful()) {
maxTries = 1;
ads = response.body().string();
advertIdObj = new JSONObject(ads);
dataList = advertIdObj.getJSONArray("data");
mapper = new ObjectMapper();
List<FacebookAdsStructure> adsLists = new ArrayList<>();
adsLists = mapper.readValue(dataList.toString(), new TypeReference<List<FacebookAdsStructure>>() {
});
adsList.addAll(adsLists);
LOGGER.info("Fetched the Ad Structure.." + adsList.size());
parser = new JsonParser();
result = parser.parse(ads);
obj = result.getAsJsonObject();
} else {
LOGGER.info("Exception in response when fetching ads for Account Id: " + advertAccId + " , error response message: " + response.message() + " and with limit value: " + limitValue);
maxTries++;
if (maxTries >= 6) {
break;
}
try {
LOGGER.info("Thread Sleeping For 2 Minutes - Started for fb se_account_id " + advertAccId + " and maxTries = " + maxTries);
Thread.sleep(120000);
LOGGER.info("Thread Sleeping For 2 Minutes - Completed for fb se_account_id " + advertAccId + " and maxTries = " + maxTries);
} catch (InterruptedException ex) {
Logger.getLogger(FacebookAccountStructureSyncThroughJson.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
obj = new JsonObject();
}
}
}
}
} catch (JsonSyntaxException | IOException | JSONException ex) {
LOGGER.error(ex);
}
return adsList;
}
If anybody knows anything about this issue, please help me.

Exporting data to PDF JAVA, Eclipse, Jasper

I tried to make an exporting data to PDF but when I try to export it, the pdf can't show up like "no data found"
this code on bean
public JasperPrint exportTo() {
if(this.listReportMaster == null || this.listReportMaster.isEmpty()){
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
return null;
}
String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/report/PRPKReportPDF.jasper");
JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(this.listReportMaster);
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(path, null, beanCollectionDataSource);
return jasperPrint;
} catch (JRException e) {
e.printStackTrace();
return null;
}
}
public void exportToPdf(ActionEvent actionEvent){
if(this.lazyMasterReportDataModel != null){
System.out.println("masuk exporttopdf");
String sql = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getSqlReportPrint();
List<Object> listObject = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getObjectSqlListReportPrint();
this.listReportMaster = reportMasterPRPKController.getPRPKForReport(sql, listObject);
JasperPrint jasperPrint = exportTo();
String fileName = "PRPKNew_Report".concat("_").concat(".pdf");
if(jasperPrint != null) reportMasterPRPKController.exportToPDF(fileName, jasperPrint);
else System.out.println("jasperprint null");
}else{
System.out.println("keluar exporttopdf");
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
}
}
every I try to export it, always show "no data found" which is the program run this code FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found"); and which meam the "this.lazyMasterReportDataModel" is null but when I check it again, there's nothing wrong on code, I don't know if it have a wrong code or deficiency code
this the lazy code
List<ReportMasterPRPK> listMasterPRPK = new ArrayList<>();
ReportMasterPRPKQuery reportMasterPRPKQuery = new ReportMasterPRPKQuery();
Page page = new Page();
String order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
String columname = "";
String sql = "";
List<Object> objectSqlList = new ArrayList<>();
String sqlReport = "";
String sqlReportPrint = "";
List<Object> objectSqlListReport = new ArrayList<>();
List<Object> objectSqlListReportPrint = new ArrayList<>();
String flag;
public LazyMasterReportDataModel() {
}
public LazyMasterReportDataModel(String flag) { //ini
this.flag = flag;
}
public LazyMasterReportDataModel(String sqlReport, List<Object> objectSqlListReport) {
this.sqlReport = sqlReport;
this.objectSqlListReport = objectSqlListReport;
}
#Override
public List<ReportMasterPRPK> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
page.setLimit(pageSize);
page.setOffset(first);
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList = new ArrayList<>();
//objectSqlList.clear();
}
if(flag != null){ //ini
if(flag.equals("no selected")){
sql = sql+" AND c.is_selected = 'n' ";
}
}
if (filters != null){
for(String key: filters.keySet()){
String filterColumnName = "";
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(key)) filterColumnName = field.getAnnotation(Column.class).value();
}
if(filters.get(key) instanceof String){
if("receivedDate".equals(key)){
if(((String)filters.get(key)).trim().length() > 20){
String startDate = "'" + filters.get(key).toString().substring(0, 10) + "'";
String endDate = "'" + filters.get(key).toString().substring(11, 21) + "'";
sql = sql + " AND " + filterColumnName + " BETWEEN " + startDate + " AND " + endDate+ " ";
}
}else{
if(((String) filters.get(key)).trim().length() > 0){
sql = sql+"AND "+filterColumnName+" ILIKE ? ";
String value = "%"+filters.get(key)+"%";
objectSqlList.add(value);
}
}
}else{
if(((String[]) filters.get(key)).length > 0){
sql = sql+" AND "+filterColumnName+" in ";
String value = "(";
for(String string : (String[]) filters.get(key)){
value = value+"'"+string+"',";
}
value = value.substring(0, value.length()-1)+") ";
sql = sql + value;
}
}
}
}
if(sortField != null){
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(sortField)) columname = field.getAnnotation(Column.class).value();
}
if(sortOrder.toString().equals("ASCENDING")) order = " ASC";
else order = " DESC";
sql = sql+" GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY "+columname+" "+order;
System.out.println("sql sort: "+sql+" : "+objectSqlList.size());
}else{
sql = sql + order;
}
sqlReportPrint = sql;
objectSqlListReportPrint = objectSqlList;
this.listMasterPRPK = reportMasterPRPKQuery.retrivePage(page, sql, objectSqlList.toArray());
int dataSize = reportMasterPRPKQuery.retrieveMaxRow(sql, objectSqlList.toArray());
this.setRowCount(dataSize);
//objectSqlList.clear();
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList.clear();
}
order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
return listMasterPRPK;
}
public List<ReportMasterPRPK> calculateRownum(List<ReportMasterPRPK> listMasterPRPK, int first){
int i = 1;
for (ReportMasterPRPK masterPRPK : listMasterPRPK) {
masterPRPK.setRownum(first + i);
i++;
}
return listMasterPRPK;
}
public String getSqlReportPrint() {
return sqlReportPrint;
}
public void setSqlReportPrint(String sqlReportPrint) {
this.sqlReportPrint = sqlReportPrint;
}
public List<Object> getObjectSqlListReportPrint() {
return objectSqlListReportPrint;
}
public void setObjectSqlListReportPrint(List<Object> objectSqlListReportPrint) {
this.objectSqlListReportPrint = objectSqlListReportPrint;
}
sorry before, if my english is to bad, but I hope you understand about what I mean...
thanks before...

How do i parse large json files with json.simple?

I am new to JSON and I am learning using the json.simple library. I try to parse a large json file, but all i get is “OutOfMemoryError: GC overhead limit exceeded”. How can i parse large json files?
this is my code:
private static void fillPublications() throws FileNotFoundException, IOException, SQLException {
JSONParser parser = new JSONParser();
try {
String username = System.getProperty("user.name");
String filename = "Datenbank";
Object jsonData = parser.parse(new FileReader("C:\\Users\\" + username + "\\Desktop\\JSON\\" + filename + ".json"));
ArrayList<String[]> list = new ArrayList<String[]>();
JSONArray jsonArray = (JSONArray) jsonData;
Iterator iterator = jsonArray.iterator();
String name = "";
Integer count = 0;
while (iterator.hasNext()) {
String[] database = new String[11];
JSONObject obj = (JSONObject) iterator.next();
if(obj.containsKey("title")){
database[0] = (String) obj.get("title");
}
if(obj.containsKey("year")){
database[1] = obj.get("year").toString();
}
if(obj.containsKey("keywords")){
JSONArray keywords = (JSONArray) obj.get("keywords");
Iterator<String> i = keywords.iterator();
String key = "";
while (i.hasNext()) {
key = key + i.next() + "#";
}
if(key.length() > 0 && key.charAt(key.length()-1)=='#'){
key = key.substring(0, key.length()-1);
}
database[2] = key;
}
if(obj.containsKey("pages")){
database[3] = (String) obj.get("pages");
}
if(obj.containsKey("volume")){
database[4] = (String) obj.get("volume");
}
if(obj.containsKey("abstract")){
database[5] = (String) obj.get("abstract");
}
if(obj.containsKey("identifiers")){
JSONObject identifiers = (JSONObject) obj.get("identifiers");
database[6] = (String) identifiers.get("doi");
}
if(obj.containsKey("type")){
database[8] = (String) obj.get("type");
}
if(obj.containsKey("authors")){
JSONArray arr = (JSONArray) obj.get("authors");
Iterator i = arr.iterator();
while(i.hasNext()){
JSONObject authorObject = (JSONObject) i.next();
name = name + (String) authorObject.get("first_name") + " " + (String) authorObject.get("last_name") + "#";
}
if(name.length() > 0 && name.charAt(name.length()-1)=='#'){
name = name.substring(0, name.length()-1);
}
database[10] = name;
}
list.add(database);
}
System.out.println(Arrays.toString(list.get(0)));
}catch (Exception e) {
System.err.println(e);
}
}
and this is what i get:
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.lang.StringBuffer.toString(StringBuffer.java:673)
at org.json.simple.parser.Yylex.yylex(Yylex.java:598)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)
at JSONExtraction.fillAuthors(JSONExtraction.java:39)
at JSONExtraction.main(JSONExtraction.java:23)
C:\Users\b\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

How to get Json data

I have a json array like this
{
"success":"true",
"crops": {
"Brinjal":[---varieties of brinjal---],
"apple":[---varieties of apple---],
.................
.................
}
}
So i have got the complete crops using.....
JSONObject jsonObject;
jsonObject.getString("crops")
but i actually need to create two arrays like
String[] crops = {"Brinjal","apple"};
String[] varities = {"---Brinjal Varities---","---apple varities---"};
how can I generate these two arrays
if i generate "crops" then i can generate other array....
so how can i generate the "crops"...
You should do:
JSONObject obj = new JSONObject(jsonStringResp);
JSONObject cropsObj = obj.getJSONObject("crops");
JSONArray arr1 = subObject.getJSONArray("Brinjal");
Then you iterate over the JSON array and create the String array.
Hope it helps you.
public static void main(String[]args){
String joson = "{\n" +
" \"success\":\"true\",\n" +
" \"crops\": {\n" +
" \"Brinjal\":[---varieties of brinjal---],\n" +
" \"apple\":[---varieties of apple---],\n" +
" .................\n" +
" .................\n" +
" }\n" +
"}";
List<Object> apple = new ArrayList<Object>();
List<Object> Brinjal = new ArrayList<Object>();
apple.add("---varieties of apple---");
Brinjal.add("---varieties of brinjal---");
Map<String,Object> mapF = new HashMap<String,Object>();
Map<String,Object> mapS = new HashMap<String,Object>();
mapS.put("Brinjal", Brinjal);
mapS.put("apple", apple);
mapF.put("success", "true");
mapF.put("crops",mapS );
JSONObject obj = new JSONObject().fromObject(mapF);
System.out.println(obj);
JSONObject objF = obj.getJSONObject("crops");
String[] ListF = {};
String str = objF.keySet().toString();
String strF = str.substring(1, str.length()-1);
ListF = strF.split(", ");
List<Object> lsitF = new ArrayList<Object>();
for(int i = 0;i<ListF.length;i++){
lsitF.add(objF.get(ListF[i]));[enter image description here][1]
}
System.out.println(str);
System.out.println(lsitF.toString());
}
Hope it helps you.
Try this:
String joson = "{\n" +
" \"success\":\"true\",\n" +
" \"crops\": {\n" +
" \"Brinjal\":[---varieties of brinjal---],\n" +
" \"apple\":[---varieties of apple---],\n" +
" .................\n" +
" .................\n" +
" }\n" +
"}";
List<String> whereCrops = new ArrayList<String>();
List<String> whereVarities = new ArrayList<String>();
String[] crops;
String[] varities;
ArrayList<String> contentKey = new ArrayList<String>();
try {
JSONObject myObject = new JSONObject(joson);
JSONObject jsonCrops = myObject.getJSONObject("crops");
Iterator<String> iter = jsonCrops.keys();
while (iter.hasNext()) {
String key = iter.next();
whereCrops.add(key);
Log.e("inningskey", key);
try {
JSONArray array = jsonCrops.getJSONArray(key);
whereVarities.add(array.toString());
} catch (JSONException e) {
// Something went wrong!
}
}
// here ! you need convert whereCrops to crops
} catch (JSONException e) {
e.printStackTrace();
}
}

Rally REST API cannot find an existing workspace

i am using following piece of code to query for workspace. But apparently, if the workspace is not set as default, this query fails.
How can I successfully query for a workspace which is not my default workspace?
Thanks.
try{
QueryRequest proj1 = new QueryRequest("Workspace");
proj1.setFetch(new Fetch("Name"));
proj1.setQueryFilter(new QueryFilter("Name", "=",args[2]));
QueryResponse proj2 = batman.query(proj1);
Wspace_ref = proj2.getResults().get(0).getAsJsonObject().get("_ref").getAsString();
System.out.println("Workspace found.");
}catch (IndexOutOfBoundsException e){
System.out.println("Workspace Not Found.");
System.exit(1);
}
Since by default Rally REST queries are workspace-scoped, to obtain an enumeration of Workspaces, you need to query the Subscription object and then pull its Workspace collection.
Here's a quick example:
public class RestExample_QueryWorkspacesAndProjects {
public static void main(String[] args) throws URISyntaxException, IOException {
// Create and configure a new instance of RallyRestApi
// Connection parameters
String rallyURL = "https://rally1.rallydev.com";
String wsapiVersion = "1.43";
String applicationName = "RestExample_QueryWorkspacesAndProjects";
// Credentials
String userName = "user#company.com";
String userPassword = "topsecret";
RallyRestApi restApi = new RallyRestApi(
new URI(rallyURL),
userName,
userPassword);
restApi.setWsapiVersion(wsapiVersion);
restApi.setApplicationName(applicationName);
//Read Subscription
QueryRequest subscriptionRequest = new QueryRequest("Subscriptions");
subscriptionRequest.setFetch(new Fetch("Name", "SubscriptionID", "Workspaces", "Name"));
QueryResponse subscriptionQueryResponse = restApi.query(subscriptionRequest);
JsonArray subscriptionQueryResults = subscriptionQueryResponse.getResults();
JsonElement subscriptionQueryElement = subscriptionQueryResults.get(0);
JsonObject subscriptionQueryObject = subscriptionQueryElement.getAsJsonObject();
String subID = subscriptionQueryObject.get("SubscriptionID").toString();
System.out.println("Read Subscription: " + subID);
// Grab Workspaces Collection
JsonArray myWorkspaces = subscriptionQueryObject.get("Workspaces").getAsJsonArray();
// Initialize Project counter
int numberProjects = 0;
for (int i=0; i<myWorkspaces.size(); i++) {
JsonObject workspaceObject = myWorkspaces.get(i).getAsJsonObject();
String workspaceRef = workspaceObject.get("_ref").getAsString();
GetRequest workspaceRequest = new GetRequest(workspaceRef);
workspaceRequest.setFetch(new Fetch("Name", "Projects"));
GetResponse workspaceResponse = restApi.get(workspaceRequest);
JsonObject workspaceObj = workspaceResponse.getObject();
String workspaceName = workspaceObj.get("Name").getAsString();
System.out.printf("Workspace %d ==> %s\n", i, workspaceName);
JsonArray myProjects = workspaceObj.get("Projects").getAsJsonArray();
for (int j=0; j<myProjects.size(); j++)
{
JsonObject projectObject = myProjects.get(j).getAsJsonObject();
String projectRef = projectObject.get("_ref").getAsString();
GetRequest projectRequest = new GetRequest(projectRef);
projectRequest.setFetch(new Fetch("Name"));
GetResponse projectResponse = restApi.get(projectRequest);
JsonObject projectObj = projectResponse.getObject();
String projectName = projectObj.get("Name").getAsString();
System.out.printf("==> Project %d ==> %s\n", j, projectName);
numberProjects++;
}
}
String numberWorkspacesStr = String.valueOf(myWorkspaces.size());
String numberProjectsStr = String.valueOf(numberProjects);
System.out.println("Total Workspaces: " + numberWorkspacesStr);
System.out.println("Total Projects: " + numberProjectsStr);
restApi.close();
}

Categories

Resources