Rally REST API cannot find an existing workspace - java

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();
}

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...

ArrayList to parse and return JSON data

iam student and i have this class for parse and return json data and i used a string array and i want to change the string array to ArrayList but i get stuck with it how can i use ArrayList to parse and return results
this is my attempts :
public static String[] getStringsFromJson(Context context, String JsonString)
throws JSONException {
final String RESULTS = "results";
final String SUBJECT = "subject";
ArrayList<ListItem> ItemsList;
JSONObject Object = new JSONObject(JsonString);
JSONArray ItemsList = Object.getJSONArray(RESULTS);
for(int i = 0; i < ItemsList.length; i++)
{
JSONObject object = ItemsList.getJSONObject(i);
Item ci = new Item();
String subject = object.getString(SUBJECT);
ci.toString(subject);
ItemsList.add(ci);
}
Instead of parsedMovieData, use this:
List<String> parsedMovieList = new ArrayList<>(moviesArray.length());
parsedMovieList.add(popularity + " - " + poster_path + " - " + original_title);
You forgot just to get a new instance of the array list here ArrayList<MovieItem> moviesItemsList = new ArrayList<MovieItem>();
Do it like this :
public static ArrayList<MovieItem> getSimpleMovieStringsFromJson(Context context, String moviesJsonString)
throws JSONException {
final String RESULTS = "results";
final String POPULARITY = "popularity";
final String POSTER_PATH = "poster_path";
final String ORIGINAL_TITLE = "original_title";
ArrayList<MovieItem> moviesItemsList = new ArrayList<MovieItem>();
JSONObject moviesObject = new JSONObject(moviesJsonString);
JSONArray moviesItemsList = moviesObject.getJSONArray(RESULTS);
for(int i = 0; i < moviesItemsList.length; i++)
{
JSONObject object = moviesItemsList.getJSONObject(i);
MovieItem ci = new MovieItem();
String original_title = object.getString(ORIGINAL_TITLE);
ci.toString(original_title);
moviesItemsList.add(ci);
}
return moviesItemsList;
}

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

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();
}
}
}

Simplest Java example retrieving user_timeline with twitter API version 1.1

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);
}

Categories

Resources