Using Twitter4j to get favorited count for a particular tweet - java

I am new to the twitter4j api, is there any way of getting no of favorite count for a particular tweet using twitter4j. I am using api version 3.0.3 for Twitter4j.
In documentation the method getFavoriteCount() is present but the same method gives compilation error in code. Should I use different version of jar file?
public static void main(String[] args) {
ConfigurationBuilder cb= new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("**************************");
cb.setOAuthConsumerSecret("**************************");
cb.setOAuthAccessToken("*******************************");
cb.setOAuthAccessTokenSecret("*****************************");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
User user = null;
try {
user = twitter.verifyCredentials();
} catch (TwitterException e1) {
e1.printStackTrace();
}
String[] test = new String[]{"teststr"};
ResponseList<User> users;
try {
users = twitter.lookupUsers(test);
for (User user1 : users) {
if (user1.getStatus() != null)
{
Paging paging = new Paging(1, 40);
ResponseList<Status> statusess = twitter.getUserTimeline(user1.getName(),paging);
for (Status status3 : statusess)
{
long retweetCount = status3.getRetweetCount();
long favoriteCount = status3.getFavoriteCount();/** this line gives compilation error saying the method getFavoriteCount() is undefined for the type Status**/
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
}

Unfortunately, it seems like the JavaDocs on the Twitter4J site linked next to the 3.0.3 release are not correct. The actual docs are here - you can see that getFavoriteCount() isn't present in these.
It looks like Status#getFavoriteCount() was only introduced in 3.0.4. So yes, you need to upgrade from 3.0.3 in order to use this method.
Although be aware that version 3.0.4 looks like it is under active development presently.

Although you have already found and marked an answer, let me provide an alternate to switching the Twitter4J version.
When using a method similar to what you are using, I had searched a lot and finally found the solution in an entirely unrelated post. Here is how you can get the Favorite count of tweets:
NOTE: This is what I use in an Android app of mine.
First, in your ConfigurationBuilder cb instance, add this one line:
cb.setJSONStoreEnabled(true);
This will return all results in a JSON format. Strangely, getting a JSON result it provides you that value.
Now, to fetch the Tweets:
try {
Paging paging = new Paging(initPagingOffset, 200);
statuses = twitter.getHomeTimeline(paging);
String strTweets = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strTweets);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
..... // PARSE ANY OTHER DATA YOU MIGHT NEED FOR DISPLAYING THE TWEETS
String FAV_COUNT = JOTweet.getString("favorite_count");
}
} catch (TwitterException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

Related

Jsoup not connecting to webpage in Android Studio

I am working on a project right now where I use jsoup in a class with the function retrieveMedia in order to return an ArrayList filled with data from the webpage. I run it in a thread since you shouldn't be connecting to URLs from the main thread. I run it and join it. However, it doesn't work (I tested the same code in Eclipse separate from Android Studio and it worked fine). It seems that no matter what I do I can't get jsoup to connect to the webpage. Below is my class MediaRetriever.
public class MediaRetreiever {
public ArrayList<Media> retrieveMedia() {
ArrayList<Media> mediaOutput = new ArrayList<Media>(); //Store each scraped post
Thread downloadThread = new Thread(new Runnable() {
public void run() {
Document doc = null;
try {
doc = Jsoup.connect(<Website Im connecting to>).timeout(20000).get();
} catch (IOException e) {
System.out.println("Failed to connect to webpage.");
mediaOutput.add(new Media("Failed to connect", "oops", "", "oh well"));
return;
}
Elements mediaFeed = doc.getElementById("main").getElementsByClass("node");
for (Element e : mediaFeed) {
String title, author, imageUrl, content;
title=e.getElementsByClass("title").text().trim();
author=e.getElementsByClass("content").tagName("p").select("em").text().trim();
content=e.getElementsByClass("content").text().replace(author,"").trim();
Media media = new Media(title, author, "", content);
mediaOutput.add(media);
}
}
});
downloadThread.start();
try {
downloadThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mediaOutput;
}
}
Running this class's method from another class and it doesn't ever connect. Any ideas?
Since you say that the problem persists only in Android, it looks like that you should add the user agent string to your request - first get the user agent string of a browser that displays correctly the site, and then add it to the request:
doc = Jsoup.connect(<Website Im connecting to>)
.userAgent("your-user-agent-string")
.timeout(20000).get();
And as a sidenote - if you are catching exception, don't print your own error message - print the original message, it may be very useful.

Google Drive for Android SDK Doesn't List Files

I've got a really odd problem with the Google Drive Android SDK. I've been using it for several months now, and until last week it performed perfectly. However, there is now a really odd error, which doesn't occur all the time but does 9 out of 10 times.
I'm trying to list the user's files and folders stored in a particular Google Drive folder. When I'm trying to use the method Drive.files().list().execute(), 9 out of 10 times literally nothing happens. The method just hangs, and even if I leave it for an hour, it just remains doing... nothing.
The code I'm using is below - all of this being run within the doInBackground of an AsyncTask. I've checked credentials - they are all fine, as is the app's certificate's SHA1 hash. No exceptions are thrown. Google searches have yielded nothing. Here is the particular bit of code that's bothering me:
try {
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
SettingsActivity.this, Arrays.asList(DriveScopes.DRIVE));
if (googleAccountName != null && googleAccountName.length() > 0) {
credential.setSelectedAccountName(googleAccountName);
Drive service = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
service.files().list().execute(); // Google Drive fails here
} else {
// ...
}
} catch (final UserRecoverableAuthIOException e) {
// Authorisation Needed
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
startActivityForResult(e.getIntent(), REQUEST_AUTHORISE_GDRIVE);
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account due to Exception after trying to show the Google Drive authroise request intent, as the UserRecoverableIOException was originally thrown. Error message:\n" + e.getMessage());
}
}
});
Log.d("SettingsActivity: Google Drive", "UserRecoverableAuthIOException when trying to add Google Drive account. This is normal if this is the first time the user has tried to use Google Drive. Error message:\n" + e.getMessage());
return;
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account. Error message:\n" + e.getMessage());
return;
}
I'm using Drive API v2. Thanks everyone!
Edit
Having played around a bit more, it turns out this isn't for just listing files. Trying to interact with any file on Google Drive behaves the same way - deleting, downloading, creating... Anything! I have also noticed that putting the device in aeroplane mode so it has not internet access makes no difference either: Google Drive doesn't throw an exception, or even return, it just freezes the thread it's on.
I've updated to the very latest Drive API lib but that hasn't helped. I remembered that the error happened soon after I added the JSch SSH library to the project, so I removed that, but it made no difference. Removing and re-adding the Drive API v2 has made no difference either, and nor has cleaning the project.
Edit 2
I've found something which may be significant. On the Google Developer console, I had some Drive errors recorded as follows:
TOP ERRORS:
Requests % Requests Methods Error codes
18 38.30% drive.files.list 400
14 29.79% drive.files.insert 500
11 23.40% drive.files.update 500
4 8.51% drive.files.get 400
Do you reckon these are the errors? How could I fix them? Thanks
This is my code and it's work
new AsyncTask<Void, Void, List<File>>() {
#Override
protected List<File> doInBackground(Void... params) {
List<File> result = new ArrayList<File>();
try {
com.google.api.services.drive.Drive.Files.List list = service.files().list();
list.setQ("'" + sourcePath + "' in parents");
FileList fileList = list.execute();
result = fileList.getItems();
if(result != null) {
return result;
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(List<File> result) {
//This is List file from Google Drive
};
}.execute();
I've come up with a solution which does work, and thought I'd post it so others could see it if they happen to come across the problem.
Luckily, I had backed up all of the previous versions of the app. So I restored the whole project to how it was two weeks ago, copied and pasted all changes from the newer version which had been made since then, and it worked. I don't see why this should work, since the end result is the same project, but it does!
Google Drive List Files
This might help you.. Try to display it in ListView u will see all fetched folders
public void if_db_updated(Drive service)
{
try {
Files.List request = service.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'");
FileList files = request.execute();
for(File file : files.getItems())
{
String title = file.getTitle();
showToast(title);
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});

java how do I get the latest tweet for a particular user

I would like to get latest tweet from #Citi in java. I thought I should use twitter4j (BUT anything easier would be fine). I cannot tell from the documentation how to supply the "user" i.e. #Citi?
public static void main(String[] args) {
// TODO Auto-generated method stub
Twitter twitter = new TwitterFactory().getInstance();
List<Status> statusList = null;
try {
statusList = twitter.getUserTimeline("#Citi");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Status status : statusList) {
System.out.println(status.toString());
}
}
I tried the above but it crashes on getUserTimeline.
The code must create an instance of ConfigurationBuider and pass in your Twitter API credentials. Add the following.
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("Your Cosumer Key")
.setOAuthConsumerSecret("Your Consumer Secret")
.setOAuthAccessToken("Your Access Token")
.setOAuthAccessTokenSecret("Your Access Token Secret");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<Status> statusList = null;
try {
statusList = twitter.getUserTimeline("#Citi");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Status status : statusList) {
System.out.println(status.toString());
}
}
A Twitter API account is required to use the Twitter API. Twitter requires this so they can track who is using their API and conduct activities such as rate limiting. To obtain a Twitter API account, first create a Twitter account, then create the API account at this page: https://dev.twitter.com/
have you looked into the provided examples?
http://twitter4j.org/en/code-examples.html
You need to have OAuth credentials configured in your twitter4j.properties
See: http://twitter4j.org/en/configuration.html
Regards
Create application in developer and you'll get consumer keys for the application. These are application specific keys to identify your application. Then you'll have to supply access tokens, which are user specific keys. With the combination of these four, Any application with any user given, you can get its tweets. If you want to get tweets in real time, user Streaming API, otherwise you can get last 20 Tweets with the code you posted.

Getting NullPointerException with row.setAttribute on Oracle ADF

I'm now trying to learn Oracle ADF and I'm getting a NullPointerException while running the following code on a Java bean.
Can you help me figure out what I'm doing wrong please? This is being invoked from a button on a JSPX page.
public String cb1_action() {
try{
BindingContext bindingctx = BindingContext.getCurrent();
BindingContainer bindings = bindingctx.getCurrentBindingsEntry();
DCBindingContainer bindingsImpl = (DCBindingContainer)bindings;
DCIteratorBinding iter = bindingsImpl.findIteratorBinding("ViewObj1Iterator");
Row row = iter.getCurrentRow();
row.setAttribute("Id", 123);
row.setAttribute("Nome", "Pedro Teste");
}
catch(Exception e) {
System.out.println("Excepcao em: ");
e.printStackTrace();
}
return null;
}
According to the Stack trace, the error occurs on the first row.setAttribute() line.
Also, I'm using the latest version of JDeveloper with the integrated WebLogic server.
Best regards,
Pedro
Row row = iter.getCurrentRow();
if(row != null){
row.setAttribute("Id", 123);
row.setAttribute("Nome", "Pedro Teste"); //name?
}
The info that you get the error at
row.setAttribute("Id", 123);
let me think that you try to alter the primary key attribute of the row, which is not allowed. Not sure about this as you did not mention the error you get.
Ok, so here's how I figured out how to get around this:
First, I asked jDeveloper to generate a class for the Application Module.
In that class, I added the following methods:
public void testEntityObject()
{
System.out.println("Let's try our Entity Object...");
try
{
EntityDefImpl entity = TesteEOImpl.getDefinitionObject();
TesteEOImpl ti = (TesteEOImpl)entity.createInstance2(getDBTransaction(), null);
ti.setId(new BigDecimal(123));
ti.setNome("Entity Object test...");
getDBTransaction().commit();
System.out.println("Looks good :-)");
}
catch(Exception e)
{
System.out.println("It seems something went wrong :-(");
e.printStackTrace();
}
}
public void testViewObject() {
System.out.println("Let's try our View Object...");
ViewObjectImpl vo = this.getTeste1();
try{
Row row = vo.createRow();
row.setAttribute("Id", 234);
row.setAttribute("Nome", "VO test");
vo.insertRow(row);
getDBTransaction().commit();
System.out.println("Looks good :-)")
}
catch(Exception e) {
System.out.println("It seems something went wrong :-(");
e.printStackTrace();
}
}
These methods are being called by a managed bean that is connected to two buttons on the page. This managed bean has the following methods. I'll post just one of them as only the method names change:
public String cb1_action() {
try{
FacesContext fctx = FacesContext.getCurrentInstance();
BindingContext bindingContext = BindingContext.getCurrent();
DCDataControl dc = bindingContext.findDataControl("AppModuleAMDataControl");
AppModuleAMImpl am = (AppModuleAMImpl)dc.getDataProvider();
am.criarTesteComEntityObject();
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
I know this is not rocket science or anything but it took a while for me to get there...
Basically, your answers helped me a lot to go and investigate what was happening. The cause? Poor design! ADF is supposed to be organized...
Thank you everyone! :D

generate oauth signature for pentaho client in js or java for twitter

I would like to be able to make a request to Twitter with Pentaho's REST client request however this software does not have any concept of oauth. I found this (Implement OAuth in Java)neat java class that I would like to implement with Pentaho's java class tranformation but I am so new to Pentaho this task will be very difficult. I am hoping someone can help me out with this....
I found this great twitter java library called twitter4J and imported the core classes into the pentaho directory pentaho/design-tools/data-integration/libext and wrote the below custom user java class.
// NO COLLECTION TYPE SAFETY ALLOWED, MUST CAST ALL OBJECTS
import twitter4j.*;
import twitter4j.auth.*;
import twitter4j.conf.*;
//import other libs here
//put your vars here
// Variables
private Twitter twitter = null;
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
Object[] r = getRow();
if (r==null)
{
setOutputDone();
return false;
}
if (first) {
first=false;
paging = new Paging();
paging.setCount(100);
}
oauth_user_key = get(Fields.In, "oauth_user_key").getString(r);
oauth_user_secret = get(Fields.In, "oauth_user_secret").getString(r);
consumer_key = get(Fields.In, "consumer_key").getString(r);
consumer_secret = get(Fields.In, "consumer_secret").getString(r);
//wierd long/string thing here (pentho compiles java wierd)
user_id = get(Fields.In, "source_user_id").getInteger(r);
Long user = user_id;
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setIncludeEntitiesEnabled(true)
.setOAuthConsumerKey(consumer_key)
.setOAuthConsumerSecret(consumer_secret)
.setOAuthAccessToken(oauth_user_key)
.setOAuthAccessTokenSecret(oauth_user_secret);
twitter = new TwitterFactory(cb.build()).getInstance();
try {
//be creative with twitter4j here and output rows with results (may require a loop)
} catch (TwitterException e){
logDebug(e.getMessage());
return true;
}
logBasic("twitter collect done" );
return true;
}

Categories