I've got a problem with trying to authenticate to Twitter using twitter4j. I've tried this out and yet it is still not working.
Here's my code, any help would be greatly appreciated.
Thanks.
public class SpeedDemon {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws TwitterException {
// Setup for Snake Charmer
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("CONSUMER_KEY")
.setOAuthConsumerSecret("CONSUMER_SECRET")
.setOAuthAccessToken("OAUTH_ACCESS")
.setOAuthAccessTokenSecret("OAUTH_SECRET");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
// Gets timeline.
Twitter twit = TwitterFactory.getSingleton();
List<Status> statuses = twit.getHomeTimeline();
System.out.println("Showing home timeline.");
for (Status status : statuses) {
System.out.println(status.getUser().getName() + ":" +
status.getText());
}
}
}
EDIT: The following error happens at compilation:
Exception in thread "main" java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/en/configuration.html for details
at twitter4j.TwitterBaseImpl.ensureAuthorizationEnabled(TwitterBaseImpl.java:215)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1784)
at twitter4j.TwitterImpl.getHomeTimeline(TwitterImpl.java:105)
at speeddemon.SpeedDemon.main(SpeedDemon.java:30)
C:\Users\Kevin\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
It looks like you construct a Twitter instance twice, once with your constructed TwitterFactory and once with the Singleton (which I suspect doesn't have auth setup).
You then use the second Twitter instance (created with the unauthenticated factory) to make your queries.
Try using twitter.getHomeTimeline() rather than twit.getHomeTimeline()
Related
Fighting to get a working twitter4j instance, but having problems with Oauth. I copied-pasted multiple times, created different apps and keys/tokens and still cant get this working. What could i do wrong here really?
my main:
public class Main {
public static void main(String[] args) {
// write your code here
Tweeter tweet = new Tweeter();
try{
tweet.searchTweets();
} catch (TwitterException e) {
e.printStackTrace();
}
}
}
my twitter class:
public class Tweeter {
public static Twitter GetTwitterInstance(){
String consumerKey = "**************";
String consumerSecret = "*************";
String accessToken = "***************"; // yourt token
String accessTokenSecret = "************"; // your token secre
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessTokenSecret);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getSingleton();
return twitter;
}
public static void searchTweets() throws TwitterException{
Twitter twitter = GetTwitterInstance();
Query query = new Query("something");
QueryResult result = twitter.search(query);
List<Status> statuses = result.getTweets();
for(Status tweet: statuses){
System.out.println("User: "+tweet.getUser().getScreenName() + " Tweet: "+tweet.getText());
}
}
}
And the error stacktrace:
400:The request was invalid. An accompanying error message will explain why.
This is the status code will be returned during version 1.0 rate
limiting(https://dev.twitter.com/pages/rate-limiting). In API v1.1, a request
without authentication is considered invalid and you will get this response.
message - Bad Authentication data.
code - 215
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=506c3b98 or
http://www.google.co.jp/search?q=11ed9ae8
TwitterException{exceptionCode=[506c3b98-11ed9ae8], statusCode=400,
message=Bad Authentication data., code=215, retryAfter=-1,
rateLimitStatus=null, version=4.0.6}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.get(HttpClientBase.java:75)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1786)
at twitter4j.TwitterImpl.search(TwitterImpl.java:268)
at Tweeter.searchTweets(Tweeter.java:58)
at Main.main(Main.java:14)
Printing the twitter factory's keys/tokens gives the normal keys/tokens as expected without weird characters or spaces or whatever. Any help will be really really appreciated!
Problem was that tf.getSingleton() does not return a twitter instance apparently.
it should be just Twitter twitter = tf.getInstance(); and then it works.
Your code appears to be cut and pasted from known working code. Check again that there are no extra characters, such as a space at the end of a string.
I'm trying to mock the following code using PowerMock
Twitter twitter = TwitterFactory.getSingleton();
RequestToken requestToken = twitter.getOAuthRequestToken();
Here is the start of my unit test
#RunWith(PowerMockRunner.class)
#PrepareForTest(TwitterFactory.class)
public class AuthorisationHelperTest {
#Test
public void testMain() throws TwitterException {
// Arrange
PowerMockito.mockStatic(TwitterFactory.class);
Twitter mockTwitter = new Twitter();
Mockito.when(TwitterFactory.getSingleton()).thenReturn(mockTwitter);
However I get an error saying I cannot instantiate the type Twitter. I figure I must be thinking about this the wrong way. Any tips?
Here's how you declare and instantiate a new instance of a Twitter object:
Twitter twitter = TwitterFactory.getSingleton();
If you cannot instantiate a Twitter class, the likelihood is that it has a non-visible constructor, and is only ever possible to get via the factory.
What you probably want to do is supply a mock of Twitter instead.
Twitter twitter = mock(Twitter.class);
I frequently get the following exception using twitter4j:
2015-06-02 10:04:30,802 DEBUG [Twitter Stream consumer-1[Establishing connection]] TwitterBot(116): Got an exception 420:Returned by the Search and Trends API when you are being rate limited (https://dev.twitter.com/docs/rate-limiting).
Returned by the Streaming API:
Too many login attempts in a short period of time.
Running too many copies of the same application authenticating with the same account name.
Exceeded connection limit for user
Since i try to avoid being banned from Twitter, i would like to ask, if I am doing something wrong in my code:
I am using a StatusListener on the Stream API, which is filtered by my own ID and some string values.
If a status matches the criteria an answer for this status is send via twitter. This does not happen very often and therefore this should not be the problem of the rate limitation exception.
The whole thing runs in a TomEE EJB environment, if this is important?
#Startup
#Singleton
public class TwitterBot implements Service {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TwitterBot.class);
//this is fix for this twitter bot
public static final String TWITTER_BOT_NAME = "botname";
public static final long TWITTER_BOT_USER_ID = 99999L; //the bot's user id
private final TwitterStream twitterStream;
private final Twitter twitter;
public TwitterBot() {
this.twitterStream = new TwitterStreamFactory().getInstance();
this.twitter = TwitterFactory.getSingleton();
}
#PostConstruct
public void listen() {
StatusListener listener = new StatusListener() {
#Override
public void onStatus(Status status) {
//this is to avoid a circle... ignore tweets coming from ourselves.
if (status.getUser().getScreenName().equalsIgnoreCase(TWITTER_BOT_NAME)) {
return;
}
try {
//do something and update own status
StatusUpdate update = new StatusUpdate("Hello World!");
update.setInReplyToStatusId(status.getId());
twitter.updateStatus(update);
} catch (TwitterException e) {
logger.error("Could not complete twitter update, {}", e.getLocalizedMessage(), e);
}
}
//other Status Listener methods, which are not used (default implementation)
};
//filtering for ourselves here
long[] userFilter = {TWITTER_BOT_USER_ID};
String[] termFilter = {TWITTER_EXPERTIZER_BOT_NAME};
FilterQuery filter = new FilterQuery(0, userFilter, termFilter);
twitterStream.addListener(listener);
twitterStream.filter(filter);
}
}
The answer on this How to handle rate limit using twitter4j to avoid being banned tells me, that the Streaming API has no rate limitation.
So what is the issue? Is there an explanation in the API documentation?
Thank you in advance!
Edit:
The Problem is related to
FilterQuery filter = new FilterQuery(0, userFilter, termFilter);
Using the query like this produces some kind of polling on the Twitter API and therefore exceeds connection limit.
Instead use:
FilterQuery filter = new FilterQuery(termFilter);
Where can I find Jira issue type values that we pass to IssueBuilder class constructor?
For ex: If i want to create a issue type of bug using jira rest api , We pass value '1L' to Issue Builder class constructor.
IssueInputBuilder issueBuilder = new IssueInputBuilder("Key", 1l);
Similarly what are the values of other jira issue types ?.. Anybody know the values we need to pass ?
If you are using later Jira REST Java Client API (e.g. 4.0), the interface has been changed. You must use following code to browsing all issue types:
private static final String JIRA_SERVER = "http://jiralab";
public static void main(String[] args) {
try {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_SERVER);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, "admin", "admin");
listAllIssueTypes(client);
}
catch (Exception ex) {
}
}
private static void listAllIssueTypes(JiraRestClient client) throws Exception {
Promise<Iterable<IssueType>> promise = client.getMetadataClient().getIssueTypes();
Iterable<IssueType> issueTypes = promise.claim();
for (IssueType it : issueTypes) {
System.out.println("Type ID = " + it.getId() + ", Name = " + it.getName());
}
}
If you want to get a list of all available issuetypes, you can use the REST API (/rest/api/2/issuetype). To try that on your JIRA instance, I like to recommend the Atlassian REST API Browser.
Or just look here: Finding the Id for Issue Types
In Java you can get a list of all issuetype object using getAllIssueTypeObjects().
I'm using Facebook4j to get status with a keyword
facebook4j.conf.ConfigurationBuilder fac = new facebook4j.conf.ConfigurationBuilder();
fac.setDebugEnabled(true)
.setOAuthAppId("******")
.setOAuthAppSecret("********")
.setOAuthPermissions("email,publish_stream,...");
FacebookFactory ff = new FacebookFactory(fac.build());
facebook = ff.getInstance();
new Thread(new Runnable() {
#Override
public void run() {
try {
search();
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e +" ERROOOOOOR");
}}}).start();
}
//search
public void search() throws Exception {
ResponseList<JSONObject> results = facebook.search("%23morocco");
System.out.println(results);
for (JSONObject result : results) {
System.out.println(result);
}
results = facebook.search("orange", new Reading().until("yesterday"));
System.out.println(results);
for (JSONObject result : results) {
System.out.println(result);
}
}
I replaced * with facebook api key
I have a exception probleme , the error is :
java.lang.IllegalStateException: No Token available. ERROOOOOOR
This is how you could use facebook4j without external configuration files. The code below provides a minimal example. Here is my simple demo:
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.auth.AccessToken;
public class Facebook4JMinimalExample {
/**
* A simple Facebook4J client.
*
*
* #param args
* #throws FacebookException
*/
public static void main(String[] args) throws FacebookException {
// Generate facebook instance.
Facebook facebook = new FacebookFactory().getInstance();
// Use default values for oauth app id.
facebook.setOAuthAppId("", "");
// Get an access token from:
// https://developers.facebook.com/tools/explorer
// Copy and paste it below.
String accessTokenString = "PASTE_YOUR_ACCESS_TOKEN_STRING_HERE";
AccessToken at = new AccessToken(accessTokenString);
// Set access token.
facebook.setOAuthAccessToken(at);
// We're done.
// Write some stuff to your wall.
facebook.postStatusMessage("Wow, it works...");
}
}
Note that it is important to FIRST make a call to "facebook.setOAuthAppId(..)" and THEN set the access token. Otherwise you'll get an IllegalStateException saying "OAuth app id/secret combination not supplied".
In this case, I've just used a default value for OAuthAppId.
You forgot to set the access token with fac.setOAuthAccessToken("*****"). From the docs (emphasis mine):
All Graph API search queries require an access token passed in with the access_token=<token> parameter. The type of access token you need depends on the type of search you're executing.
Searches across page and place objects requires an app access token.
All other endpoints require a user access token.
You can generate one for yourself here, but remember that these access tokens have an expiration time.