Simplest Java example retrieving user_timeline with twitter API version 1.1 - java

I was looking for a simple Java example using the Twitter 1.1 API and couldn't find one. Using the PHP sample posted here: Simplest PHP example for retrieving user_timeline with Twitter API version 1.1 and a few other Stackoverflow posts, I was able to come up with the following working example.
public void testUserTimelineWithAuthSample() throws Exception {
//This will read the timeline of your account.
String method = "GET";
String url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
String oAuthConsumerKey = "Your value here.";
String oAuthConsumerSecret = "Your value here."; //<--- DO NOT SHARE THIS VALUE
String oAuthAccessToken = "Your value here.";
String oAuthAccessTokenSecret = "Your value here."; //<--- DO NOT SHARE THIS VALUE
String oAuthNonce = String.valueOf(System.currentTimeMillis());
String oAuthSignatureMethod = "HMAC-SHA1";
String oAuthTimestamp = time();
String oAuthVersion = "1.0";
String signatureBaseString1 = method;
String signatureBaseString2 = url;
String signatureBaseString3Templ = "oauth_consumer_key=%s&oauth_nonce=%s&oauth_signature_method=%s&oauth_timestamp=%s&oauth_token=%s&oauth_version=%s";
String signatureBaseString3 = String.format(signatureBaseString3Templ,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureMethod,
oAuthTimestamp,
oAuthAccessToken,
oAuthVersion);
String signatureBaseStringTemplate = "%s&%s&%s";
String signatureBaseString = String.format(signatureBaseStringTemplate,
URLEncoder.encode(signatureBaseString1, "UTF-8"),
URLEncoder.encode(signatureBaseString2, "UTF-8"),
URLEncoder.encode(signatureBaseString3, "UTF-8"));
System.out.println("signatureBaseString: "+signatureBaseString);
String compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");
String oAuthSignature = computeSignature(signatureBaseString, compositeKey);
System.out.println("oAuthSignature : "+oAuthSignature);
String oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
System.out.println("oAuthSignatureEncoded: "+oAuthSignatureEncoded);
String authorizationHeaderValueTempl = "OAuth oauth_consumer_key=\"%s\", oauth_nonce=\"%s\", oauth_signature=\"%s\", oauth_signature_method=\"%s\", oauth_timestamp=\"%s\", oauth_token=\"%s\", oauth_version=\"%s\"";
String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureEncoded,
oAuthSignatureMethod,
oAuthTimestamp,
oAuthAccessToken,
oAuthVersion);
System.out.println("authorizationHeaderValue: "+authorizationHeaderValue);
System.out.println("url: "+url);
System.out.println("authorizationHeaderValue:"+authorizationHeaderValue);
GetMethod getMethod = new GetMethod(url);
getMethod.addRequestHeader("Authorization", authorizationHeaderValue);
HttpClient cli = new HttpClient();
int status = cli.executeMethod(getMethod);
System.out.println("Status:"+status);
long responseContentLength = getMethod.getResponseContentLength();
System.out.println("responseContentLength:"+responseContentLength);
String response = getMethod.getResponseBodyAsString();
System.out.println("response: "+response);
}
private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException, Exception
{
SecretKey secretKey = null;
byte[] keyBytes = keyString.getBytes();
secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] text = baseString.getBytes();
return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}
private String time() {
long millis = System.currentTimeMillis();
long secs = millis / 1000;
return String.valueOf( secs );
}
However, if I add parameters to the url like:
String url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2";
I get:
response: {"errors":[{"message":"Could not authenticate you","code":32}]}
Any idea where this is going wrong?

This works excellent for Timeline with the new Twitter API 1.1
1) Download twitter4j-core-3.0.3.jar in http://twitter4j.org/en/
2) Try use this code:
private static final String TWITTER_CONSUMER_KEY = "xxxxxxxxxxxxxxxxxx";
private static final String TWITTER_SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static final String TWITTER_ACCESS_TOKEN = "xxxxxxxxxxxxxxxxxxxxxxx";
private static final String TWITTER_ACCESS_TOKEN_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxx";
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(TWITTER_SECRET_KEY)
.setOAuthAccessToken(TWITTER_ACCESS_TOKEN)
.setOAuthAccessTokenSecret(TWITTER_ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
try {
Query query = new Query("MrEdPanama");
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
} while ((query = result.nextQuery()) != null);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}

