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.
Related
hi im creating a simple tool using java to create,update and delete issues(tickets) in jira. i am using rest api following code is im using to authenticate jira and issue tickets.
public class JiraConnection {
public static URI jiraServerUri = URI.create("http://localhost:8090/jira/rest/api/2/issue/HSP-1/");
public static void main(String args[]) throws IOException {
final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri,"vinuvish92#gmail.com","vinu1994");
System.out.println("Sending issue creation requests...");
try {
final List<Promise<BasicIssue>> promises = Lists.newArrayList();
final IssueRestClient issueClient = restClient.getIssueClient();
System.out.println("Sending issue creation requests...");
for (int i = 0; i < 100; i++) {
final String summary = "NewIssue#" + i;
final IssueInput newIssue = new IssueInputBuilder("TST", 1L, summary).build();
System.out.println("\tCreating: " + summary);
promises.add(issueClient.createIssue(newIssue));
}
System.out.println("Collecting responses...");
final Iterable<BasicIssue> createdIssues = transform(promises, new Function<Promise<BasicIssue>, BasicIssue>() {
#Override
public BasicIssue apply(Promise<BasicIssue> promise) {
return promise.claim();
}
});
System.out.println("Created issues:\n" + Joiner.on("\n").join(createdIssues));
} finally {
restClient.close();
}
}
}
according this code i couldn't connect to the jira
**following exception i am getting **
please suggest me best solution to do my task
It seems to me that your error is clearly related to url parameter. The incriminated line and the fact that the error message is about not finding the resource are good indications of it.
You don't need to input the whole endpoint since you are using the JiraRestClient. Depending on the method that you call it will resolve the endpoint. Here is an example that works: as you can see I only input the base url
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()
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);
I have used a tutorial and the Java SDK to pull reports from the new REST reporting API.
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/0201_ipp_java_devkit_3.0/reports
I have used the following code as specified by the tutorial:
String consumerKey = "XXXXXXXXXXXTDF2GEP0tlzdGxxpQRfSb4";
String consumerSecret = "XXXXXXXXXXYuy9CLaWiyAVHTowK0NuGMKN1X";
String accessToken = "XXXXXXXXXXXGPU4SUGAaeyhRJFp05NUg4s8QnbY4eI4U";
String accessTokenSecret = "XXXXXXXXXXXgkz50A8Ho3Z3pgMO8QFh2ZBv3XjI";
OAuthAuthorizer oauth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken, accessTokenSecret);
String appToken = "011e510ebf68ab4683b8a06b21f6228dfa03";
String companyID = "1067363490";
try {
Context context = new Context(oauth, appToken, ServiceType.QBO, companyID);
ReportService service = new ReportService(context);
service.setStart_date("2014-02-01");
service.setEnd_date("2014-04-20");
service.setAccounting_method("Accrual");
Object report = service.executeReport(ReportName.PROFITANDLOSS.toString());
String name = "ryan";
//System.out.println(report.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Inside service.executeReport it keeps throwing a java.lang.ClassCastException: com.intuit.ipp.data.Report cannot be cast to com.intuit.ipp.core.Response
Has anyone got these reports to work with the Java SDK? Am I doing something wrong?
At present reports support only Json.
Please verify that you are specifying:
Config.setProperty(Config.SERIALIZATION_RESPONSE_FORMAT, "json");
Update Line:
Object report = service.executeReport(ReportName.PROFITANDLOSS.toString());
To:
Report report = service.executeReport(ReportName.PROFITANDLOSS.toString());
As shown here: https://developer.intuit.com/docs/0100_accounting/0500_developer_kits/0201_ipp_java_devkit_3.0/reports
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.