You are wrong with the oauth_nonce. It is a random 32 bytes string encoded in base 64.
You can build them like this :
public String generateNonce() {
Random gen = new Random(System.currentTimeMillis());
StringBuilder nonceBuilder = new StringBuilder("");
String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int baseLength = base.length();
// Taking random word characters
for (int i = 0; i < 32; ++i) {
int position = gen.nextInt(baseLength);
nonceBuilder.append(base.charAt(position));
}
String nonce = toBase64(nonceBuilder.toString());
return nonce;
}
// In your code :
String oAuthNonce = generateNonce();
With String toBase64(String); which is a method to encode a String with Base 64.

Here's a Twitter 1.1 API example that works with parameters. The issue was not related to the nonce. It was the signatureBaseString. Think of the signatureBaseString as a 3 part string delimited by the ampersand (METHOD&URL&PARAMS). The api parameters are NOT to be included in the 2nd part of the signatureBaseString, they are to be included (with the other 6 security parameters) in the last part of signatureBaseString (Also, those params must be in alphabetic order).
public void testUserTimelineWithParams() throws Exception {
//This will read the timeline of the 'twitterapi' account.
String method = "GET";
String url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
List<NameValuePair> urlParams = new ArrayList<NameValuePair>();
urlParams.add( new NameValuePair("screen_name","twitterapi") );
urlParams.add( new NameValuePair("count", "10") );
String oAuthConsumerKey = "Your value";
String oAuthConsumerSecret = "Your value"; //<--- DO NOT SHARE THIS VALUE
String oAuthAccessToken = "Your value";
String oAuthAccessTokenSecret = "Your value"; //<--DO NOT SHARE THIS VALUE
String oAuthNonce = String.valueOf(System.currentTimeMillis());
String oAuthSignatureMethod = "HMAC-SHA1";
String oAuthTimestamp = time();
String oAuthVersion = "1.0";
String signatureBaseString1 = method;
String signatureBaseString2 = url;
List<NameValuePair> allParams = new ArrayList<NameValuePair>();
allParams.add(new NameValuePair("oauth_consumer_key", oAuthConsumerKey));
allParams.add(new NameValuePair("oauth_nonce", oAuthNonce));
allParams.add(new NameValuePair("oauth_signature_method", oAuthSignatureMethod));
allParams.add(new NameValuePair("oauth_timestamp", oAuthTimestamp));
allParams.add(new NameValuePair("oauth_token", oAuthAccessToken));
allParams.add(new NameValuePair("oauth_version", oAuthVersion));
allParams.addAll(urlParams);
Collections.sort(allParams, new NvpComparator());
StringBuffer signatureBaseString3 = new StringBuffer();
for(int i=0;i<allParams.size();i++)
{
NameValuePair nvp = allParams.get(i);
if (i>0) {
signatureBaseString3.append("&");
}
signatureBaseString3.append(nvp.getName() + "=" + nvp.getValue());
}
String signatureBaseStringTemplate = "%s&%s&%s";
String signatureBaseString = String.format(signatureBaseStringTemplate,
URLEncoder.encode(signatureBaseString1, "UTF-8"),
URLEncoder.encode(signatureBaseString2, "UTF-8"),
URLEncoder.encode(signatureBaseString3.toString(), "UTF-8"));
System.out.println("signatureBaseString: "+signatureBaseString);
String compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");
String oAuthSignature = computeSignature(signatureBaseString, compositeKey);
System.out.println("oAuthSignature : "+oAuthSignature);
String oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
System.out.println("oAuthSignatureEncoded: "+oAuthSignatureEncoded);
String authorizationHeaderValueTempl = "OAuth oauth_consumer_key=\"%s\", oauth_nonce=\"%s\", oauth_signature=\"%s\", oauth_signature_method=\"%s\", oauth_timestamp=\"%s\", oauth_token=\"%s\", oauth_version=\"%s\"";
String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureEncoded,
oAuthSignatureMethod,
oAuthTimestamp,
oAuthAccessToken,
oAuthVersion);
System.out.println("authorizationHeaderValue: "+authorizationHeaderValue);
StringBuffer urlWithParams = new StringBuffer(url);
for(int i=0;i<urlParams.size();i++) {
if(i==0)
{
urlWithParams.append("?");
}
else
{
urlWithParams.append("&");
}
NameValuePair urlParam = urlParams.get(i);
urlWithParams.append(urlParam.getName() + "=" + urlParam.getValue());
}
System.out.println("urlWithParams: "+urlWithParams.toString());
System.out.println("authorizationHeaderValue:"+authorizationHeaderValue);
GetMethod getMethod = new GetMethod(urlWithParams.toString());
getMethod.addRequestHeader("Authorization", authorizationHeaderValue);
HttpClient cli = new HttpClient();
int status = cli.executeMethod(getMethod);
System.out.println("Status:"+status);
long responseContentLength = getMethod.getResponseContentLength();
System.out.println("responseContentLength:"+responseContentLength);
String response = getMethod.getResponseBodyAsString();
System.out.println("response: "+response);
}
private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException, Exception
{
SecretKey secretKey = null;
byte[] keyBytes = keyString.getBytes();
secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] text = baseString.getBytes();
return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}
private String time() {
long millis = System.currentTimeMillis();
long secs = millis / 1000;
return String.valueOf( secs );
}
Where the NvpComparator is:
public class NvpComparator implements Comparator<NameValuePair> {
public int compare(NameValuePair arg0, NameValuePair arg1) {
String name0 = arg0.getName();
String name1 = arg1.getName();
return name0.compareTo(name1);
}
}

Here is my solution using twitter4j lib
Twitter twitter = new TwitterFactory().getInstance();
AccessToken accessToken = new AccessToken(accessTokenStr, accessTokenSecretStr);
twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);
twitter.setOAuthAccessToken(accessToken);
try {
Query query = new Query("#<HASHTAG TO SEARCH>");
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
}
catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}

Related

Get the Data from a Json String in codename one

am getting a json from the server and i managed to save it into storage,
{"FirstName":"Festus","MiddleName":"Kilaka","LastName":"Mutinda","MemberNo":"1886","IdNumber":"3125638","PayRollNumber":"87","PhoneNumber":"254743901110","EmailAddress":"FESTUS#GMAIL.COM"}
all i need is to read through it and get each variable and attach them to my strings.
i tried the code below but am getting an error.
private String str_response;
private String memberNoLabel = "";
private String nameLabel = "";
private String idNoLbl = "";
private String staffNoLbl = "";
private String emailAddLbl = "";
private String PhoneNumber = ""; //Storage.getInstance().readObject("PhoneNumber").toString();
private String AccBalanceLable = "50,500";
str_response = (String) Storage.getInstance().readObject("profile.json");
Log.p("Reading profile.json from storage.", 1);
byte[] bytes_mydetails = str_response.getBytes();
JSONParser json_mysaccos = new JSONParser();
try (Reader is_mysaccos = new InputStreamReader(new ByteArrayInputStream(bytes_mydetails), "UTF-8"))
{
Map<String, Object> map_saccos = json_mysaccos.parseJSON(is_mysaccos);
java.util.List<Map<String, Object>> objMydetails = (java.util.List<Map<String, Object>>) map_saccos.get("MemberDetails");
System.out.println("No of Details: ---------> " + objMydetails.size());
for (Map<String, Object> objDetails : objMydetails)
{
String name1 = (String) objDetails.get("FirstName");
String name2 = (String)objDetails.get("MiddleName");
String name3 = (String)objDetails.get("LastName");
nameLabel = name1+name2+name3;
memberNoLabel = (String)objDetails.get("MemberNo");
idNoLbl = (String)objDetails.get("IdNumber");
staffNoLbl = (String)objDetails.get("PayRollNumber");
PhoneNumber = (String)objDetails.get("PhoneNumber");
emailAddLbl = (String)objDetails.get("EmailAddress");
}
}
catch (Exception e)
{
System.out.println("Error # saccos: " + e);
e.printStackTrace();
}
am getting this error
Error # saccos: java.lang.NullPointerException
java.lang.NullPointerException
and it says its from the line
System.out.println("No of Details: ---------> " + objMydetails.size());
have tried all available documents and tutorials i could get, but i cant figure out this, help...

Google Web Search API returning random result for same query string in different searches

Hi all I am working on project in which I am using Google Web Search API for web search. It works in random fashion, it results different set of result for same query string on different searches. What would be the problem.
Please reply as soon as possible. I am filtering the result for suggestions from specific websites only.
Here is my code for WebSearch.
'
public Map getSearchArray(String search_key) throws Exception
{
Reader reader = null;
GoogleResults results = null;
URL url = null;
int index=0;
int result_size=0;
Map search_result_map = new HashMap();
try {
logger.info("Inside GetSearch");
for (int i = 0; i < 20 ; i=i+4) {
String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start="+i+"&q=";
String charset = "UTF-8";
url = new URL(google + URLEncoder.encode(search_key, charset));
reader = new InputStreamReader(url.openStream(), charset);
results = new Gson().fromJson(reader, GoogleResults.class);
//logger.info("resultSize: "+results.getResponseData().getResults().size());
//System.out.println("total"+t);
if (results.getResponseData().getResults().size()!=0) {
result_size = results.getResponseData().getResults().size();
} else {
result_size = 1;
}
for (int m = 0; m <result_size; m++)
{
String a=results.getResponseData().getResults().get(m).getUrl();
System.out.println(a);
if(a.matches(".*food.Some-Website.*")
||a.matches(".*Some-Website.*")
||a.matches(".*Some-Website.*")
||a.matches(".*Some-Website.*")
{
logger.info("----I----"+i+"----M----"+m);
String title = results.getResponseData().getResults().get(m).getTitle().replaceAll("\\<[^>]*>","");
String url_link = results.getResponseData().getResults().get(m).getUrl();
String embeded_link = createEmbeddedLink(url_link, title, "http");
search_result_map.put("link_"+index, embeded_link);
search_result_map.put("title_"+index, title);
index++;
logger.info("Title "+title);
}
else
{
System.out.println("No Url");
}
}
}
} catch (Exception e)
{
logger.info("Exception Thrown");
}
finally {
return search_result_map;
}
}
`

Modifying a collection property using the Rally Rest API in 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();
}
}
}

Timestamp variable changes after 1 line of code

I am trying to create a dynamic md5 hash system for authenticating to the Marvel API.
I create a timestamp variable, add the private / public key and then try and turn that into a md5 hash. When I print out the results, the timestamp in the url and the timestamp in the string to be hashed becomes different.
//I declare the timestamp here
Long tsLong = System.currentTimeMillis()/1000;
final String ts = tsLong.toString();
//Create the string to be hashed
final String toHash = ts + privateKey + publicKey;
url = "" + publicKey;
String hash = new String();
//my hashing algorithm
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashe = md.digest(toHash.getBytes("UTF-8"));
StringBuffer hex = new StringBuffer(2*hashe.length);
for (byte b : hashe) {
hex.append(String.format("%02x", b&0xff));
}
hash = hex.toString();
}
catch(NoSuchAlgorithmException e) {
}
catch(UnsupportedEncodingException e) {
}
//append the url to include the hash
url += "&hash=";
url += hash;
//call the api
RequestQueue queue = VolleySingleton.getInstance().getRequestQueue();
JsonObjectRequest obj = new JsonObjectRequest
(Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJSONResponse(response);
for (int i = 0; i < eventArray.size(); i++) {
mTV.append("Id: " + String.valueOf(eventArray.get(i).id) + '\n' +
"Title: " + eventArray.get(i).title + '\n' +
"Description: " + eventArray.get(i).description + '\n');
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//i get an authentication error so here is the log code
Log.i("tag", url);
Log.i("tag", toHash);
}
});
queue.add(obj);
Here is the logcat output
02-13 15:00:10.036 5681-5681/kim.albert.marveleventtracker I/tag﹕ http://gateway.marvel.com/v1/public/events?limit=66&ts=1423538706&apikey=fc57c9d09a46a0bdb06bd811ec4fc078&hash=0a670ef8de3c08d7c3d9dd1bc20aee75
02-13 15:00:10.036 5681-5681/kim.albert.marveleventtracker I/tag﹕ 1423857609172469841247e9a7aa64c3c89771a81299a67ef4fc57c9d09a46a0bdb06bd811ec4fc078
So as you can see: the url ts and the toHash have different values. Why is this?
I am a fool. I was hard coding the ts into my url, instead of updating it by adding the generated ts.

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